Passed
Pull Request — 1.11.x (#6501)
by
unknown
10:08
created

TicketManager::add()   F

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 290
Code Lines 173

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 173
c 0
b 0
f 0
dl 0
loc 290
rs 0
cc 36
nc 231391
nop 15

How to fix   Long Method    Complexity    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\TicketBundle\Entity\MessageAttachment;
5
use Chamilo\TicketBundle\Entity\Priority;
6
use Chamilo\TicketBundle\Entity\Project;
7
use Chamilo\TicketBundle\Entity\Status;
8
use Chamilo\TicketBundle\Entity\Ticket;
9
10
/**
11
 * Class TicketManager.
12
 *
13
 * @package chamilo.plugin.ticket
14
 */
15
class TicketManager
16
{
17
    public const PRIORITY_NORMAL = 'NRM';
18
    public const PRIORITY_HIGH = 'HGH';
19
    public const PRIORITY_LOW = 'LOW';
20
21
    public const SOURCE_EMAIL = 'MAI';
22
    public const SOURCE_PHONE = 'TEL';
23
    public const SOURCE_PLATFORM = 'PLA';
24
    public const SOURCE_PRESENTIAL = 'PRE';
25
26
    public const STATUS_NEW = 'NAT';
27
    public const STATUS_PENDING = 'PND';
28
    public const STATUS_UNCONFIRMED = 'XCF';
29
    public const STATUS_CLOSE = 'CLS';
30
    public const STATUS_FORWARDED = 'REE';
31
32
    /**
33
     * Constructor.
34
     */
35
    public function __construct()
36
    {
37
    }
38
39
    /**
40
     * Get categories of tickets.
41
     *
42
     * @param int    $projectId
43
     * @param string $order
44
     *
45
     * @return array
46
     */
47
    public static function get_all_tickets_categories($projectId, $order = '')
48
    {
49
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
50
        $table_support_project = Database::get_main_table(TABLE_TICKET_PROJECT);
51
52
        $order = empty($order) ? 'category.total_tickets DESC' : $order;
53
        $order = Database::escape_string($order);
54
        $projectId = (int) $projectId;
55
56
        $sql = "SELECT
57
                    category.*,
58
                    category.id category_id,
59
                    project.other_area,
60
                    project.email
61
                FROM
62
                $table_support_category category
63
                INNER JOIN $table_support_project project
64
                ON project.id = category.project_id
65
                WHERE project.id  = $projectId
66
                ORDER BY $order";
67
        $result = Database::query($sql);
68
        $types = [];
69
        while ($row = Database::fetch_assoc($result)) {
70
            $types[] = $row;
71
        }
72
73
        return $types;
74
    }
75
76
    /**
77
     * @param $from
78
     * @param $numberItems
79
     * @param $column
80
     * @param $direction
81
     *
82
     * @return array
83
     */
84
    public static function getCategories($from, $numberItems, $column, $direction)
85
    {
86
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
87
        $sql = "SELECT id, name, description, total_tickets
88
                FROM $table";
89
90
        if (!in_array($direction, ['ASC', 'DESC'])) {
91
            $direction = 'ASC';
92
        }
93
        $column = (int) $column;
94
        $from = (int) $from;
95
        $numberItems = (int) $numberItems;
96
97
        //$sql .= " ORDER BY col$column $direction ";
98
        $sql .= " LIMIT $from,$numberItems";
99
100
        $result = Database::query($sql);
101
        $types = [];
102
        while ($row = Database::fetch_array($result)) {
103
            $types[] = $row;
104
        }
105
106
        return $types;
107
    }
108
109
    /**
110
     * @param int $id
111
     *
112
     * @return array|mixed
113
     */
114
    public static function getCategory($id)
115
    {
116
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
117
        $id = (int) $id;
118
        $sql = "SELECT id, name, description, total_tickets
119
                FROM $table WHERE id = $id";
120
121
        $result = Database::query($sql);
122
        $category = Database::fetch_array($result);
123
124
        return $category;
125
    }
126
127
    /**
128
     * @return int
129
     */
130
    public static function getCategoriesCount()
131
    {
132
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
133
134
        $sql = "SELECT count(id) count
135
                FROM $table ";
136
137
        $result = Database::query($sql);
138
        $category = Database::fetch_array($result);
139
140
        return $category['count'];
141
    }
142
143
    /**
144
     * @param int   $id
145
     * @param array $params
146
     */
147
    public static function updateCategory($id, $params)
148
    {
149
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
150
        $id = (int) $id;
151
        Database::update($table, $params, ['id = ?' => $id]);
152
    }
153
154
    /**
155
     * @param array $params
156
     */
157
    public static function addCategory($params)
158
    {
159
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
160
        Database::insert($table, $params);
161
    }
162
163
    /**
164
     * @param int $id
165
     *
166
     * @return bool
167
     */
168
    public static function deleteCategory($id)
169
    {
170
        $id = (int) $id;
171
        if (empty($id)) {
172
            return false;
173
        }
174
175
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
176
        $sql = "UPDATE $table SET category_id = NULL WHERE category_id = $id";
177
        Database::query($sql);
178
179
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
180
        $sql = "DELETE FROM $table WHERE id = $id";
181
        Database::query($sql);
182
183
        return true;
184
    }
185
186
    /**
187
     * @param int   $categoryId
188
     * @param array $users
189
     *
190
     * @return bool
191
     */
192
    public static function addUsersToCategory($categoryId, $users)
193
    {
194
        if (empty($users) || empty($categoryId)) {
195
            return false;
196
        }
197
198
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
199
        foreach ($users as $userId) {
200
            if (self::userIsAssignedToCategory($userId, $categoryId) === false) {
201
                $params = [
202
                    'category_id' => $categoryId,
203
                    'user_id' => $userId,
204
                ];
205
                Database::insert($table, $params);
206
            }
207
        }
208
209
        return true;
210
    }
211
212
    /**
213
     * @param int $userId
214
     * @param int $categoryId
215
     *
216
     * @return bool
217
     */
218
    public static function userIsAssignedToCategory($userId, $categoryId)
219
    {
220
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
221
        $userId = (int) $userId;
222
        $categoryId = (int) $categoryId;
223
        $sql = "SELECT * FROM $table
224
                WHERE category_id = $categoryId AND user_id = $userId";
225
        $result = Database::query($sql);
226
227
        return Database::num_rows($result) > 0;
228
    }
229
230
    /**
231
     * @param int $categoryId
232
     *
233
     * @return array
234
     */
235
    public static function getUsersInCategory($categoryId)
236
    {
237
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
238
        $categoryId = (int) $categoryId;
239
        $sql = "SELECT * FROM $table WHERE category_id = $categoryId";
240
        $result = Database::query($sql);
241
242
        return Database::store_result($result);
243
    }
244
245
    /**
246
     * Returns the list of category IDs assigned to a user.
247
     *
248
     * @param int $userId
249
     * @param int $projectId
250
     *
251
     * @return int[]
252
     */
253
    public static function getCategoryIdsByUser($userId, $projectId = 0)
254
    {
255
        $tableRel = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
256
        $tableCat = Database::get_main_table(TABLE_TICKET_CATEGORY);
257
        $userId = (int) $userId;
258
        $projectId = (int) $projectId;
259
260
        $sql = "SELECT rel.category_id
261
                FROM $tableRel rel
262
                INNER JOIN $tableCat cat ON (rel.category_id = cat.id)
263
                WHERE rel.user_id = $userId";
264
265
        if (!empty($projectId)) {
266
            $sql .= " AND cat.project_id = $projectId";
267
        }
268
269
        $result = Database::query($sql);
270
        $categories = [];
271
        while ($row = Database::fetch_array($result)) {
272
            $categories[] = (int) $row['category_id'];
273
        }
274
275
        return $categories;
276
    }
277
278
    /**
279
     * @param int $categoryId
280
     */
281
    public static function deleteAllUserInCategory($categoryId)
282
    {
283
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
284
        $categoryId = (int) $categoryId;
285
        $sql = "DELETE FROM $table WHERE category_id = $categoryId";
286
        Database::query($sql);
287
    }
288
289
    /**
290
     * Get all possible tickets statuses.
291
     *
292
     * @return array
293
     */
294
    public static function get_all_tickets_status()
295
    {
296
        $table = Database::get_main_table(TABLE_TICKET_STATUS);
297
        $sql = "SELECT * FROM $table";
298
        $result = Database::query($sql);
299
        $types = [];
300
        while ($row = Database::fetch_assoc($result)) {
301
            $types[] = $row;
302
        }
303
304
        return $types;
305
    }
306
307
    /**
308
     * Inserts a new ticket in the corresponding tables.
309
     *
310
     * @param int    $category_id
311
     * @param int    $course_id
312
     * @param int    $sessionId
313
     * @param int    $project_id
314
     * @param string $other_area
315
     * @param string $subject
316
     * @param string $content
317
     * @param string $personalEmail
318
     * @param array  $fileAttachments
319
     * @param string $source
320
     * @param string $priority
321
     * @param string $status
322
     * @param int    $assignedUserId
323
     * @param int    $exerciseId
324
     * @param int    $lpId
325
     *
326
     * @return bool
327
     */
328
    public static function add(
329
        $category_id,
330
        $course_id,
331
        $sessionId,
332
        $project_id,
333
        $other_area,
334
        $subject,
335
        $content,
336
        $personalEmail = '',
337
        $fileAttachments = [],
338
        $source = '',
339
        $priority = '',
340
        $status = '',
341
        $assignedUserId = 0,
342
        $exerciseId = null,
343
        $lpId = null
344
    ) {
345
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
346
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
347
348
        if (empty($category_id)) {
349
            return false;
350
        }
351
352
        $currentUserId = api_get_user_id();
353
        $currentUserInfo = api_get_user_info();
354
        $now = api_get_utc_datetime();
355
        $course_id = (int) $course_id;
356
        $category_id = (int) $category_id;
357
        $project_id = (int) $project_id;
358
        $priority = empty($priority) ? self::PRIORITY_NORMAL : (int) $priority;
359
360
        if ($status === '') {
361
            $status = self::STATUS_NEW;
362
            if ($other_area > 0) {
363
                $status = self::STATUS_FORWARDED;
364
            }
365
        }
366
367
        if (!empty($category_id)) {
368
            if (empty($assignedUserId)) {
369
                $usersInCategory = self::getUsersInCategory($category_id);
370
                if (!empty($usersInCategory) && count($usersInCategory) > 0) {
371
                    $userCategoryInfo = $usersInCategory[0];
372
                    if (isset($userCategoryInfo['user_id'])) {
373
                        $assignedUserId = $userCategoryInfo['user_id'];
374
                    }
375
                }
376
            }
377
        }
378
379
        $assignedUserInfo = [];
380
        if (!empty($assignedUserId)) {
381
            $assignedUserInfo = api_get_user_info($assignedUserId);
382
            if (empty($assignedUserInfo)) {
383
                return false;
384
            }
385
        }
386
387
        // insert_ticket
388
        $params = [
389
            'project_id' => $project_id,
390
            'category_id' => $category_id,
391
            'priority_id' => $priority,
392
            'personal_email' => $personalEmail,
393
            'status_id' => $status,
394
            'start_date' => $now,
395
            'sys_insert_user_id' => $currentUserId,
396
            'sys_insert_datetime' => $now,
397
            'sys_lastedit_user_id' => $currentUserId,
398
            'sys_lastedit_datetime' => $now,
399
            'source' => $source,
400
            'assigned_last_user' => $assignedUserId,
401
            'subject' => $subject,
402
            'message' => $content,
403
        ];
404
405
        if (!empty($exerciseId)) {
406
            $params['exercise_id'] = $exerciseId;
407
        }
408
409
        if (!empty($lpId)) {
410
            $params['lp_id'] = $lpId;
411
        }
412
413
        if (!empty($course_id)) {
414
            $params['course_id'] = $course_id;
415
        }
416
417
        if (!empty($sessionId)) {
418
            $params['session_id'] = $sessionId;
419
        }
420
421
        $ticketId = Database::insert($table_support_tickets, $params);
422
423
        if ($ticketId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ticketId of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
424
            $ticket_code = 'A'.str_pad($ticketId, 11, '0', STR_PAD_LEFT);
425
            $titleCreated = sprintf(
426
                get_lang('TicketXCreated'),
427
                $ticket_code
428
            );
429
430
            Display::addFlash(Display::return_message(
431
                $titleCreated,
432
                'normal',
433
                false
434
            ));
435
436
            if ($assignedUserId != 0) {
437
                self::assignTicketToUser(
438
                    $ticketId,
439
                    $assignedUserId
440
                );
441
442
                Display::addFlash(Display::return_message(
443
                    sprintf(
444
                        get_lang('TicketXAssignedToUserX'),
445
                        $ticket_code,
446
                        $assignedUserInfo['complete_name']
447
                    ),
448
                    'normal',
449
                    false
450
                ));
451
            }
452
453
            if (!empty($fileAttachments)) {
454
                $attachmentCount = 0;
455
                foreach ($fileAttachments as $attach) {
456
                    if (!empty($attach['tmp_name'])) {
457
                        $attachmentCount++;
458
                    }
459
                }
460
                if ($attachmentCount > 0) {
461
                    self::insertMessage(
462
                        $ticketId,
463
                        '',
464
                        '',
465
                        $fileAttachments,
466
                        $currentUserId
467
                    );
468
                }
469
            }
470
471
            // Update code
472
            $sql = "UPDATE $table_support_tickets
473
                    SET code = '$ticket_code'
474
                    WHERE id = '$ticketId'";
475
            Database::query($sql);
476
477
            // Update total
478
            $sql = "UPDATE $table_support_category
479
                    SET total_tickets = total_tickets + 1
480
                    WHERE id = $category_id";
481
            Database::query($sql);
482
483
            $helpDeskMessage =
484
                '<table>
485
                        <tr>
486
                            <td width="100px"><b>'.get_lang('User').'</b></td>
487
                            <td width="400px">'.$currentUserInfo['complete_name'].'</td>
488
                        </tr>
489
                        <tr>
490
                            <td width="100px"><b>'.get_lang('Username').'</b></td>
491
                            <td width="400px">'.$currentUserInfo['username'].'</td>
492
                        </tr>
493
                        <tr>
494
                            <td width="100px"><b>'.get_lang('Email').'</b></td>
495
                            <td width="400px">'.$currentUserInfo['email'].'</td>
496
                        </tr>
497
                        <tr>
498
                            <td width="100px"><b>'.get_lang('Phone').'</b></td>
499
                            <td width="400px">'.$currentUserInfo['phone'].'</td>
500
                        </tr>
501
                        <tr>
502
                            <td width="100px"><b>'.get_lang('Date').'</b></td>
503
                            <td width="400px">'.api_convert_and_format_date($now, DATE_TIME_FORMAT_LONG).'</td>
504
                        </tr>
505
                        <tr>
506
                            <td width="100px"><b>'.get_lang('Title').'</b></td>
507
                            <td width="400px">'.Security::remove_XSS($subject).'</td>
508
                        </tr>
509
                        <tr>
510
                            <td width="100px"><b>'.get_lang('Description').'</b></td>
511
                            <td width="400px">'.Security::remove_XSS($content).'</td>
512
                        </tr>
513
                    </table>';
514
515
            if ($assignedUserId != 0) {
516
                $href = api_get_path(WEB_CODE_PATH).'/ticket/ticket_details.php?ticket_id='.$ticketId;
517
                $helpDeskMessage .= sprintf(
518
                    get_lang('TicketAssignedToXCheckZAtLinkY'),
519
                    $assignedUserInfo['complete_name'],
520
                    $href,
521
                    $ticketId
522
                );
523
            }
524
525
            if (empty($category_id)) {
526
                if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
527
                    $warningSubject = sprintf(
528
                        get_lang('TicketXCreatedWithNoCategory'),
529
                        $ticket_code
530
                    );
531
                    Display::addFlash(Display::return_message($warningSubject));
532
533
                    $admins = UserManager::get_all_administrators();
534
                    foreach ($admins as $userId => $data) {
535
                        if ($data['active']) {
536
                            MessageManager::send_message_simple(
537
                                $userId,
538
                                $warningSubject,
539
                                $helpDeskMessage
540
                            );
541
                        }
542
                    }
543
                }
544
            } else {
545
                $categoryInfo = self::getCategory($category_id);
546
                $usersInCategory = self::getUsersInCategory($category_id);
547
548
                $message = '<h2>'.get_lang('TicketInformation').'</h2><br />'.$helpDeskMessage;
549
550
                if (api_get_setting('ticket_warn_admin_no_user_in_category') === 'true') {
551
                    if (empty($usersInCategory)) {
552
                        $subject = sprintf(
553
                            get_lang('WarningCategoryXDoesntHaveUsers'),
554
                            $categoryInfo['name']
555
                        );
556
557
                        if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
558
                            Display::addFlash(Display::return_message(
559
                                sprintf(
560
                                    get_lang('CategoryWithNoUserNotificationSentToAdmins'),
561
                                    $categoryInfo['name']
562
                                ),
563
                                null,
564
                                false
565
                            ));
566
567
                            $admins = UserManager::get_all_administrators();
568
                            foreach ($admins as $userId => $data) {
569
                                if ($data['active']) {
570
                                    self::sendNotification(
571
                                        $ticketId,
572
                                        $subject,
573
                                        $message,
574
                                        $userId
575
                                    );
576
                                }
577
                            }
578
                        } else {
579
                            Display::addFlash(Display::return_message($subject));
580
                        }
581
                    }
582
                }
583
584
                // Send notification to all users
585
                if (!empty($usersInCategory)) {
586
                    foreach ($usersInCategory as $data) {
587
                        if ($data['user_id']) {
588
                            self::sendNotification(
589
                                $ticketId,
590
                                $subject,
591
                                $message,
592
                                $data['user_id']
593
                            );
594
                        }
595
                    }
596
                }
597
            }
598
599
            if (!empty($personalEmail)) {
600
                api_mail_html(
601
                    get_lang('VirtualSupport'),
602
                    $personalEmail,
603
                    get_lang('IncidentResentToVirtualSupport'),
604
                    $helpDeskMessage
605
                );
606
            }
607
608
            self::sendNotification(
609
                $ticketId,
610
                $titleCreated,
611
                $helpDeskMessage
612
            );
613
614
            return true;
615
        }
616
617
        return false;
618
    }
619
620
    /**
621
     * Assign ticket to admin.
622
     *
623
     * @param int $ticketId
624
     * @param int $userId
625
     *
626
     * @return bool
627
     */
628
    public static function assignTicketToUser(
629
        $ticketId,
630
        $userId
631
    ) {
632
        $ticketId = (int) $ticketId;
633
        $userId = (int) $userId;
634
635
        if (empty($ticketId)) {
636
            return false;
637
        }
638
639
        $ticket = self::get_ticket_detail_by_id($ticketId);
640
641
        if ($ticket) {
642
            $table = Database::get_main_table(TABLE_TICKET_TICKET);
643
            $sql = "UPDATE $table
644
                    SET assigned_last_user = $userId
645
                    WHERE id = $ticketId";
646
            Database::query($sql);
647
648
            $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
649
            $params = [
650
                'ticket_id' => $ticketId,
651
                'user_id' => $userId,
652
                'sys_insert_user_id' => api_get_user_id(),
653
                'assigned_date' => api_get_utc_datetime(),
654
            ];
655
            Database::insert($table, $params);
656
657
            return true;
658
        } else {
659
            return false;
660
        }
661
    }
662
663
    /**
664
     * Insert message between Users and Admins.
665
     *
666
     * @param int    $ticketId
667
     * @param string $subject
668
     * @param string $content
669
     * @param array  $fileAttachments
670
     * @param int    $userId
671
     * @param string $status
672
     * @param bool   $sendConfirmation
673
     *
674
     * @return bool
675
     */
676
    public static function insertMessage(
677
        $ticketId,
678
        $subject,
679
        $content,
680
        $fileAttachments,
681
        $userId,
682
        $status = 'NOL',
683
        $sendConfirmation = false
684
    ) {
685
        $ticketId = (int) $ticketId;
686
        $userId = (int) $userId;
687
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
688
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
689
        if ($sendConfirmation) {
690
            $form =
691
                '<form action="ticket_details.php?ticket_id='.$ticketId.'" id="confirmticket" method="POST" >
692
                     <p>'.get_lang('TicketWasThisAnswerSatisfying').'</p>
693
                     <button class="btn btn-primary responseyes" name="response" id="responseyes" value="1">'.
694
                get_lang('Yes').'</button>
695
                     <button class="btn btn-danger responseno" name="response" id="responseno" value="0">'.
696
                get_lang('No').'</button>
697
                 </form>';
698
            $content .= $form;
699
        }
700
701
        $now = api_get_utc_datetime();
702
703
        $params = [
704
            'ticket_id' => $ticketId,
705
            'subject' => $subject,
706
            'message' => $content,
707
            'ip_address' => api_get_real_ip(),
708
            'sys_insert_user_id' => $userId,
709
            'sys_insert_datetime' => $now,
710
            'sys_lastedit_user_id' => $userId,
711
            'sys_lastedit_datetime' => $now,
712
            'status' => $status,
713
        ];
714
        $messageId = Database::insert($table_support_messages, $params);
715
        if ($messageId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $messageId of type false|integer is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
716
            // update_total_message
717
            $sql = "UPDATE $table_support_tickets
718
                    SET
719
                        sys_lastedit_user_id = $userId,
720
                        sys_lastedit_datetime = '$now',
721
                        total_messages = (
722
                            SELECT COUNT(*) as total_messages
723
                            FROM $table_support_messages
724
                            WHERE ticket_id = $ticketId
725
                        )
726
                    WHERE id = $ticketId ";
727
            Database::query($sql);
728
729
            if (is_array($fileAttachments)) {
730
                foreach ($fileAttachments as $file_attach) {
731
                    if ($file_attach['error'] == 0) {
732
                        self::saveMessageAttachmentFile(
733
                            $file_attach,
734
                            $ticketId,
735
                            $messageId
736
                        );
737
                    } else {
738
                        if ($file_attach['error'] != UPLOAD_ERR_NO_FILE) {
739
                            return false;
740
                        }
741
                    }
742
                }
743
            }
744
        }
745
746
        return true;
747
    }
748
749
    /**
750
     * Attachment files when a message is sent.
751
     *
752
     * @param $file_attach
753
     * @param $ticketId
754
     * @param $message_id
755
     *
756
     * @return bool
757
     */
758
    public static function saveMessageAttachmentFile(
759
        $file_attach,
760
        $ticketId,
761
        $message_id
762
    ) {
763
        $now = api_get_utc_datetime();
764
        $userId = api_get_user_id();
765
        $ticketId = (int) $ticketId;
766
767
        $new_file_name = add_ext_on_mime(
768
            stripslashes($file_attach['name']),
769
            $file_attach['type']
770
        );
771
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
772
        if (!filter_extension($new_file_name)) {
773
            echo Display::return_message(
774
                get_lang('UplUnableToSaveFileFilteredExtension'),
775
                'error'
776
            );
777
        } else {
778
            $result = api_upload_file('ticket_attachment', $file_attach, $ticketId);
779
            if ($result) {
0 ignored issues
show
introduced by
$result is a non-empty array, thus is always true.
Loading history...
Bug Best Practice introduced by
The expression $result of type array<string,string> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
780
                $safe_file_name = Database::escape_string($new_file_name);
781
                $safe_new_file_name = Database::escape_string($result['path_to_save']);
782
                $sql = "INSERT INTO $table_support_message_attachments (
783
                        filename,
784
                        path,
785
                        ticket_id,
786
                        message_id,
787
                        size,
788
                        sys_insert_user_id,
789
                        sys_insert_datetime,
790
                        sys_lastedit_user_id,
791
                        sys_lastedit_datetime
792
                    ) VALUES (
793
                        '$safe_file_name',
794
                        '$safe_new_file_name',
795
                        '$ticketId',
796
                        '$message_id',
797
                        '".$file_attach['size']."',
798
                        '$userId',
799
                        '$now',
800
                        '$userId',
801
                        '$now'
802
                    )";
803
                Database::query($sql);
804
805
                return true;
806
            }
807
        }
808
    }
809
810
    public static function deleteTicket($ticketId)
811
    {
812
        $ticketId = (int) $ticketId;
813
        if ($ticketId <= 0) {
814
            return false;
815
        }
816
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
817
        $table_ticket_message = Database::get_main_table('ticket_message');
818
        $table_ticket_assigned_log = Database::get_main_table('ticket_assigned_log');
819
        $table_ticket_message_attachments = Database::get_main_table('ticket_message_attachments');
820
821
        $sql_get_message_ids = "SELECT id FROM $table_ticket_message WHERE ticket_id = $ticketId";
822
        $sql_delete_attachments = "DELETE FROM $table_ticket_message_attachments WHERE message_id IN ($sql_get_message_ids)";
823
        Database::query($sql_delete_attachments);
824
        
825
        $sql_assigned_log = "DELETE FROM $table_ticket_assigned_log WHERE ticket_id = $ticketId";
826
        Database::query($sql_assigned_log);
827
828
        $sql_messages = "DELETE FROM $table_ticket_message WHERE ticket_id = $ticketId";
829
        Database::query($sql_messages);
830
831
        $sql_get_category = "SELECT category_id FROM $table_support_tickets WHERE id = $ticketId";
832
        $res = Database::query($sql_get_category);
833
        if ($row = Database::fetch_array($res)) {
834
            $category_id = (int)$row['category_id'];
835
            $table_ticket_category = Database::get_main_table('ticket_category');
836
            $sql_update_category = "UPDATE $table_ticket_category SET total_tickets = total_tickets - 1 WHERE id = $category_id AND total_tickets > 0";
837
            Database::query($sql_update_category);
838
        }
839
840
        $sql_ticket = "DELETE FROM $table_support_tickets WHERE id = $ticketId";
841
        Database::query($sql_ticket);
842
843
        return true;
844
    }
845
846
    /**
847
     * Get tickets by userId.
848
     *
849
     * @param int $from
850
     * @param int $number_of_items
851
     * @param $column
852
     * @param $direction
853
     *
854
     * @return array
855
     */
856
    public static function getTicketsByCurrentUser(
857
        $from,
858
        $number_of_items,
859
        $column,
860
        $direction
861
    ) {
862
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
863
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
864
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
865
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
866
        $direction = !empty($direction) ? $direction : 'DESC';
867
        $userId = api_get_user_id();
868
        $userInfo = api_get_user_info($userId);
869
870
        if (empty($userInfo)) {
871
            return [];
872
        }
873
        $isAdmin = UserManager::is_admin($userId) || (api_get_configuration_value('allow_session_admin_manage_tickets_and_export_ticket_report') && api_is_session_admin($userId));
874
875
        if (!isset($_GET['project_id'])) {
876
            return [];
877
        }
878
879
        switch ($column) {
880
            case 0:
881
                $column = 'ticket_id';
882
                break;
883
            case 1:
884
                $column = 'status_name';
885
                break;
886
            case 2:
887
                $column = 'start_date';
888
                break;
889
            case 3:
890
                $column = 'sys_lastedit_datetime';
891
                break;
892
            case 4:
893
                $column = 'category_name';
894
                break;
895
            case 5:
896
                $column = 'sys_insert_user_id';
897
                break;
898
            case 6:
899
                $column = 'assigned_last_user';
900
                break;
901
            case 7:
902
                $column = 'total_messages';
903
                break;
904
            case 8:
905
                $column = 'subject';
906
                break;
907
            default:
908
                $column = 'ticket_id';
909
        }
910
911
        $sql = "SELECT DISTINCT
912
                ticket.*,
913
                ticket.id ticket_id,
914
                status.name AS status_name,
915
                ticket.start_date,
916
                ticket.sys_lastedit_datetime,
917
                cat.name AS category_name,
918
                priority.name AS priority_name,
919
                ticket.total_messages AS total_messages,
920
                ticket.message AS message,
921
                ticket.subject AS subject,
922
                ticket.assigned_last_user
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
        ";
932
933
        $projectId = (int) $_GET['project_id'];
934
        $userIsAllowInProject = self::userIsAllowInProject($userInfo, $projectId);
935
936
        // Check if a role was set to the project
937
        if ($userIsAllowInProject == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
938
            $categoryList = self::getCategoryIdsByUser($userId, $projectId);
939
            $categoryCondition = '';
940
            if (!empty($categoryList)) {
941
                $categoryIds = implode(',', array_map('intval', $categoryList));
942
                $categoryCondition = " OR ticket.category_id IN ($categoryIds)";
943
            }
944
945
            $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId".$categoryCondition.")";
946
        }
947
948
        // Search simple
949
        if (isset($_GET['submit_simple']) && $_GET['keyword'] != '') {
950
            $keyword = Database::escape_string(trim($_GET['keyword']));
951
            $sql .= " AND (
952
                      ticket.id LIKE '%$keyword%' OR
953
                      ticket.code LIKE '%$keyword%' OR
954
                      ticket.subject LIKE '%$keyword%' OR
955
                      ticket.message LIKE '%$keyword%' OR
956
                      ticket.keyword LIKE '%$keyword%' OR
957
                      ticket.source LIKE '%$keyword%' OR
958
                      cat.name LIKE '%$keyword%' OR
959
                      status.name LIKE '%$keyword%' OR
960
                      priority.name LIKE '%$keyword%' OR
961
                      ticket.personal_email LIKE '%$keyword%'
962
            )";
963
        }
964
965
        $keywords = [
966
            'project_id' => 'ticket.project_id',
967
            'keyword_category' => 'ticket.category_id',
968
            'keyword_assigned_to' => 'ticket.assigned_last_user',
969
            'keyword_source' => 'ticket.source ',
970
            'keyword_status' => 'ticket.status_id',
971
            'keyword_priority' => 'ticket.priority_id',
972
            'keyword_created_by' => 'ticket.sys_insert_user_id',
973
        ];
974
975
        foreach ($keywords as $keyword => $label) {
976
            if (isset($_GET[$keyword])) {
977
                $data = Database::escape_string(trim($_GET[$keyword]));
978
                if (!empty($data)) {
979
                    $sql .= " AND $label = '$data' ";
980
                }
981
            }
982
        }
983
984
        // Search advanced
985
        $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
986
        $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
987
        $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
988
        $keyword_range = !empty($keyword_start_date_start) && !empty($keyword_start_date_end);
989
990
        if ($keyword_range == false && $keyword_start_date_start != '') {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

When comparing two booleans, it is generally considered safer to use the strict comparison operator.

Loading history...
991
            $sql .= " AND ticket.start_date >= '$keyword_start_date_start' ";
992
        }
993
        if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
994
            $sql .= " AND ticket.start_date >= '$keyword_start_date_start'
995
                      AND ticket.start_date <= '$keyword_start_date_end'";
996
        }
997
998
        if ($keyword_course != '') {
999
            $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1000
            $sql .= " AND ticket.course_id IN (
1001
                     SELECT id FROM $course_table
1002
                     WHERE (
1003
                        title LIKE '%$keyword_course%' OR
1004
                        code LIKE '%$keyword_course%' OR
1005
                        visual_code LIKE '%$keyword_course%'
1006
                     )
1007
            )";
1008
        }
1009
        $sql .= " ORDER BY `$column` $direction";
1010
        $sql .= " LIMIT $from, $number_of_items";
1011
1012
        $result = Database::query($sql);
1013
        $tickets = [];
1014
        $webPath = api_get_path(WEB_PATH);
1015
        while ($row = Database::fetch_assoc($result)) {
1016
            $userInfo = api_get_user_info($row['sys_insert_user_id']);
1017
            $hrefUser = $webPath.'main/admin/user_information.php?user_id='.$userInfo['user_id'];
1018
            $name = "<a href='$hrefUser'> {$userInfo['complete_name_with_username']} </a>";
1019
            if ($row['assigned_last_user'] != 0) {
1020
                $assignedUserInfo = api_get_user_info($row['assigned_last_user']);
1021
                if (!empty($assignedUserInfo)) {
1022
                    $hrefResp = $webPath.'main/admin/user_information.php?user_id='.$assignedUserInfo['user_id'];
1023
                    $row['assigned_last_user'] = "<a href='$hrefResp'> {$assignedUserInfo['complete_name_with_username']} </a>";
1024
                } else {
1025
                    $row['assigned_last_user'] = get_lang('UnknownUser');
1026
                }
1027
            } else {
1028
                if ($row['status_id'] !== self::STATUS_FORWARDED) {
1029
                    $row['assigned_last_user'] = '<span style="color:#ff0000;">'.get_lang('ToBeAssigned').'</span>';
1030
                } else {
1031
                    $row['assigned_last_user'] = '<span style="color:#00ff00;">'.get_lang('MessageResent').'</span>';
1032
                }
1033
            }
1034
1035
            switch ($row['source']) {
1036
                case self::SOURCE_PRESENTIAL:
1037
                    $img_source = 'icons/32/user.png';
1038
                    break;
1039
                case self::SOURCE_EMAIL:
1040
                    $img_source = 'icons/32/mail.png';
1041
                    break;
1042
                case self::SOURCE_PHONE:
1043
                    $img_source = 'icons/32/event.png';
1044
                    break;
1045
                default:
1046
                    $img_source = 'icons/32/ticket.png';
1047
                    break;
1048
            }
1049
1050
            $row['start_date'] = Display::dateToStringAgoAndLongDate($row['start_date']);
1051
            $row['sys_lastedit_datetime'] = Display::dateToStringAgoAndLongDate($row['sys_lastedit_datetime']);
1052
1053
            $icon = Display::return_icon(
1054
                $img_source,
1055
                get_lang('Info'),
1056
                ['style' => 'margin-right: 10px; float: left;']
1057
            );
1058
1059
            $icon .= '<a href="ticket_details.php?ticket_id='.$row['id'].'">'.$row['code'].'</a>';
1060
1061
            if ($isAdmin) {
1062
                $ticket = [
1063
                    $icon.' '.Security::remove_XSS($row['subject']),
1064
                    $row['status_name'],
1065
                    $row['start_date'],
1066
                    $row['sys_lastedit_datetime'],
1067
                    $row['category_name'],
1068
                    $name,
1069
                    $row['assigned_last_user'],
1070
                    $row['total_messages'],
1071
                ];
1072
            } else {
1073
                $ticket = [
1074
                    $icon.' '.Security::remove_XSS($row['subject']),
1075
                    $row['status_name'],
1076
                    $row['start_date'],
1077
                    $row['sys_lastedit_datetime'],
1078
                    $row['category_name'],
1079
                ];
1080
            }
1081
            if ($isAdmin) {
1082
                $ticket['0'] .= '&nbsp;&nbsp;<a href="javascript:void(0)" onclick="load_history_ticket(\'div_'.$row['ticket_id'].'\','.$row['ticket_id'].')">
1083
					<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').'"/>
1084
					<div class="blackboard_hide" id="div_'.$row['ticket_id'].'">&nbsp;&nbsp;</div>
1085
					</a>&nbsp;&nbsp;';
1086
            }
1087
            if ($isAdmin) {
1088
                $project_id = isset($row['project_id']) ? $row['project_id'] : (isset($_GET['project_id']) ? $_GET['project_id'] : 0);
1089
                $delete_link = '<a href="tickets.php?action=delete&ticket_id='.$row['ticket_id'].'&project_id='.$project_id.'" onclick="return confirm(\''.htmlentities(get_lang('AreYouSureYouWantToDeleteThisTicket')).'\')">'
1090
                . Display::return_icon('delete.png', get_lang('Delete')) .
1091
                '</a>';
1092
                $ticket[] = $delete_link;
1093
            }
1094
1095
            $tickets[] = $ticket;
1096
        }
1097
1098
        return $tickets;
1099
    }
1100
1101
    /**
1102
     * @return int
1103
     */
1104
    public static function getTotalTicketsCurrentUser()
1105
    {
1106
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1107
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1108
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1109
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1110
1111
        $userInfo = api_get_user_info();
1112
        if (empty($userInfo)) {
1113
            return 0;
1114
        }
1115
        $userId = $userInfo['id'];
1116
1117
        if (!isset($_GET['project_id'])) {
1118
            return 0;
1119
        }
1120
1121
        $sql = "SELECT COUNT(ticket.id) AS total
1122
                FROM $table_support_tickets ticket
1123
                INNER JOIN $table_support_category cat
1124
                ON (cat.id = ticket.category_id)
1125
                INNER JOIN $table_support_priority priority
1126
                ON (ticket.priority_id = priority.id)
1127
                INNER JOIN $table_support_status status
1128
                ON (ticket.status_id = status.id)
1129
	            WHERE 1 = 1";
1130
1131
        $projectId = (int) $_GET['project_id'];
1132
        $allowRoleList = self::getAllowedRolesFromProject($projectId);
1133
1134
        // Check if a role was set to the project
1135
        if (!empty($allowRoleList) && is_array($allowRoleList)) {
1136
            if (!in_array($userInfo['status'], $allowRoleList)) {
1137
                $categoryList = self::getCategoryIdsByUser($userId, $projectId);
1138
                $categoryCondition = '';
1139
                if (!empty($categoryList)) {
1140
                    $categoryIds = implode(',', array_map('intval', $categoryList));
1141
                    $categoryCondition = " OR ticket.category_id IN ($categoryIds)";
1142
                }
1143
1144
                $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId".$categoryCondition.")";
1145
            }
1146
        } else {
1147
            if (!api_is_platform_admin()) {
1148
                $categoryList = self::getCategoryIdsByUser($userId, $projectId);
1149
                $categoryCondition = '';
1150
                if (!empty($categoryList)) {
1151
                    $categoryIds = implode(',', array_map('intval', $categoryList));
1152
                    $categoryCondition = " OR ticket.category_id IN ($categoryIds)";
1153
                }
1154
1155
                $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId".$categoryCondition.")";
1156
            }
1157
        }
1158
1159
        // Search simple
1160
        if (isset($_GET['submit_simple'])) {
1161
            if ($_GET['keyword'] != '') {
1162
                $keyword = Database::escape_string(trim($_GET['keyword']));
1163
                $sql .= " AND (
1164
                          ticket.code LIKE '%$keyword%' OR
1165
                          ticket.subject LIKE '%$keyword%' OR
1166
                          ticket.message LIKE '%$keyword%' OR
1167
                          ticket.keyword LIKE '%$keyword%' OR
1168
                          ticket.personal_email LIKE '%$keyword%' OR
1169
                          ticket.source LIKE '%$keyword%'
1170
                )";
1171
            }
1172
        }
1173
1174
        $keywords = [
1175
            'project_id' => 'ticket.project_id',
1176
            'keyword_category' => 'ticket.category_id',
1177
            'keyword_assigned_to' => 'ticket.assigned_last_user',
1178
            'keyword_source' => 'ticket.source',
1179
            'keyword_status' => 'ticket.status_id',
1180
            'keyword_priority' => 'ticket.priority_id',
1181
            'keyword_created_by' => 'ticket.sys_insert_user_id',
1182
        ];
1183
1184
        foreach ($keywords as $keyword => $sqlLabel) {
1185
            if (!empty($_GET[$keyword])) {
1186
                $data = Database::escape_string(trim($_GET[$keyword]));
1187
                $sql .= " AND $sqlLabel = '$data' ";
1188
            }
1189
        }
1190
1191
        // Search advanced
1192
        $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
1193
        $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
1194
        $keyword_range = isset($_GET['keyword_dates']) ? Database::escape_string(trim($_GET['keyword_dates'])) : '';
1195
        $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
1196
1197
        if ($keyword_range == false && $keyword_start_date_start != '') {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $keyword_range of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
1198
            $sql .= " AND ticket.start_date >= '$keyword_start_date_start' ";
1199
        }
1200
        if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
1201
            $sql .= " AND ticket.start_date >= '$keyword_start_date_start'
1202
                      AND ticket.start_date <= '$keyword_start_date_end'";
1203
        }
1204
        if ($keyword_course != '') {
1205
            $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1206
            $sql .= " AND ticket.course_id IN (
1207
                        SELECT id
1208
                        FROM $course_table
1209
                        WHERE (
1210
                            title LIKE '%$keyword_course%' OR
1211
                            code LIKE '%$keyword_course%' OR
1212
                            visual_code LIKE '%$keyword_course%'
1213
                        )
1214
                   ) ";
1215
        }
1216
1217
        $res = Database::query($sql);
1218
        $obj = Database::fetch_object($res);
1219
1220
        return (int) $obj->total;
1221
    }
1222
1223
    /**
1224
     * @param int $id
1225
     *
1226
     * @return false|MessageAttachment
1227
     */
1228
    public static function getTicketMessageAttachment($id)
1229
    {
1230
        $id = (int) $id;
1231
        $em = Database::getManager();
1232
        $item = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->find($id);
1233
        if ($item) {
1234
            return $item;
1235
        }
1236
1237
        return false;
1238
    }
1239
1240
    /**
1241
     * @param int $id
1242
     *
1243
     * @return array
1244
     */
1245
    public static function getTicketMessageAttachmentsByTicketId($id)
1246
    {
1247
        $id = (int) $id;
1248
        $em = Database::getManager();
1249
        $items = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->findBy(['ticket' => $id]);
1250
        if ($items) {
1251
            return $items;
1252
        }
1253
1254
        return false;
1255
    }
1256
1257
    /**
1258
     * @param int $ticketId
1259
     *
1260
     * @return array
1261
     */
1262
    public static function get_ticket_detail_by_id($ticketId)
1263
    {
1264
        $ticketId = (int) $ticketId;
1265
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1266
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1267
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1268
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1269
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1270
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
1271
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1272
1273
        $sql = "SELECT
1274
                    ticket.*,
1275
                    cat.name,
1276
                    status.name as status,
1277
                    priority.name priority
1278
                FROM $table_support_tickets ticket
1279
                INNER JOIN $table_support_category cat
1280
                ON (cat.id = ticket.category_id)
1281
                INNER JOIN $table_support_priority priority
1282
                ON (priority.id = ticket.priority_id)
1283
                INNER JOIN $table_support_status status
1284
                ON (status.id = ticket.status_id)
1285
		        WHERE
1286
                    ticket.id = $ticketId ";
1287
        $result = Database::query($sql);
1288
        $ticket = [];
1289
        if (Database::num_rows($result) > 0) {
1290
            while ($row = Database::fetch_assoc($result)) {
1291
                $row['course'] = null;
1292
                $row['start_date_from_db'] = $row['start_date'];
1293
                $row['start_date'] = api_convert_and_format_date(
1294
                    api_get_local_time($row['start_date']),
1295
                    DATE_TIME_FORMAT_LONG,
1296
                    api_get_timezone()
1297
                );
1298
                $row['end_date_from_db'] = $row['end_date'];
1299
                $row['end_date'] = api_convert_and_format_date(
1300
                    api_get_local_time($row['end_date']),
1301
                    DATE_TIME_FORMAT_LONG,
1302
                    api_get_timezone()
1303
                );
1304
                $row['sys_lastedit_datetime_from_db'] = $row['sys_lastedit_datetime'];
1305
                $row['sys_lastedit_datetime'] = api_convert_and_format_date(
1306
                    api_get_local_time($row['sys_lastedit_datetime']),
1307
                    DATE_TIME_FORMAT_LONG,
1308
                    api_get_timezone()
1309
                );
1310
                $row['course_url'] = null;
1311
                if ($row['course_id'] != 0) {
1312
                    $course = api_get_course_info_by_id($row['course_id']);
1313
                    $sessionId = 0;
1314
                    if ($row['session_id']) {
1315
                        $sessionId = $row['session_id'];
1316
                    }
1317
                    if ($course) {
1318
                        $row['course_url'] = '<a href="'.$course['course_public_url'].'?id_session='.$sessionId.'">'.$course['name'].'</a>';
1319
                    }
1320
1321
                    $row['exercise_url'] = null;
1322
1323
                    if (!empty($row['exercise_id'])) {
1324
                        $exerciseTitle = ExerciseLib::getExerciseTitleById($row['exercise_id']);
1325
                        $dataExercise = [
1326
                            'cidReq' => $course['code'],
1327
                            'id_session' => $sessionId,
1328
                            'exerciseId' => $row['exercise_id'],
1329
                        ];
1330
                        $urlParamsExercise = http_build_query($dataExercise);
1331
1332
                        $row['exercise_url'] = '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.$urlParamsExercise.'">'.$exerciseTitle.'</a>';
1333
                    }
1334
1335
                    $row['lp_url'] = null;
1336
1337
                    if (!empty($row['lp_id'])) {
1338
                        $lpName = learnpath::getLpNameById($row['lp_id']);
1339
                        $dataLp = [
1340
                            'cidReq' => $course['code'],
1341
                            'id_session' => $sessionId,
1342
                            'lp_id' => $row['lp_id'],
1343
                            'action' => 'view',
1344
                        ];
1345
                        $urlParamsLp = http_build_query($dataLp);
1346
1347
                        $row['lp_url'] = '<a href="'.api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.$urlParamsLp.'">'.$lpName.'</a>';
1348
                    }
1349
                }
1350
1351
                $userInfo = api_get_user_info($row['sys_insert_user_id']);
1352
                $row['user_url'] = '<a href="'.api_get_path(WEB_PATH).'main/admin/user_information.php?user_id='.$userInfo['user_id'].'">
1353
                '.$userInfo['complete_name'].'</a>';
1354
                $ticket['usuario'] = $userInfo;
1355
                $ticket['ticket'] = $row;
1356
            }
1357
1358
            $sql = "SELECT *, message.id as message_id
1359
                    FROM $table_support_messages message
1360
                    INNER JOIN $table_main_user user
1361
                    ON (message.sys_insert_user_id = user.user_id)
1362
                    WHERE
1363
                        message.ticket_id = '$ticketId' ";
1364
            $result = Database::query($sql);
1365
            $ticket['messages'] = [];
1366
            $attach_icon = Display::return_icon('attachment.gif', '');
1367
            $webPath = api_get_path(WEB_CODE_PATH);
1368
            while ($row = Database::fetch_assoc($result)) {
1369
                $message = $row;
1370
                $message['admin'] = UserManager::is_admin($message['user_id']);
1371
                $message['user_info'] = api_get_user_info($message['user_id']);
1372
                $sql = "SELECT *
1373
                        FROM $table_support_message_attachments
1374
                        WHERE
1375
                            message_id = ".$row['message_id']." AND
1376
                            ticket_id = $ticketId";
1377
1378
                $result_attach = Database::query($sql);
1379
                while ($row2 = Database::fetch_assoc($result_attach)) {
1380
                    $row2['filename'] = Security::remove_XSS($row2['filename']);
1381
                    $archiveURL = $webPath.'ticket/download.php?ticket_id='.$ticketId.'&id='.$row2['id'];
1382
                    $row2['attachment_link'] = $attach_icon.
1383
                        '&nbsp;<a href="'.$archiveURL.'">'.$row2['filename'].'</a>&nbsp;('.$row2['size'].')';
1384
                    $message['attachments'][] = $row2;
1385
                }
1386
                $ticket['messages'][] = $message;
1387
            }
1388
        }
1389
1390
        return $ticket;
1391
    }
1392
1393
    /**
1394
     * @param int $ticketId
1395
     * @param int $userId
1396
     *
1397
     * @return bool
1398
     */
1399
    public static function update_message_status($ticketId, $userId)
1400
    {
1401
        $ticketId = (int) $ticketId;
1402
        $userId = (int) $userId;
1403
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1404
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1405
        $now = api_get_utc_datetime();
1406
        $sql = "UPDATE $table_support_messages
1407
                SET
1408
                    status = 'LEI',
1409
                    sys_lastedit_user_id ='".api_get_user_id()."',
1410
                    sys_lastedit_datetime ='".$now."'
1411
                WHERE ticket_id ='$ticketId' ";
1412
1413
        if (api_is_platform_admin()) {
1414
            $sql .= " AND sys_insert_user_id = '$userId'";
1415
        } else {
1416
            $sql .= " AND sys_insert_user_id != '$userId'";
1417
        }
1418
        $result = Database::query($sql);
1419
        if (Database::affected_rows($result) > 0) {
1420
            Database::query(
1421
                "UPDATE $table_support_tickets SET
1422
                    status_id = '".self::STATUS_PENDING."'
1423
                 WHERE id ='$ticketId' AND status_id = '".self::STATUS_NEW."'"
1424
            );
1425
1426
            return true;
1427
        }
1428
1429
        return false;
1430
    }
1431
1432
    /**
1433
     * Send notification to a user through the internal messaging system.
1434
     *
1435
     * @param int    $ticketId
1436
     * @param string $title
1437
     * @param string $message
1438
     * @param int    $onlyToUserId
1439
     *
1440
     * @return bool
1441
     */
1442
    public static function sendNotification($ticketId, $title, $message, $onlyToUserId = 0)
1443
    {
1444
        $ticketInfo = self::get_ticket_detail_by_id($ticketId);
1445
1446
        if (empty($ticketInfo)) {
1447
            return false;
1448
        }
1449
1450
        $assignedUserInfo = api_get_user_info($ticketInfo['ticket']['assigned_last_user']);
1451
        $requestUserInfo = $ticketInfo['usuario'];
1452
        $ticketCode = $ticketInfo['ticket']['code'];
1453
        $status = $ticketInfo['ticket']['status'];
1454
        $priority = $ticketInfo['ticket']['priority'];
1455
1456
        // Subject
1457
        $titleEmail = "[$ticketCode] $title";
1458
1459
        // Content
1460
        $href = api_get_path(WEB_CODE_PATH).'ticket/ticket_details.php?ticket_id='.$ticketId;
1461
        $ticketUrl = Display::url($ticketCode, $href);
1462
        $messageEmail = get_lang('TicketNum').": $ticketUrl <br />";
1463
        $messageEmail .= get_lang('Status').": $status <br />";
1464
        $messageEmail .= get_lang('Priority').": $priority <br />";
1465
        $messageEmail .= '<hr /><br />';
1466
        $messageEmail .= $message;
1467
        $currentUserId = api_get_user_id();
1468
        $attachmentList = [];
1469
        $attachments = self::getTicketMessageAttachmentsByTicketId($ticketId);
1470
        if (!empty($attachments)) {
1471
            /** @var MessageAttachment $attachment */
1472
            foreach ($attachments as $attachment) {
1473
                $file = api_get_uploaded_file(
1474
                    'ticket_attachment',
1475
                    $ticketId,
1476
                    $attachment->getPath()
1477
                );
1478
                if (!empty($file)) {
1479
                    $attachmentList[] = [
1480
                        'tmp_name' => api_get_uploaded_file(
1481
                            'ticket_attachment',
1482
                            $ticketId,
1483
                            $attachment->getPath()
1484
                        ),
1485
                        'size' => $attachment->getSize(),
1486
                        'name' => $attachment->getFilename(),
1487
                        'error' => 0,
1488
                    ];
1489
                }
1490
            }
1491
        }
1492
1493
        if (!empty($onlyToUserId)) {
1494
            // Send only to specific user
1495
            if ($currentUserId != $onlyToUserId) {
1496
                MessageManager::send_message_simple(
1497
                    $onlyToUserId,
1498
                    $titleEmail,
1499
                    $messageEmail,
1500
                    0,
1501
                    false,
1502
                    false,
1503
                    [],
1504
                    false,
1505
                    $attachmentList
1506
                );
1507
            }
1508
        } else {
1509
            // Send to assigned user and to author
1510
            if ($requestUserInfo && $currentUserId != $requestUserInfo['id']) {
1511
                MessageManager::send_message_simple(
1512
                    $requestUserInfo['id'],
1513
                    $titleEmail,
1514
                    $messageEmail,
1515
                    0,
1516
                    false,
1517
                    false,
1518
                    [],
1519
                    false,
1520
                    $attachmentList
1521
                );
1522
            }
1523
1524
            if ($assignedUserInfo &&
1525
                $requestUserInfo['id'] != $assignedUserInfo['id'] &&
1526
                $currentUserId != $assignedUserInfo['id']
1527
            ) {
1528
                MessageManager::send_message_simple(
1529
                    $assignedUserInfo['id'],
1530
                    $titleEmail,
1531
                    $messageEmail,
1532
                    0,
1533
                    false,
1534
                    false,
1535
                    [],
1536
                    false,
1537
                    $attachmentList
1538
                );
1539
            }
1540
        }
1541
    }
1542
1543
    /**
1544
     * @param array $params
1545
     * @param int   $ticketId
1546
     * @param int   $userId
1547
     *
1548
     * @return bool
1549
     */
1550
    public static function updateTicket(
1551
        $params,
1552
        $ticketId,
1553
        $userId
1554
    ) {
1555
        $now = api_get_utc_datetime();
1556
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
1557
        $newParams = [
1558
            'priority_id' => isset($params['priority_id']) ? (int) $params['priority_id'] : '',
1559
            'status_id' => isset($params['status_id']) ? (int) $params['status_id'] : '',
1560
            'sys_lastedit_user_id' => (int) $userId,
1561
            'sys_lastedit_datetime' => $now,
1562
        ];
1563
        Database::update($table, $newParams, ['id = ? ' => $ticketId]);
1564
1565
        return true;
1566
    }
1567
1568
    /**
1569
     * @param int $status_id
1570
     * @param int $ticketId
1571
     * @param int $userId
1572
     *
1573
     * @return bool
1574
     */
1575
    public static function update_ticket_status(
1576
        $status_id,
1577
        $ticketId,
1578
        $userId
1579
    ) {
1580
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1581
1582
        $ticketId = (int) $ticketId;
1583
        $status_id = (int) $status_id;
1584
        $userId = (int) $userId;
1585
        $now = api_get_utc_datetime();
1586
1587
        $sql = "UPDATE $table_support_tickets
1588
                SET
1589
                    status_id = '$status_id',
1590
                    sys_lastedit_user_id ='$userId',
1591
                    sys_lastedit_datetime ='".$now."'
1592
                WHERE id ='$ticketId'";
1593
        $result = Database::query($sql);
1594
1595
        if (Database::affected_rows($result) > 0) {
1596
            self::sendNotification(
1597
                $ticketId,
1598
                get_lang('TicketUpdated'),
1599
                get_lang('TicketUpdated')
1600
            );
1601
1602
            return true;
1603
        }
1604
1605
        return false;
1606
    }
1607
1608
    /**
1609
     * @return mixed
1610
     */
1611
    public static function getNumberOfMessages()
1612
    {
1613
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1614
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1615
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1616
        $table_main_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1617
        $user_info = api_get_user_info();
1618
        $userId = $user_info['user_id'];
1619
        $sql = "SELECT COUNT(DISTINCT ticket.id) AS unread
1620
                FROM $table_support_tickets ticket,
1621
                $table_support_messages message ,
1622
                $table_main_user user
1623
                WHERE
1624
                    ticket.id = message.ticket_id AND
1625
                    message.status = 'NOL' AND
1626
                    user.user_id = message.sys_insert_user_id ";
1627
        if (!api_is_platform_admin()) {
1628
            $sql .= " AND ticket.request_user = '$userId'
1629
                      AND user_id IN (SELECT user_id FROM $table_main_admin)  ";
1630
        } else {
1631
            $sql .= " AND user_id NOT IN (SELECT user_id FROM $table_main_admin)
1632
                      AND ticket.status_id != '".self::STATUS_FORWARDED."'";
1633
        }
1634
        $sql .= "  AND ticket.project_id != '' ";
1635
        $res = Database::query($sql);
1636
        $obj = Database::fetch_object($res);
1637
1638
        return $obj->unread;
1639
    }
1640
1641
    /**
1642
     * @param int $ticketId
1643
     * @param int $userId
1644
     */
1645
    public static function send_alert($ticketId, $userId)
1646
    {
1647
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1648
        $now = api_get_utc_datetime();
1649
1650
        $ticketId = (int) $ticketId;
1651
        $userId = (int) $userId;
1652
1653
        $sql = "UPDATE $table_support_tickets SET
1654
                  priority_id = '".self::PRIORITY_HIGH."',
1655
                  sys_lastedit_user_id = $userId,
1656
                  sys_lastedit_datetime = '$now'
1657
                WHERE id = $ticketId";
1658
        Database::query($sql);
1659
    }
1660
1661
    /**
1662
     * @param int $ticketId
1663
     * @param int $userId
1664
     */
1665
    public static function close_ticket($ticketId, $userId)
1666
    {
1667
        $ticketId = (int) $ticketId;
1668
        $userId = (int) $userId;
1669
1670
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1671
        $now = api_get_utc_datetime();
1672
        $sql = "UPDATE $table_support_tickets SET
1673
                    status_id = '".self::STATUS_CLOSE."',
1674
                    sys_lastedit_user_id ='$userId',
1675
                    sys_lastedit_datetime ='".$now."',
1676
                    end_date ='$now'
1677
                WHERE id ='$ticketId'";
1678
        Database::query($sql);
1679
1680
        self::sendNotification(
1681
            $ticketId,
1682
            get_lang('TicketClosed'),
1683
            get_lang('TicketClosed')
1684
        );
1685
    }
1686
1687
    /**
1688
     * Close old tickets.
1689
     */
1690
    public static function close_old_tickets()
1691
    {
1692
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
1693
        $now = api_get_utc_datetime();
1694
        $userId = api_get_user_id();
1695
        $sql = "UPDATE $table
1696
                SET
1697
                    status_id = '".self::STATUS_CLOSE."',
1698
                    sys_lastedit_user_id ='$userId',
1699
                    sys_lastedit_datetime ='$now',
1700
                    end_date = '$now'
1701
                WHERE
1702
                    DATEDIFF('$now', sys_lastedit_datetime) > 7 AND
1703
                    status_id != '".self::STATUS_CLOSE."' AND
1704
                    status_id != '".self::STATUS_NEW."' AND
1705
                    status_id != '".self::STATUS_FORWARDED."'";
1706
        Database::query($sql);
1707
    }
1708
1709
    /**
1710
     * @param int $ticketId
1711
     *
1712
     * @return array
1713
     */
1714
    public static function get_assign_log($ticketId)
1715
    {
1716
        $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
1717
        $ticketId = (int) $ticketId;
1718
1719
        $sql = "SELECT * FROM $table
1720
                WHERE ticket_id = $ticketId
1721
                ORDER BY assigned_date DESC";
1722
        $result = Database::query($sql);
1723
        $history = [];
1724
        $webpath = api_get_path(WEB_PATH);
1725
        while ($row = Database::fetch_assoc($result)) {
1726
            if ($row['user_id'] != 0) {
1727
                $assignuser = api_get_user_info($row['user_id']);
1728
                $row['assignuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['user_id'].'"  target="_blank">'.
1729
                $assignuser['username'].'</a>';
1730
            } else {
1731
                $row['assignuser'] = get_lang('Unassign');
1732
            }
1733
            $row['assigned_date'] = Display::dateToStringAgoAndLongDate($row['assigned_date']);
1734
            $insertuser = api_get_user_info($row['sys_insert_user_id']);
1735
            $row['insertuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['sys_insert_user_id'].'"  target="_blank">'.
1736
                $insertuser['username'].'</a>';
1737
            $history[] = $row;
1738
        }
1739
1740
        return $history;
1741
    }
1742
1743
    /**
1744
     * @param $from
1745
     * @param $number_of_items
1746
     * @param $column
1747
     * @param $direction
1748
     * @param null $userId
0 ignored issues
show
Documentation Bug introduced by
Are you sure the doc-type for parameter $userId is correct as it would always require null to be passed?
Loading history...
1749
     *
1750
     * @return array
1751
     */
1752
    public static function export_tickets_by_user_id(
1753
        $from,
1754
        $number_of_items,
1755
        $column,
1756
        $direction,
1757
        $userId = null
1758
    ) {
1759
        $from = (int) $from;
1760
        $number_of_items = (int) $number_of_items;
1761
        $table_support_category = Database::get_main_table(
1762
            TABLE_TICKET_CATEGORY
1763
        );
1764
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1765
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1766
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1767
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1768
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1769
1770
        if (is_null($direction)) {
1771
            $direction = 'DESC';
1772
        }
1773
        if (is_null($userId) || $userId == 0) {
1774
            $userId = api_get_user_id();
1775
        }
1776
1777
        $sql = "SELECT
1778
                    ticket.code,
1779
                    ticket.sys_insert_datetime,
1780
                    ticket.sys_lastedit_datetime,
1781
                    cat.name as category,
1782
                    CONCAT(user.lastname,' ', user.firstname) AS fullname,
1783
                    status.name as status,
1784
                    ticket.total_messages as messages,
1785
                    ticket.assigned_last_user as responsable
1786
                FROM $table_support_tickets ticket,
1787
                $table_support_category cat ,
1788
                $table_support_priority priority,
1789
                $table_support_status status ,
1790
                $table_main_user user
1791
                WHERE
1792
                    cat.id = ticket.category_id
1793
                    AND ticket.priority_id = priority.id
1794
                    AND ticket.status_id = status.id
1795
                    AND user.user_id = ticket.request_user ";
1796
        // Search simple
1797
        if (isset($_GET['submit_simple'])) {
1798
            if ($_GET['keyword'] !== '') {
1799
                $keyword = Database::escape_string(trim($_GET['keyword']));
1800
                $sql .= " AND (ticket.code = '$keyword'
1801
                          OR user.firstname LIKE '%$keyword%'
1802
                          OR user.lastname LIKE '%$keyword%'
1803
                          OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword%'
1804
                          OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword%'
1805
                          OR user.username LIKE '%$keyword%')  ";
1806
            }
1807
        }
1808
        // Search advanced
1809
        if (isset($_GET['submit_advanced'])) {
1810
            $keyword_category = Database::escape_string(
1811
                trim($_GET['keyword_category'])
1812
            );
1813
            $keyword_request_user = Database::escape_string(
1814
                trim($_GET['keyword_request_user'])
1815
            );
1816
            $keywordAssignedTo = (int) $_GET['keyword_assigned_to'];
1817
            $keyword_start_date_start = Database::escape_string(
1818
                trim($_GET['keyword_start_date_start'])
1819
            );
1820
            $keyword_start_date_end = Database::escape_string(
1821
                trim($_GET['keyword_start_date_end'])
1822
            );
1823
            $keyword_status = Database::escape_string(
1824
                trim($_GET['keyword_status'])
1825
            );
1826
            $keyword_source = Database::escape_string(
1827
                trim($_GET['keyword_source'])
1828
            );
1829
            $keyword_priority = Database::escape_string(
1830
                trim($_GET['keyword_priority'])
1831
            );
1832
            $keyword_range = Database::escape_string(
1833
                trim($_GET['keyword_dates'])
1834
            );
1835
            $keyword_unread = Database::escape_string(
1836
                trim($_GET['keyword_unread'])
1837
            );
1838
            $keyword_course = Database::escape_string(
1839
                trim($_GET['keyword_course'])
1840
            );
1841
1842
            if ($keyword_category != '') {
1843
                $sql .= " AND ticket.category_id = '$keyword_category'  ";
1844
            }
1845
            if ($keyword_request_user != '') {
1846
                $sql .= " AND (ticket.request_user = '$keyword_request_user'
1847
                          OR user.firstname LIKE '%$keyword_request_user%'
1848
                          OR user.official_code LIKE '%$keyword_request_user%'
1849
                          OR user.lastname LIKE '%$keyword_request_user%'
1850
                          OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword_request_user%'
1851
                          OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword_request_user%'
1852
                          OR user.username LIKE '%$keyword_request_user%') ";
1853
            }
1854
            if (!empty($keywordAssignedTo)) {
1855
                $sql .= " AND ticket.assigned_last_user = $keywordAssignedTo ";
1856
            }
1857
            if ($keyword_status != '') {
1858
                $sql .= " AND ticket.status_id = '$keyword_status'  ";
1859
            }
1860
            if ($keyword_range == '' && $keyword_start_date_start != '') {
1861
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
1862
            }
1863
            if ($keyword_range == '1' && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
1864
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
1865
                          AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
1866
            }
1867
            if ($keyword_priority != '') {
1868
                $sql .= " AND ticket.priority_id = '$keyword_priority'  ";
1869
            }
1870
            if ($keyword_source != '') {
1871
                $sql .= " AND ticket.source = '$keyword_source' ";
1872
            }
1873
            if ($keyword_priority != '') {
1874
                $sql .= " AND ticket.priority_id = '$keyword_priority' ";
1875
            }
1876
            if ($keyword_course != '') {
1877
                $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1878
                $sql .= " AND ticket.course_id IN ( ";
1879
                $sql .= "SELECT id
1880
                         FROM $course_table
1881
                         WHERE (title LIKE '%$keyword_course%'
1882
                         OR code LIKE '%$keyword_course%'
1883
                         OR visual_code LIKE '%$keyword_course%' )) ";
1884
            }
1885
            if ($keyword_unread == 'yes') {
1886
                $sql .= " AND ticket.id IN (
1887
                          SELECT ticket.id
1888
                          FROM $table_support_tickets ticket,
1889
                          $table_support_messages message,
1890
                          $table_main_user user
1891
                          WHERE ticket.id = message.ticket_id
1892
                          AND message.status = 'NOL'
1893
                          AND message.sys_insert_user_id = user.user_id
1894
                          AND user.status != 1   AND ticket.status_id != '".self::STATUS_FORWARDED."'
1895
                          GROUP BY ticket.id)";
1896
            } else {
1897
                if ($keyword_unread == 'no') {
1898
                    $sql .= " AND ticket.id NOT IN (
1899
                              SELECT ticket.id
1900
                              FROM  $table_support_tickets ticket,
1901
                              $table_support_messages message,
1902
                              $table_main_user user
1903
                              WHERE ticket.id = message.ticket_id
1904
                              AND message.status = 'NOL'
1905
                              AND message.sys_insert_user_id = user.user_id
1906
                              AND user.status != 1
1907
                              AND ticket.status_id != '".self::STATUS_FORWARDED."'
1908
                             GROUP BY ticket.id)";
1909
                }
1910
            }
1911
        }
1912
1913
        $sql .= " LIMIT $from,$number_of_items";
1914
1915
        $result = Database::query($sql);
1916
        $tickets[0] = [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$tickets was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tickets = array(); before regardless.
Loading history...
1917
            utf8_decode('Ticket#'),
1918
            utf8_decode('Fecha'),
1919
            utf8_decode('Fecha Edicion'),
1920
            utf8_decode('Categoria'),
1921
            utf8_decode('Usuario'),
1922
            utf8_decode('Estado'),
1923
            utf8_decode('Mensajes'),
1924
            utf8_decode('Responsable'),
1925
            utf8_decode('Programa'),
1926
        ];
1927
1928
        while ($row = Database::fetch_assoc($result)) {
1929
            if ($row['responsable'] != 0) {
1930
                $row['responsable'] = api_get_user_info($row['responsable']);
1931
                $row['responsable'] = $row['responsable']['firstname'].' '.$row['responsable']['lastname'];
1932
            }
1933
            $row['sys_insert_datetime'] = api_format_date(
1934
                $row['sys_insert_datetime'],
1935
                '%d/%m/%y - %I:%M:%S %p'
1936
            );
1937
            $row['sys_lastedit_datetime'] = api_format_date(
1938
                $row['sys_lastedit_datetime'],
1939
                '%d/%m/%y - %I:%M:%S %p'
1940
            );
1941
            $row['category'] = utf8_decode($row['category']);
1942
            $row['programa'] = utf8_decode($row['fullname']);
1943
            $row['fullname'] = utf8_decode($row['fullname']);
1944
            $row['responsable'] = utf8_decode($row['responsable']);
1945
            $tickets[] = $row;
1946
        }
1947
1948
        return $tickets;
1949
    }
1950
1951
    /**
1952
     * @param string $url
1953
     * @param int    $projectId
1954
     *
1955
     * @return FormValidator
1956
     */
1957
    public static function getCategoryForm($url, $projectId)
1958
    {
1959
        $form = new FormValidator('category', 'post', $url);
1960
        $form->addText('name', get_lang('Name'));
1961
        $form->addHtmlEditor('description', get_lang('Description'));
1962
        $form->addHidden('project_id', $projectId);
1963
        $form->addButtonUpdate(get_lang('Save'));
1964
1965
        return $form;
1966
    }
1967
1968
    /**
1969
     * @return array
1970
     */
1971
    public static function getStatusList()
1972
    {
1973
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
1974
1975
        $list = [];
1976
        /** @var Status $row */
1977
        foreach ($items as $row) {
1978
            $list[$row->getId()] = $row->getName();
1979
        }
1980
1981
        return $list;
1982
    }
1983
1984
    /**
1985
     * @param array $criteria
1986
     *
1987
     * @return array
1988
     */
1989
    public static function getTicketsFromCriteria($criteria)
1990
    {
1991
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Ticket')->findBy($criteria);
1992
1993
        $list = [];
1994
        /** @var Ticket $row */
1995
        foreach ($items as $row) {
1996
            $list[$row->getId()] = $row->getCode();
1997
        }
1998
1999
        return $list;
2000
    }
2001
2002
    /**
2003
     * @param string $code
2004
     *
2005
     * @return int
2006
     */
2007
    public static function getStatusIdFromCode($code)
2008
    {
2009
        $item = Database::getManager()
2010
            ->getRepository('ChamiloTicketBundle:Status')
2011
            ->findOneBy(['code' => $code])
2012
        ;
2013
2014
        if ($item) {
2015
            return $item->getId();
2016
        }
2017
2018
        return 0;
2019
    }
2020
2021
    /**
2022
     * @return array
2023
     */
2024
    public static function getPriorityList()
2025
    {
2026
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2027
2028
        $list = [];
2029
        /** @var Priority $row */
2030
        foreach ($projects as $row) {
2031
            $list[$row->getId()] = $row->getName();
2032
        }
2033
2034
        return $list;
2035
    }
2036
2037
    /**
2038
     * @return array
2039
     */
2040
    public static function getProjects()
2041
    {
2042
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
2043
2044
        $list = [];
2045
        /** @var Project $row */
2046
        foreach ($projects as $row) {
2047
            $list[] = [
2048
                'id' => $row->getId(),
2049
                '0' => $row->getId(),
2050
                '1' => $row->getName(),
2051
                '2' => $row->getDescription(),
2052
                '3' => $row->getId(),
2053
            ];
2054
        }
2055
2056
        return $list;
2057
    }
2058
2059
    /**
2060
     * @return array
2061
     */
2062
    public static function getProjectsSimple()
2063
    {
2064
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
2065
2066
        $list = [];
2067
        /** @var Project $row */
2068
        foreach ($projects as $row) {
2069
            $list[] = [
2070
                'id' => $row->getId(),
2071
                '0' => $row->getId(),
2072
                '1' => Display::url(
2073
                    $row->getName(),
2074
                    api_get_path(WEB_CODE_PATH).'ticket/tickets.php?project_id='.$row->getId()
2075
                ),
2076
                '2' => $row->getDescription(),
2077
            ];
2078
        }
2079
2080
        return $list;
2081
    }
2082
2083
    /**
2084
     * @return int
2085
     */
2086
    public static function getProjectsCount()
2087
    {
2088
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->createQueryBuilder('p')
2089
            ->select('COUNT(p.id)')
2090
            ->getQuery()
2091
            ->getSingleScalarResult();
2092
2093
        return $count;
2094
    }
2095
2096
    /**
2097
     * @param array $params
2098
     */
2099
    public static function addProject($params)
2100
    {
2101
        $project = new Project();
2102
        $project->setName($params['name']);
2103
        $project->setDescription($params['description']);
2104
        $project->setInsertUserId(api_get_user_id());
2105
2106
        Database::getManager()->persist($project);
2107
        Database::getManager()->flush();
2108
    }
2109
2110
    /**
2111
     * @param int $id
2112
     *
2113
     * @return Project
2114
     */
2115
    public static function getProject($id)
2116
    {
2117
        return Database::getManager()->getRepository('ChamiloTicketBundle:Project')->find($id);
2118
    }
2119
2120
    /**
2121
     * @param int   $id
2122
     * @param array $params
2123
     */
2124
    public static function updateProject($id, $params)
2125
    {
2126
        $project = self::getProject($id);
2127
        $project->setName($params['name']);
2128
        $project->setDescription($params['description']);
2129
        $project->setLastEditDateTime(new DateTime($params['sys_lastedit_datetime']));
2130
        $project->setLastEditUserId($params['sys_lastedit_user_id']);
2131
2132
        Database::getManager()->merge($project);
2133
        Database::getManager()->flush();
2134
    }
2135
2136
    /**
2137
     * @param int $id
2138
     */
2139
    public static function deleteProject($id)
2140
    {
2141
        $project = self::getProject($id);
2142
        if ($project) {
0 ignored issues
show
introduced by
$project is of type Chamilo\TicketBundle\Entity\Project, thus it always evaluated to true.
Loading history...
2143
            Database::getManager()->remove($project);
2144
            Database::getManager()->flush();
2145
        }
2146
    }
2147
2148
    /**
2149
     * @param string $url
2150
     *
2151
     * @return FormValidator
2152
     */
2153
    public static function getProjectForm($url)
2154
    {
2155
        $form = new FormValidator('project', 'post', $url);
2156
        $form->addText('name', get_lang('Name'));
2157
        $form->addHtmlEditor('description', get_lang('Description'));
2158
        $form->addButtonUpdate(get_lang('Save'));
2159
2160
        return $form;
2161
    }
2162
2163
    /**
2164
     * @return array
2165
     */
2166
    public static function getStatusAdminList()
2167
    {
2168
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
2169
2170
        $list = [];
2171
        /** @var Status $row */
2172
        foreach ($items as $row) {
2173
            $list[] = [
2174
                'id' => $row->getId(),
2175
                'code' => $row->getCode(),
2176
                '0' => $row->getId(),
2177
                '1' => $row->getName(),
2178
                '2' => $row->getDescription(),
2179
                '3' => $row->getId(),
2180
            ];
2181
        }
2182
2183
        return $list;
2184
    }
2185
2186
    /**
2187
     * @return array
2188
     */
2189
    public static function getStatusSimple()
2190
    {
2191
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
2192
2193
        $list = [];
2194
        /** @var Project $row */
2195
        foreach ($projects as $row) {
2196
            $list[] = [
2197
                'id' => $row->getId(),
2198
                '0' => $row->getId(),
2199
                '1' => Display::url($row->getName()),
0 ignored issues
show
Bug introduced by
The call to Display::url() has too few arguments starting with url. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2199
                '1' => Display::/** @scrutinizer ignore-call */ url($row->getName()),

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
2200
                '2' => $row->getDescription(),
2201
            ];
2202
        }
2203
2204
        return $list;
2205
    }
2206
2207
    /**
2208
     * @return int
2209
     */
2210
    public static function getStatusCount()
2211
    {
2212
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->createQueryBuilder('p')
2213
            ->select('COUNT(p.id)')
2214
            ->getQuery()
2215
            ->getSingleScalarResult();
2216
2217
        return $count;
2218
    }
2219
2220
    /**
2221
     * @param array $params
2222
     */
2223
    public static function addStatus($params)
2224
    {
2225
        $item = new Status();
2226
        $item->setCode(URLify::filter($params['name']));
2227
        $item->setName($params['name']);
2228
        $item->setDescription($params['description']);
2229
2230
        Database::getManager()->persist($item);
2231
        Database::getManager()->flush();
2232
    }
2233
2234
    /**
2235
     * @param $id
2236
     *
2237
     * @return Project
2238
     */
2239
    public static function getStatus($id)
2240
    {
2241
        return Database::getManager()->getRepository('ChamiloTicketBundle:Status')->find($id);
2242
    }
2243
2244
    /**
2245
     * @param int   $id
2246
     * @param array $params
2247
     */
2248
    public static function updateStatus($id, $params)
2249
    {
2250
        $item = self::getStatus($id);
2251
        $item->setName($params['name']);
2252
        $item->setDescription($params['description']);
2253
2254
        Database::getManager()->merge($item);
2255
        Database::getManager()->flush();
2256
    }
2257
2258
    /**
2259
     * @param int $id
2260
     */
2261
    public static function deleteStatus($id)
2262
    {
2263
        $item = self::getStatus($id);
2264
        if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\TicketBundle\Entity\Project, thus it always evaluated to true.
Loading history...
2265
            Database::getManager()->remove($item);
2266
            Database::getManager()->flush();
2267
        }
2268
    }
2269
2270
    /**
2271
     * @param string $url
2272
     *
2273
     * @return FormValidator
2274
     */
2275
    public static function getStatusForm($url)
2276
    {
2277
        $form = new FormValidator('status', 'post', $url);
2278
        $form->addText('name', get_lang('Name'));
2279
        $form->addHtmlEditor('description', get_lang('Description'));
2280
        $form->addButtonUpdate(get_lang('Save'));
2281
2282
        return $form;
2283
    }
2284
2285
    /**
2286
     * @return array
2287
     */
2288
    public static function getPriorityAdminList()
2289
    {
2290
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2291
2292
        $list = [];
2293
        /** @var Status $row */
2294
        foreach ($items as $row) {
2295
            $list[] = [
2296
                'id' => $row->getId(),
2297
                'code' => $row->getCode(),
2298
                '0' => $row->getId(),
2299
                '1' => $row->getName(),
2300
                '2' => $row->getDescription(),
2301
                '3' => $row->getId(),
2302
            ];
2303
        }
2304
2305
        return $list;
2306
    }
2307
2308
    /**
2309
     * @return array
2310
     */
2311
    public static function getPrioritySimple()
2312
    {
2313
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2314
2315
        $list = [];
2316
        /** @var Priority $row */
2317
        foreach ($projects as $row) {
2318
            $list[] = [
2319
                'id' => $row->getId(),
2320
                '0' => $row->getId(),
2321
                '1' => Display::url($row->getName()),
0 ignored issues
show
Bug introduced by
The call to Display::url() has too few arguments starting with url. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

2321
                '1' => Display::/** @scrutinizer ignore-call */ url($row->getName()),

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
2322
                '2' => $row->getDescription(),
2323
            ];
2324
        }
2325
2326
        return $list;
2327
    }
2328
2329
    /**
2330
     * @return int
2331
     */
2332
    public static function getPriorityCount()
2333
    {
2334
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->createQueryBuilder('p')
2335
            ->select('COUNT(p.id)')
2336
            ->getQuery()
2337
            ->getSingleScalarResult();
2338
2339
        return $count;
2340
    }
2341
2342
    /**
2343
     * @param array $params
2344
     */
2345
    public static function addPriority($params)
2346
    {
2347
        $item = new Priority();
2348
        $item
2349
            ->setCode(URLify::filter($params['name']))
2350
            ->setName($params['name'])
2351
            ->setDescription($params['description'])
2352
            ->setColor('')
2353
            ->setInsertUserId(api_get_user_id())
2354
            ->setUrgency('')
2355
        ;
2356
2357
        Database::getManager()->persist($item);
2358
        Database::getManager()->flush();
2359
    }
2360
2361
    /**
2362
     * @param $id
2363
     *
2364
     * @return Priority
2365
     */
2366
    public static function getPriority($id)
2367
    {
2368
        return Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->find($id);
2369
    }
2370
2371
    /**
2372
     * @param int   $id
2373
     * @param array $params
2374
     */
2375
    public static function updatePriority($id, $params)
2376
    {
2377
        $item = self::getPriority($id);
2378
        $item->setName($params['name']);
2379
        $item->setDescription($params['description']);
2380
2381
        Database::getManager()->merge($item);
2382
        Database::getManager()->flush();
2383
    }
2384
2385
    /**
2386
     * @param int $id
2387
     */
2388
    public static function deletePriority($id)
2389
    {
2390
        $item = self::getPriority($id);
2391
        if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\TicketBundle\Entity\Priority, thus it always evaluated to true.
Loading history...
2392
            Database::getManager()->remove($item);
2393
            Database::getManager()->flush();
2394
        }
2395
    }
2396
2397
    /**
2398
     * @param string $url
2399
     *
2400
     * @return FormValidator
2401
     */
2402
    public static function getPriorityForm($url)
2403
    {
2404
        $form = new FormValidator('priority', 'post', $url);
2405
        $form->addText('name', get_lang('Name'));
2406
        $form->addHtmlEditor('description', get_lang('Description'));
2407
        $form->addButtonUpdate(get_lang('Save'));
2408
2409
        return $form;
2410
    }
2411
2412
    /**
2413
     * Returns a list of menu elements for the tickets system's configuration.
2414
     *
2415
     * @param string $exclude The element to exclude from the list
2416
     *
2417
     * @return array
2418
     */
2419
    public static function getSettingsMenuItems($exclude = null)
2420
    {
2421
        $project = [
2422
            'icon' => 'project.png',
2423
            'url' => 'projects.php',
2424
            'content' => get_lang('Projects'),
2425
        ];
2426
        $status = [
2427
            'icon' => 'check-circle.png',
2428
            'url' => 'status.php',
2429
            'content' => get_lang('Status'),
2430
        ];
2431
        $priority = [
2432
            'icon' => 'tickets_urgent.png',
2433
            'url' => 'priorities.php',
2434
            'content' => get_lang('Priority'),
2435
        ];
2436
        switch ($exclude) {
2437
            case 'project':
2438
                $items = [$status, $priority];
2439
                break;
2440
            case 'status':
2441
                $items = [$project, $priority];
2442
                break;
2443
            case 'priority':
2444
                $items = [$project, $status];
2445
                break;
2446
            default:
2447
                $items = [$project, $status, $priority];
2448
                break;
2449
        }
2450
2451
        return $items;
2452
    }
2453
2454
    /**
2455
     * Returns a list of strings representing the default statuses.
2456
     *
2457
     * @return array
2458
     */
2459
    public static function getDefaultStatusList()
2460
    {
2461
        return [
2462
            self::STATUS_NEW,
2463
            self::STATUS_PENDING,
2464
            self::STATUS_UNCONFIRMED,
2465
            self::STATUS_CLOSE,
2466
            self::STATUS_FORWARDED,
2467
        ];
2468
    }
2469
2470
    /**
2471
     * @return array
2472
     */
2473
    public static function getDefaultPriorityList()
2474
    {
2475
        return [
2476
            self::PRIORITY_NORMAL,
2477
            self::PRIORITY_HIGH,
2478
            self::PRIORITY_LOW,
2479
            self::STATUS_CLOSE,
2480
            self::STATUS_FORWARDED,
2481
        ];
2482
    }
2483
2484
    /**
2485
     * Deletes the user from all the ticket system.
2486
     *
2487
     * @param int $userId
2488
     */
2489
    public static function deleteUserFromTicketSystem($userId)
2490
    {
2491
        $userId = (int) $userId;
2492
        $schema = Database::getManager()->getConnection()->getSchemaManager();
2493
2494
        if ($schema->tablesExist('ticket_assigned_log')) {
2495
            $sql = "UPDATE ticket_assigned_log SET user_id = NULL WHERE user_id = $userId";
2496
            Database::query($sql);
2497
2498
            $sql = "UPDATE ticket_assigned_log SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2499
            Database::query($sql);
2500
        }
2501
2502
        if ($schema->tablesExist('ticket_ticket')) {
2503
            $sql = "UPDATE ticket_ticket SET assigned_last_user = NULL WHERE assigned_last_user = $userId";
2504
            Database::query($sql);
2505
2506
            $sql = "UPDATE ticket_ticket SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2507
            Database::query($sql);
2508
2509
            $sql = "UPDATE ticket_ticket SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2510
            Database::query($sql);
2511
        }
2512
2513
        if ($schema->tablesExist('ticket_category')) {
2514
            $sql = "UPDATE ticket_category SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2515
            Database::query($sql);
2516
2517
            $sql = "UPDATE ticket_category SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2518
            Database::query($sql);
2519
        }
2520
2521
        if ($schema->tablesExist('ticket_category_rel_user')) {
2522
            $sql = "DELETE FROM ticket_category_rel_user WHERE user_id = $userId";
2523
            Database::query($sql);
2524
        }
2525
2526
        if ($schema->tablesExist('ticket_message')) {
2527
            $sql = "UPDATE ticket_message SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2528
            Database::query($sql);
2529
2530
            $sql = "UPDATE ticket_message SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2531
            Database::query($sql);
2532
        }
2533
2534
        if ($schema->tablesExist('ticket_message_attachments')) {
2535
            $sql = "UPDATE ticket_message_attachments SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2536
            Database::query($sql);
2537
2538
            $sql = "UPDATE ticket_message_attachments SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2539
            Database::query($sql);
2540
        }
2541
2542
        if ($schema->tablesExist('ticket_priority')) {
2543
            $sql = "UPDATE ticket_priority SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2544
            Database::query($sql);
2545
2546
            $sql = "UPDATE ticket_priority SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2547
            Database::query($sql);
2548
        }
2549
2550
        if ($schema->tablesExist('ticket_project')) {
2551
            $sql = "UPDATE ticket_project SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2552
            Database::query($sql);
2553
2554
            $sql = "UPDATE ticket_project SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2555
            Database::query($sql);
2556
        }
2557
    }
2558
2559
    /**
2560
     * @param array $userInfo
2561
     * @param int   $projectId
2562
     *
2563
     * @return bool
2564
     */
2565
    public static function userIsAllowInProject($userInfo, $projectId)
2566
    {
2567
        if (api_is_platform_admin()) {
2568
            return true;
2569
        }
2570
2571
        $allowRoleList = self::getAllowedRolesFromProject($projectId);
2572
2573
        // Check if a role was set to the project
2574
        // Project 1 is considered the default and is accessible to all users
2575
        if (!empty($allowRoleList) && is_array($allowRoleList)) {
2576
            if (in_array($userInfo['status'], $allowRoleList)) {
2577
                return true;
2578
            }
2579
        }
2580
2581
        return false;
2582
    }
2583
2584
    /**
2585
     * @param int $projectId
2586
     *
2587
     * @todo load from database instead of configuration.php setting
2588
     *
2589
     * @return array
2590
     */
2591
    public static function getAllowedRolesFromProject($projectId)
2592
    {
2593
        $options = api_get_configuration_value('ticket_project_user_roles');
2594
        if ($options) {
2595
            if (isset($options['permissions'][$projectId])) {
2596
                return $options['permissions'][$projectId];
2597
            }
2598
        }
2599
2600
        return [];
2601
    }
2602
2603
    public static function notifiyTicketUpdated(int $ticketId, int $categoryId, string $message)
2604
    {
2605
        $subject = get_lang('TicketUpdated');
2606
2607
        TicketManager::sendNotification($ticketId, $subject, $message);
2608
2609
        if (empty($categoryId)) {
2610
            return;
2611
        }
2612
2613
        $usersInCategory = self::getUsersInCategory($categoryId);
2614
2615
        if (!empty($usersInCategory)) {
2616
            foreach ($usersInCategory as $data) {
2617
                if ($data['user_id']) {
2618
                    self::sendNotification($ticketId, $subject, $message, $data['user_id']);
2619
                }
2620
            }
2621
2622
            return;
2623
        }
2624
2625
        if ('true' === api_get_setting('ticket_send_warning_to_all_admins')) {
2626
            $categoryInfo = self::getCategory($categoryId);
2627
2628
            $warningNoUsers = sprintf(
2629
                get_lang('WarningCategoryXDoesntHaveUsers'),
2630
                $categoryInfo['name']
2631
            );
2632
2633
            $message = Display::return_message($warningNoUsers, 'warning')
2634
                .$message;
2635
2636
            $adminsToNotify = UserManager::get_all_administrators();
2637
2638
            foreach ($adminsToNotify as $userId => $data) {
2639
                if ($data['active']) {
2640
                    self::sendNotification($ticketId, $subject, $message, $userId);
2641
                }
2642
            }
2643
        }
2644
    }
2645
}