model.attachments.php 17 KB

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