Photo.php 37 KB

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