BxDolTranscoder.php 30 KB

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