Photo.php 34 KB

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