BxDolTranscoder.php 31 KB

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