BxDolTranscoder.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. $aQueue = $o->getDb()->getFromQueue($r['file_id_source']);
  104. if (!$aQueue || $aQueue['status'] != BX_DOL_QUEUE_PENDING)
  105. continue;
  106. $o->transcode($aQueue['file_id_source'], $aQueue['profile_id']);
  107. }
  108. }
  109. static public function pruneQueue ()
  110. {
  111. $a = BxDolTranscoderQuery::getForDeletionFromQueue (gethostname());
  112. if (!$a)
  113. return false;
  114. foreach ($a as $aQueue) {
  115. $o = self::getObjectInstance($aQueue['transcoder_object']);
  116. if ($o)
  117. $o->deleteFromQueue($aQueue['file_id_source']);
  118. }
  119. }
  120. /**
  121. * Store completed files from tmp queue storage to the final storage
  122. * Must be performed on the actual site.
  123. */
  124. static public function processCompleted ()
  125. {
  126. $a = BxDolTranscoderQuery::getCompletedFromQueue ();
  127. foreach ($a as $r) {
  128. $o = self::getObjectInstance($r['transcoder_object']);
  129. $aQueue = $o->getDb()->getFromQueue($r['file_id_source']);
  130. if (!$aQueue || $aQueue['status'] != BX_DOL_QUEUE_COMPLETE)
  131. continue;
  132. if ($aQueue['file_url_result'] && $aQueue['file_id_result']) {
  133. // get transcoded file from provided URL
  134. $sFileData = bx_file_get_contents ($aQueue['file_url_result']);
  135. if (false === $sFileData) {
  136. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "download file failed: {$aQueue['file_url_result']}\n");
  137. continue;
  138. }
  139. $sTmpFile = $o->getTmpFilename ('.' . $aQueue['file_ext_result']);
  140. if (!file_put_contents($sTmpFile, $sFileData)) {
  141. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "store downloaded file failed\n");
  142. @unlink($sTmpFile);
  143. continue;
  144. }
  145. // store downloaded file in final storage
  146. if ($o->storeTranscodedFile($aQueue['file_id_source'], $sTmpFile, $aQueue['profile_id']))
  147. $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)
  148. else
  149. $o->getDb()->updateQueueStatus($aQueue['file_id_source'], BX_DOL_QUEUE_FAILED, "store file failed:\n" . $o->getLog());
  150. // delete tmp local file
  151. @unlink($sTmpFile);
  152. }
  153. }
  154. }
  155. /**
  156. * Register handlers array
  157. * It can be called upon module enable event.
  158. * @param $mixed array of transcoders objects, or just one object
  159. */
  160. static public function registerHandlersArray ($mixed)
  161. {
  162. self::_callFuncForObjectsArray ($mixed, 'registerHandlers');
  163. }
  164. /**
  165. * Register system handlers
  166. */
  167. static public function registerHandlersSystem()
  168. {
  169. $sPrefix = 'sys_';
  170. $aResults = array();
  171. $aTranscoders = BxDolTranscoderQuery::getTranscoderObjects();
  172. foreach($aTranscoders as $aTranscoder) {
  173. if(strncasecmp($aTranscoder['object'], $sPrefix, strlen($sPrefix)) !== 0)
  174. continue;
  175. $aResults[] = $aTranscoder['object'];
  176. }
  177. if(!empty($aResults))
  178. self::registerHandlersArray($aResults);
  179. }
  180. /**
  181. * Unregister handlers array
  182. * It can be called upon module disbale event.
  183. * @param $mixed array of transcoders objects, or just one object
  184. */
  185. static public function unregisterHandlersArray ($mixed)
  186. {
  187. self::_callFuncForObjectsArray ($mixed, 'unregisterHandlers');
  188. }
  189. /**
  190. * Cleanup (queue for deletion all resized files)
  191. * It can be called upon module disbale event.
  192. * @param $mixed array of transcoders objects, or just one object
  193. */
  194. static public function cleanupObjectsArray ($mixed)
  195. {
  196. self::_callFuncForObjectsArray ($mixed, 'cleanup');
  197. }
  198. /**
  199. * Called automatically, upon local(transcoded) file deletetion.
  200. */
  201. static public function onAlertResponseFileDeleteLocal ($oAlert, $sObject)
  202. {
  203. $oTranscoder = self::getObjectInstance($sObject);
  204. if (!$oTranscoder)
  205. return;
  206. if ($oAlert->sAction != 'file_deleted')
  207. return;
  208. $oTranscoder->onDeleteFileLocal($oAlert->iObject);
  209. }
  210. /**
  211. * Called automatically, upon original file deletetion.
  212. */
  213. static public function onAlertResponseFileDeleteOrig ($oAlert, $sObject)
  214. {
  215. $oTranscoder = self::getObjectInstance($sObject);
  216. if (!$oTranscoder)
  217. return;
  218. if ($oAlert->sAction != 'file_deleted')
  219. return;
  220. $oTranscoder->onDeleteFileOrig($oAlert->iObject);
  221. }
  222. /**
  223. * Called automatically, upon local(transcoded) file deletetion.
  224. */
  225. public function onDeleteFileLocal($iFileId)
  226. {
  227. return $this->_oDb->deleteFileTraces($iFileId);
  228. }
  229. /**
  230. * Called automatically, upon original file deletetion.
  231. */
  232. public function onDeleteFileOrig($mixedHandler)
  233. {
  234. // deleted files queued for transcoding
  235. $this->_oDb->deleteFromQueue ($mixedHandler);
  236. // delete main file
  237. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  238. if (!$iFileId)
  239. return false;
  240. if (!$this->_oStorage->deleteFile($iFileId))
  241. return false;
  242. // delete retina file
  243. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler . $this->_sRetinaSuffix);
  244. if ($iFileId)
  245. $this->_oStorage->deleteFile($iFileId);
  246. return true;
  247. }
  248. /**
  249. * Register necessary alert handlers for automatic deletetion of transcoded data if source file is deleted.
  250. * Make sure that you call it once, before first usage, for example upon module installation.
  251. */
  252. public function registerHandlers ()
  253. {
  254. if (!$this->_oDb->registerHandlers ())
  255. return false;
  256. return $this->clearCacheDB();
  257. }
  258. /**
  259. * Unregister alert handlers for automatic deletetion of transcoded data if source file is deleted.
  260. * Make sure that you call it once, for example upon module uninstallation.
  261. */
  262. public function unregisterHandlers ()
  263. {
  264. if (!$this->_oDb->unregisterHandlers ())
  265. return false;
  266. return $this->clearCacheDB();
  267. }
  268. /**
  269. * Delete (queue for deletion) all resized files for the current object
  270. */
  271. public function cleanup ()
  272. {
  273. return $this->_oStorage->queueFilesForDeletionFromObject();
  274. }
  275. /**
  276. * Get storage object where transcoded data is stored
  277. */
  278. public function getStorage()
  279. {
  280. return $this->_oStorage;
  281. }
  282. /**
  283. * Get database object instance
  284. */
  285. public function getDb()
  286. {
  287. return $this->_oDb;
  288. }
  289. /**
  290. * check if transcoder suppors given file mime type
  291. */
  292. public function isMimeTypeSupported($sMimeType)
  293. {
  294. return false;
  295. }
  296. /**
  297. * Get transcoded file url.
  298. * If transcoded file is ready then direct url to the file is returned.
  299. * 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.
  300. * @param $mixedHandler - file handler
  301. * @return file url, or false on error.
  302. */
  303. public function getFileUrl($mixedHandler)
  304. {
  305. if ($this->isFileReady($mixedHandler)) {
  306. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  307. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  308. if (!$iFileId)
  309. return false;
  310. $aFile = $this->_oStorage->getFile($iFileId);
  311. if (!$aFile)
  312. return false;
  313. if ($this->_aObject['atime_tracking'])
  314. $this->_oDb->updateAccessTime($mixedHandler);
  315. return $this->_oStorage->getFileUrlById($iFileId);
  316. }
  317. if ($this->_sQueueTable && !$this->addToQueue($mixedHandler)) // add file to queue (when queue is enabled) if it isn't transcoded yet
  318. return false;
  319. return $this->getFileUrlNotReady($mixedHandler);
  320. }
  321. /**
  322. * alias for @see getFileUrl
  323. */
  324. public function getFileUrlById($mixedHandler)
  325. {
  326. return $this->getFileUrl($mixedHandler);
  327. }
  328. /**
  329. * Check if transcoded data is available. No need to call it directly, it is called automatically when it is needed.
  330. * @param $mixedHandler - file handler
  331. * @param $isCheckOutdated - check if transcoded file is outdated
  332. * @return false if there is no ready transcoded file is available or it is outdated, true if file is ready
  333. */
  334. public function isFileReady ($mixedHandler, $isCheckOutdated = true)
  335. {
  336. $sMethodFileReady = 'isFileReady_' . $this->_aObject['source_type'];
  337. return $this->$sMethodFileReady($mixedHandler, $isCheckOutdated);
  338. }
  339. /**
  340. * Transcode file, no need to call it directly, it is called automatically when it is needed.
  341. * @param $mixedHandler - file handler
  342. * @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
  343. * @return true on success, false on error
  344. */
  345. public function transcode ($mixedHandler, $iProfileId = 0)
  346. {
  347. $sExtChange = false;
  348. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_PROCESSING, '', gethostname());
  349. // create tmp file locally
  350. $sSuffix = $this->_sQueueStorage ? 'Queue' : $this->_aObject['source_type'];
  351. $sMethodStoreFile = 'storeFileLocally_' . $sSuffix;
  352. $sTmpFile = $this->$sMethodStoreFile($mixedHandler);
  353. if (!$sTmpFile) {
  354. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store local tmp file failed ($sMethodStoreFile)");
  355. return false;
  356. }
  357. // appply filters to tmp file
  358. $this->initFilters ();
  359. foreach ($this->_aObject['filters'] as $aParams) {
  360. $this->clearLog();
  361. $sMethodFilter = 'applyFilter_' . $aParams['filter'];
  362. if (!method_exists($this, $sMethodFilter))
  363. continue;
  364. if (!$this->$sMethodFilter($sTmpFile, $aParams['filter_params'])) {
  365. unlink($sTmpFile);
  366. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "filter failed: $sMethodFilter\n" . $this->getLog());
  367. return false;
  368. }
  369. if (!empty($aParams['filter_params']['force_type'])) {
  370. switch ($aParams['filter_params']['force_type']) {
  371. case 'jpeg':
  372. case 'jpg':
  373. $sExtChange = 'jpg';
  374. break;
  375. default:
  376. $sExtChange = $aParams['filter_params']['force_type'];
  377. }
  378. }
  379. if ($sExtChange) {
  380. $iDotPos = strrpos($sTmpFile, '.');
  381. $sExtOld = false === $iDotPos ? '' : substr($sTmpFile, $iDotPos+1);
  382. if ($sExtOld != $sExtChange) {
  383. $sTmpFileOld = $sTmpFile;
  384. $sTmpFile = false === $iDotPos ? $sTmpFile . '.' . $sExtChange : substr_replace($sTmpFile, $sExtChange, $iDotPos+1, strlen($sExtOld));
  385. if (!rename($sTmpFileOld, $sTmpFile)) {
  386. @unlink($sTmpFileOld);
  387. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "change file extension failed: $sTmpFileOld => $sTmpFile");
  388. return false;
  389. }
  390. }
  391. }
  392. }
  393. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  394. $bRet = true;
  395. if ($this->_sQueueStorage) {
  396. $sFileUrlResult = '';
  397. if (!($iFileIdResult = $this->storeTranscodedFileInQueueStorage($mixedHandler, $sTmpFile, $sFileUrlResult)))
  398. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store queue tmp file failed:\n" . $this->getLog());
  399. else
  400. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_COMPLETE, '', '', $iFileIdResult, $sFileUrlResult, $sExtChange);
  401. } else {
  402. $bRet = $this->storeTranscodedFile($mixedHandler, $sTmpFile, $iProfileId);
  403. if ($bRet)
  404. $this->deleteFromQueue($mixedHandler);
  405. else
  406. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store file failed:\n" . $this->getLog());
  407. }
  408. @unlink($sTmpFile);
  409. return $bRet;
  410. }
  411. /**
  412. * Delete outdated files by last access time.
  413. * @return number of pruned/deleted files
  414. */
  415. public function prune ()
  416. {
  417. $aFiles = $this->_oDb->getFilesForPruning();
  418. if (!$aFiles)
  419. return false;
  420. $iCount = 0;
  421. foreach ($aFiles as $r)
  422. $iCount += $this->_oStorage->deleteFile($r['file_id']) ? 1 : 0;
  423. return $iCount;
  424. }
  425. public function forceDevicePixelRatio ($i)
  426. {
  427. if (!$i)
  428. $this->_iDevicePixelRatio = false;
  429. elseif ($i >= 2)
  430. $this->_iDevicePixelRatio = 2;
  431. else
  432. $this->_iDevicePixelRatio = 1;
  433. }
  434. public function getDevicePixelRatio ()
  435. {
  436. $iRet = 1;
  437. if ($this->_iDevicePixelRatio) {
  438. $iRet = $this->_iDevicePixelRatio;
  439. }
  440. elseif (isset($_COOKIE['devicePixelRatio']) && (!isset($this->_aObject['source_params']['disable_retina']) || !$this->_aObject['source_params']['disable_retina'])) {
  441. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  442. if ($iDevicePixelRatio >= 2)
  443. $iRet = 2;
  444. }
  445. // don't resize images on mobile if they are already big enough
  446. if ($iRet > 1 && $this->isMobile() && $this->getMaxResizeDimention() >= BX_DOL_MAX_RETINA_DIMENSION_MOBILE)
  447. $iRet = 1;
  448. return $iRet;
  449. }
  450. public function getOrigFileUrl ($mixedHandler)
  451. {
  452. $sMethodStoreFile = 'getOrigFileUrl_' . $this->_aObject['source_type'];
  453. return $this->$sMethodStoreFile($mixedHandler);
  454. }
  455. /**
  456. * Get file url when file isn't transcoded yet
  457. */
  458. public function getFileUrlNotReady($mixedHandler)
  459. {
  460. return false;
  461. }
  462. public function getTmpFilename ($sOverrideName = false)
  463. {
  464. if ($sOverrideName)
  465. return BX_DIRECTORY_PATH_TMP . rand(10000, 99999) . $sOverrideName;
  466. return tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
  467. }
  468. public function clearLog()
  469. {
  470. $this->_sLog = '';
  471. }
  472. public function addToLog($s)
  473. {
  474. $this->_sLog .= $s;
  475. }
  476. public function getLog()
  477. {
  478. return $this->_sLog;
  479. }
  480. public function deleteFromQueue ($mixedHandler)
  481. {
  482. $sErrMsg = "delete queue tmp file failed:\n";
  483. $a = $this->_oDb->getFromQueue($mixedHandler);
  484. if (!$a || $a['server'] != gethostname()) // deletion must be performed on the server where it was transcoded
  485. return false;
  486. if ($a['file_id_result'] && $this->_sQueueStorage && 0 !== strncmp($a['log'], $sErrMsg, strlen($sErrMsg))) {
  487. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  488. if (!$oStorage->deleteFile($a['file_id_result'])) {
  489. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, $sErrMsg . $this->getLog());
  490. return false;
  491. }
  492. }
  493. return $this->_oDb->deleteFromQueue($mixedHandler);
  494. }
  495. public function storeTranscodedFile ($mixedHandler, $sTmpFile, $iProfileId)
  496. {
  497. $sMethodIsPrivate = 'isPrivate_' . $this->_aObject['source_type'];
  498. $isPrivate = $this->$sMethodIsPrivate($mixedHandler);
  499. $iFileId = $this->_oStorage->storeFileFromPath ($sTmpFile, $isPrivate, $iProfileId);
  500. if (!$iFileId) {
  501. $this->addToLog($this->_oStorage->getErrorString());
  502. return false;
  503. }
  504. if (!$this->_oDb->updateHandler($iFileId, $mixedHandler)) {
  505. $this->_oStorage->deleteFile($iFileId);
  506. return false;
  507. }
  508. $this->_oStorage->afterUploadCleanup($iFileId, $iProfileId);
  509. return true;
  510. }
  511. protected function storeTranscodedFileInQueueStorage ($mixedHandler, $sTmpFile, &$sFileUrlResult)
  512. {
  513. if (!$this->_sQueueStorage)
  514. return false;
  515. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  516. $iFileIdResult = $oStorage->storeFileFromPath ($sTmpFile, 1, 0);
  517. if (!$iFileIdResult) {
  518. $this->addToLog($oStorage->getErrorString());
  519. return false;
  520. }
  521. if (!($sFileUrlResult = $oStorage->getFileUrlById($iFileIdResult))) {
  522. $this->_oStorage->deleteFile($iFileIdResult);
  523. return false;
  524. }
  525. $oStorage->afterUploadCleanup($iFileIdResult, 0);
  526. return $iFileIdResult;
  527. }
  528. protected function addToQueue($mixedHandler, $iProfileId = 0)
  529. {
  530. if ($this->_oDb->getFromQueue($mixedHandler))
  531. return true;
  532. $sFileUrl = $this->getOrigFileUrl($mixedHandler);
  533. return $this->_oDb->addToQueue ($mixedHandler, $sFileUrl, $iProfileId);
  534. }
  535. protected function applyFilter_Resize ($sFile, $aParams)
  536. {
  537. $o = BxDolImageResize::getInstance();
  538. $o->removeCropOptions ();
  539. $o->setSize (isset($aParams['w']) ? round($aParams['w'] * $this->getDevicePixelRatio()) : null, isset($aParams['h']) ? round($aParams['h'] * $this->getDevicePixelRatio()) : null);
  540. if (isset($aParams['crop_resize']) && $aParams['crop_resize'])
  541. $o->setAutoCrop (true);
  542. elseif (isset($aParams['square_resize']) && $aParams['square_resize'])
  543. $o->setSquareResize (true);
  544. else
  545. $o->setSquareResize (false);
  546. if (IMAGE_ERROR_SUCCESS == $o->resize($sFile))
  547. return true;
  548. return false;
  549. }
  550. protected function isFileReady_Folder ($mixedHandlerOrig, $isCheckOutdated = true)
  551. {
  552. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  553. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  554. if (!$iFileId)
  555. return false;
  556. $aFile = $this->_oStorage->getFile($iFileId);
  557. if (!$aFile)
  558. return false;
  559. if ($isCheckOutdated) { // warning, $isCheckOutdated is partially supported for Folder source type - file modification is not checked
  560. if ($this->_aObject['ts'] > $aFile['modified'] || !$this->getFilePath_Folder($mixedHandlerOrig)) { // if we changed transcoder object params or original file is deleted
  561. // delete file, so it will be recreated next time
  562. if ($this->_oStorage->deleteFile($aFile['id']))
  563. return false;
  564. }
  565. }
  566. return true;
  567. }
  568. protected function isFileReady_Storage ($mixedHandlerOrig, $isCheckOutdated = true)
  569. {
  570. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  571. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  572. if (!$iFileId)
  573. return false;
  574. $aFile = $this->_oStorage->getFile($iFileId);
  575. if (!$aFile)
  576. return false;
  577. if ($isCheckOutdated) {
  578. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  579. if ($oStorageOriginal) {
  580. $aFileOriginal = $oStorageOriginal->getFile($mixedHandlerOrig);
  581. if (!$aFileOriginal || $aFileOriginal['modified'] > $aFile['modified'] || $this->_aObject['ts'] >= $aFile['modified']) { // if original file was changed OR we changed transcoder object params
  582. // delete file, so it will be recreated next time
  583. if ($this->_oStorage->deleteFile($aFile['id']))
  584. return false;
  585. }
  586. }
  587. }
  588. return true;
  589. }
  590. protected function isPrivate_Folder ($mixedHandler)
  591. {
  592. if ('no' == $this->_aObject['private'])
  593. return false;
  594. return true;
  595. }
  596. protected function isPrivate_Storage ($mixedHandler)
  597. {
  598. switch ($this->_aObject['private']) {
  599. case 'no':
  600. return false;
  601. case 'yes':
  602. return true;
  603. default:
  604. case 'auto':
  605. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  606. if (!$oStorageOriginal)
  607. return true; // in case of error - make sure that file is not public accidentally
  608. $aFile = $oStorageOriginal->getFile($mixedHandler);
  609. return $oStorageOriginal->isFilePrivate($aFile['id']);
  610. }
  611. }
  612. protected function getFilePath_Folder ($mixedHandler)
  613. {
  614. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  615. if (!file_exists($sPath))
  616. $sPath = BX_DIRECTORY_PATH_ROOT . $sPath;
  617. if (!file_exists($sPath))
  618. return false;
  619. return $sPath;
  620. }
  621. protected function storeFileLocally_Folder ($mixedHandler)
  622. {
  623. $sPath = $this->getFilePath_Folder($mixedHandler);
  624. if (!$sPath)
  625. return false;
  626. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  627. if (!copy($sPath, $sTmpFile))
  628. return false;
  629. return $sTmpFile;
  630. }
  631. protected function storeFileLocally_Storage ($mixedHandler)
  632. {
  633. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  634. if (!$oStorageOriginal)
  635. return false;
  636. $aFile = $oStorageOriginal->getFile($mixedHandler);
  637. if (!$aFile)
  638. return false;
  639. $sUrl = $oStorageOriginal->getFileUrlById($mixedHandler);
  640. if (!$sUrl)
  641. return false;
  642. $sFileData = bx_file_get_contents ($sUrl);
  643. if (false === $sFileData)
  644. return false;
  645. $sTmpFile = $this->getTmpFilename ($aFile['file_name']);
  646. if (!file_put_contents($sTmpFile, $sFileData))
  647. return false;
  648. return $sTmpFile;
  649. }
  650. protected function storeFileLocally_Queue ($mixedHandler)
  651. {
  652. $aQueue = $this->_oDb->getFromQueue($mixedHandler);
  653. if (!$aQueue || !$aQueue['file_url_source'])
  654. return false;
  655. $sFileData = bx_file_get_contents ($aQueue['file_url_source']);
  656. if (false === $sFileData)
  657. return false;
  658. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  659. if (!file_put_contents($sTmpFile, $sFileData))
  660. return false;
  661. return $sTmpFile;
  662. }
  663. protected function getOrigFileUrl_Folder ($mixedHandler)
  664. {
  665. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  666. if (!file_exists(BX_DIRECTORY_PATH_ROOT . $sPath))
  667. return false;
  668. return BX_DOL_URL_ROOT . $sPath;
  669. }
  670. protected function getOrigFileUrl_Storage ($mixedHandler)
  671. {
  672. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  673. if (!$oStorageOriginal)
  674. return false;
  675. return $oStorageOriginal->getFileUrlById($mixedHandler);
  676. }
  677. protected function initFilters ()
  678. {
  679. if (false !== $this->_aObject['filters']) // filters are already initilized
  680. return;
  681. // get transcoder filters
  682. $aFilters = $this->_oDb->getTranscoderFilters();
  683. $this->_aObject['filters'] = array();
  684. foreach ($aFilters as $aFilter) {
  685. $aFilter['filter_params'] = $aFilter['filter_params'] ? unserialize($aFilter['filter_params']) : array();
  686. $this->_aObject['filters'][] = $aFilter;
  687. }
  688. }
  689. protected function clearCacheDB()
  690. {
  691. $oCacheDb = $this->_oDb->getDbCacheObject();
  692. return $oCacheDb->removeAllByPrefix('db_');
  693. }
  694. public function getDevicePixelRatioHandlerSuffix ()
  695. {
  696. $iDevicePixelRatio = $this->getDevicePixelRatio ();
  697. if ($iDevicePixelRatio >= 2)
  698. return $this->_sRetinaSuffix;
  699. return '';
  700. }
  701. protected function processHandlerForRetinaDevice ($mixedHandler)
  702. {
  703. return '' . $mixedHandler . $this->getDevicePixelRatioHandlerSuffix ();
  704. }
  705. static protected function _callFuncForObjectsArray ($mixed, $sFunc)
  706. {
  707. if (!is_array($mixed))
  708. $mixed = array($mixed);
  709. foreach ($mixed as $sObject) {
  710. $oTranscoder = self::getObjectInstance($sObject);
  711. if ($oTranscoder)
  712. $oTranscoder->$sFunc();
  713. }
  714. }
  715. /**
  716. * Get filter params
  717. * @param $sName filter name
  718. * @return array of filter params if filter was found, or false if given filter isn't enabled for the transcoder
  719. */
  720. public function getFilterParams ($sName)
  721. {
  722. $this->initFilters ();
  723. foreach ($this->_aObject['filters'] as $aParams)
  724. if ($sName == $aParams['filter'])
  725. return $aParams['filter_params'];
  726. return false;
  727. }
  728. public function getMaxResizeDimention ()
  729. {
  730. $a = $this->_oDb->getTranscoderFilters('Resize');
  731. if (!$a)
  732. return 0;
  733. $aFilter = array_pop($a);
  734. $aFilterParams = $aFilter['filter_params'] ? unserialize($aFilter['filter_params']) : array();
  735. return $aFilterParams ? max(isset($aFilterParams['w']) ? $aFilterParams['w'] : 0, isset($aFilterParams['h']) ? $aFilterParams['h'] : 0) : 0;
  736. }
  737. public function isMobile ()
  738. {
  739. if (!isset($_SERVER['HTTP_USER_AGENT']))
  740. return false;
  741. $s = $_SERVER['HTTP_USER_AGENT'];
  742. return preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i', $s) || preg_match('/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i', substr($s, 0, 4));
  743. }
  744. }
  745. /** @} */