main.attachments.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. // Copyright (C) 2010 Combodo SARL
  3. //
  4. // This program is free software; you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation; version 3 of the License.
  7. //
  8. // This program is distributed in the hope that it will be useful,
  9. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. // GNU General Public License for more details.
  12. //
  13. // You should have received a copy of the GNU General Public License
  14. // along with this program; if not, write to the Free Software
  15. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  16. class AttachmentPlugIn implements iApplicationUIExtension, iApplicationObjectExtension
  17. {
  18. public function OnDisplayProperties($oObject, WebPage $oPage, $bEditMode = false)
  19. {
  20. if ($this->GetAttachmentsPosition() == 'properties')
  21. {
  22. $this->DisplayAttachments($oObject, $oPage, $bEditMode);
  23. }
  24. }
  25. public function OnDisplayRelations($oObject, WebPage $oPage, $bEditMode = false)
  26. {
  27. if ($this->GetAttachmentsPosition() == 'relations')
  28. {
  29. $this->DisplayAttachments($oObject, $oPage, $bEditMode);
  30. }
  31. }
  32. public function OnFormSubmit($oObject, $sFormPrefix = '')
  33. {
  34. if ($this->IsTargetObject($oObject))
  35. {
  36. // For new objects attachments are processed in OnDBInsert
  37. if (!$oObject->IsNew())
  38. {
  39. self::UpdateAttachments($oObject);
  40. }
  41. }
  42. }
  43. protected function GetMaxUpload()
  44. {
  45. $iMaxUpload = ini_get('upload_max_filesize');
  46. if (!$iMaxUpload)
  47. {
  48. $sRet = Dict::S('Attachments:UploadNotAllowedOnThisSystem');
  49. }
  50. else
  51. {
  52. $iMaxUpload = utils::ConvertToBytes($iMaxUpload);
  53. if ($iMaxUpload > 1024*1024*1024)
  54. {
  55. $sRet = Dict::Format('Attachment:Max_Go', sprintf('%0.2f', $iMaxUpload/(1024*1024*1024)));
  56. }
  57. else if ($iMaxUpload > 1024*1024)
  58. {
  59. $sRet = Dict::Format('Attachment:Max_Mo', sprintf('%0.2f', $iMaxUpload/(1024*1024)));
  60. }
  61. else
  62. {
  63. $sRet = Dict::Format('Attachment:Max_Ko', sprintf('%0.2f', $iMaxUpload/(1024)));
  64. }
  65. }
  66. return $sRet;
  67. }
  68. public function OnFormCancel($sTempId)
  69. {
  70. // Delete all "pending" attachments for this form
  71. $sOQL = 'SELECT Attachment WHERE temp_id = :temp_id';
  72. $oSearch = DBObjectSearch::FromOQL($sOQL);
  73. $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
  74. while($oAttachment = $oSet->Fetch())
  75. {
  76. $oAttachment->DBDelete();
  77. // Pending attachment, don't mention it in the history
  78. }
  79. }
  80. public function EnumUsedAttributes($oObject)
  81. {
  82. return array();
  83. }
  84. public function GetIcon($oObject)
  85. {
  86. return '';
  87. }
  88. public function GetHilightClass($oObject)
  89. {
  90. // Possible return values are:
  91. // HILIGHT_CLASS_CRITICAL, HILIGHT_CLASS_WARNING, HILIGHT_CLASS_OK, HILIGHT_CLASS_NONE
  92. return HILIGHT_CLASS_NONE;
  93. }
  94. public function EnumAllowedActions(DBObjectSet $oSet)
  95. {
  96. // No action
  97. return array();
  98. }
  99. public function OnIsModified($oObject)
  100. {
  101. if ($this->IsTargetObject($oObject))
  102. {
  103. $aAttachmentIds = utils::ReadParam('attachments', array());
  104. $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', array());
  105. if ( (count($aAttachmentIds) > 0) || (count($aRemovedAttachmentIds) > 0) )
  106. {
  107. return true;
  108. }
  109. }
  110. return false;
  111. }
  112. public function OnCheckToWrite($oObject)
  113. {
  114. return array();
  115. }
  116. public function OnCheckToDelete($oObject)
  117. {
  118. return array();
  119. }
  120. public function OnDBUpdate($oObject, $oChange = null)
  121. {
  122. if ($this->IsTargetObject($oObject))
  123. {
  124. // Get all current attachments
  125. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  126. $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
  127. while ($oAttachment = $oSet->Fetch())
  128. {
  129. $oAttachment->SetItem($oObject, true /*updateonchange*/);
  130. }
  131. }
  132. }
  133. public function OnDBInsert($oObject, $oChange = null)
  134. {
  135. if ($this->IsTargetObject($oObject))
  136. {
  137. self::UpdateAttachments($oObject, $oChange);
  138. }
  139. }
  140. public function OnDBDelete($oObject, $oChange = null)
  141. {
  142. if ($this->IsTargetObject($oObject))
  143. {
  144. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  145. $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
  146. while ($oAttachment = $oSet->Fetch())
  147. {
  148. $oAttachment->DBDelete();
  149. }
  150. }
  151. }
  152. ///////////////////////////////////////////////////////////////////////////////////////////////////////
  153. //
  154. // Plug-ins specific functions
  155. //
  156. ///////////////////////////////////////////////////////////////////////////////////////////////////////
  157. protected function IsTargetObject($oObject)
  158. {
  159. $aAllowedClasses = MetaModel::GetModuleSetting('itop-attachments', 'allowed_classes', array('Ticket'));
  160. foreach($aAllowedClasses as $sAllowedClass)
  161. {
  162. if ($oObject instanceof $sAllowedClass)
  163. {
  164. return true;
  165. }
  166. }
  167. return false;
  168. }
  169. protected function GetAttachmentsPosition()
  170. {
  171. return MetaModel::GetModuleSetting('itop-attachments', 'position', 'relations');
  172. }
  173. var $m_bDeleteEnabled = true;
  174. public function EnableDelete($bEnabled)
  175. {
  176. $this->m_bDeleteEnabled = $bEnabled;
  177. }
  178. public function DisplayAttachments($oObject, WebPage $oPage, $bEditMode = false)
  179. {
  180. // Exit here if the class is not allowed
  181. if (!$this->IsTargetObject($oObject)) return;
  182. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  183. $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
  184. if ($this->GetAttachmentsPosition() == 'relations')
  185. {
  186. $sTitle = ($oSet->Count() > 0)? Dict::Format('Attachments:TabTitle_Count', $oSet->Count()) : Dict::S('Attachments:EmptyTabTitle');
  187. $oPage->SetCurrentTab($sTitle);
  188. }
  189. $oPage->add_style(
  190. <<<EOF
  191. .attachment {
  192. display: inline-block;
  193. text-align:center;
  194. float:left;
  195. padding:5px;
  196. }
  197. .attachment:hover {
  198. background-color: #e0e0e0;
  199. }
  200. .attachment img {
  201. border: 0;
  202. }
  203. .attachment a {
  204. text-decoration: none;
  205. color: #1C94C4;
  206. }
  207. .btn_hidden {
  208. display: none;
  209. }
  210. EOF
  211. );
  212. $oPage->add('<fieldset>');
  213. $oPage->add('<legend>'.Dict::S('Attachments:FieldsetTitle').'</legend>');
  214. if ($bEditMode)
  215. {
  216. $sIsDeleteEnabled = $this->m_bDeleteEnabled ? 'true' : 'false';
  217. $iTransactionId = $oPage->GetTransactionId();
  218. $oPage->add_linked_script(utils::GetAbsoluteUrlAppRoot().'modules/itop-attachments/ajaxfileupload.js');
  219. $sClass = get_class($oObject);
  220. $sTempId = session_id().'_'.$iTransactionId;
  221. $sDeleteBtn = Dict::S('Attachments:DeleteBtn');
  222. $oPage->add_script(
  223. <<<EOF
  224. function RemoveNewAttachment(att_id)
  225. {
  226. $('#attachment_'+att_id).attr('name', 'removed_attachments[]');
  227. $('#display_attachment_'+att_id).hide();
  228. $('#attachment_plugin').trigger('remove_attachment', [att_id]);
  229. return false; // Do not submit the form !
  230. }
  231. function ajaxFileUpload()
  232. {
  233. //starting setting some animation when the ajax starts and completes
  234. $("#attachment_loading").ajaxStart(function(){
  235. $(this).show();
  236. }).ajaxComplete(function(){
  237. $(this).hide();
  238. });
  239. /*
  240. prepareing ajax file upload
  241. url: the url of script file handling the uploaded files
  242. fileElementId: the file type of input element id and it will be the index of $_FILES Array()
  243. dataType: it support json, xml
  244. secureuri:use secure protocol
  245. success: call back function when the ajax complete
  246. error: callback function when the ajax failed
  247. */
  248. $.ajaxFileUpload
  249. (
  250. {
  251. url: GetAbsoluteUrlAppRoot()+'modules/itop-attachments/ajax.attachment.php?obj_class={$sClass}&temp_id={$sTempId}&operation=add',
  252. secureuri:false,
  253. fileElementId:'file',
  254. dataType: 'json',
  255. success: function (data, status)
  256. {
  257. if(typeof(data.error) != 'undefined')
  258. {
  259. if(data.error != '')
  260. {
  261. alert(data.error);
  262. }
  263. else
  264. {
  265. var sDownloadLink = GetAbsoluteUrlAppRoot()+'pages/ajax.render.php/?operation=download_document&class=Attachment&id='+data.att_id+'&field=contents';
  266. $('#attachments').append('<div class="attachment" id="display_attachment_'+data.att_id+'"><a href="'+sDownloadLink+'"><img src="'+data.icon+'"><br/>'+data.msg+'<input id="attachment_'+data.att_id+'" type="hidden" name="attachments[]" value="'+data.att_id+'"/></a><br/><input type="button" class="btn_hidden" value="{$sDeleteBtn}" onClick="RemoveNewAttachment('+data.att_id+');"/></div>');
  267. if($sIsDeleteEnabled)
  268. {
  269. $('#display_attachment_'+data.att_id).hover( function() { $(this).children(':button').toggleClass('btn_hidden'); } );
  270. }
  271. $('#attachment_plugin').trigger('add_attachment', [data.att_id, data.msg]);
  272. //alert(data.msg);
  273. }
  274. }
  275. },
  276. error: function (data, status, e)
  277. {
  278. alert(e);
  279. }
  280. }
  281. )
  282. return false;
  283. }
  284. EOF
  285. );
  286. $oPage->add('<span id="attachments">');
  287. while ($oAttachment = $oSet->Fetch())
  288. {
  289. $iAttId = $oAttachment->GetKey();
  290. $oDoc = $oAttachment->Get('contents');
  291. $sFileName = $oDoc->GetFileName();
  292. $sIcon = utils::GetAbsoluteUrlAppRoot().AttachmentPlugIn::GetFileIcon($sFileName);
  293. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php/?operation=download_document&class=Attachment&id='.$iAttId.'&field=contents';
  294. $oPage->add('<div class="attachment" id="attachment_'.$iAttId.'"><a href="'.$sDownloadLink.'"><img src="'.$sIcon.'"><br/>'.$sFileName.'<input type="hidden" name="attachments[]" value="'.$iAttId.'"/></a><br/>&nbsp;<input id="btn_remove_'.$iAttId.'" type="button" class="btn_hidden" value="Delete" onClick="$(\'#attachment_'.$iAttId.'\').remove();"/>&nbsp;</div>');
  295. }
  296. $oPage->add('</span>');
  297. $oPage->add('<div style="clear:both"></div>');
  298. $sMaxUpload = $this->GetMaxUpload();
  299. $oPage->p(Dict::S('Attachments:AddAttachment').'<input type="file" name="file" id="file" onChange="ajaxFileUpload();"><span style="display:none;" id="attachment_loading">&nbsp;<img src="../images/indicator.gif"></span> '.$sMaxUpload);
  300. //$oPage->p('<input type="button" onClick="ajaxFileUpload();" value=" Upload !">');
  301. $oPage->p('<span style="display:none;" id="attachment_loading">Loading, please wait...</span>');
  302. $oPage->p('<input type="hidden" id="attachment_plugin"/>');
  303. $oPage->add('</fieldset>');
  304. if ($this->m_bDeleteEnabled)
  305. {
  306. $oPage->add_ready_script('$(".attachment").hover( function() {$(this).children(":button").toggleClass("btn_hidden"); } );');
  307. }
  308. }
  309. else
  310. {
  311. $oPage->add('<span id="attachments">');
  312. if ($oSet->Count() == 0)
  313. {
  314. $oPage->add(Dict::S('Attachments:NoAttachment'));
  315. }
  316. else
  317. {
  318. while ($oAttachment = $oSet->Fetch())
  319. {
  320. $iAttId = $oAttachment->GetKey();
  321. $oDoc = $oAttachment->Get('contents');
  322. $sFileName = $oDoc->GetFileName();
  323. $sIcon = utils::GetAbsoluteUrlAppRoot().AttachmentPlugIn::GetFileIcon($sFileName);
  324. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php/?operation=download_document&class=Attachment&id='.$iAttId.'&field=contents';
  325. $oPage->add('<div class="attachment" id="attachment_'.$iAttId.'"><a href="'.$sDownloadLink.'"><img src="'.$sIcon.'"><br/>'.$sFileName.'</a><input type="hidden" name="attachments[]" value="'.$iAttId.'"/><br/>&nbsp;&nbsp;</div>');
  326. }
  327. }
  328. }
  329. }
  330. protected static function UpdateAttachments($oObject, $oChange = null)
  331. {
  332. $iTransactionId = utils::ReadParam('transaction_id', null);
  333. if (!is_null($iTransactionId))
  334. {
  335. $aActions = array();
  336. $aAttachmentIds = utils::ReadParam('attachments', array());
  337. // Get all current attachments
  338. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  339. $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
  340. while ($oAttachment = $oSet->Fetch())
  341. {
  342. // Remove attachments that are no longer attached to the current object
  343. if (!in_array($oAttachment->GetKey(), $aAttachmentIds))
  344. {
  345. $oAttachment->DBDelete();
  346. $aActions[] = self::GetActionDescription($oAttachment, false /* false => deletion */);
  347. }
  348. }
  349. // Attach new (temporary) attachements
  350. $sTempId = session_id().'_'.$iTransactionId;
  351. // The object is being created from a form, check if there are pending attachments
  352. // for this object, but deleting the "new" ones that were already removed from the form
  353. $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', array());
  354. $sOQL = 'SELECT Attachment WHERE temp_id = :temp_id';
  355. $oSearch = DBObjectSearch::FromOQL($sOQL);
  356. foreach($aAttachmentIds as $iAttachmentId)
  357. {
  358. $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
  359. while($oAttachment = $oSet->Fetch())
  360. {
  361. if (in_array($oAttachment->GetKey(),$aRemovedAttachmentIds))
  362. {
  363. $oAttachment->DBDelete();
  364. // temporary attachment removed, don't even mention it in the history
  365. }
  366. else
  367. {
  368. $oAttachment->SetItem($oObject);
  369. $oAttachment->Set('temp_id', '');
  370. $oAttachment->DBUpdate();
  371. // temporary attachment confirmed, list it in the history
  372. $aActions[] = self::GetActionDescription($oAttachment, true /* true => creation */);
  373. }
  374. }
  375. }
  376. if (count($aActions) > 0)
  377. {
  378. if ($oChange == null)
  379. {
  380. // Let's create a change if non is supplied
  381. $oChange = MetaModel::NewObject("CMDBChange");
  382. $oChange->Set("date", time());
  383. $sUserString = CMDBChange::GetCurrentUserName();
  384. $oChange->Set("userinfo", $sUserString);
  385. $iChangeId = $oChange->DBInsert();
  386. }
  387. foreach($aActions as $sActionDescription)
  388. {
  389. self::RecordHistory($oChange, $oObject, $sActionDescription);
  390. }
  391. }
  392. }
  393. }
  394. /////////////////////////////////////////////////////////////////////////////////////////
  395. public static function GetFileIcon($sFileName)
  396. {
  397. $aPathParts = pathinfo($sFileName);
  398. switch($aPathParts['extension'])
  399. {
  400. case 'doc':
  401. case 'docx':
  402. $sIcon = 'doc.png';
  403. break;
  404. case 'xls':
  405. case 'xlsx':
  406. $sIcon = 'xls.png';
  407. break;
  408. case 'ppt':
  409. case 'pptx':
  410. $sIcon = 'ppt.png';
  411. break;
  412. case 'pdf':
  413. $sIcon = 'pdf.png';
  414. break;
  415. case 'txt':
  416. case 'text':
  417. $sIcon = 'txt.png';
  418. break;
  419. case 'rtf':
  420. $sIcon = 'rtf.png';
  421. break;
  422. case 'odt':
  423. $sIcon = 'odt.png';
  424. break;
  425. case 'ods':
  426. $sIcon = 'ods.png';
  427. break;
  428. case 'odp':
  429. $sIcon = 'odp.png';
  430. break;
  431. case 'html':
  432. case 'htm':
  433. $sIcon = 'html.png';
  434. break;
  435. case 'png':
  436. case 'gif':
  437. case 'jpg':
  438. case 'jpeg':
  439. case 'tiff':
  440. case 'tif':
  441. case 'bmp':
  442. $sIcon = 'image.png';
  443. break;
  444. case 'zip':
  445. case 'gz':
  446. case 'tgz':
  447. case 'rar':
  448. $sIcon = 'zip.png';
  449. break;
  450. default:
  451. $sIcon = 'document.png';
  452. break;
  453. }
  454. return "modules/itop-attachments/icons/$sIcon";
  455. }
  456. /////////////////////////////////////////////////////////////////////////
  457. private static function RecordHistory(CMDBChange $oChange, $oTargetObject, $sDescription)
  458. {
  459. $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpPlugin");
  460. $oMyChangeOp->Set("change", $oChange->GetKey());
  461. $oMyChangeOp->Set("objclass", get_class($oTargetObject));
  462. $oMyChangeOp->Set("objkey", $oTargetObject->GetKey());
  463. $oMyChangeOp->Set("description", $sDescription);
  464. $iId = $oMyChangeOp->DBInsertNoReload();
  465. }
  466. /////////////////////////////////////////////////////////////////////////
  467. private static function GetActionDescription($oAttachment, $bCreate = true)
  468. {
  469. $oBlob = $oAttachment->Get('contents');
  470. $sFileName = $oBlob->GetFileName();
  471. if ($bCreate)
  472. {
  473. $sDescription = Dict::Format('Attachments:History_File_Added', $sFileName);
  474. }
  475. else
  476. {
  477. $sDescription = Dict::Format('Attachments:History_File_Removed', $sFileName);
  478. }
  479. return $sDescription;
  480. }
  481. }
  482. ?>