BxDolImageTranscoder.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup DolphinCore Dolphin Core
  7. * @{
  8. */
  9. bx_import('BxDolStorage');
  10. bx_import('BxDolImageTranscoderQuery');
  11. /**
  12. * @page objects
  13. * @section images_transcoder Images Transcoder
  14. * @ref BxDolImageTranscoder
  15. */
  16. /**
  17. * This class transcodes images on the fly.
  18. * Transcoded image is saved in the specified storage engine and next time ready image is served.
  19. *
  20. *
  21. * To add image transcoder object add record to 'sys_objects_transcoder_images' table:
  22. * - object - name of the transcoder object, in the format: vendor prefix, underscore, module prefix, underscore, image size name; for example: bx_images_thumb.
  23. * - storage_object - name of the storage object to store transcoded data, the specified storage object need to be created too, @see BxDolStorage.
  24. * - source_type - type of the source, where is source image is taken from, available options 'Storage' and 'Folder' for now.
  25. * - source_params - source_type params, each source_type can have own set of params, please read futher for more info about particular source_types, serialized array of params is stored here.
  26. * - private - how to store transcoded data:
  27. * - no - store transcoded data publicly.
  28. * - yes - store transcoded data privately.
  29. * - auto - detect automatically, not supported for 'Folder' source type.
  30. * - atime_tracking - track last access time to the transcoded data, allowed values 0 - disables or 1 - enabled.
  31. * - atime_pruning - prune transcoded images by last access time, if last access time of the image is older than atime_pruning seconds - it is deleted, it works when atime_tracking is enabled
  32. * - ts - unix timestamp of the last change of transcoder parameters, if transcoded image is older than this value - image is deleted and transcoded again.
  33. *
  34. *
  35. * Then you need to add image filters to 'sys_transcoder_images_filters' table:
  36. * - transcoder_object - name of the transcoded object to apply filter to.
  37. * - filter - filter name, please read futher for available filters.
  38. * - filter_params - serialized array of filter params, please read futher for particular filters params.
  39. * - order - if there are several filters for one object, they will be applied in this order.
  40. *
  41. *
  42. * 'Folder' source types:
  43. * This source type is some folder with original images for the transcoding, the identifier of the image (handler) is file name.
  44. * The params are the following:
  45. * - path - path to the folder with original images
  46. * This source type has some limitation:
  47. * - automatic detection of private files is not supported
  48. * - transcoded file is not automaticlaly deleted/renewed if original file is changed
  49. *
  50. *
  51. * 'Storage' source type:
  52. * The source of original files is Storage engine, the identifier of the image (handler) is file id.
  53. * The params are the following:
  54. * - object - name of the Storage object
  55. *
  56. *
  57. * Available filters:
  58. * - Resize - this filter resizes original image, the parameters are the following:
  59. * - w - width of resulted image.
  60. * - h - height of resulted image.
  61. * - square_resize - make resulted image square, even of original image is not square, 'w' and 'h' parameters must be the same.
  62. * - force_type - always change type of the image to the specified type: jpg, png, gif.
  63. * - Grayscale - make image grayscale, there is no parameters for this filter
  64. *
  65. *
  66. * Automatic deletetion of associated data is supported - in the case if original or transcoded file is deleted,
  67. * but you need to register alert handlers, just call registerHandlers () function to register handler (for example, during module installation)
  68. * and call unregisterHandlers () function to unregister handlers (for example, during module uninstallation)
  69. *
  70. *
  71. * Example of usage:
  72. * @code
  73. * bx_import('BxDolImageTranscoder');
  74. * $oTranscoder = BxDolImageTranscoder::getObjectInstance('bx_images_thumb'); // change images transcode object name to your own
  75. * $oTranscoder->registerHandlers(); // make sure to call it only once! before the first usage, no need to call it every time
  76. * $sTranscodedImageUrl = $oTranscoder->getImageUrl('my_dog.jpg'); // the name of file, in the case of 'Folder' storage type this is file name
  77. * echo 'My dog : <img src="' . $sUrl . '" />'; // transcoded(resized and/or grayscaled) image will be shown, according to the specified filters
  78. * @endcode
  79. *
  80. */
  81. class BxDolImageTranscoder extends BxDol implements iBxDolFactoryObject {
  82. protected $_aObject; ///< object properties
  83. protected $_oStorage; ///< storage object, transcoded images are stored here
  84. protected $_oDb; ///< database queries object
  85. /**
  86. * constructor
  87. */
  88. protected function BxDolImageTranscoder($aObject, $oStorage) {
  89. parent::BxDol();
  90. $this->_aObject = $aObject;
  91. $this->_oStorage = $oStorage;
  92. $this->_oDb = new BxDolImageTranscoderQuery($aObject);
  93. }
  94. /**
  95. * Get image transcode object instance.
  96. * @param $sObject - name of trancode object.
  97. * @return false on error or instance of BxDolImageTranscoder class.
  98. */
  99. public static function getObjectInstance($sObject) {
  100. if (isset($GLOBALS['bxDolClasses']['BxDolImageTranscoder!'.$sObject]))
  101. return $GLOBALS['bxDolClasses']['BxDolImageTranscoder!'.$sObject];
  102. // get transcode object
  103. $aObject = BxDolImageTranscoderQuery::getTranscoderObject($sObject);
  104. if (!$aObject || !is_array($aObject))
  105. return false;
  106. if ($aObject['source_params'])
  107. $aObject['source_params'] = unserialize($aObject['source_params']);
  108. $aObject['filters'] = false; // filters are initialized on demand
  109. // create storage object to store transcoded data
  110. $oStorage = BxDolStorage::getObjectInstance($aObject['storage_object']);
  111. if (!$oStorage)
  112. return false;
  113. // create instance
  114. $o = new BxDolImageTranscoder($aObject, $oStorage);
  115. return ($GLOBALS['bxDolClasses']['BxDolImageTranscoder!'.$sObject] = $o);
  116. }
  117. /**
  118. * Delete outdated transcoed data from all transcoeeed objects, by last access time.
  119. * It called on cron, usually every day.
  120. * @return total number of pruned/deleted files
  121. */
  122. static public function pruning () {
  123. $iCount = 0;
  124. $aObjects = BxDolImageTranscoderQuery::getTranscoderObjects ();
  125. foreach ($aObjects as $aObject) {
  126. if (!$aObject['atime_tracking'] || !$aObject['atime_pruning'])
  127. continue;
  128. $oTranscoder = BxDolImageTranscoder::getObjectInstance($aObject['object']);
  129. if (!$oTranscoder)
  130. continue;
  131. $iCount += $oTranscoder->prune();
  132. }
  133. return $iCount;
  134. }
  135. /**
  136. * Register handlers array
  137. * It can be called upon module enable event.
  138. * @param $mixed array of transcoders objects, or just one object
  139. */
  140. static public function registerHandlersArray ($mixed) {
  141. self::_registerHandlersArray ($mixed, 'registerHandlers');
  142. }
  143. /**
  144. * Unregister handlers array
  145. * It can be called upon module disbale event.
  146. * @param $mixed array of transcoders objects, or just one object
  147. */
  148. static public function unregisterHandlersArray ($mixed) {
  149. self::_registerHandlersArray ($mixed, 'unregisterHandlers');
  150. }
  151. /**
  152. * Called automatically, upon local(transcoded) file deletetion.
  153. */
  154. static public function onAlertResponseFileDeleteLocal ($sObject, $oAlert) {
  155. $oTranscoder = BxDolImageTranscoder::getObjectInstance($sObject);
  156. if (!$oTranscoder)
  157. return;
  158. if ($oAlert->sAction != 'file_deleted')
  159. return;
  160. $oTranscoder->onDeleteFileLocal($oAlert->iObject);
  161. }
  162. /**
  163. * Called automatically, upon original file deletetion.
  164. */
  165. static public function onAlertResponseFileDeleteOrig ($sObject, $oAlert) {
  166. $oTranscoder = BxDolImageTranscoder::getObjectInstance($sObject);
  167. if (!$oTranscoder)
  168. return;
  169. if ($oAlert->sAction != 'file_deleted')
  170. return;
  171. $oTranscoder->onDeleteFileOrig($oAlert->iObject);
  172. }
  173. /**
  174. * Called automatically, upon local(transcoded) file deletetion.
  175. */
  176. public function onDeleteFileLocal($iFileId) {
  177. return $this->_oDb->deleteFileTraces($iFileId);
  178. }
  179. /**
  180. * Called automatically, upon original file deletetion.
  181. */
  182. public function onDeleteFileOrig($mixedHandler) {
  183. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  184. if (!$iFileId)
  185. return false;
  186. return $this->_oStorage->deleteFile($iFileId);
  187. }
  188. /**
  189. * Register necessary alert handlers for automatic deletetion of transcoded data if source file is deleted.
  190. * Make sure that you call it once, before first usage, for example upon module installation.
  191. */
  192. public function registerHandlers () {
  193. if (!$this->_oDb->registerHandlers ())
  194. return false;
  195. return $this->clearCacheDB();
  196. }
  197. /**
  198. * Unregister alert handlers for automatic deletetion of transcoded data if source file is deleted.
  199. * Make sure that you call it once, for example upon module uninstallation.
  200. */
  201. public function unregisterHandlers () {
  202. if (!$this->_oDb->unregisterHandlers ())
  203. return false;
  204. return $this->clearCacheDB();
  205. }
  206. /**
  207. * Get storage object where transcoded data is stored
  208. */
  209. public function getStorage() {
  210. return $this->_oStorage;
  211. }
  212. /**
  213. * Get transcoded image url.
  214. * If transcoded image is ready then direct url to this image is returned.
  215. * If there is not transcoded data available special url is returned, upon opening this url - image is transcoed automatically and redirects to the ready transcoed image.
  216. * @params $mixedHandler - image handler
  217. * @return image url, or false on error.
  218. */
  219. public function getImageUrl($mixedHandler) {
  220. if ($this->isImageReady($mixedHandler)) {
  221. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  222. if (!$iFileId)
  223. return false;
  224. $aFile = $this->_oStorage->getFile($iFileId);
  225. if (!$aFile)
  226. return false;
  227. if ($this->_aObject['atime_tracking'])
  228. $this->_oDb->updateAccessTime($mixedHandler);
  229. return $this->_oStorage->getFileUrlById($iFileId);
  230. }
  231. return BX_DOL_URL_ROOT . 'image_transcoder.php?o=' . $this->_aObject['object'] . '&h=' . $mixedHandler . '&t=' . time();
  232. }
  233. /**
  234. * Check if transcoded data is available. No need to call it directly, it is called automatically when it is needed.
  235. * @params $mixedHandler - image handler
  236. * @params $isCheckOutdated - check if transcoded image outdated
  237. * @return false if there is no ready transcoed image is available or it is outdated, true if image is ready
  238. */
  239. public function isImageReady ($mixedHandler, $isCheckOutdated = true) {
  240. $sMethodImageReady = 'isImageReady_' . $this->_aObject['source_type'];
  241. return $this->$sMethodImageReady($mixedHandler, $isCheckOutdated);
  242. }
  243. /**
  244. * Transcode image, no need to call it directly, it is called automatically when it is needed.
  245. * @params $mixedHandler - image handler
  246. * @params $iProfileId - optional profile id, to assign transcoded image to, usually it is NOT assigned to any particular profile, so just leave it default
  247. * @return true on success, false on error
  248. */
  249. public function transcode ($mixedHandler, $iProfileId = 0) {
  250. $sExtChange = false;
  251. // create tmp file locally
  252. $sMethodStoreFile = 'storeFileLocally_' . $this->_aObject['source_type'];
  253. $sTmpFile = $this->$sMethodStoreFile($mixedHandler);
  254. if (!$sTmpFile)
  255. return false;
  256. // appply filters to tmp file
  257. $this->initFilters ();
  258. foreach ($this->_aObject['filters'] as $aParams) {
  259. $sMethodFilter = 'applyFilter_' . $aParams['filter'];
  260. if (!method_exists($this, $sMethodFilter))
  261. continue;
  262. if (!$this->$sMethodFilter($sTmpFile, $aParams['filter_params'])) {
  263. unlink($sTmpFile);
  264. return false;
  265. }
  266. if (!empty($aParams['filter_params']['force_type'])) {
  267. switch ($aParams['filter_params']['force_type']) {
  268. case 'jpeg':
  269. case 'jpg':
  270. $sExtChange = 'jpg';
  271. break;
  272. case 'png':
  273. $sExtChange = 'png';
  274. break;
  275. case 'gif':
  276. $sExtChange = 'gif';
  277. break;
  278. }
  279. }
  280. }
  281. if ($sExtChange && false !== ($iDotPos = strrpos($sTmpFile, '.'))) {
  282. $sExtOld = substr($sTmpFile, $iDotPos+1);
  283. if ($sExtOld != $sExtChange) {
  284. $sTmpFileOld = $sTmpFile;
  285. $sTmpFile = substr_replace ($sTmpFile, $sExtChange, $iDotPos+1, strlen($sExtOld));
  286. if (!rename($sTmpFileOld, $sTmpFile)) {
  287. unlink($sTmpFileOld);
  288. return false;
  289. }
  290. }
  291. }
  292. // store transcoded file in the storage
  293. $sMethodIsPrivate = 'isPrivate_' . $this->_aObject['source_type'];
  294. $isPrivate = $this->$sMethodIsPrivate($mixedHandler);
  295. $iFileId = $this->_oStorage->storeFileFromPath ($sTmpFile, $isPrivate, $iProfileId);
  296. @unlink($sTmpFile);
  297. if (!$iFileId)
  298. return false;
  299. if (!$this->_oDb->updateHandler($iFileId, $mixedHandler)) {
  300. $this->_oStorage->deleteFile($iFileId);
  301. return false;
  302. }
  303. $this->_oStorage->afterUploadCleanup($iFileId, $iProfileId);
  304. return true;
  305. }
  306. /**
  307. * Delete outdated files by last access time.
  308. * @return number of pruned/deleted files
  309. */
  310. public function prune () {
  311. $aFiles = $this->_oDb->getFilesForPruning();
  312. if (!$aFiles)
  313. return false;
  314. $iCount = 0;
  315. foreach ($aFiles as $r)
  316. $iCount += $this->_oStorage->deleteFile($r['file_id']) ? 1 : 0;
  317. return $iCount;
  318. }
  319. // ---------------------------
  320. protected function isImageReady_Folder ($mixedHandler, $isCheckOutdated = true) {
  321. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  322. if (!$iFileId)
  323. return false;
  324. $aFile = $this->_oStorage->getFile($iFileId);
  325. if (!$aFile)
  326. return false;
  327. if ($isCheckOutdated) { // warning, $isCheckOutdated is partially supported for Folder source type - file modification is not checked
  328. if ($this->_aObject['ts'] > $aFile['modified'] || !$this->getFilePath_Folder($mixedHandler)) { // if we changed transcoder object params or original file is deleted
  329. // delete file, so it will be recreated next time
  330. if ($this->_oStorage->deleteFile($aFile['id']))
  331. return false;
  332. }
  333. }
  334. return true;
  335. }
  336. protected function isImageReady_Storage ($mixedHandler, $isCheckOutdated = true) {
  337. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  338. if (!$iFileId)
  339. return false;
  340. $aFile = $this->_oStorage->getFile($iFileId);
  341. if (!$aFile)
  342. return false;
  343. if ($isCheckOutdated) {
  344. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  345. if ($oStorageOriginal) {
  346. $aFileOriginal = $oStorageOriginal->getFile($mixedHandler);
  347. if (!$aFileOriginal || $aFileOriginal['modified'] > $aFile['modified'] || $this->_aObject['ts'] > $aFile['modified']) { // if original file was changed OR we changed transcoder object params
  348. // delete file, so it will be recreated next time
  349. if ($this->_oStorage->deleteFile($aFile['id']))
  350. return false;
  351. }
  352. }
  353. }
  354. return true;
  355. }
  356. protected function isPrivate_Folder ($mixedHandler) {
  357. if ('no' == $this->_aObject['private'])
  358. return false;
  359. return true;
  360. }
  361. protected function isPrivate_Storage ($mixedHandler) {
  362. switch ($this->_aObject['private']) {
  363. case 'no':
  364. return false;
  365. case 'yes':
  366. return true;
  367. default:
  368. case 'auto':
  369. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  370. if (!$oStorageOriginal)
  371. return true; // in case of error - make sure that file is not public accidentally
  372. $aFile = $oStorageOriginal->getFile($mixedHandler);
  373. return $oStorageOriginal->isFilePrivate($aFile['id']);
  374. }
  375. }
  376. protected function getFilePath_Folder ($mixedHandler) {
  377. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  378. if (!file_exists($sPath))
  379. $sPath = BX_DIRECTORY_PATH_ROOT . $sPath;
  380. if (!file_exists($sPath))
  381. return false;
  382. return $sPath;
  383. }
  384. protected function storeFileLocally_Folder ($mixedHandler) {
  385. $sPath = $this->getFilePath_Folder($mixedHandler);
  386. if (!$sPath)
  387. return false;
  388. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  389. if (!copy($sPath, $sTmpFile))
  390. return false;
  391. return $sTmpFile;
  392. }
  393. protected function storeFileLocally_Storage ($mixedHandler) {
  394. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  395. if (!$oStorageOriginal)
  396. return false;
  397. $aFile = $oStorageOriginal->getFile($mixedHandler);
  398. if (!$aFile)
  399. return false;
  400. $sUrl = $oStorageOriginal->getFileUrlById($mixedHandler);
  401. if (!$sUrl)
  402. return false;
  403. $sFileData = bx_file_get_contents ($sUrl);
  404. if (false === $sFileData)
  405. return false;
  406. $sTmpFile = $this->getTmpFilename ($aFile['file_name']);
  407. if (!file_put_contents($sTmpFile, $sFileData))
  408. return false;
  409. return $sTmpFile;
  410. }
  411. protected function getTmpFilename ($sOverrideName = false) {
  412. if ($sOverrideName) {
  413. // TODO: generate uniq folder for current dolphin instance and image object
  414. return realpath(sys_get_temp_dir()) . DIRECTORY_SEPARATOR . rand(10000, 99999) . $sOverrideName;
  415. }
  416. return tempnam(realpath(sys_get_temp_dir()), 'bxdol');
  417. }
  418. protected function applyFilter_Grayscale ($sFile, $aParams) {
  419. bx_import ('BxDolImageResize');
  420. $o = BxDolImageResize::getInstance();
  421. $o->removeCropOptions ();
  422. $this->_checkForceType ($o, $aParams);
  423. if (IMAGE_ERROR_SUCCESS == $o->grayscale($sFile))
  424. return true;
  425. return false;
  426. }
  427. protected function applyFilter_Resize ($sFile, $aParams) {
  428. bx_import ('BxDolImageResize');
  429. $o = BxDolImageResize::getInstance();
  430. $o->removeCropOptions ();
  431. if (isset($aParams['w']) && isset($aParams['h']))
  432. $o->setSize ($aParams['w'], $aParams['h']);
  433. if (isset($aParams['crop_resize']) && $aParams['crop_resize']) {
  434. $o->setAutoCrop (true);
  435. } elseif (isset($aParams['square_resize']) && $aParams['square_resize']) {
  436. $o->setSquareResize (true);
  437. } else {
  438. $o->setSquareResize (false);
  439. }
  440. $this->_checkForceType ($o, $aParams);
  441. if (IMAGE_ERROR_SUCCESS == $o->resize($sFile))
  442. return true;
  443. return false;
  444. }
  445. protected function _checkForceType ($oImageProcessor, $aParams) {
  446. if (empty($aParams['force_type']))
  447. $aParams['force_type'] = false;
  448. switch ($aParams['force_type']) {
  449. case 'jpeg':
  450. case 'jpg':
  451. $oImageProcessor->setOutputType(IMAGE_TYPE_JPG);
  452. break;
  453. case 'png':
  454. $oImageProcessor->setOutputType(IMAGE_TYPE_PNG);
  455. break;
  456. case 'gif':
  457. $oImageProcessor->setOutputType(IMAGE_TYPE_GIF);
  458. break;
  459. default:
  460. $oImageProcessor->setOutputType(false);
  461. break;
  462. }
  463. }
  464. protected function initFilters () {
  465. if (false !== $this->_aObject['filters']) // filters are already initilized
  466. return;
  467. // get transcoder filters
  468. $aFilters = $this->_oDb->getTranscoderFilters();
  469. $this->_aObject['filters'] = array();
  470. foreach ($aFilters as $aFilter) {
  471. if ($aFilter['filter_params'])
  472. $aFilter['filter_params'] = unserialize($aFilter['filter_params']);
  473. $this->_aObject['filters'][] = $aFilter;
  474. }
  475. }
  476. protected function clearCacheDB() {
  477. $this->_oDb->oParams->clearCache();
  478. $oCacheDb = $this->_oDb->getDbCacheObject();
  479. return $oCacheDb->removeAllByPrefix('db_');
  480. }
  481. static protected function _registerHandlersArray ($mixed, $sFunc) {
  482. if (!is_array($mixed))
  483. $mixed = array($mixed);
  484. foreach ($mixed as $sObject) {
  485. $oTranscoder = self::getObjectInstance($sObject);
  486. if ($oTranscoder)
  487. $oTranscoder->$sFunc();
  488. }
  489. }
  490. }
  491. /** @} */