Photo.php 35 KB

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