Photo.php 37 KB

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