BxDolUploader.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. * Uploaders are disigned to work as form field in forms. @see BxDolForm.
  12. *
  13. *
  14. * To add file to any form, use the following form field array:
  15. * @code
  16. * 'attachment' => array(
  17. * 'type' => 'files', // this is new form type, which enable upholders automatically
  18. * 'storage_object' => 'sample', // the storage object, where uploaded files are going to be saved
  19. * 'images_transcoder' => 'sample2', // images transcoder object to use for images preview
  20. * 'uploaders' => array ('sys_simple', 'sys_html5'), // the set of uploaders to use to upload files
  21. * '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
  22. * 'multiple' => true, // allow to upload multiple files per one upload
  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-{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 BxDolFormNested class - use BxDolFormNested 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. * bx_import('BxDolFormNested');
  85. * $oFormNested = new BxDolFormNested('attachment', $aFormNested, 'do_submit');
  86. * @endcode
  87. *
  88. * - 'attachment' is the name of file form field from main form.
  89. * - $aFormNested is form array from previous example.
  90. * - 'do_submit' is main form submit_name; field name of submit form input to determine if form is submitted or not.
  91. *
  92. *
  93. * All 3 variants can have the following replace markers to substitute with real values:
  94. * - {file_id} - uploaded file id
  95. * - {file_name} - uploaded file name with extension
  96. * - {file_title} - uploaded file name without extension
  97. * - {file_icon} - URL to file icon automatically determined by file extension
  98. * - {file_url} - URL to the original file
  99. * - {js_instance_name} - instance of BxDolUploader javascript class
  100. *
  101. */
  102. abstract class BxDolUploader extends BxDol {
  103. protected $_aObject; ///< object properties
  104. protected $_sStorageObject; ///< storage object name
  105. protected $_sUniqId; ///< uniq id used to generate UploaderJsInstance, ResultContainerId, UploadInProgressContainerId and PopupContainerId
  106. protected $_sUploaderJsInstance; ///< uplooader js object instance name
  107. protected $_sResultContainerId; ///< uploading/uploaded objects container id
  108. protected $_sUploadInProgressContainerId; ///< container id where upload in progress element resides
  109. protected $_sPopupContainerId; ///< popup container id
  110. protected $_sUploadErrorMessages; ///< upload error message
  111. protected $_sButtonTemplate; ///< template name for displaying upload button
  112. /**
  113. * constructor
  114. */
  115. protected function __construct($aObject, $sStorageObject, $sUniqId) {
  116. parent::__construct();
  117. $this->_aObject = $aObject;
  118. $this->_sStorageObject = $sStorageObject;
  119. $this->_sUniqId = $sUniqId;
  120. $this->_sUploaderJsInstance = 'glUploader_' . $sUniqId . '_' . $this->_aObject['object'];
  121. $this->_sUploadInProgressContainerId = 'bx-form-input-files-' . $sUniqId . '-upload-in-progress-' . $this->_aObject['object'];
  122. $this->_sPopupContainerId = 'bx-form-input-files-' . $sUniqId . '-popup-wrapper-' . $this->_aObject['object'];
  123. $this->_sResultContainerId = 'bx-form-input-files-' . $sUniqId . '-upload-result';
  124. $this->_sErrorsContainerId = 'bx-form-input-files-' . $sUniqId . '-errors';
  125. $this->_sFormContainerId = 'bx-form-input-files-' . $sUniqId . '-form-cont';
  126. }
  127. static public function getObjectInstance($sObject, $sStorageObject, $sResultContainerId) {
  128. $aObject = BxDolUploaderQuery::getUploaderObject($sObject);
  129. if (!$aObject || !is_array($aObject) || !$aObject['active'])
  130. return false;
  131. $sClass = $aObject['override_class_name'];
  132. if (!empty($aObject['override_class_file']))
  133. require_once(BX_DIRECTORY_PATH_ROOT . $aObject['override_class_file']);
  134. else
  135. bx_import($sClass);
  136. $o = new $sClass($aObject, $sStorageObject, $sResultContainerId);
  137. if (!$o->isInstalled() || !$o->isAvailable())
  138. return false;
  139. return $o;
  140. }
  141. /**
  142. * Is uploader available?
  143. * @return boolean
  144. */
  145. function isAvailable() {
  146. return $this->_aObject['active'] ? true : false;
  147. }
  148. /**
  149. * Are required php modules installed for this uploader ?
  150. * @return boolean
  151. */
  152. public function isInstalled() {
  153. return true;
  154. }
  155. public function getNameJsInstanceUploader() {
  156. return $this->_sUploaderJsInstance;
  157. }
  158. public function getIdContainerResult() {
  159. return $this->_sResultContainerId;
  160. }
  161. public function getIdContainerUploadInProgress() {
  162. return $this->_sUploadInProgressContainerId;
  163. }
  164. public function getIdContainerPopup() {
  165. return $this->_sPopupContainerId;
  166. }
  167. public function getIdContainerErrors() {
  168. return $this->_sErrorsContainerId;
  169. }
  170. /**
  171. * Handle uploads here.
  172. * @param $mixedFiles as usual $_FILES['some_name'] array, but maybe some other params depending on the uploader
  173. * @return nothing, but if some files failed to upload, the actual error message can be determined by calling BxDolUploader::getUploadErrorMessages()
  174. */
  175. public function handleUploads ($iProfileId, $mixedFiles, $isMultiple = true, $iContentId = false) {
  176. bx_import('BxDolStorage');
  177. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  178. if (false == ($aMultipleFiles = $oStorage->convertMultipleFilesArray($mixedFiles)))
  179. $aMultipleFiles = array($mixedFiles);
  180. if (!$isMultiple)
  181. $this->cleanupGhostsForProfile($iProfileId, $iContentId);
  182. foreach ($aMultipleFiles as $aFile) {
  183. $iId = $oStorage->storeFileFromForm($aFile, true, $iProfileId, $iContentId);
  184. if (!$iId)
  185. $this->appendUploadErrorMessage(_t('_sys_uploader_err_msg', $aFile['name'], $oStorage->getErrorString()));
  186. if (!$isMultiple)
  187. break;
  188. }
  189. echo '<script>window.parent.' . $this->getNameJsInstanceUploader() . '.onUploadCompleted(\'' . bx_js_string($this->getUploadErrorMessages(), BX_ESCAPE_STR_APOS) . '\');</script>';
  190. }
  191. public function getUploadErrorMessages ($sFormat = 'HTML') {
  192. if ('HTML' == $sFormat)
  193. return nl2br($this->_sUploadErrorMessages);
  194. else
  195. return $this->_sUploadErrorMessages;
  196. }
  197. /**
  198. * Show uploader button.
  199. * @return HTML string
  200. */
  201. public function getUploaderButton($mixedGhostTemplate, $isMultiple = true, $aParams = array()) {
  202. $oTemplate = BxDolTemplate::getInstance();
  203. $oTemplate->addCss('uploaders.css');
  204. $oTemplate->addJs('BxDolUploader.js');
  205. $oTemplate->addJsTranslation(array(
  206. '_sys_uploader_confirm_leaving_page',
  207. '_sys_uploader_confirm_close_popup',
  208. '_sys_uploader_upload_canceled',
  209. ));
  210. $sJsValue = '';
  211. if (is_array($mixedGhostTemplate)) {
  212. $sJsValue = "{\n";
  213. foreach ($mixedGhostTemplate as $iFileId => $s) {
  214. $sJsValue .= $iFileId . ':' . "'" . bx_js_string($s, BX_ESCAPE_STR_APOS) . "',\n";
  215. }
  216. $sJsValue = substr($sJsValue, 0, -2);
  217. $sJsValue .= "}\n";
  218. } else {
  219. $sJsValue = "'" . bx_js_string($mixedGhostTemplate, BX_ESCAPE_STR_APOS) . "'";
  220. }
  221. $aParamsDefault = array (
  222. 'uploader_instance_name' => $this->getNameJsInstanceUploader(),
  223. 'engine' => $this->_aObject['object'],
  224. 'storage_object' => $this->_sStorageObject,
  225. 'uniq_id' => $this->_sUniqId,
  226. 'template_ghost' => $sJsValue,
  227. 'multiple' => $isMultiple ? 1 : 0,
  228. );
  229. $aParams = array_merge($aParamsDefault, $aParams);
  230. return $oTemplate->parseHtmlByName($this->_sButtonTemplate, $aParams);
  231. }
  232. /**
  233. * Get uploader button title
  234. */
  235. public function getUploaderButtonTitle($mixed = false) {
  236. // it is overrided in child classes
  237. }
  238. /**
  239. * Show uploader form.
  240. * @return HTML string
  241. */
  242. public function getUploaderForm($isMultiple = true, $iContentId = false) {
  243. // it is overrided in child classes
  244. }
  245. /**
  246. * Display uploaded, but not saved files - ghosts
  247. * @return HTML or JSON string
  248. */
  249. public function getGhosts($iProfileId, $sFormat, $sImagesTranscoder = false, $iContentId = false) {
  250. $oTemplate = BxDolTemplate::getInstance();
  251. bx_import('BxDolStorage');
  252. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  253. $oImagesTranscoder = false;
  254. if ($sImagesTranscoder) {
  255. bx_import('BxDolImageTranscoder');
  256. $oImagesTranscoder = BxDolImageTranscoder::getObjectInstance($sImagesTranscoder);
  257. }
  258. $a = '';
  259. $aGhosts = $oStorage->getGhosts($iProfileId, $iContentId);
  260. foreach ($aGhosts as $aFile) {
  261. $sFileIcon = $oImagesTranscoder && 0 == strncmp($aFile['mime_type'], 'image/', 6) ? $oImagesTranscoder->getImageUrl($aFile['id']) : $oTemplate->getIconUrl($oStorage->getIconNameByFileName($aFile['file_name']));
  262. $a[$aFile['id']] = array (
  263. 'file_id' => $aFile['id'],
  264. 'file_name' => $aFile['file_name'],
  265. 'file_title' => $oStorage->getFileTitle($aFile['file_name']),
  266. 'file_icon' => $sFileIcon,
  267. 'file_url' => $oStorage->getFileUrlById($aFile['id']),
  268. 'js_instance_name' => $this->_sUploaderJsInstance,
  269. );
  270. }
  271. if ('json' == $sFormat) {
  272. require_once(BX_DIRECTORY_PATH_PLUGINS . 'Services_JSON.php');
  273. $oParser = new Services_JSON();
  274. return $oParser->encode($a);
  275. } else { // html format is not suported for this data type
  276. return false;
  277. }
  278. }
  279. /**
  280. * Delete file by file id, usually ghost file
  281. * @return 'ok' string on success or error string on error
  282. */
  283. public function deleteGhost($iFileId, $iProfileId) {
  284. bx_import('BxDolStorage');
  285. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  286. $aFile = $oStorage->getFile ($iFileId);
  287. if (!$aFile)
  288. return _t('_Error Occured');
  289. if ($aFile['profile_id'] != $iProfileId)
  290. return _t('_Error Occured');
  291. if (!$oStorage->deleteFile($iFileId))
  292. return $oStorage->getErrorString();
  293. return 'ok';
  294. }
  295. /**
  296. * Delete all ghosts files for the specified profile
  297. * @return number of delete ghost files
  298. */
  299. public function cleanupGhostsForProfile($iProfileId, $iContentId = false) {
  300. $iCount = 0;
  301. bx_import('BxDolStorage');
  302. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  303. $aGhosts = $oStorage->getGhosts($iProfileId, $iContentId);
  304. foreach ($aGhosts as $aFile)
  305. $iCount += $oStorage->afterUploadCleanup($aFile['id'], $iProfileId);
  306. return $iCount;
  307. }
  308. protected function cleanUploadErrorMessages () {
  309. $this->_sUploadErrorMessages = '';
  310. }
  311. protected function appendUploadErrorMessage ($s) {
  312. $this->_sUploadErrorMessages .= ($this->_sUploadErrorMessages ? "\n" : '') . $s;
  313. }
  314. protected function getRestrictionsText () {
  315. $sTextRestrictions = '';
  316. bx_import('BxDolStorage');
  317. $oStorage = BxDolStorage::getObjectInstance($this->_sStorageObject);
  318. if (!$oStorage)
  319. return '';
  320. $a = $oStorage->getRestrictionsTextArray(bx_get_logged_profile_id());
  321. foreach ($a as $s)
  322. $sTextRestrictions .= '<div class="bx-uploader-msg-info">' . $s . '</div>';
  323. return $sTextRestrictions;
  324. }
  325. }
  326. /** @} */