model.attachments.php 18 KB

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