Photo.php 34 KB

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