BxDolUploader.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. <?php defined('BX_DOL') or die('hack attempt');
  2. /**
  3. * Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
  4. * CC-BY License - http://creativecommons.org/licenses/by/3.0/
  5. *
  6. * @defgroup TridentCore Trident Core
  7. * @{
  8. */
  9. /**
  10. * @page objects
  11. * @section uploader Uploader
  12. * @ref BxDolUploader
  13. */
  14. /**
  15. * Uploaders are disigned to work as form field in forms. @see BxDolForm.
  16. *
  17. *
  18. * To add file to any form, use the following form field array:
  19. * @code
  20. * 'attachment' => array(
  21. * 'type' => 'files', // this is new form type, which enable upholders automatically
  22. * 'storage_object' => 'sample', // the storage object, where uploaded files are going to be saved
  23. * 'images_transcoder' => 'sample2', // images transcoder object to use for images preview
  24. * 'uploaders' => array ('sys_simple', 'sys_html5'), // the set of uploaders to use to upload files
  25. * 'upload_buttons_titles' => array('sys_simple' => 'Upload one by one', 'sys_html5' => 'Upload several files in bulk'); // change default button titles, array with button names, or string to assign to all bnuttons
  26. * 'multiple' => true, // allow to upload multiple files per one upload
  27. * 'content_id' => 4321, // content id to associate ghost files with
  28. * 'ghost_template' => $mixedGhostTemplate, // template for nested form
  29. * 'name' => 'attachment', // name of file form field, resulted file id is assigned to this field name
  30. * 'caption' => _t('Attachments'), // form field caption
  31. * ),
  32. * @endcode
  33. *
  34. *
  35. * Available uploaders:
  36. * - sys_simple - upload files using standard HTML forms.
  37. * - sys_html5 - upload files using AJAX uploader with multiple files selection support (without flash),
  38. * it works in Firefox and WebKit(Safari, Chrome) browsers only, but has fallback for other browsers (IE, Opera).
  39. *
  40. *
  41. * Uploaded files are showed as "nested" forms.
  42. * You can pass nested form in 'ghost_template' parameter.
  43. * If you don't pass anything in 'ghost_template' parameter, then only file id is passed upon form submission.
  44. * The nested form can be declared using the different ways:
  45. *
  46. *
  47. * 1. Pass template as string - just plain string with HTML, for example:
  48. *
  49. * @code
  50. * <div id="bx-uploader-file-{file_id}" class="bx-uploader-ghost">
  51. * <div style="border:2px dotted green; padding:10px; margin-bottom:10px;">
  52. * <input type="hidden" name="f[]" value="{file_id}" />
  53. * {file_name} <br />
  54. * <a href="javascript:void(0);" onclick="{js_instance_name}.deleteGhost('{file_id}')">delete</a>
  55. * </div>
  56. * </div>
  57. * @endcode
  58. *
  59. *
  60. * 2. Pass form array - regular form array, but with inputs array only, for example:
  61. *
  62. * @code
  63. * array (
  64. * 'inputs' => array (
  65. * 'file_name' => array (
  66. * 'type' => 'text',
  67. * 'name' => 'file_name[]',
  68. * 'value' => '{file_title}',
  69. * 'caption' => _t('Caption'),
  70. * ),
  71. * 'file_desc' => array (
  72. * 'type' => 'textarea',
  73. * 'name' => 'file_desc[]',
  74. * 'caption' => _t('Description'),
  75. * ),
  76. * ),
  77. * );
  78. * @endcode
  79. *
  80. * Array is automatically modified to add necessary form attributes to work as nested form,
  81. * file id field is added automatically as hidden input as well.
  82. *
  83. *
  84. * 3. Pass instance of BxDolFormNested class - use BxDolFormNested class or its custom subclass;
  85. * to create instance use the same form array as in the previous variant, for example:
  86. *
  87. * @code
  88. * $oFormNested = new BxDolFormNested('attachment', $aFormNested, 'do_submit');
  89. * @endcode
  90. *
  91. * - 'attachment' is the name of file form field from main form.
  92. * - $aFormNested is form array from previous example.
  93. * - 'do_submit' is main form submit_name; field name of submit form input to determine if form is submitted or not.
  94. *
  95. *
  96. * All 3 variants can have the following replace markers to substitute with real values:
  97. * - {file_id} - uploaded file id
  98. * - {file_name} - uploaded file name with extension
  99. * - {file_title} - uploaded file name without extension
  100. * - {file_icon} - URL to file icon automatically determined by file extension
  101. * - {file_url} - URL to the original file
  102. * - {js_instance_name} - instance of BxDolUploader javascript class
  103. *
  104. */
  105. abstract class BxDolUploader extends BxDol
  106. {
  107. protected $_oTemplate;
  108. protected $_aObject; ///< object properties
  109. protected $_sStorageObject; ///< storage object name
  110. protected $_sUniqId; ///< uniq id used to generate UploaderJsInstance, ResultContainerId, UploadInProgressContainerId and PopupContainerId
  111. protected $_sUploaderJsInstance; ///< uplooader js object instance name
  112. protected $_sResultContainerId; ///< uploading/uploaded objects container id
  113. protected $_sUploadInProgressContainerId; ///< container id where upload in progress element resides
  114. protected $_sPopupContainerId; ///< popup container id
  115. protected $_sUploadErrorMessages; ///< upload error message
  116. protected $_sButtonTemplate; ///< template name for displaying upload button
  117. /**
  118. * constructor
  119. */
  120. protected function __construct($aObject, $sStorageObject, $sUniqId)
  121. {
  122. parent::__construct();
  123. $this->_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. }
  134. static public function getObjectInstance($sObject, $sStorageObject, $sResultContainerId)
  135. {
  136. $aObject = BxDolUploaderQuery::getUploaderObject($sObject);
  137. if (!$aObject || !is_array($aObject) || !$aObject['active'])
  138. return false;
  139. $sClass = $aObject['override_class_name'];
  140. if (!empty($aObject['override_class_file']))
  141. require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
  142. $o = new $sClass($aObject, $sStorageObject, $sResultContainerId);
  143. if (!$o->isInstalled() || !$o->isAvailable())
  144. return false;
  145. return $o;
  146. }
  147. /**
  148. * Is uploader available?
  149. * @return boolean
  150. */
  151. function isAvailable()
  152. {
  153. return $this->_aObject['active'] ? true : false;
  154. }
  155. /**
  156. * Are required php modules installed for this uploader ?
  157. * @return boolean
  158. */
  159. public function isInstalled()
  160. {
  161. return true;
  162. }
  163. public function getNameJsInstanceUploader()
  164. {
  165. return $this->_sUploaderJsInstance;
  166. }
  167. public function getIdContainerResult()
  168. {
  169. return $this->_sResultContainerId;
  170. }
  171. public function getIdContainerUploadInProgress()
  172. {
  173. return $this->_sUploadInProgressContainerId;
  174. }
  175. public function getIdContainerPopup()
  176. {
  177. return $this->_sPopupContainerId;
  178. }
  179. public function getIdContainerErrors()
  180. {
  181. return $this->_sErrorsContainerId;
  182. }
  183. /**
  184. * Handle uploads here.
  185. * @param $mixedFiles as usual $_FILES['some_name'] array, but maybe some other params depending on the uploader
  186. * @return nothing, but if some files failed to upload, the actual error message can be determined by calling BxDolUploader::getUploadErrorMessages()
  187. */
  188. public function handleUploads ($iProfileId, $mixedFiles, $isMultiple = true, $iContentId = false, $bPrivate = true)
  189. {
  190. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  191. if (false == ($aMultipleFiles = $oStorage->convertMultipleFilesArray($mixedFiles)))
  192. $aMultipleFiles = array($mixedFiles);
  193. if (!$isMultiple)
  194. $this->cleanupGhostsForProfile($iProfileId, $iContentId);
  195. foreach ($aMultipleFiles as $aFile) {
  196. $iId = $oStorage->storeFileFromForm($aFile, $bPrivate, $iProfileId, $iContentId);
  197. if (!$iId)
  198. $this->appendUploadErrorMessage(_t('_sys_uploader_err_msg', $aFile['name'], $oStorage->getErrorString()));
  199. if (!$isMultiple)
  200. break;
  201. }
  202. echo '<script>window.parent.' . $this->getNameJsInstanceUploader() . '.onUploadCompleted(\'' . bx_js_string($this->getUploadErrorMessages(), BX_ESCAPE_STR_APOS) . '\');</script>';
  203. }
  204. public function getUploadErrorMessages ($sFormat = 'HTML')
  205. {
  206. if ('HTML' == $sFormat)
  207. return nl2br($this->_sUploadErrorMessages);
  208. else
  209. return $this->_sUploadErrorMessages;
  210. }
  211. /**
  212. * Show uploader button.
  213. * @return HTML string
  214. */
  215. public function getUploaderButton($mixedGhostTemplate, $isMultiple = true, $aParams = array())
  216. {
  217. $this->addCssJs ();
  218. $sJsValue = '';
  219. if (is_array($mixedGhostTemplate)) {
  220. $sJsValue = "{\n";
  221. foreach ($mixedGhostTemplate as $iFileId => $s) {
  222. $sJsValue .= $iFileId . ':' . "'" . bx_js_string($s, BX_ESCAPE_STR_APOS) . "',\n";
  223. }
  224. $sJsValue = substr($sJsValue, 0, -2);
  225. $sJsValue .= "}\n";
  226. } else {
  227. $sJsValue = "'" . bx_js_string($mixedGhostTemplate, BX_ESCAPE_STR_APOS) . "'";
  228. }
  229. $aParamsDefault = array (
  230. 'uploader_instance_name' => $this->getNameJsInstanceUploader(),
  231. 'engine' => $this->_aObject['object'],
  232. 'storage_object' => $this->_sStorageObject,
  233. 'uniq_id' => $this->_sUniqId,
  234. 'template_ghost' => $sJsValue,
  235. 'multiple' => $isMultiple ? 1 : 0,
  236. 'storage_private' => isset($aParams['storage_private']) ? $aParams['storage_private'] : 1,
  237. );
  238. $aParams = array_merge($aParamsDefault, $aParams);
  239. return $this->_oTemplate->parseHtmlByName($this->_sButtonTemplate, $aParams);
  240. }
  241. /**
  242. * add necessary js, css files and js translations
  243. */
  244. public function addCssJs ()
  245. {
  246. $this->_oTemplate->addCss('uploaders.css');
  247. $this->_oTemplate->addJs('BxDolUploader.js');
  248. $this->_oTemplate->addJsTranslation(array(
  249. '_sys_uploader_confirm_leaving_page',
  250. '_sys_uploader_confirm_close_popup',
  251. '_sys_uploader_upload_canceled',
  252. ));
  253. }
  254. /**
  255. * Get uploader button title
  256. */
  257. public function getUploaderButtonTitle($mixed = false)
  258. {
  259. // it is overrided in child classes
  260. }
  261. /**
  262. * Show uploader form.
  263. * @return HTML string
  264. */
  265. public function getUploaderForm($isMultiple = true, $iContentId = false, $isPrivate = true)
  266. {
  267. // it is overrided in child classes
  268. }
  269. /**
  270. * Display uploaded, but not saved files - ghosts
  271. * @param $iProfileId - profile id to get orphaned files from
  272. * @param $sFormat - output format, only 'json' output formt is supported
  273. * @param $sImagesTranscoder - transcoder object for files preview for images and videos, false by default - no preview
  274. * @param $iContentId - content id to get orphaned files from, false by default
  275. * @return JSON string
  276. */
  277. public function getGhosts($iProfileId, $sFormat, $sImagesTranscoder = false, $iContentId = false)
  278. {
  279. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  280. $oImagesTranscoder = false;
  281. if ($sImagesTranscoder)
  282. $oImagesTranscoder = BxDolTranscoderImage::getObjectInstance($sImagesTranscoder);
  283. $a = '';
  284. $aGhosts = $oStorage->getGhosts($iProfileId, $iContentId);
  285. foreach ($aGhosts as $aFile) {
  286. $sFileIcon = '';
  287. if ($oImagesTranscoder && (0 == strncmp($aFile['mime_type'], 'image/', 6) || 0 == strncmp($aFile['mime_type'], 'video/', 6)))
  288. $sFileIcon = $oImagesTranscoder->getFileUrl($aFile['id']);
  289. if (!$sFileIcon)
  290. $sFileIcon = $this->_oTemplate->getIconUrl($oStorage->getIconNameByFileName($aFile['file_name']));
  291. $aVars = array (
  292. 'file_id' => $aFile['id'],
  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 ('json' == $sFormat) {
  302. return json_encode($a);
  303. } else { // html format is not suported for this data type
  304. return false;
  305. }
  306. }
  307. /**
  308. * Delete file by file id, usually ghost file
  309. * @return 'ok' string on success or error string on error
  310. */
  311. public function deleteGhost($iFileId, $iProfileId)
  312. {
  313. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  314. $aFile = $oStorage->getFile ($iFileId);
  315. if (!$aFile)
  316. return _t('_Error Occured');
  317. if ($aFile['profile_id'] != $iProfileId)
  318. return _t('_Error Occured');
  319. if (!$oStorage->deleteFile($iFileId))
  320. return $oStorage->getErrorString();
  321. return 'ok';
  322. }
  323. /**
  324. * Delete all ghosts files for the specified profile
  325. * @return number of delete ghost files
  326. */
  327. public function cleanupGhostsForProfile($iProfileId, $iContentId = false)
  328. {
  329. $iCount = 0;
  330. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  331. $aGhosts = $oStorage->getGhosts($iProfileId, $iContentId);
  332. foreach ($aGhosts as $aFile)
  333. $iCount += $oStorage->afterUploadCleanup($aFile['id'], $iProfileId);
  334. return $iCount;
  335. }
  336. protected function cleanUploadErrorMessages ()
  337. {
  338. $this->_sUploadErrorMessages = '';
  339. }
  340. protected function appendUploadErrorMessage ($s)
  341. {
  342. $this->_sUploadErrorMessages .= ($this->_sUploadErrorMessages ? "\n" : '') . $s;
  343. }
  344. protected function getRestrictionsText ()
  345. {
  346. $sTextRestrictions = '';
  347. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  348. if (!$oStorage)
  349. return '';
  350. $a = $oStorage->getRestrictionsTextArray(bx_get_logged_profile_id());
  351. foreach ($a as $s)
  352. $sTextRestrictions .= '<div class="bx-uploader-msg-info bx-def-font-grayed">' . $s . '</div>';
  353. return $sTextRestrictions;
  354. }
  355. protected function getGhostTemplateVars($aFile, $iProfileId, $iContentId, $oStorage, $oImagesTranscoder)
  356. {
  357. return array();
  358. }
  359. }
  360. /** @} */