Photo.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. <?php
  2. namespace Lychee\Modules;
  3. use ZipArchive;
  4. use Imagick;
  5. use ImagickPixel;
  6. final class Photo {
  7. private $photoIDs = null;
  8. public static $validTypes = array(
  9. IMAGETYPE_JPEG,
  10. IMAGETYPE_GIF,
  11. IMAGETYPE_PNG
  12. );
  13. public static $validExtensions = array(
  14. '.jpg',
  15. '.jpeg',
  16. '.png',
  17. '.gif'
  18. );
  19. /**
  20. * @return boolean Returns true when successful.
  21. */
  22. public function __construct($photoIDs) {
  23. // Init vars
  24. $this->photoIDs = $photoIDs;
  25. return true;
  26. }
  27. /**
  28. * Creats new photo(s).
  29. * Exits on error.
  30. * Use $returnOnError if you want to handle errors by your own.
  31. * @return boolean Returns true when successful.
  32. */
  33. public function add(array $files, $albumID = 0, $returnOnError = false) {
  34. // Check permissions
  35. if (hasPermissions(LYCHEE_UPLOADS)===false||
  36. hasPermissions(LYCHEE_UPLOADS_BIG)===false||
  37. hasPermissions(LYCHEE_UPLOADS_THUMB)===false) {
  38. Log::error(Database::get(), __METHOD__, __LINE__, 'An upload-folder is missing or not readable and writable');
  39. if ($returnOnError===true) return false;
  40. Response::error('An upload-folder is missing or not readable and writable!');
  41. }
  42. // Call plugins
  43. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  44. switch($albumID) {
  45. case 's':
  46. // s for public (share)
  47. $public = 1;
  48. $star = 0;
  49. $albumID = 0;
  50. break;
  51. case 'f':
  52. // f for starred (fav)
  53. $star = 1;
  54. $public = 0;
  55. $albumID = 0;
  56. break;
  57. case 'r':
  58. // r for recent
  59. $public = 0;
  60. $star = 0;
  61. $albumID = 0;
  62. break;
  63. default:
  64. $star = 0;
  65. $public = 0;
  66. break;
  67. }
  68. // Only process the first photo in the array
  69. $file = $files[0];
  70. // Check if file exceeds the upload_max_filesize directive
  71. if ($file['error']===UPLOAD_ERR_INI_SIZE) {
  72. Log::error(Database::get(), __METHOD__, __LINE__, 'The uploaded file exceeds the upload_max_filesize directive in php.ini');
  73. if ($returnOnError===true) return false;
  74. Response::error('The uploaded file exceeds the upload_max_filesize directive in php.ini!');
  75. }
  76. // Check if file was only partially uploaded
  77. if ($file['error']===UPLOAD_ERR_PARTIAL) {
  78. Log::error(Database::get(), __METHOD__, __LINE__, 'The uploaded file was only partially uploaded');
  79. if ($returnOnError===true) return false;
  80. Response::error('The uploaded file was only partially uploaded!');
  81. }
  82. // Check if writing file to disk failed
  83. if ($file['error']===UPLOAD_ERR_CANT_WRITE) {
  84. Log::error(Database::get(), __METHOD__, __LINE__, 'Failed to write photo to disk');
  85. if ($returnOnError===true) return false;
  86. Response::error('Failed to write photo to disk!');
  87. }
  88. // Check if a extension stopped the file upload
  89. if ($file['error']===UPLOAD_ERR_EXTENSION) {
  90. Log::error(Database::get(), __METHOD__, __LINE__, 'A PHP extension stopped the file upload');
  91. if ($returnOnError===true) return false;
  92. Response::error('A PHP extension stopped the file upload!');
  93. }
  94. // Check if the upload was successful
  95. if ($file['error']!==UPLOAD_ERR_OK) {
  96. Log::error(Database::get(), __METHOD__, __LINE__, 'Upload contains an error (' . $file['error'] . ')');
  97. if ($returnOnError===true) return false;
  98. Response::error('Upload failed!');
  99. }
  100. // Verify extension
  101. $extension = getExtension($file['name'], false);
  102. if (!in_array(strtolower($extension), self::$validExtensions, true)) {
  103. Log::error(Database::get(), __METHOD__, __LINE__, 'Photo format not supported');
  104. if ($returnOnError===true) return false;
  105. Response::error('Photo format not supported!');
  106. }
  107. // Verify image
  108. $type = @exif_imagetype($file['tmp_name']);
  109. if (!in_array($type, self::$validTypes, true)) {
  110. Log::error(Database::get(), __METHOD__, __LINE__, 'Photo type not supported');
  111. if ($returnOnError===true) return false;
  112. Response::error('Photo type not supported!');
  113. }
  114. // Generate id
  115. $id = generateID();
  116. // Set paths
  117. $tmp_name = $file['tmp_name'];
  118. $photo_name = md5($id) . $extension;
  119. $path = LYCHEE_UPLOADS_BIG . $photo_name;
  120. // Calculate checksum
  121. $checksum = sha1_file($tmp_name);
  122. if ($checksum===false) {
  123. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not calculate checksum for photo');
  124. if ($returnOnError===true) return false;
  125. Response::error('Could not calculate checksum for photo!');
  126. }
  127. // Check if image exists based on checksum
  128. if ($checksum===false) {
  129. $checksum = '';
  130. $exists = false;
  131. } else {
  132. $exists = $this->exists($checksum);
  133. if ($exists!==false) {
  134. $photo_name = $exists['photo_name'];
  135. $path = $exists['path'];
  136. $path_thumb = $exists['path_thumb'];
  137. $medium = ($exists['medium']==='1' ? 1 : 0);
  138. $exists = true;
  139. }
  140. }
  141. if ($exists===false) {
  142. // Import if not uploaded via web
  143. if (!is_uploaded_file($tmp_name)) {
  144. if (!@copy($tmp_name, $path)) {
  145. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not copy photo to uploads');
  146. if ($returnOnError===true) return false;
  147. Response::error('Could not copy photo to uploads!');
  148. } else @unlink($tmp_name);
  149. } else {
  150. if (!@move_uploaded_file($tmp_name, $path)) {
  151. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not move photo to uploads');
  152. if ($returnOnError===true) return false;
  153. Response::error('Could not move photo to uploads!');
  154. }
  155. }
  156. } else {
  157. // Photo already exists
  158. // Check if the user wants to skip duplicates
  159. if (Settings::get()['skipDuplicates']==='1') {
  160. Log::notice(Database::get(), __METHOD__, __LINE__, 'Skipped upload of existing photo because skipDuplicates is activated');
  161. if ($returnOnError===true) return false;
  162. Response::warning('This photo has been skipped because it\'s already in your library.');
  163. }
  164. }
  165. // Read infos
  166. $info = $this->getInfo($path);
  167. // Use title of file if IPTC title missing
  168. if ($info['title']==='') $info['title'] = substr(basename($file['name'], $extension), 0, 30);
  169. if ($exists===false) {
  170. // Set orientation based on EXIF data
  171. if ($file['type']==='image/jpeg'&&isset($info['orientation'])&&$info['orientation']!=='') {
  172. $adjustFile = $this->adjustFile($path, $info);
  173. if ($adjustFile!==false) $info = $adjustFile;
  174. else Log::notice(Database::get(), __METHOD__, __LINE__, 'Skipped adjustment of photo (' . $info['title'] . ')');
  175. }
  176. // Set original date
  177. if ($info['takestamp']!==''&&$info['takestamp']!==0) @touch($path, $info['takestamp']);
  178. // Create Thumb
  179. if (!$this->createThumb($path, $photo_name, $info['type'], $info['width'], $info['height'])) {
  180. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not create thumbnail for photo');
  181. if ($returnOnError===true) return false;
  182. Response::error('Could not create thumbnail for photo!');
  183. }
  184. // Create Medium
  185. if ($this->createMedium($path, $photo_name, $info['width'], $info['height'])) $medium = 1;
  186. else $medium = 0;
  187. // Set thumb url
  188. $path_thumb = md5($id) . '.jpeg';
  189. }
  190. // Save to DB
  191. $values = array(LYCHEE_TABLE_PHOTOS, $id, $info['title'], $photo_name, $info['description'], $info['tags'], $info['type'], $info['width'], $info['height'], $info['size'], $info['iso'], $info['aperture'], $info['make'], $info['model'], $info['shutter'], $info['focal'], $info['takestamp'], $path_thumb, $albumID, $public, $star, $checksum, $medium);
  192. $query = Database::prepare(Database::get(), "INSERT INTO ? (id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum, medium) VALUES ('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')", $values);
  193. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  194. if ($result===false) {
  195. if ($returnOnError===true) return false;
  196. Response::error('Could not save photo in database!');
  197. }
  198. // Call plugins
  199. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  200. return true;
  201. }
  202. /**
  203. * @return array|false Returns a subset of a photo when same photo exists or returns false on failure.
  204. */
  205. private function exists($checksum, $photoID = null) {
  206. // Exclude $photoID from select when $photoID is set
  207. if (isset($photoID)) $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, medium FROM ? WHERE checksum = '?' AND id <> '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $checksum, $photoID));
  208. else $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, medium FROM ? WHERE checksum = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $checksum));
  209. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  210. if ($result===false) return false;
  211. if ($result->num_rows===1) {
  212. $result = $result->fetch_object();
  213. $return = array(
  214. 'photo_name' => $result->url,
  215. 'path' => LYCHEE_UPLOADS_BIG . $result->url,
  216. 'path_thumb' => $result->thumbUrl,
  217. 'medium' => $result->medium
  218. );
  219. return $return;
  220. }
  221. return false;
  222. }
  223. /**
  224. * @return boolean Returns true when successful.
  225. */
  226. private function createThumb($url, $filename, $type, $width, $height) {
  227. // Call plugins
  228. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  229. // Quality of thumbnails
  230. $thumbQuality = 90;
  231. // Size of the thumbnail
  232. $newWidth = 200;
  233. $newHeight = 200;
  234. $photoName = explode('.', $filename);
  235. $newUrl = LYCHEE_UPLOADS_THUMB . $photoName[0] . '.jpeg';
  236. $newUrl2x = LYCHEE_UPLOADS_THUMB . $photoName[0] . '@2x.jpeg';
  237. // Create thumbnails with Imagick
  238. if(Settings::hasImagick()) {
  239. // Read image
  240. $thumb = new Imagick();
  241. $thumb->readImage($url);
  242. $thumb->setImageCompressionQuality($thumbQuality);
  243. $thumb->setImageFormat('jpeg');
  244. // Copy image for 2nd thumb version
  245. $thumb2x = clone $thumb;
  246. // Create 1st version
  247. $thumb->cropThumbnailImage($newWidth, $newHeight);
  248. $thumb->writeImage($newUrl);
  249. $thumb->clear();
  250. $thumb->destroy();
  251. // Create 2nd version
  252. $thumb2x->cropThumbnailImage($newWidth*2, $newHeight*2);
  253. $thumb2x->writeImage($newUrl2x);
  254. $thumb2x->clear();
  255. $thumb2x->destroy();
  256. } else {
  257. // Create image
  258. $thumb = imagecreatetruecolor($newWidth, $newHeight);
  259. $thumb2x = imagecreatetruecolor($newWidth*2, $newHeight*2);
  260. // Set position
  261. if ($width<$height) {
  262. $newSize = $width;
  263. $startWidth = 0;
  264. $startHeight = $height/2 - $width/2;
  265. } else {
  266. $newSize = $height;
  267. $startWidth = $width/2 - $height/2;
  268. $startHeight = 0;
  269. }
  270. // Create new image
  271. switch($type) {
  272. case 'image/jpeg': $sourceImg = imagecreatefromjpeg($url); break;
  273. case 'image/png': $sourceImg = imagecreatefrompng($url); break;
  274. case 'image/gif': $sourceImg = imagecreatefromgif($url); break;
  275. default: Log::error(Database::get(), __METHOD__, __LINE__, 'Type of photo is not supported');
  276. return false;
  277. break;
  278. }
  279. // Create thumb
  280. fastImageCopyResampled($thumb, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth, $newHeight, $newSize, $newSize);
  281. imagejpeg($thumb, $newUrl, $thumbQuality);
  282. imagedestroy($thumb);
  283. // Create retina thumb
  284. fastImageCopyResampled($thumb2x, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth*2, $newHeight*2, $newSize, $newSize);
  285. imagejpeg($thumb2x, $newUrl2x, $thumbQuality);
  286. imagedestroy($thumb2x);
  287. // Free memory
  288. imagedestroy($sourceImg);
  289. }
  290. // Call plugins
  291. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  292. return true;
  293. }
  294. /**
  295. * Creates a smaller version of a photo when its size is bigger than a preset size.
  296. * Photo must be big enough and Imagick must be installed and activated.
  297. * @return boolean Returns true when successful.
  298. */
  299. private function createMedium($url, $filename, $width, $height) {
  300. // Excepts the following:
  301. // (string) $url = Path to the photo-file
  302. // (string) $filename = Name of the photo-file
  303. // (int) $width = Width of the photo
  304. // (int) $height = Height of the photo
  305. // Call plugins
  306. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  307. // Set to true when creation of medium-photo failed
  308. $error = false;
  309. // Size of the medium-photo
  310. // When changing these values,
  311. // also change the size detection in the front-end
  312. $newWidth = 1920;
  313. $newHeight = 1080;
  314. // Check permissions
  315. if (hasPermissions(LYCHEE_UPLOADS_MEDIUM)===false) {
  316. // Permissions are missing
  317. Log::notice(Database::get(), __METHOD__, __LINE__, 'Skipped creation of medium-photo, because uploads/medium/ is missing or not readable and writable.');
  318. $error = true;
  319. }
  320. // Is photo big enough?
  321. // Is Imagick installed and activated?
  322. if (($error===false)&&
  323. ($width>$newWidth||$height>$newHeight)&&
  324. (extension_loaded('imagick')&&Settings::get()['imagick']==='1')) {
  325. $newUrl = LYCHEE_UPLOADS_MEDIUM . $filename;
  326. // Read image
  327. $medium = new Imagick();
  328. $medium->readImage($url);
  329. // Adjust image
  330. $medium->scaleImage($newWidth, $newHeight, true);
  331. // Save image
  332. try { $medium->writeImage($newUrl); }
  333. catch (ImagickException $err) {
  334. Log::notice(Database::get(), __METHOD__, __LINE__, 'Could not save medium-photo (' . $err->getMessage() . ')');
  335. $error = true;
  336. }
  337. $medium->clear();
  338. $medium->destroy();
  339. } else {
  340. // Photo too small or
  341. // Medium is deactivated or
  342. // Imagick not installed
  343. $error = true;
  344. }
  345. // Call plugins
  346. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  347. if ($error===true) return false;
  348. return true;
  349. }
  350. /**
  351. * Rotates and flips a photo based on its EXIF orientation.
  352. * @return array|false Returns an array with the new orientation, width, height or false on failure.
  353. */
  354. public function adjustFile($path, array $info) {
  355. // Excepts the following:
  356. // (string) $path = Path to the photo-file
  357. // (array) $info = ['orientation', 'width', 'height']
  358. // Call plugins
  359. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  360. $swapSize = false;
  361. if (extension_loaded('imagick')&&Settings::get()['imagick']==='1') {
  362. switch ($info['orientation']) {
  363. case 3:
  364. $rotateImage = 180;
  365. break;
  366. case 6:
  367. $rotateImage = 90;
  368. $swapSize = true;
  369. break;
  370. case 8:
  371. $rotateImage = 270;
  372. $swapSize = true;
  373. break;
  374. default:
  375. return false;
  376. break;
  377. }
  378. if ($rotateImage!==0) {
  379. $image = new Imagick();
  380. $image->readImage($path);
  381. $image->rotateImage(new ImagickPixel(), $rotateImage);
  382. $image->setImageOrientation(1);
  383. $image->writeImage($path);
  384. $image->clear();
  385. $image->destroy();
  386. }
  387. } else {
  388. $newWidth = $info['width'];
  389. $newHeight = $info['height'];
  390. $sourceImg = imagecreatefromjpeg($path);
  391. switch ($info['orientation']) {
  392. case 2:
  393. // mirror
  394. // not yet implemented
  395. return false;
  396. break;
  397. case 3:
  398. $sourceImg = imagerotate($sourceImg, -180, 0);
  399. break;
  400. case 4:
  401. // rotate 180 and mirror
  402. // not yet implemented
  403. return false;
  404. break;
  405. case 5:
  406. // rotate 90 and mirror
  407. // not yet implemented
  408. return false;
  409. break;
  410. case 6:
  411. $sourceImg = imagerotate($sourceImg, -90, 0);
  412. $newWidth = $info['height'];
  413. $newHeight = $info['width'];
  414. $swapSize = true;
  415. break;
  416. case 7:
  417. // rotate -90 and mirror
  418. // not yet implemented
  419. return false;
  420. break;
  421. case 8:
  422. $sourceImg = imagerotate($sourceImg, 90, 0);
  423. $newWidth = $info['height'];
  424. $newHeight = $info['width'];
  425. $swapSize = true;
  426. break;
  427. default:
  428. return false;
  429. break;
  430. }
  431. // Recreate photo
  432. $newSourceImg = imagecreatetruecolor($newWidth, $newHeight);
  433. imagecopyresampled($newSourceImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight);
  434. imagejpeg($newSourceImg, $path, 100);
  435. // Free memory
  436. imagedestroy($sourceImg);
  437. imagedestroy($newSourceImg);
  438. }
  439. // Call plugins
  440. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  441. // SwapSize should be true when the image has been rotated
  442. // Return new dimensions in this case
  443. if ($swapSize===true) {
  444. $swapSize = $info['width'];
  445. $info['width'] = $info['height'];
  446. $info['height'] = $swapSize;
  447. }
  448. return $info;
  449. }
  450. /**
  451. * Rurns photo-attributes into a front-end friendly format. Note that some attributes remain unchanged.
  452. * @return array Returns photo-attributes in a normalized structure.
  453. */
  454. public static function prepareData(array $data) {
  455. // Excepts the following:
  456. // (array) $data = ['id', 'title', 'tags', 'public', 'star', 'album', 'thumbUrl', 'takestamp', 'url']
  457. // Init
  458. $photo = null;
  459. // Set unchanged attributes
  460. $photo['id'] = $data['id'];
  461. $photo['title'] = $data['title'];
  462. $photo['tags'] = $data['tags'];
  463. $photo['public'] = $data['public'];
  464. $photo['star'] = $data['star'];
  465. $photo['album'] = $data['album'];
  466. // Parse urls
  467. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $data['thumbUrl'];
  468. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $data['url'];
  469. // Use takestamp as sysdate when possible
  470. if (isset($data['takestamp'])&&$data['takestamp']!=='0') {
  471. // Use takestamp
  472. $photo['cameraDate'] = '1';
  473. $photo['sysdate'] = strftime('%d %B %Y', $data['takestamp']);
  474. } else {
  475. // Use sysstamp from the id
  476. $photo['cameraDate'] = '0';
  477. $photo['sysdate'] = strftime('%d %B %Y', substr($data['id'], 0, -4));
  478. }
  479. return $photo;
  480. }
  481. /**
  482. * @return array|false Returns an array with information about the photo or false on failure.
  483. */
  484. public function get($albumID) {
  485. // Excepts the following:
  486. // (string) $albumID = Album which is currently visible to the user
  487. // Check dependencies
  488. Validator::required(isset($this->photoIDs), __METHOD__);
  489. // Call plugins
  490. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  491. // Get photo
  492. $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  493. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  494. if ($photos===false) return false;
  495. // Get photo object
  496. $photo = $photos->fetch_assoc();
  497. // Photo not found?
  498. if ($photo===null) {
  499. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  500. return false;
  501. }
  502. // Parse photo
  503. $photo['sysdate'] = strftime('%d %b. %Y', substr($photo['id'], 0, -4));
  504. if (strlen($photo['takestamp'])>1) $photo['takedate'] = strftime('%d %b. %Y', $photo['takestamp']);
  505. // Parse medium
  506. if ($photo['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $photo['url'];
  507. else $photo['medium'] = '';
  508. // Parse paths
  509. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $photo['url'];
  510. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $photo['thumbUrl'];
  511. if ($albumID!='false') {
  512. // Only show photo as public when parent album is public
  513. // Check if parent album is not 'Unsorted'
  514. if ($photo['album']!=='0') {
  515. // Get album
  516. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $photo['album']));
  517. $albums = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  518. if ($albums===false) return false;
  519. // Get album object
  520. $album = $albums->fetch_assoc();
  521. // Photo not found?
  522. if ($photo===null) {
  523. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified album');
  524. return false;
  525. }
  526. // Parse album
  527. $photo['public'] = ($album['public']==='1' ? '2' : $photo['public']);
  528. }
  529. $photo['original_album'] = $photo['album'];
  530. $photo['album'] = $albumID;
  531. }
  532. // Call plugins
  533. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  534. return $photo;
  535. }
  536. /**
  537. * Reads and parses information and metadata out of a photo.
  538. * @return array Returns an array of photo information and metadata.
  539. */
  540. public function getInfo($url) {
  541. // Functions returns information and metadata of a photo
  542. // Excepts the following:
  543. // (string) $url = Path to photo-file
  544. // Returns the following:
  545. // (array) $return
  546. // Call plugins
  547. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  548. $iptcArray = array();
  549. $info = getimagesize($url, $iptcArray);
  550. // General information
  551. $return['type'] = $info['mime'];
  552. $return['width'] = $info[0];
  553. $return['height'] = $info[1];
  554. $return['title'] = '';
  555. $return['description'] = '';
  556. $return['orientation'] = '';
  557. $return['iso'] = '';
  558. $return['aperture'] = '';
  559. $return['make'] = '';
  560. $return['model'] = '';
  561. $return['shutter'] = '';
  562. $return['focal'] = '';
  563. $return['takestamp'] = 0;
  564. $return['lens'] = '';
  565. $return['tags'] = array();
  566. $return['position'] = '';
  567. $return['latitude'] = '';
  568. $return['longitude'] = '';
  569. $return['altitude'] = '';
  570. // Size
  571. $size = filesize($url)/1024;
  572. if ($size>=1024) $return['size'] = round($size/1024, 1) . ' MB';
  573. else $return['size'] = round($size, 1) . ' KB';
  574. // IPTC Metadata
  575. // See https://www.iptc.org/std/IIM/4.2/specification/IIMV4.2.pdf for mapping
  576. if(isset($iptcArray['APP13'])) {
  577. $iptcInfo = iptcparse($iptcArray['APP13']);
  578. if (is_array($iptcInfo)) {
  579. // Title
  580. if (!empty($iptcInfo['2#105'][0])) $return['title'] = $iptcInfo['2#105'][0];
  581. else if (!empty($iptcInfo['2#005'][0])) $return['title'] = $iptcInfo['2#005'][0];
  582. // Description
  583. if (!empty($iptcInfo['2#120'][0])) $return['description'] = $iptcInfo['2#120'][0];
  584. // Tags
  585. if (!empty($iptcInfo['2#025'])) $return['tags'] = implode(',', $iptcInfo['2#025']);
  586. // Position
  587. $fields = array();
  588. if (!empty($iptcInfo['2#090'])) $fields[] = trim($iptcInfo['2#090']);
  589. if (!empty($iptcInfo['2#092'])) $fields[] = trim($iptcInfo['2#092']);
  590. if (!empty($iptcInfo['2#095'])) $fields[] = trim($iptcInfo['2#095']);
  591. if (!empty($iptcInfo['2#101'])) $fields[] = trim($iptcInfo['2#101']);
  592. if (!empty($fields)) $return['position'] = implode(', ', $fields);
  593. }
  594. }
  595. // Read EXIF
  596. if ($info['mime']=='image/jpeg') $exif = @exif_read_data($url, 'EXIF', 0);
  597. else $exif = false;
  598. // EXIF Metadata
  599. if ($exif!==false) {
  600. if (isset($exif['Orientation'])) $return['orientation'] = $exif['Orientation'];
  601. else if (isset($exif['IFD0']['Orientation'])) $return['orientation'] = $exif['IFD0']['Orientation'];
  602. if (!empty($exif['ISOSpeedRatings'])) $return['iso'] = $exif['ISOSpeedRatings'];
  603. if (!empty($exif['COMPUTED']['ApertureFNumber'])) $return['aperture'] = $exif['COMPUTED']['ApertureFNumber'];
  604. if (!empty($exif['Make'])) $return['make'] = trim($exif['Make']);
  605. if (!empty($exif['Model'])) $return['model'] = trim($exif['Model']);
  606. if (!empty($exif['ExposureTime'])) $return['shutter'] = $exif['ExposureTime'] . ' s';
  607. $temp = @$exif['FocalLength'];
  608. if (isset($temp)) {
  609. if (strpos($temp, '/')!==false) {
  610. $temp = explode('/', $temp, 2);
  611. $temp = $temp[0] / $temp[1];
  612. $temp = round($temp, 1);
  613. $return['focal'] = $temp . ' mm';
  614. }
  615. $return['focal'] = $temp . ' mm';
  616. }
  617. if (!empty($exif['DateTimeOriginal'])) $return['takestamp'] = strtotime($exif['DateTimeOriginal']);
  618. // Lens field from Lightroom
  619. if (!empty($exif['UndefinedTag:0xA434'])) $return['lens'] = trim($exif['UndefinedTag:0xA434']);
  620. // Deal with GPS coordinates
  621. if (!empty($exif['GPSLatitude']) && !empty($exif['GPSLatitudeRef']))
  622. $return['latitude'] = getGPSCoordinate($exif['GPSLatitude'], $exif['GPSLatitudeRef']);
  623. if (!empty($exif['GPSLongitude']) && !empty($exif['GPSLongitudeRef']))
  624. $return['longitude'] = getGPSCoordinate($exif['GPSLongitude'], $exif['GPSLongitudeRef']);
  625. }
  626. // Call plugins
  627. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  628. return $return;
  629. }
  630. /**
  631. * Starts a download of a photo.
  632. * @return resource|boolean Sends a ZIP-file or returns false on failure.
  633. */
  634. public function getArchive() {
  635. // Check dependencies
  636. Validator::required(isset($this->photoIDs), __METHOD__);
  637. // Call plugins
  638. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  639. // Get photo
  640. $query = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  641. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  642. if ($photos===false) return false;
  643. // Get photo object
  644. $photo = $photos->fetch_object();
  645. // Photo not found?
  646. if ($photo===null) {
  647. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  648. return false;
  649. }
  650. // Get extension
  651. $extension = getExtension($photo->url, false);
  652. if (empty($extension)===true) {
  653. Log::error(Database::get(), __METHOD__, __LINE__, 'Invalid photo extension');
  654. return false;
  655. }
  656. // Illicit chars
  657. $badChars = array_merge(
  658. array_map('chr', range(0,31)),
  659. array("<", ">", ":", '"', "/", "\\", "|", "?", "*")
  660. );
  661. // Parse title
  662. if ($photo->title=='') $photo->title = 'Untitled';
  663. // Escape title
  664. $photo->title = str_replace($badChars, '', $photo->title);
  665. // Set headers
  666. header("Content-Type: application/octet-stream");
  667. header("Content-Disposition: attachment; filename=\"" . $photo->title . $extension . "\"");
  668. header("Content-Length: " . filesize(LYCHEE_UPLOADS_BIG . $photo->url));
  669. // Send file
  670. readfile(LYCHEE_UPLOADS_BIG . $photo->url);
  671. // Call plugins
  672. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  673. return true;
  674. }
  675. /**
  676. * Sets the title of a photo.
  677. * @return boolean Returns true when successful.
  678. */
  679. public function setTitle($title = 'Untitled') {
  680. // Check dependencies
  681. Validator::required(isset($this->photoIDs), __METHOD__);
  682. // Call plugins
  683. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  684. // Set title
  685. $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $title, $this->photoIDs));
  686. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  687. // Call plugins
  688. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  689. if ($result===false) return false;
  690. return true;
  691. }
  692. /**
  693. * Sets the description of a photo.
  694. * @return boolean Returns true when successful.
  695. */
  696. public function setDescription($description) {
  697. // Check dependencies
  698. Validator::required(isset($this->photoIDs), __METHOD__);
  699. // Call plugins
  700. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  701. // Set description
  702. $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN ('?')", array(LYCHEE_TABLE_PHOTOS, $description, $this->photoIDs));
  703. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  704. // Call plugins
  705. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  706. if ($result===false) return false;
  707. return true;
  708. }
  709. /**
  710. * Toggles the star property of a photo.
  711. * @return boolean Returns true when successful.
  712. */
  713. public function setStar() {
  714. // Check dependencies
  715. Validator::required(isset($this->photoIDs), __METHOD__);
  716. // Call plugins
  717. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  718. // Init vars
  719. $error = false;
  720. // Get photos
  721. $query = Database::prepare(Database::get(), "SELECT id, star FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  722. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  723. if ($photos===false) return false;
  724. // For each photo
  725. while ($photo = $photos->fetch_object()) {
  726. // Invert star
  727. $star = ($photo->star==0 ? 1 : 0);
  728. // Set star
  729. $query = Database::prepare(Database::get(), "UPDATE ? SET star = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $star, $photo->id));
  730. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  731. if ($result===false) $error = true;
  732. }
  733. // Call plugins
  734. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  735. if ($error===true) return false;
  736. return true;
  737. }
  738. /**
  739. * Checks if photo or parent album is public.
  740. * @return integer 0 = Photo private and parent album private
  741. * 1 = Album public, but password incorrect
  742. * 2 = Photo public or album public and password correct
  743. */
  744. public function getPublic($password) {
  745. // Check dependencies
  746. Validator::required(isset($this->photoIDs), __METHOD__);
  747. // Call plugins
  748. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  749. // Get photo
  750. $query = Database::prepare(Database::get(), "SELECT public, album FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  751. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  752. if ($photos===false) return 0;
  753. // Get photo object
  754. $photo = $photos->fetch_object();
  755. // Photo not found?
  756. if ($photo===null) {
  757. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  758. return false;
  759. }
  760. // Check if public
  761. if ($photo->public==='1') {
  762. // Photo public
  763. return 2;
  764. } else {
  765. // Check if album public
  766. $album = new Album($photo->album);
  767. $agP = $album->getPublic();
  768. $acP = $album->checkPassword($password);
  769. // Album public and password correct
  770. if ($agP===true&&$acP===true) return 2;
  771. // Album public, but password incorrect
  772. if ($agP===true&&$acP===false) return 1;
  773. }
  774. // Call plugins
  775. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  776. // Photo private
  777. return 0;
  778. }
  779. /**
  780. * Toggles the public property of a photo.
  781. * @return boolean Returns true when successful.
  782. */
  783. public function setPublic() {
  784. // Check dependencies
  785. Validator::required(isset($this->photoIDs), __METHOD__);
  786. // Call plugins
  787. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  788. // Get public
  789. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  790. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  791. if ($photos===false) return false;
  792. // Get photo object
  793. $photo = $photos->fetch_object();
  794. // Photo not found?
  795. if ($photo===null) {
  796. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  797. return false;
  798. }
  799. // Invert public
  800. $public = ($photo->public==0 ? 1 : 0);
  801. // Set public
  802. $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $public, $this->photoIDs));
  803. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  804. // Call plugins
  805. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  806. if ($result===false) return false;
  807. return true;
  808. }
  809. /**
  810. * Sets the parent album of a photo.
  811. * @return boolean Returns true when successful.
  812. */
  813. function setAlbum($albumID) {
  814. // Check dependencies
  815. Validator::required(isset($this->photoIDs), __METHOD__);
  816. // Call plugins
  817. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  818. // Set album
  819. $query = Database::prepare(Database::get(), "UPDATE ? SET album = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->photoIDs));
  820. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  821. // Call plugins
  822. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  823. if ($result===false) return false;
  824. return true;
  825. }
  826. /**
  827. * Sets the tags of a photo.
  828. * @return boolean Returns true when successful.
  829. */
  830. public function setTags($tags) {
  831. // Excepts the following:
  832. // (string) $tags = Comma separated list of tags with a maximum length of 1000 chars
  833. // Check dependencies
  834. Validator::required(isset($this->photoIDs), __METHOD__);
  835. // Call plugins
  836. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  837. // Parse tags
  838. $tags = preg_replace('/(\ ,\ )|(\ ,)|(,\ )|(,{1,}\ {0,})|(,$|^,)/', ',', $tags);
  839. $tags = preg_replace('/,$|^,|(\ ){0,}$/', '', $tags);
  840. // Set tags
  841. $query = Database::prepare(Database::get(), "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs));
  842. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  843. // Call plugins
  844. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  845. if ($result===false) return false;
  846. return true;
  847. }
  848. /**
  849. * Duplicates a photo.
  850. * @return boolean Returns true when successful.
  851. */
  852. public function duplicate() {
  853. // Check dependencies
  854. Validator::required(isset($this->photoIDs), __METHOD__);
  855. // Call plugins
  856. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  857. // Init vars
  858. $error = false;
  859. // Get photos
  860. $query = Database::prepare(Database::get(), "SELECT id, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  861. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  862. if ($photos===false) return false;
  863. // For each photo
  864. while ($photo = $photos->fetch_object()) {
  865. // Generate id
  866. $id = generateID();
  867. // Duplicate entry
  868. $values = array(LYCHEE_TABLE_PHOTOS, $id, LYCHEE_TABLE_PHOTOS, $photo->id);
  869. $query = Database::prepare(Database::get(), "INSERT INTO ? (id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum) SELECT '?' AS id, title, url, description, tags, type, width, height, size, iso, aperture, make, model, shutter, focal, takestamp, thumbUrl, album, public, star, checksum FROM ? WHERE id = '?'", $values);
  870. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  871. if ($result===false) $error = true;
  872. }
  873. if ($error===true) return false;
  874. return true;
  875. }
  876. /**
  877. * Deletes a photo with all its data and files.
  878. * @return boolean Returns true when successful.
  879. */
  880. public function delete() {
  881. // Check dependencies
  882. Validator::required(isset($this->photoIDs), __METHOD__);
  883. // Call plugins
  884. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  885. // Init vars
  886. $error = false;
  887. // Get photos
  888. $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  889. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  890. if ($photos===false) return false;
  891. // For each photo
  892. while ($photo = $photos->fetch_object()) {
  893. // Check if other photos are referring to this images
  894. // If so, only delete the db entry
  895. if ($this->exists($photo->checksum, $photo->id)===false) {
  896. // Get retina thumb url
  897. $thumbUrl2x = explode(".", $photo->thumbUrl);
  898. $thumbUrl2x = $thumbUrl2x[0] . '@2x.' . $thumbUrl2x[1];
  899. // Delete big
  900. if (file_exists(LYCHEE_UPLOADS_BIG . $photo->url)&&!unlink(LYCHEE_UPLOADS_BIG . $photo->url)) {
  901. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/big/');
  902. $error = true;
  903. }
  904. // Delete medium
  905. if (file_exists(LYCHEE_UPLOADS_MEDIUM . $photo->url)&&!unlink(LYCHEE_UPLOADS_MEDIUM . $photo->url)) {
  906. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/medium/');
  907. $error = true;
  908. }
  909. // Delete thumb
  910. if (file_exists(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)&&!unlink(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)) {
  911. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/thumb/');
  912. $error = true;
  913. }
  914. // Delete thumb@2x
  915. if (file_exists(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)&&!unlink(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)) {
  916. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete high-res photo in uploads/thumb/');
  917. $error = true;
  918. }
  919. }
  920. // Delete db entry
  921. $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photo->id));
  922. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  923. if ($result===false) $error = true;
  924. }
  925. // Call plugins
  926. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  927. if ($error===true) return false;
  928. return true;
  929. }
  930. }
  931. ?>