Photo.php 34 KB

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