main.attachments.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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. $sClass = get_class($oObject);
  219. $sTempId = session_id().'_'.$iTransactionId;
  220. $sDeleteBtn = Dict::S('Attachments:DeleteBtn');
  221. $oPage->add_script(
  222. <<<EOF
  223. function RemoveNewAttachment(att_id)
  224. {
  225. $('#attachment_'+att_id).attr('name', 'removed_attachments[]');
  226. $('#display_attachment_'+att_id).hide();
  227. $('#attachment_plugin').trigger('remove_attachment', [att_id]);
  228. return false; // Do not submit the form !
  229. }
  230. function ajaxFileUpload()
  231. {
  232. //starting setting some animation when the ajax starts and completes
  233. $("#attachment_loading").ajaxStart(function(){
  234. $(this).show();
  235. }).ajaxComplete(function(){
  236. $(this).hide();
  237. });
  238. /*
  239. prepareing ajax file upload
  240. url: the url of script file handling the uploaded files
  241. fileElementId: the file type of input element id and it will be the index of \$_FILES Array()
  242. dataType: it support json, xml
  243. secureuri:use secure protocol
  244. success: call back function when the ajax complete
  245. error: callback function when the ajax failed
  246. */
  247. $.ajaxFileUpload
  248. (
  249. {
  250. url: GetAbsoluteUrlModulesRoot()+'itop-attachments/ajax.attachment.php?obj_class={$sClass}&temp_id={$sTempId}&operation=add',
  251. secureuri:false,
  252. fileElementId:'file',
  253. dataType: 'json',
  254. success: function (data, status)
  255. {
  256. if(typeof(data.error) != 'undefined')
  257. {
  258. if(data.error != '')
  259. {
  260. alert(data.error);
  261. }
  262. else
  263. {
  264. var sDownloadLink = GetAbsoluteUrlAppRoot()+'pages/ajax.render.php/?operation=download_document&class=Attachment&id='+data.att_id+'&field=contents';
  265. $('#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>');
  266. if($sIsDeleteEnabled)
  267. {
  268. $('#display_attachment_'+data.att_id).hover( function() { $(this).children(':button').toggleClass('btn_hidden'); } );
  269. }
  270. $('#attachment_plugin').trigger('add_attachment', [data.att_id, data.msg]);
  271. //alert(data.msg);
  272. }
  273. }
  274. },
  275. error: function (data, status, e)
  276. {
  277. alert(e);
  278. }
  279. }
  280. )
  281. return false;
  282. }
  283. EOF
  284. );
  285. $oPage->add('<span id="attachments">');
  286. while ($oAttachment = $oSet->Fetch())
  287. {
  288. $iAttId = $oAttachment->GetKey();
  289. $oDoc = $oAttachment->Get('contents');
  290. $sFileName = $oDoc->GetFileName();
  291. $sIcon = utils::GetAbsoluteUrlAppRoot().AttachmentPlugIn::GetFileIcon($sFileName);
  292. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php/?operation=download_document&class=Attachment&id='.$iAttId.'&field=contents';
  293. $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>');
  294. }
  295. // Suggested attachments are listed here but treated as temporary
  296. $aDefault = utils::ReadParam('default', array(), false, 'raw_data');
  297. if (array_key_exists('suggested_attachments', $aDefault))
  298. {
  299. $sSuggestedAttachements = $aDefault['suggested_attachments'];
  300. if (is_array($sSuggestedAttachements))
  301. {
  302. $sSuggestedAttachements = implode(',', $sSuggestedAttachements);
  303. }
  304. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE id IN($sSuggestedAttachements)");
  305. $oSet = new DBObjectSet($oSearch, array());
  306. if ($oSet->Count() > 0)
  307. {
  308. while ($oAttachment = $oSet->Fetch())
  309. {
  310. // Mark the attachments as temporary attachments for the current object/form
  311. $oAttachment->Set('temp_id', $sTempId);
  312. $oAttachment->DBUpdate();
  313. // Display them
  314. $iAttId = $oAttachment->GetKey();
  315. $oDoc = $oAttachment->Get('contents');
  316. $sFileName = $oDoc->GetFileName();
  317. $sIcon = utils::GetAbsoluteUrlAppRoot().AttachmentPlugIn::GetFileIcon($sFileName);
  318. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php/?operation=download_document&class=Attachment&id='.$iAttId.'&field=contents';
  319. $oPage->add('<div class="attachment" id="display_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="RemoveNewAttachment('.$iAttId.');"/>&nbsp;</div>');
  320. $oPage->add_ready_script("$('#attachment_plugin').trigger('add_attachment', [$iAttId, '".addslashes($sFileName)."']);");
  321. }
  322. }
  323. }
  324. $oPage->add('</span>');
  325. $oPage->add('<div style="clear:both"></div>');
  326. $sMaxUpload = $this->GetMaxUpload();
  327. $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);
  328. $oPage->p('<span style="display:none;" id="attachment_loading">Loading, please wait...</span>');
  329. $oPage->p('<input type="hidden" id="attachment_plugin" name="attachment_plugin"/>');
  330. $oPage->add('</fieldset>');
  331. if ($this->m_bDeleteEnabled)
  332. {
  333. $oPage->add_ready_script('$(".attachment").hover( function() {$(this).children(":button").toggleClass("btn_hidden"); } );');
  334. }
  335. }
  336. else
  337. {
  338. $oPage->add('<span id="attachments">');
  339. if ($oSet->Count() == 0)
  340. {
  341. $oPage->add(Dict::S('Attachments:NoAttachment'));
  342. }
  343. else
  344. {
  345. while ($oAttachment = $oSet->Fetch())
  346. {
  347. $iAttId = $oAttachment->GetKey();
  348. $oDoc = $oAttachment->Get('contents');
  349. $sFileName = $oDoc->GetFileName();
  350. $sIcon = utils::GetAbsoluteUrlAppRoot().AttachmentPlugIn::GetFileIcon($sFileName);
  351. $sDownloadLink = utils::GetAbsoluteUrlAppRoot().'pages/ajax.render.php/?operation=download_document&class=Attachment&id='.$iAttId.'&field=contents';
  352. $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>');
  353. }
  354. }
  355. }
  356. }
  357. protected static function UpdateAttachments($oObject, $oChange = null)
  358. {
  359. if (utils::ReadParam('attachment_plugin', 'not-in-form') == 'not-in-form')
  360. {
  361. // Workaround to an issue in iTop < 2.0
  362. // Leave silently if there is no trace of the attachment form
  363. return;
  364. }
  365. $iTransactionId = utils::ReadParam('transaction_id', null);
  366. if (!is_null($iTransactionId))
  367. {
  368. $aActions = array();
  369. $aAttachmentIds = utils::ReadParam('attachments', array());
  370. // Get all current attachments
  371. $oSearch = DBObjectSearch::FromOQL("SELECT Attachment WHERE item_class = :class AND item_id = :item_id");
  372. $oSet = new DBObjectSet($oSearch, array(), array('class' => get_class($oObject), 'item_id' => $oObject->GetKey()));
  373. while ($oAttachment = $oSet->Fetch())
  374. {
  375. // Remove attachments that are no longer attached to the current object
  376. if (!in_array($oAttachment->GetKey(), $aAttachmentIds))
  377. {
  378. $oAttachment->DBDelete();
  379. $aActions[] = self::GetActionDescription($oAttachment, false /* false => deletion */);
  380. }
  381. }
  382. // Attach new (temporary) attachements
  383. $sTempId = session_id().'_'.$iTransactionId;
  384. // The object is being created from a form, check if there are pending attachments
  385. // for this object, but deleting the "new" ones that were already removed from the form
  386. $aRemovedAttachmentIds = utils::ReadParam('removed_attachments', array());
  387. $sOQL = 'SELECT Attachment WHERE temp_id = :temp_id';
  388. $oSearch = DBObjectSearch::FromOQL($sOQL);
  389. foreach($aAttachmentIds as $iAttachmentId)
  390. {
  391. $oSet = new DBObjectSet($oSearch, array(), array('temp_id' => $sTempId));
  392. while($oAttachment = $oSet->Fetch())
  393. {
  394. if (in_array($oAttachment->GetKey(),$aRemovedAttachmentIds))
  395. {
  396. $oAttachment->DBDelete();
  397. // temporary attachment removed, don't even mention it in the history
  398. }
  399. else
  400. {
  401. $oAttachment->SetItem($oObject);
  402. $oAttachment->Set('temp_id', '');
  403. $oAttachment->DBUpdate();
  404. // temporary attachment confirmed, list it in the history
  405. $aActions[] = self::GetActionDescription($oAttachment, true /* true => creation */);
  406. }
  407. }
  408. }
  409. if (count($aActions) > 0)
  410. {
  411. if ($oChange == null)
  412. {
  413. // Let's create a change if non is supplied
  414. $oChange = MetaModel::NewObject("CMDBChange");
  415. $oChange->Set("date", time());
  416. $sUserString = CMDBChange::GetCurrentUserName();
  417. $oChange->Set("userinfo", $sUserString);
  418. $iChangeId = $oChange->DBInsert();
  419. }
  420. foreach($aActions as $sActionDescription)
  421. {
  422. self::RecordHistory($oChange, $oObject, $sActionDescription);
  423. }
  424. }
  425. }
  426. }
  427. /////////////////////////////////////////////////////////////////////////////////////////
  428. public static function GetFileIcon($sFileName)
  429. {
  430. $aPathParts = pathinfo($sFileName);
  431. switch($aPathParts['extension'])
  432. {
  433. case 'doc':
  434. case 'docx':
  435. $sIcon = 'doc.png';
  436. break;
  437. case 'xls':
  438. case 'xlsx':
  439. $sIcon = 'xls.png';
  440. break;
  441. case 'ppt':
  442. case 'pptx':
  443. $sIcon = 'ppt.png';
  444. break;
  445. case 'pdf':
  446. $sIcon = 'pdf.png';
  447. break;
  448. case 'txt':
  449. case 'text':
  450. $sIcon = 'txt.png';
  451. break;
  452. case 'rtf':
  453. $sIcon = 'rtf.png';
  454. break;
  455. case 'odt':
  456. $sIcon = 'odt.png';
  457. break;
  458. case 'ods':
  459. $sIcon = 'ods.png';
  460. break;
  461. case 'odp':
  462. $sIcon = 'odp.png';
  463. break;
  464. case 'html':
  465. case 'htm':
  466. $sIcon = 'html.png';
  467. break;
  468. case 'png':
  469. case 'gif':
  470. case 'jpg':
  471. case 'jpeg':
  472. case 'tiff':
  473. case 'tif':
  474. case 'bmp':
  475. $sIcon = 'image.png';
  476. break;
  477. case 'zip':
  478. case 'gz':
  479. case 'tgz':
  480. case 'rar':
  481. $sIcon = 'zip.png';
  482. break;
  483. default:
  484. $sIcon = 'document.png';
  485. break;
  486. }
  487. return 'env-'.utils::GetCurrentEnvironment()."/itop-attachments/icons/$sIcon";
  488. }
  489. /////////////////////////////////////////////////////////////////////////
  490. private static function RecordHistory(CMDBChange $oChange, $oTargetObject, $sDescription)
  491. {
  492. $oMyChangeOp = MetaModel::NewObject("CMDBChangeOpPlugin");
  493. $oMyChangeOp->Set("change", $oChange->GetKey());
  494. $oMyChangeOp->Set("objclass", get_class($oTargetObject));
  495. $oMyChangeOp->Set("objkey", $oTargetObject->GetKey());
  496. $oMyChangeOp->Set("description", $sDescription);
  497. $iId = $oMyChangeOp->DBInsertNoReload();
  498. }
  499. /////////////////////////////////////////////////////////////////////////
  500. private static function GetActionDescription($oAttachment, $bCreate = true)
  501. {
  502. $oBlob = $oAttachment->Get('contents');
  503. $sFileName = $oBlob->GetFileName();
  504. if ($bCreate)
  505. {
  506. $sDescription = Dict::Format('Attachments:History_File_Added', $sFileName);
  507. }
  508. else
  509. {
  510. $sDescription = Dict::Format('Attachments:History_File_Removed', $sFileName);
  511. }
  512. return $sDescription;
  513. }
  514. }
  515. ?>