bsfileuploadfieldrenderer.class.inc.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. // Copyright (C) 2010-2017 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. $oOutput->AddCssClass('form_field_' . $this->oField->GetDisplayMode());
  45. $sObjectClass = get_class($this->oField->GetObject());
  46. $sIsDeleteAllowed = ($this->oField->GetAllowDelete() && !$this->oField->GetReadOnly()) ? 'true' : 'false';
  47. $sDeleteBtn = Dict::S('Portal:Button:Delete');
  48. $sTempId = session_id() . '_' . $this->oField->GetTransactionId();
  49. $sUploadDropZoneLabel = Dict::S('Portal:Attachments:DropZone:Message');
  50. // Starting field container
  51. $oOutput->AddHtml('<div class="form-group">');
  52. // Label
  53. $oOutput->AddHtml('<div class="form_field_label">');
  54. if ($this->oField->GetLabel() !== '')
  55. {
  56. $oOutput->AddHtml('<label for="' . $this->oField->GetGlobalId() . '" class="control-label">')->AddHtml($this->oField->GetLabel(), true)->AddHtml('</label>');
  57. }
  58. $oOutput->AddHtml('</div>');
  59. // Value
  60. $oOutput->AddHtml('<div class="form_field_control">');
  61. // - Field feedback
  62. $oOutput->AddHtml('<div class="help-block"></div>');
  63. // Starting files container
  64. $oOutput->AddHtml('<div class="fileupload_field_content">');
  65. // Files list
  66. $oOutput->AddHtml('<div class="attachments_container row">');
  67. $this->PrepareExistingFiles($oOutput);
  68. $oOutput->Addhtml('</div>');
  69. // Removing upload input if in read only
  70. // TODO : Add max upload size when itop attachment has been refactored
  71. if (!$this->oField->GetReadOnly())
  72. {
  73. $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>');
  74. }
  75. // Ending files container
  76. $oOutput->AddHtml('</div>');
  77. $oOutput->AddHtml('</div>');
  78. // Ending field container
  79. $oOutput->AddHtml('</div>');
  80. // JS for file upload
  81. // Note : This is based on itop-attachement/main.attachments.php
  82. $oOutput->AddJs(
  83. <<<EOF
  84. var RemoveAttachment = function(sAttId)
  85. {
  86. $('#attachment_' + sAttId).attr('name', 'removed_attachments[]');
  87. $('#display_attachment_' + sAttId).hide();
  88. };
  89. $('#{$this->oField->GetGlobalId()}').fileupload({
  90. url: '{$this->oField->GetUploadEndpoint()}',
  91. formData: { operation: 'add', temp_id: '{$sTempId}', object_class: '{$sObjectClass}', 'field_name': '{$this->oField->GetId()}' },
  92. dataType: 'json',
  93. pasteZone: null, // Don't accept files via Chrome's copy/paste
  94. done: function (e, data) {
  95. if((data.result.error !== undefined) && window.console)
  96. {
  97. console.log(data.result.error);
  98. }
  99. else
  100. {
  101. var sDownloadLink = '{$this->oField->GetDownloadEndpoint()}'.replace(/-sAttachmentId-/, data.result.att_id);
  102. $(this).closest('.fileupload_field_content').find('.attachments_container').append(
  103. '<div class="attachment col-xs-6 col-sm-3 col-md-2" id="display_attachment_'+data.result.att_id+'">'+
  104. ' <a data-preview="'+data.result.preview+'" href="'+sDownloadLink+'" title="'+data.result.msg+'">'+
  105. ' <div class="attachment_icon"><img src="'+data.result.icon+'"></div>'+
  106. ' <div class="attachment_name">'+data.result.msg+'</div>'+
  107. ' <input id="attachment_'+data.result.att_id+'" type="hidden" name="attachments[]" value="'+data.result.att_id+'"/>'+
  108. ' </a>'+
  109. ' <input type="button" class="btn btn-xs btn-danger hidden" value="{$sDeleteBtn}"/>'+
  110. '</div>'
  111. );
  112. // Preview tooltip
  113. if(data.result.preview){
  114. $('#display_attachment_'+data.result.att_id).tooltip({
  115. html: true,
  116. title: function(){ return '<img src="'+sDownloadLink+'" style="max-width: 100%;" />'; }
  117. });
  118. }
  119. // Showing remove button on hover
  120. $('#display_attachment_'+data.result.att_id).hover( function(){
  121. $(this).children(':button').toggleClass('hidden');
  122. });
  123. // Remove button handler
  124. $('#display_attachment_'+data.result.att_id+' :button').click(function(oEvent){
  125. oEvent.preventDefault();
  126. RemoveAttachment(data.result.att_id);
  127. });
  128. }
  129. },
  130. start: function() {
  131. // Scrolling to dropzone so the user can see that attachments are uploaded
  132. $(this)[0].scrollIntoView();
  133. // Showing loader
  134. $(this).closest('.upload_container').find('.loader').css('visibility', 'visible');
  135. },
  136. stop: function() {
  137. // Hiding the loader
  138. $(this).closest('.upload_container').find('.loader').css('visibility', 'hidden');
  139. // Adding this field to the touched fields of the field set so the cancel event is called if necessary
  140. $(this).closest(".field_set").trigger("field_change", {
  141. id: '{$this->oField->GetGlobalId()}',
  142. name: '{$this->oField->GetId()}'
  143. });
  144. }
  145. });
  146. // Preview tooltip
  147. $('.attachment [data-preview="true"]').each(function(iIndex, oElem){
  148. $(oElem).parent().tooltip({
  149. html: true,
  150. title: function(){ return '<img src="'+$(oElem).attr('href')+'" style="max-width: 100%;" />'; }
  151. });
  152. });
  153. // Remove button handler
  154. $('.attachments_container .attachment :button').click(function(oEvent){
  155. oEvent.preventDefault();
  156. RemoveAttachment($(this).closest('.attachment').find(':input[name="attachments[]"]').val());
  157. });
  158. // Remove button showing
  159. if($sIsDeleteAllowed)
  160. {
  161. $('.attachment').hover( function(){
  162. $(this).find(':button').toggleClass('hidden');
  163. });
  164. }
  165. // Handles a drag / drop overlay
  166. if($('#drag_overlay').length === 0)
  167. {
  168. $('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>') );
  169. }
  170. // Handles highlighting of the drop zone
  171. // Note : This is inspired by itop-attachments/main.attachments.php
  172. $(document).on('dragover', function(oEvent){
  173. var bFiles = false;
  174. if (oEvent.dataTransfer && oEvent.dataTransfer.types)
  175. {
  176. for (var i = 0; i < oEvent.dataTransfer.types.length; i++)
  177. {
  178. if (oEvent.dataTransfer.types[i] == "application/x-moz-nativeimage")
  179. {
  180. bFiles = false; // mozilla contains "Files" in the types list when dragging images inside the page, but it also contains "application/x-moz-nativeimage" before
  181. break;
  182. }
  183. if (oEvent.dataTransfer.types[i] == "Files")
  184. {
  185. bFiles = true;
  186. break;
  187. }
  188. }
  189. }
  190. if (!bFiles) return; // Not dragging files
  191. var oDropZone = $('#drag_overlay');
  192. var oTimeout = window.dropZoneTimeout;
  193. // This is to detect when there is no drag over because there is no "drag out" event
  194. if (!oTimeout) {
  195. oDropZone.removeClass('drag_out').addClass('drag_in');
  196. } else {
  197. clearTimeout(oTimeout);
  198. }
  199. window.dropZoneTimeout = setTimeout(function () {
  200. window.dropZoneTimeout = null;
  201. oDropZone.removeClass('drag_in').addClass('drag_out');
  202. }, 200);
  203. });
  204. EOF
  205. );
  206. return $oOutput;
  207. }
  208. /**
  209. *
  210. * @param RenderingOutput $oOutput
  211. */
  212. protected function PrepareExistingFiles(RenderingOutput &$oOutput)
  213. {
  214. $sObjectClass = get_class($this->oField->GetObject());
  215. $sDeleteBtn = Dict::S('Portal:Button:Delete');
  216. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  217. // Note : AllowAllData set to true here instead of checking scope's flag because we are displaying a value that has been set and validated
  218. $oSearch->AllowAllData();
  219. $oSet = new DBObjectSet($oSearch, array(), array('class' => $sObjectClass, 'item_id' => $this->oField->GetObject()->GetKey()));
  220. // If in read only and no attachments, we display a short message
  221. if ($this->oField->GetReadOnly() && ($oSet->Count() === 0))
  222. {
  223. $oOutput->AddHtml(Dict::S('Attachments:NoAttachment'));
  224. }
  225. else
  226. {
  227. while ($oAttachment = $oSet->Fetch())
  228. {
  229. $iAttId = $oAttachment->GetKey();
  230. $oDoc = $oAttachment->Get('contents');
  231. $sFileName = htmlentities($oDoc->GetFileName(), ENT_QUOTES, 'UTF-8');
  232. $sIcon = utils::GetAbsoluteUrlAppRoot() . 'env-' . utils::GetCurrentEnvironment() . '/itop-attachments/icons/image.png';
  233. $sPreview = $oDoc->IsPreviewAvailable() ? 'true' : 'false';
  234. $sDownloadLink = str_replace('-sAttachmentId-', $iAttId, $this->oField->GetDownloadEndpoint());
  235. $oOutput->Addhtml(
  236. <<<EOF
  237. <div class="attachment col-xs-6 col-sm-3 col-md-2" id="display_attachment_{$iAttId}">
  238. <a data-preview="{$sPreview}" href="{$sDownloadLink}" title="{$sFileName}">
  239. <div class="attachment_icon"><img src="{$sIcon}"></div>
  240. <div class="attachment_name">{$sFileName}</div>
  241. <input id="attachment_{$iAttId}" type="hidden" name="attachments[]" value="{$iAttId}"/>
  242. </a>
  243. <input id="btn_remove_{$iAttId}" type="button" class="btn btn-xs btn-danger hidden" value="{$sDeleteBtn}"/>
  244. </div>
  245. EOF
  246. );
  247. }
  248. }
  249. }
  250. }