BxDolTranscoder.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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 TridentCore Trident Core
  7. * @{
  8. */
  9. define('BX_DOL_QUEUE_PENDING', 'pending'); ///< file is pending for processing
  10. define('BX_DOL_QUEUE_PROCESSING', 'processing'); ///< file is in the process
  11. define('BX_DOL_QUEUE_COMPLETE', 'complete'); ///< file is already processed
  12. define('BX_DOL_QUEUE_FAILED', 'failed'); ///< file processing was failed
  13. define('BX_DOL_QUEUE_DELETE', 'delete'); ///< file is subject to delete
  14. /**
  15. * Base class for @see BxDolTranscoderImage and @see BxDolTranscoderVideo transcoders
  16. */
  17. class BxDolTranscoder extends BxDol implements iBxDolFactoryObject
  18. {
  19. protected $_sLog = ''; ///< file conversion log
  20. protected $_aObject; ///< object properties
  21. protected $_oStorage; ///< storage object, transcoded files are stored here
  22. protected $_oDb; ///< database queries object
  23. protected $_sRetinaSuffix = '@2x'; ///< handler suffix for retina image file
  24. protected $_sQueueTable = ''; ///< table with queued files for transcoding
  25. protected $_sQueueStorage = ''; ///< storage object to storage temporary files
  26. /**
  27. * constructor
  28. */
  29. protected function __construct($aObject, $oStorage)
  30. {
  31. parent::__construct();
  32. $this->_aObject = $aObject;
  33. $this->_oStorage = $oStorage;
  34. $this->_oDb = null;
  35. }
  36. /**
  37. * Get transcode object instance.
  38. * @param $sObject - name of transcode object.
  39. * @return false on error or instance of transcoder class.
  40. */
  41. public static function getObjectInstance($sObject)
  42. {
  43. if (isset($GLOBALS['bxDolClasses'][__CLASS__ . '!' . $sObject]))
  44. return $GLOBALS['bxDolClasses'][__CLASS__ . '!'.$sObject];
  45. // get transcode object
  46. $aObject = BxDolTranscoderQuery::getTranscoderObject($sObject);
  47. if (!$aObject || !is_array($aObject))
  48. return false;
  49. if ($aObject['source_params'])
  50. $aObject['source_params'] = unserialize($aObject['source_params']);
  51. $aObject['filters'] = false; // filters are initialized on demand
  52. // create storage object to store transcoded data
  53. $oStorage = BxDolStorage::getObjectInstance($aObject['storage_object']);
  54. if (!$oStorage)
  55. return false;
  56. // create instance
  57. $sClass = $aObject['override_class_name'] ? $aObject['override_class_name'] : 'BxDolTranscoderImage';
  58. if (!empty($aObject['override_class_file']))
  59. require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
  60. $o = new $sClass ($aObject, $oStorage);
  61. return ($GLOBALS['bxDolClasses'][__CLASS__ . '!' . $sObject] = $o);
  62. }
  63. /**
  64. * Delete outdated transcoed data from all transcoeeed objects, by last access time.
  65. * It called on cron, usually every day.
  66. * @return total number of pruned/deleted files
  67. */
  68. static public function pruning ()
  69. {
  70. $iCount = 0;
  71. $aObjects = self::getTranscoderObjects();
  72. foreach ($aObjects as $aObject) {
  73. if (!$aObject['atime_tracking'] || !$aObject['atime_pruning'])
  74. continue;
  75. $oTranscoder = self::getObjectInstance($aObject['object']);
  76. if (!$oTranscoder)
  77. continue;
  78. $iCount += $oTranscoder->prune();
  79. }
  80. return $iCount;
  81. }
  82. /**
  83. * Get transcoder objects array
  84. * @return array
  85. */
  86. static protected function getTranscoderObjects ()
  87. {
  88. return BxDolTranscoderQuery::getTranscoderObjects ();
  89. }
  90. /**
  91. * Process files queued for transcoding
  92. * Can be performed on separate server.
  93. */
  94. static public function processQueue ($bQueuePruning = true)
  95. {
  96. if ($bQueuePruning)
  97. self::pruneQueue();
  98. $a = BxDolTranscoderQuery::getNextInQueue (gethostname());
  99. foreach ($a as $r) {
  100. $o = self::getObjectInstance($r['transcoder_object']);
  101. $aQueue = $o->getDb()->getFromQueue($r['file_id_source']);
  102. if (!$aQueue || $aQueue['status'] != BX_DOL_QUEUE_PENDING)
  103. continue;
  104. $o->transcode($aQueue['file_id_source'], $aQueue['profile_id']);
  105. }
  106. }
  107. static public function pruneQueue ()
  108. {
  109. $a = BxDolTranscoderQuery::getForDeletionFromQueue (gethostname());
  110. if (!$a)
  111. return false;
  112. foreach ($a as $aQueue) {
  113. $o = self::getObjectInstance($aQueue['transcoder_object']);
  114. $o->deleteFromQueue($aQueue['file_id_source']);
  115. }
  116. }
  117. /**
  118. * Store completed files from tmp queue storage to the final storage
  119. * Must be performed on the actual site.
  120. */
  121. static public function processCompleted ()
  122. {
  123. $a = BxDolTranscoderQuery::getCompletedFromQueue ();
  124. foreach ($a as $r) {
  125. $o = self::getObjectInstance($r['transcoder_object']);
  126. $aQueue = $o->getDb()->getFromQueue($r['file_id_source']);
  127. if (!$aQueue || $aQueue['status'] != BX_DOL_QUEUE_COMPLETE)
  128. continue;
  129. if ($aQueue['file_url_result'] && $aQueue['file_id_result']) {
  130. // get transcoded file from provided URL
  131. $sFileData = bx_file_get_contents ($aQueue['file_url_result']);
  132. if (false === $sFileData) {
  133. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "download file failed: {$aQueue['file_url_result']}\n");
  134. continue;
  135. }
  136. $sTmpFile = $o->getTmpFilename ('.' . $aQueue['file_ext_result']);
  137. if (!file_put_contents($sTmpFile, $sFileData)) {
  138. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "store downloaded file failed\n");
  139. @unlink($sTmpFile);
  140. continue;
  141. }
  142. // store downloaded file in final storage
  143. if ($o->storeTranscodedFile($aQueue['file_id_source'], $sTmpFile, $aQueue['profile_id']))
  144. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_DELETE); // mark to delete it (deletion is performed on the server where it was transcoded)
  145. else
  146. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "store file failed:\n" . $o->getLog());
  147. // delete tmp local file
  148. @unlink($sTmpFile);
  149. }
  150. }
  151. }
  152. /**
  153. * Register handlers array
  154. * It can be called upon module enable event.
  155. * @param $mixed array of transcoders objects, or just one object
  156. */
  157. static public function registerHandlersArray ($mixed)
  158. {
  159. self::_callFuncForObjectsArray ($mixed, 'registerHandlers');
  160. }
  161. /**
  162. * Unregister handlers array
  163. * It can be called upon module disbale event.
  164. * @param $mixed array of transcoders objects, or just one object
  165. */
  166. static public function unregisterHandlersArray ($mixed)
  167. {
  168. self::_callFuncForObjectsArray ($mixed, 'unregisterHandlers');
  169. }
  170. /**
  171. * Cleanup (queue for deletion all resized files)
  172. * It can be called upon module disbale event.
  173. * @param $mixed array of transcoders objects, or just one object
  174. */
  175. static public function cleanupObjectsArray ($mixed)
  176. {
  177. self::_callFuncForObjectsArray ($mixed, 'cleanup');
  178. }
  179. /**
  180. * Called automatically, upon local(transcoded) file deletetion.
  181. */
  182. static public function onAlertResponseFileDeleteLocal ($oAlert, $sObject)
  183. {
  184. $oTranscoder = self::getObjectInstance($sObject);
  185. if (!$oTranscoder)
  186. return;
  187. if ($oAlert->sAction != 'file_deleted')
  188. return;
  189. $oTranscoder->onDeleteFileLocal($oAlert->iObject);
  190. }
  191. /**
  192. * Called automatically, upon original file deletetion.
  193. */
  194. static public function onAlertResponseFileDeleteOrig ($oAlert, $sObject)
  195. {
  196. $oTranscoder = self::getObjectInstance($sObject);
  197. if (!$oTranscoder)
  198. return;
  199. if ($oAlert->sAction != 'file_deleted')
  200. return;
  201. $oTranscoder->onDeleteFileOrig($oAlert->iObject);
  202. }
  203. /**
  204. * Called automatically, upon local(transcoded) file deletetion.
  205. */
  206. public function onDeleteFileLocal($iFileId)
  207. {
  208. return $this->_oDb->deleteFileTraces($iFileId);
  209. }
  210. /**
  211. * Called automatically, upon original file deletetion.
  212. */
  213. public function onDeleteFileOrig($mixedHandler)
  214. {
  215. // deleted files queued for transcoding
  216. $this->_oDb->deleteFromQueue ($mixedHandler);
  217. // delete main file
  218. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  219. if (!$iFileId)
  220. return false;
  221. if (!$this->_oStorage->deleteFile($iFileId))
  222. return false;
  223. // delete retina file
  224. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler . $this->_sRetinaSuffix);
  225. if ($iFileId)
  226. $this->_oStorage->deleteFile($iFileId);
  227. return true;
  228. }
  229. /**
  230. * Register necessary alert handlers for automatic deletetion of transcoded data if source file is deleted.
  231. * Make sure that you call it once, before first usage, for example upon module installation.
  232. */
  233. public function registerHandlers ()
  234. {
  235. if (!$this->_oDb->registerHandlers ())
  236. return false;
  237. return $this->clearCacheDB();
  238. }
  239. /**
  240. * Unregister alert handlers for automatic deletetion of transcoded data if source file is deleted.
  241. * Make sure that you call it once, for example upon module uninstallation.
  242. */
  243. public function unregisterHandlers ()
  244. {
  245. if (!$this->_oDb->unregisterHandlers ())
  246. return false;
  247. return $this->clearCacheDB();
  248. }
  249. /**
  250. * Delete (queue for deletion) all resized files for the current object
  251. */
  252. public function cleanup ()
  253. {
  254. return $this->_oStorage->queueFilesForDeletionFromObject();
  255. }
  256. /**
  257. * Get storage object where transcoded data is stored
  258. */
  259. public function getStorage()
  260. {
  261. return $this->_oStorage;
  262. }
  263. /**
  264. * Get database object instance
  265. */
  266. public function getDb()
  267. {
  268. return $this->_oDb;
  269. }
  270. /**
  271. * Get transcoded file url.
  272. * If transcoded file is ready then direct url to the file is returned.
  273. * If there is no transcoded data available, then special url is returned, upon opening this url image is transcoded automatically and redirects to the ready transcoed image.
  274. * @params $mixedHandler - file handler
  275. * @return file url, or false on error.
  276. */
  277. public function getFileUrl($mixedHandler)
  278. {
  279. if ($this->isFileReady($mixedHandler)) {
  280. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  281. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  282. if (!$iFileId)
  283. return false;
  284. $aFile = $this->_oStorage->getFile($iFileId);
  285. if (!$aFile)
  286. return false;
  287. if ($this->_aObject['atime_tracking'])
  288. $this->_oDb->updateAccessTime($mixedHandler);
  289. return $this->_oStorage->getFileUrlById($iFileId);
  290. }
  291. if ($this->_sQueueTable && !$this->addToQueue($mixedHandler)) // add file to queue (when queue is enabled) if it isn't transcoded yet
  292. return false;
  293. return $this->getFileUrlNotReady($mixedHandler);
  294. }
  295. /**
  296. * alias for @see getFileUrl
  297. */
  298. public function getFileUrlById($mixedHandler)
  299. {
  300. return $this->getFileUrl($mixedHandler);
  301. }
  302. /**
  303. * Check if transcoded data is available. No need to call it directly, it is called automatically when it is needed.
  304. * @params $mixedHandler - file handler
  305. * @params $isCheckOutdated - check if transcoded file is outdated
  306. * @return false if there is no ready transcoded file is available or it is outdated, true if file is ready
  307. */
  308. public function isFileReady ($mixedHandler, $isCheckOutdated = true)
  309. {
  310. $sMethodFileReady = 'isFileReady_' . $this->_aObject['source_type'];
  311. return $this->$sMethodFileReady($mixedHandler, $isCheckOutdated);
  312. }
  313. /**
  314. * Transcode file, no need to call it directly, it is called automatically when it is needed.
  315. * @params $mixedHandler - file handler
  316. * @params $iProfileId - optional profile id, to assign transcoded file ownership to, usually it is NOT assigned to any particular profile, so just leave it default
  317. * @return true on success, false on error
  318. */
  319. public function transcode ($mixedHandler, $iProfileId = 0)
  320. {
  321. $sExtChange = false;
  322. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_PROCESSING, '', gethostname());
  323. // create tmp file locally
  324. $sSuffix = $this->_sQueueStorage ? 'Queue' : $this->_aObject['source_type'];
  325. $sMethodStoreFile = 'storeFileLocally_' . $sSuffix;
  326. $sTmpFile = $this->$sMethodStoreFile($mixedHandler);
  327. if (!$sTmpFile) {
  328. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store local tmp file failed ($sMethodStoreFile)");
  329. return false;
  330. }
  331. // appply filters to tmp file
  332. $this->initFilters ();
  333. foreach ($this->_aObject['filters'] as $aParams) {
  334. $this->clearLog();
  335. $sMethodFilter = 'applyFilter_' . $aParams['filter'];
  336. if (!method_exists($this, $sMethodFilter))
  337. continue;
  338. if (!$this->$sMethodFilter($sTmpFile, $aParams['filter_params'])) {
  339. unlink($sTmpFile);
  340. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "filter failed: $sMethodFilter\n" . $this->getLog());
  341. return false;
  342. }
  343. if (!empty($aParams['filter_params']['force_type'])) {
  344. switch ($aParams['filter_params']['force_type']) {
  345. case 'jpeg':
  346. case 'jpg':
  347. $sExtChange = 'jpg';
  348. break;
  349. default:
  350. $sExtChange = $aParams['filter_params']['force_type'];
  351. }
  352. }
  353. }
  354. if ($sExtChange) {
  355. $iDotPos = strrpos($sTmpFile, '.');
  356. $sExtOld = false === $iDotPos ? '' : substr($sTmpFile, $iDotPos+1);
  357. if ($sExtOld != $sExtChange) {
  358. $sTmpFileOld = $sTmpFile;
  359. $sTmpFile = false === $iDotPos ? $sTmpFile . '.' . $sExtChange : substr_replace($sTmpFile, $sExtChange, $iDotPos+1, strlen($sExtOld));
  360. if (!rename($sTmpFileOld, $sTmpFile)) {
  361. @unlink($sTmpFileOld);
  362. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "change file extension failed: $sTmpFileOld => $sTmpFile");
  363. return false;
  364. }
  365. }
  366. }
  367. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  368. $bRet = true;
  369. if ($this->_sQueueStorage) {
  370. $sFileUrlResult = '';
  371. if (!($iFileIdResult = $this->storeTranscodedFileInQueueStorage($mixedHandler, $sTmpFile, $sFileUrlResult)))
  372. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store queue tmp file failed:\n" . $this->getLog());
  373. else
  374. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_COMPLETE, '', '', $iFileIdResult, $sFileUrlResult, $sExtChange);
  375. } else {
  376. $bRet = $this->storeTranscodedFile($mixedHandler, $sTmpFile, $iProfileId);
  377. if ($bRet)
  378. $this->deleteFromQueue($mixedHandler);
  379. else
  380. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store file failed:\n" . $this->getLog());
  381. }
  382. @unlink($sTmpFile);
  383. return $bRet;
  384. }
  385. /**
  386. * Delete outdated files by last access time.
  387. * @return number of pruned/deleted files
  388. */
  389. public function prune ()
  390. {
  391. $aFiles = $this->_oDb->getFilesForPruning();
  392. if (!$aFiles)
  393. return false;
  394. $iCount = 0;
  395. foreach ($aFiles as $r)
  396. $iCount += $this->_oStorage->deleteFile($r['file_id']) ? 1 : 0;
  397. return $iCount;
  398. }
  399. public function getDevicePixelRatio ()
  400. {
  401. if (isset($_COOKIE['devicePixelRatio']) && (!isset($this->_aObject['source_params']['disable_retina']) || !$this->_aObject['source_params']['disable_retina'])) {
  402. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  403. if ($iDevicePixelRatio >= 2)
  404. return 2;
  405. }
  406. return 1;
  407. }
  408. public function getOrigFileUrl ($mixedHandler)
  409. {
  410. $sMethodStoreFile = 'getOrigFileUrl_' . $this->_aObject['source_type'];
  411. return $this->$sMethodStoreFile($mixedHandler);
  412. }
  413. /**
  414. * Get file url when file isn't transcoded yet
  415. */
  416. public function getFileUrlNotReady($mixedHandler)
  417. {
  418. return false;
  419. }
  420. public function getTmpFilename ($sOverrideName = false)
  421. {
  422. if ($sOverrideName)
  423. return BX_DIRECTORY_PATH_TMP . rand(10000, 99999) . $sOverrideName;
  424. return tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
  425. }
  426. public function clearLog()
  427. {
  428. $this->_sLog = '';
  429. }
  430. public function addToLog($s)
  431. {
  432. $this->_sLog .= $s;
  433. }
  434. public function getLog()
  435. {
  436. return $this->_sLog;
  437. }
  438. public function deleteFromQueue ($mixedHandler)
  439. {
  440. $sErrMsg = "delete queue tmp file failed:\n";
  441. $a = $this->_oDb->getFromQueue($mixedHandler);
  442. if (!$a || $a['server'] != gethostname()) // deletion must be performed on the server where it was transcoded
  443. return false;
  444. if ($a['file_id_result'] && $this->_sQueueStorage && 0 != strncmp($a['log'], $sErrMsg, strlen($sErrMsg))) {
  445. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  446. if (!$oStorage->deleteFile($a['file_id_result'])) {
  447. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, $sErrMsg . $this->getLog());
  448. return false;
  449. }
  450. }
  451. return $this->_oDb->deleteFromQueue($mixedHandler);
  452. }
  453. public function storeTranscodedFile ($mixedHandler, $sTmpFile, $iProfileId)
  454. {
  455. $sMethodIsPrivate = 'isPrivate_' . $this->_aObject['source_type'];
  456. $isPrivate = $this->$sMethodIsPrivate($mixedHandler);
  457. $iFileId = $this->_oStorage->storeFileFromPath ($sTmpFile, $isPrivate, $iProfileId);
  458. if (!$iFileId) {
  459. $this->addToLog($this->_oStorage->getErrorString());
  460. return false;
  461. }
  462. if (!$this->_oDb->updateHandler($iFileId, $mixedHandler)) {
  463. $this->_oStorage->deleteFile($iFileId);
  464. return false;
  465. }
  466. $this->_oStorage->afterUploadCleanup($iFileId, $iProfileId);
  467. return true;
  468. }
  469. protected function storeTranscodedFileInQueueStorage ($mixedHandler, $sTmpFile, &$sFileUrlResult)
  470. {
  471. if (!$this->_sQueueStorage)
  472. return false;
  473. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  474. $iFileIdResult = $oStorage->storeFileFromPath ($sTmpFile, 1, 0);
  475. if (!$iFileIdResult) {
  476. $this->addToLog($oStorage->getErrorString());
  477. return false;
  478. }
  479. if (!($sFileUrlResult = $oStorage->getFileUrlById($iFileIdResult))) {
  480. $this->_oStorage->deleteFile($iFileIdResult);
  481. return false;
  482. }
  483. $oStorage->afterUploadCleanup($iFileIdResult, 0);
  484. return $iFileIdResult;
  485. }
  486. protected function addToQueue($mixedHandler, $iProfileId = 0)
  487. {
  488. if ($this->_oDb->getFromQueue($mixedHandler))
  489. return true;
  490. $sFileUrl = $this->getOrigFileUrl($mixedHandler);
  491. return $this->_oDb->addToQueue ($mixedHandler, $sFileUrl, $iProfileId);
  492. }
  493. protected function applyFilter_Resize ($sFile, $aParams)
  494. {
  495. $o = BxDolImageResize::getInstance();
  496. $o->removeCropOptions ();
  497. // if only one dimension specified - automatically calculate another dimension
  498. if ((isset($aParams['w']) && !isset($aParams['h'])) || (isset($aParams['h']) && !isset($aParams['w']))) {
  499. $a = $o->getImageSize ($sFile);
  500. $fRatio = $a['w'] / $a['h'];
  501. if (isset($aParams['w']))
  502. $aParams['h'] = round($aParams['w'] / $fRatio);
  503. else
  504. $aParams['w'] = round($aParams['h'] * $fRatio);
  505. }
  506. if (isset($aParams['w']) && isset($aParams['h']))
  507. $o->setSize ($aParams['w'] * $this->getDevicePixelRatio(), $aParams['h'] * $this->getDevicePixelRatio());
  508. if (isset($aParams['crop_resize']) && $aParams['crop_resize'])
  509. $o->setAutoCrop (true);
  510. elseif (isset($aParams['square_resize']) && $aParams['square_resize'])
  511. $o->setSquareResize (true);
  512. else
  513. $o->setSquareResize (false);
  514. $this->_checkForceImageType ($o, $aParams);
  515. if (IMAGE_ERROR_SUCCESS == $o->resize($sFile))
  516. return true;
  517. return false;
  518. }
  519. protected function _checkForceImageType ($oImageProcessor, $aParams)
  520. {
  521. if (empty($aParams['force_type']))
  522. $aParams['force_type'] = false;
  523. switch ($aParams['force_type']) {
  524. case 'jpeg':
  525. case 'jpg':
  526. $oImageProcessor->setOutputType(IMAGE_TYPE_JPG);
  527. break;
  528. case 'png':
  529. $oImageProcessor->setOutputType(IMAGE_TYPE_PNG);
  530. break;
  531. case 'gif':
  532. $oImageProcessor->setOutputType(IMAGE_TYPE_GIF);
  533. break;
  534. default:
  535. $oImageProcessor->setOutputType(false);
  536. break;
  537. }
  538. }
  539. protected function isFileReady_Folder ($mixedHandlerOrig, $isCheckOutdated = true)
  540. {
  541. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  542. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  543. if (!$iFileId)
  544. return false;
  545. $aFile = $this->_oStorage->getFile($iFileId);
  546. if (!$aFile)
  547. return false;
  548. if ($isCheckOutdated) { // warning, $isCheckOutdated is partially supported for Folder source type - file modification is not checked
  549. if ($this->_aObject['ts'] > $aFile['modified'] || !$this->getFilePath_Folder($mixedHandlerOrig)) { // if we changed transcoder object params or original file is deleted
  550. // delete file, so it will be recreated next time
  551. if ($this->_oStorage->deleteFile($aFile['id']))
  552. return false;
  553. }
  554. }
  555. return true;
  556. }
  557. protected function isFileReady_Storage ($mixedHandlerOrig, $isCheckOutdated = true)
  558. {
  559. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  560. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  561. if (!$iFileId)
  562. return false;
  563. $aFile = $this->_oStorage->getFile($iFileId);
  564. if (!$aFile)
  565. return false;
  566. if ($isCheckOutdated) {
  567. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  568. if ($oStorageOriginal) {
  569. $aFileOriginal = $oStorageOriginal->getFile($mixedHandlerOrig);
  570. if (!$aFileOriginal || $aFileOriginal['modified'] > $aFile['modified'] || $this->_aObject['ts'] >= $aFile['modified']) { // if original file was changed OR we changed transcoder object params
  571. // delete file, so it will be recreated next time
  572. if ($this->_oStorage->deleteFile($aFile['id']))
  573. return false;
  574. }
  575. }
  576. }
  577. return true;
  578. }
  579. protected function isPrivate_Folder ($mixedHandler)
  580. {
  581. if ('no' == $this->_aObject['private'])
  582. return false;
  583. return true;
  584. }
  585. protected function isPrivate_Storage ($mixedHandler)
  586. {
  587. switch ($this->_aObject['private']) {
  588. case 'no':
  589. return false;
  590. case 'yes':
  591. return true;
  592. default:
  593. case 'auto':
  594. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  595. if (!$oStorageOriginal)
  596. return true; // in case of error - make sure that file is not public accidentally
  597. $aFile = $oStorageOriginal->getFile($mixedHandler);
  598. return $oStorageOriginal->isFilePrivate($aFile['id']);
  599. }
  600. }
  601. protected function getFilePath_Folder ($mixedHandler)
  602. {
  603. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  604. if (!file_exists($sPath))
  605. $sPath = BX_DIRECTORY_PATH_ROOT . $sPath;
  606. if (!file_exists($sPath))
  607. return false;
  608. return $sPath;
  609. }
  610. protected function storeFileLocally_Folder ($mixedHandler)
  611. {
  612. $sPath = $this->getFilePath_Folder($mixedHandler);
  613. if (!$sPath)
  614. return false;
  615. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  616. if (!copy($sPath, $sTmpFile))
  617. return false;
  618. return $sTmpFile;
  619. }
  620. protected function storeFileLocally_Storage ($mixedHandler)
  621. {
  622. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  623. if (!$oStorageOriginal)
  624. return false;
  625. $aFile = $oStorageOriginal->getFile($mixedHandler);
  626. if (!$aFile)
  627. return false;
  628. $sUrl = $oStorageOriginal->getFileUrlById($mixedHandler);
  629. if (!$sUrl)
  630. return false;
  631. $sFileData = bx_file_get_contents ($sUrl);
  632. if (false === $sFileData)
  633. return false;
  634. $sTmpFile = $this->getTmpFilename ($aFile['file_name']);
  635. if (!file_put_contents($sTmpFile, $sFileData))
  636. return false;
  637. return $sTmpFile;
  638. }
  639. protected function storeFileLocally_Queue ($mixedHandler)
  640. {
  641. $aQueue = $this->_oDb->getFromQueue($mixedHandler);
  642. if (!$aQueue || !$aQueue['file_url_source'])
  643. return false;
  644. $sFileData = bx_file_get_contents ($aQueue['file_url_source']);
  645. if (false === $sFileData)
  646. return false;
  647. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  648. if (!file_put_contents($sTmpFile, $sFileData))
  649. return false;
  650. return $sTmpFile;
  651. }
  652. protected function getOrigFileUrl_Folder ($mixedHandler)
  653. {
  654. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  655. if (!file_exists(BX_DIRECTORY_PATH_ROOT . $sPath))
  656. return false;
  657. return BX_DOL_URL_ROOT . $sPath;
  658. }
  659. protected function getOrigFileUrl_Storage ($mixedHandler)
  660. {
  661. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  662. if (!$oStorageOriginal)
  663. return false;
  664. return $oStorageOriginal->getFileUrlById($mixedHandler);
  665. }
  666. protected function initFilters ()
  667. {
  668. if (false !== $this->_aObject['filters']) // filters are already initilized
  669. return;
  670. // get transcoder filters
  671. $aFilters = $this->_oDb->getTranscoderFilters();
  672. $this->_aObject['filters'] = array();
  673. foreach ($aFilters as $aFilter) {
  674. $aFilter['filter_params'] = $aFilter['filter_params'] ? unserialize($aFilter['filter_params']) : array();
  675. $this->_aObject['filters'][] = $aFilter;
  676. }
  677. }
  678. protected function clearCacheDB()
  679. {
  680. $oCacheDb = $this->_oDb->getDbCacheObject();
  681. return $oCacheDb->removeAllByPrefix('db_');
  682. }
  683. public function getDevicePixelRatioHandlerSuffix ()
  684. {
  685. $iDevicePixelRatio = $this->getDevicePixelRatio ();
  686. if ($iDevicePixelRatio >= 2)
  687. return $this->_sRetinaSuffix;
  688. return '';
  689. }
  690. protected function processHandlerForRetinaDevice ($mixedHandler)
  691. {
  692. return '' . $mixedHandler . $this->getDevicePixelRatioHandlerSuffix ();
  693. }
  694. static protected function _callFuncForObjectsArray ($mixed, $sFunc)
  695. {
  696. if (!is_array($mixed))
  697. $mixed = array($mixed);
  698. foreach ($mixed as $sObject) {
  699. $oTranscoder = self::getObjectInstance($sObject);
  700. if ($oTranscoder)
  701. $oTranscoder->$sFunc();
  702. }
  703. }
  704. /**
  705. * Get filter params
  706. * @param $sName filter name
  707. * @return array of filter params if filter was found, or false if given filter isn't enabled for the transcoder
  708. */
  709. protected function getFilterParams ($sName)
  710. {
  711. $this->initFilters ();
  712. foreach ($this->_aObject['filters'] as $aParams)
  713. if ($sName == $aParams['filter'])
  714. return $aParams['filter_params'];
  715. return false;
  716. }
  717. }
  718. /** @} */