TicketManager.php 82 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462
  1. <?php
  2. /* For licensing terms, see /license.txt */
  3. use Chamilo\TicketBundle\Entity\MessageAttachment;
  4. use Chamilo\TicketBundle\Entity\Priority;
  5. use Chamilo\TicketBundle\Entity\Project;
  6. use Chamilo\TicketBundle\Entity\Status;
  7. use Chamilo\TicketBundle\Entity\Ticket;
  8. /**
  9. * Class TicketManager.
  10. *
  11. * @package chamilo.plugin.ticket
  12. */
  13. class TicketManager
  14. {
  15. const PRIORITY_NORMAL = 'NRM';
  16. const PRIORITY_HIGH = 'HGH';
  17. const PRIORITY_LOW = 'LOW';
  18. const SOURCE_EMAIL = 'MAI';
  19. const SOURCE_PHONE = 'TEL';
  20. const SOURCE_PLATFORM = 'PLA';
  21. const SOURCE_PRESENTIAL = 'PRE';
  22. const STATUS_NEW = 'NAT';
  23. const STATUS_PENDING = 'PND';
  24. const STATUS_UNCONFIRMED = 'XCF';
  25. const STATUS_CLOSE = 'CLS';
  26. const STATUS_FORWARDED = 'REE';
  27. /**
  28. * Constructor.
  29. */
  30. public function __construct()
  31. {
  32. }
  33. /**
  34. * Get categories of tickets.
  35. *
  36. * @param int $projectId
  37. * @param string $order
  38. *
  39. * @return array
  40. */
  41. public static function get_all_tickets_categories($projectId, $order = '')
  42. {
  43. $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
  44. $table_support_project = Database::get_main_table(TABLE_TICKET_PROJECT);
  45. $order = empty($order) ? 'category.total_tickets DESC' : $order;
  46. $order = Database::escape_string($order);
  47. $projectId = (int) $projectId;
  48. $sql = "SELECT
  49. category.*,
  50. category.id category_id,
  51. project.other_area,
  52. project.email
  53. FROM
  54. $table_support_category category
  55. INNER JOIN $table_support_project project
  56. ON project.id = category.project_id
  57. WHERE project.id = $projectId
  58. ORDER BY $order";
  59. $result = Database::query($sql);
  60. $types = [];
  61. while ($row = Database::fetch_assoc($result)) {
  62. $types[] = $row;
  63. }
  64. return $types;
  65. }
  66. /**
  67. * @param $from
  68. * @param $numberItems
  69. * @param $column
  70. * @param $direction
  71. *
  72. * @return array
  73. */
  74. public static function getCategories($from, $numberItems, $column, $direction)
  75. {
  76. $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
  77. $sql = "SELECT id, name, description, total_tickets
  78. FROM $table";
  79. if (!in_array($direction, ['ASC', 'DESC'])) {
  80. $direction = 'ASC';
  81. }
  82. $column = (int) $column;
  83. $from = (int) $from;
  84. $numberItems = (int) $numberItems;
  85. //$sql .= " ORDER BY col$column $direction ";
  86. $sql .= " LIMIT $from,$numberItems";
  87. $result = Database::query($sql);
  88. $types = [];
  89. while ($row = Database::fetch_array($result)) {
  90. $types[] = $row;
  91. }
  92. return $types;
  93. }
  94. /**
  95. * @param int $id
  96. *
  97. * @return array|mixed
  98. */
  99. public static function getCategory($id)
  100. {
  101. $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
  102. $id = (int) $id;
  103. $sql = "SELECT id, name, description, total_tickets
  104. FROM $table WHERE id = $id";
  105. $result = Database::query($sql);
  106. $category = Database::fetch_array($result);
  107. return $category;
  108. }
  109. /**
  110. * @return int
  111. */
  112. public static function getCategoriesCount()
  113. {
  114. $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
  115. $sql = "SELECT count(id) count
  116. FROM $table ";
  117. $result = Database::query($sql);
  118. $category = Database::fetch_array($result);
  119. return $category['count'];
  120. }
  121. /**
  122. * @param int $id
  123. * @param array $params
  124. */
  125. public static function updateCategory($id, $params)
  126. {
  127. $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
  128. $id = (int) $id;
  129. Database::update($table, $params, ['id = ?' => $id]);
  130. }
  131. /**
  132. * @param array $params
  133. */
  134. public static function addCategory($params)
  135. {
  136. $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
  137. Database::insert($table, $params);
  138. }
  139. /**
  140. * @param int $id
  141. *
  142. * @return bool
  143. */
  144. public static function deleteCategory($id)
  145. {
  146. $id = (int) $id;
  147. if (empty($id)) {
  148. return false;
  149. }
  150. $table = Database::get_main_table(TABLE_TICKET_TICKET);
  151. $sql = "UPDATE $table SET category_id = NULL WHERE category_id = $id";
  152. Database::query($sql);
  153. $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
  154. $sql = "DELETE FROM $table WHERE id = $id";
  155. Database::query($sql);
  156. return true;
  157. }
  158. /**
  159. * @param int $categoryId
  160. * @param array $users
  161. *
  162. * @return bool
  163. */
  164. public static function addUsersToCategory($categoryId, $users)
  165. {
  166. if (empty($users) || empty($categoryId)) {
  167. return false;
  168. }
  169. $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
  170. foreach ($users as $userId) {
  171. if (self::userIsAssignedToCategory($userId, $categoryId) === false) {
  172. $params = [
  173. 'category_id' => $categoryId,
  174. 'user_id' => $userId,
  175. ];
  176. Database::insert($table, $params);
  177. }
  178. }
  179. return true;
  180. }
  181. /**
  182. * @param int $userId
  183. * @param int $categoryId
  184. *
  185. * @return bool
  186. */
  187. public static function userIsAssignedToCategory($userId, $categoryId)
  188. {
  189. $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
  190. $userId = (int) $userId;
  191. $categoryId = (int) $categoryId;
  192. $sql = "SELECT * FROM $table
  193. WHERE category_id = $categoryId AND user_id = $userId";
  194. $result = Database::query($sql);
  195. return Database::num_rows($result) > 0;
  196. }
  197. /**
  198. * @param int $categoryId
  199. *
  200. * @return array
  201. */
  202. public static function getUsersInCategory($categoryId)
  203. {
  204. $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
  205. $categoryId = (int) $categoryId;
  206. $sql = "SELECT * FROM $table WHERE category_id = $categoryId";
  207. $result = Database::query($sql);
  208. return Database::store_result($result);
  209. }
  210. /**
  211. * @param int $categoryId
  212. */
  213. public static function deleteAllUserInCategory($categoryId)
  214. {
  215. $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
  216. $categoryId = (int) $categoryId;
  217. $sql = "DELETE FROM $table WHERE category_id = $categoryId";
  218. Database::query($sql);
  219. }
  220. /**
  221. * Get all possible tickets statuses.
  222. *
  223. * @return array
  224. */
  225. public static function get_all_tickets_status()
  226. {
  227. $table = Database::get_main_table(TABLE_TICKET_STATUS);
  228. $sql = "SELECT * FROM $table";
  229. $result = Database::query($sql);
  230. $types = [];
  231. while ($row = Database::fetch_assoc($result)) {
  232. $types[] = $row;
  233. }
  234. return $types;
  235. }
  236. /**
  237. * Inserts a new ticket in the corresponding tables.
  238. *
  239. * @param int $category_id
  240. * @param int $course_id
  241. * @param int $sessionId
  242. * @param int $project_id
  243. * @param string $other_area
  244. * @param string $subject
  245. * @param string $content
  246. * @param string $personalEmail
  247. * @param array $fileAttachments
  248. * @param string $source
  249. * @param string $priority
  250. * @param string $status
  251. * @param int $assignedUserId
  252. *
  253. * @return bool
  254. */
  255. public static function add(
  256. $category_id,
  257. $course_id,
  258. $sessionId,
  259. $project_id,
  260. $other_area,
  261. $subject,
  262. $content,
  263. $personalEmail = '',
  264. $fileAttachments = [],
  265. $source = '',
  266. $priority = '',
  267. $status = '',
  268. $assignedUserId = 0
  269. ) {
  270. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  271. $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
  272. if (empty($category_id)) {
  273. return false;
  274. }
  275. $currentUserId = api_get_user_id();
  276. $currentUserInfo = api_get_user_info();
  277. $now = api_get_utc_datetime();
  278. $course_id = (int) $course_id;
  279. $category_id = (int) $category_id;
  280. $project_id = (int) $project_id;
  281. $priority = empty($priority) ? self::PRIORITY_NORMAL : (int) $priority;
  282. if ($status === '') {
  283. $status = self::STATUS_NEW;
  284. if ($other_area > 0) {
  285. $status = self::STATUS_FORWARDED;
  286. }
  287. }
  288. if (!empty($category_id)) {
  289. if (empty($assignedUserId)) {
  290. $usersInCategory = self::getUsersInCategory($category_id);
  291. if (!empty($usersInCategory) && count($usersInCategory) > 0) {
  292. $userCategoryInfo = $usersInCategory[0];
  293. if (isset($userCategoryInfo['user_id'])) {
  294. $assignedUserId = $userCategoryInfo['user_id'];
  295. }
  296. }
  297. }
  298. }
  299. $assignedUserInfo = [];
  300. if (!empty($assignedUserId)) {
  301. $assignedUserInfo = api_get_user_info($assignedUserId);
  302. if (empty($assignedUserInfo)) {
  303. return false;
  304. }
  305. }
  306. // insert_ticket
  307. $params = [
  308. 'project_id' => $project_id,
  309. 'category_id' => $category_id,
  310. 'priority_id' => $priority,
  311. 'personal_email' => $personalEmail,
  312. 'status_id' => $status,
  313. 'start_date' => $now,
  314. 'sys_insert_user_id' => $currentUserId,
  315. 'sys_insert_datetime' => $now,
  316. 'sys_lastedit_user_id' => $currentUserId,
  317. 'sys_lastedit_datetime' => $now,
  318. 'source' => $source,
  319. 'assigned_last_user' => $assignedUserId,
  320. 'subject' => $subject,
  321. 'message' => $content,
  322. 'code' => '',
  323. 'total_messages' => 0,
  324. ];
  325. if (!empty($course_id)) {
  326. $params['course_id'] = $course_id;
  327. }
  328. if (!empty($sessionId)) {
  329. $params['session_id'] = $sessionId;
  330. }
  331. $ticketId = Database::insert($table_support_tickets, $params);
  332. if ($ticketId) {
  333. $ticket_code = 'A'.str_pad($ticketId, 11, '0', STR_PAD_LEFT);
  334. $titleCreated = sprintf(
  335. get_lang('Ticket %s created'),
  336. $ticket_code
  337. );
  338. Display::addFlash(Display::return_message(
  339. $titleCreated,
  340. 'normal',
  341. false
  342. ));
  343. if ($assignedUserId != 0) {
  344. self::assignTicketToUser(
  345. $ticketId,
  346. $assignedUserId
  347. );
  348. Display::addFlash(Display::return_message(
  349. sprintf(
  350. get_lang('TicketXAssignedToUserX'),
  351. $ticket_code,
  352. $assignedUserInfo['complete_name']
  353. ),
  354. 'normal',
  355. false
  356. ));
  357. }
  358. if (!empty($fileAttachments)) {
  359. $attachmentCount = 0;
  360. foreach ($fileAttachments as $attach) {
  361. if (!empty($attach['tmp_name'])) {
  362. $attachmentCount++;
  363. }
  364. }
  365. if ($attachmentCount > 0) {
  366. self::insertMessage(
  367. $ticketId,
  368. '',
  369. '',
  370. $fileAttachments,
  371. $currentUserId
  372. );
  373. }
  374. }
  375. // Update code
  376. $sql = "UPDATE $table_support_tickets
  377. SET code = '$ticket_code'
  378. WHERE id = '$ticketId'";
  379. Database::query($sql);
  380. // Update total
  381. $sql = "UPDATE $table_support_category
  382. SET total_tickets = total_tickets + 1
  383. WHERE id = $category_id";
  384. Database::query($sql);
  385. $helpDeskMessage =
  386. '<table>
  387. <tr>
  388. <td width="100px"><b>'.get_lang('User').'</b></td>
  389. <td width="400px">'.$currentUserInfo['complete_name'].'</td>
  390. </tr>
  391. <tr>
  392. <td width="100px"><b>'.get_lang('Username').'</b></td>
  393. <td width="400px">'.$currentUserInfo['username'].'</td>
  394. </tr>
  395. <tr>
  396. <td width="100px"><b>'.get_lang('Email').'</b></td>
  397. <td width="400px">'.$currentUserInfo['email'].'</td>
  398. </tr>
  399. <tr>
  400. <td width="100px"><b>'.get_lang('Phone').'</b></td>
  401. <td width="400px">'.$currentUserInfo['phone'].'</td>
  402. </tr>
  403. <tr>
  404. <td width="100px"><b>'.get_lang('Date').'</b></td>
  405. <td width="400px">'.api_convert_and_format_date($now, DATE_TIME_FORMAT_LONG).'</td>
  406. </tr>
  407. <tr>
  408. <td width="100px"><b>'.get_lang('Title').'</b></td>
  409. <td width="400px">'.Security::remove_XSS($subject).'</td>
  410. </tr>
  411. <tr>
  412. <td width="100px"><b>'.get_lang('Description').'</b></td>
  413. <td width="400px">'.Security::remove_XSS($content).'</td>
  414. </tr>
  415. </table>';
  416. if ($assignedUserId != 0) {
  417. $href = api_get_path(WEB_CODE_PATH).'/ticket/ticket_details.php?ticket_id='.$ticketId;
  418. $helpDeskMessage .= sprintf(
  419. get_lang('TicketAssignedToXCheckZAtLinkY'),
  420. $assignedUserInfo['complete_name'],
  421. $href,
  422. $ticketId
  423. );
  424. }
  425. if (empty($category_id)) {
  426. if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
  427. $warningSubject = sprintf(
  428. get_lang('Ticket %s createdWithNoCategory'),
  429. $ticket_code
  430. );
  431. Display::addFlash(Display::return_message($warningSubject));
  432. $admins = UserManager::get_all_administrators();
  433. foreach ($admins as $userId => $data) {
  434. if ($data['active']) {
  435. MessageManager::send_message_simple(
  436. $userId,
  437. $warningSubject,
  438. $helpDeskMessage
  439. );
  440. }
  441. }
  442. }
  443. } else {
  444. $categoryInfo = self::getCategory($category_id);
  445. $usersInCategory = self::getUsersInCategory($category_id);
  446. $message = '<h2>'.get_lang('Ticket info').'</h2><br />'.$helpDeskMessage;
  447. if (api_get_setting('ticket_warn_admin_no_user_in_category') === 'true') {
  448. $usersInCategory = self::getUsersInCategory($category_id);
  449. if (empty($usersInCategory)) {
  450. $subject = sprintf(
  451. get_lang('Warning: No one has been assigned to category %s'),
  452. $categoryInfo['name']
  453. );
  454. if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
  455. Display::addFlash(Display::return_message(
  456. sprintf(
  457. get_lang('A notification was sent to the administrators to report this category has no user assigned'),
  458. $categoryInfo['name']
  459. ),
  460. null,
  461. false
  462. ));
  463. $admins = UserManager::get_all_administrators();
  464. foreach ($admins as $userId => $data) {
  465. if ($data['active']) {
  466. self::sendNotification(
  467. $ticketId,
  468. $subject,
  469. $message,
  470. $userId
  471. );
  472. }
  473. }
  474. } else {
  475. Display::addFlash(Display::return_message($subject));
  476. }
  477. }
  478. }
  479. // Send notification to all users
  480. if (!empty($usersInCategory)) {
  481. foreach ($usersInCategory as $data) {
  482. if ($data['user_id']) {
  483. self::sendNotification(
  484. $ticketId,
  485. $subject,
  486. $message,
  487. $data['user_id']
  488. );
  489. }
  490. }
  491. }
  492. }
  493. if (!empty($personalEmail)) {
  494. api_mail_html(
  495. get_lang('Virtual support'),
  496. $personalEmail,
  497. get_lang('IncidentResentToVirtual support'),
  498. $helpDeskMessage
  499. );
  500. }
  501. self::sendNotification(
  502. $ticketId,
  503. $titleCreated,
  504. $helpDeskMessage
  505. );
  506. return true;
  507. }
  508. return false;
  509. }
  510. /**
  511. * Assign ticket to admin.
  512. *
  513. * @param int $ticketId
  514. * @param int $userId
  515. *
  516. * @return bool
  517. */
  518. public static function assignTicketToUser(
  519. $ticketId,
  520. $userId
  521. ) {
  522. $ticketId = (int) $ticketId;
  523. $userId = (int) $userId;
  524. if (empty($ticketId)) {
  525. return false;
  526. }
  527. $ticket = self::get_ticket_detail_by_id($ticketId);
  528. if ($ticket) {
  529. $table = Database::get_main_table(TABLE_TICKET_TICKET);
  530. $sql = "UPDATE $table
  531. SET assigned_last_user = $userId
  532. WHERE id = $ticketId";
  533. Database::query($sql);
  534. $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
  535. $params = [
  536. 'ticket_id' => $ticketId,
  537. 'user_id' => $userId,
  538. 'sys_insert_user_id' => api_get_user_id(),
  539. 'assigned_date' => api_get_utc_datetime(),
  540. ];
  541. Database::insert($table, $params);
  542. return true;
  543. } else {
  544. return false;
  545. }
  546. }
  547. /**
  548. * Insert message between Users and Admins.
  549. *
  550. * @param int $ticketId
  551. * @param string $subject
  552. * @param string $content
  553. * @param array $fileAttachments
  554. * @param int $userId
  555. * @param string $status
  556. * @param bool $sendConfirmation
  557. *
  558. * @return bool
  559. */
  560. public static function insertMessage(
  561. $ticketId,
  562. $subject,
  563. $content,
  564. $fileAttachments,
  565. $userId,
  566. $status = 'NOL',
  567. $sendConfirmation = false
  568. ) {
  569. $ticketId = (int) $ticketId;
  570. $userId = (int) $userId;
  571. $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
  572. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  573. if ($sendConfirmation) {
  574. $form =
  575. '<form action="ticket_details.php?ticket_id='.$ticketId.'" id="confirmticket" method="POST" >
  576. <p>'.get_lang('Was this answer satisfactory?').'</p>
  577. <button class="btn btn-primary responseyes" name="response" id="responseyes" value="1">'.
  578. get_lang('Yes').'</button>
  579. <button class="btn btn-danger responseno" name="response" id="responseno" value="0">'.
  580. get_lang('No').'</button>
  581. </form>';
  582. $content .= $form;
  583. }
  584. $now = api_get_utc_datetime();
  585. $params = [
  586. 'ticket_id' => $ticketId,
  587. 'subject' => $subject,
  588. 'message' => $content,
  589. 'ip_address' => api_get_real_ip(),
  590. 'sys_insert_user_id' => $userId,
  591. 'sys_insert_datetime' => $now,
  592. 'sys_lastedit_user_id' => $userId,
  593. 'sys_lastedit_datetime' => $now,
  594. 'status' => $status,
  595. ];
  596. $messageId = Database::insert($table_support_messages, $params);
  597. if ($messageId) {
  598. // update_total_message
  599. $sql = "UPDATE $table_support_tickets
  600. SET
  601. sys_lastedit_user_id = $userId,
  602. sys_lastedit_datetime = '$now',
  603. total_messages = (
  604. SELECT COUNT(*) as total_messages
  605. FROM $table_support_messages
  606. WHERE ticket_id = $ticketId
  607. )
  608. WHERE id = $ticketId ";
  609. Database::query($sql);
  610. if (is_array($fileAttachments)) {
  611. foreach ($fileAttachments as $file_attach) {
  612. if ($file_attach['error'] == 0) {
  613. self::saveMessageAttachmentFile(
  614. $file_attach,
  615. $ticketId,
  616. $messageId
  617. );
  618. } else {
  619. if ($file_attach['error'] != UPLOAD_ERR_NO_FILE) {
  620. return false;
  621. }
  622. }
  623. }
  624. }
  625. }
  626. return true;
  627. }
  628. /**
  629. * Attachment files when a message is sent.
  630. *
  631. * @param $file_attach
  632. * @param $ticketId
  633. * @param $message_id
  634. *
  635. * @return bool
  636. */
  637. public static function saveMessageAttachmentFile(
  638. $file_attach,
  639. $ticketId,
  640. $message_id
  641. ) {
  642. $now = api_get_utc_datetime();
  643. $userId = api_get_user_id();
  644. $ticketId = (int) $ticketId;
  645. $new_file_name = add_ext_on_mime(
  646. stripslashes($file_attach['name']),
  647. $file_attach['type']
  648. );
  649. $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
  650. if (!filter_extension($new_file_name)) {
  651. echo Display::return_message(
  652. get_lang('File upload failed: this file extension or file type is prohibited'),
  653. 'error'
  654. );
  655. } else {
  656. $result = api_upload_file('ticket_attachment', $file_attach, $ticketId);
  657. if ($result) {
  658. $safe_file_name = Database::escape_string($new_file_name);
  659. $safe_new_file_name = Database::escape_string($result['path_to_save']);
  660. $sql = "INSERT INTO $table_support_message_attachments (
  661. filename,
  662. path,
  663. ticket_id,
  664. message_id,
  665. size,
  666. sys_insert_user_id,
  667. sys_insert_datetime,
  668. sys_lastedit_user_id,
  669. sys_lastedit_datetime
  670. ) VALUES (
  671. '$safe_file_name',
  672. '$safe_new_file_name',
  673. '$ticketId',
  674. '$message_id',
  675. '".$file_attach['size']."',
  676. '$userId',
  677. '$now',
  678. '$userId',
  679. '$now'
  680. )";
  681. Database::query($sql);
  682. return true;
  683. }
  684. }
  685. }
  686. /**
  687. * Get tickets by userId.
  688. *
  689. * @param int $from
  690. * @param int $number_of_items
  691. * @param $column
  692. * @param $direction
  693. *
  694. * @return array
  695. */
  696. public static function getTicketsByCurrentUser(
  697. $from,
  698. $number_of_items,
  699. $column,
  700. $direction
  701. ) {
  702. $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
  703. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  704. $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
  705. $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
  706. $direction = !empty($direction) ? $direction : 'DESC';
  707. $userId = api_get_user_id();
  708. $userInfo = api_get_user_info($userId);
  709. if (empty($userInfo)) {
  710. return [];
  711. }
  712. $isAdmin = UserManager::is_admin($userId);
  713. if (!isset($_GET['project_id'])) {
  714. return [];
  715. }
  716. switch ($column) {
  717. case 0:
  718. $column = 'ticket_id';
  719. break;
  720. case 1:
  721. $column = 'status_name';
  722. break;
  723. case 2:
  724. $column = 'start_date';
  725. break;
  726. case 3:
  727. $column = 'sys_lastedit_datetime';
  728. break;
  729. case 4:
  730. $column = 'category_name';
  731. break;
  732. case 5:
  733. $column = 'sys_insert_user_id';
  734. break;
  735. case 6:
  736. $column = 'assigned_last_user';
  737. break;
  738. case 7:
  739. $column = 'total_messages';
  740. break;
  741. case 8:
  742. $column = 'subject';
  743. break;
  744. default:
  745. $column = 'ticket_id';
  746. }
  747. $sql = "SELECT DISTINCT
  748. ticket.*,
  749. ticket.id ticket_id,
  750. status.name AS status_name,
  751. ticket.start_date,
  752. ticket.sys_lastedit_datetime,
  753. cat.name AS category_name,
  754. priority.name AS priority_name,
  755. ticket.total_messages AS total_messages,
  756. ticket.message AS message,
  757. ticket.subject AS subject,
  758. ticket.assigned_last_user
  759. FROM $table_support_tickets ticket
  760. INNER JOIN $table_support_category cat
  761. ON (cat.id = ticket.category_id)
  762. INNER JOIN $table_support_priority priority
  763. ON (ticket.priority_id = priority.id)
  764. INNER JOIN $table_support_status status
  765. ON (ticket.status_id = status.id)
  766. WHERE 1=1
  767. ";
  768. $projectId = (int) $_GET['project_id'];
  769. $userIsAllowInProject = self::userIsAllowInProject($userInfo, $projectId);
  770. // Check if a role was set to the project
  771. if ($userIsAllowInProject == false) {
  772. $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
  773. }
  774. // Search simple
  775. if (isset($_GET['submit_simple']) && $_GET['keyword'] != '') {
  776. $keyword = Database::escape_string(trim($_GET['keyword']));
  777. $sql .= " AND (
  778. ticket.id LIKE '%$keyword%' OR
  779. ticket.code LIKE '%$keyword%' OR
  780. ticket.subject LIKE '%$keyword%' OR
  781. ticket.message LIKE '%$keyword%' OR
  782. ticket.keyword LIKE '%$keyword%' OR
  783. ticket.source LIKE '%$keyword%' OR
  784. cat.name LIKE '%$keyword%' OR
  785. status.name LIKE '%$keyword%' OR
  786. priority.name LIKE '%$keyword%' OR
  787. ticket.personal_email LIKE '%$keyword%'
  788. )";
  789. }
  790. $keywords = [
  791. 'project_id' => 'ticket.project_id',
  792. 'keyword_category' => 'ticket.category_id',
  793. 'keyword_assigned_to' => 'ticket.assigned_last_user',
  794. 'keyword_source' => 'ticket.source ',
  795. 'keyword_status' => 'ticket.status_id',
  796. 'keyword_priority' => 'ticket.priority_id',
  797. ];
  798. foreach ($keywords as $keyword => $label) {
  799. if (isset($_GET[$keyword])) {
  800. $data = Database::escape_string(trim($_GET[$keyword]));
  801. if (!empty($data)) {
  802. $sql .= " AND $label = '$data' ";
  803. }
  804. }
  805. }
  806. // Search advanced
  807. $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
  808. $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
  809. $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
  810. $keyword_range = !empty($keyword_start_date_start) && !empty($keyword_start_date_end);
  811. if ($keyword_range == false && $keyword_start_date_start != '') {
  812. $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start' ";
  813. }
  814. if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
  815. $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
  816. AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
  817. }
  818. if ($keyword_course != '') {
  819. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  820. $sql .= " AND ticket.course_id IN (
  821. SELECT id FROM $course_table
  822. WHERE (
  823. title LIKE '%$keyword_course%' OR
  824. code LIKE '%$keyword_course%' OR
  825. visual_code LIKE '%$keyword_course%'
  826. )
  827. )";
  828. }
  829. $sql .= " ORDER BY $column $direction";
  830. $sql .= " LIMIT $from, $number_of_items";
  831. $result = Database::query($sql);
  832. $tickets = [];
  833. $webPath = api_get_path(WEB_PATH);
  834. while ($row = Database::fetch_assoc($result)) {
  835. $userInfo = api_get_user_info($row['sys_insert_user_id']);
  836. $hrefUser = $webPath.'main/admin/user_information.php?user_id='.$userInfo['user_id'];
  837. $name = "<a href='$hrefUser'> {$userInfo['complete_name_with_username']} </a>";
  838. if ($row['assigned_last_user'] != 0) {
  839. $assignedUserInfo = api_get_user_info($row['assigned_last_user']);
  840. if (!empty($assignedUserInfo)) {
  841. $hrefResp = $webPath.'main/admin/user_information.php?user_id='.$assignedUserInfo['user_id'];
  842. $row['assigned_last_user'] = "<a href='$hrefResp'> {$assignedUserInfo['complete_name_with_username']} </a>";
  843. } else {
  844. $row['assigned_last_user'] = get_lang('Unknown user');
  845. }
  846. } else {
  847. if ($row['status_id'] !== self::STATUS_FORWARDED) {
  848. $row['assigned_last_user'] = '<span style="color:#ff0000;">'.get_lang('To be assigned').'</span>';
  849. } else {
  850. $row['assigned_last_user'] = '<span style="color:#00ff00;">'.get_lang('Message resent').'</span>';
  851. }
  852. }
  853. switch ($row['source']) {
  854. case self::SOURCE_PRESENTIAL:
  855. $img_source = 'icons/32/user.png';
  856. break;
  857. case self::SOURCE_EMAIL:
  858. $img_source = 'icons/32/mail.png';
  859. break;
  860. case self::SOURCE_PHONE:
  861. $img_source = 'icons/32/event.png';
  862. break;
  863. default:
  864. $img_source = 'icons/32/ticket.png';
  865. break;
  866. }
  867. $row['start_date'] = Display::dateToStringAgoAndLongDate($row['start_date']);
  868. $row['sys_lastedit_datetime'] = Display::dateToStringAgoAndLongDate($row['sys_lastedit_datetime']);
  869. $icon = Display::return_icon(
  870. $img_source,
  871. get_lang('Information'),
  872. ['style' => 'margin-right: 10px; float: left;']
  873. );
  874. $icon .= '<a href="ticket_details.php?ticket_id='.$row['id'].'">'.$row['code'].'</a>';
  875. if ($isAdmin) {
  876. $ticket = [
  877. $icon.' '.Security::remove_XSS($row['subject']),
  878. $row['status_name'],
  879. $row['start_date'],
  880. $row['sys_lastedit_datetime'],
  881. $row['category_name'],
  882. $name,
  883. $row['assigned_last_user'],
  884. $row['total_messages'],
  885. ];
  886. } else {
  887. $ticket = [
  888. $icon.' '.Security::remove_XSS($row['subject']),
  889. $row['status_name'],
  890. $row['start_date'],
  891. $row['sys_lastedit_datetime'],
  892. $row['category_name'],
  893. ];
  894. }
  895. if ($isAdmin) {
  896. $ticket['0'] .= '&nbsp;&nbsp;<a href="javascript:void(0)" onclick="load_history_ticket(\'div_'.$row['ticket_id'].'\','.$row['ticket_id'].')">
  897. <img onclick="load_course_list(\'div_'.$row['ticket_id'].'\','.$row['ticket_id'].')" onmouseover="clear_course_list (\'div_'.$row['ticket_id'].'\')" src="'.Display::returnIconPath('history.gif').'" title="'.get_lang('History').'" alt="'.get_lang('History').'"/>
  898. <div class="blackboard_hide" id="div_'.$row['ticket_id'].'">&nbsp;&nbsp;</div>
  899. </a>&nbsp;&nbsp;';
  900. }
  901. $tickets[] = $ticket;
  902. }
  903. return $tickets;
  904. }
  905. /**
  906. * @return int
  907. */
  908. public static function getTotalTicketsCurrentUser()
  909. {
  910. $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
  911. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  912. $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
  913. $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
  914. $userInfo = api_get_user_info();
  915. if (empty($userInfo)) {
  916. return 0;
  917. }
  918. $userId = $userInfo['id'];
  919. if (!isset($_GET['project_id'])) {
  920. return 0;
  921. }
  922. $sql = "SELECT COUNT(ticket.id) AS total
  923. FROM $table_support_tickets ticket
  924. INNER JOIN $table_support_category cat
  925. ON (cat.id = ticket.category_id)
  926. INNER JOIN $table_support_priority priority
  927. ON (ticket.priority_id = priority.id)
  928. INNER JOIN $table_support_status status
  929. ON (ticket.status_id = status.id)
  930. WHERE 1 = 1";
  931. $projectId = (int) $_GET['project_id'];
  932. $allowRoleList = self::getAllowedRolesFromProject($projectId);
  933. // Check if a role was set to the project
  934. if (!empty($allowRoleList) && is_array($allowRoleList)) {
  935. if (!in_array($userInfo['status'], $allowRoleList)) {
  936. $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
  937. }
  938. } else {
  939. if (!api_is_platform_admin()) {
  940. $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
  941. }
  942. }
  943. // Search simple
  944. if (isset($_GET['submit_simple'])) {
  945. if ($_GET['keyword'] != '') {
  946. $keyword = Database::escape_string(trim($_GET['keyword']));
  947. $sql .= " AND (
  948. ticket.code LIKE '%$keyword%' OR
  949. ticket.subject LIKE '%$keyword%' OR
  950. ticket.message LIKE '%$keyword%' OR
  951. ticket.keyword LIKE '%$keyword%' OR
  952. ticket.personal_email LIKE '%$keyword%' OR
  953. ticket.source LIKE '%$keyword%'
  954. )";
  955. }
  956. }
  957. $keywords = [
  958. 'project_id' => 'ticket.project_id',
  959. 'keyword_category' => 'ticket.category_id',
  960. 'keyword_assigned_to' => 'ticket.assigned_last_user',
  961. 'keyword_source' => 'ticket.source',
  962. 'keyword_status' => 'ticket.status_id',
  963. 'keyword_priority' => 'ticket.priority_id',
  964. ];
  965. foreach ($keywords as $keyword => $sqlLabel) {
  966. if (isset($_GET[$keyword])) {
  967. $data = Database::escape_string(trim($_GET[$keyword]));
  968. $sql .= " AND $sqlLabel = '$data' ";
  969. }
  970. }
  971. // Search advanced
  972. $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
  973. $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
  974. $keyword_range = isset($_GET['keyword_dates']) ? Database::escape_string(trim($_GET['keyword_dates'])) : '';
  975. $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
  976. if ($keyword_range == false && $keyword_start_date_start != '') {
  977. $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
  978. }
  979. if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
  980. $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
  981. AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
  982. }
  983. if ($keyword_course != '') {
  984. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  985. $sql .= " AND ticket.course_id IN (
  986. SELECT id
  987. FROM $course_table
  988. WHERE (
  989. title LIKE '%$keyword_course%' OR
  990. code LIKE '%$keyword_course%' OR
  991. visual_code LIKE '%$keyword_course%'
  992. )
  993. ) ";
  994. }
  995. $res = Database::query($sql);
  996. $obj = Database::fetch_object($res);
  997. return (int) $obj->total;
  998. }
  999. /**
  1000. * @param int $id
  1001. *
  1002. * @return false|MessageAttachment
  1003. */
  1004. public static function getTicketMessageAttachment($id)
  1005. {
  1006. $id = (int) $id;
  1007. $em = Database::getManager();
  1008. $item = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->find($id);
  1009. if ($item) {
  1010. return $item;
  1011. }
  1012. return false;
  1013. }
  1014. /**
  1015. * @param int $id
  1016. *
  1017. * @return array
  1018. */
  1019. public static function getTicketMessageAttachmentsByTicketId($id)
  1020. {
  1021. $id = (int) $id;
  1022. $em = Database::getManager();
  1023. $items = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->findBy(['ticket' => $id]);
  1024. if ($items) {
  1025. return $items;
  1026. }
  1027. return false;
  1028. }
  1029. /**
  1030. * @param int $ticketId
  1031. *
  1032. * @return array
  1033. */
  1034. public static function get_ticket_detail_by_id($ticketId)
  1035. {
  1036. $ticketId = (int) $ticketId;
  1037. $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
  1038. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  1039. $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
  1040. $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
  1041. $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
  1042. $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
  1043. $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
  1044. $sql = "SELECT
  1045. ticket.*,
  1046. cat.name,
  1047. status.name as status,
  1048. priority.name priority
  1049. FROM $table_support_tickets ticket
  1050. INNER JOIN $table_support_category cat
  1051. ON (cat.id = ticket.category_id)
  1052. INNER JOIN $table_support_priority priority
  1053. ON (priority.id = ticket.priority_id)
  1054. INNER JOIN $table_support_status status
  1055. ON (status.id = ticket.status_id)
  1056. WHERE
  1057. ticket.id = $ticketId ";
  1058. $result = Database::query($sql);
  1059. $ticket = [];
  1060. if (Database::num_rows($result) > 0) {
  1061. while ($row = Database::fetch_assoc($result)) {
  1062. $row['course'] = null;
  1063. $row['start_date_from_db'] = $row['start_date'];
  1064. $row['start_date'] = api_convert_and_format_date(
  1065. api_get_local_time($row['start_date']),
  1066. DATE_TIME_FORMAT_LONG,
  1067. api_get_timezone()
  1068. );
  1069. $row['end_date_from_db'] = $row['end_date'];
  1070. $row['end_date'] = api_convert_and_format_date(
  1071. api_get_local_time($row['end_date']),
  1072. DATE_TIME_FORMAT_LONG,
  1073. api_get_timezone()
  1074. );
  1075. $row['sys_lastedit_datetime_from_db'] = $row['sys_lastedit_datetime'];
  1076. $row['sys_lastedit_datetime'] = api_convert_and_format_date(
  1077. api_get_local_time($row['sys_lastedit_datetime']),
  1078. DATE_TIME_FORMAT_LONG,
  1079. api_get_timezone()
  1080. );
  1081. $row['course_url'] = null;
  1082. if ($row['course_id'] != 0) {
  1083. $course = api_get_course_info_by_id($row['course_id']);
  1084. $sessionId = 0;
  1085. if ($row['session_id']) {
  1086. $sessionId = $row['session_id'];
  1087. }
  1088. if ($course) {
  1089. $row['course_url'] = '<a href="'.$course['course_public_url'].'?id_session='.$sessionId.'">'.$course['name'].'</a>';
  1090. }
  1091. }
  1092. $userInfo = api_get_user_info($row['sys_insert_user_id']);
  1093. $row['user_url'] = '<a href="'.api_get_path(WEB_PATH).'main/admin/user_information.php?user_id='.$userInfo['user_id'].'">
  1094. '.$userInfo['complete_name'].'</a>';
  1095. $ticket['usuario'] = $userInfo;
  1096. $ticket['ticket'] = $row;
  1097. }
  1098. $sql = "SELECT *, message.id as message_id
  1099. FROM $table_support_messages message
  1100. INNER JOIN $table_main_user user
  1101. ON (message.sys_insert_user_id = user.user_id)
  1102. WHERE
  1103. message.ticket_id = '$ticketId' ";
  1104. $result = Database::query($sql);
  1105. $ticket['messages'] = [];
  1106. $attach_icon = Display::return_icon('attachment.gif', '');
  1107. $webPath = api_get_path(WEB_CODE_PATH);
  1108. while ($row = Database::fetch_assoc($result)) {
  1109. $message = $row;
  1110. $message['admin'] = UserManager::is_admin($message['user_id']);
  1111. $message['user_info'] = api_get_user_info($message['user_id']);
  1112. $sql = "SELECT *
  1113. FROM $table_support_message_attachments
  1114. WHERE
  1115. message_id = ".$row['message_id']." AND
  1116. ticket_id = $ticketId";
  1117. $result_attach = Database::query($sql);
  1118. while ($row2 = Database::fetch_assoc($result_attach)) {
  1119. $archiveURL = $webPath.'ticket/download.php?ticket_id='.$ticketId.'&id='.$row2['id'];
  1120. $row2['attachment_link'] = $attach_icon.
  1121. '&nbsp;<a href="'.$archiveURL.'">'.$row2['filename'].'</a>&nbsp;('.$row2['size'].')';
  1122. $message['attachments'][] = $row2;
  1123. }
  1124. $ticket['messages'][] = $message;
  1125. }
  1126. }
  1127. return $ticket;
  1128. }
  1129. /**
  1130. * @param int $ticketId
  1131. * @param int $userId
  1132. *
  1133. * @return bool
  1134. */
  1135. public static function update_message_status($ticketId, $userId)
  1136. {
  1137. $ticketId = (int) $ticketId;
  1138. $userId = (int) $userId;
  1139. $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
  1140. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  1141. $now = api_get_utc_datetime();
  1142. $sql = "UPDATE $table_support_messages
  1143. SET
  1144. status = 'LEI',
  1145. sys_lastedit_user_id ='".api_get_user_id()."',
  1146. sys_lastedit_datetime ='".$now."'
  1147. WHERE ticket_id ='$ticketId' ";
  1148. if (api_is_platform_admin()) {
  1149. $sql .= " AND sys_insert_user_id = '$userId'";
  1150. } else {
  1151. $sql .= " AND sys_insert_user_id != '$userId'";
  1152. }
  1153. $result = Database::query($sql);
  1154. if (Database::affected_rows($result) > 0) {
  1155. Database::query(
  1156. "UPDATE $table_support_tickets SET
  1157. status_id = '".self::STATUS_PENDING."'
  1158. WHERE id ='$ticketId' AND status_id = '".self::STATUS_NEW."'"
  1159. );
  1160. return true;
  1161. }
  1162. return false;
  1163. }
  1164. /**
  1165. * Send notification to a user through the internal messaging system.
  1166. *
  1167. * @param int $ticketId
  1168. * @param string $title
  1169. * @param string $message
  1170. * @param int $onlyToUserId
  1171. *
  1172. * @return bool
  1173. */
  1174. public static function sendNotification($ticketId, $title, $message, $onlyToUserId = 0)
  1175. {
  1176. $ticketInfo = self::get_ticket_detail_by_id($ticketId);
  1177. if (empty($ticketInfo)) {
  1178. return false;
  1179. }
  1180. $assignedUserInfo = api_get_user_info($ticketInfo['ticket']['assigned_last_user']);
  1181. $requestUserInfo = $ticketInfo['usuario'];
  1182. $ticketCode = $ticketInfo['ticket']['code'];
  1183. $status = $ticketInfo['ticket']['status'];
  1184. $priority = $ticketInfo['ticket']['priority'];
  1185. // Subject
  1186. $titleEmail = "[$ticketCode] $title";
  1187. // Content
  1188. $href = api_get_path(WEB_CODE_PATH).'/ticket/ticket_details.php?ticket_id='.$ticketId;
  1189. $ticketUrl = Display::url($ticketCode, $href);
  1190. $messageEmail = get_lang('TicketNum').": $ticketUrl <br />";
  1191. $messageEmail .= get_lang('Status').": $status <br />";
  1192. $messageEmail .= get_lang('Priority').": $priority <br />";
  1193. $messageEmail .= '<hr /><br />';
  1194. $messageEmail .= $message;
  1195. $currentUserId = api_get_user_id();
  1196. $attachmentList = [];
  1197. $attachments = self::getTicketMessageAttachmentsByTicketId($ticketId);
  1198. if (!empty($attachments)) {
  1199. /** @var MessageAttachment $attachment */
  1200. foreach ($attachments as $attachment) {
  1201. $file = api_get_uploaded_file(
  1202. 'ticket_attachment',
  1203. $ticketId,
  1204. $attachment->getPath()
  1205. );
  1206. if (!empty($file)) {
  1207. $attachmentList[] = [
  1208. 'tmp_name' => api_get_uploaded_file(
  1209. 'ticket_attachment',
  1210. $ticketId,
  1211. $attachment->getPath()
  1212. ),
  1213. 'size' => $attachment->getSize(),
  1214. 'name' => $attachment->getFilename(),
  1215. 'error' => 0,
  1216. ];
  1217. }
  1218. }
  1219. }
  1220. if (!empty($onlyToUserId)) {
  1221. // Send only to specific user
  1222. if ($currentUserId != $onlyToUserId) {
  1223. MessageManager::send_message_simple(
  1224. $onlyToUserId,
  1225. $titleEmail,
  1226. $messageEmail,
  1227. 0,
  1228. false,
  1229. false,
  1230. [],
  1231. false,
  1232. $attachmentList
  1233. );
  1234. }
  1235. } else {
  1236. // Send to assigned user and to author
  1237. if ($requestUserInfo && $currentUserId != $requestUserInfo['id']) {
  1238. MessageManager::send_message_simple(
  1239. $requestUserInfo['id'],
  1240. $titleEmail,
  1241. $messageEmail,
  1242. 0,
  1243. false,
  1244. false,
  1245. [],
  1246. false,
  1247. $attachmentList
  1248. );
  1249. }
  1250. if ($assignedUserInfo &&
  1251. $requestUserInfo['id'] != $assignedUserInfo['id'] &&
  1252. $currentUserId != $assignedUserInfo['id']
  1253. ) {
  1254. MessageManager::send_message_simple(
  1255. $assignedUserInfo['id'],
  1256. $titleEmail,
  1257. $messageEmail,
  1258. 0,
  1259. false,
  1260. false,
  1261. [],
  1262. false,
  1263. $attachmentList
  1264. );
  1265. }
  1266. }
  1267. }
  1268. /**
  1269. * @param array $params
  1270. * @param int $ticketId
  1271. * @param int $userId
  1272. *
  1273. * @return bool
  1274. */
  1275. public static function updateTicket(
  1276. $params,
  1277. $ticketId,
  1278. $userId
  1279. ) {
  1280. $now = api_get_utc_datetime();
  1281. $table = Database::get_main_table(TABLE_TICKET_TICKET);
  1282. $newParams = [
  1283. 'priority_id' => isset($params['priority_id']) ? (int) $params['priority_id'] : '',
  1284. 'status_id' => isset($params['status_id']) ? (int) $params['status_id'] : '',
  1285. 'sys_lastedit_user_id' => (int) $userId,
  1286. 'sys_lastedit_datetime' => $now,
  1287. ];
  1288. Database::update($table, $newParams, ['id = ? ' => $ticketId]);
  1289. return true;
  1290. }
  1291. /**
  1292. * @param int $status_id
  1293. * @param int $ticketId
  1294. * @param int $userId
  1295. *
  1296. * @return bool
  1297. */
  1298. public static function update_ticket_status(
  1299. $status_id,
  1300. $ticketId,
  1301. $userId
  1302. ) {
  1303. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  1304. $ticketId = (int) $ticketId;
  1305. $status_id = (int) $status_id;
  1306. $userId = (int) $userId;
  1307. $now = api_get_utc_datetime();
  1308. $sql = "UPDATE $table_support_tickets
  1309. SET
  1310. status_id = '$status_id',
  1311. sys_lastedit_user_id ='$userId',
  1312. sys_lastedit_datetime ='".$now."'
  1313. WHERE id ='$ticketId'";
  1314. $result = Database::query($sql);
  1315. if (Database::affected_rows($result) > 0) {
  1316. self::sendNotification(
  1317. $ticketId,
  1318. get_lang('Ticket updated'),
  1319. get_lang('Ticket updated')
  1320. );
  1321. return true;
  1322. }
  1323. return false;
  1324. }
  1325. /**
  1326. * @return mixed
  1327. */
  1328. public static function getNumberOfMessages()
  1329. {
  1330. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  1331. $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
  1332. $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
  1333. $table_main_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
  1334. $user_info = api_get_user_info();
  1335. $userId = $user_info['user_id'];
  1336. $sql = "SELECT COUNT(DISTINCT ticket.id) AS unread
  1337. FROM $table_support_tickets ticket,
  1338. $table_support_messages message ,
  1339. $table_main_user user
  1340. WHERE
  1341. ticket.id = message.ticket_id AND
  1342. message.status = 'NOL' AND
  1343. user.user_id = message.sys_insert_user_id ";
  1344. if (!api_is_platform_admin()) {
  1345. $sql .= " AND ticket.request_user = '$userId'
  1346. AND user_id IN (SELECT user_id FROM $table_main_admin) ";
  1347. } else {
  1348. $sql .= " AND user_id NOT IN (SELECT user_id FROM $table_main_admin)
  1349. AND ticket.status_id != '".self::STATUS_FORWARDED."'";
  1350. }
  1351. $sql .= " AND ticket.project_id != '' ";
  1352. $res = Database::query($sql);
  1353. $obj = Database::fetch_object($res);
  1354. return $obj->unread;
  1355. }
  1356. /**
  1357. * @param int $ticketId
  1358. * @param int $userId
  1359. */
  1360. public static function send_alert($ticketId, $userId)
  1361. {
  1362. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  1363. $now = api_get_utc_datetime();
  1364. $ticketId = (int) $ticketId;
  1365. $userId = (int) $userId;
  1366. $sql = "UPDATE $table_support_tickets SET
  1367. priority_id = '".self::PRIORITY_HIGH."',
  1368. sys_lastedit_user_id = $userId,
  1369. sys_lastedit_datetime = '$now'
  1370. WHERE id = $ticketId";
  1371. Database::query($sql);
  1372. }
  1373. /**
  1374. * @param int $ticketId
  1375. * @param int $userId
  1376. */
  1377. public static function close_ticket($ticketId, $userId)
  1378. {
  1379. $ticketId = (int) $ticketId;
  1380. $userId = (int) $userId;
  1381. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  1382. $now = api_get_utc_datetime();
  1383. $sql = "UPDATE $table_support_tickets SET
  1384. status_id = '".self::STATUS_CLOSE."',
  1385. sys_lastedit_user_id ='$userId',
  1386. sys_lastedit_datetime ='".$now."',
  1387. end_date ='$now'
  1388. WHERE id ='$ticketId'";
  1389. Database::query($sql);
  1390. self::sendNotification(
  1391. $ticketId,
  1392. get_lang('Ticket closed'),
  1393. get_lang('Ticket closed')
  1394. );
  1395. }
  1396. /**
  1397. * Close old tickets.
  1398. */
  1399. public static function close_old_tickets()
  1400. {
  1401. $table = Database::get_main_table(TABLE_TICKET_TICKET);
  1402. $now = api_get_utc_datetime();
  1403. $userId = api_get_user_id();
  1404. $sql = "UPDATE $table
  1405. SET
  1406. status_id = '".self::STATUS_CLOSE."',
  1407. sys_lastedit_user_id ='$userId',
  1408. sys_lastedit_datetime ='$now',
  1409. end_date = '$now'
  1410. WHERE
  1411. DATEDIFF('$now', sys_lastedit_datetime) > 7 AND
  1412. status_id != '".self::STATUS_CLOSE."' AND
  1413. status_id != '".self::STATUS_NEW."' AND
  1414. status_id != '".self::STATUS_FORWARDED."'";
  1415. Database::query($sql);
  1416. }
  1417. /**
  1418. * @param int $ticketId
  1419. *
  1420. * @return array
  1421. */
  1422. public static function get_assign_log($ticketId)
  1423. {
  1424. $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
  1425. $ticketId = (int) $ticketId;
  1426. $sql = "SELECT * FROM $table
  1427. WHERE ticket_id = $ticketId
  1428. ORDER BY assigned_date DESC";
  1429. $result = Database::query($sql);
  1430. $history = [];
  1431. $webpath = api_get_path(WEB_PATH);
  1432. while ($row = Database::fetch_assoc($result)) {
  1433. if ($row['user_id'] != 0) {
  1434. $assignuser = api_get_user_info($row['user_id']);
  1435. $row['assignuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['user_id'].'" target="_blank">'.
  1436. $assignuser['username'].'</a>';
  1437. } else {
  1438. $row['assignuser'] = get_lang('Unassign');
  1439. }
  1440. $row['assigned_date'] = Display::dateToStringAgoAndLongDate($row['assigned_date']);
  1441. $insertuser = api_get_user_info($row['sys_insert_user_id']);
  1442. $row['insertuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['sys_insert_user_id'].'" target="_blank">'.
  1443. $insertuser['username'].'</a>';
  1444. $history[] = $row;
  1445. }
  1446. return $history;
  1447. }
  1448. /**
  1449. * @param $from
  1450. * @param $number_of_items
  1451. * @param $column
  1452. * @param $direction
  1453. * @param null $userId
  1454. *
  1455. * @return array
  1456. */
  1457. public static function export_tickets_by_user_id(
  1458. $from,
  1459. $number_of_items,
  1460. $column,
  1461. $direction,
  1462. $userId = null
  1463. ) {
  1464. $from = (int) $from;
  1465. $number_of_items = (int) $number_of_items;
  1466. $table_support_category = Database::get_main_table(
  1467. TABLE_TICKET_CATEGORY
  1468. );
  1469. $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
  1470. $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
  1471. $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
  1472. $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
  1473. $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
  1474. if (is_null($direction)) {
  1475. $direction = 'DESC';
  1476. }
  1477. if (is_null($userId) || $userId == 0) {
  1478. $userId = api_get_user_id();
  1479. }
  1480. $sql = "SELECT
  1481. ticket.code,
  1482. ticket.sys_insert_datetime,
  1483. ticket.sys_lastedit_datetime,
  1484. cat.name as category,
  1485. CONCAT(user.lastname,' ', user.firstname) AS fullname,
  1486. status.name as status,
  1487. ticket.total_messages as messages,
  1488. ticket.assigned_last_user as responsable
  1489. FROM $table_support_tickets ticket,
  1490. $table_support_category cat ,
  1491. $table_support_priority priority,
  1492. $table_support_status status ,
  1493. $table_main_user user
  1494. WHERE
  1495. cat.id = ticket.category_id
  1496. AND ticket.priority_id = priority.id
  1497. AND ticket.status_id = status.id
  1498. AND user.user_id = ticket.request_user ";
  1499. // Search simple
  1500. if (isset($_GET['submit_simple'])) {
  1501. if ($_GET['keyword'] !== '') {
  1502. $keyword = Database::escape_string(trim($_GET['keyword']));
  1503. $sql .= " AND (ticket.code = '$keyword'
  1504. OR user.firstname LIKE '%$keyword%'
  1505. OR user.lastname LIKE '%$keyword%'
  1506. OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword%'
  1507. OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword%'
  1508. OR user.username LIKE '%$keyword%') ";
  1509. }
  1510. }
  1511. // Search advanced
  1512. if (isset($_GET['submit_advanced'])) {
  1513. $keyword_category = Database::escape_string(
  1514. trim($_GET['keyword_category'])
  1515. );
  1516. $keyword_request_user = Database::escape_string(
  1517. trim($_GET['keyword_request_user'])
  1518. );
  1519. $keywordAssignedTo = (int) $_GET['keyword_assigned_to'];
  1520. $keyword_start_date_start = Database::escape_string(
  1521. trim($_GET['keyword_start_date_start'])
  1522. );
  1523. $keyword_start_date_end = Database::escape_string(
  1524. trim($_GET['keyword_start_date_end'])
  1525. );
  1526. $keyword_status = Database::escape_string(
  1527. trim($_GET['keyword_status'])
  1528. );
  1529. $keyword_source = Database::escape_string(
  1530. trim($_GET['keyword_source'])
  1531. );
  1532. $keyword_priority = Database::escape_string(
  1533. trim($_GET['keyword_priority'])
  1534. );
  1535. $keyword_range = Database::escape_string(
  1536. trim($_GET['keyword_dates'])
  1537. );
  1538. $keyword_unread = Database::escape_string(
  1539. trim($_GET['keyword_unread'])
  1540. );
  1541. $keyword_course = Database::escape_string(
  1542. trim($_GET['keyword_course'])
  1543. );
  1544. if ($keyword_category != '') {
  1545. $sql .= " AND ticket.category_id = '$keyword_category' ";
  1546. }
  1547. if ($keyword_request_user != '') {
  1548. $sql .= " AND (ticket.request_user = '$keyword_request_user'
  1549. OR user.firstname LIKE '%$keyword_request_user%'
  1550. OR user.official_code LIKE '%$keyword_request_user%'
  1551. OR user.lastname LIKE '%$keyword_request_user%'
  1552. OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword_request_user%'
  1553. OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword_request_user%'
  1554. OR user.username LIKE '%$keyword_request_user%') ";
  1555. }
  1556. if (!empty($keywordAssignedTo)) {
  1557. $sql .= " AND ticket.assigned_last_user = $keywordAssignedTo ";
  1558. }
  1559. if ($keyword_status != '') {
  1560. $sql .= " AND ticket.status_id = '$keyword_status' ";
  1561. }
  1562. if ($keyword_range == '' && $keyword_start_date_start != '') {
  1563. $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
  1564. }
  1565. if ($keyword_range == '1' && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
  1566. $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
  1567. AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
  1568. }
  1569. if ($keyword_priority != '') {
  1570. $sql .= " AND ticket.priority_id = '$keyword_priority' ";
  1571. }
  1572. if ($keyword_source != '') {
  1573. $sql .= " AND ticket.source = '$keyword_source' ";
  1574. }
  1575. if ($keyword_priority != '') {
  1576. $sql .= " AND ticket.priority_id = '$keyword_priority' ";
  1577. }
  1578. if ($keyword_course != '') {
  1579. $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
  1580. $sql .= " AND ticket.course_id IN ( ";
  1581. $sql .= "SELECT id
  1582. FROM $course_table
  1583. WHERE (title LIKE '%$keyword_course%'
  1584. OR code LIKE '%$keyword_course%'
  1585. OR visual_code LIKE '%$keyword_course%' )) ";
  1586. }
  1587. if ($keyword_unread == 'yes') {
  1588. $sql .= " AND ticket.id IN (
  1589. SELECT ticket.id
  1590. FROM $table_support_tickets ticket,
  1591. $table_support_messages message,
  1592. $table_main_user user
  1593. WHERE ticket.id = message.ticket_id
  1594. AND message.status = 'NOL'
  1595. AND message.sys_insert_user_id = user.user_id
  1596. AND user.status != 1 AND ticket.status_id != '".self::STATUS_FORWARDED."'
  1597. GROUP BY ticket.id)";
  1598. } else {
  1599. if ($keyword_unread == 'no') {
  1600. $sql .= " AND ticket.id NOT IN (
  1601. SELECT ticket.id
  1602. FROM $table_support_tickets ticket,
  1603. $table_support_messages message,
  1604. $table_main_user user
  1605. WHERE ticket.id = message.ticket_id
  1606. AND message.status = 'NOL'
  1607. AND message.sys_insert_user_id = user.user_id
  1608. AND user.status != 1
  1609. AND ticket.status_id != '".self::STATUS_FORWARDED."'
  1610. GROUP BY ticket.id)";
  1611. }
  1612. }
  1613. }
  1614. $sql .= " LIMIT $from,$number_of_items";
  1615. $result = Database::query($sql);
  1616. $tickets[0] = [
  1617. utf8_decode('Ticket#'),
  1618. utf8_decode('Fecha'),
  1619. utf8_decode('Fecha Edicion'),
  1620. utf8_decode('Categoria'),
  1621. utf8_decode('Usuario'),
  1622. utf8_decode('Estado'),
  1623. utf8_decode('Mensajes'),
  1624. utf8_decode('Responsable'),
  1625. utf8_decode('Programa'),
  1626. ];
  1627. while ($row = Database::fetch_assoc($result)) {
  1628. if ($row['responsable'] != 0) {
  1629. $row['responsable'] = api_get_user_info($row['responsable']);
  1630. $row['responsable'] = $row['responsable']['firstname'].' '.$row['responsable']['lastname'];
  1631. }
  1632. $row['sys_insert_datetime'] = api_format_date(
  1633. $row['sys_insert_datetime'],
  1634. '%d/%m/%y - %I:%M:%S %p'
  1635. );
  1636. $row['sys_lastedit_datetime'] = api_format_date(
  1637. $row['sys_lastedit_datetime'],
  1638. '%d/%m/%y - %I:%M:%S %p'
  1639. );
  1640. $row['category'] = utf8_decode($row['category']);
  1641. $row['programa'] = utf8_decode($row['fullname']);
  1642. $row['fullname'] = utf8_decode($row['fullname']);
  1643. $row['responsable'] = utf8_decode($row['responsable']);
  1644. $tickets[] = $row;
  1645. }
  1646. return $tickets;
  1647. }
  1648. /**
  1649. * @param string $url
  1650. * @param int $projectId
  1651. *
  1652. * @return FormValidator
  1653. */
  1654. public static function getCategoryForm($url, $projectId)
  1655. {
  1656. $form = new FormValidator('category', 'post', $url);
  1657. $form->addText('name', get_lang('Name'));
  1658. $form->addHtmlEditor('description', get_lang('Description'));
  1659. $form->addHidden('project_id', $projectId);
  1660. $form->addButtonUpdate(get_lang('Save'));
  1661. return $form;
  1662. }
  1663. /**
  1664. * @return array
  1665. */
  1666. public static function getStatusList()
  1667. {
  1668. $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
  1669. $list = [];
  1670. /** @var Status $row */
  1671. foreach ($items as $row) {
  1672. $list[$row->getId()] = $row->getName();
  1673. }
  1674. return $list;
  1675. }
  1676. /**
  1677. * @param array $criteria
  1678. *
  1679. * @return array
  1680. */
  1681. public static function getTicketsFromCriteria($criteria)
  1682. {
  1683. $items = Database::getManager()->getRepository('ChamiloTicketBundle:Ticket')->findBy($criteria);
  1684. $list = [];
  1685. /** @var Ticket $row */
  1686. foreach ($items as $row) {
  1687. $list[$row->getId()] = $row->getCode();
  1688. }
  1689. return $list;
  1690. }
  1691. /**
  1692. * @param string $code
  1693. *
  1694. * @return int
  1695. */
  1696. public static function getStatusIdFromCode($code)
  1697. {
  1698. $item = Database::getManager()
  1699. ->getRepository('ChamiloTicketBundle:Status')
  1700. ->findOneBy(['code' => $code])
  1701. ;
  1702. if ($item) {
  1703. return $item->getId();
  1704. }
  1705. return 0;
  1706. }
  1707. /**
  1708. * @return array
  1709. */
  1710. public static function getPriorityList()
  1711. {
  1712. $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
  1713. $list = [];
  1714. /** @var Priority $row */
  1715. foreach ($projects as $row) {
  1716. $list[$row->getId()] = $row->getName();
  1717. }
  1718. return $list;
  1719. }
  1720. /**
  1721. * @return array
  1722. */
  1723. public static function getProjects()
  1724. {
  1725. $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
  1726. $list = [];
  1727. /** @var Project $row */
  1728. foreach ($projects as $row) {
  1729. $list[] = [
  1730. 'id' => $row->getId(),
  1731. '0' => $row->getId(),
  1732. '1' => $row->getName(),
  1733. '2' => $row->getDescription(),
  1734. '3' => $row->getId(),
  1735. ];
  1736. }
  1737. return $list;
  1738. }
  1739. /**
  1740. * @return array
  1741. */
  1742. public static function getProjectsSimple()
  1743. {
  1744. $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
  1745. $list = [];
  1746. /** @var Project $row */
  1747. foreach ($projects as $row) {
  1748. $list[] = [
  1749. 'id' => $row->getId(),
  1750. '0' => $row->getId(),
  1751. '1' => Display::url(
  1752. $row->getName(),
  1753. api_get_path(WEB_CODE_PATH).'ticket/tickets.php?project_id='.$row->getId()
  1754. ),
  1755. '2' => $row->getDescription(),
  1756. ];
  1757. }
  1758. return $list;
  1759. }
  1760. /**
  1761. * @return int
  1762. */
  1763. public static function getProjectsCount()
  1764. {
  1765. $count = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->createQueryBuilder('p')
  1766. ->select('COUNT(p.id)')
  1767. ->getQuery()
  1768. ->getSingleScalarResult();
  1769. return $count;
  1770. }
  1771. /**
  1772. * @param array $params
  1773. */
  1774. public static function addProject($params)
  1775. {
  1776. $project = new Project();
  1777. $project->setName($params['name']);
  1778. $project->setDescription($params['description']);
  1779. $project->setInsertUserId(api_get_user_id());
  1780. Database::getManager()->persist($project);
  1781. Database::getManager()->flush();
  1782. }
  1783. /**
  1784. * @param int $id
  1785. *
  1786. * @return Project
  1787. */
  1788. public static function getProject($id)
  1789. {
  1790. return Database::getManager()->getRepository('ChamiloTicketBundle:Project')->find($id);
  1791. }
  1792. /**
  1793. * @param int $id
  1794. * @param array $params
  1795. */
  1796. public static function updateProject($id, $params)
  1797. {
  1798. $project = self::getProject($id);
  1799. $project->setName($params['name']);
  1800. $project->setDescription($params['description']);
  1801. $project->setLastEditDateTime(new DateTime($params['sys_lastedit_datetime']));
  1802. $project->setLastEditUserId($params['sys_lastedit_user_id']);
  1803. Database::getManager()->merge($project);
  1804. Database::getManager()->flush();
  1805. }
  1806. /**
  1807. * @param int $id
  1808. */
  1809. public static function deleteProject($id)
  1810. {
  1811. $project = self::getProject($id);
  1812. if ($project) {
  1813. Database::getManager()->remove($project);
  1814. Database::getManager()->flush();
  1815. }
  1816. }
  1817. /**
  1818. * @param string $url
  1819. *
  1820. * @return FormValidator
  1821. */
  1822. public static function getProjectForm($url)
  1823. {
  1824. $form = new FormValidator('project', 'post', $url);
  1825. $form->addText('name', get_lang('Name'));
  1826. $form->addHtmlEditor('description', get_lang('Description'));
  1827. $form->addButtonUpdate(get_lang('Save'));
  1828. return $form;
  1829. }
  1830. /**
  1831. * @return array
  1832. */
  1833. public static function getStatusAdminList()
  1834. {
  1835. $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
  1836. $list = [];
  1837. /** @var Status $row */
  1838. foreach ($items as $row) {
  1839. $list[] = [
  1840. 'id' => $row->getId(),
  1841. 'code' => $row->getCode(),
  1842. '0' => $row->getId(),
  1843. '1' => $row->getName(),
  1844. '2' => $row->getDescription(),
  1845. '3' => $row->getId(),
  1846. ];
  1847. }
  1848. return $list;
  1849. }
  1850. /**
  1851. * @return array
  1852. */
  1853. public static function getStatusSimple()
  1854. {
  1855. $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
  1856. $list = [];
  1857. /** @var Project $row */
  1858. foreach ($projects as $row) {
  1859. $list[] = [
  1860. 'id' => $row->getId(),
  1861. '0' => $row->getId(),
  1862. '1' => Display::url($row->getName()),
  1863. '2' => $row->getDescription(),
  1864. ];
  1865. }
  1866. return $list;
  1867. }
  1868. /**
  1869. * @return int
  1870. */
  1871. public static function getStatusCount()
  1872. {
  1873. $count = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->createQueryBuilder('p')
  1874. ->select('COUNT(p.id)')
  1875. ->getQuery()
  1876. ->getSingleScalarResult();
  1877. return $count;
  1878. }
  1879. /**
  1880. * @param array $params
  1881. */
  1882. public static function addStatus($params)
  1883. {
  1884. $item = new Status();
  1885. $item->setCode(URLify::filter($params['name']));
  1886. $item->setName($params['name']);
  1887. $item->setDescription($params['description']);
  1888. Database::getManager()->persist($item);
  1889. Database::getManager()->flush();
  1890. }
  1891. /**
  1892. * @param $id
  1893. *
  1894. * @return Project
  1895. */
  1896. public static function getStatus($id)
  1897. {
  1898. return Database::getManager()->getRepository('ChamiloTicketBundle:Status')->find($id);
  1899. }
  1900. /**
  1901. * @param int $id
  1902. * @param array $params
  1903. */
  1904. public static function updateStatus($id, $params)
  1905. {
  1906. $item = self::getStatus($id);
  1907. $item->setName($params['name']);
  1908. $item->setDescription($params['description']);
  1909. Database::getManager()->merge($item);
  1910. Database::getManager()->flush();
  1911. }
  1912. /**
  1913. * @param int $id
  1914. */
  1915. public static function deleteStatus($id)
  1916. {
  1917. $item = self::getStatus($id);
  1918. if ($item) {
  1919. Database::getManager()->remove($item);
  1920. Database::getManager()->flush();
  1921. }
  1922. }
  1923. /**
  1924. * @param string $url
  1925. *
  1926. * @return FormValidator
  1927. */
  1928. public static function getStatusForm($url)
  1929. {
  1930. $form = new FormValidator('status', 'post', $url);
  1931. $form->addText('name', get_lang('Name'));
  1932. $form->addHtmlEditor('description', get_lang('Description'));
  1933. $form->addButtonUpdate(get_lang('Save'));
  1934. return $form;
  1935. }
  1936. /**
  1937. * @return array
  1938. */
  1939. public static function getPriorityAdminList()
  1940. {
  1941. $items = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
  1942. $list = [];
  1943. /** @var Status $row */
  1944. foreach ($items as $row) {
  1945. $list[] = [
  1946. 'id' => $row->getId(),
  1947. 'code' => $row->getCode(),
  1948. '0' => $row->getId(),
  1949. '1' => $row->getName(),
  1950. '2' => $row->getDescription(),
  1951. '3' => $row->getId(),
  1952. ];
  1953. }
  1954. return $list;
  1955. }
  1956. /**
  1957. * @return array
  1958. */
  1959. public static function getPrioritySimple()
  1960. {
  1961. $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
  1962. $list = [];
  1963. /** @var Priority $row */
  1964. foreach ($projects as $row) {
  1965. $list[] = [
  1966. 'id' => $row->getId(),
  1967. '0' => $row->getId(),
  1968. '1' => Display::url($row->getName()),
  1969. '2' => $row->getDescription(),
  1970. ];
  1971. }
  1972. return $list;
  1973. }
  1974. /**
  1975. * @return int
  1976. */
  1977. public static function getPriorityCount()
  1978. {
  1979. $count = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->createQueryBuilder('p')
  1980. ->select('COUNT(p.id)')
  1981. ->getQuery()
  1982. ->getSingleScalarResult();
  1983. return $count;
  1984. }
  1985. /**
  1986. * @param array $params
  1987. */
  1988. public static function addPriority($params)
  1989. {
  1990. $item = new Priority();
  1991. $item
  1992. ->setCode(URLify::filter($params['name']))
  1993. ->setName($params['name'])
  1994. ->setDescription($params['description'])
  1995. ->setColor('')
  1996. ->setInsertUserId(api_get_user_id())
  1997. ->setUrgency('')
  1998. ;
  1999. Database::getManager()->persist($item);
  2000. Database::getManager()->flush();
  2001. }
  2002. /**
  2003. * @param $id
  2004. *
  2005. * @return Priority
  2006. */
  2007. public static function getPriority($id)
  2008. {
  2009. return Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->find($id);
  2010. }
  2011. /**
  2012. * @param int $id
  2013. * @param array $params
  2014. */
  2015. public static function updatePriority($id, $params)
  2016. {
  2017. $item = self::getPriority($id);
  2018. $item->setName($params['name']);
  2019. $item->setDescription($params['description']);
  2020. Database::getManager()->merge($item);
  2021. Database::getManager()->flush();
  2022. }
  2023. /**
  2024. * @param int $id
  2025. */
  2026. public static function deletePriority($id)
  2027. {
  2028. $item = self::getPriority($id);
  2029. if ($item) {
  2030. Database::getManager()->remove($item);
  2031. Database::getManager()->flush();
  2032. }
  2033. }
  2034. /**
  2035. * @param string $url
  2036. *
  2037. * @return FormValidator
  2038. */
  2039. public static function getPriorityForm($url)
  2040. {
  2041. $form = new FormValidator('priority', 'post', $url);
  2042. $form->addText('name', get_lang('Name'));
  2043. $form->addHtmlEditor('description', get_lang('Description'));
  2044. $form->addButtonUpdate(get_lang('Save'));
  2045. return $form;
  2046. }
  2047. /**
  2048. * Returns a list of menu elements for the tickets system's configuration.
  2049. *
  2050. * @param string $exclude The element to exclude from the list
  2051. *
  2052. * @return array
  2053. */
  2054. public static function getSettingsMenuItems($exclude = null)
  2055. {
  2056. $project = [
  2057. 'icon' => 'project.png',
  2058. 'url' => 'projects.php',
  2059. 'content' => get_lang('Projects'),
  2060. ];
  2061. $status = [
  2062. 'icon' => 'check-circle.png',
  2063. 'url' => 'status.php',
  2064. 'content' => get_lang('Status'),
  2065. ];
  2066. $priority = [
  2067. 'icon' => 'tickets_urgent.png',
  2068. 'url' => 'priorities.php',
  2069. 'content' => get_lang('Priority'),
  2070. ];
  2071. switch ($exclude) {
  2072. case 'project':
  2073. $items = [$status, $priority];
  2074. break;
  2075. case 'status':
  2076. $items = [$project, $priority];
  2077. break;
  2078. case 'priority':
  2079. $items = [$project, $status];
  2080. break;
  2081. default:
  2082. $items = [$project, $status, $priority];
  2083. break;
  2084. }
  2085. return $items;
  2086. }
  2087. /**
  2088. * Returns a list of strings representing the default statuses.
  2089. *
  2090. * @return array
  2091. */
  2092. public static function getDefaultStatusList()
  2093. {
  2094. return [
  2095. self::STATUS_NEW,
  2096. self::STATUS_PENDING,
  2097. self::STATUS_UNCONFIRMED,
  2098. self::STATUS_CLOSE,
  2099. self::STATUS_FORWARDED,
  2100. ];
  2101. }
  2102. /**
  2103. * @return array
  2104. */
  2105. public static function getDefaultPriorityList()
  2106. {
  2107. return [
  2108. self::PRIORITY_NORMAL,
  2109. self::PRIORITY_HIGH,
  2110. self::PRIORITY_LOW,
  2111. self::STATUS_CLOSE,
  2112. self::STATUS_FORWARDED,
  2113. ];
  2114. }
  2115. /**
  2116. * Deletes the user from all the ticket system.
  2117. *
  2118. * @param int $userId
  2119. */
  2120. public static function deleteUserFromTicketSystem($userId)
  2121. {
  2122. $userId = (int) $userId;
  2123. $schema = Database::getManager()->getConnection()->getSchemaManager();
  2124. if ($schema->tablesExist('ticket_assigned_log')) {
  2125. $sql = "UPDATE ticket_assigned_log SET user_id = NULL WHERE user_id = $userId";
  2126. Database::query($sql);
  2127. $sql = "UPDATE ticket_assigned_log SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
  2128. Database::query($sql);
  2129. }
  2130. if ($schema->tablesExist('ticket_ticket')) {
  2131. $sql = "UPDATE ticket_ticket SET assigned_last_user = NULL WHERE assigned_last_user = $userId";
  2132. Database::query($sql);
  2133. $sql = "UPDATE ticket_ticket SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
  2134. Database::query($sql);
  2135. $sql = "UPDATE ticket_ticket SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
  2136. Database::query($sql);
  2137. }
  2138. if ($schema->tablesExist('ticket_category')) {
  2139. $sql = "UPDATE ticket_category SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
  2140. Database::query($sql);
  2141. $sql = "UPDATE ticket_category SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
  2142. Database::query($sql);
  2143. }
  2144. if ($schema->tablesExist('ticket_category_rel_user')) {
  2145. $sql = "DELETE FROM ticket_category_rel_user WHERE user_id = $userId";
  2146. Database::query($sql);
  2147. }
  2148. if ($schema->tablesExist('ticket_message')) {
  2149. $sql = "UPDATE ticket_message SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
  2150. Database::query($sql);
  2151. $sql = "UPDATE ticket_message SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
  2152. Database::query($sql);
  2153. }
  2154. if ($schema->tablesExist('ticket_message_attachments')) {
  2155. $sql = "UPDATE ticket_message_attachments SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
  2156. Database::query($sql);
  2157. $sql = "UPDATE ticket_message_attachments SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
  2158. Database::query($sql);
  2159. }
  2160. if ($schema->tablesExist('ticket_priority')) {
  2161. $sql = "UPDATE ticket_priority SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
  2162. Database::query($sql);
  2163. $sql = "UPDATE ticket_priority SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
  2164. Database::query($sql);
  2165. }
  2166. if ($schema->tablesExist('ticket_project')) {
  2167. $sql = "UPDATE ticket_project SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
  2168. Database::query($sql);
  2169. $sql = "UPDATE ticket_project SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
  2170. Database::query($sql);
  2171. }
  2172. }
  2173. /**
  2174. * @param array $userInfo
  2175. * @param int $projectId
  2176. *
  2177. * @return bool
  2178. */
  2179. public static function userIsAllowInProject($userInfo, $projectId)
  2180. {
  2181. if (api_is_platform_admin()) {
  2182. return true;
  2183. }
  2184. $allowRoleList = self::getAllowedRolesFromProject($projectId);
  2185. // Check if a role was set to the project
  2186. // Project 1 is considered the default and is accessible to all users
  2187. if (!empty($allowRoleList) && is_array($allowRoleList)) {
  2188. if (in_array($userInfo['status'], $allowRoleList)) {
  2189. return true;
  2190. }
  2191. }
  2192. return false;
  2193. }
  2194. /**
  2195. * @param int $projectId
  2196. *
  2197. * @todo load from database instead of configuration.php setting
  2198. *
  2199. * @return array
  2200. */
  2201. public static function getAllowedRolesFromProject($projectId)
  2202. {
  2203. $options = api_get_configuration_value('ticket_project_user_roles');
  2204. if ($options) {
  2205. if (isset($options['permissions'][$projectId])) {
  2206. return $options['permissions'][$projectId];
  2207. }
  2208. }
  2209. return [];
  2210. }
  2211. }