1
0

BxDolUploader.php 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  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 $_oTemplate;
  104. protected $_aObject; ///< object properties
  105. protected $_sStorageObject; ///< storage object name
  106. protected $_sUniqId; ///< uniq id used to generate UploaderJsInstance, ResultContainerId, UploadInProgressContainerId and PopupContainerId
  107. protected $_sUploaderJsInstance; ///< uplooader js object instance name
  108. protected $_sResultContainerId; ///< uploading/uploaded objects container id
  109. protected $_sUploadInProgressContainerId; ///< container id where upload in progress element resides
  110. protected $_sPopupContainerId; ///< popup container id
  111. protected $_sUploadErrorMessages; ///< upload error message
  112. protected $_sButtonTemplate; ///< template name for displaying upload button
  113. protected $_sJsTemplate; ///< template name for displaying upload JS
  114. protected $_sUploaderFormTemplate; ///< template name for displaying uploader form
  115. protected $_aJs;
  116. protected $_aCss;
  117. /**
  118. * constructor
  119. */
  120. protected function __construct($aObject, $sStorageObject, $sUniqId, $oTemplate)
  121. {
  122. parent::__construct();
  123. $this->_oTemplate = $oTemplate ? $oTemplate : BxDolTemplate::getInstance();
  124. $this->_aObject = $aObject;
  125. $this->_sStorageObject = $sStorageObject;
  126. $this->_sUniqId = $sUniqId;
  127. $this->_sUploaderJsInstance = 'glUploader_' . $sUniqId . '_' . $this->_aObject['object'];
  128. $this->_sUploadInProgressContainerId = 'bx-form-input-files-' . $sUniqId . '-upload-in-progress-' . $this->_aObject['object'];
  129. $this->_sPopupContainerId = 'bx-form-input-files-' . $sUniqId . '-popup-wrapper-' . $this->_aObject['object'];
  130. $this->_sResultContainerId = 'bx-form-input-files-' . $sUniqId . '-upload-result';
  131. $this->_sErrorsContainerId = 'bx-form-input-files-' . $sUniqId . '-errors';
  132. $this->_sFormContainerId = 'bx-form-input-files-' . $sUniqId . '-form-cont';
  133. $this->_aJs = ['BxDolUploader.js'];
  134. $this->_aCss = ['uploaders.css'];
  135. }
  136. static public function getObjectInstance($sObject, $sStorageObject, $sResultContainerId, $oTemplate = false)
  137. {
  138. $aObject = BxDolUploaderQuery::getUploaderObject($sObject);
  139. if (!$aObject || !is_array($aObject) || !$aObject['active'])
  140. return false;
  141. $sClass = $aObject['override_class_name'];
  142. if (!empty($aObject['override_class_file']))
  143. require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
  144. $o = new $sClass($aObject, $sStorageObject, $sResultContainerId, $oTemplate);
  145. if (!$o->isInstalled() || !$o->isAvailable())
  146. return false;
  147. return $o;
  148. }
  149. /**
  150. * Is uploader available?
  151. * @return boolean
  152. */
  153. public function isAvailable()
  154. {
  155. return $this->_aObject['active'] ? true : false;
  156. }
  157. /**
  158. * Are required php modules installed for this uploader ?
  159. * @return boolean
  160. */
  161. public function isInstalled()
  162. {
  163. return true;
  164. }
  165. public function getNameJsInstanceUploader()
  166. {
  167. return $this->_sUploaderJsInstance;
  168. }
  169. public function getIdContainerResult()
  170. {
  171. return $this->_sResultContainerId;
  172. }
  173. public function getIdContainerUploadInProgress()
  174. {
  175. return $this->_sUploadInProgressContainerId;
  176. }
  177. public function getIdContainerPopup()
  178. {
  179. return $this->_sPopupContainerId;
  180. }
  181. public function getIdContainerErrors()
  182. {
  183. return $this->_sErrorsContainerId;
  184. }
  185. /**
  186. * Handle uploads here.
  187. * @param $mixedFiles as usual $_FILES['some_name'] array, but maybe some other params depending on the uploader
  188. * @return nothing, but if some files failed to upload, the actual error message can be determined by calling BxDolUploader::getUploadErrorMessages()
  189. */
  190. public function handleUploads ($iProfileId, $mixedFiles, $isMultiple = true, $iContentId = false, $bPrivate = true)
  191. {
  192. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  193. if (false == ($aMultipleFiles = $oStorage->convertMultipleFilesArray($mixedFiles)))
  194. $aMultipleFiles = array($mixedFiles);
  195. if (!$isMultiple)
  196. $this->deleteGhostsForProfile($iProfileId, $iContentId);
  197. foreach ($aMultipleFiles as $aFile) {
  198. $iId = $oStorage->storeFileFromForm($aFile, $bPrivate, $iProfileId, $iContentId);
  199. if (!$iId)
  200. $this->appendUploadErrorMessage(_t('_sys_uploader_err_msg', $aFile['name'], $oStorage->getErrorString()));
  201. if (!$isMultiple)
  202. break;
  203. }
  204. echo '<script>window.parent.' . $this->getNameJsInstanceUploader() . '.onUploadCompleted(\'' . bx_js_string($this->getUploadErrorMessages(), BX_ESCAPE_STR_APOS) . '\');</script>';
  205. }
  206. public function getUploadErrorMessages ($sFormat = 'HTML')
  207. {
  208. if (!$this->_sUploadErrorMessages)
  209. return '';
  210. if ('HTML' == $sFormat)
  211. return nl2br($this->_sUploadErrorMessages);
  212. else
  213. return $this->_sUploadErrorMessages;
  214. }
  215. /**
  216. * Show uploader button.
  217. * @return HTML string
  218. */
  219. public function getUploaderButton($aParams = array())
  220. {
  221. return $this->_oTemplate->parseHtmlByName($this->_sButtonTemplate, $aParams);
  222. }
  223. public function getUploaderJsParams()
  224. {
  225. return [];
  226. }
  227. /**
  228. * Show uploader JS.
  229. * @return HTML string
  230. */
  231. public function getUploaderJs($mixedGhostTemplate, $isMultiple = true, $aParams = array(), $bDynamic = false)
  232. {
  233. $sJsValue = '';
  234. if(is_array($mixedGhostTemplate))
  235. $sJsValue = json_encode($mixedGhostTemplate);
  236. else
  237. $sJsValue = "'" . bx_js_string($mixedGhostTemplate, BX_ESCAPE_STR_APOS) . "'";
  238. $sJsObject = $this->getNameJsInstanceUploader();
  239. $sJsCode = $this->_oTemplate->parseHtmlByName($this->_sJsTemplate, array_merge([
  240. 'uploader_instance_name' => $sJsObject,
  241. 'engine' => $this->_aObject['object'],
  242. 'storage_object' => $this->_sStorageObject,
  243. 'images_transcoder' => '',
  244. 'uniq_id' => $this->_sUniqId,
  245. 'template_ghost' => $sJsValue,
  246. 'multiple' => $isMultiple ? 1 : 0,
  247. 'storage_private' => isset($aParams['storage_private']) ? $aParams['storage_private'] : 1,
  248. 'is_init_reordering' => isset($aParams['is_init_reordering']) ? $aParams['is_init_reordering'] : 0,
  249. 'bx_if:restore_ghosts' => [
  250. 'condition' => isset($aParams['is_init_ghosts']) ? $aParams['is_init_ghosts'] : 1,
  251. 'content' => [
  252. 'uploader_instance_name' => $sJsObject,
  253. 'is_init_reordering' => isset($aParams['is_init_reordering']) ? $aParams['is_init_reordering'] : 0,
  254. ]
  255. ],
  256. 'on_upload_before' => 'false',
  257. 'on_upload' => 'false',
  258. 'on_restore_ghosts' => 'false'
  259. ], $aParams));
  260. if(!$bDynamic) {
  261. $this->_oTemplate->addJs($this->_aJs);
  262. $sJsCode = $this->_oTemplate->addJsCodeOnLoadWrapped($sJsCode);
  263. }
  264. else
  265. $sJsCode = $this->_oTemplate->addJsPreloadedWrapped($this->_aJs, $sJsCode);
  266. return $this->addCssJs($bDynamic) . $sJsCode;
  267. }
  268. /**
  269. * add necessary js, css files and js translations
  270. */
  271. public function addCssJs($bDynamic = false)
  272. {
  273. $s = '';
  274. $s .= $this->_oTemplate->addCss($this->_aCss, $bDynamic);
  275. $s .= $this->_oTemplate->addJsTranslation([
  276. '_sys_uploader_confirm_leaving_page',
  277. '_sys_uploader_confirm_close_popup',
  278. '_sys_uploader_upload_canceled',
  279. '_sys_uploader_image_reposition_info',
  280. ], $bDynamic);
  281. return $bDynamic ? $s : '';
  282. }
  283. public function addJs($mixedFile)
  284. {
  285. if(!is_array($mixedFile))
  286. $mixedFile = [$mixedFile];
  287. foreach($mixedFile as $sFile)
  288. if(!in_array($sFile, $this->_aJs))
  289. $this->_aJs[] = $sFile;
  290. }
  291. public function addCss($mixedFile)
  292. {
  293. if(!is_array($mixedFile))
  294. $mixedFile = [$mixedFile];
  295. foreach($mixedFile as $sFile)
  296. if(!in_array($sFile, $this->_aCss))
  297. $this->_aCss[] = $sFile;
  298. }
  299. /**
  300. * Get uploader button title
  301. */
  302. public function getUploaderButtonTitle($mixed = false)
  303. {
  304. // it is overrided in child classes
  305. }
  306. /**
  307. * Show uploader form.
  308. * @return HTML string
  309. */
  310. public function getUploaderForm($isMultiple = true, $iContentId = false, $isPrivate = true)
  311. {
  312. // it is overrided in child classes
  313. }
  314. /**
  315. * Display uploaded, but not saved files - ghosts
  316. * @param $iProfileId - profile id to get orphaned files from
  317. * @param $sFormat - output format, only 'json' output formt is supported
  318. * @param $sImagesTranscoder - transcoder object for files preview for images and videos, false by default - no preview
  319. * @param $iContentId - content id to get orphaned files from, false by default
  320. * @return JSON string
  321. */
  322. public function getGhosts($iProfileId, $sFormat, $sImagesTranscoder = false, $iContentId = false)
  323. {
  324. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  325. $oImagesTranscoder = false;
  326. if ($sImagesTranscoder)
  327. $oImagesTranscoder = BxDolTranscoderImage::getObjectInstance($sImagesTranscoder);
  328. $a = array();
  329. $aGhosts = $oStorage->getGhosts($this->isAdmin($iContentId) && $iContentId ? false : $iProfileId, $iContentId);
  330. foreach ($aGhosts as $aFile) {
  331. $sFileIcon = '';
  332. if ($this->isUseTranscoderForPreview($oImagesTranscoder, $aFile))
  333. $sFileIcon = $oImagesTranscoder->getFileUrl($aFile['id']);
  334. if (!$sFileIcon)
  335. $sFileIcon = $this->_oTemplate->getIconUrl($oStorage->getIconNameByFileName($aFile['file_name']));
  336. $aVars = array (
  337. 'storage_object' => $this->_sStorageObject,
  338. 'file_id' => $aFile['id'],
  339. 'file_type' => $aFile['mime_type'],
  340. 'file_name' => $aFile['file_name'],
  341. 'file_title' => $oStorage->getFileTitle($aFile['file_name']),
  342. 'file_icon' => $sFileIcon,
  343. 'file_url' => $oStorage->getFileUrlById($aFile['id']),
  344. 'file_remote_id' => $aFile['remote_id'],
  345. 'js_instance_name' => $this->_sUploaderJsInstance,
  346. );
  347. $a[$aFile['id']] = array_merge($aVars, $this->getGhostTemplateVars($aFile, $iProfileId, $iContentId, $oStorage, $oImagesTranscoder));
  348. }
  349. if ('array' == $sFormat) {
  350. return $a;
  351. }
  352. else if ('json' == $sFormat) {
  353. return json_encode($a);
  354. } else { // html format is not suported for this data type
  355. return false;
  356. }
  357. }
  358. public function getGhostsWithOrder($iProfileId, $sFormat, $sImagesTranscoder = false, $iContentId = false)
  359. {
  360. $a = $this->getGhosts($iProfileId, 'array', $sImagesTranscoder, $iContentId);
  361. if(!empty($a) && is_array($a))
  362. $a = ['g' => $a, 'o' => array_keys($a)];
  363. if ('json' == $sFormat) {
  364. return json_encode($a);
  365. } else { // html format is not suported for this data type
  366. return $a;
  367. }
  368. }
  369. /**
  370. * Reorder uploaded ghosts.
  371. * @param $iProfileId - profile id to get orphaned files from
  372. * @param $sFormat - output format, only 'json' output formt is supported
  373. * @param $aGhosts - an array of ordered ghosts' IDs.
  374. * @param $iContentId - content id to order orphaned files for, false by default
  375. * @return JSON string
  376. */
  377. public function reorderGhosts($iProfileId, $sFormat, $aGhosts, $iContentId = false)
  378. {
  379. $bResult = true;
  380. if(($oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject)) !== false)
  381. $bResult = $oStorage->reorderGhosts($this->isAdmin($iContentId) && $iContentId ? false : $iProfileId, $iContentId, $aGhosts);
  382. if($sFormat == 'json')
  383. return json_encode($bResult ? [] : ['msg' => _t('_error occured')]);
  384. else
  385. return $bResult;
  386. }
  387. /**
  388. * Delete file by file id, usually ghost file
  389. * @return 'ok' string on success or error string on error
  390. */
  391. public function deleteGhost($iFileId, $iProfileId)
  392. {
  393. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  394. $aFile = $oStorage->getGhost ($iFileId);
  395. if (!$aFile)
  396. $aFile = $oStorage->getFile ($iFileId);
  397. if (!$aFile)
  398. return _t('_error occured');
  399. $oProfile = BxDolProfile::getInstance($iProfileId);
  400. $oAccount = $oProfile ? $oProfile->getAccountObject() : null;
  401. $aProfiles = $oAccount ? $oAccount->getProfiles(false) : array();
  402. if (!isset($aProfiles[$aFile['profile_id']]) && !$this->isAdmin($aFile['content_id']))
  403. return _t('_sys_txt_access_denied');
  404. if (!$oStorage->deleteFile($iFileId))
  405. return $oStorage->getErrorString();
  406. return 'ok';
  407. }
  408. /**
  409. * Delete all ghosts files for the specified profile
  410. * @return number of delete ghost files
  411. */
  412. public function deleteGhostsForProfile($iProfileId, $iContentId = false)
  413. {
  414. $iCount = 0;
  415. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  416. $aGhosts = $oStorage->getGhosts($iProfileId, $iContentId, $iContentId ? true : false);
  417. foreach ($aGhosts as $aFile)
  418. $iCount += $oStorage->deleteFile($aFile['id']);
  419. return $iCount;
  420. }
  421. protected function cleanUploadErrorMessages ()
  422. {
  423. $this->_sUploadErrorMessages = '';
  424. }
  425. public function appendUploadErrorMessage ($s)
  426. {
  427. $this->_sUploadErrorMessages .= ($this->_sUploadErrorMessages ? "\n" : '') . $s;
  428. }
  429. protected function getRestrictionsText ()
  430. {
  431. $sTextRestrictions = '';
  432. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  433. if (!$oStorage)
  434. return '';
  435. $a = $oStorage->getRestrictionsTextArray(bx_get_logged_profile_id());
  436. foreach ($a as $s)
  437. $sTextRestrictions .= '<div class="bx-uploader-msg-info bx-def-font-grayed">' . $s . '</div>';
  438. return $sTextRestrictions;
  439. }
  440. protected function getMaxUploadFileSize ()
  441. {
  442. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  443. if (!$oStorage)
  444. return 0;
  445. return $oStorage->getMaxUploadFileSize(bx_get_logged_profile_id());
  446. }
  447. protected function getAcceptedFilesExtensions ()
  448. {
  449. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  450. if (!$oStorage)
  451. return null;
  452. return $oStorage->getAllowedExtensions();
  453. }
  454. protected function getGhostTemplateVars($aFile, $iProfileId, $iContentId, $oStorage, $oImagesTranscoder)
  455. {
  456. return array();
  457. }
  458. protected function isUseTranscoderForPreview($oImagesTranscoder, $aFile)
  459. {
  460. if (!$oImagesTranscoder)
  461. return false;
  462. return $oImagesTranscoder->isMimeTypeSupported($aFile['mime_type']);
  463. }
  464. protected function isAdmin ($iContentId = 0)
  465. {
  466. return isAdmin();
  467. }
  468. }
  469. /** @} */