TidypicsImage.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  1. <?php
  2. /**
  3. * Tidypics Image class
  4. *
  5. * @package TidypicsImage
  6. * @author Cash Costello
  7. * @license http://www.gnu.org/licenses/gpl-2.0.html GNU General Public License v2
  8. */
  9. class TidypicsImage extends ElggFile {
  10. protected function initializeAttributes() {
  11. parent::initializeAttributes();
  12. $this->attributes['subtype'] = "image";
  13. }
  14. public function __construct($guid = null) {
  15. parent::__construct($guid);
  16. }
  17. /**
  18. * Save the image
  19. *
  20. * @warning container_guid must be set first
  21. *
  22. * @param array $data
  23. * @return bool
  24. */
  25. public function save($data = null) {
  26. if (!parent::save()) {
  27. return false;
  28. }
  29. if ($data) {
  30. // new image
  31. $this->simpletype = "image";
  32. $this->saveImageFile($data);
  33. $this->saveThumbnails();
  34. $this->extractExifData();
  35. }
  36. return true;
  37. }
  38. /**
  39. * Delete image
  40. *
  41. * @return bool
  42. */
  43. public function delete() {
  44. // check if batch should be deleted
  45. $batch = elgg_get_entities_from_relationship(array(
  46. 'relationship' => 'belongs_to_batch',
  47. 'relationship_guid' => $this->guid,
  48. 'inverse_relationship' => false,
  49. ));
  50. if ($batch) {
  51. $batch = $batch[0];
  52. $count = elgg_get_entities_from_relationship(array(
  53. 'relationship' => 'belongs_to_batch',
  54. 'relationship_guid' => $batch->guid,
  55. 'inverse_relationship' => true,
  56. 'count' => true,
  57. ));
  58. if ($count == 1) {
  59. // last image so delete batch
  60. $batch->delete();
  61. }
  62. }
  63. $this->removeThumbnails();
  64. $album = get_entity($this->container_guid);
  65. if ($album) {
  66. $album->removeImage($this->guid);
  67. }
  68. // update quota
  69. $owner = $this->getOwnerEntity();
  70. $owner->image_repo_size = (int)$owner->image_repo_size - $this->getSize();
  71. return parent::delete();
  72. }
  73. /**
  74. * Get the title of the image
  75. *
  76. * @return string
  77. */
  78. public function getTitle() {
  79. if ($this->title) {
  80. return $this->title;
  81. } else {
  82. return $this->originalfilename;
  83. }
  84. }
  85. /**
  86. * Get the URL for the web page of this image
  87. *
  88. * @return string
  89. */
  90. public function getURL() {
  91. $title = elgg_get_friendly_title($this->getTitle());
  92. $url = "photos/image/$this->guid/$title";
  93. return elgg_normalize_url($url);
  94. }
  95. /**
  96. * Get the src URL for the image
  97. *
  98. * @return string
  99. */
  100. public function getIconURL($size = 'small') {
  101. if ($size == 'tiny') {
  102. $size = 'thumb';
  103. }
  104. return elgg_normalize_url("photos/thumbnail/$this->guid/$size/");
  105. }
  106. /**
  107. * Get the view information for this image
  108. *
  109. * @param $viewer_guid The guid of the viewer
  110. * @return array with number of views, number of unique viewers, and number of views for this viewer
  111. */
  112. public function getViewInfo($viewer_guid = 0) {
  113. if ($viewer_guid == 0) {
  114. $viewer_guid = elgg_get_logged_in_user_guid();
  115. }
  116. $views = elgg_get_annotations(array(
  117. 'guid' => $this->getGUID(),
  118. 'annotation_name' => 'tp_view',
  119. 'limit' => 0,
  120. ));
  121. if ($views) {
  122. $total_views = count($views);
  123. if ($this->getOwnerGUID() == $viewer_guid) {
  124. // get unique number of viewers
  125. $diff_viewers = array();
  126. foreach ($views as $view) {
  127. $diff_viewers[$view->owner_guid] = 1;
  128. }
  129. $unique_viewers = count($diff_viewers);
  130. } else if ($viewer_guid) {
  131. // get the number of times this user has viewed the photo
  132. $my_views = 0;
  133. foreach ($views as $view) {
  134. if ($view->owner_guid == $viewer_guid) {
  135. $my_views++;
  136. }
  137. }
  138. }
  139. $view_info = array("total" => $total_views, "unique" => $unique_viewers, "mine" => $my_views);
  140. }
  141. else {
  142. $view_info = array("total" => 0, "unique" => 0, "mine" => 0);
  143. }
  144. return $view_info;
  145. }
  146. /**
  147. * Add a view to this image
  148. *
  149. * @param $viewer_guid
  150. * @return void
  151. */
  152. public function addView($viewer_guid = 0) {
  153. if ($viewer_guid == 0) {
  154. $viewer_guid = elgg_get_logged_in_user_guid();
  155. }
  156. if ($viewer_guid != $this->owner_guid && tp_is_person()) {
  157. create_annotation($this->getGUID(), "tp_view", "1", "integer", $viewer_guid, ACCESS_PUBLIC);
  158. }
  159. }
  160. /**
  161. * Set the internal filenames
  162. */
  163. protected function setOriginalFilename($originalName) {
  164. $prefix = "image/" . $this->container_guid . "/";
  165. $filestorename = elgg_strtolower(time() . $originalName);
  166. $this->setFilename($prefix . $filestorename);
  167. $this->originalfilename = $originalName;
  168. }
  169. /**
  170. * Auto-correction of image orientation based on exif data
  171. *
  172. * @param array $data
  173. */
  174. protected function OrientationCorrection($data) {
  175. // catch for those who don't have exif module loaded
  176. if (!is_callable('exif_read_data')) {
  177. return;
  178. }
  179. $exif = exif_read_data($data['tmp_name']);
  180. $orientation = isset($exif['Orientation']) ? $exif['Orientation'] : 0;
  181. if($orientation != 0 || $orientation != 1) {
  182. $imageLib = elgg_get_plugin_setting('image_lib', 'tidypics');
  183. if ($imageLib == 'ImageMagick') {
  184. // ImageMagick command line
  185. $im_path = elgg_get_plugin_setting('im_path', 'tidypics');
  186. if (!$im_path) {
  187. $im_path = "/usr/bin/";
  188. }
  189. if (substr($im_path, strlen($im_path)-1, 1) != "/") {
  190. $im_path .= "/";
  191. }
  192. $filename = $data['tmp_name'];
  193. $command = $im_path . "mogrify -auto-orient $filename";
  194. $output = array();
  195. $ret = 0;
  196. exec($command, $output, $ret);
  197. } else if ($imageLib == 'ImageMagickPHP') {
  198. // imagick php extension
  199. $rotate = false;
  200. $flop = false;
  201. $angle = 0;
  202. switch($orientation) {
  203. case 2:
  204. $rotate = false;
  205. $flop = true;
  206. break;
  207. case 3:
  208. $rotate = true;
  209. $flop = false;
  210. $angle = 180;
  211. break;
  212. case 4:
  213. $rotate = true;
  214. $flop = true;
  215. $angle = 180;
  216. break;
  217. case 5:
  218. $rotate = true;
  219. $flop = true;
  220. $angle = 90;
  221. break;
  222. case 6:
  223. $rotate = true;
  224. $flop = false;
  225. $angle = 90;
  226. break;
  227. case 7:
  228. $rotate = true;
  229. $flop = true;
  230. $angle = -90;
  231. break;
  232. case 8:
  233. $rotate = true;
  234. $flop = false;
  235. $angle = -90;
  236. break;
  237. default:
  238. $rotate = false;
  239. $flop = false;
  240. break;
  241. }
  242. $imagick = new Imagick();
  243. $imagick->readImage($data['tmp_name']);
  244. if ($rotate) {
  245. $imagick->rotateImage('#000000', $angle);
  246. }
  247. if ($flop) {
  248. $imagick->flopImage();
  249. }
  250. $imagick->setImageOrientation(imagick::ORIENTATION_TOPLEFT);
  251. $imagick->writeImage($data['tmp_name']);
  252. $imagick->clear();
  253. $imagick->destroy();
  254. } else {
  255. // make sure the in memory image size does not exceed memory available
  256. $imginfo = getimagesize($data['tmp_name']);
  257. $requiredMemory1 = ceil($imginfo[0] * $imginfo[1] * 5.35);
  258. $requiredMemory2 = ceil($imginfo[0] * $imginfo[1] * ($imginfo['bits'] / 8) * $imginfo['channels'] * 2.5);
  259. $requiredMemory = (int)max($requiredMemory1, $requiredMemory2);
  260. $mem_avail = elgg_get_ini_setting_in_bytes('memory_limit');
  261. $mem_used = memory_get_usage();
  262. $mem_avail = $mem_avail - $mem_used - 2097152; // 2 MB buffer
  263. if ($requiredMemory < $mem_avail) {
  264. $image = imagecreatefromstring(file_get_contents($data['tmp_name']));
  265. $rotate = false;
  266. $flip = false;
  267. $angle = 0;
  268. switch($orientation) {
  269. case 2:
  270. $rotate = false;
  271. $flip = true;
  272. break;
  273. case 3:
  274. $rotate = true;
  275. $flip = false;
  276. $angle = 180;
  277. break;
  278. case 4:
  279. $rotate = true;
  280. $flip = true;
  281. $angle = 180;
  282. break;
  283. case 5:
  284. $rotate = true;
  285. $flip = true;
  286. $angle = -90;
  287. break;
  288. case 6:
  289. $rotate = true;
  290. $flip = false;
  291. $angle = -90;
  292. break;
  293. case 7:
  294. $rotate = true;
  295. $flip = true;
  296. $angle = 90;
  297. break;
  298. case 8:
  299. $rotate = true;
  300. $flip = false;
  301. $angle = 90;
  302. break;
  303. default:
  304. $rotate = false;
  305. $flip = false;
  306. break;
  307. }
  308. if ($rotate) {
  309. $image = imagerotate($image, $angle, 0);
  310. imagejpeg($image, $data['tmp_name']);
  311. }
  312. if ($flip) {
  313. $mem_avail = elgg_get_ini_setting_in_bytes('memory_limit');
  314. $mem_used = memory_get_usage();
  315. $mem_avail = $mem_avail - $mem_used - 2097152; // 2 MB buffer
  316. if (($requiredMemory) < $mem_avail) {
  317. $width = imagesx($image);
  318. $height = imagesy($image);
  319. $src_x = 0;
  320. $src_y = 0;
  321. $src_width = $width;
  322. $src_height = $height;
  323. $src_x = $width -1;
  324. $src_width = -$width;
  325. $imgdest = imagecreatetruecolor($width, $height);
  326. imagecopyresampled($imgdest, $image, 0, 0, $src_x, $src_y, $width, $height, $src_width, $src_height);
  327. imagejpeg($imgdest, $data['tmp_name']);
  328. imagedestroy($imgdest);
  329. }
  330. }
  331. imagedestroy($image);
  332. }
  333. }
  334. }
  335. }
  336. /**
  337. * Save the uploaded image
  338. *
  339. * @param array $data
  340. */
  341. protected function saveImageFile($data) {
  342. $this->checkUploadErrors($data);
  343. $this->OrientationCorrection($data);
  344. // we need to make sure the directory for the album exists
  345. // @note for group albums, the photos are distributed among the users
  346. $dir = tp_get_img_dir($this->getContainerGUID());
  347. if (!file_exists($dir)) {
  348. mkdir($dir, 0755, true);
  349. }
  350. // move the uploaded file into album directory
  351. $this->setOriginalFilename($data['name']);
  352. $filename = $this->getFilenameOnFilestore();
  353. $result = move_uploaded_file($data['tmp_name'], $filename);
  354. if (!$result) {
  355. return false;
  356. }
  357. $owner = $this->getOwnerEntity();
  358. $owner->image_repo_size = (int)$owner->image_repo_size + $this->getSize();
  359. return true;
  360. }
  361. /**
  362. * Need to restore sanity to this function
  363. * @param type $data
  364. */
  365. protected function checkUploadErrors($data) {
  366. // check for upload errors
  367. if ($data['error']) {
  368. if ($data['error'] == 1) {
  369. trigger_error('Tidypics warning: image exceeded server php upload limit', E_USER_WARNING);
  370. throw new Exception(elgg_echo('tidypics:image_mem'));
  371. } else {
  372. throw new Exception(elgg_echo('tidypics:unk_error'));
  373. }
  374. }
  375. // must be an image
  376. if (!tp_upload_check_format($data['type'])) {
  377. throw new Exception(elgg_echo('tidypics:not_image'));
  378. }
  379. // make sure file does not exceed memory limit
  380. if (!tp_upload_check_max_size($data['size'])) {
  381. throw new Exception(elgg_echo('tidypics:image_mem'));
  382. }
  383. // make sure the in memory image size does not exceed memory available
  384. $imginfo = getimagesize($data['tmp_name']);
  385. $requiredMemory1 = ceil($imginfo[0] * $imginfo[1] * 5.35);
  386. $requiredMemory2 = ceil($imginfo[0] * $imginfo[1] * ($imginfo['bits'] / 8) * $imginfo['channels'] * 2.5);
  387. $requiredMemory = (int)max($requiredMemory1, $requiredMemory2);
  388. $image_lib = elgg_get_plugin_setting('image_lib', 'tidypics');
  389. if (!tp_upload_memory_check($image_lib, $requiredMemory)) {
  390. trigger_error('Tidypics warning: image memory size too large for resizing so rejecting', E_USER_WARNING);
  391. throw new Exception(elgg_echo('tidypics:image_pixels'));
  392. }
  393. // make sure file fits quota
  394. if (!tp_upload_check_quota($data['size'], elgg_get_logged_in_user_guid())) {
  395. throw new Exception(elgg_echo('tidypics:cannot_upload_exceeds_quota'));
  396. }
  397. }
  398. /**
  399. * Save the image thumbnails
  400. */
  401. protected function saveThumbnails() {
  402. elgg_load_library('tidypics:resize');
  403. $imageLib = elgg_get_plugin_setting('image_lib', 'tidypics');
  404. $prefix = "image/" . $this->container_guid . "/";
  405. $filename = $this->getFilename();
  406. $filename = substr($filename, strrpos($filename, '/') + 1);
  407. if ($imageLib == 'ImageMagick') {
  408. // ImageMagick command line
  409. if (tp_create_im_cmdline_thumbnails($this, $prefix, $filename) != true) {
  410. trigger_error('Tidypics warning: failed to create thumbnails - ImageMagick command line', E_USER_WARNING);
  411. }
  412. } else if ($imageLib == 'ImageMagickPHP') {
  413. // imagick php extension
  414. if (tp_create_imagick_thumbnails($this, $prefix, $filename) != true) {
  415. trigger_error('Tidypics warning: failed to create thumbnails - ImageMagick PHP', E_USER_WARNING);
  416. }
  417. } else {
  418. if (tp_create_gd_thumbnails($this, $prefix, $filename) != true) {
  419. trigger_error('Tidypics warning: failed to create thumbnails - GD', E_USER_WARNING);
  420. }
  421. }
  422. }
  423. /**
  424. * Get the image data of a thumbnail
  425. *
  426. * @param string $size
  427. * @return string
  428. */
  429. public function getThumbnail($size) {
  430. switch ($size) {
  431. case 'thumb':
  432. $thumb = $this->thumbnail;
  433. break;
  434. case 'small':
  435. $thumb = $this->smallthumb;
  436. break;
  437. case 'large':
  438. $thumb = $this->largethumb;
  439. break;
  440. default:
  441. return '';
  442. break;
  443. }
  444. if (!$thumb) {
  445. return '';
  446. }
  447. $file = new ElggFile();
  448. $file->owner_guid = $this->getOwnerGUID();
  449. $file->setFilename($thumb);
  450. return $file->grabFile();
  451. }
  452. public function getImage() {
  453. return $this->grabFile();
  454. }
  455. /**
  456. * Extract EXIF Data from image
  457. *
  458. * @warning image file must be saved first
  459. */
  460. public function extractExifData() {
  461. elgg_load_library('tidypics:exif');
  462. td_get_exif($this);
  463. }
  464. /**
  465. * Has the photo been tagged with "in this photo" tags
  466. *
  467. * @return true/false
  468. */
  469. public function isPhotoTagged() {
  470. $num_tags = elgg_get_annotations(array('guid' => $this->getGUID(), 'type' => 'object', 'subtype' => 'image', 'annotation_name' => 'phototag', 'count' => true));
  471. if ($num_tags > 0) {
  472. return true;
  473. } else {
  474. return false;
  475. }
  476. }
  477. /**
  478. * Get an array of photo tag information
  479. *
  480. * @return array
  481. */
  482. public function getPhotoTags() {
  483. $tags = array();
  484. $annotations = elgg_get_annotations(array(
  485. 'guid' => $this->getGUID(),
  486. 'annotation_name' => 'phototag',
  487. ));
  488. foreach ($annotations as $annotation) {
  489. $tag = unserialize($annotation->value);
  490. $tag->annotation_id = $annotation->id;
  491. $tags[] = $tag;
  492. }
  493. return $tags;
  494. }
  495. /**
  496. * Remove thumbnails - usually in preparation for deletion
  497. *
  498. * The thumbnails are not actually ElggObjects so we create
  499. * temporary objects to delete them.
  500. */
  501. protected function removeThumbnails() {
  502. $thumbnail = $this->thumbnail;
  503. $smallthumb = $this->smallthumb;
  504. $largethumb = $this->largethumb;
  505. //delete standard thumbnail image
  506. if ($thumbnail) {
  507. $delfile = new ElggFile();
  508. $delfile->owner_guid = $this->getOwnerGUID();
  509. $delfile->setFilename($thumbnail);
  510. $delfile->delete();
  511. }
  512. //delete small thumbnail image
  513. if ($smallthumb) {
  514. $delfile = new ElggFile();
  515. $delfile->owner_guid = $this->getOwnerGUID();
  516. $delfile->setFilename($smallthumb);
  517. $delfile->delete();
  518. }
  519. //delete large thumbnail image
  520. if ($largethumb) {
  521. $delfile = new ElggFile();
  522. $delfile->owner_guid = $this->getOwnerGUID();
  523. $delfile->setFilename($largethumb);
  524. $delfile->delete();
  525. }
  526. }
  527. }