1
0

BxDolUploader.php 18 KB

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