bsfileuploadfieldrenderer.class.inc.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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(/-sAttachmentId-/, 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. // Preview tooltip
  103. if(data.result.preview){
  104. $('#display_attachment_'+data.result.att_id).tooltip({
  105. html: true,
  106. title: function(){ return '<img src="'+sDownloadLink+'" style="max-width: 100%;" />'; }
  107. });
  108. }
  109. // Showing remove button on hover
  110. $('#display_attachment_'+data.result.att_id).hover( function(){
  111. $(this).children(':button').toggleClass('hidden');
  112. });
  113. // Remove button handler
  114. $('#display_attachment_'+data.result.att_id+' :button').click(function(oEvent){
  115. oEvent.preventDefault();
  116. RemoveAttachment(data.result.att_id);
  117. });
  118. }
  119. },
  120. start: function() {
  121. // Scrolling to dropzone so the user can see that attachments are uploaded
  122. $(this)[0].scrollIntoView();
  123. // Showing loader
  124. $(this).closest('.upload_container').find('.loader').css('visibility', 'visible');
  125. },
  126. stop: function() {
  127. // Hiding the loader
  128. $(this).closest('.upload_container').find('.loader').css('visibility', 'hidden');
  129. // Adding this field to the touched fields of the field set so the cancel event is called if necessary
  130. $(this).closest(".field_set").trigger("field_change", {
  131. id: '{$this->oField->GetGlobalId()}',
  132. name: '{$this->oField->GetId()}'
  133. });
  134. }
  135. });
  136. // Preview tooltip
  137. $('.attachment [data-preview="true"]').each(function(iIndex, oElem){
  138. $(oElem).parent().tooltip({
  139. html: true,
  140. title: function(){ return '<img src="'+$(oElem).attr('href')+'" style="max-width: 100%;" />'; }
  141. });
  142. });
  143. // Remove button handler
  144. $('.attachments_container .attachment :button').click(function(oEvent){
  145. oEvent.preventDefault();
  146. RemoveAttachment($(this).closest('.attachment').find(':input[name="attachments[]"]').val());
  147. });
  148. // Remove button showing
  149. if($sIsDeleteAllowed)
  150. {
  151. $('.attachment').hover( function(){
  152. $(this).find(':button').toggleClass('hidden');
  153. });
  154. }
  155. // Handles a drag / drop overlay
  156. if($('#drag_overlay').length === 0)
  157. {
  158. $('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>') );
  159. }
  160. // Handles highlighting of the drop zone
  161. // Note : This is inspired by itop-attachments/main.attachments.php
  162. $(document).on('dragover', function(oEvent){
  163. var bFiles = false;
  164. if (oEvent.dataTransfer && oEvent.dataTransfer.types)
  165. {
  166. for (var i = 0; i < oEvent.dataTransfer.types.length; i++)
  167. {
  168. if (oEvent.dataTransfer.types[i] == "application/x-moz-nativeimage")
  169. {
  170. bFiles = false; // mozilla contains "Files" in the types list when dragging images inside the page, but it also contains "application/x-moz-nativeimage" before
  171. break;
  172. }
  173. if (oEvent.dataTransfer.types[i] == "Files")
  174. {
  175. bFiles = true;
  176. break;
  177. }
  178. }
  179. }
  180. if (!bFiles) return; // Not dragging files
  181. var oDropZone = $('#drag_overlay');
  182. var oTimeout = window.dropZoneTimeout;
  183. // This is to detect when there is no drag over because there is no "drag out" event
  184. if (!oTimeout) {
  185. oDropZone.removeClass('drag_out').addClass('drag_in');
  186. } else {
  187. clearTimeout(oTimeout);
  188. }
  189. window.dropZoneTimeout = setTimeout(function () {
  190. window.dropZoneTimeout = null;
  191. oDropZone.removeClass('drag_in').addClass('drag_out');
  192. }, 200);
  193. });
  194. EOF
  195. );
  196. return $oOutput;
  197. }
  198. /**
  199. *
  200. * @param RenderingOutput $oOutput
  201. */
  202. protected function PrepareExistingFiles(RenderingOutput &$oOutput)
  203. {
  204. $sObjectClass = get_class($this->oField->GetObject());
  205. $sDeleteBtn = Dict::S('Portal:Button:Delete');
  206. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  207. $oSet = new DBObjectSet($oSearch, array(), array('class' => $sObjectClass, 'item_id' => $this->oField->GetObject()->GetKey()));
  208. while ($oAttachment = $oSet->Fetch())
  209. {
  210. $iAttId = $oAttachment->GetKey();
  211. $oDoc = $oAttachment->Get('contents');
  212. $sFileName = htmlentities($oDoc->GetFileName(), ENT_QUOTES, 'UTF-8');
  213. $sIcon = utils::GetAbsoluteUrlAppRoot() . 'env-' . utils::GetCurrentEnvironment() . '/itop-attachments/icons/image.png';
  214. $sPreview = $oDoc->IsPreviewAvailable() ? 'true' : 'false';
  215. $sDownloadLink = str_replace('-sAttachmentId-', $iAttId, $this->oField->GetDownloadEndpoint());
  216. $oOutput->Addhtml(
  217. <<<EOF
  218. <div class="attachment col-xs-6 col-sm-3 col-md-2" id="display_attachment_{$iAttId}">
  219. <a data-preview="{$sPreview}" href="{$sDownloadLink}" title="{$sFileName}">
  220. <div class="attachment_icon"><img src="{$sIcon}"></div>
  221. <div class="attachment_name">{$sFileName}</div>
  222. <input id="attachment_{$iAttId}" type="hidden" name="attachments[]" value="{$iAttId}"/>
  223. </a>
  224. <input id="btn_remove_{$iAttId}" type="button" class="btn btn-xs btn-danger hidden" value="{$sDeleteBtn}"/>
  225. </div>
  226. EOF
  227. );
  228. }
  229. }
  230. }