Photo.php 34 KB

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