Completed
Push — master ( af42cb...3888f0 )
by Julito
13:17
created

TicketManager::getTotalTicketsCurrentUser()   F

Complexity

Conditions 21
Paths 4610

Size

Total Lines 102
Code Lines 63

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 21
eloc 63
nc 4610
nop 0
dl 0
loc 102
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

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

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
377
            $ticket_code = "A".str_pad($ticketId, 11, '0', STR_PAD_LEFT);
378
            $titleCreated = sprintf(
379
                get_lang('TicketXCreated'),
380
                $ticket_code
381
            );
382
383
            Display::addFlash(Display::return_message(
384
                $titleCreated,
385
                'normal',
386
                false
387
            ));
388
389
            if ($assignedUserId != 0) {
390
                self::assignTicketToUser(
391
                    $ticketId,
392
                    $assignedUserId
393
                );
394
395
                Display::addFlash(Display::return_message(
396
                    sprintf(
397
                        get_lang('TicketXAssignedToUserX'),
398
                        $ticket_code,
399
                        $assignedUserInfo['complete_name']
400
                    ),
401
                    'normal',
402
                    false
403
                ));
404
            }
405
406
            if (!empty($fileAttachments)) {
407
                $attachmentCount = 0;
408
                foreach ($fileAttachments as $attach) {
409
                    if (!empty($attach['tmp_name'])) {
410
                        $attachmentCount++;
411
                    }
412
                }
413
                if ($attachmentCount > 0) {
414
                    self::insertMessage(
415
                        $ticketId,
416
                        '',
417
                        '',
418
                        $fileAttachments,
419
                        $currentUserId
420
                    );
421
                }
422
            }
423
424
            // Update code
425
            $sql = "UPDATE $table_support_tickets
426
                    SET code = '$ticket_code'
427
                    WHERE id = '$ticketId'";
428
            Database::query($sql);
429
430
            // Update total
431
            $sql = "UPDATE $table_support_category
432
                    SET total_tickets = total_tickets + 1
433
                    WHERE id = $category_id";
434
            Database::query($sql);
435
436
            $helpDeskMessage =
437
                '<table>
438
                        <tr>
439
                            <td width="100px"><b>'.get_lang('User').'</b></td>
440
                            <td width="400px">'.$currentUserInfo['complete_name'].'</td>
441
                        </tr>
442
                        <tr>
443
                            <td width="100px"><b>'.get_lang('Username').'</b></td>
444
                            <td width="400px">'.$currentUserInfo['username'].'</td>
445
                        </tr>
446
                        <tr>
447
                            <td width="100px"><b>'.get_lang('Email').'</b></td>
448
                            <td width="400px">'.$currentUserInfo['email'].'</td>
449
                        </tr>
450
                        <tr>
451
                            <td width="100px"><b>'.get_lang('Phone').'</b></td>
452
                            <td width="400px">'.$currentUserInfo['phone'].'</td>
453
                        </tr>
454
                        <tr>
455
                            <td width="100px"><b>'.get_lang('Date').'</b></td>
456
                            <td width="400px">'.api_convert_and_format_date($now, DATE_TIME_FORMAT_LONG).'</td>
457
                        </tr>
458
                        <tr>
459
                            <td width="100px"><b>'.get_lang('Title').'</b></td>
460
                            <td width="400px">'.$subject.'</td>
461
                        </tr>
462
                        <tr>
463
                            <td width="100px"><b>'.get_lang('Description').'</b></td>
464
                            <td width="400px">'.$content.'</td>
465
                        </tr>
466
                    </table>';
467
468
            if ($assignedUserId != 0) {
469
                $href = api_get_path(WEB_CODE_PATH).'/ticket/ticket_details.php?ticket_id='.$ticketId;
470
                $helpDeskMessage .= sprintf(
471
                    get_lang('TicketAssignedToXCheckZAtLinkY'),
472
                    $assignedUserInfo['complete_name'],
473
                    $href,
474
                    $ticketId
475
                );
476
            }
477
478
            if (empty($category_id)) {
479
                if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
480
                    $warningSubject = sprintf(
481
                        get_lang('TicketXCreatedWithNoCategory'),
482
                        $ticket_code
483
                    );
484
                    Display::addFlash(Display::return_message($warningSubject));
485
486
                    $admins = UserManager::get_all_administrators();
487
                    foreach ($admins as $userId => $data) {
488
                        if ($data['active']) {
489
                            MessageManager::send_message_simple(
490
                                $userId,
491
                                $warningSubject,
492
                                $helpDeskMessage
493
                            );
494
                        }
495
                    }
496
                }
497
            } else {
498
                $categoryInfo = self::getCategory($category_id);
499
                $usersInCategory = self::getUsersInCategory($category_id);
500
501
                $message = '<h2>'.get_lang('TicketInformation').'</h2><br />'.$helpDeskMessage;
502
503
                if (api_get_setting('ticket_warn_admin_no_user_in_category') === 'true') {
504
                    $usersInCategory = self::getUsersInCategory($category_id);
505
                    if (empty($usersInCategory)) {
506
                        $subject = sprintf(
507
                            get_lang('WarningCategoryXDoesntHaveUsers'),
508
                            $categoryInfo['name']
509
                        );
510
511
                        if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
512
                            Display::addFlash(Display::return_message(
513
                                sprintf(
514
                                    get_lang('CategoryWithNoUserNotificationSentToAdmins'),
515
                                    $categoryInfo['name']
516
                                ),
517
                                null,
518
                                false
519
                            ));
520
521
                            $admins = UserManager::get_all_administrators();
522
                            foreach ($admins as $userId => $data) {
523
                                if ($data['active']) {
524
                                    self::sendNotification(
525
                                        $ticketId,
526
                                        $subject,
527
                                        $message,
528
                                        $userId
529
                                    );
530
                                }
531
                            }
532
                        } else {
533
                            Display::addFlash(Display::return_message($subject));
534
                        }
535
                    }
536
                }
537
538
                // Send notification to all users
539
                if (!empty($usersInCategory)) {
540
                    foreach ($usersInCategory as $data) {
541
                        if ($data['user_id']) {
542
                            self::sendNotification(
543
                                $ticketId,
544
                                $subject,
545
                                $message,
546
                                $data['user_id']
547
                            );
548
                        }
549
                    }
550
                }
551
            }
552
553
            if (!empty($personalEmail)) {
554
                api_mail_html(
555
                    get_lang('VirtualSupport'),
556
                    $personalEmail,
557
                    get_lang('IncidentResentToVirtualSupport'),
558
                    $helpDeskMessage
559
                );
560
            }
561
562
            self::sendNotification(
563
                $ticketId,
564
                $titleCreated,
565
                $helpDeskMessage
566
            );
567
568
            return true;
569
        } else {
570
            return false;
571
        }
572
    }
573
574
    /**
575
     * Assign ticket to admin.
576
     *
577
     * @param int $ticketId
578
     * @param int $userId
579
     *
580
     * @return bool
581
     */
582
    public static function assignTicketToUser(
583
        $ticketId,
584
        $userId
585
    ) {
586
        $ticketId = (int) $ticketId;
587
        $userId = (int) $userId;
588
589
        if (empty($ticketId)) {
590
            return false;
591
        }
592
593
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
594
        $ticket = self::get_ticket_detail_by_id($ticketId);
595
596
        if ($ticket) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ticket of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
597
            $sql = "UPDATE $table_support_tickets
598
                    SET assigned_last_user = $userId
599
                    WHERE id = $ticketId";
600
            Database::query($sql);
601
602
            $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
603
            $params = [
604
                'ticket_id' => $ticketId,
605
                'user_id' => $userId,
606
                'sys_insert_user_id' => api_get_user_id(),
607
                'assigned_date' => api_get_utc_datetime(),
608
            ];
609
            Database::insert($table, $params);
610
611
            return true;
612
        } else {
613
            return false;
614
        }
615
    }
616
617
    /**
618
     * Insert message between Users and Admins.
619
     *
620
     * @param int    $ticketId
621
     * @param string $subject
622
     * @param string $content
623
     * @param array  $fileAttachments
624
     * @param int    $userId
625
     * @param string $status
626
     * @param bool   $sendConfirmation
627
     *
628
     * @return bool
629
     */
630
    public static function insertMessage(
631
        $ticketId,
632
        $subject,
633
        $content,
634
        $fileAttachments,
635
        $userId,
636
        $status = 'NOL',
637
        $sendConfirmation = false
638
    ) {
639
        $ticketId = (int) $ticketId;
640
        $userId = (int) $userId;
641
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
642
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
643
        if ($sendConfirmation) {
644
            $form = '<form action="ticket_details.php?ticket_id='.$ticketId.'" id="confirmticket" method="POST" >
645
                         <p>'.get_lang('TicketWasThisAnswerSatisfying').'</p>
646
                         <button class="btn btn-primary responseyes" name="response" id="responseyes" value="1">'.get_lang('Yes').'</button>
647
                         <button class="btn btn-danger responseno" name="response" id="responseno" value="0">'.get_lang('No').'</button>
648
                     </form>';
649
            $content .= $form;
650
        }
651
652
        $now = api_get_utc_datetime();
653
654
        $params = [
655
            'ticket_id' => $ticketId,
656
            'subject' => $subject,
657
            'message' => $content,
658
            'ip_address' => $_SERVER['REMOTE_ADDR'],
659
            'sys_insert_user_id' => $userId,
660
            'sys_insert_datetime' => $now,
661
            'sys_lastedit_user_id' => $userId,
662
            'sys_lastedit_datetime' => $now,
663
            'status' => $status,
664
        ];
665
        $messageId = Database::insert($table_support_messages, $params);
666
        if ($messageId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $messageId of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
667
            // update_total_message
668
            $sql = "UPDATE $table_support_tickets
669
                    SET 
670
                        sys_lastedit_user_id ='$userId',
671
                        sys_lastedit_datetime ='$now',
672
                        total_messages = (
673
                            SELECT COUNT(*) as total_messages
674
                            FROM $table_support_messages
675
                            WHERE ticket_id ='$ticketId'
676
                        )
677
                    WHERE id = $ticketId ";
678
            Database::query($sql);
679
680
            if (is_array($fileAttachments)) {
681
                foreach ($fileAttachments as $file_attach) {
682
                    if ($file_attach['error'] == 0) {
683
                        self::saveMessageAttachmentFile(
684
                            $file_attach,
685
                            $ticketId,
686
                            $messageId
687
                        );
688
                    } else {
689
                        if ($file_attach['error'] != UPLOAD_ERR_NO_FILE) {
690
                            return false;
691
                        }
692
                    }
693
                }
694
            }
695
        }
696
697
        return true;
698
    }
699
700
    /**
701
     * Attachment files when a message is sent.
702
     *
703
     * @param $file_attach
704
     * @param $ticketId
705
     * @param $message_id
706
     *
707
     * @return bool
708
     */
709
    public static function saveMessageAttachmentFile(
710
        $file_attach,
711
        $ticketId,
712
        $message_id
713
    ) {
714
        $now = api_get_utc_datetime();
715
        $userId = api_get_user_id();
716
        $ticketId = intval($ticketId);
717
        $new_file_name = add_ext_on_mime(
718
            stripslashes($file_attach['name']),
719
            $file_attach['type']
720
        );
721
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
722
        if (!filter_extension($new_file_name)) {
723
            echo Display::return_message(
724
                get_lang('UplUnableToSaveFileFilteredExtension'),
725
                'error'
726
            );
727
        } else {
728
            $result = api_upload_file('ticket_attachment', $file_attach, $ticketId);
729
            if ($result) {
730
                $safe_file_name = Database::escape_string($new_file_name);
731
                $safe_new_file_name = Database::escape_string($result['path_to_save']);
732
                $sql = "INSERT INTO $table_support_message_attachments (
733
                        filename,
734
                        path,
735
                        ticket_id,
736
                        message_id,
737
                        size,
738
                        sys_insert_user_id,
739
                        sys_insert_datetime,
740
                        sys_lastedit_user_id,
741
                        sys_lastedit_datetime
742
                    ) VALUES (
743
                        '$safe_file_name',
744
                        '$safe_new_file_name',
745
                        '$ticketId',
746
                        '$message_id',
747
                        '".$file_attach['size']."',
748
                        '$userId',
749
                        '$now',
750
                        '$userId',
751
                        '$now'
752
                    )";
753
                Database::query($sql);
754
755
                return true;
756
            }
757
        }
758
    }
759
760
    /**
761
     * Get tickets by userId.
762
     *
763
     * @param int $from
764
     * @param int $number_of_items
765
     * @param $column
766
     * @param $direction
767
     *
768
     * @return array
769
     */
770
    public static function getTicketsByCurrentUser(
771
        $from,
772
        $number_of_items,
773
        $column,
774
        $direction
775
    ) {
776
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
777
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
778
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
779
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
780
        $direction = !empty($direction) ? $direction : 'DESC';
781
        $userId = api_get_user_id();
782
        $userInfo = api_get_user_info($userId);
783
784
        if (empty($userInfo)) {
785
            return [];
786
        }
787
        $isAdmin = UserManager::is_admin($userId);
788
789
        if (!isset($_GET['project_id'])) {
790
            return [];
791
        }
792
793
        switch ($column) {
794
            case 0:
795
                $column = 'ticket_id';
796
                break;
797
            case 1:
798
                $column = 'status_name';
799
                break;
800
            case 2:
801
                $column = 'start_date';
802
                break;
803
            case 3:
804
                $column = 'sys_lastedit_datetime';
805
                break;
806
            case 4:
807
                $column = 'category_name';
808
                break;
809
            case 5:
810
                $column = 'sys_insert_user_id';
811
                break;
812
            case 6:
813
                $column = 'assigned_last_user';
814
                break;
815
            case 7:
816
                $column = 'total_messages';
817
                break;
818
            case 8:
819
                $column = 'subject';
820
                break;
821
            default:
822
                $column = 'ticket_id';
823
        }
824
825
        $sql = "SELECT DISTINCT 
826
                ticket.*,
827
                ticket.id ticket_id,
828
                status.name AS status_name,
829
                ticket.start_date,
830
                ticket.sys_lastedit_datetime,
831
                cat.name AS category_name,
832
                priority.name AS priority_name,                           
833
                ticket.total_messages AS total_messages,
834
                ticket.message AS message,
835
                ticket.subject AS subject,
836
                ticket.assigned_last_user
837
            FROM $table_support_tickets ticket 
838
            INNER JOIN $table_support_category cat
839
            ON (cat.id = ticket.category_id)
840
            INNER JOIN $table_support_priority priority
841
            ON (ticket.priority_id = priority.id)
842
            INNER JOIN $table_support_status status
843
            ON (ticket.status_id = status.id)
844
            WHERE 1=1                                
845
        ";
846
847
        $projectId = (int) $_GET['project_id'];
848
        $userIsAllowInProject = self::userIsAllowInProject($userInfo, $projectId);
849
850
        // Check if a role was set to the project
851
        if ($userIsAllowInProject == false) {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
852
            $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
853
        }
854
855
        // Search simple
856
        if (isset($_GET['submit_simple']) && $_GET['keyword'] != '') {
857
            $keyword = Database::escape_string(trim($_GET['keyword']));
858
            $sql .= " AND (
859
                      ticket.id LIKE '%$keyword%' OR
860
                      ticket.code LIKE '%$keyword%' OR
861
                      ticket.subject LIKE '%$keyword%' OR
862
                      ticket.message LIKE '%$keyword%' OR
863
                      ticket.keyword LIKE '%$keyword%' OR
864
                      ticket.source LIKE '%$keyword%' OR
865
                      cat.name LIKE '%$keyword%' OR
866
                      status.name LIKE '%$keyword%' OR
867
                      priority.name LIKE '%$keyword%' OR
868
                      ticket.personal_email LIKE '%$keyword%'                          
869
            )";
870
        }
871
872
        $keywords = [
873
            'project_id' => 'ticket.project_id',
874
            'keyword_category' => 'ticket.category_id',
875
            'keyword_assigned_to' => 'ticket.assigned_last_user',
876
            'keyword_source' => 'ticket.source ',
877
            'keyword_status' => 'ticket.status_id',
878
            'keyword_priority' => 'ticket.priority_id',
879
        ];
880
881
        foreach ($keywords as $keyword => $label) {
882
            if (isset($_GET[$keyword])) {
883
                $data = Database::escape_string(trim($_GET[$keyword]));
884
                if (!empty($data)) {
885
                    $sql .= " AND $label = '$data' ";
886
                }
887
            }
888
        }
889
890
        // Search advanced
891
        $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
892
        $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
893
        $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
894
        $keyword_range = !empty($keyword_start_date_start) && !empty($keyword_start_date_end);
895
896
        if ($keyword_range == false && $keyword_start_date_start != '') {
0 ignored issues
show
Coding Style Best Practice introduced by
It seems like you are loosely comparing two booleans. Considering using the strict comparison === instead.

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

Loading history...
897
            $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start' ";
898
        }
899
        if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
900
            $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
901
                      AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
902
        }
903
904
        if ($keyword_course != '') {
905
            $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
906
            $sql .= " AND ticket.course_id IN ( 
907
                     SELECT id FROM $course_table
908
                     WHERE (
909
                        title LIKE '%$keyword_course%' OR 
910
                        code LIKE '%$keyword_course%' OR 
911
                        visual_code LIKE '%$keyword_course%'
912
                     )
913
            )";
914
        }
915
        $sql .= " ORDER BY $column $direction";
916
        $sql .= " LIMIT $from, $number_of_items";
917
918
        $result = Database::query($sql);
919
        $tickets = [];
920
        $webPath = api_get_path(WEB_PATH);
921
        while ($row = Database::fetch_assoc($result)) {
922
            $userInfo = api_get_user_info($row['sys_insert_user_id']);
923
            $hrefUser = $webPath.'main/admin/user_information.php?user_id='.$userInfo['user_id'];
924
            $name = "<a href='$hrefUser'> {$userInfo['complete_name_with_username']} </a>";
925
            if ($row['assigned_last_user'] != 0) {
926
                $assignedUserInfo = api_get_user_info($row['assigned_last_user']);
927
                if (!empty($assignedUserInfo)) {
928
                    $hrefResp = $webPath.'main/admin/user_information.php?user_id='.$assignedUserInfo['user_id'];
929
                    $row['assigned_last_user'] = "<a href='$hrefResp'> {$assignedUserInfo['complete_name_with_username']} </a>";
930
                } else {
931
                    $row['assigned_last_user'] = get_lang('UnknownUser');
932
                }
933
            } else {
934
                if ($row['status_id'] !== self::STATUS_FORWARDED) {
935
                    $row['assigned_last_user'] = '<span style="color:#ff0000;">'.get_lang('ToBeAssigned').'</span>';
936
                } else {
937
                    $row['assigned_last_user'] = '<span style="color:#00ff00;">'.get_lang('MessageResent').'</span>';
938
                }
939
            }
940
941
            switch ($row['source']) {
942
                case self::SOURCE_PRESENTIAL:
943
                    $img_source = 'icons/32/user.png';
944
                    break;
945
                case self::SOURCE_EMAIL:
946
                    $img_source = 'icons/32/mail.png';
947
                    break;
948
                case self::SOURCE_PHONE:
949
                    $img_source = 'icons/32/event.png';
950
                    break;
951
                default:
952
                    $img_source = 'icons/32/ticket.png';
953
                    break;
954
            }
955
956
            $row['start_date'] = Display::dateToStringAgoAndLongDate($row['start_date']);
957
            $row['sys_lastedit_datetime'] = Display::dateToStringAgoAndLongDate($row['sys_lastedit_datetime']);
958
959
            $icon = Display::return_icon(
960
                $img_source,
961
                get_lang('Info'),
962
                ['style' => 'margin-right: 10px; float: left;']
963
            );
964
965
            $icon .= '<a href="ticket_details.php?ticket_id='.$row['id'].'">'.$row['code'].'</a>';
966
967
            if ($isAdmin) {
968
                $ticket = [
969
                    $icon.' '.$row['subject'],
970
                    $row['status_name'],
971
                    $row['start_date'],
972
                    $row['sys_lastedit_datetime'],
973
                    $row['category_name'],
974
                    $name,
975
                    $row['assigned_last_user'],
976
                    $row['total_messages'],
977
                ];
978
            } else {
979
                $ticket = [
980
                    $icon.' '.$row['subject'],
981
                    $row['status_name'],
982
                    $row['start_date'],
983
                    $row['sys_lastedit_datetime'],
984
                    $row['category_name'],
985
                ];
986
            }
987
            if ($isAdmin) {
988
                $ticket['0'] .= '&nbsp;&nbsp;<a  href="javascript:void(0)" onclick="load_history_ticket(\'div_'.$row['ticket_id'].'\','.$row['ticket_id'].')">
989
					<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').'"/>
990
					<div class="blackboard_hide" id="div_'.$row['ticket_id'].'">&nbsp;&nbsp;</div>
991
					</a>&nbsp;&nbsp;';
992
            }
993
            $tickets[] = $ticket;
994
        }
995
996
        return $tickets;
997
    }
998
999
    /**
1000
     * @return int
1001
     */
1002
    public static function getTotalTicketsCurrentUser()
1003
    {
1004
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1005
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1006
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1007
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1008
1009
        $userInfo = api_get_user_info();
1010
        if (empty($userInfo)) {
1011
            return 0;
1012
        }
1013
        $userId = $userInfo['id'];
1014
1015
        if (!isset($_GET['project_id'])) {
1016
            return 0;
1017
        }
1018
1019
        $sql = "SELECT COUNT(ticket.id) AS total
1020
                FROM $table_support_tickets ticket
1021
                INNER JOIN $table_support_category cat
1022
                ON (cat.id = ticket.category_id)
1023
                INNER JOIN $table_support_priority priority
1024
                ON (ticket.priority_id = priority.id)
1025
                INNER JOIN $table_support_status status
1026
                ON (ticket.status_id = status.id)
1027
	            WHERE 1 = 1";
1028
1029
        $projectId = (int) $_GET['project_id'];
1030
        $allowRoleList = self::getAllowedRolesFromProject($projectId);
1031
1032
        // Check if a role was set to the project
1033
        if (!empty($allowRoleList) && is_array($allowRoleList)) {
1034
            if (!in_array($userInfo['status'], $allowRoleList)) {
1035
                $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
1036
            }
1037
        } else {
1038
            if (!api_is_platform_admin()) {
1039
                $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
1040
            }
1041
        }
1042
1043
        // Search simple
1044
        if (isset($_GET['submit_simple'])) {
1045
            if ($_GET['keyword'] != '') {
1046
                $keyword = Database::escape_string(trim($_GET['keyword']));
1047
                $sql .= " AND (
1048
                          ticket.code LIKE '%$keyword%' OR
1049
                          ticket.subject LIKE '%$keyword%' OR
1050
                          ticket.message LIKE '%$keyword%' OR
1051
                          ticket.keyword LIKE '%$keyword%' OR
1052
                          ticket.personal_email LIKE '%$keyword%' OR
1053
                          ticket.source LIKE '%$keyword%'
1054
                )";
1055
            }
1056
        }
1057
1058
        $keywords = [
1059
            'project_id' => 'ticket.project_id',
1060
            'keyword_category' => 'ticket.category_id',
1061
            'keyword_assigned_to' => 'ticket.assigned_last_user',
1062
            'keyword_source' => 'ticket.source',
1063
            'keyword_status' => 'ticket.status_id',
1064
            'keyword_priority' => 'ticket.priority_id',
1065
        ];
1066
1067
        foreach ($keywords as $keyword => $sqlLabel) {
1068
            if (isset($_GET[$keyword])) {
1069
                $data = Database::escape_string(trim($_GET[$keyword]));
1070
                $sql .= " AND $sqlLabel = '$data' ";
1071
            }
1072
        }
1073
1074
        // Search advanced
1075
        $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
1076
        $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
1077
        $keyword_range = isset($_GET['keyword_dates']) ? Database::escape_string(trim($_GET['keyword_dates'])) : '';
1078
        $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
1079
1080
        if ($keyword_range == false && $keyword_start_date_start != '') {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $keyword_range of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
1081
            $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
1082
        }
1083
        if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
1084
            $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
1085
                      AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
1086
        }
1087
        if ($keyword_course != '') {
1088
            $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1089
            $sql .= " AND ticket.course_id IN (  
1090
                        SELECT id
1091
                        FROM $course_table
1092
                        WHERE (
1093
                            title LIKE '%$keyword_course%' OR 
1094
                            code LIKE '%$keyword_course%' OR 
1095
                            visual_code LIKE '%$keyword_course%'
1096
                        )
1097
                   ) ";
1098
        }
1099
1100
        $res = Database::query($sql);
1101
        $obj = Database::fetch_object($res);
1102
1103
        return (int) $obj->total;
1104
    }
1105
1106
    /**
1107
     * @param int $id
1108
     *
1109
     * @return false|MessageAttachment
1110
     */
1111
    public static function getTicketMessageAttachment($id)
1112
    {
1113
        $id = (int) $id;
1114
        $em = Database::getManager();
1115
        $item = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->find($id);
1116
        if ($item) {
1117
            return $item;
1118
        }
1119
1120
        return false;
1121
    }
1122
1123
    /**
1124
     * @param int $id
1125
     *
1126
     * @return array
1127
     */
1128
    public static function getTicketMessageAttachmentsByTicketId($id)
1129
    {
1130
        $id = (int) $id;
1131
        $em = Database::getManager();
1132
        $items = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->findBy(['ticket' => $id]);
1133
        if ($items) {
1134
            return $items;
1135
        }
1136
1137
        return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type array.
Loading history...
1138
    }
1139
1140
    /**
1141
     * @param int $ticketId
1142
     *
1143
     * @return array
1144
     */
1145
    public static function get_ticket_detail_by_id($ticketId)
1146
    {
1147
        $ticketId = intval($ticketId);
1148
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1149
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1150
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1151
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1152
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1153
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
1154
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1155
1156
        $sql = "SELECT
1157
                    ticket.*, 
1158
                    cat.name,
1159
                    status.name as status, 
1160
                    priority.name priority
1161
                FROM $table_support_tickets ticket
1162
                INNER JOIN $table_support_category cat
1163
                ON (cat.id = ticket.category_id)
1164
                INNER JOIN $table_support_priority priority
1165
                ON (priority.id = ticket.priority_id)
1166
                INNER JOIN $table_support_status status
1167
                ON (status.id = ticket.status_id)
1168
		        WHERE
1169
                    ticket.id = $ticketId ";
1170
        $result = Database::query($sql);
1171
        $ticket = [];
1172
        if (Database::num_rows($result) > 0) {
1173
            while ($row = Database::fetch_assoc($result)) {
1174
                $row['course'] = null;
1175
                $row['start_date_from_db'] = $row['start_date'];
1176
                $row['start_date'] = api_convert_and_format_date(
1177
                    api_get_local_time($row['start_date']),
1178
                    DATE_TIME_FORMAT_LONG,
1179
                    api_get_timezone()
1180
                );
1181
                $row['end_date_from_db'] = $row['end_date'];
1182
                $row['end_date'] = api_convert_and_format_date(
1183
                    api_get_local_time($row['end_date']),
1184
                    DATE_TIME_FORMAT_LONG,
1185
                    api_get_timezone()
1186
                );
1187
                $row['sys_lastedit_datetime_from_db'] = $row['sys_lastedit_datetime'];
1188
                $row['sys_lastedit_datetime'] = api_convert_and_format_date(
1189
                    api_get_local_time($row['sys_lastedit_datetime']),
1190
                    DATE_TIME_FORMAT_LONG,
1191
                    api_get_timezone()
1192
                );
1193
                $row['course_url'] = null;
1194
                if ($row['course_id'] != 0) {
1195
                    $course = api_get_course_info_by_id($row['course_id']);
1196
                    $sessionId = 0;
1197
                    if ($row['session_id']) {
1198
                        $sessionId = $row['session_id'];
1199
                    }
1200
                    if ($course) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $course of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
1201
                        $row['course_url'] = '<a href="'.$course['course_public_url'].'?id_session='.$sessionId.'">'.$course['name'].'</a>';
1202
                    }
1203
                }
1204
1205
                $userInfo = api_get_user_info($row['sys_insert_user_id']);
1206
                $row['user_url'] = '<a href="'.api_get_path(WEB_PATH).'main/admin/user_information.php?user_id='.$userInfo['user_id'].'">
1207
                '.$userInfo['complete_name'].'</a>';
1208
                $ticket['usuario'] = $userInfo;
1209
                $ticket['ticket'] = $row;
1210
            }
1211
1212
            $sql = "SELECT *, message.id as message_id 
1213
                    FROM $table_support_messages message 
1214
                    INNER JOIN $table_main_user user
1215
                    ON (message.sys_insert_user_id = user.user_id)
1216
                    WHERE
1217
                        message.ticket_id = '$ticketId' ";
1218
            $result = Database::query($sql);
1219
            $ticket['messages'] = [];
1220
            $attach_icon = Display::return_icon('attachment.gif', '');
1221
            $webPath = api_get_path(WEB_CODE_PATH);
1222
            while ($row = Database::fetch_assoc($result)) {
1223
                $message = $row;
1224
                $message['admin'] = UserManager::is_admin($message['user_id']);
1225
                $message['user_info'] = api_get_user_info($message['user_id']);
1226
                $sql = "SELECT *
1227
                        FROM $table_support_message_attachments
1228
                        WHERE
1229
                            message_id = ".$row['message_id']." AND
1230
                            ticket_id = $ticketId";
1231
1232
                $result_attach = Database::query($sql);
1233
                while ($row2 = Database::fetch_assoc($result_attach)) {
1234
                    $archiveURL = $webPath.'ticket/download.php?ticket_id='.$ticketId.'&id='.$row2['id'];
1235
                    $row2['attachment_link'] = $attach_icon.'&nbsp;<a href="'.$archiveURL.'">'.$row2['filename'].'</a>&nbsp;('.$row2['size'].')';
1236
                    $message['attachments'][] = $row2;
1237
                }
1238
                $ticket['messages'][] = $message;
1239
            }
1240
        }
1241
1242
        return $ticket;
1243
    }
1244
1245
    /**
1246
     * @param int $ticketId
1247
     * @param int $userId
1248
     *
1249
     * @return bool
1250
     */
1251
    public static function update_message_status($ticketId, $userId)
1252
    {
1253
        $ticketId = intval($ticketId);
1254
        $userId = intval($userId);
1255
        $table_support_messages = Database::get_main_table(
1256
            TABLE_TICKET_MESSAGE
1257
        );
1258
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1259
        $now = api_get_utc_datetime();
1260
        $sql = "UPDATE $table_support_messages
1261
                SET
1262
                    status = 'LEI',
1263
                    sys_lastedit_user_id ='".api_get_user_id()."',
1264
                    sys_lastedit_datetime ='".$now."'
1265
                WHERE ticket_id ='$ticketId' ";
1266
1267
        if (api_is_platform_admin()) {
1268
            $sql .= " AND sys_insert_user_id = '$userId'";
1269
        } else {
1270
            $sql .= " AND sys_insert_user_id != '$userId'";
1271
        }
1272
        $result = Database::query($sql);
1273
        if (Database::affected_rows($result) > 0) {
1274
            Database::query(
1275
                "UPDATE $table_support_tickets SET
1276
                    status_id = '".self::STATUS_PENDING."'
1277
                 WHERE id ='$ticketId' AND status_id = '".self::STATUS_NEW."'"
1278
            );
1279
1280
            return true;
1281
        } else {
1282
            return false;
1283
        }
1284
    }
1285
1286
    /**
1287
     * Send notification to a user through the internal messaging system.
1288
     *
1289
     * @param int    $ticketId
1290
     * @param string $title
1291
     * @param string $message
1292
     * @param int    $onlyToUserId
1293
     *
1294
     * @return bool
1295
     */
1296
    public static function sendNotification($ticketId, $title, $message, $onlyToUserId = 0)
1297
    {
1298
        $ticketInfo = self::get_ticket_detail_by_id($ticketId);
1299
1300
        if (empty($ticketInfo)) {
1301
            return false;
1302
        }
1303
1304
        $assignedUserInfo = api_get_user_info($ticketInfo['ticket']['assigned_last_user']);
1305
        $requestUserInfo = $ticketInfo['usuario'];
1306
        $ticketCode = $ticketInfo['ticket']['code'];
1307
        $status = $ticketInfo['ticket']['status'];
1308
        $priority = $ticketInfo['ticket']['priority'];
1309
1310
        // Subject
1311
        $titleEmail = "[$ticketCode] $title";
1312
1313
        // Content
1314
        $href = api_get_path(WEB_CODE_PATH).'/ticket/ticket_details.php?ticket_id='.$ticketId;
1315
        $ticketUrl = Display::url($ticketCode, $href);
1316
        $messageEmail = get_lang('TicketNum').": $ticketUrl <br />";
1317
        $messageEmail .= get_lang('Status').": $status <br />";
1318
        $messageEmail .= get_lang('Priority').": $priority <br />";
1319
        $messageEmail .= '<hr /><br />';
1320
        $messageEmail .= $message;
1321
        $currentUserId = api_get_user_id();
1322
        $attachmentList = [];
1323
        $attachments = self::getTicketMessageAttachmentsByTicketId($ticketId);
1324
        if (!empty($attachments)) {
1325
            /** @var MessageAttachment $attachment */
1326
            foreach ($attachments as $attachment) {
1327
                $file = api_get_uploaded_file(
1328
                    'ticket_attachment',
1329
                    $ticketId,
1330
                    $attachment->getPath()
1331
                );
1332
                if (!empty($file)) {
1333
                    $attachmentList[] = [
1334
                        'tmp_name' => api_get_uploaded_file(
1335
                            'ticket_attachment',
1336
                            $ticketId,
1337
                            $attachment->getPath()
1338
                        ),
1339
                        'size' => $attachment->getSize(),
1340
                        'name' => $attachment->getFilename(),
1341
                        'error' => 0,
1342
                    ];
1343
                }
1344
            }
1345
        }
1346
1347
        if (!empty($onlyToUserId)) {
1348
            // Send only to specific user
1349
            if ($currentUserId != $onlyToUserId) {
1350
                MessageManager::send_message_simple(
1351
                    $onlyToUserId,
1352
                    $titleEmail,
1353
                    $messageEmail,
1354
                    0,
1355
                    false,
1356
                    false,
1357
                    [],
1358
                    false,
1359
                    $attachmentList
1360
                );
1361
            }
1362
        } else {
1363
            // Send to assigned user and to author
1364
            if ($requestUserInfo && $currentUserId != $requestUserInfo['id']) {
1365
                MessageManager::send_message_simple(
1366
                    $requestUserInfo['id'],
1367
                    $titleEmail,
1368
                    $messageEmail,
1369
                    0,
1370
                    false,
1371
                    false,
1372
                    [],
1373
                    false,
1374
                    $attachmentList
1375
                );
1376
            }
1377
1378
            if ($assignedUserInfo &&
0 ignored issues
show
Bug Best Practice introduced by
The expression $assignedUserInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
1379
                $requestUserInfo['id'] != $assignedUserInfo['id'] &&
1380
                $currentUserId != $assignedUserInfo['id']
1381
            ) {
1382
                MessageManager::send_message_simple(
1383
                    $assignedUserInfo['id'],
1384
                    $titleEmail,
1385
                    $messageEmail,
1386
                    0,
1387
                    false,
1388
                    false,
1389
                    [],
1390
                    false,
1391
                    $attachmentList
1392
                );
1393
            }
1394
        }
1395
    }
1396
1397
    /**
1398
     * @param array $params
1399
     * @param int   $ticketId
1400
     * @param int   $userId
1401
     *
1402
     * @return bool
1403
     */
1404
    public static function updateTicket(
1405
        $params,
1406
        $ticketId,
1407
        $userId
1408
    ) {
1409
        $now = api_get_utc_datetime();
1410
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
1411
        $newParams = [
1412
            'priority_id' => isset($params['priority_id']) ? $params['priority_id'] : '',
1413
            'status_id' => isset($params['status_id']) ? $params['status_id'] : '',
1414
            'sys_lastedit_user_id' => $userId,
1415
            'sys_lastedit_datetime' => $now,
1416
        ];
1417
        Database::update($table, $newParams, ['id = ? ' => $ticketId]);
1418
1419
        return true;
1420
    }
1421
1422
    /**
1423
     * @param int $status_id
1424
     * @param int $ticketId
1425
     * @param int $userId
1426
     *
1427
     * @return bool
1428
     */
1429
    public static function update_ticket_status(
1430
        $status_id,
1431
        $ticketId,
1432
        $userId
1433
    ) {
1434
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1435
1436
        $ticketId = intval($ticketId);
1437
        $status_id = intval($status_id);
1438
        $userId = intval($userId);
1439
1440
        $now = api_get_utc_datetime();
1441
        $sql = "UPDATE $table_support_tickets
1442
                SET
1443
                    status_id = '$status_id',
1444
                    sys_lastedit_user_id ='$userId',
1445
                    sys_lastedit_datetime ='".$now."'
1446
                WHERE id ='$ticketId'";
1447
        $result = Database::query($sql);
1448
1449
        if (Database::affected_rows($result) > 0) {
1450
            self::sendNotification(
1451
                $ticketId,
1452
                get_lang('TicketUpdated'),
1453
                get_lang('TicketUpdated')
1454
            );
1455
1456
            return true;
1457
        } else {
1458
            return false;
1459
        }
1460
    }
1461
1462
    /**
1463
     * @return mixed
1464
     */
1465
    public static function getNumberOfMessages()
1466
    {
1467
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1468
        $table_support_messages = Database::get_main_table(
1469
            TABLE_TICKET_MESSAGE
1470
        );
1471
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1472
        $table_main_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1473
        $user_info = api_get_user_info();
1474
        $userId = $user_info['user_id'];
1475
        $sql = "SELECT COUNT(DISTINCT ticket.id) AS unread
1476
                FROM $table_support_tickets ticket,
1477
                $table_support_messages message ,
1478
                $table_main_user user
1479
                WHERE
1480
                    ticket.id = message.ticket_id AND
1481
                    message.status = 'NOL' AND
1482
                    user.user_id = message.sys_insert_user_id ";
1483
        if (!api_is_platform_admin()) {
1484
            $sql .= " AND ticket.request_user = '$userId'
1485
                      AND user_id IN (SELECT user_id FROM $table_main_admin)  ";
1486
        } else {
1487
            $sql .= " AND user_id NOT IN (SELECT user_id FROM $table_main_admin)
1488
                      AND ticket.status_id != '".self::STATUS_FORWARDED."'";
1489
        }
1490
        $sql .= "  AND ticket.project_id != '' ";
1491
        $res = Database::query($sql);
1492
        $obj = Database::fetch_object($res);
1493
1494
        return $obj->unread;
1495
    }
1496
1497
    /**
1498
     * @param int $ticketId
1499
     * @param int $userId
1500
     */
1501
    public static function send_alert($ticketId, $userId)
1502
    {
1503
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1504
        $now = api_get_utc_datetime();
1505
1506
        $ticketId = intval($ticketId);
1507
        $userId = intval($userId);
1508
1509
        $sql = "UPDATE $table_support_tickets SET
1510
                  priority_id = '".self::PRIORITY_HIGH."',
1511
                  sys_lastedit_user_id ='$userId',
1512
                  sys_lastedit_datetime ='$now'
1513
                WHERE id = '$ticketId'";
1514
        Database::query($sql);
1515
    }
1516
1517
    /**
1518
     * @param int $ticketId
1519
     * @param int $userId
1520
     */
1521
    public static function close_ticket($ticketId, $userId)
1522
    {
1523
        $ticketId = intval($ticketId);
1524
        $userId = intval($userId);
1525
1526
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1527
        $now = api_get_utc_datetime();
1528
        $sql = "UPDATE $table_support_tickets SET
1529
                    status_id = '".self::STATUS_CLOSE."',
1530
                    sys_lastedit_user_id ='$userId',
1531
                    sys_lastedit_datetime ='".$now."',
1532
                    end_date ='$now'
1533
                WHERE id ='$ticketId'";
1534
        Database::query($sql);
1535
1536
        self::sendNotification(
1537
            $ticketId,
1538
            get_lang('TicketClosed'),
1539
            get_lang('TicketClosed')
1540
        );
1541
    }
1542
1543
    /**
1544
     * Close old tickets.
1545
     */
1546
    public static function close_old_tickets()
1547
    {
1548
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
1549
        $now = api_get_utc_datetime();
1550
        $userId = api_get_user_id();
1551
        $sql = "UPDATE $table
1552
                SET
1553
                    status_id = '".self::STATUS_CLOSE."',
1554
                    sys_lastedit_user_id ='$userId',
1555
                    sys_lastedit_datetime ='$now',
1556
                    end_date = '$now'
1557
                WHERE
1558
                    DATEDIFF('$now', sys_lastedit_datetime) > 7 AND
1559
                    status_id != '".self::STATUS_CLOSE."' AND
1560
                    status_id != '".self::STATUS_NEW."' AND
1561
                    status_id != '".self::STATUS_FORWARDED."'";
1562
        Database::query($sql);
1563
    }
1564
1565
    /**
1566
     * @param int $ticketId
1567
     *
1568
     * @return array
1569
     */
1570
    public static function get_assign_log($ticketId)
1571
    {
1572
        $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
1573
        $ticketId = intval($ticketId);
1574
1575
        $sql = "SELECT * FROM $table
1576
                WHERE ticket_id = $ticketId
1577
                ORDER BY assigned_date DESC";
1578
        $result = Database::query($sql);
1579
        $history = [];
1580
        $webpath = api_get_path(WEB_PATH);
1581
        while ($row = Database::fetch_assoc($result)) {
1582
            if ($row['user_id'] != 0) {
1583
                $assignuser = api_get_user_info($row['user_id']);
1584
                $row['assignuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['user_id'].'"  target="_blank">'.
1585
                $assignuser['username'].'</a>';
1586
            } else {
1587
                $row['assignuser'] = get_lang('Unassign');
1588
            }
1589
            $row['assigned_date'] = Display::dateToStringAgoAndLongDate($row['assigned_date']);
1590
            $insertuser = api_get_user_info($row['sys_insert_user_id']);
1591
            $row['insertuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['sys_insert_user_id'].'"  target="_blank">'.
1592
                $insertuser['username'].'</a>';
1593
            $history[] = $row;
1594
        }
1595
1596
        return $history;
1597
    }
1598
1599
    /**
1600
     * @param $from
1601
     * @param $number_of_items
1602
     * @param $column
1603
     * @param $direction
1604
     * @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...
1605
     *
1606
     * @return array
1607
     */
1608
    public static function export_tickets_by_user_id(
1609
        $from,
1610
        $number_of_items,
1611
        $column,
0 ignored issues
show
Unused Code introduced by
The parameter $column is not used and could be removed. ( Ignorable by Annotation )

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

1611
        /** @scrutinizer ignore-unused */ $column,

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
1612
        $direction,
1613
        $userId = null
1614
    ) {
1615
        $from = intval($from);
1616
        $number_of_items = intval($number_of_items);
1617
        $table_support_category = Database::get_main_table(
1618
            TABLE_TICKET_CATEGORY
1619
        );
1620
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1621
        $table_support_priority = Database::get_main_table(
1622
            TABLE_TICKET_PRIORITY
1623
        );
1624
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1625
        $table_support_messages = Database::get_main_table(
1626
            TABLE_TICKET_MESSAGE
1627
        );
1628
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1629
1630
        if (is_null($direction)) {
1631
            $direction = "DESC";
1632
        }
1633
        if (is_null($userId) || $userId == 0) {
1634
            $userId = api_get_user_id();
1635
        }
1636
1637
        $sql = "SELECT
1638
                    ticket.code,
1639
                    ticket.sys_insert_datetime,
1640
                    ticket.sys_lastedit_datetime,
1641
                    cat.name as category,
1642
                    CONCAT(user.lastname,' ', user.firstname) AS fullname,
1643
                    status.name as status,
1644
                    ticket.total_messages as messages,
1645
                    ticket.assigned_last_user as responsable
1646
                FROM $table_support_tickets ticket,
1647
                $table_support_category cat ,
1648
                $table_support_priority priority,
1649
                $table_support_status status ,
1650
                $table_main_user user
1651
                WHERE
1652
                    cat.id = ticket.category_id
1653
                    AND ticket.priority_id = priority.id
1654
                    AND ticket.status_id = status.id
1655
                    AND user.user_id = ticket.request_user ";
1656
        // Search simple
1657
        if (isset($_GET['submit_simple'])) {
1658
            if ($_GET['keyword'] !== '') {
1659
                $keyword = Database::escape_string(trim($_GET['keyword']));
1660
                $sql .= " AND (ticket.code = '$keyword'
1661
                          OR user.firstname LIKE '%$keyword%'
1662
                          OR user.lastname LIKE '%$keyword%'
1663
                          OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword%'
1664
                          OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword%'
1665
                          OR user.username LIKE '%$keyword%')  ";
1666
            }
1667
        }
1668
        // Search advanced
1669
        if (isset($_GET['submit_advanced'])) {
1670
            $keyword_category = Database::escape_string(
1671
                trim($_GET['keyword_category'])
1672
            );
1673
            $keyword_request_user = Database::escape_string(
1674
                trim($_GET['keyword_request_user'])
1675
            );
1676
            $keywordAssignedTo = (int) $_GET['keyword_assigned_to'];
1677
            $keyword_start_date_start = Database::escape_string(
1678
                trim($_GET['keyword_start_date_start'])
1679
            );
1680
            $keyword_start_date_end = Database::escape_string(
1681
                trim($_GET['keyword_start_date_end'])
1682
            );
1683
            $keyword_status = Database::escape_string(
1684
                trim($_GET['keyword_status'])
1685
            );
1686
            $keyword_source = Database::escape_string(
1687
                trim($_GET['keyword_source'])
1688
            );
1689
            $keyword_priority = Database::escape_string(
1690
                trim($_GET['keyword_priority'])
1691
            );
1692
            $keyword_range = Database::escape_string(
1693
                trim($_GET['keyword_dates'])
1694
            );
1695
            $keyword_unread = Database::escape_string(
1696
                trim($_GET['keyword_unread'])
1697
            );
1698
            $keyword_course = Database::escape_string(
1699
                trim($_GET['keyword_course'])
1700
            );
1701
1702
            if ($keyword_category != '') {
1703
                $sql .= " AND ticket.category_id = '$keyword_category'  ";
1704
            }
1705
            if ($keyword_request_user != '') {
1706
                $sql .= " AND (ticket.request_user = '$keyword_request_user'
1707
                          OR user.firstname LIKE '%$keyword_request_user%'
1708
                          OR user.official_code LIKE '%$keyword_request_user%'
1709
                          OR user.lastname LIKE '%$keyword_request_user%'
1710
                          OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword_request_user%'
1711
                          OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword_request_user%'
1712
                          OR user.username LIKE '%$keyword_request_user%') ";
1713
            }
1714
            if (!empty($keywordAssignedTo)) {
1715
                $sql .= " AND ticket.assigned_last_user = $keywordAssignedTo ";
1716
            }
1717
            if ($keyword_status != '') {
1718
                $sql .= " AND ticket.status_id = '$keyword_status'  ";
1719
            }
1720
            if ($keyword_range == '' && $keyword_start_date_start != '') {
1721
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
1722
            }
1723
            if ($keyword_range == '1' && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
1724
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
1725
                          AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
1726
            }
1727
            if ($keyword_priority != '') {
1728
                $sql .= " AND ticket.priority_id = '$keyword_priority'  ";
1729
            }
1730
            if ($keyword_source != '') {
1731
                $sql .= " AND ticket.source = '$keyword_source' ";
1732
            }
1733
            if ($keyword_priority != '') {
1734
                $sql .= " AND ticket.priority_id = '$keyword_priority' ";
1735
            }
1736
            if ($keyword_course != '') {
1737
                $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1738
                $sql .= " AND ticket.course_id IN ( ";
1739
                $sql .= "SELECT id
1740
                         FROM $course_table
1741
                         WHERE (title LIKE '%$keyword_course%'
1742
                         OR code LIKE '%$keyword_course%'
1743
                         OR visual_code LIKE '%$keyword_course%' )) ";
1744
            }
1745
            if ($keyword_unread == 'yes') {
1746
                $sql .= " AND ticket.id IN (
1747
                          SELECT ticket.id
1748
                          FROM $table_support_tickets ticket,
1749
                          $table_support_messages message,
1750
                          $table_main_user user
1751
                          WHERE ticket.id = message.ticket_id
1752
                          AND message.status = 'NOL'
1753
                          AND message.sys_insert_user_id = user.user_id
1754
                          AND user.status != 1   AND ticket.status_id != '".self::STATUS_FORWARDED."'
1755
                          GROUP BY ticket.id)";
1756
            } else {
1757
                if ($keyword_unread == 'no') {
1758
                    $sql .= " AND ticket.id NOT IN (
1759
                              SELECT ticket.id
1760
                              FROM  $table_support_tickets ticket,
1761
                              $table_support_messages message,
1762
                              $table_main_user user
1763
                              WHERE ticket.id = message.ticket_id
1764
                              AND message.status = 'NOL'
1765
                              AND message.sys_insert_user_id = user.user_id
1766
                              AND user.status != 1
1767
                              AND ticket.status_id != '".self::STATUS_FORWARDED."'
1768
                             GROUP BY ticket.id)";
1769
                }
1770
            }
1771
        }
1772
1773
        $sql .= " LIMIT $from,$number_of_items";
1774
1775
        $result = Database::query($sql);
1776
        $tickets[0] = [
0 ignored issues
show
Comprehensibility Best Practice introduced by
$tickets was never initialized. Although not strictly required by PHP, it is generally a good practice to add $tickets = array(); before regardless.
Loading history...
1777
            utf8_decode('Ticket#'),
1778
            utf8_decode('Fecha'),
1779
            utf8_decode('Fecha Edicion'),
1780
            utf8_decode('Categoria'),
1781
            utf8_decode('Usuario'),
1782
            utf8_decode('Estado'),
1783
            utf8_decode('Mensajes'),
1784
            utf8_decode('Responsable'),
1785
            utf8_decode('Programa'),
1786
        ];
1787
1788
        while ($row = Database::fetch_assoc($result)) {
1789
            if ($row['responsable'] != 0) {
1790
                $row['responsable'] = api_get_user_info($row['responsable']);
1791
                $row['responsable'] = $row['responsable']['firstname'].' '.$row['responsable']['lastname'];
1792
            }
1793
            $row['sys_insert_datetime'] = api_format_date(
1794
                $row['sys_insert_datetime'],
1795
                '%d/%m/%y - %I:%M:%S %p'
1796
            );
1797
            $row['sys_lastedit_datetime'] = api_format_date(
1798
                $row['sys_lastedit_datetime'],
1799
                '%d/%m/%y - %I:%M:%S %p'
1800
            );
1801
            $row['category'] = utf8_decode($row['category']);
1802
            $row['programa'] = utf8_decode($row['fullname']);
1803
            $row['fullname'] = utf8_decode($row['fullname']);
1804
            $row['responsable'] = utf8_decode($row['responsable']);
1805
            $tickets[] = $row;
1806
        }
1807
1808
        return $tickets;
1809
    }
1810
1811
    /**
1812
     * @param string $url
1813
     * @param int    $projectId
1814
     *
1815
     * @return FormValidator
1816
     */
1817
    public static function getCategoryForm($url, $projectId)
1818
    {
1819
        $form = new FormValidator('category', 'post', $url);
1820
        $form->addText('name', get_lang('Name'));
1821
        $form->addHtmlEditor('description', get_lang('Description'));
1822
        $form->addHidden('project_id', $projectId);
1823
        $form->addButtonUpdate(get_lang('Save'));
1824
1825
        return $form;
1826
    }
1827
1828
    /**
1829
     * @return array
1830
     */
1831
    public static function getStatusList()
1832
    {
1833
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
1834
1835
        $list = [];
1836
        /** @var Status $row */
1837
        foreach ($items as $row) {
1838
            $list[$row->getId()] = $row->getName();
1839
        }
1840
1841
        return $list;
1842
    }
1843
1844
    /**
1845
     * @return array
1846
     */
1847
    public static function getTicketsFromCriteria($criteria)
1848
    {
1849
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Ticket')->findBy($criteria);
1850
1851
        $list = [];
1852
        /** @var Ticket $row */
1853
        foreach ($items as $row) {
1854
            $list[$row->getId()] = $row->getCode();
1855
        }
1856
1857
        return $list;
1858
    }
1859
1860
    /**
1861
     * @param string $code
1862
     *
1863
     * @return int
1864
     */
1865
    public static function getStatusIdFromCode($code)
1866
    {
1867
        $item = Database::getManager()
1868
            ->getRepository('ChamiloTicketBundle:Status')
1869
            ->findOneBy(['code' => $code])
1870
        ;
1871
        if ($item) {
1872
            return $item->getId();
1873
        }
1874
1875
        return 0;
1876
    }
1877
1878
    /**
1879
     * @return array
1880
     */
1881
    public static function getPriorityList()
1882
    {
1883
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
1884
1885
        $list = [];
1886
        /** @var Priority $row */
1887
        foreach ($projects as $row) {
1888
            $list[$row->getId()] = $row->getName();
1889
        }
1890
1891
        return $list;
1892
    }
1893
1894
    /**
1895
     * @return array
1896
     */
1897
    public static function getProjects()
1898
    {
1899
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
1900
1901
        $list = [];
1902
        /** @var Project $row */
1903
        foreach ($projects as $row) {
1904
            $list[] = [
1905
                'id' => $row->getId(),
1906
                '0' => $row->getId(),
1907
                '1' => $row->getName(),
1908
                '2' => $row->getDescription(),
1909
                '3' => $row->getId(),
1910
            ];
1911
        }
1912
1913
        return $list;
1914
    }
1915
1916
    /**
1917
     * @return array
1918
     */
1919
    public static function getProjectsSimple()
1920
    {
1921
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
1922
1923
        $list = [];
1924
        /** @var Project $row */
1925
        foreach ($projects as $row) {
1926
            $list[] = [
1927
                'id' => $row->getId(),
1928
                '0' => $row->getId(),
1929
                '1' => Display::url(
1930
                    $row->getName(),
1931
                    api_get_path(WEB_CODE_PATH).'ticket/tickets.php?project_id='.$row->getId()
1932
                ),
1933
                '2' => $row->getDescription(),
1934
            ];
1935
        }
1936
1937
        return $list;
1938
    }
1939
1940
    /**
1941
     * @return int
1942
     */
1943
    public static function getProjectsCount()
1944
    {
1945
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->createQueryBuilder('p')
1946
            ->select('COUNT(p.id)')
1947
            ->getQuery()
1948
            ->getSingleScalarResult();
1949
1950
        return $count;
1951
    }
1952
1953
    /**
1954
     * @param array $params
1955
     */
1956
    public static function addProject($params)
1957
    {
1958
        $project = new Project();
1959
        $project->setName($params['name']);
1960
        $project->setDescription($params['description']);
1961
        $project->setInsertUserId(api_get_user_id());
1962
        Database::getManager()->persist($project);
1963
        Database::getManager()->flush();
1964
    }
1965
1966
    /**
1967
     * @param $id
1968
     *
1969
     * @return Project
1970
     */
1971
    public static function getProject($id)
1972
    {
1973
        return Database::getManager()->getRepository('ChamiloTicketBundle:Project')->find($id);
1974
    }
1975
1976
    /**
1977
     * @param int   $id
1978
     * @param array $params
1979
     */
1980
    public static function updateProject($id, $params)
1981
    {
1982
        $project = self::getProject($id);
1983
        $project->setName($params['name']);
1984
        $project->setDescription($params['description']);
1985
        $project->setLastEditDateTime(new DateTime($params['sys_lastedit_datetime']));
1986
        $project->setLastEditUserId($params['sys_lastedit_user_id']);
1987
1988
        Database::getManager()->merge($project);
1989
        Database::getManager()->flush();
1990
    }
1991
1992
    /**
1993
     * @param int $id
1994
     */
1995
    public static function deleteProject($id)
1996
    {
1997
        $project = self::getProject($id);
1998
        if ($project) {
0 ignored issues
show
introduced by
$project is of type Chamilo\TicketBundle\Entity\Project, thus it always evaluated to true.
Loading history...
1999
            Database::getManager()->remove($project);
2000
            Database::getManager()->flush();
2001
        }
2002
    }
2003
2004
    /**
2005
     * @param string $url
2006
     *
2007
     * @return FormValidator
2008
     */
2009
    public static function getProjectForm($url)
2010
    {
2011
        $form = new FormValidator('project', 'post', $url);
2012
        $form->addText('name', get_lang('Name'));
2013
        $form->addHtmlEditor('description', get_lang('Description'));
2014
        $form->addButtonUpdate(get_lang('Save'));
2015
2016
        return $form;
2017
    }
2018
2019
    /**
2020
     * @return array
2021
     */
2022
    public static function getStatusAdminList()
2023
    {
2024
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
2025
2026
        $list = [];
2027
        /** @var Status $row */
2028
        foreach ($items as $row) {
2029
            $list[] = [
2030
                'id' => $row->getId(),
2031
                'code' => $row->getCode(),
2032
                '0' => $row->getId(),
2033
                '1' => $row->getName(),
2034
                '2' => $row->getDescription(),
2035
                '3' => $row->getId(),
2036
            ];
2037
        }
2038
2039
        return $list;
2040
    }
2041
2042
    /**
2043
     * @return array
2044
     */
2045
    public static function getStatusSimple()
2046
    {
2047
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
2048
2049
        $list = [];
2050
        /** @var Project $row */
2051
        foreach ($projects as $row) {
2052
            $list[] = [
2053
                'id' => $row->getId(),
2054
                '0' => $row->getId(),
2055
                '1' => Display::url($row->getName()),
0 ignored issues
show
Bug introduced by
The call to Display::url() has too few arguments starting with url. ( Ignorable by Annotation )

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

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

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

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

Loading history...
2056
                '2' => $row->getDescription(),
2057
            ];
2058
        }
2059
2060
        return $list;
2061
    }
2062
2063
    /**
2064
     * @return int
2065
     */
2066
    public static function getStatusCount()
2067
    {
2068
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->createQueryBuilder('p')
2069
            ->select('COUNT(p.id)')
2070
            ->getQuery()
2071
            ->getSingleScalarResult();
2072
2073
        return $count;
2074
    }
2075
2076
    /**
2077
     * @param array $params
2078
     */
2079
    public static function addStatus($params)
2080
    {
2081
        $item = new Status();
2082
        $item->setCode(URLify::filter($params['name']));
2083
        $item->setName($params['name']);
2084
        $item->setDescription($params['description']);
2085
2086
        Database::getManager()->persist($item);
2087
        Database::getManager()->flush();
2088
    }
2089
2090
    /**
2091
     * @param $id
2092
     *
2093
     * @return Project
2094
     */
2095
    public static function getStatus($id)
2096
    {
2097
        return Database::getManager()->getRepository('ChamiloTicketBundle:Status')->find($id);
2098
    }
2099
2100
    /**
2101
     * @param int   $id
2102
     * @param array $params
2103
     */
2104
    public static function updateStatus($id, $params)
2105
    {
2106
        $item = self::getStatus($id);
2107
        $item->setName($params['name']);
2108
        $item->setDescription($params['description']);
2109
2110
        Database::getManager()->merge($item);
2111
        Database::getManager()->flush();
2112
    }
2113
2114
    /**
2115
     * @param int $id
2116
     */
2117
    public static function deleteStatus($id)
2118
    {
2119
        $item = self::getStatus($id);
2120
        if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\TicketBundle\Entity\Project, thus it always evaluated to true.
Loading history...
2121
            Database::getManager()->remove($item);
2122
            Database::getManager()->flush();
2123
        }
2124
    }
2125
2126
    /**
2127
     * @param string $url
2128
     *
2129
     * @return FormValidator
2130
     */
2131
    public static function getStatusForm($url)
2132
    {
2133
        $form = new FormValidator('status', 'post', $url);
2134
        $form->addText('name', get_lang('Name'));
2135
        $form->addHtmlEditor('description', get_lang('Description'));
2136
        $form->addButtonUpdate(get_lang('Save'));
2137
2138
        return $form;
2139
    }
2140
2141
    /**
2142
     * @return array
2143
     */
2144
    public static function getPriorityAdminList()
2145
    {
2146
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2147
2148
        $list = [];
2149
        /** @var Status $row */
2150
        foreach ($items as $row) {
2151
            $list[] = [
2152
                'id' => $row->getId(),
2153
                'code' => $row->getCode(),
2154
                '0' => $row->getId(),
2155
                '1' => $row->getName(),
2156
                '2' => $row->getDescription(),
2157
                '3' => $row->getId(),
2158
            ];
2159
        }
2160
2161
        return $list;
2162
    }
2163
2164
    /**
2165
     * @return array
2166
     */
2167
    public static function getPrioritySimple()
2168
    {
2169
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2170
2171
        $list = [];
2172
        /** @var Priority $row */
2173
        foreach ($projects as $row) {
2174
            $list[] = [
2175
                'id' => $row->getId(),
2176
                '0' => $row->getId(),
2177
                '1' => Display::url($row->getName()),
0 ignored issues
show
Bug introduced by
The call to Display::url() has too few arguments starting with url. ( Ignorable by Annotation )

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

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

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

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

Loading history...
2178
                '2' => $row->getDescription(),
2179
            ];
2180
        }
2181
2182
        return $list;
2183
    }
2184
2185
    /**
2186
     * @return int
2187
     */
2188
    public static function getPriorityCount()
2189
    {
2190
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->createQueryBuilder('p')
2191
            ->select('COUNT(p.id)')
2192
            ->getQuery()
2193
            ->getSingleScalarResult();
2194
2195
        return $count;
2196
    }
2197
2198
    /**
2199
     * @param array $params
2200
     */
2201
    public static function addPriority($params)
2202
    {
2203
        $item = new Priority();
2204
        $item
2205
            ->setCode(URLify::filter($params['name']))
2206
            ->setName($params['name'])
2207
            ->setDescription($params['description'])
2208
            ->setColor('')
2209
            ->setInsertUserId(api_get_user_id())
2210
            ->setUrgency('')
2211
        ;
2212
2213
        Database::getManager()->persist($item);
2214
        Database::getManager()->flush();
2215
    }
2216
2217
    /**
2218
     * @param $id
2219
     *
2220
     * @return Priority
2221
     */
2222
    public static function getPriority($id)
2223
    {
2224
        return Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->find($id);
2225
    }
2226
2227
    /**
2228
     * @param int   $id
2229
     * @param array $params
2230
     */
2231
    public static function updatePriority($id, $params)
2232
    {
2233
        $item = self::getPriority($id);
2234
        $item->setName($params['name']);
2235
        $item->setDescription($params['description']);
2236
2237
        Database::getManager()->merge($item);
2238
        Database::getManager()->flush();
2239
    }
2240
2241
    /**
2242
     * @param int $id
2243
     */
2244
    public static function deletePriority($id)
2245
    {
2246
        $item = self::getPriority($id);
2247
        if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\TicketBundle\Entity\Priority, thus it always evaluated to true.
Loading history...
2248
            Database::getManager()->remove($item);
2249
            Database::getManager()->flush();
2250
        }
2251
    }
2252
2253
    /**
2254
     * @param string $url
2255
     *
2256
     * @return FormValidator
2257
     */
2258
    public static function getPriorityForm($url)
2259
    {
2260
        $form = new FormValidator('priority', 'post', $url);
2261
        $form->addText('name', get_lang('Name'));
2262
        $form->addHtmlEditor('description', get_lang('Description'));
2263
        $form->addButtonUpdate(get_lang('Save'));
2264
2265
        return $form;
2266
    }
2267
2268
    /**
2269
     * Returns a list of menu elements for the tickets system's configuration.
2270
     *
2271
     * @param string $exclude The element to exclude from the list
2272
     *
2273
     * @return array
2274
     */
2275
    public static function getSettingsMenuItems($exclude = null)
2276
    {
2277
        $items = [];
2278
        $project = [
2279
            'icon' => 'project.png',
2280
            'url' => 'projects.php',
2281
            'content' => get_lang('Projects'),
2282
        ];
2283
        $status = [
2284
            'icon' => 'check-circle.png',
2285
            'url' => 'status.php',
2286
            'content' => get_lang('Status'),
2287
        ];
2288
        $priority = [
2289
            'icon' => 'tickets_urgent.png',
2290
            'url' => 'priorities.php',
2291
            'content' => get_lang('Priority'),
2292
        ];
2293
        switch ($exclude) {
2294
            case 'project':
2295
                $items = [$status, $priority];
2296
                break;
2297
            case 'status':
2298
                $items = [$project, $priority];
2299
                break;
2300
            case 'priority':
2301
                $items = [$project, $status];
2302
                break;
2303
            default:
2304
                $items = [$project, $status, $priority];
2305
                break;
2306
        }
2307
2308
        return $items;
2309
    }
2310
2311
    /**
2312
     * Returns a list of strings representing the default statuses.
2313
     *
2314
     * @return array
2315
     */
2316
    public static function getDefaultStatusList()
2317
    {
2318
        return [
2319
            self::STATUS_NEW,
2320
            self::STATUS_PENDING,
2321
            self::STATUS_UNCONFIRMED,
2322
            self::STATUS_CLOSE,
2323
            self::STATUS_FORWARDED,
2324
        ];
2325
    }
2326
2327
    /**
2328
     * @return array
2329
     */
2330
    public static function getDefaultPriorityList()
2331
    {
2332
        return [
2333
            self::PRIORITY_NORMAL,
2334
            self::PRIORITY_HIGH,
2335
            self::PRIORITY_LOW,
2336
            self::STATUS_CLOSE,
2337
            self::STATUS_FORWARDED,
2338
        ];
2339
    }
2340
2341
    /**
2342
     * Deletes the user from all the ticket system.
2343
     *
2344
     * @param int $userId
2345
     */
2346
    public static function deleteUserFromTicketSystem($userId)
2347
    {
2348
        $userId = (int) $userId;
2349
        $schema = Database::getManager()->getConnection()->getSchemaManager();
2350
2351
        if ($schema->tablesExist('ticket_assigned_log')) {
2352
            $sql = "UPDATE ticket_assigned_log SET user_id = NULL WHERE user_id = $userId";
2353
            Database::query($sql);
2354
2355
            $sql = "UPDATE ticket_assigned_log SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2356
            Database::query($sql);
2357
        }
2358
2359
        if ($schema->tablesExist('ticket_ticket')) {
2360
            $sql = "UPDATE ticket_ticket SET assigned_last_user = NULL WHERE assigned_last_user = $userId";
2361
            Database::query($sql);
2362
2363
            $sql = "UPDATE ticket_ticket SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2364
            Database::query($sql);
2365
2366
            $sql = "UPDATE ticket_ticket SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2367
            Database::query($sql);
2368
        }
2369
2370
        if ($schema->tablesExist('ticket_category')) {
2371
            $sql = "UPDATE ticket_category SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2372
            Database::query($sql);
2373
2374
            $sql = "UPDATE ticket_category SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2375
            Database::query($sql);
2376
        }
2377
2378
        if ($schema->tablesExist('ticket_category_rel_user')) {
2379
            $sql = "DELETE FROM ticket_category_rel_user WHERE user_id = $userId";
2380
            Database::query($sql);
2381
        }
2382
2383
        if ($schema->tablesExist('ticket_message')) {
2384
            $sql = "UPDATE ticket_message SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2385
            Database::query($sql);
2386
2387
            $sql = "UPDATE ticket_message SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2388
            Database::query($sql);
2389
        }
2390
2391
        if ($schema->tablesExist('ticket_message_attachments')) {
2392
            $sql = "UPDATE ticket_message_attachments SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2393
            Database::query($sql);
2394
2395
            $sql = "UPDATE ticket_message_attachments SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2396
            Database::query($sql);
2397
        }
2398
2399
        if ($schema->tablesExist('ticket_priority')) {
2400
            $sql = "UPDATE ticket_priority SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2401
            Database::query($sql);
2402
2403
            $sql = "UPDATE ticket_priority SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2404
            Database::query($sql);
2405
        }
2406
2407
        if ($schema->tablesExist('ticket_project')) {
2408
            $sql = "UPDATE ticket_project SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2409
            Database::query($sql);
2410
2411
            $sql = "UPDATE ticket_project SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2412
            Database::query($sql);
2413
        }
2414
    }
2415
2416
    /**
2417
     * @param array $userInfo
2418
     * @param int   $projectId
2419
     *
2420
     * @return bool
2421
     */
2422
    public static function userIsAllowInProject($userInfo, $projectId)
2423
    {
2424
        if (api_is_platform_admin()) {
2425
            return true;
2426
        }
2427
2428
        $allowRoleList = self::getAllowedRolesFromProject($projectId);
2429
2430
        // Check if a role was set to the project
2431
        // Project 1 is considered the default and is accessible to all users
2432
        if (!empty($allowRoleList) && is_array($allowRoleList)) {
2433
            if (in_array($userInfo['status'], $allowRoleList)) {
2434
                return true;
2435
            }
2436
        }
2437
2438
        return false;
2439
    }
2440
2441
    /**
2442
     * @param int $projectId
2443
     *
2444
     * @todo load from database instead of configuration.php setting
2445
     *
2446
     * @return array
2447
     */
2448
    public static function getAllowedRolesFromProject($projectId)
2449
    {
2450
        $options = api_get_configuration_value('ticket_project_user_roles');
2451
        if ($options) {
2452
            if (isset($options['permissions'][$projectId])) {
2453
                return $options['permissions'][$projectId];
2454
            }
2455
        }
2456
2457
        return [];
2458
    }
2459
}
2460