action.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673
  1. <?php
  2. /** ISSUEREPORT **/
  3. //Récuperation d'une liste de issuereport
  4. Action::register('issue_issuereport_search',function(&$response){
  5. global $myUser,$_;
  6. User::check_access('issue','read');
  7. require_once(__DIR__.SLASH.'IssueReport.class.php');
  8. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  9. require_once(__DIR__.SLASH.'IssueReportTag.class.php');
  10. $allTags = IssueReportTag::tags();
  11. $query = 'SELECT DISTINCT {{table}}.id, {{table}}.*,(SELECT ie.content FROM '.IssueEvent::tableName().' ie WHERE ie.type=? AND ie.issue={{table}}.id ORDER BY id ASC LIMIT 1) as comment,(SELECT COUNT(ie2.id) FROM '.IssueEvent::tableName().' ie2 WHERE ie2.type=? AND ie2.issue={{table}}.id) as comments FROM {{table}} LEFT JOIN '.IssueReportTag::tableName().' t ON t.report={{table}}.id WHERE 1';
  12. $data = array(IssueEvent::TYPE_COMMENT,IssueEvent::TYPE_COMMENT);
  13. //Recherche simple
  14. if(!empty($_['filters']['keyword'])){
  15. $query .= ' AND (SELECT ie.content FROM '.IssueEvent::tableName().' ie WHERE ie.type=? AND ie.issue={{table}}.id ORDER BY id ASC LIMIT 1) LIKE ?';
  16. $data[] = IssueEvent::TYPE_COMMENT;
  17. $data[] = '%'.$_['filters']['keyword'].'%';
  18. }
  19. $tags = array_filter(explode(',',$_['tags']));
  20. if(count($tags)!=0){
  21. $query .= ' AND t.tag IN ('.str_repeat('?,',count($tags)-1).'?)';
  22. $data = array_merge($data, $tags);
  23. }
  24. //Recherche avancée
  25. if(isset($_['filters']['advanced'])){
  26. $_['filters']['advanced'] = filter_alteration($_['filters']['advanced'],'comment',function($filter) use (&$query,&$data){
  27. $query .= ' AND (SELECT ie.content FROM '.IssueEvent::tableName().' ie WHERE ie.type=? AND ie.issue={{table}}.id ORDER BY id ASC LIMIT 1) ';
  28. switch($filter['operator']){
  29. case 'like':
  30. $value = '%'.$filter['value'][0].'%';
  31. $query .= ' LIKE ? ';
  32. break;
  33. case 'not like':
  34. $value = '%'.$filter['value'][0].'%';
  35. $query .= ' NOT LIKE ? ';
  36. break;
  37. case 'null':
  38. $value = null;
  39. $query .= ' IS NULL ';
  40. break;
  41. case 'not null':
  42. $value = null;
  43. $query .= ' IS NOT NULL ';
  44. break;
  45. case '=':
  46. case '!=':
  47. $value = $filter['value'][0];
  48. $query .= ' '.$filter['operator'].' ? ';
  49. break;
  50. }
  51. $data[] = IssueEvent::TYPE_COMMENT;
  52. if($value!= null) $data[] = $value;
  53. return null;
  54. });
  55. filter_secure_query($_['filters']['advanced'],array('{{table}}.id','from','module','{{table}}.creator','{{table}}.created','assign','browser','ip','state'),$query,$data);
  56. }
  57. $query .= ' ORDER BY {{table}}.id desc ';
  58. $dataPaginate = $data;
  59. array_splice($dataPaginate, 0, 2);
  60. //Pagination
  61. $response['pagination'] = IssueReport::paginate(20,(!empty($_['page'])?$_['page']:0),$query,$dataPaginate);
  62. //Récupération des Users
  63. $users = array();
  64. foreach(User::getAll(array('right'=>false)) as $user)
  65. $users[$user->login] = $user;
  66. $response['rows'] = array();
  67. foreach(IssueReport::staticQuery($query,$data) as $row){
  68. //$row = $issueReport->toArray(true);
  69. $row['state'] = IssueReport::states($row['state']);
  70. $row['relativefrom'] = str_replace(ROOT_URL,'',$row['from']);
  71. $row['date'] = date('d-m-Y',$row['created']);
  72. $row['hour'] = date('H:i',$row['created']);
  73. $row['osIcon'] = 'fas fa-question-circle';
  74. $row['browserIcon'] = 'fas fa-question-circle';
  75. $row['comments'] = $row['comments']==1 ? false : $row['comments']-1;
  76. $row['excerpt'] = isset($row['comment']) ? truncate(strip_tags($row['comment']),150) : 'Aucun commentaire';
  77. $row['excerpt'] = preg_replace('/https?:\/\/[^\s]*\?module=issue&page=sheet\.report&id=([0-9]*)/is','<span class="text-muted" title="$0">#$1</span>',$row['excerpt']);
  78. $row['belongUser'] = $myUser->login == $row['creator'] || $myUser->can('issue','configure');
  79. $row['fullName'] = isset($users[$row['creator']]) ? $users[$row['creator']]->fullName() : $row['creator'];
  80. if(strlen($row['os'])>=3 && substr(strtolower($row['os']),0,3) == 'win') $row['osIcon'] = 'fab fa-windows text-primary';
  81. if(strlen($row['os'])>=5 && substr(strtolower($row['os']),0,5) == 'linux') $row['osIcon'] = 'fab fa-linux text-danger';
  82. if(strlen($row['os'])>=3 && substr(strtolower($row['os']),0,3) == 'mac') $row['osIcon'] = 'fab fa-apple text-secondary';
  83. switch($row['browser']){
  84. case 'firefox': $row['browserIcon'] = 'fab fa-firefox text-warning'; break;
  85. case 'ie': $row['browserIcon'] = 'fab fa-internet-explorer text-danger'; break;
  86. case 'edge': $row['browserIcon'] = 'fab fa-edge text-primary'; break;
  87. case 'chrome': $row['browserIcon'] = 'fab fa-chrome text-success'; break;
  88. }
  89. $row['tags'] = array();
  90. foreach(IssueReportTag::loadAll(array('report'=>$row['id'])) as $tag){
  91. if(!isset($allTags[$tag->tag])) continue;
  92. $row['tags'][] = $allTags[$tag->tag];
  93. }
  94. $response['rows'][] = $row;
  95. }
  96. });
  97. Action::register('issue_autocomplete',function(&$response){
  98. global $myUser,$_;
  99. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  100. require_once(__DIR__.SLASH.'IssueReport.class.php');
  101. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  102. $query = IssueReport::staticQuery('SELECT ir.id as id,ie.content as content FROM {{table}} ir LEFT JOIN '.IssueEvent::tableName().' ie ON ie.id=( SELECT id FROM '.IssueEvent::tableName().' ie2 WHERE ir.id=ie2.issue AND ie2.type=? ORDER BY id LIMIT 1) WHERE ie.content LIKE ?',array("comment",'%'.$_['keyword'].'%'));
  103. $response['rows'] = array();
  104. foreach ($query->fetchAll() as $row) {
  105. $response['rows'][] = array(
  106. 'id' => $row['id'],
  107. 'name' => $row['id'].' - '.strip_tags($row['content']),
  108. 'slug' => $row['id']
  109. );
  110. }
  111. });
  112. //Gestion avatar drag & drop
  113. Action::register('issue_attachments',function(&$response){
  114. File::handle_component(array(
  115. 'namespace' => 'issue', //stockés dans file/summary/*.*
  116. 'access' => 'issue', // crud sur summary,
  117. 'size' => '1000000000', // taille max
  118. 'storage' => 'issue/attachments/{{data.id}}/*' //chemin complet vers le fichier stocké
  119. ),$response);
  120. });
  121. Action::register('issue_add_document',function(&$response){
  122. global $myUser,$_;
  123. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  124. require_once(__DIR__.SLASH.'IssueReport.class.php');
  125. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  126. $report = IssueReport::provide();
  127. $report->save();
  128. foreach ($_['files'] as $file) {
  129. $name = (get_OS() === 'WIN') ? utf8_decode($file['name']) : $file['name'];
  130. $row = File::move(File::temp().$file['path'],'issue'.SLASH.'screens'.SLASH.$report->id.SLASH.$name);
  131. $row['url'] = 'action.php?action=issue_download_document&event='.$event->id.'&path='.base64_encode($file['name']);
  132. $row['oldPath'] = $file['path'];
  133. $response['files'][] = $row;
  134. }
  135. $response['id'] = $report->id;
  136. });
  137. //Téléchargement des documents
  138. Action::register('issue_download_document',function(&$response){
  139. global $myUser,$_;
  140. if(!$myUser->connected()) throw new Exception("Vous devez être connecté",401);
  141. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  142. $event = IssueEvent::getById($_['event']);
  143. $path = str_replace(array('..','/','\\'),'',base64_decode($_['path']));
  144. $path = $event->dir().SLASH.$path;
  145. File::downloadFile($path);
  146. });
  147. Action::register('issue_issuereport_meta_save',function(&$response){
  148. global $myUser,$_,$conf;
  149. User::check_access('issue','edit');
  150. require_once(__DIR__.SLASH.'IssueReport.class.php');
  151. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  152. require_once(__DIR__.SLASH.'IssueReportTag.class.php');
  153. if(!array_key_exists($_['state'], IssueReport::states())) throw new Exception("L'état du ticket est invalide");
  154. $item = IssueReport::provide();
  155. $oldItem = clone $item;
  156. if($item->creator != $myUser->login && !$myUser->can('issue','configure')) throw new Exception("Permissions insuffisantes", 403);
  157. //Maj des tags
  158. if(empty($_['tags'])) throw new Exception("Le ticket doit avoir au moins un tag");
  159. $existingTags = IssueReportTag::loadAll(array('report'=>$item->id));
  160. $tags = explode(',',$_['tags']);
  161. $tagsAction = false;
  162. $similarTags = array();
  163. foreach ($existingTags as $existingTag) {
  164. if(in_array($existingTag->tag, $tags)){
  165. $similarTags[] = $existingTag->tag;
  166. continue;
  167. }
  168. IssueReportTag::deleteById($existingTag->id);
  169. $tagsAction = array('action'=>'deleted','tag'=>IssueReportTag::tags($existingTag->tag));
  170. }
  171. foreach ($tags as $tag) {
  172. if(in_array($tag, $similarTags)) continue;
  173. $newTag = new IssueReportTag();
  174. $newTag->tag = $tag;
  175. $newTag->report = $item->id;
  176. $newTag->save();
  177. $tagsAction = array('action'=>'added','tag'=>IssueReportTag::tags($tag));
  178. }
  179. if($tagsAction != false){
  180. $event = new IssueEvent();
  181. $event->type = IssueEvent::TYPE_TAG;
  182. $event->issue = $item->id;
  183. $event->content = json_encode($tagsAction);
  184. $event->save();
  185. }
  186. if(!$myUser->can('issue','configure')) throw new Exception("Permissions insuffisantes", 403);
  187. $item->state = $_['state'];
  188. if(!empty($_['assign'])){
  189. $item->assign = stripslashes($_['assign']);
  190. $item->addFollower($item->assign);
  191. }
  192. $item->addFollower($myUser->login);
  193. $item->save();
  194. //Si l'assignation a changée on envoi une notification
  195. if($oldItem->assign != $item->assign){
  196. $event = new IssueEvent();
  197. $event->type = IssueEvent::TYPE_ASSIGNATION;
  198. $event->issue = $item->id;
  199. $event->content = json_encode(array(
  200. 'assigned' => $item->assign
  201. ));
  202. $event->save();
  203. if($item->assign != $myUser->login){
  204. Plugin::callHook("emit_notification", array(array(
  205. 'label' => '['.PROGRAM_NAME.' ] Le Ticket #'.$item->id.' vous a été assigné',
  206. 'html' => "Le ticket <a href='".ROOT_URL."/index.php?module=issue&page=sheet.report&id=".$item->id."'>#".$item->id."</a> vous a été assigné par ".(!empty($myUser->fullName())?$myUser->fullName():$myUser->login)." le ".date('d-m-Y à H:i').".
  207. <br>Bonne chance :).",
  208. 'type' => "issue",
  209. 'meta' => array('link' => ROOT_URL.'/index.php?module=issue&page=sheet.report&id='.$item->id),
  210. 'recipients' => array($item->assign)
  211. )));
  212. Plugin::callHook("emit_notification", array(array(
  213. 'label' => '['.PROGRAM_NAME.'] Le Ticket #'.$item->id.' a été assigné à '.User::byLogin($item->assign)->fullName(),
  214. 'html' => "Le ticket <a href='".ROOT_URL."/index.php?module=issue&page=sheet.report&id=".$item->id."'>#".$item->id."</a> a été assigné à ".User::byLogin($item->assign)->fullName()." par ".(!empty($myUser->fullName())?$myUser->fullName():$myUser->login)." le ".date('d-m-Y à H:i').".",
  215. 'type' => "issue",
  216. 'meta' => array('link' => ROOT_URL.'/index.php?module=issue&page=sheet.report&id='.$item->id),
  217. 'recipients' => array_diff( $item->followers(), array($myUser->login), array($item->assign) )
  218. )));
  219. }
  220. }
  221. //Si l'etat a changé on envois une notification
  222. if($oldItem->state != $item->state){
  223. $infos = array(
  224. 'meta' => array('link' => ROOT_URL.'/index.php?module=issue&page=sheet.report&id='.$item->id),
  225. 'recipients' => array_diff( $item->followers(), array($myUser->login) ) ,
  226. 'type' => "notice"
  227. );
  228. switch ($item->state) {
  229. case 'closed':
  230. $infos['label'] = "Le Ticket #".$item->id." est résolu";
  231. $infos['html'] = "Le ticket d'erreur <a href='".ROOT_URL."/index.php?module=issue&page=sheet.report&id=".$item->id."'>#".$item->id."</a> a été marqué comme résolu par ".(!empty($myUser->fullName())?$myUser->fullName():$myUser->login).' le '.date('d-m-Y à H:i').'.
  232. <br>Il est possible que la résolution de cette erreur ne soit mise en production que dans quelques jours.';
  233. break;
  234. case 'open':
  235. $infos['label'] = "Le Ticket #".$item->id." a été ré-ouvert";
  236. $infos['html'] = "Le ticket d'erreur <a href='".ROOT_URL."/index.php?module=issue&page=sheet.report&id=".$item->id."'>#".$item->id."</a> a été ré-ouvert par ".(!empty($myUser->fullName())?$myUser->fullName():$myUser->login).' le '.date('d-m-Y à H:i').'.
  237. <br>Il est possible que la résolution de cette erreur ne soit mise en production que dans quelques jours.';
  238. break;
  239. case 'canceled':
  240. $infos['label'] = "Le Ticket #".$item->id." a été annulé";
  241. $infos['html'] = "Le ticket d'erreur <a href='".ROOT_URL."/index.php?module=issue&page=sheet.report&id=".$item->id."'>#".$item->id."</a> a été annulé ".(!empty($myUser->fullName())?$myUser->fullName():$myUser->login).' le '.date('d-m-Y à H:i').'.
  242. <br>Il est possible que ce ticket soit un doublon ou que son contenu soit innaproprié.';
  243. break;
  244. default:
  245. # code...
  246. break;
  247. }
  248. $event = new IssueEvent();
  249. $event->type = IssueEvent::TYPE_STATE;
  250. $event->issue = $item->id;
  251. $event->content = json_encode(array(
  252. 'old' => $oldItem->state,
  253. 'new' => $item->state
  254. ));
  255. $event->save();
  256. Plugin::callHook("emit_notification", array($infos));
  257. }
  258. });
  259. //Ajout ou modification d'élément issuereport
  260. Action::register('issue_issuereport_save',function(&$response){
  261. global $myUser,$_,$conf;
  262. require_once(__DIR__.SLASH.'IssueReport.class.php');
  263. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  264. require_once(__DIR__.SLASH.'IssueReportTag.class.php');
  265. if(!$myUser->connected()) throw new Exception("Vous devez être connecté pour laisser un rapport d'erreur",401);
  266. $item = IssueReport::provide();
  267. if(!$myUser->can('issue','edit') && is_numeric($item->id) && $item->id!=0) throw new Exception("Permissions insuffisantes",403);
  268. $tags = array_filter(explode(',',$_['tags']));
  269. if(count($tags)==0) throw new Exception("Merci de sélectionner au moins une catégorie");
  270. if(!isset($_['issue-comment']) || empty($_['issue-comment'])) throw new Exception("Merci de commenter votre ticket");
  271. $item->browser = $_['browser'];
  272. $item->browserVersion = $_['browserVersion'];
  273. $item->online = $_['online'];
  274. $item->os = $_['os'];
  275. $item->state = 'open';
  276. $item->from = $_['from'];
  277. $item->width = $_['width'];
  278. $item->height = $_['height'];
  279. $item->history = $_['history'];
  280. $item->ip = ip();
  281. $item->addFollower($myUser->login);
  282. $item->save();
  283. $firstEvent = new IssueEvent();
  284. $firstEvent->created = $item->created;
  285. $firstEvent->updated = $item->updated;
  286. $firstEvent->creator = $item->creator;
  287. $firstEvent->updater = $item->updater;
  288. $firstEvent->type = IssueEvent::TYPE_COMMENT;
  289. $firstEvent->content = preg_replace('/<img.*?(src="data).*?>/', '', wysiwyg_filter(html_entity_decode($_['issue-comment'])));
  290. $firstEvent->issue = $item->id;
  291. $firstEvent->save();
  292. if (preg_match_all('/<img.*?>/', wysiwyg_filter(html_entity_decode($_['issue-comment'])), $matches)) {
  293. foreach ($matches[0] as $index => $imgTag) {
  294. if(preg_match('/src="data:image.*base64,.*"/', $imgTag, $imgSrc)) {
  295. list($type, $data) = explode(';', $imgSrc[0]);
  296. $ext = explode('/', $type)[1];
  297. $dataEncode = explode(',', $data);
  298. $stream = base64_decode($dataEncode[1]);
  299. $attachmentFolder = $firstEvent->dir();
  300. if(!file_exists($attachmentFolder)) mkdir($attachmentFolder,0755,true);
  301. $screenPath = $firstEvent->dir().SLASH.'image'.$index.'.'.$ext;
  302. file_put_contents($screenPath, $stream);
  303. }
  304. }
  305. }
  306. $response['item'] = $item->toArray();
  307. IssueReportTag::delete(array('report'=>$item->id));
  308. foreach ($tags as $tag) {
  309. $reportTag = new IssueReportTag();
  310. $reportTag->tag = $tag;
  311. $reportTag->report = $item->id;
  312. $reportTag->save();
  313. }
  314. if(!empty($_['screenshot'])){
  315. $screenshot = str_replace('data:image/png;base64,', '', $_['screenshot']);
  316. $screenshot = str_replace(' ', '+', $screenshot);
  317. $stream = base64_decode($screenshot);
  318. $attachmentFolder = $firstEvent->dir();
  319. if(!file_exists($attachmentFolder)) mkdir($attachmentFolder,0755,true);
  320. $screenPath = $attachmentFolder.SLASH.'screenshot.jpg';
  321. file_put_contents($screenPath, $stream);
  322. }
  323. //Ajout fichiers joints
  324. if(!empty($_['document']))
  325. File::save_component('document', 'issue/attachments/'.$firstEvent->id.'/{{label}}');
  326. $data = $item->toArray();
  327. $data['comment'] = '<strong>'.$item->creator.': </strong>'.$firstEvent->content;
  328. $data['url'] = ROOT_URL.'/index.php?module=issue&page=sheet.report&id='.$data['id'];
  329. $data['title'] = 'Le Ticket <a href="'.$data['url'].'">#'.$item->id.'</a> a été ouvert par '.$item->creator;
  330. if(!empty($conf->get('issue_report_mails'))){
  331. $path = __DIR__.SLASH.'mail.template.php';
  332. if(!file_exists($path)) return;
  333. $stream = file_get_contents($path);
  334. $recipients = array();
  335. foreach (explode(',', $conf->get('issue_report_mails')) as $recipient) {
  336. if(is_numeric($recipient)){
  337. foreach(UserFirmRank::loadAll(array('rank'=>$recipient)) as $ufr)
  338. $recipients[] = $ufr->user;
  339. continue;
  340. }
  341. $recipients[] = $recipient;
  342. }
  343. // Émission d'une notification pour les devs
  344. Plugin::callHook("emit_notification", array(array(
  345. 'label' => 'Ticket #'.$item->id.' ouvert',
  346. 'html' => template($stream,$data),
  347. 'type' => "issue",
  348. 'meta' => array('link' => $data['url']),
  349. 'recipients' => $recipients
  350. )));
  351. }
  352. // Émission d'une notification pour l'auteur du ticket
  353. Plugin::callHook("emit_notification", array(array(
  354. 'label' => "Votre Ticket #".$item->id." a été envoyé",
  355. 'html' => "Le ticket <a href='".ROOT_URL."/index.php?module=issue&page=sheet.report&id=".$item->id."'>#".$item->id."</a> a été créé et sera pris en compte par nos techniciens, vous pouvez consulter
  356. son avancement en <a href='".ROOT_URL."/index.php?module=issue&page=sheet.report&id=".$item->id."'>cliquant ici</a>",
  357. 'type' => "notice",
  358. 'meta' => array('link' => $data['url']),
  359. 'recipients' => array($item->creator)
  360. )));
  361. Log::put('Déclaration d\'un rapport d\'erreur #'.$item->toText(), 'Issue');
  362. });
  363. Action::register('issue_screenshot_download',function(&$response){
  364. global $myUser,$_;
  365. if(!$myUser->connected()) throw new Exception("Connexion requise",401);
  366. try {
  367. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  368. $event = IssueEvent::getById($_['id']);
  369. File::downloadFile($event->dir().SLASH.'screenshot.jpg');
  370. } catch(Exception $e) {
  371. File::downloadFile(__ROOT__.'img/default-image-muted.png');
  372. }
  373. });
  374. //Suppression d'élement issuereport
  375. Action::register('issue_issuereport_delete',function(&$response){
  376. global $myUser,$_;
  377. require_once(__DIR__.SLASH.'IssueReport.class.php');
  378. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  379. $issue = IssueReport::provide();
  380. if($issue->creator != $myUser->login && !$myUser->can('issue','configure')) throw new Exception("Permissions insuffisantes", 403);
  381. $issue->remove();
  382. });
  383. //Etre notifié du sujet
  384. Action::register('issue_follow_toggle',function(&$response){
  385. global $myUser,$_;
  386. require_once(__DIR__.SLASH.'IssueReport.class.php');
  387. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  388. User::check_access('issue','read');
  389. $issue = IssueReport::provide();
  390. $followers = $issue->followers();
  391. $key = array_search($myUser->login, $followers);
  392. if($_['state']){
  393. if($key===false) $followers[] = $myUser->login;
  394. }else{
  395. if($issue->creator == $myUser->login) throw new Exception("Vous ne pouvez pas arrêter de suivre un ticket que vous avez créé.");
  396. if($key!==false) unset($followers[$key]);
  397. }
  398. $issue->followers($followers);
  399. $issue->save();
  400. });
  401. //Sauvegarde des configurations de issue
  402. Action::register('issue_setting_save',function(&$response){
  403. global $myUser,$_,$conf;
  404. User::check_access('issue','configure');
  405. foreach(Configuration::setting('issue') as $key=>$value){
  406. if(!is_array($value)) continue;
  407. $allowed[] = $key;
  408. }
  409. foreach ($_['fields'] as $key => $value)
  410. if(in_array($key, $allowed)) $conf->put($key,$value);
  411. });
  412. /** EVENT **/
  413. //Récuperation d'une liste de issueevent
  414. Action::register('issue_issue_event_search',function(&$response){
  415. global $myUser,$_;
  416. User::check_access('issue','read');
  417. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  418. require_once(__DIR__.SLASH.'IssueReport.class.php');
  419. $events = IssueEvent::loadAll(array('issue'=>$_['issue']),array('id ASC'));
  420. foreach($events as $i=>$event){
  421. $row = $event->toArray();
  422. $creator = User::byLogin($event->creator);
  423. $row['edit_rights'] = ($myUser->login == $event->creator || $myUser->superadmin);
  424. $row['creator'] = $creator->toArray();
  425. $row['avatar'] = $creator->getAvatar();
  426. $row['fullName'] = $creator->fullName();
  427. $row['created'] = date('d/m/Y H:i', $event->created);
  428. $row['createdRelative'] = relative_time($event->created, null, 6, true);
  429. switch($event->type){
  430. case 'comment':
  431. $row['classes'] = $i == 0 ? 'issue-first-comment' : '';
  432. $row['files'] = array();
  433. foreach (glob($event->dir().SLASH.'*') as $key => $value){
  434. $file = array();
  435. $file['extension'] = getExt($value);
  436. $file['label'] = mt_basename($value);
  437. $file['labelExcerpt'] = truncate($file['label'],35);
  438. $file['type'] = in_array($file['extension'], array('jpg','png','jpeg','bmp','gif','svg')) ? 'image' : 'file';
  439. $file['url'] = 'action.php?action=issue_download_document&event='.$event->id.'&path='.base64_encode(basename($value));
  440. $file['icon'] = getExtIcon($file['extension']);
  441. $row['files'][] = $file;
  442. }
  443. if($creator->login == $myUser->login || $myUser->can('issue','configure')) $row['classes'] .=' editable';
  444. $row['comment'] = empty($event->content) ? 'Pas de commentaire': $event->content;
  445. $row['comment'] = preg_replace('/https?:\/\/[^\s]*\?module=issue&page=sheet\.report&id=([0-9]*)/is','<a href="$0">#$1</a>',$row['comment']);
  446. $row['hasfiles'] = count($row['files']) > 0 ? true : false;
  447. break;
  448. case IssueEvent::TYPE_STATE:
  449. $infos = json_decode($row['content'],true);
  450. $row['oldstate'] = IssueReport::states($infos['old']);
  451. $row['state'] = IssueReport::states($infos['new']);
  452. break;
  453. case IssueEvent::TYPE_TAG:
  454. $infos = json_decode($row['content'],true);
  455. $row['action'] = $infos['action'] == 'added' ? 'ajouté' :'supprimé';
  456. $row['tag'] = $infos['tag'];
  457. break;
  458. case IssueEvent::TYPE_ASSIGNATION:
  459. $infos = json_decode($row['content'],true);
  460. $assigned = User::byLogin($infos['assigned']);
  461. $row['assigned'] = array(
  462. 'fullName' => $assigned->fullName(),
  463. 'avatar' => $assigned->getAvatar()
  464. );
  465. break;
  466. }
  467. $response['rows'][] = $row;
  468. }
  469. });
  470. //Ajout ou modification d'élément issueevent
  471. Action::register('issue_issue_event_save',function(&$response){
  472. global $myUser,$_;
  473. require_once(__DIR__.SLASH.'IssueReport.class.php');
  474. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  475. $item = IssueEvent::provide('id',1);
  476. $isNew = empty($item->id);
  477. if($myUser->login != $item->creator && !$myUser->can('issue','edit')) throw new Exception("Permissions insuffisantes", 403);
  478. if(!isset($_['content']) || empty($_['content'])) throw new Exception("Vous devez spécifier un commentaire");
  479. $item->type = IssueEvent::TYPE_COMMENT;
  480. $item->content = wysiwyg_filter(html_entity_decode($_['content']));
  481. $item->issue = $_['issue'];
  482. $mentionned = array();
  483. if($item->id == 0){
  484. preg_match_all('|data-mention-value="([^"]*)"|isU', $item->content, $matches,PREG_SET_ORDER);
  485. foreach ($matches as $match) {
  486. $mentionned[] = $match[1];
  487. }
  488. }
  489. $item->save();
  490. if(!empty($_['event-files']))
  491. File::save_component('event-files', 'issue/attachments/'.$item->id.'/{{label}}');
  492. $issue = IssueReport::getById($item->issue);
  493. $issue->addFollower($myUser->login);
  494. $issue->save();
  495. $path = __DIR__.SLASH.'mail.template.php';
  496. if(!file_exists($path)) return;
  497. $stream = file_get_contents($path);
  498. $data = $item->toArray();
  499. $data['comment'] = '<strong>'.$item->creator.': </strong>'.$item->content;
  500. $data['url'] = ROOT_URL.'/index.php?module=issue&page=sheet.report&id='.$data['issue'];
  501. $data['title'] = 'Le Ticket <a href="'.$data['url'].'">#'.$item->issue.'</a> a été commenté par '.$item->creator;
  502. $recipients = array_diff($issue->followers(), array($myUser->login));
  503. // Émission d'une notification pour les acteurs du rapport
  504. Plugin::callHook("emit_notification", array(array(
  505. 'label' => 'Ticket #'.$item->issue.': '.($isNew?'Nouveau commentaire':'Édition d\'un commentaire') ,
  506. 'html' => template($stream,$data),
  507. 'type' => "issue",
  508. 'meta' => array('link' => $data['url']),
  509. 'recipients' => $recipients
  510. )));
  511. // Émission d'une notification pour les acteurs spécifiquement mentionnés
  512. if(count($mentionned)){
  513. $data['comment'] = 'Vous avez été mentionné dans le commentaire suivant : <br>'.$data['comment'];
  514. $data['url'] = ROOT_URL.'/index.php?module=issue&page=sheet.report&id='.$data['issue'].'#issue-comment-'.$item->id;
  515. $data['title'] = 'Vous avez été mentionné par '.$item->creator.' dans le ticket <a href="'.$data['url'].'">#'.$item->issue.'</a>';
  516. Plugin::callHook("emit_notification", array(array(
  517. 'label' => 'Vous avez été mentionné par '.$item->creator.' dans le ticket #'.$item->issue.':' ,
  518. 'html' => template($stream,$data),
  519. 'type' => "issue",
  520. 'meta' => array('link' => $data['url']),
  521. 'recipients' => $mentionned
  522. )));
  523. }
  524. });
  525. //Récuperation ou edition d'élément issueevent
  526. Action::register('issue_issue_event_edit',function(&$response){
  527. global $myUser,$_;
  528. User::check_access('issue','edit');
  529. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  530. require_once(__DIR__.SLASH.'IssueReport.class.php');
  531. $event = IssueEvent::getById($_['id'],1);
  532. if($event->type != 'comment') throw new Exception("Vous ne pouvez pas éditer cet événement");
  533. if($myUser->login != $event->creator && !$myUser->superadmin) throw new Exception("Permissions insuffisantes", 403);
  534. $response = $event->toArray(true);
  535. });
  536. //Suppression d'élement issueevent
  537. Action::register('issue_issue_event_delete',function(&$response){
  538. global $myUser,$_;
  539. require_once(__DIR__.SLASH.'IssueReport.class.php');
  540. require_once(__DIR__.SLASH.'IssueEvent.class.php');
  541. $event = IssueEvent::getById($_['id'],1);
  542. if($event->type != 'comment') throw new Exception("Vous ne pouvez pas supprimer cet événement");
  543. $issue = $event->join('issue');
  544. if($event->creator != $myUser->login && !$myUser->can('issue','configure')) throw new Exception("Permissions insuffisantes", 403);
  545. $event->remove();
  546. if(IssueEvent::rowCount(array('issue'=>$issue->id)) == 0){
  547. if($issue->creator != $myUser->login && !$myUser->can('issue','configure')) throw new Exception("Permissions insuffisantes", 403);
  548. $issue->remove(false);
  549. $response['redirect'] = 'index.php?module=issue&page=list.issue';
  550. }
  551. });
  552. ?>