BxDolTranscoder.php 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  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. $bRet = true;
  349. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_PROCESSING, '', gethostname());
  350. do {
  351. // create tmp file locally
  352. $sSuffix = $this->_sQueueStorage ? 'Queue' : $this->_aObject['source_type'];
  353. $sMethodStoreFile = 'storeFileLocally_' . $sSuffix;
  354. $sTmpFile = $this->$sMethodStoreFile($mixedHandler);
  355. if (!$sTmpFile) {
  356. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store local tmp file failed ($sMethodStoreFile)");
  357. $bRet = false;
  358. break;
  359. }
  360. // appply filters to tmp file
  361. $this->initFilters ();
  362. foreach ($this->_aObject['filters'] as $aParams) {
  363. $this->clearLog();
  364. $sMethodFilter = 'applyFilter_' . $aParams['filter'];
  365. if (!method_exists($this, $sMethodFilter))
  366. continue;
  367. if (!$this->$sMethodFilter($sTmpFile, $aParams['filter_params'])) {
  368. unlink($sTmpFile);
  369. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "filter failed: $sMethodFilter\n" . $this->getLog());
  370. $bRet = false;
  371. break 2;
  372. }
  373. if (!empty($aParams['filter_params']['force_type'])) {
  374. switch ($aParams['filter_params']['force_type']) {
  375. case 'jpeg':
  376. case 'jpg':
  377. $sExtChange = 'jpg';
  378. break;
  379. default:
  380. $sExtChange = $aParams['filter_params']['force_type'];
  381. }
  382. }
  383. if ($sExtChange) {
  384. $iDotPos = strrpos($sTmpFile, '.');
  385. $sExtOld = false === $iDotPos ? '' : substr($sTmpFile, $iDotPos+1);
  386. if ($sExtOld != $sExtChange) {
  387. $sTmpFileOld = $sTmpFile;
  388. $sTmpFile = false === $iDotPos ? $sTmpFile . '.' . $sExtChange : substr_replace($sTmpFile, $sExtChange, $iDotPos+1, strlen($sExtOld));
  389. if (!rename($sTmpFileOld, $sTmpFile)) {
  390. @unlink($sTmpFileOld);
  391. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "change file extension failed: $sTmpFileOld => $sTmpFile");
  392. $bRet = false;
  393. break 2;
  394. }
  395. }
  396. }
  397. }
  398. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandler);
  399. if ($this->_sQueueStorage) {
  400. $sFileUrlResult = '';
  401. if (!($iFileIdResult = $this->storeTranscodedFileInQueueStorage($mixedHandler, $sTmpFile, $sFileUrlResult)))
  402. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store queue tmp file failed:\n" . $this->getLog());
  403. else
  404. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_COMPLETE, '', '', $iFileIdResult, $sFileUrlResult, $sExtChange);
  405. } else {
  406. $bRet = $this->storeTranscodedFile($mixedHandler, $sTmpFile, $iProfileId);
  407. if ($bRet)
  408. $this->deleteFromQueue($mixedHandler);
  409. else
  410. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, "store file failed:\n" . $this->getLog());
  411. }
  412. @unlink($sTmpFile);
  413. } while (false);
  414. bx_alert($this->_aObject['object'], 'transcoded', $mixedHandler, false, array(
  415. 'object' => $this,
  416. 'ret' => $bRet,
  417. ));
  418. return $bRet;
  419. }
  420. /**
  421. * Delete outdated files by last access time.
  422. * @return number of pruned/deleted files
  423. */
  424. public function prune ()
  425. {
  426. $aFiles = $this->_oDb->getFilesForPruning();
  427. if (!$aFiles)
  428. return false;
  429. $iCount = 0;
  430. foreach ($aFiles as $r)
  431. $iCount += $this->_oStorage->deleteFile($r['file_id']) ? 1 : 0;
  432. return $iCount;
  433. }
  434. public function forceDevicePixelRatio ($i)
  435. {
  436. if (!$i)
  437. $this->_iDevicePixelRatio = false;
  438. elseif ($i >= 2)
  439. $this->_iDevicePixelRatio = 2;
  440. else
  441. $this->_iDevicePixelRatio = 1;
  442. }
  443. public function getDevicePixelRatio ()
  444. {
  445. $iRet = 1;
  446. if ($this->_iDevicePixelRatio) {
  447. $iRet = $this->_iDevicePixelRatio;
  448. }
  449. elseif (isset($_COOKIE['devicePixelRatio']) && (!isset($this->_aObject['source_params']['disable_retina']) || !$this->_aObject['source_params']['disable_retina'])) {
  450. $iDevicePixelRatio = intval($_COOKIE['devicePixelRatio']);
  451. if ($iDevicePixelRatio >= 2)
  452. $iRet = 2;
  453. }
  454. // don't resize images on mobile if they are already big enough
  455. if ($iRet > 1 && $this->isMobile() && $this->getMaxResizeDimention() >= BX_DOL_MAX_RETINA_DIMENSION_MOBILE)
  456. $iRet = 1;
  457. return $iRet;
  458. }
  459. public function getOrigFileUrl ($mixedHandler)
  460. {
  461. $sMethodStoreFile = 'getOrigFileUrl_' . $this->_aObject['source_type'];
  462. return $this->$sMethodStoreFile($mixedHandler);
  463. }
  464. /**
  465. * Get file url when file isn't transcoded yet
  466. */
  467. public function getFileUrlNotReady($mixedHandler)
  468. {
  469. return false;
  470. }
  471. public function getTmpFilename ($sOverrideName = false)
  472. {
  473. if ($sOverrideName)
  474. return BX_DIRECTORY_PATH_TMP . rand(10000, 99999) . $sOverrideName;
  475. return tempnam(BX_DIRECTORY_PATH_TMP, $this->_aObject['object']);
  476. }
  477. public function clearLog()
  478. {
  479. $this->_sLog = '';
  480. }
  481. public function addToLog($s)
  482. {
  483. $this->_sLog .= $s;
  484. }
  485. public function getLog()
  486. {
  487. return $this->_sLog;
  488. }
  489. public function deleteFromQueue ($mixedHandler)
  490. {
  491. $sErrMsg = "delete queue tmp file failed:\n";
  492. $a = $this->_oDb->getFromQueue($mixedHandler);
  493. if (!$a || $a['server'] != gethostname()) // deletion must be performed on the server where it was transcoded
  494. return false;
  495. if ($a['file_id_result'] && $this->_sQueueStorage && 0 !== strncmp($a['log'], $sErrMsg, strlen($sErrMsg))) {
  496. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  497. if (!$oStorage->deleteFile($a['file_id_result'])) {
  498. $this->_oDb->updateQueueStatus($mixedHandler, BX_DOL_QUEUE_FAILED, $sErrMsg . $this->getLog());
  499. return false;
  500. }
  501. }
  502. return $this->_oDb->deleteFromQueue($mixedHandler);
  503. }
  504. public function storeTranscodedFile ($mixedHandler, $sTmpFile, $iProfileId)
  505. {
  506. $sMethodIsPrivate = 'isPrivate_' . $this->_aObject['source_type'];
  507. $isPrivate = $this->$sMethodIsPrivate($mixedHandler);
  508. $iFileId = $this->_oStorage->storeFileFromPath ($sTmpFile, $isPrivate, $iProfileId);
  509. if (!$iFileId) {
  510. $this->addToLog($this->_oStorage->getErrorString());
  511. return false;
  512. }
  513. if (!$this->_oDb->updateHandler($iFileId, $mixedHandler)) {
  514. $this->_oStorage->deleteFile($iFileId);
  515. return false;
  516. }
  517. $this->_oStorage->afterUploadCleanup($iFileId, $iProfileId);
  518. return true;
  519. }
  520. protected function storeTranscodedFileInQueueStorage ($mixedHandler, $sTmpFile, &$sFileUrlResult)
  521. {
  522. if (!$this->_sQueueStorage)
  523. return false;
  524. $oStorage = BxDolStorage::getObjectInstance($this->_sQueueStorage);
  525. $iFileIdResult = $oStorage->storeFileFromPath ($sTmpFile, 1, 0);
  526. if (!$iFileIdResult) {
  527. $this->addToLog($oStorage->getErrorString());
  528. return false;
  529. }
  530. if (!($sFileUrlResult = $oStorage->getFileUrlById($iFileIdResult))) {
  531. $this->_oStorage->deleteFile($iFileIdResult);
  532. return false;
  533. }
  534. $oStorage->afterUploadCleanup($iFileIdResult, 0);
  535. return $iFileIdResult;
  536. }
  537. protected function addToQueue($mixedHandler, $iProfileId = 0)
  538. {
  539. if ($this->_oDb->getFromQueue($mixedHandler))
  540. return true;
  541. $sFileUrl = $this->getOrigFileUrl($mixedHandler);
  542. return $this->_oDb->addToQueue ($mixedHandler, $sFileUrl, $iProfileId);
  543. }
  544. protected function applyFilter_Resize ($sFile, $aParams)
  545. {
  546. $o = BxDolImageResize::getInstance();
  547. $o->removeCropOptions ();
  548. $o->setSize (isset($aParams['w']) ? round($aParams['w'] * $this->getDevicePixelRatio()) : null, isset($aParams['h']) ? round($aParams['h'] * $this->getDevicePixelRatio()) : null);
  549. if (isset($aParams['crop_resize']) && $aParams['crop_resize'])
  550. $o->setAutoCrop (true);
  551. elseif (isset($aParams['square_resize']) && $aParams['square_resize'])
  552. $o->setSquareResize (true);
  553. else
  554. $o->setSquareResize (false);
  555. if (IMAGE_ERROR_SUCCESS == $o->resize($sFile))
  556. return true;
  557. return false;
  558. }
  559. protected function isFileReady_Folder ($mixedHandlerOrig, $isCheckOutdated = true)
  560. {
  561. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  562. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  563. if (!$iFileId)
  564. return false;
  565. $aFile = $this->_oStorage->getFile($iFileId);
  566. if (!$aFile)
  567. return false;
  568. if ($isCheckOutdated) { // warning, $isCheckOutdated is partially supported for Folder source type - file modification is not checked
  569. if ($this->_aObject['ts'] > $aFile['modified'] || !$this->getFilePath_Folder($mixedHandlerOrig)) { // if we changed transcoder object params or original file is deleted
  570. // delete file, so it will be recreated next time
  571. if ($this->_oStorage->deleteFile($aFile['id']))
  572. return false;
  573. }
  574. }
  575. return true;
  576. }
  577. protected function isFileReady_Storage ($mixedHandlerOrig, $isCheckOutdated = true)
  578. {
  579. $mixedHandler = $this->processHandlerForRetinaDevice($mixedHandlerOrig);
  580. $iFileId = $this->_oDb->getFileIdByHandler($mixedHandler);
  581. if (!$iFileId)
  582. return false;
  583. $aFile = $this->_oStorage->getFile($iFileId);
  584. if (!$aFile)
  585. return false;
  586. if ($isCheckOutdated) {
  587. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  588. if ($oStorageOriginal) {
  589. $aFileOriginal = $oStorageOriginal->getFile($mixedHandlerOrig);
  590. if (!$aFileOriginal || $aFileOriginal['modified'] > $aFile['modified'] || $this->_aObject['ts'] >= $aFile['modified']) { // if original file was changed OR we changed transcoder object params
  591. // delete file, so it will be recreated next time
  592. if ($this->_oStorage->deleteFile($aFile['id']))
  593. return false;
  594. }
  595. }
  596. }
  597. return true;
  598. }
  599. protected function isPrivate_Folder ($mixedHandler)
  600. {
  601. if ('no' == $this->_aObject['private'])
  602. return false;
  603. return true;
  604. }
  605. protected function isPrivate_Storage ($mixedHandler)
  606. {
  607. switch ($this->_aObject['private']) {
  608. case 'no':
  609. return false;
  610. case 'yes':
  611. return true;
  612. default:
  613. case 'auto':
  614. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  615. if (!$oStorageOriginal)
  616. return true; // in case of error - make sure that file is not public accidentally
  617. $aFile = $oStorageOriginal->getFile($mixedHandler);
  618. return $oStorageOriginal->isFilePrivate($aFile['id']);
  619. }
  620. }
  621. protected function getFilePath_Folder ($mixedHandler)
  622. {
  623. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  624. if (!file_exists($sPath))
  625. $sPath = BX_DIRECTORY_PATH_ROOT . $sPath;
  626. if (!file_exists($sPath))
  627. return false;
  628. return $sPath;
  629. }
  630. protected function storeFileLocally_Folder ($mixedHandler)
  631. {
  632. $sPath = $this->getFilePath_Folder($mixedHandler);
  633. if (!$sPath)
  634. return false;
  635. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  636. if (!copy($sPath, $sTmpFile))
  637. return false;
  638. return $sTmpFile;
  639. }
  640. protected function storeFileLocally_Storage ($mixedHandler)
  641. {
  642. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  643. if (!$oStorageOriginal)
  644. return false;
  645. $aFile = $oStorageOriginal->getFile($mixedHandler);
  646. if (!$aFile)
  647. return false;
  648. $sUrl = $oStorageOriginal->getFileUrlById($mixedHandler);
  649. if (!$sUrl)
  650. return false;
  651. $sFileData = bx_file_get_contents ($sUrl);
  652. if (false === $sFileData)
  653. return false;
  654. $sTmpFile = $this->getTmpFilename ($aFile['file_name']);
  655. if (!file_put_contents($sTmpFile, $sFileData))
  656. return false;
  657. return $sTmpFile;
  658. }
  659. protected function storeFileLocally_Queue ($mixedHandler)
  660. {
  661. $aQueue = $this->_oDb->getFromQueue($mixedHandler);
  662. if (!$aQueue || !$aQueue['file_url_source'])
  663. return false;
  664. $sFileData = bx_file_get_contents ($aQueue['file_url_source']);
  665. if (false === $sFileData)
  666. return false;
  667. $sTmpFile = $this->getTmpFilename ($mixedHandler);
  668. if (!file_put_contents($sTmpFile, $sFileData))
  669. return false;
  670. return $sTmpFile;
  671. }
  672. protected function getOrigFileUrl_Folder ($mixedHandler)
  673. {
  674. $sPath = $this->_aObject['source_params']['path'] . $mixedHandler;
  675. if (!file_exists(BX_DIRECTORY_PATH_ROOT . $sPath))
  676. return false;
  677. return BX_DOL_URL_ROOT . $sPath;
  678. }
  679. protected function getOrigFileUrl_Storage ($mixedHandler)
  680. {
  681. $oStorageOriginal = BxDolStorage::getObjectInstance($this->_aObject['source_params']['object']);
  682. if (!$oStorageOriginal)
  683. return false;
  684. return $oStorageOriginal->getFileUrlById($mixedHandler);
  685. }
  686. protected function initFilters ()
  687. {
  688. if (false !== $this->_aObject['filters']) // filters are already initilized
  689. return;
  690. // get transcoder filters
  691. $aFilters = $this->_oDb->getTranscoderFilters();
  692. $this->_aObject['filters'] = array();
  693. foreach ($aFilters as $aFilter) {
  694. $aFilter['filter_params'] = $aFilter['filter_params'] ? unserialize($aFilter['filter_params']) : array();
  695. $this->_aObject['filters'][] = $aFilter;
  696. }
  697. }
  698. protected function clearCacheDB()
  699. {
  700. $oCacheDb = $this->_oDb->getDbCacheObject();
  701. return $oCacheDb->removeAllByPrefix('db_');
  702. }
  703. public function getDevicePixelRatioHandlerSuffix ()
  704. {
  705. $iDevicePixelRatio = $this->getDevicePixelRatio ();
  706. if ($iDevicePixelRatio >= 2)
  707. return $this->_sRetinaSuffix;
  708. return '';
  709. }
  710. protected function processHandlerForRetinaDevice ($mixedHandler)
  711. {
  712. return '' . $mixedHandler . $this->getDevicePixelRatioHandlerSuffix ();
  713. }
  714. static protected function _callFuncForObjectsArray ($mixed, $sFunc)
  715. {
  716. if (!is_array($mixed))
  717. $mixed = array($mixed);
  718. foreach ($mixed as $sObject) {
  719. $oTranscoder = self::getObjectInstance($sObject);
  720. if ($oTranscoder)
  721. $oTranscoder->$sFunc();
  722. }
  723. }
  724. /**
  725. * Get filter params
  726. * @param $sName filter name
  727. * @return array of filter params if filter was found, or false if given filter isn't enabled for the transcoder
  728. */
  729. public function getFilterParams ($sName)
  730. {
  731. $this->initFilters ();
  732. foreach ($this->_aObject['filters'] as $aParams)
  733. if ($sName == $aParams['filter'])
  734. return $aParams['filter_params'];
  735. return false;
  736. }
  737. public function getMaxResizeDimention ()
  738. {
  739. $a = $this->_oDb->getTranscoderFilters('Resize');
  740. if (!$a)
  741. return 0;
  742. $aFilter = array_pop($a);
  743. $aFilterParams = $aFilter['filter_params'] ? unserialize($aFilter['filter_params']) : array();
  744. return $aFilterParams ? max(isset($aFilterParams['w']) ? $aFilterParams['w'] : 0, isset($aFilterParams['h']) ? $aFilterParams['h'] : 0) : 0;
  745. }
  746. public function isMobile ()
  747. {
  748. if (!isset($_SERVER['HTTP_USER_AGENT']))
  749. return false;
  750. $s = $_SERVER['HTTP_USER_AGENT'];
  751. 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));
  752. }
  753. }
  754. /** @} */