bsfileuploadfieldrenderer.class.inc.php 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. namespace Combodo\iTop\Renderer\Bootstrap\FieldRenderer;
  19. use \utils;
  20. use \Dict;
  21. use \UserRights;
  22. use \InlineImage;
  23. use \DBObjectSet;
  24. use \DBObjectSearch;
  25. use \MetaModel;
  26. use \Combodo\iTop\Renderer\FieldRenderer;
  27. use \Combodo\iTop\Renderer\RenderingOutput;
  28. use \Combodo\iTop\Form\Field\LinkedSetField;
  29. /**
  30. * Description of BsFileUploadFieldRenderer
  31. *
  32. * @author Guillaume Lajarige <guillaume.lajarige@combodo.com>
  33. */
  34. class BsFileUploadFieldRenderer extends FieldRenderer
  35. {
  36. /**
  37. * Returns a RenderingOutput for the FieldRenderer's Field
  38. *
  39. * @return \Combodo\iTop\Renderer\RenderingOutput
  40. */
  41. public function Render()
  42. {
  43. $oOutput = new RenderingOutput();
  44. $sObjectClass = get_class($this->oField->GetObject());
  45. $sIsDeleteAllowed = ($this->oField->GetAllowDelete()) ? 'true' : 'false';
  46. $sDeleteBtn = Dict::S('Portal:Button:Delete');
  47. $sTempId = session_id() . '_' . $this->oField->GetTransactionId();
  48. $sUploadDropZoneLabel = Dict::S('Portal:Attachments:DropZone:Message');
  49. // Starting field container
  50. $oOutput->AddHtml('<div class="form-group">');
  51. // Field label
  52. if ($this->oField->GetLabel() !== '')
  53. {
  54. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
  55. }
  56. // Field feedback
  57. $oOutput->AddHtml('<div class="help-block"></div>');
  58. // Starting files container
  59. $oOutput->AddHtml('<div class="fileupload_field_content">');
  60. // Files list
  61. $oOutput->AddHtml('<div class="attachments_container row">');
  62. $this->PrepareExistingFiles($oOutput);
  63. $oOutput->Addhtml('</div>');
  64. // Removing upload input if in read only
  65. // TODO : Add max upload size when itop attachment has been refactored
  66. if (!$this->oField->GetReadOnly())
  67. {
  68. $oOutput->AddHtml('<div class="upload_container row">' . Dict::S('Attachments:AddAttachment') . '<input type="file" id="' . $this->oField->GetGlobalId() . '" name="' . $this->oField->GetId() . '" /><span class="loader glyphicon glyphicon-refresh"></span></div>');
  69. }
  70. // Ending files container
  71. $oOutput->AddHtml('</div>');
  72. // Ending field container
  73. $oOutput->AddHtml('</div>');
  74. // JS for file upload
  75. // Note : This is based on itop-attachement/main.attachments.php
  76. $oOutput->AddJs(
  77. <<<EOF
  78. var RemoveAttachment = function(sAttId)
  79. {
  80. $('#attachment_' + sAttId).attr('name', 'removed_attachments[]');
  81. $('#display_attachment_' + sAttId).hide();
  82. };
  83. $('#{$this->oField->GetGlobalId()}').fileupload({
  84. url: '{$this->oField->GetUploadEndpoint()}',
  85. formData: { operation: 'add', temp_id: '{$sTempId}', object_class: '{$sObjectClass}', 'field_name': '{$this->oField->GetId()}' },
  86. dataType: 'json',
  87. pasteZone: null, // Don't accept files via Chrome's copy/paste
  88. done: function (e, data) {
  89. if(data.result.error !== undefined)
  90. {
  91. console.log(data.result.error);
  92. }
  93. else
  94. {
  95. var sDownloadLink = '{$this->oField->GetDownloadEndpoint()}'.replace(/-sAttachmentId-/, data.result.att_id);
  96. $(this).closest('.fileupload_field_content').find('.attachments_container').append(
  97. '<div class="attachment col-xs-6 col-sm-3 col-md-2" id="display_attachment_'+data.result.att_id+'">'+
  98. ' <a data-preview="'+data.result.preview+'" href="'+sDownloadLink+'" title="'+data.result.msg+'">'+
  99. ' <div class="attachment_icon"><img src="'+data.result.icon+'"></div>'+
  100. ' <div class="attachment_name">'+data.result.msg+'</div>'+
  101. ' <input id="attachment_'+data.result.att_id+'" type="hidden" name="attachments[]" value="'+data.result.att_id+'"/>'+
  102. ' </a>'+
  103. ' <input type="button" class="btn btn-xs btn-danger hidden" value="{$sDeleteBtn}"/>'+
  104. '</div>'
  105. );
  106. // Preview tooltip
  107. if(data.result.preview){
  108. $('#display_attachment_'+data.result.att_id).tooltip({
  109. html: true,
  110. title: function(){ return '<img src="'+sDownloadLink+'" style="max-width: 100%;" />'; }
  111. });
  112. }
  113. // Showing remove button on hover
  114. $('#display_attachment_'+data.result.att_id).hover( function(){
  115. $(this).children(':button').toggleClass('hidden');
  116. });
  117. // Remove button handler
  118. $('#display_attachment_'+data.result.att_id+' :button').click(function(oEvent){
  119. oEvent.preventDefault();
  120. RemoveAttachment(data.result.att_id);
  121. });
  122. }
  123. },
  124. start: function() {
  125. // Scrolling to dropzone so the user can see that attachments are uploaded
  126. $(this)[0].scrollIntoView();
  127. // Showing loader
  128. $(this).closest('.upload_container').find('.loader').css('visibility', 'visible');
  129. },
  130. stop: function() {
  131. // Hiding the loader
  132. $(this).closest('.upload_container').find('.loader').css('visibility', 'hidden');
  133. // Adding this field to the touched fields of the field set so the cancel event is called if necessary
  134. $(this).closest(".field_set").trigger("field_change", {
  135. id: '{$this->oField->GetGlobalId()}',
  136. name: '{$this->oField->GetId()}'
  137. });
  138. }
  139. });
  140. // Preview tooltip
  141. $('.attachment [data-preview="true"]').each(function(iIndex, oElem){
  142. $(oElem).parent().tooltip({
  143. html: true,
  144. title: function(){ return '<img src="'+$(oElem).attr('href')+'" style="max-width: 100%;" />'; }
  145. });
  146. });
  147. // Remove button handler
  148. $('.attachments_container .attachment :button').click(function(oEvent){
  149. oEvent.preventDefault();
  150. RemoveAttachment($(this).closest('.attachment').find(':input[name="attachments[]"]').val());
  151. });
  152. // Remove button showing
  153. if($sIsDeleteAllowed)
  154. {
  155. $('.attachment').hover( function(){
  156. $(this).find(':button').toggleClass('hidden');
  157. });
  158. }
  159. // Handles a drag / drop overlay
  160. if($('#drag_overlay').length === 0)
  161. {
  162. $('body').append( $('<div id="drag_overlay" class="global_overlay"><div class="overlay_content"><div class="content_uploader"><div class="icon glyphicon glyphicon-cloud-upload"></div><div class="message">{$sUploadDropZoneLabel}</div></div></div></div>') );
  163. }
  164. // Handles highlighting of the drop zone
  165. // Note : This is inspired by itop-attachments/main.attachments.php
  166. $(document).on('dragover', function(oEvent){
  167. var bFiles = false;
  168. if (oEvent.dataTransfer && oEvent.dataTransfer.types)
  169. {
  170. for (var i = 0; i < oEvent.dataTransfer.types.length; i++)
  171. {
  172. if (oEvent.dataTransfer.types[i] == "application/x-moz-nativeimage")
  173. {
  174. bFiles = false; // mozilla contains "Files" in the types list when dragging images inside the page, but it also contains "application/x-moz-nativeimage" before
  175. break;
  176. }
  177. if (oEvent.dataTransfer.types[i] == "Files")
  178. {
  179. bFiles = true;
  180. break;
  181. }
  182. }
  183. }
  184. if (!bFiles) return; // Not dragging files
  185. var oDropZone = $('#drag_overlay');
  186. var oTimeout = window.dropZoneTimeout;
  187. // This is to detect when there is no drag over because there is no "drag out" event
  188. if (!oTimeout) {
  189. oDropZone.removeClass('drag_out').addClass('drag_in');
  190. } else {
  191. clearTimeout(oTimeout);
  192. }
  193. window.dropZoneTimeout = setTimeout(function () {
  194. window.dropZoneTimeout = null;
  195. oDropZone.removeClass('drag_in').addClass('drag_out');
  196. }, 200);
  197. });
  198. EOF
  199. );
  200. return $oOutput;
  201. }
  202. /**
  203. *
  204. * @param RenderingOutput $oOutput
  205. */
  206. protected function PrepareExistingFiles(RenderingOutput &$oOutput)
  207. {
  208. $sObjectClass = get_class($this->oField->GetObject());
  209. $sDeleteBtn = Dict::S('Portal:Button:Delete');
  210. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  211. $oSet = new DBObjectSet($oSearch, array(), array('class' => $sObjectClass, 'item_id' => $this->oField->GetObject()->GetKey()));
  212. // If in read only and no attachments, we display a short message
  213. if ($this->oField->GetReadOnly() && ($oSet->Count() === 0))
  214. {
  215. $oOutput->AddHtml(Dict::S('Attachments:NoAttachment'));
  216. }
  217. else
  218. {
  219. while ($oAttachment = $oSet->Fetch())
  220. {
  221. $iAttId = $oAttachment->GetKey();
  222. $oDoc = $oAttachment->Get('contents');
  223. $sFileName = htmlentities($oDoc->GetFileName(), ENT_QUOTES, 'UTF-8');
  224. $sIcon = utils::GetAbsoluteUrlAppRoot() . 'env-' . utils::GetCurrentEnvironment() . '/itop-attachments/icons/image.png';
  225. $sPreview = $oDoc->IsPreviewAvailable() ? 'true' : 'false';
  226. $sDownloadLink = str_replace('-sAttachmentId-', $iAttId, $this->oField->GetDownloadEndpoint());
  227. $oOutput->Addhtml(
  228. <<<EOF
  229. <div class="attachment col-xs-6 col-sm-3 col-md-2" id="display_attachment_{$iAttId}">
  230. <a data-preview="{$sPreview}" href="{$sDownloadLink}" title="{$sFileName}">
  231. <div class="attachment_icon"><img src="{$sIcon}"></div>
  232. <div class="attachment_name">{$sFileName}</div>
  233. <input id="attachment_{$iAttId}" type="hidden" name="attachments[]" value="{$iAttId}"/>
  234. </a>
  235. <input id="btn_remove_{$iAttId}" type="button" class="btn btn-xs btn-danger hidden" value="{$sDeleteBtn}"/>
  236. </div>
  237. EOF
  238. );
  239. }
  240. }
  241. }
  242. }