BxDolTranscoder.php 33 KB

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