Photo.php 33 KB

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