Photo.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311
  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. // not yet implemented
  424. return false;
  425. break;
  426. case 3:
  427. $sourceImg = imagerotate($sourceImg, -180, 0);
  428. break;
  429. case 4:
  430. // rotate 180 and mirror
  431. // not yet implemented
  432. return false;
  433. break;
  434. case 5:
  435. // rotate 90 and mirror
  436. // not yet implemented
  437. return false;
  438. break;
  439. case 6:
  440. $sourceImg = imagerotate($sourceImg, -90, 0);
  441. $newWidth = $info['height'];
  442. $newHeight = $info['width'];
  443. $swapSize = true;
  444. break;
  445. case 7:
  446. // rotate -90 and mirror
  447. // not yet implemented
  448. return false;
  449. break;
  450. case 8:
  451. $sourceImg = imagerotate($sourceImg, 90, 0);
  452. $newWidth = $info['height'];
  453. $newHeight = $info['width'];
  454. $swapSize = true;
  455. break;
  456. default:
  457. return false;
  458. break;
  459. }
  460. // Recreate photo
  461. // In this step the photos also loses its metadata :(
  462. $newSourceImg = imagecreatetruecolor($newWidth, $newHeight);
  463. imagecopyresampled($newSourceImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight);
  464. imagejpeg($newSourceImg, $path, 100);
  465. // Free memory
  466. imagedestroy($sourceImg);
  467. imagedestroy($newSourceImg);
  468. }
  469. // Call plugins
  470. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  471. // SwapSize should be true when the image has been rotated
  472. // Return new dimensions in this case
  473. if ($swapSize===true) {
  474. $swapSize = $info['width'];
  475. $info['width'] = $info['height'];
  476. $info['height'] = $swapSize;
  477. }
  478. return $info;
  479. }
  480. /**
  481. * Rurns photo-attributes into a front-end friendly format. Note that some attributes remain unchanged.
  482. * @return array Returns photo-attributes in a normalized structure.
  483. */
  484. public static function prepareData(array $data) {
  485. // Excepts the following:
  486. // (array) $data = ['id', 'title', 'tags', 'public', 'star', 'album', 'thumbUrl', 'takestamp', 'url', 'medium']
  487. // Init
  488. $photo = null;
  489. // Set unchanged attributes
  490. $photo['id'] = $data['id'];
  491. $photo['title'] = $data['title'];
  492. $photo['tags'] = $data['tags'];
  493. $photo['public'] = $data['public'];
  494. $photo['star'] = $data['star'];
  495. $photo['album'] = $data['album'];
  496. // Parse medium
  497. if ($data['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $data['url'];
  498. else $photo['medium'] = '';
  499. // Parse paths
  500. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $data['thumbUrl'];
  501. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $data['url'];
  502. // Use takestamp as sysdate when possible
  503. if (isset($data['takestamp'])&&$data['takestamp']!=='0') {
  504. // Use takestamp
  505. $photo['cameraDate'] = '1';
  506. $photo['sysdate'] = strftime('%d %B %Y', $data['takestamp']);
  507. } else {
  508. // Use sysstamp from the id
  509. $photo['cameraDate'] = '0';
  510. $photo['sysdate'] = strftime('%d %B %Y', substr($data['id'], 0, -4));
  511. }
  512. return $photo;
  513. }
  514. /**
  515. * @return array|false Returns an array with information about the photo or false on failure.
  516. */
  517. public function get($albumID) {
  518. // Excepts the following:
  519. // (string) $albumID = Album which is currently visible to the user
  520. // Check dependencies
  521. Validator::required(isset($this->photoIDs), __METHOD__);
  522. // Call plugins
  523. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  524. // Get photo
  525. $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  526. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  527. if ($photos===false) return false;
  528. // Get photo object
  529. $photo = $photos->fetch_assoc();
  530. // Photo not found?
  531. if ($photo===null) {
  532. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  533. return false;
  534. }
  535. // Parse photo
  536. $photo['sysdate'] = strftime('%d %b. %Y', substr($photo['id'], 0, -4));
  537. if (strlen($photo['takestamp'])>1) $photo['takedate'] = strftime('%d %b. %Y', $photo['takestamp']);
  538. // Parse medium
  539. if ($photo['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $photo['url'];
  540. else $photo['medium'] = '';
  541. // Parse paths
  542. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $photo['url'];
  543. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $photo['thumbUrl'];
  544. if ($albumID!='false') {
  545. // Only show photo as public when parent album is public
  546. // Check if parent album is not 'Unsorted'
  547. if ($photo['album']!=='0') {
  548. // Get album
  549. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $photo['album']));
  550. $albums = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  551. if ($albums===false) return false;
  552. // Get album object
  553. $album = $albums->fetch_assoc();
  554. // Photo not found?
  555. if ($photo===null) {
  556. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified album');
  557. return false;
  558. }
  559. // Parse album
  560. $photo['public'] = ($album['public']==='1' ? '2' : $photo['public']);
  561. }
  562. $photo['original_album'] = $photo['album'];
  563. $photo['album'] = $albumID;
  564. }
  565. // Call plugins
  566. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  567. return $photo;
  568. }
  569. /**
  570. * Reads and parses information and metadata out of a photo.
  571. * @return array Returns an array of photo information and metadata.
  572. */
  573. public function getInfo($url) {
  574. // Functions returns information and metadata of a photo
  575. // Excepts the following:
  576. // (string) $url = Path to photo-file
  577. // Returns the following:
  578. // (array) $return
  579. // Call plugins
  580. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  581. $iptcArray = array();
  582. $info = getimagesize($url, $iptcArray);
  583. // General information
  584. $return['type'] = $info['mime'];
  585. $return['width'] = $info[0];
  586. $return['height'] = $info[1];
  587. $return['title'] = '';
  588. $return['description'] = '';
  589. $return['orientation'] = '';
  590. $return['iso'] = '';
  591. $return['aperture'] = '';
  592. $return['make'] = '';
  593. $return['model'] = '';
  594. $return['shutter'] = '';
  595. $return['focal'] = '';
  596. $return['takestamp'] = 0;
  597. $return['lens'] = '';
  598. $return['tags'] = '';
  599. $return['position'] = '';
  600. $return['latitude'] = '';
  601. $return['longitude'] = '';
  602. $return['altitude'] = '';
  603. // Size
  604. $size = filesize($url)/1024;
  605. if ($size>=1024) $return['size'] = round($size/1024, 1) . ' MB';
  606. else $return['size'] = round($size, 1) . ' KB';
  607. // IPTC Metadata
  608. // See https://www.iptc.org/std/IIM/4.2/specification/IIMV4.2.pdf for mapping
  609. if(isset($iptcArray['APP13'])) {
  610. $iptcInfo = iptcparse($iptcArray['APP13']);
  611. if (is_array($iptcInfo)) {
  612. // Title
  613. if (!empty($iptcInfo['2#105'][0])) $return['title'] = $iptcInfo['2#105'][0];
  614. else if (!empty($iptcInfo['2#005'][0])) $return['title'] = $iptcInfo['2#005'][0];
  615. // Description
  616. if (!empty($iptcInfo['2#120'][0])) $return['description'] = $iptcInfo['2#120'][0];
  617. // Tags
  618. if (!empty($iptcInfo['2#025'])) $return['tags'] = implode(',', $iptcInfo['2#025']);
  619. // Position
  620. $fields = array();
  621. if (!empty($iptcInfo['2#090'])) $fields[] = trim($iptcInfo['2#090'][0]);
  622. if (!empty($iptcInfo['2#092'])) $fields[] = trim($iptcInfo['2#092'][0]);
  623. if (!empty($iptcInfo['2#095'])) $fields[] = trim($iptcInfo['2#095'][0]);
  624. if (!empty($iptcInfo['2#101'])) $fields[] = trim($iptcInfo['2#101'][0]);
  625. if (!empty($fields)) $return['position'] = implode(', ', $fields);
  626. }
  627. }
  628. // Read EXIF
  629. if ($info['mime']=='image/jpeg') $exif = @exif_read_data($url, 'EXIF', false, false);
  630. else $exif = false;
  631. // EXIF Metadata
  632. if ($exif!==false) {
  633. // Orientation
  634. if (isset($exif['Orientation'])) $return['orientation'] = $exif['Orientation'];
  635. else if (isset($exif['IFD0']['Orientation'])) $return['orientation'] = $exif['IFD0']['Orientation'];
  636. // ISO
  637. if (!empty($exif['ISOSpeedRatings'])) $return['iso'] = $exif['ISOSpeedRatings'];
  638. // Aperture
  639. if (!empty($exif['COMPUTED']['ApertureFNumber'])) $return['aperture'] = $exif['COMPUTED']['ApertureFNumber'];
  640. // Make
  641. if (!empty($exif['Make'])) $return['make'] = trim($exif['Make']);
  642. // Model
  643. if (!empty($exif['Model'])) $return['model'] = trim($exif['Model']);
  644. // Exposure
  645. if (!empty($exif['ExposureTime'])) $return['shutter'] = $exif['ExposureTime'] . ' s';
  646. // Focal Length
  647. if (!empty($exif['FocalLength'])) {
  648. if (strpos($exif['FocalLength'], '/')!==false) {
  649. $temp = explode('/', $exif['FocalLength'], 2);
  650. $temp = $temp[0] / $temp[1];
  651. $temp = round($temp, 1);
  652. $return['focal'] = $temp . ' mm';
  653. } else {
  654. $return['focal'] = $exif['FocalLength'] . ' mm';
  655. }
  656. }
  657. // Takestamp
  658. if (!empty($exif['DateTimeOriginal'])) $return['takestamp'] = strtotime($exif['DateTimeOriginal']);
  659. // Lens field from Lightroom
  660. if (!empty($exif['UndefinedTag:0xA434'])) $return['lens'] = trim($exif['UndefinedTag:0xA434']);
  661. // Deal with GPS coordinates
  662. if (!empty($exif['GPSLatitude']) && !empty($exif['GPSLatitudeRef'])) $return['latitude'] = getGPSCoordinate($exif['GPSLatitude'], $exif['GPSLatitudeRef']);
  663. if (!empty($exif['GPSLongitude']) && !empty($exif['GPSLongitudeRef'])) $return['longitude'] = getGPSCoordinate($exif['GPSLongitude'], $exif['GPSLongitudeRef']);
  664. }
  665. // Call plugins
  666. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  667. return $return;
  668. }
  669. /**
  670. * Starts a download of a photo.
  671. * @return resource|boolean Sends a ZIP-file or returns false on failure.
  672. */
  673. public function getArchive() {
  674. // Check dependencies
  675. Validator::required(isset($this->photoIDs), __METHOD__);
  676. // Call plugins
  677. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  678. // Get photo
  679. $query = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  680. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  681. if ($photos===false) return false;
  682. // Get photo object
  683. $photo = $photos->fetch_object();
  684. // Photo not found?
  685. if ($photo===null) {
  686. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  687. return false;
  688. }
  689. // Get extension
  690. $extension = getExtension($photo->url, false);
  691. if (empty($extension)===true) {
  692. Log::error(Database::get(), __METHOD__, __LINE__, 'Invalid photo extension');
  693. return false;
  694. }
  695. // Illicit chars
  696. $badChars = array_merge(
  697. array_map('chr', range(0,31)),
  698. array("<", ">", ":", '"', "/", "\\", "|", "?", "*")
  699. );
  700. // Parse title
  701. if ($photo->title=='') $photo->title = 'Untitled';
  702. // Escape title
  703. $photo->title = str_replace($badChars, '', $photo->title);
  704. // Set headers
  705. header("Content-Type: application/octet-stream");
  706. header("Content-Disposition: attachment; filename=\"" . $photo->title . $extension . "\"");
  707. header("Content-Length: " . filesize(LYCHEE_UPLOADS_BIG . $photo->url));
  708. // Send file
  709. readfile(LYCHEE_UPLOADS_BIG . $photo->url);
  710. // Call plugins
  711. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  712. return true;
  713. }
  714. /**
  715. * Sets the title of a photo.
  716. * @return boolean Returns true when successful.
  717. */
  718. public function setTitle($title = 'Untitled') {
  719. // Check dependencies
  720. Validator::required(isset($this->photoIDs), __METHOD__);
  721. // Call plugins
  722. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  723. // Set title
  724. $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $title, $this->photoIDs));
  725. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  726. // Call plugins
  727. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  728. if ($result===false) return false;
  729. return true;
  730. }
  731. /**
  732. * Sets the description of a photo.
  733. * @return boolean Returns true when successful.
  734. */
  735. public function setDescription($description) {
  736. // Check dependencies
  737. Validator::required(isset($this->photoIDs), __METHOD__);
  738. // Call plugins
  739. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  740. // Set description
  741. $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN ('?')", array(LYCHEE_TABLE_PHOTOS, $description, $this->photoIDs));
  742. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  743. // Call plugins
  744. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  745. if ($result===false) return false;
  746. return true;
  747. }
  748. /**
  749. * Toggles the star property of a photo.
  750. * @return boolean Returns true when successful.
  751. */
  752. public function setStar() {
  753. // Check dependencies
  754. Validator::required(isset($this->photoIDs), __METHOD__);
  755. // Call plugins
  756. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  757. // Init vars
  758. $error = false;
  759. // Get photos
  760. $query = Database::prepare(Database::get(), "SELECT id, star FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  761. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  762. if ($photos===false) return false;
  763. // For each photo
  764. while ($photo = $photos->fetch_object()) {
  765. // Invert star
  766. $star = ($photo->star==0 ? 1 : 0);
  767. // Set star
  768. $query = Database::prepare(Database::get(), "UPDATE ? SET star = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $star, $photo->id));
  769. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  770. if ($result===false) $error = true;
  771. }
  772. // Call plugins
  773. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  774. if ($error===true) return false;
  775. return true;
  776. }
  777. /**
  778. * Checks if photo or parent album is public.
  779. * @return integer 0 = Photo private and parent album private
  780. * 1 = Album public, but password incorrect
  781. * 2 = Photo public or album public and password correct
  782. */
  783. public function getPublic($password) {
  784. // Check dependencies
  785. Validator::required(isset($this->photoIDs), __METHOD__);
  786. // Call plugins
  787. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  788. // Get photo
  789. $query = Database::prepare(Database::get(), "SELECT public, album 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 0;
  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. // Check if public
  800. if ($photo->public==='1') {
  801. // Photo public
  802. return 2;
  803. } else {
  804. // Check if album public
  805. $album = new Album($photo->album);
  806. $agP = $album->getPublic();
  807. $acP = $album->checkPassword($password);
  808. // Album public and password correct
  809. if ($agP===true&&$acP===true) return 2;
  810. // Album public, but password incorrect
  811. if ($agP===true&&$acP===false) return 1;
  812. }
  813. // Call plugins
  814. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  815. // Photo private
  816. return 0;
  817. }
  818. /**
  819. * Toggles the public property of a photo.
  820. * @return boolean Returns true when successful.
  821. */
  822. public function setPublic() {
  823. // Check dependencies
  824. Validator::required(isset($this->photoIDs), __METHOD__);
  825. // Call plugins
  826. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  827. // Get public
  828. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  829. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  830. if ($photos===false) return false;
  831. // Get photo object
  832. $photo = $photos->fetch_object();
  833. // Photo not found?
  834. if ($photo===null) {
  835. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  836. return false;
  837. }
  838. // Invert public
  839. $public = ($photo->public==0 ? 1 : 0);
  840. // Set public
  841. $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $public, $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. * Sets the parent album of a photo.
  850. * @return boolean Returns true when successful.
  851. */
  852. function setAlbum($albumID) {
  853. // Check dependencies
  854. Validator::required(isset($this->photoIDs), __METHOD__);
  855. // Call plugins
  856. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  857. // Set album
  858. $query = Database::prepare(Database::get(), "UPDATE ? SET album = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->photoIDs));
  859. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  860. // Call plugins
  861. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  862. if ($result===false) return false;
  863. return true;
  864. }
  865. /**
  866. * Sets the tags of a photo.
  867. * @return boolean Returns true when successful.
  868. */
  869. public function setTags($tags) {
  870. // Excepts the following:
  871. // (string) $tags = Comma separated list of tags with a maximum length of 1000 chars
  872. // Check dependencies
  873. Validator::required(isset($this->photoIDs), __METHOD__);
  874. // Call plugins
  875. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  876. // Parse tags
  877. $tags = preg_replace('/(\ ,\ )|(\ ,)|(,\ )|(,{1,}\ {0,})|(,$|^,)/', ',', $tags);
  878. $tags = preg_replace('/,$|^,|(\ ){0,}$/', '', $tags);
  879. // Set tags
  880. $query = Database::prepare(Database::get(), "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs));
  881. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  882. // Call plugins
  883. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  884. if ($result===false) return false;
  885. return true;
  886. }
  887. /**
  888. * Duplicates a photo.
  889. * @return boolean Returns true when successful.
  890. */
  891. public function duplicate() {
  892. // Check dependencies
  893. Validator::required(isset($this->photoIDs), __METHOD__);
  894. // Call plugins
  895. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  896. // Init vars
  897. $error = false;
  898. // Get photos
  899. $query = Database::prepare(Database::get(), "SELECT id, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  900. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  901. if ($photos===false) return false;
  902. // For each photo
  903. while ($photo = $photos->fetch_object()) {
  904. // Generate id
  905. $id = generateID();
  906. // Duplicate entry
  907. $values = array(LYCHEE_TABLE_PHOTOS, $id, LYCHEE_TABLE_PHOTOS, $photo->id);
  908. $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);
  909. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  910. if ($result===false) $error = true;
  911. }
  912. if ($error===true) return false;
  913. return true;
  914. }
  915. /**
  916. * Deletes a photo with all its data and files.
  917. * @return boolean Returns true when successful.
  918. */
  919. public function delete() {
  920. // Check dependencies
  921. Validator::required(isset($this->photoIDs), __METHOD__);
  922. // Call plugins
  923. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  924. // Init vars
  925. $error = false;
  926. // Get photos
  927. $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  928. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  929. if ($photos===false) return false;
  930. // For each photo
  931. while ($photo = $photos->fetch_object()) {
  932. // Check if other photos are referring to this images
  933. // If so, only delete the db entry
  934. if ($this->exists($photo->checksum, $photo->id)===false) {
  935. // Get retina thumb url
  936. $thumbUrl2x = explode(".", $photo->thumbUrl);
  937. $thumbUrl2x = $thumbUrl2x[0] . '@2x.' . $thumbUrl2x[1];
  938. // Delete big
  939. if (file_exists(LYCHEE_UPLOADS_BIG . $photo->url)&&!unlink(LYCHEE_UPLOADS_BIG . $photo->url)) {
  940. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/big/');
  941. $error = true;
  942. }
  943. // Delete medium
  944. if (file_exists(LYCHEE_UPLOADS_MEDIUM . $photo->url)&&!unlink(LYCHEE_UPLOADS_MEDIUM . $photo->url)) {
  945. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/medium/');
  946. $error = true;
  947. }
  948. // Delete thumb
  949. if (file_exists(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)&&!unlink(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)) {
  950. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/thumb/');
  951. $error = true;
  952. }
  953. // Delete thumb@2x
  954. if (file_exists(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)&&!unlink(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)) {
  955. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete high-res photo in uploads/thumb/');
  956. $error = true;
  957. }
  958. }
  959. // Delete db entry
  960. $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photo->id));
  961. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  962. if ($result===false) $error = true;
  963. }
  964. // Call plugins
  965. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  966. if ($error===true) return false;
  967. return true;
  968. }
  969. }
  970. ?>