Photo.php 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. <?php
  2. namespace Lychee\Modules;
  3. use ZipArchive;
  4. use Imagick;
  5. final class Photo {
  6. private $photoIDs = null;
  7. public static $validTypes = array(
  8. IMAGETYPE_JPEG,
  9. IMAGETYPE_GIF,
  10. IMAGETYPE_PNG
  11. );
  12. public static $validExtensions = array(
  13. '.jpg',
  14. '.jpeg',
  15. '.png',
  16. '.gif'
  17. );
  18. /**
  19. * @return boolean Returns true when successful.
  20. */
  21. public function __construct($photoIDs) {
  22. // Init vars
  23. $this->photoIDs = $photoIDs;
  24. return true;
  25. }
  26. /**
  27. * Creats new photo(s).
  28. * Exits on error.
  29. * Use $returnOnError if you want to handle errors by your own.
  30. * @return boolean Returns true when successful.
  31. */
  32. public function add(array $files, $albumID = 0, $returnOnError = false) {
  33. // Check permissions
  34. if (hasPermissions(LYCHEE_UPLOADS)===false||
  35. hasPermissions(LYCHEE_UPLOADS_BIG)===false||
  36. hasPermissions(LYCHEE_UPLOADS_THUMB)===false) {
  37. Log::error(Database::get(), __METHOD__, __LINE__, 'An upload-folder is missing or not readable and writable');
  38. if ($returnOnError===true) return false;
  39. Response::error('An upload-folder is missing or not readable and writable!');
  40. }
  41. // Call plugins
  42. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  43. switch($albumID) {
  44. case 's':
  45. // s for public (share)
  46. $public = 1;
  47. $star = 0;
  48. $albumID = 0;
  49. break;
  50. case 'f':
  51. // f for starred (fav)
  52. $star = 1;
  53. $public = 0;
  54. $albumID = 0;
  55. break;
  56. case 'r':
  57. // r for recent
  58. $public = 0;
  59. $star = 0;
  60. $albumID = 0;
  61. break;
  62. default:
  63. $star = 0;
  64. $public = 0;
  65. break;
  66. }
  67. // Only process the first photo in the array
  68. $file = $files[0];
  69. // Check if file exceeds the upload_max_filesize directive
  70. if ($file['error']===UPLOAD_ERR_INI_SIZE) {
  71. Log::error(Database::get(), __METHOD__, __LINE__, 'The uploaded file exceeds the upload_max_filesize directive in php.ini');
  72. if ($returnOnError===true) return false;
  73. Response::error('The uploaded file exceeds the upload_max_filesize directive in php.ini!');
  74. }
  75. // Check if file was only partially uploaded
  76. if ($file['error']===UPLOAD_ERR_PARTIAL) {
  77. Log::error(Database::get(), __METHOD__, __LINE__, 'The uploaded file was only partially uploaded');
  78. if ($returnOnError===true) return false;
  79. Response::error('The uploaded file was only partially uploaded!');
  80. }
  81. // Check if writing file to disk failed
  82. if ($file['error']===UPLOAD_ERR_CANT_WRITE) {
  83. Log::error(Database::get(), __METHOD__, __LINE__, 'Failed to write photo to disk');
  84. if ($returnOnError===true) return false;
  85. Response::error('Failed to write photo to disk!');
  86. }
  87. // Check if a extension stopped the file upload
  88. if ($file['error']===UPLOAD_ERR_EXTENSION) {
  89. Log::error(Database::get(), __METHOD__, __LINE__, 'A PHP extension stopped the file upload');
  90. if ($returnOnError===true) return false;
  91. Response::error('A PHP extension stopped the file upload!');
  92. }
  93. // Check if the upload was successful
  94. if ($file['error']!==UPLOAD_ERR_OK) {
  95. Log::error(Database::get(), __METHOD__, __LINE__, 'Upload contains an error (' . $file['error'] . ')');
  96. if ($returnOnError===true) return false;
  97. Response::error('Upload failed!');
  98. }
  99. // Verify extension
  100. $extension = getExtension($file['name']);
  101. if (!in_array(strtolower($extension), self::$validExtensions, true)) {
  102. Log::error(Database::get(), __METHOD__, __LINE__, 'Photo format not supported');
  103. if ($returnOnError===true) return false;
  104. Response::error('Photo format not supported!');
  105. }
  106. // Verify image
  107. $type = @exif_imagetype($file['tmp_name']);
  108. if (!in_array($type, self::$validTypes, true)) {
  109. Log::error(Database::get(), __METHOD__, __LINE__, 'Photo type not supported');
  110. if ($returnOnError===true) return false;
  111. Response::error('Photo type not supported!');
  112. }
  113. // Generate id
  114. $id = generateID();
  115. // Set paths
  116. $tmp_name = $file['tmp_name'];
  117. $photo_name = md5($id) . $extension;
  118. $path = LYCHEE_UPLOADS_BIG . $photo_name;
  119. // Calculate checksum
  120. $checksum = sha1_file($tmp_name);
  121. if ($checksum===false) {
  122. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not calculate checksum for photo');
  123. if ($returnOnError===true) return false;
  124. Response::error('Could not calculate checksum for photo!');
  125. }
  126. // Check if image exists based on checksum
  127. if ($checksum===false) {
  128. $checksum = '';
  129. $exists = false;
  130. } else {
  131. $exists = $this->exists($checksum);
  132. if ($exists!==false) {
  133. $photo_name = $exists['photo_name'];
  134. $path = $exists['path'];
  135. $path_thumb = $exists['path_thumb'];
  136. $medium = ($exists['medium']==='1' ? 1 : 0);
  137. $exists = true;
  138. }
  139. }
  140. if ($exists===false) {
  141. // Import if not uploaded via web
  142. if (!is_uploaded_file($tmp_name)) {
  143. if (!@copy($tmp_name, $path)) {
  144. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not copy photo to uploads');
  145. if ($returnOnError===true) return false;
  146. Response::error('Could not copy photo to uploads!');
  147. } else @unlink($tmp_name);
  148. } else {
  149. if (!@move_uploaded_file($tmp_name, $path)) {
  150. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not move photo to uploads');
  151. if ($returnOnError===true) return false;
  152. Response::error('Could not move photo to uploads!');
  153. }
  154. }
  155. } else {
  156. // Photo already exists
  157. // Check if the user wants to skip duplicates
  158. if (Settings::get()['skipDuplicates']==='1') {
  159. Log::notice(Database::get(), __METHOD__, __LINE__, 'Skipped upload of existing photo because skipDuplicates is activated');
  160. if ($returnOnError===true) return false;
  161. Response::warning('This photo has been skipped because it\'s already in your library.');
  162. }
  163. }
  164. // Read infos
  165. $info = $this->getInfo($path);
  166. // Use title of file if IPTC title missing
  167. if ($info['title']==='') $info['title'] = substr(basename($file['name'], $extension), 0, 30);
  168. if ($exists===false) {
  169. // Set orientation based on EXIF data
  170. if ($file['type']==='image/jpeg'&&isset($info['orientation'])&&$info['orientation']!=='') {
  171. $adjustFile = $this->adjustFile($path, $info);
  172. if ($adjustFile!==false) $info = $adjustFile;
  173. else Log::notice(Database::get(), __METHOD__, __LINE__, 'Skipped adjustment of photo (' . $info['title'] . ')');
  174. }
  175. // Set original date
  176. if ($info['takestamp']!==''&&$info['takestamp']!==0) @touch($path, $info['takestamp']);
  177. // Create Thumb
  178. if (!$this->createThumb($path, $photo_name, $info['type'], $info['width'], $info['height'])) {
  179. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not create thumbnail for photo');
  180. if ($returnOnError===true) return false;
  181. Response::error('Could not create thumbnail for photo!');
  182. }
  183. // Create Medium
  184. if ($this->createMedium($path, $photo_name, $info['width'], $info['height'])) $medium = 1;
  185. else $medium = 0;
  186. // Set thumb url
  187. $path_thumb = md5($id) . '.jpeg';
  188. }
  189. // Save to DB
  190. $values = array(LYCHEE_TABLE_PHOTOS, $id, $info['title'], $photo_name, $info['description'], '', $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 true;
  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. $thumbQuality = 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(extension_loaded('imagick')&&Settings::get()['imagick']==='1') {
  238. // Read image
  239. $thumb = new Imagick();
  240. $thumb->readImage($url);
  241. $thumb->setImageCompressionQuality($thumbQuality);
  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. switch ($info['orientation']) {
  362. case 3:
  363. $rotateImage = 180;
  364. break;
  365. case 6:
  366. $rotateImage = 90;
  367. $swapSize = true;
  368. break;
  369. case 8:
  370. $rotateImage = 270;
  371. $swapSize = true;
  372. break;
  373. default:
  374. return false;
  375. break;
  376. }
  377. if ($rotateImage!==0) {
  378. $image = new Imagick();
  379. $image->readImage($path);
  380. $image->rotateImage(new ImagickPixel(), $rotateImage);
  381. $image->setImageOrientation(1);
  382. $image->writeImage($path);
  383. $image->clear();
  384. $image->destroy();
  385. }
  386. } else {
  387. $newWidth = $info['width'];
  388. $newHeight = $info['height'];
  389. $sourceImg = imagecreatefromjpeg($path);
  390. switch ($info['orientation']) {
  391. case 2:
  392. // mirror
  393. // not yet implemented
  394. return false;
  395. break;
  396. case 3:
  397. $sourceImg = imagerotate($sourceImg, -180, 0);
  398. break;
  399. case 4:
  400. // rotate 180 and mirror
  401. // not yet implemented
  402. return false;
  403. break;
  404. case 5:
  405. // rotate 90 and mirror
  406. // not yet implemented
  407. return false;
  408. break;
  409. case 6:
  410. $sourceImg = imagerotate($sourceImg, -90, 0);
  411. $newWidth = $info['height'];
  412. $newHeight = $info['width'];
  413. $swapSize = true;
  414. break;
  415. case 7:
  416. // rotate -90 and mirror
  417. // not yet implemented
  418. return false;
  419. break;
  420. case 8:
  421. $sourceImg = imagerotate($sourceImg, 90, 0);
  422. $newWidth = $info['height'];
  423. $newHeight = $info['width'];
  424. $swapSize = true;
  425. break;
  426. default:
  427. return false;
  428. break;
  429. }
  430. // Recreate photo
  431. $newSourceImg = imagecreatetruecolor($newWidth, $newHeight);
  432. imagecopyresampled($newSourceImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight);
  433. imagejpeg($newSourceImg, $path, 100);
  434. // Free memory
  435. imagedestroy($sourceImg);
  436. imagedestroy($newSourceImg);
  437. }
  438. // Call plugins
  439. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  440. // SwapSize should be true when the image has been rotated
  441. // Return new dimensions in this case
  442. if ($swapSize===true) {
  443. $swapSize = $info['width'];
  444. $info['width'] = $info['height'];
  445. $info['height'] = $swapSize;
  446. }
  447. return $info;
  448. }
  449. /**
  450. * Rurns photo-attributes into a front-end friendly format. Note that some attributes remain unchanged.
  451. * @return array Returns photo-attributes in a normalized structure.
  452. */
  453. public static function prepareData(array $data) {
  454. // Excepts the following:
  455. // (array) $data = ['id', 'title', 'tags', 'public', 'star', 'album', 'thumbUrl', 'takestamp', 'url']
  456. // Init
  457. $photo = null;
  458. // Set unchanged attributes
  459. $photo['id'] = $data['id'];
  460. $photo['title'] = $data['title'];
  461. $photo['tags'] = $data['tags'];
  462. $photo['public'] = $data['public'];
  463. $photo['star'] = $data['star'];
  464. $photo['album'] = $data['album'];
  465. // Parse urls
  466. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $data['thumbUrl'];
  467. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $data['url'];
  468. // Use takestamp as sysdate when possible
  469. if (isset($data['takestamp'])&&$data['takestamp']!=='0') {
  470. // Use takestamp
  471. $photo['cameraDate'] = '1';
  472. $photo['sysdate'] = date('d F Y', $data['takestamp']);
  473. } else {
  474. // Use sysstamp from the id
  475. $photo['cameraDate'] = '0';
  476. $photo['sysdate'] = date('d F Y', substr($data['id'], 0, -4));
  477. }
  478. return $photo;
  479. }
  480. /**
  481. * @return array|false Returns an array with information about the photo or false on failure.
  482. */
  483. public function get($albumID) {
  484. // Excepts the following:
  485. // (string) $albumID = Album which is currently visible to the user
  486. // Check dependencies
  487. Validator::required(isset($this->photoIDs), __METHOD__);
  488. // Call plugins
  489. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  490. // Get photo
  491. $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  492. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  493. if ($photos===false) return false;
  494. // Get photo object
  495. $photo = $photos->fetch_assoc();
  496. // Photo not found?
  497. if ($photo===null) {
  498. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  499. return false;
  500. }
  501. // Parse photo
  502. $photo['sysdate'] = date('d M. Y', substr($photo['id'], 0, -4));
  503. if (strlen($photo['takestamp'])>1) $photo['takedate'] = date('d M. Y', $photo['takestamp']);
  504. // Parse medium
  505. if ($photo['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $photo['url'];
  506. else $photo['medium'] = '';
  507. // Parse paths
  508. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $photo['url'];
  509. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $photo['thumbUrl'];
  510. if ($albumID!='false') {
  511. // Only show photo as public when parent album is public
  512. // Check if parent album is not 'Unsorted'
  513. if ($photo['album']!=='0') {
  514. // Get album
  515. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $photo['album']));
  516. $albums = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  517. if ($albums===false) return false;
  518. // Get album object
  519. $album = $albums->fetch_assoc();
  520. // Photo not found?
  521. if ($photo===null) {
  522. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified album');
  523. return false;
  524. }
  525. // Parse album
  526. $photo['public'] = ($album['public']==='1' ? '2' : $photo['public']);
  527. }
  528. $photo['original_album'] = $photo['album'];
  529. $photo['album'] = $albumID;
  530. }
  531. // Call plugins
  532. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  533. return $photo;
  534. }
  535. /**
  536. * Reads and parses information and metadata out of a photo.
  537. * @return array Returns an array of photo information and metadata.
  538. */
  539. public function getInfo($url) {
  540. // Functions returns information and metadata of a photo
  541. // Excepts the following:
  542. // (string) $url = Path to photo-file
  543. // Returns the following:
  544. // (array) $return
  545. // Call plugins
  546. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  547. $iptcArray = array();
  548. $info = getimagesize($url, $iptcArray);
  549. // General information
  550. $return['type'] = $info['mime'];
  551. $return['width'] = $info[0];
  552. $return['height'] = $info[1];
  553. // Size
  554. $size = filesize($url)/1024;
  555. if ($size>=1024) $return['size'] = round($size/1024, 1) . ' MB';
  556. else $return['size'] = round($size, 1) . ' KB';
  557. // IPTC Metadata Fallback
  558. $return['title'] = '';
  559. $return['description'] = '';
  560. // IPTC Metadata
  561. if(isset($iptcArray['APP13'])) {
  562. $iptcInfo = iptcparse($iptcArray['APP13']);
  563. if (is_array($iptcInfo)) {
  564. $temp = @$iptcInfo['2#105'][0];
  565. if (isset($temp)&&strlen($temp)>0) $return['title'] = $temp;
  566. $temp = @$iptcInfo['2#120'][0];
  567. if (isset($temp)&&strlen($temp)>0) $return['description'] = $temp;
  568. $temp = @$iptcInfo['2#005'][0];
  569. if (isset($temp)&&strlen($temp)>0&&$return['title']==='') $return['title'] = $temp;
  570. }
  571. }
  572. // EXIF Metadata Fallback
  573. $return['orientation'] = '';
  574. $return['iso'] = '';
  575. $return['aperture'] = '';
  576. $return['make'] = '';
  577. $return['model'] = '';
  578. $return['shutter'] = '';
  579. $return['focal'] = '';
  580. $return['takestamp'] = 0;
  581. // Read EXIF
  582. if ($info['mime']=='image/jpeg') $exif = @exif_read_data($url, 'EXIF', 0);
  583. else $exif = false;
  584. // EXIF Metadata
  585. if ($exif!==false) {
  586. if (isset($exif['Orientation'])) $return['orientation'] = $exif['Orientation'];
  587. else if (isset($exif['IFD0']['Orientation'])) $return['orientation'] = $exif['IFD0']['Orientation'];
  588. $temp = @$exif['ISOSpeedRatings'];
  589. if (isset($temp)) $return['iso'] = $temp;
  590. $temp = @$exif['COMPUTED']['ApertureFNumber'];
  591. if (isset($temp)) $return['aperture'] = $temp;
  592. $temp = @$exif['Make'];
  593. if (isset($temp)) $return['make'] = trim($temp);
  594. $temp = @$exif['Model'];
  595. if (isset($temp)) $return['model'] = trim($temp);
  596. $temp = @$exif['ExposureTime'];
  597. if (isset($temp)) $return['shutter'] = $exif['ExposureTime'] . ' s';
  598. $temp = @$exif['FocalLength'];
  599. if (isset($temp)) {
  600. if (strpos($temp, '/')!==FALSE) {
  601. $temp = explode('/', $temp, 2);
  602. $temp = $temp[0] / $temp[1];
  603. $temp = round($temp, 1);
  604. $return['focal'] = $temp . ' mm';
  605. }
  606. $return['focal'] = $temp . ' mm';
  607. }
  608. $temp = @$exif['DateTimeOriginal'];
  609. if (isset($temp)) $return['takestamp'] = strtotime($temp);
  610. }
  611. // Call plugins
  612. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  613. return $return;
  614. }
  615. /**
  616. * Starts a download of a photo.
  617. * @return resource|boolean Sends a ZIP-file or returns false on failure.
  618. */
  619. public function getArchive() {
  620. // Check dependencies
  621. Validator::required(isset($this->photoIDs), __METHOD__);
  622. // Call plugins
  623. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  624. // Get photo
  625. $query = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  626. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  627. if ($photos===false) return false;
  628. // Get photo object
  629. $photo = $photos->fetch_object();
  630. // Photo not found?
  631. if ($photo===null) {
  632. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  633. return false;
  634. }
  635. // Get extension
  636. $extension = getExtension($photo->url);
  637. if ($extension===false) {
  638. Log::error(Database::get(), __METHOD__, __LINE__, 'Invalid photo extension');
  639. return false;
  640. }
  641. // Illicit chars
  642. $badChars = array_merge(
  643. array_map('chr', range(0,31)),
  644. array("<", ">", ":", '"', "/", "\\", "|", "?", "*")
  645. );
  646. // Parse title
  647. if ($photo->title=='') $photo->title = 'Untitled';
  648. // Escape title
  649. $photo->title = str_replace($badChars, '', $photo->title);
  650. // Set headers
  651. header("Content-Type: application/octet-stream");
  652. header("Content-Disposition: attachment; filename=\"" . $photo->title . $extension . "\"");
  653. header("Content-Length: " . filesize(LYCHEE_UPLOADS_BIG . $photo->url));
  654. // Send file
  655. readfile(LYCHEE_UPLOADS_BIG . $photo->url);
  656. // Call plugins
  657. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  658. return true;
  659. }
  660. /**
  661. * Sets the title of a photo.
  662. * @return boolean Returns true when successful.
  663. */
  664. public function setTitle($title = 'Untitled') {
  665. // Check dependencies
  666. Validator::required(isset($this->photoIDs), __METHOD__);
  667. // Call plugins
  668. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  669. // Set title
  670. $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $title, $this->photoIDs));
  671. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  672. // Call plugins
  673. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  674. if ($result===false) return false;
  675. return true;
  676. }
  677. /**
  678. * Sets the description of a photo.
  679. * @return boolean Returns true when successful.
  680. */
  681. public function setDescription($description) {
  682. // Check dependencies
  683. Validator::required(isset($this->photoIDs), __METHOD__);
  684. // Call plugins
  685. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  686. // Set description
  687. $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN ('?')", array(LYCHEE_TABLE_PHOTOS, $description, $this->photoIDs));
  688. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  689. // Call plugins
  690. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  691. if ($result===false) return false;
  692. return true;
  693. }
  694. /**
  695. * Toggles the star property of a photo.
  696. * @return boolean Returns true when successful.
  697. */
  698. public function setStar() {
  699. // Check dependencies
  700. Validator::required(isset($this->photoIDs), __METHOD__);
  701. // Call plugins
  702. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  703. // Init vars
  704. $error = false;
  705. // Get photos
  706. $query = Database::prepare(Database::get(), "SELECT id, star FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  707. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  708. if ($photos===false) return false;
  709. // For each photo
  710. while ($photo = $photos->fetch_object()) {
  711. // Invert star
  712. $star = ($photo->star==0 ? 1 : 0);
  713. // Set star
  714. $query = Database::prepare(Database::get(), "UPDATE ? SET star = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $star, $photo->id));
  715. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  716. if ($result===false) $error = true;
  717. }
  718. // Call plugins
  719. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  720. if ($error===true) return false;
  721. return true;
  722. }
  723. /**
  724. * Checks if photo or parent album is public.
  725. * @return integer 0 = Photo private and parent album private
  726. * 1 = Album public, but password incorrect
  727. * 2 = Photo public or album public and password correct
  728. */
  729. public function getPublic($password) {
  730. // Check dependencies
  731. Validator::required(isset($this->photoIDs), __METHOD__);
  732. // Call plugins
  733. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  734. // Get photo
  735. $query = Database::prepare(Database::get(), "SELECT public, album FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  736. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  737. if ($photos===false) return 0;
  738. // Get photo object
  739. $photo = $photos->fetch_object();
  740. // Photo not found?
  741. if ($photo===null) {
  742. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  743. return false;
  744. }
  745. // Check if public
  746. if ($photo->public==='1') {
  747. // Photo public
  748. return 2;
  749. } else {
  750. // Check if album public
  751. $album = new Album($photo->album);
  752. $agP = $album->getPublic();
  753. $acP = $album->checkPassword($password);
  754. // Album public and password correct
  755. if ($agP===true&&$acP===true) return 2;
  756. // Album public, but password incorrect
  757. if ($agP===true&&$acP===false) return 1;
  758. }
  759. // Call plugins
  760. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  761. // Photo private
  762. return 0;
  763. }
  764. /**
  765. * Toggles the public property of a photo.
  766. * @return boolean Returns true when successful.
  767. */
  768. public function setPublic() {
  769. // Check dependencies
  770. Validator::required(isset($this->photoIDs), __METHOD__);
  771. // Call plugins
  772. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  773. // Get public
  774. $query = Database::prepare(Database::get(), "SELECT public 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 false;
  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. // Invert public
  785. $public = ($photo->public==0 ? 1 : 0);
  786. // Set public
  787. $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $public, $this->photoIDs));
  788. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  789. // Call plugins
  790. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  791. if ($result===false) return false;
  792. return true;
  793. }
  794. /**
  795. * Sets the parent album of a photo.
  796. * @return boolean Returns true when successful.
  797. */
  798. function setAlbum($albumID) {
  799. // Check dependencies
  800. Validator::required(isset($this->photoIDs), __METHOD__);
  801. // Call plugins
  802. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  803. // Set album
  804. $query = Database::prepare(Database::get(), "UPDATE ? SET album = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->photoIDs));
  805. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  806. // Call plugins
  807. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  808. if ($result===false) return false;
  809. return true;
  810. }
  811. /**
  812. * Sets the tags of a photo.
  813. * @return boolean Returns true when successful.
  814. */
  815. public function setTags($tags) {
  816. // Excepts the following:
  817. // (string) $tags = Comma separated list of tags with a maximum length of 1000 chars
  818. // Check dependencies
  819. Validator::required(isset($this->photoIDs), __METHOD__);
  820. // Call plugins
  821. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  822. // Parse tags
  823. $tags = preg_replace('/(\ ,\ )|(\ ,)|(,\ )|(,{1,}\ {0,})|(,$|^,)/', ',', $tags);
  824. $tags = preg_replace('/,$|^,|(\ ){0,}$/', '', $tags);
  825. // Set tags
  826. $query = Database::prepare(Database::get(), "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $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. * Duplicates a photo.
  835. * @return boolean Returns true when successful.
  836. */
  837. public function duplicate() {
  838. // Check dependencies
  839. Validator::required(isset($this->photoIDs), __METHOD__);
  840. // Call plugins
  841. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  842. // Init vars
  843. $error = false;
  844. // Get photos
  845. $query = Database::prepare(Database::get(), "SELECT id, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  846. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  847. if ($photos===false) return false;
  848. // For each photo
  849. while ($photo = $photos->fetch_object()) {
  850. // Generate id
  851. $id = generateID();
  852. // Duplicate entry
  853. $values = array(LYCHEE_TABLE_PHOTOS, $id, LYCHEE_TABLE_PHOTOS, $photo->id);
  854. $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);
  855. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  856. if ($result===false) $error = true;
  857. }
  858. if ($error===true) return false;
  859. return true;
  860. }
  861. /**
  862. * Deletes a photo with all its data and files.
  863. * @return boolean Returns true when successful.
  864. */
  865. public function delete() {
  866. // Check dependencies
  867. Validator::required(isset($this->photoIDs), __METHOD__);
  868. // Call plugins
  869. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  870. // Init vars
  871. $error = false;
  872. // Get photos
  873. $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  874. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  875. if ($photos===false) return false;
  876. // For each photo
  877. while ($photo = $photos->fetch_object()) {
  878. // Check if other photos are referring to this images
  879. // If so, only delete the db entry
  880. if ($this->exists($photo->checksum, $photo->id)===false) {
  881. // Get retina thumb url
  882. $thumbUrl2x = explode(".", $photo->thumbUrl);
  883. $thumbUrl2x = $thumbUrl2x[0] . '@2x.' . $thumbUrl2x[1];
  884. // Delete big
  885. if (file_exists(LYCHEE_UPLOADS_BIG . $photo->url)&&!unlink(LYCHEE_UPLOADS_BIG . $photo->url)) {
  886. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/big/');
  887. $error = true;
  888. }
  889. // Delete medium
  890. if (file_exists(LYCHEE_UPLOADS_MEDIUM . $photo->url)&&!unlink(LYCHEE_UPLOADS_MEDIUM . $photo->url)) {
  891. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/medium/');
  892. $error = true;
  893. }
  894. // Delete thumb
  895. if (file_exists(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)&&!unlink(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)) {
  896. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/thumb/');
  897. $error = true;
  898. }
  899. // Delete thumb@2x
  900. if (file_exists(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)&&!unlink(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)) {
  901. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete high-res photo in uploads/thumb/');
  902. $error = true;
  903. }
  904. }
  905. // Delete db entry
  906. $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photo->id));
  907. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  908. if ($result===false) $error = true;
  909. }
  910. // Call plugins
  911. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  912. if ($error===true) return false;
  913. return true;
  914. }
  915. }
  916. ?>