Passed
Push — master ( dc373e...baaca7 )
by Julito
11:31
created

getTicketMessageAttachmentsByTicketId()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

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