Photo.php 34 KB

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