BxDolTranscoder.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825
  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. if ($o)
  115. $o->deleteFromQueue($aQueue['file_id_source']);
  116. }
  117. }
  118. /**
  119. * Store completed files from tmp queue storage to the final storage
  120. * Must be performed on the actual site.
  121. */
  122. static public function processCompleted ()
  123. {
  124. $a = BxDolTranscoderQuery::getCompletedFromQueue ();
  125. foreach ($a as $r) {
  126. $o = self::getObjectInstance($r['transcoder_object']);
  127. $aQueue = $o->getDb()->getFromQueue($r['file_id_source']);
  128. if (!$aQueue || $aQueue['status'] != BX_DOL_QUEUE_COMPLETE)
  129. continue;
  130. if ($aQueue['file_url_result'] && $aQueue['file_id_result']) {
  131. // get transcoded file from provided URL
  132. $sFileData = bx_file_get_contents ($aQueue['file_url_result']);
  133. if (false === $sFileData) {
  134. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "download file failed: {$aQueue['file_url_result']}\n");
  135. continue;
  136. }
  137. $sTmpFile = $o->getTmpFilename ('.' . $aQueue['file_ext_result']);
  138. if (!file_put_contents($sTmpFile, $sFileData)) {
  139. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "store downloaded file failed\n");
  140. @unlink($sTmpFile);
  141. continue;
  142. }
  143. // store downloaded file in final storage
  144. if ($o->storeTranscodedFile($aQueue['file_id_source'], $sTmpFile, $aQueue['profile_id']))
  145. $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)
  146. else
  147. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "store file failed:\n" . $o->getLog());
  148. // delete tmp local file
  149. @unlink($sTmpFile);
  150. }
  151. }
  152. }
  153. /**
  154. * Register handlers array
  155. * It can be called upon module enable event.
  156. * @param $mixed array of transcoders objects, or just one object
  157. */
  158. static public function registerHandlersArray ($mixed)
  159. {
  160. self::_callFuncForObjectsArray ($mixed, 'registerHandlers');
  161. }
  162. /**
  163. * Unregister handlers array
  164. * It can be called upon module disbale event.
  165. * @param $mixed array of transcoders objects, or just one object
  166. */
  167. static public function unregisterHandlersArray ($mixed)
  168. {
  169. self::_callFuncForObjectsArray ($mixed, 'unregisterHandlers');
  170. }
  171. /**
  172. * Cleanup (queue for deletion all resized files)
  173. * It can be called upon module disbale event.
  174. * @param $mixed array of transcoders objects, or just one object
  175. */
  176. static public function cleanupObjectsArray ($mixed)
  177. {
  178. self::_callFuncForObjectsArray ($mixed, 'cleanup');
  179. }
  180. /**
  181. * Called automatically, upon local(transcoded) file deletetion.
  182. */
  183. static public function onAlertResponseFileDeleteLocal ($oAlert, $sObject)
  184. {
  185. $oTranscoder = self::getObjectInstance($sObject);
  186. if (!$oTranscoder)
  187. return;
  188. if ($oAlert->sAction != 'file_deleted')
  189. return;
  190. $oTranscoder->onDeleteFileLocal($oAlert->iObject);
  191. }
  192. /**
  193. * Called automatically, upon original file deletetion.
  194. */
  195. static public function onAlertResponseFileDeleteOrig ($oAlert, $sObject)
  196. {
  197. $oTranscoder = self::getObjectInstance($sObject);
  198. if (!$oTranscoder)
  199. return;
  200. if ($oAlert->sAction != 'file_deleted')
  201. return;
  202. $oTranscoder->onDeleteFileOrig($oAlert->iObject);
  203. }
  204. /**
  205. * Called automatically, upon local(transcoded) file deletetion.
  206. */
  207. public function onDeleteFileLocal($iFileId)
  208. {
  209. return $this->_oDb->deleteFileTraces($iFileId);
  210. }
  211. /**
  212. * Called automatically, upon original file deletetion.
  213. */
  214. public function onDeleteFileOrig($mixedHandler)
  215. {
  216. // deleted files queued for transcoding
  217. $this->_oDb->deleteFromQueue ($mixedHandler);
  218. // delete main file
  219. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  220. if (!$iFileId)
  221. return false;
  222. if (!$this->_oStorage->deleteFile($iFileId))
  223. return false;
  224. // delete retina file
  225. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler . $this->_sRetinaSuffix);
  226. if ($iFileId)
  227. $this->_oStorage->deleteFile($iFileId);
  228. return true;
  229. }
  230. /**
  231. * Register necessary alert handlers for automatic deletetion of transcoded data if source file is deleted.
  232. * Make sure that you call it once, before first usage, for example upon module installation.
  233. */
  234. public function registerHandlers ()
  235. {
  236. if (!$this->_oDb->registerHandlers ())
  237. return false;
  238. return $this->clearCacheDB();
  239. }
  240. /**
  241. * Unregister alert handlers for automatic deletetion of transcoded data if source file is deleted.
  242. * Make sure that you call it once, for example upon module uninstallation.
  243. */
  244. public function unregisterHandlers ()
  245. {
  246. if (!$this->_oDb->unregisterHandlers ())
  247. return false;
  248. return $this->clearCacheDB();
  249. }
  250. /**
  251. * Delete (queue for deletion) all resized files for the current object
  252. */
  253. public function cleanup ()
  254. {
  255. return $this->_oStorage->queueFilesForDeletionFromObject();
  256. }
  257. /**
  258. * Get storage object where transcoded data is stored
  259. */
  260. public function getStorage()
  261. {
  262. return $this->_oStorage;
  263. }
  264. /**
  265. * Get database object instance
  266. */
  267. public function getDb()
  268. {
  269. return $this->_oDb;
  270. }
  271. /**
  272. * Get transcoded file url.
  273. * If transcoded file is ready then direct url to the file is returned.
  274. * 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.
  275. * @params $mixedHandler - file handler
  276. * @return file url, or false on error.
  277. */
  278. public function getFileUrl($mixedHandler)
  279. {
  280. if ($this->isFileReady($mixedHandler)) {
  281. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  282. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  283. if (!$iFileId)
  284. return false;
  285. $aFile = $this->_oStorage->getFile($iFileId);
  286. if (!$aFile)
  287. return false;
  288. if ($this->_aObject['atime_tracking'])
  289. $this->_oDb->updateAccessTime($mixedHandler);
  290. return $this->_oStorage->getFileUrlById($iFileId);
  291. }
  292. if ($this->_sQueueTable && !$this->addToQueue($mixedHandler)) // add file to queue (when queue is enabled) if it isn't transcoded yet
  293. return false;
  294. return $this->getFileUrlNotReady($mixedHandler);
  295. }
  296. /**
  297. * alias for @see getFileUrl
  298. */
  299. public function getFileUrlById($mixedHandler)
  300. {
  301. return $this->getFileUrl($mixedHandler);
  302. }
  303. /**
  304. * Check if transcoded data is available. No need to call it directly, it is called automatically when it is needed.
  305. * @params $mixedHandler - file handler
  306. * @params $isCheckOutdated - check if transcoded file is outdated
  307. * @return false if there is no ready transcoded file is available or it is outdated, true if file is ready
  308. */
  309. public function isFileReady ($mixedHandler, $isCheckOutdated = true)
  310. {
  311. $sMethodFileReady = 'isFileReady_' . $this->_aObject['source_type'];
  312. return $this->$sMethodFileReady($mixedHandler, $isCheckOutdated);
  313. }
  314. /**
  315. * Transcode file, no need to call it directly, it is called automatically when it is needed.
  316. * @params $mixedHandler - file handler
  317. * @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
  318. * @return true on success, false on error
  319. */
  320. public function transcode ($mixedHandler, $iProfileId = 0)
  321. {
  322. $sExtChange = false;
  323. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_PROCESSING, '', gethostname());
  324. // create tmp file locally
  325. $sSuffix = $this->_sQueueStorage ? 'Queue' : $this->_aObject['source_type'];
  326. $sMethodStoreFile = 'storeFileLocally_' . $sSuffix;
  327. $sTmpFile = $this->$sMethodStoreFile($mixedHandler);
  328. if (!$sTmpFile) {
  329. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store local tmp file failed ($sMethodStoreFile)");
  330. return false;
  331. }
  332. // appply filters to tmp file
  333. $this->initFilters ();
  334. foreach ($this->_aObject['filters'] as $aParams) {
  335. $this->clearLog();
  336. $sMethodFilter = 'applyFilter_' . $aParams['filter'];
  337. if (!method_exists($this, $sMethodFilter))
  338. continue;
  339. if (!$this->$sMethodFilter($sTmpFile, $aParams['filter_params'])) {
  340. unlink($sTmpFile);
  341. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "filter failed: $sMethodFilter\n" . $this->getLog());
  342. return false;
  343. }
  344. if (!empty($aParams['filter_params']['force_type'])) {
  345. switch ($aParams['filter_params']['force_type']) {
  346. case 'jpeg':
  347. case 'jpg':
  348. $sExtChange = 'jpg';
  349. break;
  350. default:
  351. $sExtChange = $aParams['filter_params']['force_type'];
  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. }
  368. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  369. $bRet = true;
  370. if ($this->_sQueueStorage) {
  371. $sFileUrlResult = '';
  372. if (!($iFileIdResult = $this->storeTranscodedFileInQueueStorage($mixedHandler, $sTmpFile, $sFileUrlResult)))
  373. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store queue tmp file failed:\n" . $this->getLog());
  374. else
  375. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_COMPLETE, '', '', $iFileIdResult, $sFileUrlResult, $sExtChange);
  376. } else {
  377. $bRet = $this->storeTranscodedFile($mixedHandler, $sTmpFile, $iProfileId);
  378. if ($bRet)
  379. $this->deleteFromQueue($mixedHandler);
  380. else
  381. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store file failed:\n" . $this->getLog());
  382. }
  383. @unlink($sTmpFile);
  384. return $bRet;
  385. }
  386. /**
  387. * Delete outdated files by last access time.
  388. * @return number of pruned/deleted files
  389. */
  390. public function prune ()
  391. {
  392. $aFiles = $this->_oDb->getFilesForPruning();
  393. if (!$aFiles)
  394. return false;
  395. $iCount = 0;
  396. foreach ($aFiles as $r)
  397. $iCount += $this->_oStorage->deleteFile($r['file_id']) ? 1 : 0;
  398. return $iCount;
  399. }
  400. public function getDevicePixelRatio ()
  401. {
  402. if (isset($_COOKIE['devicePixelRatio']) && (!isset($this->_aObject['source_params']['disable_retina']) || !$this->_aObject['source_params']['disable_retina'])) {
  403. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  404. if ($iDevicePixelRatio >= 2)
  405. return 2;
  406. }
  407. return 1;
  408. }
  409. public function getOrigFileUrl ($mixedHandler)
  410. {
  411. $sMethodStoreFile = 'getOrigFileUrl_' . $this->_aObject['source_type'];
  412. return $this->$sMethodStoreFile($mixedHandler);
  413. }
  414. /**
  415. * Get file url when file isn't transcoded yet
  416. */
  417. public function getFileUrlNotReady($mixedHandler)
  418. {
  419. return false;
  420. }
  421. public function getTmpFilename ($sOverrideName = false)
  422. {
  423. if ($sOverrideName)
  424. return BX_DIRECTORY_PATH_TMP . rand(10000, 99999) . $sOverrideName;
  425. return tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
  426. }
  427. public function clearLog()
  428. {
  429. $this->_sLog = '';
  430. }
  431. public function addToLog($s)
  432. {
  433. $this->_sLog .= $s;
  434. }
  435. public function getLog()
  436. {
  437. return $this->_sLog;
  438. }
  439. public function deleteFromQueue ($mixedHandler)
  440. {
  441. $sErrMsg = "delete queue tmp file failed:\n";
  442. $a = $this->_oDb->getFromQueue($mixedHandler);
  443. if (!$a || $a['server'] != gethostname()) // deletion must be performed on the server where it was transcoded
  444. return false;
  445. if ($a['file_id_result'] && $this->_sQueueStorage && 0 != strncmp($a['log'], $sErrMsg, strlen($sErrMsg))) {
  446. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  447. if (!$oStorage->deleteFile($a['file_id_result'])) {
  448. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, $sErrMsg . $this->getLog());
  449. return false;
  450. }
  451. }
  452. return $this->_oDb->deleteFromQueue($mixedHandler);
  453. }
  454. public function storeTranscodedFile ($mixedHandler, $sTmpFile, $iProfileId)
  455. {
  456. $sMethodIsPrivate = 'isPrivate_' . $this->_aObject['source_type'];
  457. $isPrivate = $this->$sMethodIsPrivate($mixedHandler);
  458. $iFileId = $this->_oStorage->storeFileFromPath ($sTmpFile, $isPrivate, $iProfileId);
  459. if (!$iFileId) {
  460. $this->addToLog($this->_oStorage->getErrorString());
  461. return false;
  462. }
  463. if (!$this->_oDb->updateHandler($iFileId, $mixedHandler)) {
  464. $this->_oStorage->deleteFile($iFileId);
  465. return false;
  466. }
  467. $this->_oStorage->afterUploadCleanup($iFileId, $iProfileId);
  468. return true;
  469. }
  470. protected function storeTranscodedFileInQueueStorage ($mixedHandler, $sTmpFile, &$sFileUrlResult)
  471. {
  472. if (!$this->_sQueueStorage)
  473. return false;
  474. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  475. $iFileIdResult = $oStorage->storeFileFromPath ($sTmpFile, 1, 0);
  476. if (!$iFileIdResult) {
  477. $this->addToLog($oStorage->getErrorString());
  478. return false;
  479. }
  480. if (!($sFileUrlResult = $oStorage->getFileUrlById($iFileIdResult))) {
  481. $this->_oStorage->deleteFile($iFileIdResult);
  482. return false;
  483. }
  484. $oStorage->afterUploadCleanup($iFileIdResult, 0);
  485. return $iFileIdResult;
  486. }
  487. protected function addToQueue($mixedHandler, $iProfileId = 0)
  488. {
  489. if ($this->_oDb->getFromQueue($mixedHandler))
  490. return true;
  491. $sFileUrl = $this->getOrigFileUrl($mixedHandler);
  492. return $this->_oDb->addToQueue ($mixedHandler, $sFileUrl, $iProfileId);
  493. }
  494. protected function applyFilter_Resize ($sFile, $aParams)
  495. {
  496. $o = BxDolImageResize::getInstance();
  497. $o->removeCropOptions ();
  498. $o->setSize (isset($aParams['w']) ? round($aParams['w'] * $this->getDevicePixelRatio()) : null, isset($aParams['h']) ? round($aParams['h'] * $this->getDevicePixelRatio()) : null);
  499. if (isset($aParams['crop_resize']) && $aParams['crop_resize'])
  500. $o->setAutoCrop (true);
  501. elseif (isset($aParams['square_resize']) && $aParams['square_resize'])
  502. $o->setSquareResize (true);
  503. else
  504. $o->setSquareResize (false);
  505. if (IMAGE_ERROR_SUCCESS == $o->resize($sFile))
  506. return true;
  507. return false;
  508. }
  509. protected function isFileReady_Folder ($mixedHandlerOrig, $isCheckOutdated = true)
  510. {
  511. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  512. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  513. if (!$iFileId)
  514. return false;
  515. $aFile = $this->_oStorage->getFile($iFileId);
  516. if (!$aFile)
  517. return false;
  518. if ($isCheckOutdated) { // warning, $isCheckOutdated is partially supported for Folder source type - file modification is not checked
  519. if ($this->_aObject['ts'] > $aFile['modified'] || !$this->getFilePath_Folder($mixedHandlerOrig)) { // if we changed transcoder object params or original file is deleted
  520. // delete file, so it will be recreated next time
  521. if ($this->_oStorage->deleteFile($aFile['id']))
  522. return false;
  523. }
  524. }
  525. return true;
  526. }
  527. protected function isFileReady_Storage ($mixedHandlerOrig, $isCheckOutdated = true)
  528. {
  529. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  530. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  531. if (!$iFileId)
  532. return false;
  533. $aFile = $this->_oStorage->getFile($iFileId);
  534. if (!$aFile)
  535. return false;
  536. if ($isCheckOutdated) {
  537. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  538. if ($oStorageOriginal) {
  539. $aFileOriginal = $oStorageOriginal->getFile($mixedHandlerOrig);
  540. if (!$aFileOriginal || $aFileOriginal['modified'] > $aFile['modified'] || $this->_aObject['ts'] >= $aFile['modified']) { // if original file was changed OR we changed transcoder object params
  541. // delete file, so it will be recreated next time
  542. if ($this->_oStorage->deleteFile($aFile['id']))
  543. return false;
  544. }
  545. }
  546. }
  547. return true;
  548. }
  549. protected function isPrivate_Folder ($mixedHandler)
  550. {
  551. if ('no' == $this->_aObject['private'])
  552. return false;
  553. return true;
  554. }
  555. protected function isPrivate_Storage ($mixedHandler)
  556. {
  557. switch ($this->_aObject['private']) {
  558. case 'no':
  559. return false;
  560. case 'yes':
  561. return true;
  562. default:
  563. case 'auto':
  564. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  565. if (!$oStorageOriginal)
  566. return true; // in case of error - make sure that file is not public accidentally
  567. $aFile = $oStorageOriginal->getFile($mixedHandler);
  568. return $oStorageOriginal->isFilePrivate($aFile['id']);
  569. }
  570. }
  571. protected function getFilePath_Folder ($mixedHandler)
  572. {
  573. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  574. if (!file_exists($sPath))
  575. $sPath = BX_DIRECTORY_PATH_ROOT . $sPath;
  576. if (!file_exists($sPath))
  577. return false;
  578. return $sPath;
  579. }
  580. protected function storeFileLocally_Folder ($mixedHandler)
  581. {
  582. $sPath = $this->getFilePath_Folder($mixedHandler);
  583. if (!$sPath)
  584. return false;
  585. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  586. if (!copy($sPath, $sTmpFile))
  587. return false;
  588. return $sTmpFile;
  589. }
  590. protected function storeFileLocally_Storage ($mixedHandler)
  591. {
  592. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  593. if (!$oStorageOriginal)
  594. return false;
  595. $aFile = $oStorageOriginal->getFile($mixedHandler);
  596. if (!$aFile)
  597. return false;
  598. $sUrl = $oStorageOriginal->getFileUrlById($mixedHandler);
  599. if (!$sUrl)
  600. return false;
  601. $sFileData = bx_file_get_contents ($sUrl);
  602. if (false === $sFileData)
  603. return false;
  604. $sTmpFile = $this->getTmpFilename ($aFile['file_name']);
  605. if (!file_put_contents($sTmpFile, $sFileData))
  606. return false;
  607. return $sTmpFile;
  608. }
  609. protected function storeFileLocally_Queue ($mixedHandler)
  610. {
  611. $aQueue = $this->_oDb->getFromQueue($mixedHandler);
  612. if (!$aQueue || !$aQueue['file_url_source'])
  613. return false;
  614. $sFileData = bx_file_get_contents ($aQueue['file_url_source']);
  615. if (false === $sFileData)
  616. return false;
  617. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  618. if (!file_put_contents($sTmpFile, $sFileData))
  619. return false;
  620. return $sTmpFile;
  621. }
  622. protected function getOrigFileUrl_Folder ($mixedHandler)
  623. {
  624. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  625. if (!file_exists(BX_DIRECTORY_PATH_ROOT . $sPath))
  626. return false;
  627. return BX_DOL_URL_ROOT . $sPath;
  628. }
  629. protected function getOrigFileUrl_Storage ($mixedHandler)
  630. {
  631. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  632. if (!$oStorageOriginal)
  633. return false;
  634. return $oStorageOriginal->getFileUrlById($mixedHandler);
  635. }
  636. protected function initFilters ()
  637. {
  638. if (false !== $this->_aObject['filters']) // filters are already initilized
  639. return;
  640. // get transcoder filters
  641. $aFilters = $this->_oDb->getTranscoderFilters();
  642. $this->_aObject['filters'] = array();
  643. foreach ($aFilters as $aFilter) {
  644. $aFilter['filter_params'] = $aFilter['filter_params'] ? unserialize($aFilter['filter_params']) : array();
  645. $this->_aObject['filters'][] = $aFilter;
  646. }
  647. }
  648. protected function clearCacheDB()
  649. {
  650. $oCacheDb = $this->_oDb->getDbCacheObject();
  651. return $oCacheDb->removeAllByPrefix('db_');
  652. }
  653. public function getDevicePixelRatioHandlerSuffix ()
  654. {
  655. $iDevicePixelRatio = $this->getDevicePixelRatio ();
  656. if ($iDevicePixelRatio >= 2)
  657. return $this->_sRetinaSuffix;
  658. return '';
  659. }
  660. protected function processHandlerForRetinaDevice ($mixedHandler)
  661. {
  662. return '' . $mixedHandler . $this->getDevicePixelRatioHandlerSuffix ();
  663. }
  664. static protected function _callFuncForObjectsArray ($mixed, $sFunc)
  665. {
  666. if (!is_array($mixed))
  667. $mixed = array($mixed);
  668. foreach ($mixed as $sObject) {
  669. $oTranscoder = self::getObjectInstance($sObject);
  670. if ($oTranscoder)
  671. $oTranscoder->$sFunc();
  672. }
  673. }
  674. /**
  675. * Get filter params
  676. * @param $sName filter name
  677. * @return array of filter params if filter was found, or false if given filter isn't enabled for the transcoder
  678. */
  679. protected function getFilterParams ($sName)
  680. {
  681. $this->initFilters ();
  682. foreach ($this->_aObject['filters'] as $aParams)
  683. if ($sName == $aParams['filter'])
  684. return $aParams['filter_params'];
  685. return false;
  686. }
  687. }
  688. /** @} */