BxDolUploader.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587
  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. /**
  10. * Uploaders are disigned to work as form field in forms. @see BxDolForm.
  11. *
  12. *
  13. * To add file to any form, use the following form field array:
  14. * @code
  15. * 'attachment' => array(
  16. * 'type' => 'files', // this is new form type, which enable upholders automatically
  17. * 'storage_object' => 'sample', // the storage object, where uploaded files are going to be saved
  18. * 'images_transcoder' => 'sample2', // images transcoder object to use for images preview
  19. * 'uploaders' => array ('sys_simple', 'sys_html5'), // the set of uploaders to use to upload files
  20. * 'upload_buttons_titles' => array('Simple' => 'Upload one by one', 'HTML5' => 'Upload several files in bulk'); // change default button titles, array with button names, or string to assign to all bnuttons
  21. * 'multiple' => true, // allow to upload multiple files per one upload
  22. * 'storage_private' => 0, // private or public storage (by default - private), if file is provate generated link will expire, for public storage the link is always persistent
  23. * 'content_id' => 4321, // content id to associate ghost files with
  24. * 'ghost_template' => $mixedGhostTemplate, // template for nested form
  25. * 'name' => 'attachment', // name of file form field, resulted file id is assigned to this field name
  26. * 'caption' => _t('Attachments'), // form field caption
  27. * ),
  28. * @endcode
  29. *
  30. *
  31. * Available uploaders:
  32. * - sys_simple - upload files using standard HTML forms.
  33. * - sys_html5 - upload files using AJAX uploader with multiple files selection support (without flash),
  34. * it works in Firefox and WebKit(Safari, Chrome) browsers only, but has fallback for other browsers (IE, Opera).
  35. *
  36. *
  37. * Uploaded files are showed as "nested" forms.
  38. * You can pass nested form in 'ghost_template' parameter.
  39. * If you don't pass anything in 'ghost_template' parameter, then only file id is passed upon form submission.
  40. * The nested form can be declared using the different ways:
  41. *
  42. *
  43. * 1. Pass template as string - just plain string with HTML, for example:
  44. *
  45. * @code
  46. * <div id="bx-uploader-file-{storage_object}-{file_id}" class="bx-uploader-ghost">
  47. * <div style="border:2px dotted green; padding:10px; margin-bottom:10px;">
  48. * <input type="hidden" name="f[]" value="{file_id}" />
  49. * {file_name} <br />
  50. * <a href="javascript:void(0);" onclick="{js_instance_name}.deleteGhost('{file_id}')">delete</a>
  51. * </div>
  52. * </div>
  53. * @endcode
  54. *
  55. *
  56. * 2. Pass form array - regular form array, but with inputs array only, for example:
  57. *
  58. * @code
  59. * array (
  60. * 'inputs' => array (
  61. * 'file_name' => array (
  62. * 'type' => 'text',
  63. * 'name' => 'file_name[]',
  64. * 'value' => '{file_title}',
  65. * 'caption' => _t('Caption'),
  66. * ),
  67. * 'file_desc' => array (
  68. * 'type' => 'textarea',
  69. * 'name' => 'file_desc[]',
  70. * 'caption' => _t('Description'),
  71. * ),
  72. * ),
  73. * );
  74. * @endcode
  75. *
  76. * Array is automatically modified to add necessary form attributes to work as nested form,
  77. * file id field is added automatically as hidden input as well.
  78. *
  79. *
  80. * 3. Pass instance of BxDolFormNestedGhost class - use BxDolFormNestedGhost class or its custom subclass;
  81. * to create instance use the same form array as in the previous variant, for example:
  82. *
  83. * @code
  84. * $oFormNested = new BxDolFormNestedGhost('attachment', $aFormNested, 'do_submit');
  85. * @endcode
  86. *
  87. * - 'attachment' is the name of file form field from main form.
  88. * - $aFormNested is form array from previous example.
  89. * - 'do_submit' is main form submit_name; field name of submit form input to determine if form is submitted or not.
  90. *
  91. *
  92. * All 3 variants can have the following replace markers to substitute with real values:
  93. * - {file_id} - uploaded file id
  94. * - {file_name} - uploaded file name with extension
  95. * - {file_title} - uploaded file name without extension
  96. * - {file_icon} - URL to file icon automatically determined by file extension
  97. * - {file_url} - URL to the original file
  98. * - {js_instance_name} - instance of BxDolUploader javascript class
  99. *
  100. */
  101. abstract class BxDolUploader extends BxDolFactory
  102. {
  103. protected $_bIsApi;
  104. protected $_oTemplate;
  105. protected $_iId; ///< object ID
  106. protected $_aObject; ///< object properties
  107. protected $_sStorageObject; ///< storage object name
  108. protected $_bMultiple;
  109. protected $_sUniqId; ///< uniq id used to generate UploaderJsInstance, ResultContainerId, UploadInProgressContainerId and PopupContainerId
  110. protected $_sUploaderJsInstance; ///< uplooader js object instance name
  111. protected $_sUploadInProgressContainerId; ///< container id where upload in progress element resides
  112. protected $_sPopupContainerId; ///< popup container id
  113. protected $_sResultContainerId; ///< uploading/uploaded objects container id
  114. protected $_sErrorsContainerId;
  115. protected $_sFormContainerId;
  116. protected $_sUploadErrorMessages; ///< upload error message
  117. protected $_sButtonTemplate; ///< template name for displaying upload button
  118. protected $_sJsTemplate; ///< template name for displaying upload JS
  119. protected $_sUploaderFormTemplate; ///< template name for displaying uploader form
  120. protected $_aJs;
  121. protected $_aCss;
  122. /**
  123. * constructor
  124. */
  125. protected function __construct($aObject, $sStorageObject, $sUniqId, $oTemplate)
  126. {
  127. parent::__construct();
  128. $this->_bIsApi = bx_is_api();
  129. $this->_oTemplate = $oTemplate ? $oTemplate : BxDolTemplate::getInstance();
  130. $this->_iId = (int)$aObject['id'];
  131. $this->_aObject = $aObject;
  132. $this->_sStorageObject = $sStorageObject;
  133. $this->_bMultiple = true;
  134. $this->_sUniqId = $sUniqId;
  135. $this->_sUploaderJsInstance = 'glUploader_' . $sUniqId . '_' . $this->_aObject['object'];
  136. $this->_sUploadInProgressContainerId = 'bx-form-input-files-' . $sUniqId . '-upload-in-progress-' . $this->_aObject['object'];
  137. $this->_sPopupContainerId = 'bx-form-input-files-' . $sUniqId . '-popup-wrapper-' . $this->_aObject['object'];
  138. $this->_sResultContainerId = 'bx-form-input-files-' . $sUniqId . '-upload-result';
  139. $this->_sErrorsContainerId = 'bx-form-input-files-' . $sUniqId . '-errors';
  140. $this->_sFormContainerId = 'bx-form-input-files-' . $sUniqId . '-form-cont';
  141. $this->_aJs = ['BxDolUploader.js'];
  142. $this->_aCss = ['uploaders.css'];
  143. }
  144. static public function getObjectInstance($sObject, $sStorageObject, $sResultContainerId, $oTemplate = false)
  145. {
  146. $aObject = BxDolUploaderQuery::getUploaderObject($sObject);
  147. if (!$aObject || !is_array($aObject) || !$aObject['active'])
  148. return false;
  149. $sClass = $aObject['override_class_name'];
  150. if (!empty($aObject['override_class_file']))
  151. require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
  152. $o = new $sClass($aObject, $sStorageObject, $sResultContainerId, $oTemplate);
  153. if (!$o->isInstalled() || !$o->isAvailable())
  154. return false;
  155. return $o;
  156. }
  157. /**
  158. * Is uploader available?
  159. * @return boolean
  160. */
  161. public function isAvailable()
  162. {
  163. return $this->_aObject['active'] ? true : false;
  164. }
  165. /**
  166. * Are required php modules installed for this uploader ?
  167. * @return boolean
  168. */
  169. public function isInstalled()
  170. {
  171. return true;
  172. }
  173. public function isMultiple()
  174. {
  175. return $this->_bMultiple;
  176. }
  177. public function setMultiple($bMultiple)
  178. {
  179. $this->_bMultiple = (bool)$bMultiple;
  180. }
  181. public function getNameJsInstanceUploader()
  182. {
  183. return $this->_sUploaderJsInstance;
  184. }
  185. public function getIdContainerResult()
  186. {
  187. return $this->_sResultContainerId;
  188. }
  189. public function getIdContainerUploadInProgress()
  190. {
  191. return $this->_sUploadInProgressContainerId;
  192. }
  193. public function getIdContainerPopup()
  194. {
  195. return $this->_sPopupContainerId;
  196. }
  197. public function getIdContainerErrors()
  198. {
  199. return $this->_sErrorsContainerId;
  200. }
  201. /**
  202. * Handle uploads here.
  203. * @param $mixedFiles as usual $_FILES['some_name'] array, but maybe some other params depending on the uploader
  204. * @return nothing, but if some files failed to upload, the actual error message can be determined by calling BxDolUploader::getUploadErrorMessages()
  205. */
  206. public function handleUploads ($iProfileId, $mixedFiles, $isMultiple = true, $iContentId = false, $bPrivate = true)
  207. {
  208. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  209. if(!$isMultiple)
  210. $this->deleteGhostsForProfile($iProfileId, [$iContentId, $this->_iId]);
  211. if($this->_bIsApi && $mixedFiles) {
  212. if(($iId = $oStorage->storeFileFromForm($mixedFiles, $bPrivate, $iProfileId, $iContentId)))
  213. $oStorage->updateGhostsUploaderId($iId, $this->_iId);
  214. return [
  215. 'success' => 1,
  216. 'id' => $iId
  217. ];
  218. }
  219. if(($aMultipleFiles = $oStorage->convertMultipleFilesArray($mixedFiles)) === false)
  220. $aMultipleFiles = [$mixedFiles];
  221. foreach($aMultipleFiles as $aFile) {
  222. if(($iId = $oStorage->storeFileFromForm($aFile, $bPrivate, $iProfileId, $iContentId)))
  223. $oStorage->updateGhostsUploaderId($iId, $this->_iId);
  224. else
  225. $this->appendUploadErrorMessage(_t('_sys_uploader_err_msg', $aFile['name'], $oStorage->getErrorString()));
  226. if(!$isMultiple)
  227. break;
  228. }
  229. echo '<script>window.parent.' . $this->getNameJsInstanceUploader() . '.onUploadCompleted(\'' . bx_js_string($this->getUploadErrorMessages(), BX_ESCAPE_STR_APOS) . '\');</script>';
  230. }
  231. public function getUploadErrorMessages ($sFormat = 'HTML')
  232. {
  233. if (!$this->_sUploadErrorMessages)
  234. return '';
  235. if ('HTML' == $sFormat)
  236. return nl2br($this->_sUploadErrorMessages);
  237. else
  238. return $this->_sUploadErrorMessages;
  239. }
  240. /**
  241. * Show uploader button.
  242. * @return HTML string
  243. */
  244. public function getUploaderButton($aParams = array())
  245. {
  246. return $this->_oTemplate->parseHtmlByName($this->_sButtonTemplate, $aParams);
  247. }
  248. public function getUploaderJsParams()
  249. {
  250. return [];
  251. }
  252. /**
  253. * Show uploader JS.
  254. * @return HTML string
  255. */
  256. public function getUploaderJs($mixedGhostTemplate, $isMultiple = true, $aParams = array(), $bDynamic = false)
  257. {
  258. $sJsValue = '';
  259. if(is_array($mixedGhostTemplate))
  260. $sJsValue = json_encode($mixedGhostTemplate);
  261. else
  262. $sJsValue = "'" . bx_js_string($mixedGhostTemplate, BX_ESCAPE_STR_APOS) . "'";
  263. $sJsObject = $this->getNameJsInstanceUploader();
  264. $sJsCode = $this->_oTemplate->parseHtmlByName($this->_sJsTemplate, array_merge([
  265. 'uploader_instance_name' => $sJsObject,
  266. 'engine' => $this->_aObject['object'],
  267. 'storage_object' => $this->_sStorageObject,
  268. 'images_transcoder' => '',
  269. 'uniq_id' => $this->_sUniqId,
  270. 'template_ghost' => $sJsValue,
  271. 'multiple' => $isMultiple ? 1 : 0,
  272. 'latest' => 0, //--- Return the latest one uploaded ghost only.
  273. 'storage_private' => isset($aParams['storage_private']) ? $aParams['storage_private'] : 1,
  274. 'is_init_reordering' => isset($aParams['is_init_reordering']) ? $aParams['is_init_reordering'] : 0,
  275. 'bx_if:restore_ghosts' => [
  276. 'condition' => isset($aParams['is_init_ghosts']) ? $aParams['is_init_ghosts'] : 1,
  277. 'content' => [
  278. 'uploader_instance_name' => $sJsObject,
  279. 'is_init_reordering' => isset($aParams['is_init_reordering']) ? $aParams['is_init_reordering'] : 0,
  280. ]
  281. ],
  282. 'on_upload_before' => 'false',
  283. 'on_upload' => 'false',
  284. 'on_restore_ghosts' => 'false'
  285. ], $aParams));
  286. if(!$bDynamic) {
  287. $this->_oTemplate->addJs($this->_aJs);
  288. $sJsCode = $this->_oTemplate->addJsCodeOnLoadWrapped($sJsCode);
  289. }
  290. else
  291. $sJsCode = $this->_oTemplate->addJsPreloadedWrapped($this->_aJs, $sJsCode);
  292. return $this->addCssJs($bDynamic) . $sJsCode;
  293. }
  294. /**
  295. * add necessary js, css files and js translations
  296. */
  297. public function addCssJs($bDynamic = false)
  298. {
  299. $s = '';
  300. $s .= $this->_oTemplate->addCss($this->_aCss, $bDynamic);
  301. $s .= $this->_oTemplate->addJsTranslation([
  302. '_sys_uploader_confirm_leaving_page',
  303. '_sys_uploader_confirm_close_popup',
  304. '_sys_uploader_upload_canceled',
  305. '_sys_uploader_image_reposition_info',
  306. ], $bDynamic);
  307. return $bDynamic ? $s : '';
  308. }
  309. public function addJs($mixedFile)
  310. {
  311. if(!is_array($mixedFile))
  312. $mixedFile = [$mixedFile];
  313. foreach($mixedFile as $sFile)
  314. if(!in_array($sFile, $this->_aJs))
  315. $this->_aJs[] = $sFile;
  316. }
  317. public function addCss($mixedFile)
  318. {
  319. if(!is_array($mixedFile))
  320. $mixedFile = [$mixedFile];
  321. foreach($mixedFile as $sFile)
  322. if(!in_array($sFile, $this->_aCss))
  323. $this->_aCss[] = $sFile;
  324. }
  325. /**
  326. * Get uploader button title
  327. */
  328. public function getUploaderButtonTitle($mixed = false)
  329. {
  330. // it is overrided in child classes
  331. }
  332. /**
  333. * Show uploader form.
  334. * @return HTML string
  335. */
  336. public function getUploaderForm($isMultiple = true, $iContentId = false, $isPrivate = true)
  337. {
  338. // it is overrided in child classes
  339. }
  340. /**
  341. * Display uploaded, but not saved files - ghosts
  342. * @param $iProfileId - profile id to get orphaned files from
  343. * @param $sFormat - output format, only 'json' output formt is supported
  344. * @param $sImagesTranscoder - transcoder object for files preview for images and videos, false by default - no preview
  345. * @param $mixedContent - int Content ID | array Content ID + Uploader ID | false to not consider content id at all
  346. * @return JSON string
  347. */
  348. public function getGhosts($iProfileId, $sFormat, $sImagesTranscoder = false, $mixedContent = false)
  349. {
  350. $iContent = (int)(is_array($mixedContent) ? reset($mixedContent) : $mixedContent);
  351. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  352. $oImagesTranscoder = false;
  353. if($sImagesTranscoder)
  354. $oImagesTranscoder = BxDolTranscoderImage::getObjectInstance($sImagesTranscoder);
  355. $a = [];
  356. $aGhosts = $oStorage->getGhosts($this->isAdmin($iContent) && $iContent ? false : $iProfileId, $mixedContent);
  357. foreach($aGhosts as $aFile) {
  358. $sFileIcon = '';
  359. if($this->isUseTranscoderForPreview($oImagesTranscoder, $aFile))
  360. $sFileIcon = $oImagesTranscoder->getFileUrl($aFile['id']);
  361. if(!$sFileIcon)
  362. $sFileIcon = $this->_oTemplate->getIconUrl($oStorage->getIconNameByFileName($aFile['file_name']));
  363. $a[$aFile['id']] = array_merge([
  364. 'storage_object' => $this->_sStorageObject,
  365. 'uploader_id' => $aFile['uploader_id'] ?? 0,
  366. 'file_id' => $aFile['id'],
  367. 'file_type' => $aFile['mime_type'],
  368. 'file_name' => $aFile['file_name'],
  369. 'file_title' => $oStorage->getFileTitle($aFile['file_name']),
  370. 'file_icon' => $sFileIcon,
  371. 'file_url' => $oStorage->getFileUrlById($aFile['id']),
  372. 'file_remote_id' => $aFile['remote_id'],
  373. 'file_created' => $aFile['created'],
  374. 'js_instance_name' => $this->_sUploaderJsInstance,
  375. ], $this->getGhostTemplateVars($aFile, $iProfileId, $iContent, $oStorage, $oImagesTranscoder));
  376. }
  377. if('array' == $sFormat) {
  378. return $a;
  379. }
  380. else if('json' == $sFormat) {
  381. return json_encode($a);
  382. }
  383. else { // html format is not suported for this data type
  384. return false;
  385. }
  386. }
  387. public function getGhostsWithOrder($iProfileId, $sFormat, $sImagesTranscoder = false, $mixedContent = false, $isLatestOnly = false)
  388. {
  389. $a = $this->getGhosts($iProfileId, 'array', $sImagesTranscoder, $mixedContent);
  390. if($isLatestOnly)
  391. $a = array_slice($a, 0, 1, true);
  392. if(!empty($a) && is_array($a))
  393. $a = ['g' => $a, 'o' => array_keys($a)];
  394. if ('json' == $sFormat) {
  395. return json_encode($a);
  396. } else { // html format is not suported for this data type
  397. return $a;
  398. }
  399. }
  400. /**
  401. * Reorder uploaded ghosts.
  402. * @param $iProfileId - profile id to get orphaned files from
  403. * @param $sFormat - output format, only 'json' output formt is supported
  404. * @param $aGhosts - an array of ordered ghosts' IDs.
  405. * @param $iContentId - content id to order orphaned files for, false by default
  406. * @return JSON string
  407. */
  408. public function reorderGhosts($iProfileId, $sFormat, $aGhosts, $iContentId = false)
  409. {
  410. $bResult = true;
  411. if(($oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject)) !== false)
  412. $bResult = $oStorage->reorderGhosts($this->isAdmin($iContentId) && $iContentId ? false : $iProfileId, $iContentId, $aGhosts);
  413. if($sFormat == 'json')
  414. return json_encode($bResult ? [] : ['msg' => _t('_error occured')]);
  415. else
  416. return $bResult;
  417. }
  418. /**
  419. * Delete file by file id, usually ghost file
  420. * @return 'ok' string on success or error string on error
  421. */
  422. public function deleteGhost($iFileId, $iProfileId)
  423. {
  424. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  425. $aFile = $oStorage->getGhost ($iFileId);
  426. if (!$aFile)
  427. $aFile = $oStorage->getFile ($iFileId);
  428. if (!$aFile)
  429. return _t('_error occured');
  430. $oProfile = BxDolProfile::getInstance($iProfileId);
  431. $oAccount = $oProfile ? $oProfile->getAccountObject() : null;
  432. $aProfiles = $oAccount ? $oAccount->getProfiles(false) : array();
  433. if (!isset($aProfiles[$aFile['profile_id']]) && !$this->isAdmin($aFile['content_id']))
  434. return _t('_sys_txt_access_denied');
  435. if (!$oStorage->deleteFile($iFileId))
  436. return $oStorage->getErrorString();
  437. return 'ok';
  438. }
  439. /**
  440. * Delete all ghosts files for the specified profile
  441. * @param $iProfileId - profile id to get orphaned files from
  442. * @param $mixedContent - int Content ID | array Content ID + Uploader ID | false
  443. * @return number of delete ghost files
  444. */
  445. public function deleteGhostsForProfile($iProfileId, $mixedContent = false)
  446. {
  447. $iCount = 0;
  448. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  449. if($oStorage === false)
  450. return $iCount;
  451. $aGhosts = $oStorage->getGhosts($iProfileId, $mixedContent, $mixedContent ? true : false);
  452. foreach ($aGhosts as $aFile)
  453. $iCount += $oStorage->deleteFile($aFile['id']);
  454. return $iCount;
  455. }
  456. protected function cleanUploadErrorMessages ()
  457. {
  458. $this->_sUploadErrorMessages = '';
  459. }
  460. public function appendUploadErrorMessage ($s)
  461. {
  462. $this->_sUploadErrorMessages .= ($this->_sUploadErrorMessages ? "\n" : '') . $s;
  463. }
  464. protected function getRestrictionsText ()
  465. {
  466. $sTextRestrictions = '';
  467. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  468. if (!$oStorage)
  469. return '';
  470. $a = $oStorage->getRestrictionsTextArray(bx_get_logged_profile_id());
  471. foreach ($a as $s)
  472. $sTextRestrictions .= '<div class="bx-uploader-msg-info bx-def-font-grayed">' . $s . '</div>';
  473. return $sTextRestrictions;
  474. }
  475. protected function getMaxUploadFileSize ()
  476. {
  477. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  478. if (!$oStorage)
  479. return 0;
  480. return $oStorage->getMaxUploadFileSize(bx_get_logged_profile_id());
  481. }
  482. protected function getAcceptedFilesExtensions ()
  483. {
  484. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  485. if (!$oStorage)
  486. return null;
  487. return $oStorage->getAllowedExtensions();
  488. }
  489. protected function getGhostTemplateVars($aFile, $iProfileId, $iContentId, $oStorage, $oImagesTranscoder)
  490. {
  491. return array();
  492. }
  493. protected function isUseTranscoderForPreview($oImagesTranscoder, $aFile)
  494. {
  495. if (!$oImagesTranscoder)
  496. return false;
  497. return $oImagesTranscoder->isMimeTypeSupported($aFile['mime_type']);
  498. }
  499. protected function isAdmin ($iContentId = 0)
  500. {
  501. return isAdmin();
  502. }
  503. }
  504. /** @} */