BxDolUploader.php 14 KB

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