BxDolTranscoder.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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 && !$this->_oStorage->deleteFile($iFileId))
  239. return false;
  240. // delete retina file
  241. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler . $this->_sRetinaSuffix);
  242. if ($iFileId && !$this->_oStorage->deleteFile($iFileId))
  243. return false;
  244. return true;
  245. }
  246. /**
  247. * Register necessary alert handlers for automatic deletetion of transcoded data if source file is deleted.
  248. * Make sure that you call it once, before first usage, for example upon module installation.
  249. */
  250. public function registerHandlers ()
  251. {
  252. if (!$this->_oDb->registerHandlers ())
  253. return false;
  254. return $this->clearCacheDB();
  255. }
  256. /**
  257. * Unregister alert handlers for automatic deletetion of transcoded data if source file is deleted.
  258. * Make sure that you call it once, for example upon module uninstallation.
  259. */
  260. public function unregisterHandlers ()
  261. {
  262. if (!$this->_oDb->unregisterHandlers ())
  263. return false;
  264. return $this->clearCacheDB();
  265. }
  266. /**
  267. * Delete (queue for deletion) all resized files for the current object
  268. */
  269. public function cleanup ()
  270. {
  271. return $this->_oStorage->queueFilesForDeletionFromObject();
  272. }
  273. /**
  274. * Get storage object where transcoded data is stored
  275. */
  276. public function getStorage()
  277. {
  278. return $this->_oStorage;
  279. }
  280. /**
  281. * Get database object instance
  282. */
  283. public function getDb()
  284. {
  285. return $this->_oDb;
  286. }
  287. /**
  288. * check if transcoder suppors given file mime type
  289. */
  290. public function isMimeTypeSupported($sMimeType)
  291. {
  292. return false;
  293. }
  294. /**
  295. * Get transcoded file url.
  296. * If transcoded file is ready then direct url to the file is returned.
  297. * 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.
  298. * @param $mixedHandler - file handler
  299. * @return file url, or false on error.
  300. */
  301. public function getFileUrl($mixedHandler)
  302. {
  303. if ($this->isFileReady($mixedHandler)) {
  304. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  305. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  306. if (!$iFileId)
  307. return false;
  308. $aFile = $this->_oStorage->getFile($iFileId);
  309. if (!$aFile)
  310. return false;
  311. if ($this->_aObject['atime_tracking'])
  312. $this->_oDb->updateAccessTime($mixedHandler);
  313. return $this->_oStorage->getFileUrlById($iFileId);
  314. }
  315. if ($this->_sQueueTable && !$this->addToQueue($mixedHandler)) // add file to queue (when queue is enabled) if it isn't transcoded yet
  316. return false;
  317. return $this->getFileUrlNotReady($mixedHandler);
  318. }
  319. /**
  320. * alias for @see getFileUrl
  321. */
  322. public function getFileUrlById($mixedHandler)
  323. {
  324. return $this->getFileUrl($mixedHandler);
  325. }
  326. /**
  327. * Check if transcoded data is available. No need to call it directly, it is called automatically when it is needed.
  328. * @param $mixedHandler - file handler
  329. * @param $isCheckOutdated - check if transcoded file is outdated
  330. * @return false if there is no ready transcoded file is available or it is outdated, true if file is ready
  331. */
  332. public function isFileReady ($mixedHandler, $isCheckOutdated = true)
  333. {
  334. $sMethodFileReady = 'isFileReady_' . $this->_aObject['source_type'];
  335. return $this->$sMethodFileReady($mixedHandler, $isCheckOutdated);
  336. }
  337. /**
  338. * Transcode file, no need to call it directly, it is called automatically when it is needed.
  339. * @param $mixedHandler - file handler
  340. * @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
  341. * @return true on success, false on error
  342. */
  343. public function transcode ($mixedHandler, $iProfileId = 0)
  344. {
  345. $sExtChange = false;
  346. $bRet = true;
  347. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_PROCESSING, '', gethostname());
  348. do {
  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. $bRet = false;
  356. break;
  357. }
  358. // appply filters to tmp file
  359. $this->initFilters ();
  360. foreach ($this->_aObject['filters'] as $aParams) {
  361. $this->clearLog();
  362. $sMethodFilter = 'applyFilter_' . $aParams['filter'];
  363. if (!method_exists($this, $sMethodFilter))
  364. continue;
  365. if (!$this->$sMethodFilter($sTmpFile, $aParams['filter_params'])) {
  366. unlink($sTmpFile);
  367. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "filter failed: $sMethodFilter\n" . $this->getLog());
  368. $bRet = false;
  369. break 2;
  370. }
  371. if (!empty($aParams['filter_params']['force_type'])) {
  372. switch ($aParams['filter_params']['force_type']) {
  373. case 'jpeg':
  374. case 'jpg':
  375. $sExtChange = 'jpg';
  376. break;
  377. default:
  378. $sExtChange = $aParams['filter_params']['force_type'];
  379. }
  380. }
  381. if ($sExtChange) {
  382. $iDotPos = strrpos($sTmpFile, '.');
  383. $sExtOld = false === $iDotPos ? '' : substr($sTmpFile, $iDotPos+1);
  384. if ($sExtOld != $sExtChange) {
  385. $sTmpFileOld = $sTmpFile;
  386. $sTmpFile = false === $iDotPos ? $sTmpFile . '.' . $sExtChange : substr_replace($sTmpFile, $sExtChange, $iDotPos+1, strlen($sExtOld));
  387. if (!rename($sTmpFileOld, $sTmpFile)) {
  388. @unlink($sTmpFileOld);
  389. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "change file extension failed: $sTmpFileOld => $sTmpFile");
  390. $bRet = false;
  391. break 2;
  392. }
  393. }
  394. }
  395. }
  396. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  397. if ($this->_sQueueStorage) {
  398. $sFileUrlResult = '';
  399. if (!($iFileIdResult = $this->storeTranscodedFileInQueueStorage($mixedHandler, $sTmpFile, $sFileUrlResult)))
  400. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store queue tmp file failed:\n" . $this->getLog());
  401. else
  402. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_COMPLETE, '', '', $iFileIdResult, $sFileUrlResult, $sExtChange);
  403. } else {
  404. $bRet = $this->storeTranscodedFile($mixedHandler, $sTmpFile, $iProfileId);
  405. if ($bRet)
  406. $this->deleteFromQueue($mixedHandler);
  407. else
  408. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store file failed:\n" . $this->getLog());
  409. }
  410. @unlink($sTmpFile);
  411. } while (false);
  412. bx_alert($this->_aObject['object'], 'transcoded', $mixedHandler, false, array(
  413. 'object' => $this,
  414. 'ret' => $bRet,
  415. ));
  416. return $bRet;
  417. }
  418. /**
  419. * Delete outdated files by last access time.
  420. * @return number of pruned/deleted files
  421. */
  422. public function prune ()
  423. {
  424. $aFiles = $this->_oDb->getFilesForPruning();
  425. if (!$aFiles)
  426. return false;
  427. $iCount = 0;
  428. foreach ($aFiles as $r)
  429. $iCount += $this->_oStorage->deleteFile($r['file_id']) ? 1 : 0;
  430. return $iCount;
  431. }
  432. public function forceDevicePixelRatio ($i)
  433. {
  434. if (!$i)
  435. $this->_iDevicePixelRatio = false;
  436. elseif ($i >= 2)
  437. $this->_iDevicePixelRatio = 2;
  438. else
  439. $this->_iDevicePixelRatio = 1;
  440. }
  441. public function getDevicePixelRatio ()
  442. {
  443. $iRet = 1;
  444. if ($this->_iDevicePixelRatio) {
  445. $iRet = $this->_iDevicePixelRatio;
  446. }
  447. elseif (isset($_COOKIE['devicePixelRatio']) && (!isset($this->_aObject['source_params']['disable_retina']) || !$this->_aObject['source_params']['disable_retina'])) {
  448. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  449. if ($iDevicePixelRatio >= 2)
  450. $iRet = 2;
  451. }
  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. if (!isset($_SERVER['HTTP_USER_AGENT']))
  747. return false;
  748. $s = $_SERVER['HTTP_USER_AGENT'];
  749. 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));
  750. }
  751. }
  752. /** @} */