Photo.php 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294
  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 string|false ID of the added photo.
  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. $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);
  191. $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);
  192. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  193. if ($result===false) {
  194. if ($returnOnError===true) return false;
  195. Response::error('Could not save photo in database!');
  196. }
  197. // Call plugins
  198. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  199. return $id;
  200. }
  201. /**
  202. * @return array|false Returns a subset of a photo when same photo exists or returns false on failure.
  203. */
  204. private function exists($checksum, $photoID = null) {
  205. // Exclude $photoID from select when $photoID is set
  206. 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));
  207. else $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, medium FROM ? WHERE checksum = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $checksum));
  208. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  209. if ($result===false) return false;
  210. if ($result->num_rows===1) {
  211. $result = $result->fetch_object();
  212. $return = array(
  213. 'photo_name' => $result->url,
  214. 'path' => LYCHEE_UPLOADS_BIG . $result->url,
  215. 'path_thumb' => $result->thumbUrl,
  216. 'medium' => $result->medium
  217. );
  218. return $return;
  219. }
  220. return false;
  221. }
  222. /**
  223. * @return boolean Returns true when successful.
  224. */
  225. private function createThumb($url, $filename, $type, $width, $height) {
  226. // Call plugins
  227. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  228. // Quality of thumbnails
  229. $quality = 90;
  230. // Size of the thumbnail
  231. $newWidth = 200;
  232. $newHeight = 200;
  233. $photoName = explode('.', $filename);
  234. $newUrl = LYCHEE_UPLOADS_THUMB . $photoName[0] . '.jpeg';
  235. $newUrl2x = LYCHEE_UPLOADS_THUMB . $photoName[0] . '@2x.jpeg';
  236. // Create thumbnails with Imagick
  237. if(Settings::hasImagick()) {
  238. // Read image
  239. $thumb = new Imagick();
  240. $thumb->readImage($url);
  241. $thumb->setImageCompressionQuality($quality);
  242. $thumb->setImageFormat('jpeg');
  243. // Copy image for 2nd thumb version
  244. $thumb2x = clone $thumb;
  245. // Create 1st version
  246. $thumb->cropThumbnailImage($newWidth, $newHeight);
  247. $thumb->writeImage($newUrl);
  248. $thumb->clear();
  249. $thumb->destroy();
  250. // Create 2nd version
  251. $thumb2x->cropThumbnailImage($newWidth*2, $newHeight*2);
  252. $thumb2x->writeImage($newUrl2x);
  253. $thumb2x->clear();
  254. $thumb2x->destroy();
  255. } else {
  256. // Create image
  257. $thumb = imagecreatetruecolor($newWidth, $newHeight);
  258. $thumb2x = imagecreatetruecolor($newWidth*2, $newHeight*2);
  259. // Set position
  260. if ($width<$height) {
  261. $newSize = $width;
  262. $startWidth = 0;
  263. $startHeight = $height/2 - $width/2;
  264. } else {
  265. $newSize = $height;
  266. $startWidth = $width/2 - $height/2;
  267. $startHeight = 0;
  268. }
  269. // Create new image
  270. switch($type) {
  271. case 'image/jpeg': $sourceImg = imagecreatefromjpeg($url); break;
  272. case 'image/png': $sourceImg = imagecreatefrompng($url); break;
  273. case 'image/gif': $sourceImg = imagecreatefromgif($url); break;
  274. default: Log::error(Database::get(), __METHOD__, __LINE__, 'Type of photo is not supported');
  275. return false;
  276. break;
  277. }
  278. // Create thumb
  279. fastImageCopyResampled($thumb, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth, $newHeight, $newSize, $newSize);
  280. imagejpeg($thumb, $newUrl, $thumbQuality);
  281. imagedestroy($thumb);
  282. // Create retina thumb
  283. fastImageCopyResampled($thumb2x, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth*2, $newHeight*2, $newSize, $newSize);
  284. imagejpeg($thumb2x, $newUrl2x, $thumbQuality);
  285. imagedestroy($thumb2x);
  286. // Free memory
  287. imagedestroy($sourceImg);
  288. }
  289. // Call plugins
  290. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  291. return true;
  292. }
  293. /**
  294. * Creates a smaller version of a photo when its size is bigger than a preset size.
  295. * Photo must be big enough and Imagick must be installed and activated.
  296. * @return boolean Returns true when successful.
  297. */
  298. private function createMedium($url, $filename, $width, $height) {
  299. // Excepts the following:
  300. // (string) $url = Path to the photo-file
  301. // (string) $filename = Name of the photo-file
  302. // (int) $width = Width of the photo
  303. // (int) $height = Height of the photo
  304. // Call plugins
  305. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  306. // Set to true when creation of medium-photo failed
  307. $error = false;
  308. // Size of the medium-photo
  309. // When changing these values,
  310. // also change the size detection in the front-end
  311. $newWidth = 1920;
  312. $newHeight = 1080;
  313. // Check permissions
  314. if (hasPermissions(LYCHEE_UPLOADS_MEDIUM)===false) {
  315. // Permissions are missing
  316. Log::notice(Database::get(), __METHOD__, __LINE__, 'Skipped creation of medium-photo, because uploads/medium/ is missing or not readable and writable.');
  317. $error = true;
  318. }
  319. // Is photo big enough?
  320. // Is Imagick installed and activated?
  321. if (($error===false)&&
  322. ($width>$newWidth||$height>$newHeight)&&
  323. (extension_loaded('imagick')&&Settings::get()['imagick']==='1')) {
  324. $newUrl = LYCHEE_UPLOADS_MEDIUM . $filename;
  325. // Read image
  326. $medium = new Imagick();
  327. $medium->readImage($url);
  328. // Adjust image
  329. $medium->scaleImage($newWidth, $newHeight, true);
  330. // Save image
  331. try { $medium->writeImage($newUrl); }
  332. catch (ImagickException $err) {
  333. Log::notice(Database::get(), __METHOD__, __LINE__, 'Could not save medium-photo (' . $err->getMessage() . ')');
  334. $error = true;
  335. }
  336. $medium->clear();
  337. $medium->destroy();
  338. } else {
  339. // Photo too small or
  340. // Medium is deactivated or
  341. // Imagick not installed
  342. $error = true;
  343. }
  344. // Call plugins
  345. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  346. if ($error===true) return false;
  347. return true;
  348. }
  349. /**
  350. * Rotates and flips a photo based on its EXIF orientation.
  351. * @return array|false Returns an array with the new orientation, width, height or false on failure.
  352. */
  353. public function adjustFile($path, array $info) {
  354. // Excepts the following:
  355. // (string) $path = Path to the photo-file
  356. // (array) $info = ['orientation', 'width', 'height']
  357. // Call plugins
  358. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  359. $swapSize = false;
  360. if (extension_loaded('imagick')&&Settings::get()['imagick']==='1') {
  361. $image = new Imagick();
  362. $image->readImage($path);
  363. $orientation = $image->getImageOrientation();
  364. // Check if the images needs to be adjusted at all
  365. if ($orientation!==Imagick::ORIENTATION_TOPLEFT) {
  366. switch ($orientation) {
  367. case Imagick::ORIENTATION_TOPLEFT:
  368. break;
  369. case Imagick::ORIENTATION_TOPRIGHT:
  370. $image->flopImage();
  371. break;
  372. case Imagick::ORIENTATION_BOTTOMRIGHT:
  373. $image->rotateImage(new ImagickPixel(), 180);
  374. break;
  375. case Imagick::ORIENTATION_BOTTOMLEFT:
  376. $image->flopImage();
  377. $image->rotateImage(new ImagickPixel(), 180);
  378. break;
  379. case Imagick::ORIENTATION_LEFTTOP:
  380. $image->flopImage();
  381. $image->rotateImage(new ImagickPixel(), -90);
  382. $swapSize = true;
  383. break;
  384. case Imagick::ORIENTATION_RIGHTTOP:
  385. $image->rotateImage(new ImagickPixel(), 90);
  386. $swapSize = true;
  387. break;
  388. case Imagick::ORIENTATION_RIGHTBOTTOM:
  389. $image->flopImage();
  390. $image->rotateImage(new ImagickPixel(), 90);
  391. $swapSize = true;
  392. break;
  393. case Imagick::ORIENTATION_LEFTBOTTOM:
  394. $image->rotateImage(new ImagickPixel(), -90);
  395. $swapSize = true;
  396. break;
  397. default:
  398. break;
  399. }
  400. $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
  401. $image->writeImage($path);
  402. }
  403. $image->clear();
  404. $image->destroy();
  405. } else {
  406. $newWidth = $info['width'];
  407. $newHeight = $info['height'];
  408. $sourceImg = imagecreatefromjpeg($path);
  409. switch ($info['orientation']) {
  410. case 2:
  411. // mirror
  412. // not yet implemented
  413. return false;
  414. break;
  415. case 3:
  416. $sourceImg = imagerotate($sourceImg, -180, 0);
  417. break;
  418. case 4:
  419. // rotate 180 and mirror
  420. // not yet implemented
  421. return false;
  422. break;
  423. case 5:
  424. // rotate 90 and mirror
  425. // not yet implemented
  426. return false;
  427. break;
  428. case 6:
  429. $sourceImg = imagerotate($sourceImg, -90, 0);
  430. $newWidth = $info['height'];
  431. $newHeight = $info['width'];
  432. $swapSize = true;
  433. break;
  434. case 7:
  435. // rotate -90 and mirror
  436. // not yet implemented
  437. return false;
  438. break;
  439. case 8:
  440. $sourceImg = imagerotate($sourceImg, 90, 0);
  441. $newWidth = $info['height'];
  442. $newHeight = $info['width'];
  443. $swapSize = true;
  444. break;
  445. default:
  446. return false;
  447. break;
  448. }
  449. // Recreate photo
  450. $newSourceImg = imagecreatetruecolor($newWidth, $newHeight);
  451. imagecopyresampled($newSourceImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight);
  452. imagejpeg($newSourceImg, $path, 100);
  453. // Free memory
  454. imagedestroy($sourceImg);
  455. imagedestroy($newSourceImg);
  456. }
  457. // Call plugins
  458. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  459. // SwapSize should be true when the image has been rotated
  460. // Return new dimensions in this case
  461. if ($swapSize===true) {
  462. $swapSize = $info['width'];
  463. $info['width'] = $info['height'];
  464. $info['height'] = $swapSize;
  465. }
  466. return $info;
  467. }
  468. /**
  469. * Rurns photo-attributes into a front-end friendly format. Note that some attributes remain unchanged.
  470. * @return array Returns photo-attributes in a normalized structure.
  471. */
  472. public static function prepareData(array $data) {
  473. // Excepts the following:
  474. // (array) $data = ['id', 'title', 'tags', 'public', 'star', 'album', 'thumbUrl', 'takestamp', 'url']
  475. // Init
  476. $photo = null;
  477. // Set unchanged attributes
  478. $photo['id'] = $data['id'];
  479. $photo['title'] = $data['title'];
  480. $photo['tags'] = $data['tags'];
  481. $photo['public'] = $data['public'];
  482. $photo['star'] = $data['star'];
  483. $photo['album'] = $data['album'];
  484. // Parse urls
  485. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $data['thumbUrl'];
  486. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $data['url'];
  487. // Use takestamp as sysdate when possible
  488. if (isset($data['takestamp'])&&$data['takestamp']!=='0') {
  489. // Use takestamp
  490. $photo['cameraDate'] = '1';
  491. $photo['sysdate'] = strftime('%d %B %Y', $data['takestamp']);
  492. } else {
  493. // Use sysstamp from the id
  494. $photo['cameraDate'] = '0';
  495. $photo['sysdate'] = strftime('%d %B %Y', substr($data['id'], 0, -4));
  496. }
  497. return $photo;
  498. }
  499. /**
  500. * @return array|false Returns an array with information about the photo or false on failure.
  501. */
  502. public function get($albumID) {
  503. // Excepts the following:
  504. // (string) $albumID = Album which is currently visible to the user
  505. // Check dependencies
  506. Validator::required(isset($this->photoIDs), __METHOD__);
  507. // Call plugins
  508. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  509. // Get photo
  510. $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  511. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  512. if ($photos===false) return false;
  513. // Get photo object
  514. $photo = $photos->fetch_assoc();
  515. // Photo not found?
  516. if ($photo===null) {
  517. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  518. return false;
  519. }
  520. // Parse photo
  521. $photo['sysdate'] = strftime('%d %b. %Y', substr($photo['id'], 0, -4));
  522. if (strlen($photo['takestamp'])>1) $photo['takedate'] = strftime('%d %b. %Y', $photo['takestamp']);
  523. // Parse medium
  524. if ($photo['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $photo['url'];
  525. else $photo['medium'] = '';
  526. // Parse paths
  527. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $photo['url'];
  528. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $photo['thumbUrl'];
  529. if ($albumID!='false') {
  530. // Only show photo as public when parent album is public
  531. // Check if parent album is not 'Unsorted'
  532. if ($photo['album']!=='0') {
  533. // Get album
  534. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $photo['album']));
  535. $albums = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  536. if ($albums===false) return false;
  537. // Get album object
  538. $album = $albums->fetch_assoc();
  539. // Photo not found?
  540. if ($photo===null) {
  541. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified album');
  542. return false;
  543. }
  544. // Parse album
  545. $photo['public'] = ($album['public']==='1' ? '2' : $photo['public']);
  546. }
  547. $photo['original_album'] = $photo['album'];
  548. $photo['album'] = $albumID;
  549. }
  550. // Call plugins
  551. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  552. return $photo;
  553. }
  554. /**
  555. * Reads and parses information and metadata out of a photo.
  556. * @return array Returns an array of photo information and metadata.
  557. */
  558. public function getInfo($url) {
  559. // Functions returns information and metadata of a photo
  560. // Excepts the following:
  561. // (string) $url = Path to photo-file
  562. // Returns the following:
  563. // (array) $return
  564. // Call plugins
  565. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  566. $iptcArray = array();
  567. $info = getimagesize($url, $iptcArray);
  568. // General information
  569. $return['type'] = $info['mime'];
  570. $return['width'] = $info[0];
  571. $return['height'] = $info[1];
  572. $return['title'] = '';
  573. $return['description'] = '';
  574. $return['orientation'] = '';
  575. $return['iso'] = '';
  576. $return['aperture'] = '';
  577. $return['make'] = '';
  578. $return['model'] = '';
  579. $return['shutter'] = '';
  580. $return['focal'] = '';
  581. $return['takestamp'] = 0;
  582. $return['lens'] = '';
  583. $return['tags'] = '';
  584. $return['position'] = '';
  585. $return['latitude'] = '';
  586. $return['longitude'] = '';
  587. $return['altitude'] = '';
  588. // Size
  589. $size = filesize($url)/1024;
  590. if ($size>=1024) $return['size'] = round($size/1024, 1) . ' MB';
  591. else $return['size'] = round($size, 1) . ' KB';
  592. // IPTC Metadata
  593. // See https://www.iptc.org/std/IIM/4.2/specification/IIMV4.2.pdf for mapping
  594. if(isset($iptcArray['APP13'])) {
  595. $iptcInfo = iptcparse($iptcArray['APP13']);
  596. if (is_array($iptcInfo)) {
  597. // Title
  598. if (!empty($iptcInfo['2#105'][0])) $return['title'] = $iptcInfo['2#105'][0];
  599. else if (!empty($iptcInfo['2#005'][0])) $return['title'] = $iptcInfo['2#005'][0];
  600. // Description
  601. if (!empty($iptcInfo['2#120'][0])) $return['description'] = $iptcInfo['2#120'][0];
  602. // Tags
  603. if (!empty($iptcInfo['2#025'])) $return['tags'] = implode(',', $iptcInfo['2#025']);
  604. // Position
  605. $fields = array();
  606. if (!empty($iptcInfo['2#090'])) $fields[] = trim($iptcInfo['2#090'][0]);
  607. if (!empty($iptcInfo['2#092'])) $fields[] = trim($iptcInfo['2#092'][0]);
  608. if (!empty($iptcInfo['2#095'])) $fields[] = trim($iptcInfo['2#095'][0]);
  609. if (!empty($iptcInfo['2#101'])) $fields[] = trim($iptcInfo['2#101'][0]);
  610. if (!empty($fields)) $return['position'] = implode(', ', $fields);
  611. }
  612. }
  613. // Read EXIF
  614. if ($info['mime']=='image/jpeg') $exif = @exif_read_data($url, 'EXIF', false, false);
  615. else $exif = false;
  616. // EXIF Metadata
  617. if ($exif!==false) {
  618. // Orientation
  619. if (isset($exif['Orientation'])) $return['orientation'] = $exif['Orientation'];
  620. else if (isset($exif['IFD0']['Orientation'])) $return['orientation'] = $exif['IFD0']['Orientation'];
  621. // ISO
  622. if (!empty($exif['ISOSpeedRatings'])) $return['iso'] = $exif['ISOSpeedRatings'];
  623. // Aperture
  624. if (!empty($exif['COMPUTED']['ApertureFNumber'])) $return['aperture'] = $exif['COMPUTED']['ApertureFNumber'];
  625. // Make
  626. if (!empty($exif['Make'])) $return['make'] = trim($exif['Make']);
  627. // Model
  628. if (!empty($exif['Model'])) $return['model'] = trim($exif['Model']);
  629. // Exposure
  630. if (!empty($exif['ExposureTime'])) $return['shutter'] = $exif['ExposureTime'] . ' s';
  631. // Focal Length
  632. if (!empty($exif['FocalLength'])) {
  633. if (strpos($exif['FocalLength'], '/')!==false) {
  634. $temp = explode('/', $exif['FocalLength'], 2);
  635. $temp = $temp[0] / $temp[1];
  636. $temp = round($temp, 1);
  637. $return['focal'] = $temp . ' mm';
  638. } else {
  639. $return['focal'] = $exif['FocalLength'] . ' mm';
  640. }
  641. }
  642. // Takestamp
  643. if (!empty($exif['DateTimeOriginal'])) $return['takestamp'] = strtotime($exif['DateTimeOriginal']);
  644. // Lens field from Lightroom
  645. if (!empty($exif['UndefinedTag:0xA434'])) $return['lens'] = trim($exif['UndefinedTag:0xA434']);
  646. // Deal with GPS coordinates
  647. if (!empty($exif['GPSLatitude']) && !empty($exif['GPSLatitudeRef'])) $return['latitude'] = getGPSCoordinate($exif['GPSLatitude'], $exif['GPSLatitudeRef']);
  648. if (!empty($exif['GPSLongitude']) && !empty($exif['GPSLongitudeRef'])) $return['longitude'] = getGPSCoordinate($exif['GPSLongitude'], $exif['GPSLongitudeRef']);
  649. }
  650. // Call plugins
  651. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  652. return $return;
  653. }
  654. /**
  655. * Starts a download of a photo.
  656. * @return resource|boolean Sends a ZIP-file or returns false on failure.
  657. */
  658. public function getArchive() {
  659. // Check dependencies
  660. Validator::required(isset($this->photoIDs), __METHOD__);
  661. // Call plugins
  662. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  663. // Get photo
  664. $query = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  665. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  666. if ($photos===false) return false;
  667. // Get photo object
  668. $photo = $photos->fetch_object();
  669. // Photo not found?
  670. if ($photo===null) {
  671. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  672. return false;
  673. }
  674. // Get extension
  675. $extension = getExtension($photo->url, false);
  676. if (empty($extension)===true) {
  677. Log::error(Database::get(), __METHOD__, __LINE__, 'Invalid photo extension');
  678. return false;
  679. }
  680. // Illicit chars
  681. $badChars = array_merge(
  682. array_map('chr', range(0,31)),
  683. array("<", ">", ":", '"', "/", "\\", "|", "?", "*")
  684. );
  685. // Parse title
  686. if ($photo->title=='') $photo->title = 'Untitled';
  687. // Escape title
  688. $photo->title = str_replace($badChars, '', $photo->title);
  689. // Set headers
  690. header("Content-Type: application/octet-stream");
  691. header("Content-Disposition: attachment; filename=\"" . $photo->title . $extension . "\"");
  692. header("Content-Length: " . filesize(LYCHEE_UPLOADS_BIG . $photo->url));
  693. // Send file
  694. readfile(LYCHEE_UPLOADS_BIG . $photo->url);
  695. // Call plugins
  696. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  697. return true;
  698. }
  699. /**
  700. * Sets the title of a photo.
  701. * @return boolean Returns true when successful.
  702. */
  703. public function setTitle($title = 'Untitled') {
  704. // Check dependencies
  705. Validator::required(isset($this->photoIDs), __METHOD__);
  706. // Call plugins
  707. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  708. // Set title
  709. $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $title, $this->photoIDs));
  710. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  711. // Call plugins
  712. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  713. if ($result===false) return false;
  714. return true;
  715. }
  716. /**
  717. * Sets the description of a photo.
  718. * @return boolean Returns true when successful.
  719. */
  720. public function setDescription($description) {
  721. // Check dependencies
  722. Validator::required(isset($this->photoIDs), __METHOD__);
  723. // Call plugins
  724. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  725. // Set description
  726. $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN ('?')", array(LYCHEE_TABLE_PHOTOS, $description, $this->photoIDs));
  727. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  728. // Call plugins
  729. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  730. if ($result===false) return false;
  731. return true;
  732. }
  733. /**
  734. * Toggles the star property of a photo.
  735. * @return boolean Returns true when successful.
  736. */
  737. public function setStar() {
  738. // Check dependencies
  739. Validator::required(isset($this->photoIDs), __METHOD__);
  740. // Call plugins
  741. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  742. // Init vars
  743. $error = false;
  744. // Get photos
  745. $query = Database::prepare(Database::get(), "SELECT id, star FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  746. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  747. if ($photos===false) return false;
  748. // For each photo
  749. while ($photo = $photos->fetch_object()) {
  750. // Invert star
  751. $star = ($photo->star==0 ? 1 : 0);
  752. // Set star
  753. $query = Database::prepare(Database::get(), "UPDATE ? SET star = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $star, $photo->id));
  754. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  755. if ($result===false) $error = true;
  756. }
  757. // Call plugins
  758. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  759. if ($error===true) return false;
  760. return true;
  761. }
  762. /**
  763. * Checks if photo or parent album is public.
  764. * @return integer 0 = Photo private and parent album private
  765. * 1 = Album public, but password incorrect
  766. * 2 = Photo public or album public and password correct
  767. */
  768. public function getPublic($password) {
  769. // Check dependencies
  770. Validator::required(isset($this->photoIDs), __METHOD__);
  771. // Call plugins
  772. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  773. // Get photo
  774. $query = Database::prepare(Database::get(), "SELECT public, album FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  775. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  776. if ($photos===false) return 0;
  777. // Get photo object
  778. $photo = $photos->fetch_object();
  779. // Photo not found?
  780. if ($photo===null) {
  781. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  782. return false;
  783. }
  784. // Check if public
  785. if ($photo->public==='1') {
  786. // Photo public
  787. return 2;
  788. } else {
  789. // Check if album public
  790. $album = new Album($photo->album);
  791. $agP = $album->getPublic();
  792. $acP = $album->checkPassword($password);
  793. // Album public and password correct
  794. if ($agP===true&&$acP===true) return 2;
  795. // Album public, but password incorrect
  796. if ($agP===true&&$acP===false) return 1;
  797. }
  798. // Call plugins
  799. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  800. // Photo private
  801. return 0;
  802. }
  803. /**
  804. * Toggles the public property of a photo.
  805. * @return boolean Returns true when successful.
  806. */
  807. public function setPublic() {
  808. // Check dependencies
  809. Validator::required(isset($this->photoIDs), __METHOD__);
  810. // Call plugins
  811. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  812. // Get public
  813. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  814. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  815. if ($photos===false) return false;
  816. // Get photo object
  817. $photo = $photos->fetch_object();
  818. // Photo not found?
  819. if ($photo===null) {
  820. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  821. return false;
  822. }
  823. // Invert public
  824. $public = ($photo->public==0 ? 1 : 0);
  825. // Set public
  826. $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $public, $this->photoIDs));
  827. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  828. // Call plugins
  829. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  830. if ($result===false) return false;
  831. return true;
  832. }
  833. /**
  834. * Sets the parent album of a photo.
  835. * @return boolean Returns true when successful.
  836. */
  837. function setAlbum($albumID) {
  838. // Check dependencies
  839. Validator::required(isset($this->photoIDs), __METHOD__);
  840. // Call plugins
  841. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  842. // Set album
  843. $query = Database::prepare(Database::get(), "UPDATE ? SET album = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->photoIDs));
  844. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  845. // Call plugins
  846. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  847. if ($result===false) return false;
  848. return true;
  849. }
  850. /**
  851. * Sets the tags of a photo.
  852. * @return boolean Returns true when successful.
  853. */
  854. public function setTags($tags) {
  855. // Excepts the following:
  856. // (string) $tags = Comma separated list of tags with a maximum length of 1000 chars
  857. // Check dependencies
  858. Validator::required(isset($this->photoIDs), __METHOD__);
  859. // Call plugins
  860. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  861. // Parse tags
  862. $tags = preg_replace('/(\ ,\ )|(\ ,)|(,\ )|(,{1,}\ {0,})|(,$|^,)/', ',', $tags);
  863. $tags = preg_replace('/,$|^,|(\ ){0,}$/', '', $tags);
  864. // Set tags
  865. $query = Database::prepare(Database::get(), "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs));
  866. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  867. // Call plugins
  868. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  869. if ($result===false) return false;
  870. return true;
  871. }
  872. /**
  873. * Duplicates a photo.
  874. * @return boolean Returns true when successful.
  875. */
  876. public function duplicate() {
  877. // Check dependencies
  878. Validator::required(isset($this->photoIDs), __METHOD__);
  879. // Call plugins
  880. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  881. // Init vars
  882. $error = false;
  883. // Get photos
  884. $query = Database::prepare(Database::get(), "SELECT id, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  885. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  886. if ($photos===false) return false;
  887. // For each photo
  888. while ($photo = $photos->fetch_object()) {
  889. // Generate id
  890. $id = generateID();
  891. // Duplicate entry
  892. $values = array(LYCHEE_TABLE_PHOTOS, $id, LYCHEE_TABLE_PHOTOS, $photo->id);
  893. $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);
  894. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  895. if ($result===false) $error = true;
  896. }
  897. if ($error===true) return false;
  898. return true;
  899. }
  900. /**
  901. * Deletes a photo with all its data and files.
  902. * @return boolean Returns true when successful.
  903. */
  904. public function delete() {
  905. // Check dependencies
  906. Validator::required(isset($this->photoIDs), __METHOD__);
  907. // Call plugins
  908. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  909. // Init vars
  910. $error = false;
  911. // Get photos
  912. $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  913. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  914. if ($photos===false) return false;
  915. // For each photo
  916. while ($photo = $photos->fetch_object()) {
  917. // Check if other photos are referring to this images
  918. // If so, only delete the db entry
  919. if ($this->exists($photo->checksum, $photo->id)===false) {
  920. // Get retina thumb url
  921. $thumbUrl2x = explode(".", $photo->thumbUrl);
  922. $thumbUrl2x = $thumbUrl2x[0] . '@2x.' . $thumbUrl2x[1];
  923. // Delete big
  924. if (file_exists(LYCHEE_UPLOADS_BIG . $photo->url)&&!unlink(LYCHEE_UPLOADS_BIG . $photo->url)) {
  925. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/big/');
  926. $error = true;
  927. }
  928. // Delete medium
  929. if (file_exists(LYCHEE_UPLOADS_MEDIUM . $photo->url)&&!unlink(LYCHEE_UPLOADS_MEDIUM . $photo->url)) {
  930. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/medium/');
  931. $error = true;
  932. }
  933. // Delete thumb
  934. if (file_exists(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)&&!unlink(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)) {
  935. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/thumb/');
  936. $error = true;
  937. }
  938. // Delete thumb@2x
  939. if (file_exists(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)&&!unlink(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)) {
  940. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete high-res photo in uploads/thumb/');
  941. $error = true;
  942. }
  943. }
  944. // Delete db entry
  945. $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photo->id));
  946. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  947. if ($result===false) $error = true;
  948. }
  949. // Call plugins
  950. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  951. if ($error===true) return false;
  952. return true;
  953. }
  954. }
  955. ?>