Photo.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295
  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. // Save to DB
  191. $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);
  192. $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);
  193. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  194. if ($result===false) {
  195. if ($returnOnError===true) return false;
  196. Response::error('Could not save photo in database!');
  197. }
  198. // Call plugins
  199. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  200. return $id;
  201. }
  202. /**
  203. * @return array|false Returns a subset of a photo when same photo exists or returns false on failure.
  204. */
  205. private function exists($checksum, $photoID = null) {
  206. // Exclude $photoID from select when $photoID is set
  207. 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));
  208. else $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, medium FROM ? WHERE checksum = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $checksum));
  209. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  210. if ($result===false) return false;
  211. if ($result->num_rows===1) {
  212. $result = $result->fetch_object();
  213. $return = array(
  214. 'photo_name' => $result->url,
  215. 'path' => LYCHEE_UPLOADS_BIG . $result->url,
  216. 'path_thumb' => $result->thumbUrl,
  217. 'medium' => $result->medium
  218. );
  219. return $return;
  220. }
  221. return false;
  222. }
  223. /**
  224. * @return boolean Returns true when successful.
  225. */
  226. private function createThumb($url, $filename, $type, $width, $height) {
  227. // Call plugins
  228. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  229. // Quality of thumbnails
  230. $thumbQuality = 90;
  231. // Size of the thumbnail
  232. $newWidth = 200;
  233. $newHeight = 200;
  234. $photoName = explode('.', $filename);
  235. $newUrl = LYCHEE_UPLOADS_THUMB . $photoName[0] . '.jpeg';
  236. $newUrl2x = LYCHEE_UPLOADS_THUMB . $photoName[0] . '@2x.jpeg';
  237. // Create thumbnails with Imagick
  238. if(Settings::hasImagick()) {
  239. // Read image
  240. $thumb = new Imagick();
  241. $thumb->readImage($url);
  242. $thumb->setImageCompressionQuality($thumbQuality);
  243. $thumb->setImageFormat('jpeg');
  244. // Copy image for 2nd thumb version
  245. $thumb2x = clone $thumb;
  246. // Create 1st version
  247. $thumb->cropThumbnailImage($newWidth, $newHeight);
  248. $thumb->writeImage($newUrl);
  249. $thumb->clear();
  250. $thumb->destroy();
  251. // Create 2nd version
  252. $thumb2x->cropThumbnailImage($newWidth*2, $newHeight*2);
  253. $thumb2x->writeImage($newUrl2x);
  254. $thumb2x->clear();
  255. $thumb2x->destroy();
  256. } else {
  257. // Create image
  258. $thumb = imagecreatetruecolor($newWidth, $newHeight);
  259. $thumb2x = imagecreatetruecolor($newWidth*2, $newHeight*2);
  260. // Set position
  261. if ($width<$height) {
  262. $newSize = $width;
  263. $startWidth = 0;
  264. $startHeight = $height/2 - $width/2;
  265. } else {
  266. $newSize = $height;
  267. $startWidth = $width/2 - $height/2;
  268. $startHeight = 0;
  269. }
  270. // Create new image
  271. switch($type) {
  272. case 'image/jpeg': $sourceImg = imagecreatefromjpeg($url); break;
  273. case 'image/png': $sourceImg = imagecreatefrompng($url); break;
  274. case 'image/gif': $sourceImg = imagecreatefromgif($url); break;
  275. default: Log::error(Database::get(), __METHOD__, __LINE__, 'Type of photo is not supported');
  276. return false;
  277. break;
  278. }
  279. // Create thumb
  280. fastImageCopyResampled($thumb, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth, $newHeight, $newSize, $newSize);
  281. imagejpeg($thumb, $newUrl, $thumbQuality);
  282. imagedestroy($thumb);
  283. // Create retina thumb
  284. fastImageCopyResampled($thumb2x, $sourceImg, 0, 0, $startWidth, $startHeight, $newWidth*2, $newHeight*2, $newSize, $newSize);
  285. imagejpeg($thumb2x, $newUrl2x, $thumbQuality);
  286. imagedestroy($thumb2x);
  287. // Free memory
  288. imagedestroy($sourceImg);
  289. }
  290. // Call plugins
  291. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  292. return true;
  293. }
  294. /**
  295. * Creates a smaller version of a photo when its size is bigger than a preset size.
  296. * Photo must be big enough and Imagick must be installed and activated.
  297. * @return boolean Returns true when successful.
  298. */
  299. private function createMedium($url, $filename, $width, $height) {
  300. // Excepts the following:
  301. // (string) $url = Path to the photo-file
  302. // (string) $filename = Name of the photo-file
  303. // (int) $width = Width of the photo
  304. // (int) $height = Height of the photo
  305. // Call plugins
  306. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  307. // Set to true when creation of medium-photo failed
  308. $error = false;
  309. // Size of the medium-photo
  310. // When changing these values,
  311. // also change the size detection in the front-end
  312. $newWidth = 1920;
  313. $newHeight = 1080;
  314. // Check permissions
  315. if (hasPermissions(LYCHEE_UPLOADS_MEDIUM)===false) {
  316. // Permissions are missing
  317. Log::notice(Database::get(), __METHOD__, __LINE__, 'Skipped creation of medium-photo, because uploads/medium/ is missing or not readable and writable.');
  318. $error = true;
  319. }
  320. // Is photo big enough?
  321. // Is Imagick installed and activated?
  322. if (($error===false)&&
  323. ($width>$newWidth||$height>$newHeight)&&
  324. (extension_loaded('imagick')&&Settings::get()['imagick']==='1')) {
  325. $newUrl = LYCHEE_UPLOADS_MEDIUM . $filename;
  326. // Read image
  327. $medium = new Imagick();
  328. $medium->readImage($url);
  329. // Adjust image
  330. $medium->scaleImage($newWidth, $newHeight, true);
  331. // Save image
  332. try { $medium->writeImage($newUrl); }
  333. catch (ImagickException $err) {
  334. Log::notice(Database::get(), __METHOD__, __LINE__, 'Could not save medium-photo (' . $err->getMessage() . ')');
  335. $error = true;
  336. }
  337. $medium->clear();
  338. $medium->destroy();
  339. } else {
  340. // Photo too small or
  341. // Medium is deactivated or
  342. // Imagick not installed
  343. $error = true;
  344. }
  345. // Call plugins
  346. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  347. if ($error===true) return false;
  348. return true;
  349. }
  350. /**
  351. * Rotates and flips a photo based on its EXIF orientation.
  352. * @return array|false Returns an array with the new orientation, width, height or false on failure.
  353. */
  354. public function adjustFile($path, array $info) {
  355. // Excepts the following:
  356. // (string) $path = Path to the photo-file
  357. // (array) $info = ['orientation', 'width', 'height']
  358. // Call plugins
  359. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  360. $swapSize = false;
  361. if (extension_loaded('imagick')&&Settings::get()['imagick']==='1') {
  362. $image = new Imagick();
  363. $image->readImage($path);
  364. $orientation = $image->getImageOrientation();
  365. // Check if the images needs to be adjusted at all
  366. if ($orientation!==Imagick::ORIENTATION_TOPLEFT) {
  367. switch ($orientation) {
  368. case Imagick::ORIENTATION_TOPLEFT:
  369. break;
  370. case Imagick::ORIENTATION_TOPRIGHT:
  371. $image->flopImage();
  372. break;
  373. case Imagick::ORIENTATION_BOTTOMRIGHT:
  374. $image->rotateImage(new ImagickPixel(), 180);
  375. break;
  376. case Imagick::ORIENTATION_BOTTOMLEFT:
  377. $image->flopImage();
  378. $image->rotateImage(new ImagickPixel(), 180);
  379. break;
  380. case Imagick::ORIENTATION_LEFTTOP:
  381. $image->flopImage();
  382. $image->rotateImage(new ImagickPixel(), -90);
  383. $swapSize = true;
  384. break;
  385. case Imagick::ORIENTATION_RIGHTTOP:
  386. $image->rotateImage(new ImagickPixel(), 90);
  387. $swapSize = true;
  388. break;
  389. case Imagick::ORIENTATION_RIGHTBOTTOM:
  390. $image->flopImage();
  391. $image->rotateImage(new ImagickPixel(), 90);
  392. $swapSize = true;
  393. break;
  394. case Imagick::ORIENTATION_LEFTBOTTOM:
  395. $image->rotateImage(new ImagickPixel(), -90);
  396. $swapSize = true;
  397. break;
  398. default:
  399. break;
  400. }
  401. $image->setImageOrientation(Imagick::ORIENTATION_TOPLEFT);
  402. $image->writeImage($path);
  403. }
  404. $image->clear();
  405. $image->destroy();
  406. } else {
  407. $newWidth = $info['width'];
  408. $newHeight = $info['height'];
  409. $sourceImg = imagecreatefromjpeg($path);
  410. switch ($info['orientation']) {
  411. case 2:
  412. // mirror
  413. // not yet implemented
  414. return false;
  415. break;
  416. case 3:
  417. $sourceImg = imagerotate($sourceImg, -180, 0);
  418. break;
  419. case 4:
  420. // rotate 180 and mirror
  421. // not yet implemented
  422. return false;
  423. break;
  424. case 5:
  425. // rotate 90 and mirror
  426. // not yet implemented
  427. return false;
  428. break;
  429. case 6:
  430. $sourceImg = imagerotate($sourceImg, -90, 0);
  431. $newWidth = $info['height'];
  432. $newHeight = $info['width'];
  433. $swapSize = true;
  434. break;
  435. case 7:
  436. // rotate -90 and mirror
  437. // not yet implemented
  438. return false;
  439. break;
  440. case 8:
  441. $sourceImg = imagerotate($sourceImg, 90, 0);
  442. $newWidth = $info['height'];
  443. $newHeight = $info['width'];
  444. $swapSize = true;
  445. break;
  446. default:
  447. return false;
  448. break;
  449. }
  450. // Recreate photo
  451. $newSourceImg = imagecreatetruecolor($newWidth, $newHeight);
  452. imagecopyresampled($newSourceImg, $sourceImg, 0, 0, 0, 0, $newWidth, $newHeight, $newWidth, $newHeight);
  453. imagejpeg($newSourceImg, $path, 100);
  454. // Free memory
  455. imagedestroy($sourceImg);
  456. imagedestroy($newSourceImg);
  457. }
  458. // Call plugins
  459. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  460. // SwapSize should be true when the image has been rotated
  461. // Return new dimensions in this case
  462. if ($swapSize===true) {
  463. $swapSize = $info['width'];
  464. $info['width'] = $info['height'];
  465. $info['height'] = $swapSize;
  466. }
  467. return $info;
  468. }
  469. /**
  470. * Rurns photo-attributes into a front-end friendly format. Note that some attributes remain unchanged.
  471. * @return array Returns photo-attributes in a normalized structure.
  472. */
  473. public static function prepareData(array $data) {
  474. // Excepts the following:
  475. // (array) $data = ['id', 'title', 'tags', 'public', 'star', 'album', 'thumbUrl', 'takestamp', 'url']
  476. // Init
  477. $photo = null;
  478. // Set unchanged attributes
  479. $photo['id'] = $data['id'];
  480. $photo['title'] = $data['title'];
  481. $photo['tags'] = $data['tags'];
  482. $photo['public'] = $data['public'];
  483. $photo['star'] = $data['star'];
  484. $photo['album'] = $data['album'];
  485. // Parse urls
  486. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $data['thumbUrl'];
  487. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $data['url'];
  488. // Use takestamp as sysdate when possible
  489. if (isset($data['takestamp'])&&$data['takestamp']!=='0') {
  490. // Use takestamp
  491. $photo['cameraDate'] = '1';
  492. $photo['sysdate'] = strftime('%d %B %Y', $data['takestamp']);
  493. } else {
  494. // Use sysstamp from the id
  495. $photo['cameraDate'] = '0';
  496. $photo['sysdate'] = strftime('%d %B %Y', substr($data['id'], 0, -4));
  497. }
  498. return $photo;
  499. }
  500. /**
  501. * @return array|false Returns an array with information about the photo or false on failure.
  502. */
  503. public function get($albumID) {
  504. // Excepts the following:
  505. // (string) $albumID = Album which is currently visible to the user
  506. // Check dependencies
  507. Validator::required(isset($this->photoIDs), __METHOD__);
  508. // Call plugins
  509. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  510. // Get photo
  511. $query = Database::prepare(Database::get(), "SELECT * FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  512. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  513. if ($photos===false) return false;
  514. // Get photo object
  515. $photo = $photos->fetch_assoc();
  516. // Photo not found?
  517. if ($photo===null) {
  518. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  519. return false;
  520. }
  521. // Parse photo
  522. $photo['sysdate'] = strftime('%d %b. %Y', substr($photo['id'], 0, -4));
  523. if (strlen($photo['takestamp'])>1) $photo['takedate'] = strftime('%d %b. %Y', $photo['takestamp']);
  524. // Parse medium
  525. if ($photo['medium']==='1') $photo['medium'] = LYCHEE_URL_UPLOADS_MEDIUM . $photo['url'];
  526. else $photo['medium'] = '';
  527. // Parse paths
  528. $photo['url'] = LYCHEE_URL_UPLOADS_BIG . $photo['url'];
  529. $photo['thumbUrl'] = LYCHEE_URL_UPLOADS_THUMB . $photo['thumbUrl'];
  530. if ($albumID!='false') {
  531. // Only show photo as public when parent album is public
  532. // Check if parent album is not 'Unsorted'
  533. if ($photo['album']!=='0') {
  534. // Get album
  535. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_ALBUMS, $photo['album']));
  536. $albums = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  537. if ($albums===false) return false;
  538. // Get album object
  539. $album = $albums->fetch_assoc();
  540. // Photo not found?
  541. if ($photo===null) {
  542. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified album');
  543. return false;
  544. }
  545. // Parse album
  546. $photo['public'] = ($album['public']==='1' ? '2' : $photo['public']);
  547. }
  548. $photo['original_album'] = $photo['album'];
  549. $photo['album'] = $albumID;
  550. }
  551. // Call plugins
  552. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  553. return $photo;
  554. }
  555. /**
  556. * Reads and parses information and metadata out of a photo.
  557. * @return array Returns an array of photo information and metadata.
  558. */
  559. public function getInfo($url) {
  560. // Functions returns information and metadata of a photo
  561. // Excepts the following:
  562. // (string) $url = Path to photo-file
  563. // Returns the following:
  564. // (array) $return
  565. // Call plugins
  566. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  567. $iptcArray = array();
  568. $info = getimagesize($url, $iptcArray);
  569. // General information
  570. $return['type'] = $info['mime'];
  571. $return['width'] = $info[0];
  572. $return['height'] = $info[1];
  573. $return['title'] = '';
  574. $return['description'] = '';
  575. $return['orientation'] = '';
  576. $return['iso'] = '';
  577. $return['aperture'] = '';
  578. $return['make'] = '';
  579. $return['model'] = '';
  580. $return['shutter'] = '';
  581. $return['focal'] = '';
  582. $return['takestamp'] = 0;
  583. $return['lens'] = '';
  584. $return['tags'] = '';
  585. $return['position'] = '';
  586. $return['latitude'] = '';
  587. $return['longitude'] = '';
  588. $return['altitude'] = '';
  589. // Size
  590. $size = filesize($url)/1024;
  591. if ($size>=1024) $return['size'] = round($size/1024, 1) . ' MB';
  592. else $return['size'] = round($size, 1) . ' KB';
  593. // IPTC Metadata
  594. // See https://www.iptc.org/std/IIM/4.2/specification/IIMV4.2.pdf for mapping
  595. if(isset($iptcArray['APP13'])) {
  596. $iptcInfo = iptcparse($iptcArray['APP13']);
  597. if (is_array($iptcInfo)) {
  598. // Title
  599. if (!empty($iptcInfo['2#105'][0])) $return['title'] = $iptcInfo['2#105'][0];
  600. else if (!empty($iptcInfo['2#005'][0])) $return['title'] = $iptcInfo['2#005'][0];
  601. // Description
  602. if (!empty($iptcInfo['2#120'][0])) $return['description'] = $iptcInfo['2#120'][0];
  603. // Tags
  604. if (!empty($iptcInfo['2#025'])) $return['tags'] = implode(',', $iptcInfo['2#025']);
  605. // Position
  606. $fields = array();
  607. if (!empty($iptcInfo['2#090'])) $fields[] = trim($iptcInfo['2#090'][0]);
  608. if (!empty($iptcInfo['2#092'])) $fields[] = trim($iptcInfo['2#092'][0]);
  609. if (!empty($iptcInfo['2#095'])) $fields[] = trim($iptcInfo['2#095'][0]);
  610. if (!empty($iptcInfo['2#101'])) $fields[] = trim($iptcInfo['2#101'][0]);
  611. if (!empty($fields)) $return['position'] = implode(', ', $fields);
  612. }
  613. }
  614. // Read EXIF
  615. if ($info['mime']=='image/jpeg') $exif = @exif_read_data($url, 'EXIF', false, false);
  616. else $exif = false;
  617. // EXIF Metadata
  618. if ($exif!==false) {
  619. // Orientation
  620. if (isset($exif['Orientation'])) $return['orientation'] = $exif['Orientation'];
  621. else if (isset($exif['IFD0']['Orientation'])) $return['orientation'] = $exif['IFD0']['Orientation'];
  622. // ISO
  623. if (!empty($exif['ISOSpeedRatings'])) $return['iso'] = $exif['ISOSpeedRatings'];
  624. // Aperture
  625. if (!empty($exif['COMPUTED']['ApertureFNumber'])) $return['aperture'] = $exif['COMPUTED']['ApertureFNumber'];
  626. // Make
  627. if (!empty($exif['Make'])) $return['make'] = trim($exif['Make']);
  628. // Model
  629. if (!empty($exif['Model'])) $return['model'] = trim($exif['Model']);
  630. // Exposure
  631. if (!empty($exif['ExposureTime'])) $return['shutter'] = $exif['ExposureTime'] . ' s';
  632. // Focal Length
  633. if (!empty($exif['FocalLength'])) {
  634. if (strpos($exif['FocalLength'], '/')!==false) {
  635. $temp = explode('/', $exif['FocalLength'], 2);
  636. $temp = $temp[0] / $temp[1];
  637. $temp = round($temp, 1);
  638. $return['focal'] = $temp . ' mm';
  639. } else {
  640. $return['focal'] = $exif['FocalLength'] . ' mm';
  641. }
  642. }
  643. // Takestamp
  644. if (!empty($exif['DateTimeOriginal'])) $return['takestamp'] = strtotime($exif['DateTimeOriginal']);
  645. // Lens field from Lightroom
  646. if (!empty($exif['UndefinedTag:0xA434'])) $return['lens'] = trim($exif['UndefinedTag:0xA434']);
  647. // Deal with GPS coordinates
  648. if (!empty($exif['GPSLatitude']) && !empty($exif['GPSLatitudeRef'])) $return['latitude'] = getGPSCoordinate($exif['GPSLatitude'], $exif['GPSLatitudeRef']);
  649. if (!empty($exif['GPSLongitude']) && !empty($exif['GPSLongitudeRef'])) $return['longitude'] = getGPSCoordinate($exif['GPSLongitude'], $exif['GPSLongitudeRef']);
  650. }
  651. // Call plugins
  652. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  653. return $return;
  654. }
  655. /**
  656. * Starts a download of a photo.
  657. * @return resource|boolean Sends a ZIP-file or returns false on failure.
  658. */
  659. public function getArchive() {
  660. // Check dependencies
  661. Validator::required(isset($this->photoIDs), __METHOD__);
  662. // Call plugins
  663. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  664. // Get photo
  665. $query = Database::prepare(Database::get(), "SELECT title, url FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  666. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  667. if ($photos===false) return false;
  668. // Get photo object
  669. $photo = $photos->fetch_object();
  670. // Photo not found?
  671. if ($photo===null) {
  672. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  673. return false;
  674. }
  675. // Get extension
  676. $extension = getExtension($photo->url, false);
  677. if (empty($extension)===true) {
  678. Log::error(Database::get(), __METHOD__, __LINE__, 'Invalid photo extension');
  679. return false;
  680. }
  681. // Illicit chars
  682. $badChars = array_merge(
  683. array_map('chr', range(0,31)),
  684. array("<", ">", ":", '"', "/", "\\", "|", "?", "*")
  685. );
  686. // Parse title
  687. if ($photo->title=='') $photo->title = 'Untitled';
  688. // Escape title
  689. $photo->title = str_replace($badChars, '', $photo->title);
  690. // Set headers
  691. header("Content-Type: application/octet-stream");
  692. header("Content-Disposition: attachment; filename=\"" . $photo->title . $extension . "\"");
  693. header("Content-Length: " . filesize(LYCHEE_UPLOADS_BIG . $photo->url));
  694. // Send file
  695. readfile(LYCHEE_UPLOADS_BIG . $photo->url);
  696. // Call plugins
  697. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  698. return true;
  699. }
  700. /**
  701. * Sets the title of a photo.
  702. * @return boolean Returns true when successful.
  703. */
  704. public function setTitle($title = 'Untitled') {
  705. // Check dependencies
  706. Validator::required(isset($this->photoIDs), __METHOD__);
  707. // Call plugins
  708. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  709. // Set title
  710. $query = Database::prepare(Database::get(), "UPDATE ? SET title = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $title, $this->photoIDs));
  711. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  712. // Call plugins
  713. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  714. if ($result===false) return false;
  715. return true;
  716. }
  717. /**
  718. * Sets the description of a photo.
  719. * @return boolean Returns true when successful.
  720. */
  721. public function setDescription($description) {
  722. // Check dependencies
  723. Validator::required(isset($this->photoIDs), __METHOD__);
  724. // Call plugins
  725. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  726. // Set description
  727. $query = Database::prepare(Database::get(), "UPDATE ? SET description = '?' WHERE id IN ('?')", array(LYCHEE_TABLE_PHOTOS, $description, $this->photoIDs));
  728. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  729. // Call plugins
  730. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  731. if ($result===false) return false;
  732. return true;
  733. }
  734. /**
  735. * Toggles the star property of a photo.
  736. * @return boolean Returns true when successful.
  737. */
  738. public function setStar() {
  739. // Check dependencies
  740. Validator::required(isset($this->photoIDs), __METHOD__);
  741. // Call plugins
  742. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  743. // Init vars
  744. $error = false;
  745. // Get photos
  746. $query = Database::prepare(Database::get(), "SELECT id, star FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  747. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  748. if ($photos===false) return false;
  749. // For each photo
  750. while ($photo = $photos->fetch_object()) {
  751. // Invert star
  752. $star = ($photo->star==0 ? 1 : 0);
  753. // Set star
  754. $query = Database::prepare(Database::get(), "UPDATE ? SET star = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $star, $photo->id));
  755. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  756. if ($result===false) $error = true;
  757. }
  758. // Call plugins
  759. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  760. if ($error===true) return false;
  761. return true;
  762. }
  763. /**
  764. * Checks if photo or parent album is public.
  765. * @return integer 0 = Photo private and parent album private
  766. * 1 = Album public, but password incorrect
  767. * 2 = Photo public or album public and password correct
  768. */
  769. public function getPublic($password) {
  770. // Check dependencies
  771. Validator::required(isset($this->photoIDs), __METHOD__);
  772. // Call plugins
  773. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  774. // Get photo
  775. $query = Database::prepare(Database::get(), "SELECT public, album FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  776. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  777. if ($photos===false) return 0;
  778. // Get photo object
  779. $photo = $photos->fetch_object();
  780. // Photo not found?
  781. if ($photo===null) {
  782. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  783. return false;
  784. }
  785. // Check if public
  786. if ($photo->public==='1') {
  787. // Photo public
  788. return 2;
  789. } else {
  790. // Check if album public
  791. $album = new Album($photo->album);
  792. $agP = $album->getPublic();
  793. $acP = $album->checkPassword($password);
  794. // Album public and password correct
  795. if ($agP===true&&$acP===true) return 2;
  796. // Album public, but password incorrect
  797. if ($agP===true&&$acP===false) return 1;
  798. }
  799. // Call plugins
  800. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  801. // Photo private
  802. return 0;
  803. }
  804. /**
  805. * Toggles the public property of a photo.
  806. * @return boolean Returns true when successful.
  807. */
  808. public function setPublic() {
  809. // Check dependencies
  810. Validator::required(isset($this->photoIDs), __METHOD__);
  811. // Call plugins
  812. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  813. // Get public
  814. $query = Database::prepare(Database::get(), "SELECT public FROM ? WHERE id = '?' LIMIT 1", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  815. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  816. if ($photos===false) return false;
  817. // Get photo object
  818. $photo = $photos->fetch_object();
  819. // Photo not found?
  820. if ($photo===null) {
  821. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not find specified photo');
  822. return false;
  823. }
  824. // Invert public
  825. $public = ($photo->public==0 ? 1 : 0);
  826. // Set public
  827. $query = Database::prepare(Database::get(), "UPDATE ? SET public = '?' WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $public, $this->photoIDs));
  828. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  829. // Call plugins
  830. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  831. if ($result===false) return false;
  832. return true;
  833. }
  834. /**
  835. * Sets the parent album of a photo.
  836. * @return boolean Returns true when successful.
  837. */
  838. function setAlbum($albumID) {
  839. // Check dependencies
  840. Validator::required(isset($this->photoIDs), __METHOD__);
  841. // Call plugins
  842. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  843. // Set album
  844. $query = Database::prepare(Database::get(), "UPDATE ? SET album = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $albumID, $this->photoIDs));
  845. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  846. // Call plugins
  847. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  848. if ($result===false) return false;
  849. return true;
  850. }
  851. /**
  852. * Sets the tags of a photo.
  853. * @return boolean Returns true when successful.
  854. */
  855. public function setTags($tags) {
  856. // Excepts the following:
  857. // (string) $tags = Comma separated list of tags with a maximum length of 1000 chars
  858. // Check dependencies
  859. Validator::required(isset($this->photoIDs), __METHOD__);
  860. // Call plugins
  861. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  862. // Parse tags
  863. $tags = preg_replace('/(\ ,\ )|(\ ,)|(,\ )|(,{1,}\ {0,})|(,$|^,)/', ',', $tags);
  864. $tags = preg_replace('/,$|^,|(\ ){0,}$/', '', $tags);
  865. // Set tags
  866. $query = Database::prepare(Database::get(), "UPDATE ? SET tags = '?' WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $tags, $this->photoIDs));
  867. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  868. // Call plugins
  869. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  870. if ($result===false) return false;
  871. return true;
  872. }
  873. /**
  874. * Duplicates a photo.
  875. * @return boolean Returns true when successful.
  876. */
  877. public function duplicate() {
  878. // Check dependencies
  879. Validator::required(isset($this->photoIDs), __METHOD__);
  880. // Call plugins
  881. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  882. // Init vars
  883. $error = false;
  884. // Get photos
  885. $query = Database::prepare(Database::get(), "SELECT id, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  886. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  887. if ($photos===false) return false;
  888. // For each photo
  889. while ($photo = $photos->fetch_object()) {
  890. // Generate id
  891. $id = generateID();
  892. // Duplicate entry
  893. $values = array(LYCHEE_TABLE_PHOTOS, $id, LYCHEE_TABLE_PHOTOS, $photo->id);
  894. $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);
  895. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  896. if ($result===false) $error = true;
  897. }
  898. if ($error===true) return false;
  899. return true;
  900. }
  901. /**
  902. * Deletes a photo with all its data and files.
  903. * @return boolean Returns true when successful.
  904. */
  905. public function delete() {
  906. // Check dependencies
  907. Validator::required(isset($this->photoIDs), __METHOD__);
  908. // Call plugins
  909. Plugins::get()->activate(__METHOD__, 0, func_get_args());
  910. // Init vars
  911. $error = false;
  912. // Get photos
  913. $query = Database::prepare(Database::get(), "SELECT id, url, thumbUrl, checksum FROM ? WHERE id IN (?)", array(LYCHEE_TABLE_PHOTOS, $this->photoIDs));
  914. $photos = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  915. if ($photos===false) return false;
  916. // For each photo
  917. while ($photo = $photos->fetch_object()) {
  918. // Check if other photos are referring to this images
  919. // If so, only delete the db entry
  920. if ($this->exists($photo->checksum, $photo->id)===false) {
  921. // Get retina thumb url
  922. $thumbUrl2x = explode(".", $photo->thumbUrl);
  923. $thumbUrl2x = $thumbUrl2x[0] . '@2x.' . $thumbUrl2x[1];
  924. // Delete big
  925. if (file_exists(LYCHEE_UPLOADS_BIG . $photo->url)&&!unlink(LYCHEE_UPLOADS_BIG . $photo->url)) {
  926. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/big/');
  927. $error = true;
  928. }
  929. // Delete medium
  930. if (file_exists(LYCHEE_UPLOADS_MEDIUM . $photo->url)&&!unlink(LYCHEE_UPLOADS_MEDIUM . $photo->url)) {
  931. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/medium/');
  932. $error = true;
  933. }
  934. // Delete thumb
  935. if (file_exists(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)&&!unlink(LYCHEE_UPLOADS_THUMB . $photo->thumbUrl)) {
  936. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete photo in uploads/thumb/');
  937. $error = true;
  938. }
  939. // Delete thumb@2x
  940. if (file_exists(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)&&!unlink(LYCHEE_UPLOADS_THUMB . $thumbUrl2x)) {
  941. Log::error(Database::get(), __METHOD__, __LINE__, 'Could not delete high-res photo in uploads/thumb/');
  942. $error = true;
  943. }
  944. }
  945. // Delete db entry
  946. $query = Database::prepare(Database::get(), "DELETE FROM ? WHERE id = '?'", array(LYCHEE_TABLE_PHOTOS, $photo->id));
  947. $result = Database::execute(Database::get(), $query, __METHOD__, __LINE__);
  948. if ($result===false) $error = true;
  949. }
  950. // Call plugins
  951. Plugins::get()->activate(__METHOD__, 1, func_get_args());
  952. if ($error===true) return false;
  953. return true;
  954. }
  955. }
  956. ?>