bsfileuploadfieldrenderer.class.inc.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. // TODO : Add max upload size when itop attachment has been refactored
  65. $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>');
  66. // Ending files container
  67. $oOutput->AddHtml('</div>');
  68. // Ending field container
  69. $oOutput->AddHtml('</div>');
  70. // JS for file upload
  71. // Note : This is based on itop-attachement/main.attachments.php
  72. $oOutput->AddJs(
  73. <<<EOF
  74. var RemoveAttachment = function(sAttId)
  75. {
  76. $('#attachment_' + sAttId).attr('name', 'removed_attachments[]');
  77. $('#display_attachment_' + sAttId).hide();
  78. };
  79. $('#{$this->oField->GetGlobalId()}').fileupload({
  80. url: '{$this->oField->GetUploadEndpoint()}',
  81. formData: { operation: 'add', temp_id: '{$sTempId}', object_class: '{$sObjectClass}', 'field_name': '{$this->oField->GetId()}' },
  82. dataType: 'json',
  83. pasteZone: null, // Don't accept files via Chrome's copy/paste
  84. done: function (e, data) {
  85. if(data.result.error !== undefined)
  86. {
  87. console.log(data.result.error);
  88. }
  89. else
  90. {
  91. var sDownloadLink = '{$this->oField->GetDownloadEndpoint()}'.replace(/-sAttId-/, data.result.att_id);
  92. $(this).closest('.fileupload_field_content').find('.attachments_container').append(
  93. '<div class="attachment col-xs-6 col-sm-3 col-md-2" id="display_attachment_'+data.result.att_id+'">'+
  94. ' <a data-preview="'+data.result.preview+'" href="'+sDownloadLink+'" title="'+data.result.msg+'">'+
  95. ' <div class="attachment_icon"><img src="'+data.result.icon+'"></div>'+
  96. ' <div class="attachment_name">'+data.result.msg+'</div>'+
  97. ' <input id="attachment_'+data.result.att_id+'" type="hidden" name="attachments[]" value="'+data.result.att_id+'"/>'+
  98. ' </a>'+
  99. ' <input type="button" class="btn btn-xs btn-danger hidden" value="{$sDeleteBtn}"/>'+
  100. '</div>'
  101. );
  102. $('#display_attachment_'+data.result.att_id+' :button').click(function(oEvent){
  103. oEvent.preventDefault();
  104. RemoveAttachment(data.result.att_id);
  105. });
  106. $('#display_attachment_'+data.result.att_id).hover( function(){
  107. $(this).children(':button').toggleClass('hidden');
  108. });
  109. }
  110. },
  111. start: function() {
  112. // Scrolling to dropzone so the user can see that attachments are uploaded
  113. $(this)[0].scrollIntoView();
  114. // Showing loader
  115. $(this).closest('.upload_container').find('.loader').css('visibility', 'visible');
  116. },
  117. stop: function() {
  118. // Hiding the loader
  119. $(this).closest('.upload_container').find('.loader').css('visibility', 'hidden');
  120. // Adding this field to the touched fields of the field set so the cancel event is called if necessary
  121. $(this).closest(".field_set").trigger("field_change", {
  122. id: '{$this->oField->GetGlobalId()}',
  123. name: '{$this->oField->GetId()}'
  124. });
  125. }
  126. });
  127. $('.attachments_container .attachment :button').click(function(oEvent){
  128. oEvent.preventDefault();
  129. RemoveAttachment($(this).closest('.attachment').find(':input[name="attachments[]"]').val());
  130. });
  131. if($sIsDeleteAllowed)
  132. {
  133. $('.attachment').hover( function(){
  134. $(this).find(':button').toggleClass('hidden');
  135. });
  136. }
  137. // Handles a drag / drop overlay
  138. if($('#drag_overlay').length === 0)
  139. {
  140. $('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>') );
  141. }
  142. // Handles highlighting of the drop zone
  143. // Note : This is inspired by itop-attachments/main.attachments.php
  144. $(document).on('dragover', function(oEvent){
  145. var bFiles = false;
  146. if (oEvent.dataTransfer && oEvent.dataTransfer.types)
  147. {
  148. for (var i = 0; i < oEvent.dataTransfer.types.length; i++)
  149. {
  150. if (oEvent.dataTransfer.types[i] == "application/x-moz-nativeimage")
  151. {
  152. bFiles = false; // mozilla contains "Files" in the types list when dragging images inside the page, but it also contains "application/x-moz-nativeimage" before
  153. break;
  154. }
  155. if (oEvent.dataTransfer.types[i] == "Files")
  156. {
  157. bFiles = true;
  158. break;
  159. }
  160. }
  161. }
  162. if (!bFiles) return; // Not dragging files
  163. var oDropZone = $('#drag_overlay');
  164. var oTimeout = window.dropZoneTimeout;
  165. // This is to detect when there is no drag over because there is no "drag out" event
  166. if (!oTimeout) {
  167. oDropZone.removeClass('drag_out').addClass('drag_in');
  168. } else {
  169. clearTimeout(oTimeout);
  170. }
  171. window.dropZoneTimeout = setTimeout(function () {
  172. window.dropZoneTimeout = null;
  173. oDropZone.removeClass('drag_in').addClass('drag_out');
  174. }, 200);
  175. });
  176. EOF
  177. );
  178. return $oOutput;
  179. }
  180. /**
  181. *
  182. * @param RenderingOutput $oOutput
  183. */
  184. protected function PrepareExistingFiles(RenderingOutput &$oOutput)
  185. {
  186. $sObjectClass = get_class($this->oField->GetObject());
  187. $sDeleteBtn = Dict::S('Portal:Button:Delete');
  188. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  189. $oSet = new DBObjectSet($oSearch, array(), array('class' => $sObjectClass, 'item_id' => $this->oField->GetObject()->GetKey()));
  190. while ($oAttachment = $oSet->Fetch())
  191. {
  192. $iAttId = $oAttachment->GetKey();
  193. $oDoc = $oAttachment->Get('contents');
  194. $sFileName = htmlentities($oDoc->GetFileName(), ENT_QUOTES, 'UTF-8');
  195. $sIcon = utils::GetAbsoluteUrlAppRoot() . 'env-' . utils::GetCurrentEnvironment() . '/itop-attachments/icons/image.png';
  196. $sPreview = $oDoc->IsPreviewAvailable() ? 'true' : 'false';
  197. $sDownloadLink = str_replace('-sAttachmentId-', $iAttId, $this->oField->GetDownloadEndpoint());
  198. $oOutput->Addhtml(
  199. <<<EOF
  200. <div class="attachment col-xs-6 col-sm-3 col-md-2" id="display_attachment_{$iAttId}">
  201. <a data-preview="{$sPreview}" href="{$sDownloadLink}" title="{$sFileName}">
  202. <div class="attachment_icon"><img src="{$sIcon}"></div>
  203. <div class="attachment_name">{$sFileName}</div>
  204. <input id="attachment_{$iAttId}" type="hidden" name="attachments[]" value="{$iAttId}"/>
  205. </a>
  206. <input id="btn_remove_{$iAttId}" type="button" class="btn btn-xs btn-danger hidden" value="{$sDeleteBtn}"/>
  207. </div>
  208. EOF
  209. );
  210. }
  211. }
  212. }