TicketManager.php 82 KB

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