BxDolImageTranscoder.php 20 KB

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