Photo.php 34 KB

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