Passed
Push — ofaj ( 0f9380...ade756 )
by
unknown
12:01 queued 12s
created

TicketManager   F

Complexity

Total Complexity 262

Size/Duplication

Total Lines 2484
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 1268
dl 0
loc 2484
rs 0.8
c 0
b 0
f 0
wmc 262

67 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A addCategory() 0 4 1
A userIsAssignedToCategory() 0 10 1
A getUsersInCategory() 0 8 1
A deleteAllUserInCategory() 0 6 1
A addUsersToCategory() 0 18 5
A getCategory() 0 11 1
A updateCategory() 0 5 1
A deleteCategory() 0 16 2
A getCategoriesCount() 0 11 1
A get_all_tickets_status() 0 11 2
A getCategories() 0 23 3
A get_all_tickets_categories() 0 27 3
A getProjects() 0 17 2
A getProjectForm() 0 8 1
A update_ticket_status() 0 31 2
B insertMessage() 0 71 7
A getTicketMessageAttachment() 0 10 2
A getAllowedRolesFromProject() 0 10 3
C sendNotification() 0 96 12
A get_assign_log() 0 27 3
A getSettingsMenuItems() 0 33 4
A close_ticket() 0 19 1
A getCategoryForm() 0 9 1
A getStatus() 0 3 1
C deleteUserFromTicketSystem() 0 67 9
A getStatusAdminList() 0 18 2
A getPriority() 0 3 1
A getProjectsSimple() 0 19 2
F add() 0 289 36
F getTicketsByCurrentUser() 0 227 38
A getPriorityForm() 0 8 1
A assignTicketToUser() 0 32 3
A saveMessageAttachmentFile() 0 48 3
C get_ticket_detail_by_id() 0 128 10
A getDefaultStatusList() 0 8 1
A getDefaultPriorityList() 0 8 1
A getProject() 0 3 1
A getStatusIdFromCode() 0 12 2
A getPriorityAdminList() 0 18 2
A getPriorityCount() 0 8 1
F export_tickets_by_user_id() 0 197 24
A update_message_status() 0 31 3
A deleteStatus() 0 6 2
A updatePriority() 0 8 1
A getStatusForm() 0 8 1
A getTicketsFromCriteria() 0 11 2
A addPriority() 0 14 1
A deletePriority() 0 6 2
A getTicketMessageAttachmentsByTicketId() 0 10 2
A updateTicket() 0 16 3
A getStatusCount() 0 8 1
A getStatusSimple() 0 16 2
A send_alert() 0 14 1
F getTotalTicketsCurrentUser() 0 102 21
A getPrioritySimple() 0 16 2
A userIsAllowInProject() 0 17 5
A addStatus() 0 9 1
A getPriorityList() 0 11 2
A updateProject() 0 10 1
A addProject() 0 9 1
A getStatusList() 0 11 2
A getNumberOfMessages() 0 28 2
A deleteProject() 0 6 2
A getProjectsCount() 0 8 1
A close_old_tickets() 0 17 1
A updateStatus() 0 8 1

How to fix   Complexity   

Complex Class

Complex classes like TicketManager often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use TicketManager, and based on these observations, apply Extract Interface, too.

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

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

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

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

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

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

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

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

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
682
            // update_total_message
683
            $sql = "UPDATE $table_support_tickets
684
                    SET 
685
                        sys_lastedit_user_id = $userId,
686
                        sys_lastedit_datetime = '$now',
687
                        total_messages = (
688
                            SELECT COUNT(*) as total_messages
689
                            FROM $table_support_messages
690
                            WHERE ticket_id = $ticketId
691
                        )
692
                    WHERE id = $ticketId ";
693
            Database::query($sql);
694
695
            if (is_array($fileAttachments)) {
696
                foreach ($fileAttachments as $file_attach) {
697
                    if ($file_attach['error'] == 0) {
698
                        self::saveMessageAttachmentFile(
699
                            $file_attach,
700
                            $ticketId,
701
                            $messageId
702
                        );
703
                    } else {
704
                        if ($file_attach['error'] != UPLOAD_ERR_NO_FILE) {
705
                            return false;
706
                        }
707
                    }
708
                }
709
            }
710
        }
711
712
        return true;
713
    }
714
715
    /**
716
     * Attachment files when a message is sent.
717
     *
718
     * @param $file_attach
719
     * @param $ticketId
720
     * @param $message_id
721
     *
722
     * @return bool
723
     */
724
    public static function saveMessageAttachmentFile(
725
        $file_attach,
726
        $ticketId,
727
        $message_id
728
    ) {
729
        $now = api_get_utc_datetime();
730
        $userId = api_get_user_id();
731
        $ticketId = (int) $ticketId;
732
733
        $new_file_name = add_ext_on_mime(
734
            stripslashes($file_attach['name']),
735
            $file_attach['type']
736
        );
737
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
738
        if (!filter_extension($new_file_name)) {
739
            echo Display::return_message(
740
                get_lang('UplUnableToSaveFileFilteredExtension'),
741
                'error'
742
            );
743
        } else {
744
            $result = api_upload_file('ticket_attachment', $file_attach, $ticketId);
745
            if ($result) {
0 ignored issues
show
introduced by
$result is a non-empty array, thus is always true.
Loading history...
Bug Best Practice introduced by
The expression $result of type array<string,string> is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

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

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

Loading history...
746
                $safe_file_name = Database::escape_string($new_file_name);
747
                $safe_new_file_name = Database::escape_string($result['path_to_save']);
748
                $sql = "INSERT INTO $table_support_message_attachments (
749
                        filename,
750
                        path,
751
                        ticket_id,
752
                        message_id,
753
                        size,
754
                        sys_insert_user_id,
755
                        sys_insert_datetime,
756
                        sys_lastedit_user_id,
757
                        sys_lastedit_datetime
758
                    ) VALUES (
759
                        '$safe_file_name',
760
                        '$safe_new_file_name',
761
                        '$ticketId',
762
                        '$message_id',
763
                        '".$file_attach['size']."',
764
                        '$userId',
765
                        '$now',
766
                        '$userId',
767
                        '$now'
768
                    )";
769
                Database::query($sql);
770
771
                return true;
772
            }
773
        }
774
    }
775
776
    /**
777
     * Get tickets by userId.
778
     *
779
     * @param int $from
780
     * @param int $number_of_items
781
     * @param $column
782
     * @param $direction
783
     *
784
     * @return array
785
     */
786
    public static function getTicketsByCurrentUser(
787
        $from,
788
        $number_of_items,
789
        $column,
790
        $direction
791
    ) {
792
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
793
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
794
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
795
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
796
        $direction = !empty($direction) ? $direction : 'DESC';
797
        $userId = api_get_user_id();
798
        $userInfo = api_get_user_info($userId);
799
800
        if (empty($userInfo)) {
801
            return [];
802
        }
803
        $isAdmin = UserManager::is_admin($userId);
804
805
        if (!isset($_GET['project_id'])) {
806
            return [];
807
        }
808
809
        switch ($column) {
810
            case 0:
811
                $column = 'ticket_id';
812
                break;
813
            case 1:
814
                $column = 'status_name';
815
                break;
816
            case 2:
817
                $column = 'start_date';
818
                break;
819
            case 3:
820
                $column = 'sys_lastedit_datetime';
821
                break;
822
            case 4:
823
                $column = 'category_name';
824
                break;
825
            case 5:
826
                $column = 'sys_insert_user_id';
827
                break;
828
            case 6:
829
                $column = 'assigned_last_user';
830
                break;
831
            case 7:
832
                $column = 'total_messages';
833
                break;
834
            case 8:
835
                $column = 'subject';
836
                break;
837
            default:
838
                $column = 'ticket_id';
839
        }
840
841
        $sql = "SELECT DISTINCT 
842
                ticket.*,
843
                ticket.id ticket_id,
844
                status.name AS status_name,
845
                ticket.start_date,
846
                ticket.sys_lastedit_datetime,
847
                cat.name AS category_name,
848
                priority.name AS priority_name,                           
849
                ticket.total_messages AS total_messages,
850
                ticket.message AS message,
851
                ticket.subject AS subject,
852
                ticket.assigned_last_user
853
            FROM $table_support_tickets ticket 
854
            INNER JOIN $table_support_category cat
855
            ON (cat.id = ticket.category_id)
856
            INNER JOIN $table_support_priority priority
857
            ON (ticket.priority_id = priority.id)
858
            INNER JOIN $table_support_status status
859
            ON (ticket.status_id = status.id)
860
            WHERE 1=1                                
861
        ";
862
863
        $projectId = (int) $_GET['project_id'];
864
        $userIsAllowInProject = self::userIsAllowInProject($userInfo, $projectId);
865
866
        // Check if a role was set to the project
867
        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...
868
            $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
869
        }
870
871
        // Search simple
872
        if (isset($_GET['submit_simple']) && $_GET['keyword'] != '') {
873
            $keyword = Database::escape_string(trim($_GET['keyword']));
874
            $sql .= " AND (
875
                      ticket.id LIKE '%$keyword%' OR
876
                      ticket.code LIKE '%$keyword%' OR
877
                      ticket.subject LIKE '%$keyword%' OR
878
                      ticket.message LIKE '%$keyword%' OR
879
                      ticket.keyword LIKE '%$keyword%' OR
880
                      ticket.source LIKE '%$keyword%' OR
881
                      cat.name LIKE '%$keyword%' OR
882
                      status.name LIKE '%$keyword%' OR
883
                      priority.name LIKE '%$keyword%' OR
884
                      ticket.personal_email LIKE '%$keyword%'                          
885
            )";
886
        }
887
888
        $keywords = [
889
            'project_id' => 'ticket.project_id',
890
            'keyword_category' => 'ticket.category_id',
891
            'keyword_assigned_to' => 'ticket.assigned_last_user',
892
            'keyword_source' => 'ticket.source ',
893
            'keyword_status' => 'ticket.status_id',
894
            'keyword_priority' => 'ticket.priority_id',
895
        ];
896
897
        foreach ($keywords as $keyword => $label) {
898
            if (isset($_GET[$keyword])) {
899
                $data = Database::escape_string(trim($_GET[$keyword]));
900
                if (!empty($data)) {
901
                    $sql .= " AND $label = '$data' ";
902
                }
903
            }
904
        }
905
906
        // Search advanced
907
        $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
908
        $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
909
        $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
910
        $keyword_range = !empty($keyword_start_date_start) && !empty($keyword_start_date_end);
911
912
        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...
913
            $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start' ";
914
        }
915
        if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
916
            $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
917
                      AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
918
        }
919
920
        if ($keyword_course != '') {
921
            $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
922
            $sql .= " AND ticket.course_id IN ( 
923
                     SELECT id FROM $course_table
924
                     WHERE (
925
                        title LIKE '%$keyword_course%' OR 
926
                        code LIKE '%$keyword_course%' OR 
927
                        visual_code LIKE '%$keyword_course%'
928
                     )
929
            )";
930
        }
931
        $sql .= " ORDER BY `$column` $direction";
932
        $sql .= " LIMIT $from, $number_of_items";
933
934
        $result = Database::query($sql);
935
        $tickets = [];
936
        $webPath = api_get_path(WEB_PATH);
937
        while ($row = Database::fetch_assoc($result)) {
938
            $userInfo = api_get_user_info($row['sys_insert_user_id']);
939
            $hrefUser = $webPath.'main/admin/user_information.php?user_id='.$userInfo['user_id'];
940
            $name = "<a href='$hrefUser'> {$userInfo['complete_name_with_username']} </a>";
941
            if ($row['assigned_last_user'] != 0) {
942
                $assignedUserInfo = api_get_user_info($row['assigned_last_user']);
943
                if (!empty($assignedUserInfo)) {
944
                    $hrefResp = $webPath.'main/admin/user_information.php?user_id='.$assignedUserInfo['user_id'];
945
                    $row['assigned_last_user'] = "<a href='$hrefResp'> {$assignedUserInfo['complete_name_with_username']} </a>";
946
                } else {
947
                    $row['assigned_last_user'] = get_lang('UnknownUser');
948
                }
949
            } else {
950
                if ($row['status_id'] !== self::STATUS_FORWARDED) {
951
                    $row['assigned_last_user'] = '<span style="color:#ff0000;">'.get_lang('ToBeAssigned').'</span>';
952
                } else {
953
                    $row['assigned_last_user'] = '<span style="color:#00ff00;">'.get_lang('MessageResent').'</span>';
954
                }
955
            }
956
957
            switch ($row['source']) {
958
                case self::SOURCE_PRESENTIAL:
959
                    $img_source = 'icons/32/user.png';
960
                    break;
961
                case self::SOURCE_EMAIL:
962
                    $img_source = 'icons/32/mail.png';
963
                    break;
964
                case self::SOURCE_PHONE:
965
                    $img_source = 'icons/32/event.png';
966
                    break;
967
                default:
968
                    $img_source = 'icons/32/ticket.png';
969
                    break;
970
            }
971
972
            $row['start_date'] = Display::dateToStringAgoAndLongDate($row['start_date']);
973
            $row['sys_lastedit_datetime'] = Display::dateToStringAgoAndLongDate($row['sys_lastedit_datetime']);
974
975
            $icon = Display::return_icon(
976
                $img_source,
977
                get_lang('Info'),
978
                ['style' => 'margin-right: 10px; float: left;']
979
            );
980
981
            $icon .= '<a href="ticket_details.php?ticket_id='.$row['id'].'">'.$row['code'].'</a>';
982
983
            if ($isAdmin) {
984
                $ticket = [
985
                    $icon.' '.Security::remove_XSS($row['subject']),
986
                    $row['status_name'],
987
                    $row['start_date'],
988
                    $row['sys_lastedit_datetime'],
989
                    $row['category_name'],
990
                    $name,
991
                    $row['assigned_last_user'],
992
                    $row['total_messages'],
993
                ];
994
            } else {
995
                $ticket = [
996
                    $icon.' '.Security::remove_XSS($row['subject']),
997
                    $row['status_name'],
998
                    $row['start_date'],
999
                    $row['sys_lastedit_datetime'],
1000
                    $row['category_name'],
1001
                ];
1002
            }
1003
            if ($isAdmin) {
1004
                $ticket['0'] .= '&nbsp;&nbsp;<a href="javascript:void(0)" onclick="load_history_ticket(\'div_'.$row['ticket_id'].'\','.$row['ticket_id'].')">
1005
					<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').'"/>
1006
					<div class="blackboard_hide" id="div_'.$row['ticket_id'].'">&nbsp;&nbsp;</div>
1007
					</a>&nbsp;&nbsp;';
1008
            }
1009
            $tickets[] = $ticket;
1010
        }
1011
1012
        return $tickets;
1013
    }
1014
1015
    /**
1016
     * @return int
1017
     */
1018
    public static function getTotalTicketsCurrentUser()
1019
    {
1020
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1021
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1022
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1023
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1024
1025
        $userInfo = api_get_user_info();
1026
        if (empty($userInfo)) {
1027
            return 0;
1028
        }
1029
        $userId = $userInfo['id'];
1030
1031
        if (!isset($_GET['project_id'])) {
1032
            return 0;
1033
        }
1034
1035
        $sql = "SELECT COUNT(ticket.id) AS total
1036
                FROM $table_support_tickets ticket
1037
                INNER JOIN $table_support_category cat
1038
                ON (cat.id = ticket.category_id)
1039
                INNER JOIN $table_support_priority priority
1040
                ON (ticket.priority_id = priority.id)
1041
                INNER JOIN $table_support_status status
1042
                ON (ticket.status_id = status.id)
1043
	            WHERE 1 = 1";
1044
1045
        $projectId = (int) $_GET['project_id'];
1046
        $allowRoleList = self::getAllowedRolesFromProject($projectId);
1047
1048
        // Check if a role was set to the project
1049
        if (!empty($allowRoleList) && is_array($allowRoleList)) {
1050
            if (!in_array($userInfo['status'], $allowRoleList)) {
1051
                $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
1052
            }
1053
        } else {
1054
            if (!api_is_platform_admin()) {
1055
                $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
1056
            }
1057
        }
1058
1059
        // Search simple
1060
        if (isset($_GET['submit_simple'])) {
1061
            if ($_GET['keyword'] != '') {
1062
                $keyword = Database::escape_string(trim($_GET['keyword']));
1063
                $sql .= " AND (
1064
                          ticket.code LIKE '%$keyword%' OR
1065
                          ticket.subject LIKE '%$keyword%' OR
1066
                          ticket.message LIKE '%$keyword%' OR
1067
                          ticket.keyword LIKE '%$keyword%' OR
1068
                          ticket.personal_email LIKE '%$keyword%' OR
1069
                          ticket.source LIKE '%$keyword%'
1070
                )";
1071
            }
1072
        }
1073
1074
        $keywords = [
1075
            'project_id' => 'ticket.project_id',
1076
            'keyword_category' => 'ticket.category_id',
1077
            'keyword_assigned_to' => 'ticket.assigned_last_user',
1078
            'keyword_source' => 'ticket.source',
1079
            'keyword_status' => 'ticket.status_id',
1080
            'keyword_priority' => 'ticket.priority_id',
1081
        ];
1082
1083
        foreach ($keywords as $keyword => $sqlLabel) {
1084
            if (isset($_GET[$keyword])) {
1085
                $data = Database::escape_string(trim($_GET[$keyword]));
1086
                $sql .= " AND $sqlLabel = '$data' ";
1087
            }
1088
        }
1089
1090
        // Search advanced
1091
        $keyword_start_date_start = isset($_GET['keyword_start_date_start']) ? Database::escape_string(trim($_GET['keyword_start_date_start'])) : '';
1092
        $keyword_start_date_end = isset($_GET['keyword_start_date_end']) ? Database::escape_string(trim($_GET['keyword_start_date_end'])) : '';
1093
        $keyword_range = isset($_GET['keyword_dates']) ? Database::escape_string(trim($_GET['keyword_dates'])) : '';
1094
        $keyword_course = isset($_GET['keyword_course']) ? Database::escape_string(trim($_GET['keyword_course'])) : '';
1095
1096
        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...
1097
            $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
1098
        }
1099
        if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
1100
            $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
1101
                      AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
1102
        }
1103
        if ($keyword_course != '') {
1104
            $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1105
            $sql .= " AND ticket.course_id IN (  
1106
                        SELECT id
1107
                        FROM $course_table
1108
                        WHERE (
1109
                            title LIKE '%$keyword_course%' OR 
1110
                            code LIKE '%$keyword_course%' OR 
1111
                            visual_code LIKE '%$keyword_course%'
1112
                        )
1113
                   ) ";
1114
        }
1115
1116
        $res = Database::query($sql);
1117
        $obj = Database::fetch_object($res);
1118
1119
        return (int) $obj->total;
1120
    }
1121
1122
    /**
1123
     * @param int $id
1124
     *
1125
     * @return false|MessageAttachment
1126
     */
1127
    public static function getTicketMessageAttachment($id)
1128
    {
1129
        $id = (int) $id;
1130
        $em = Database::getManager();
1131
        $item = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->find($id);
1132
        if ($item) {
1133
            return $item;
1134
        }
1135
1136
        return false;
1137
    }
1138
1139
    /**
1140
     * @param int $id
1141
     *
1142
     * @return array
1143
     */
1144
    public static function getTicketMessageAttachmentsByTicketId($id)
1145
    {
1146
        $id = (int) $id;
1147
        $em = Database::getManager();
1148
        $items = $em->getRepository('ChamiloTicketBundle:MessageAttachment')->findBy(['ticket' => $id]);
1149
        if ($items) {
1150
            return $items;
1151
        }
1152
1153
        return false;
1154
    }
1155
1156
    /**
1157
     * @param int $ticketId
1158
     *
1159
     * @return array
1160
     */
1161
    public static function get_ticket_detail_by_id($ticketId)
1162
    {
1163
        $ticketId = (int) $ticketId;
1164
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1165
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1166
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1167
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1168
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1169
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
1170
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1171
1172
        $sql = "SELECT
1173
                    ticket.*, 
1174
                    cat.name,
1175
                    status.name as status, 
1176
                    priority.name priority
1177
                FROM $table_support_tickets ticket
1178
                INNER JOIN $table_support_category cat
1179
                ON (cat.id = ticket.category_id)
1180
                INNER JOIN $table_support_priority priority
1181
                ON (priority.id = ticket.priority_id)
1182
                INNER JOIN $table_support_status status
1183
                ON (status.id = ticket.status_id)
1184
		        WHERE
1185
                    ticket.id = $ticketId ";
1186
        $result = Database::query($sql);
1187
        $ticket = [];
1188
        if (Database::num_rows($result) > 0) {
1189
            while ($row = Database::fetch_assoc($result)) {
1190
                $row['course'] = null;
1191
                $row['start_date_from_db'] = $row['start_date'];
1192
                $row['start_date'] = api_convert_and_format_date(
1193
                    api_get_local_time($row['start_date']),
1194
                    DATE_TIME_FORMAT_LONG,
1195
                    api_get_timezone()
1196
                );
1197
                $row['end_date_from_db'] = $row['end_date'];
1198
                $row['end_date'] = api_convert_and_format_date(
1199
                    api_get_local_time($row['end_date']),
1200
                    DATE_TIME_FORMAT_LONG,
1201
                    api_get_timezone()
1202
                );
1203
                $row['sys_lastedit_datetime_from_db'] = $row['sys_lastedit_datetime'];
1204
                $row['sys_lastedit_datetime'] = api_convert_and_format_date(
1205
                    api_get_local_time($row['sys_lastedit_datetime']),
1206
                    DATE_TIME_FORMAT_LONG,
1207
                    api_get_timezone()
1208
                );
1209
                $row['course_url'] = null;
1210
                if ($row['course_id'] != 0) {
1211
                    $course = api_get_course_info_by_id($row['course_id']);
1212
                    $sessionId = 0;
1213
                    if ($row['session_id']) {
1214
                        $sessionId = $row['session_id'];
1215
                    }
1216
                    if ($course) {
1217
                        $row['course_url'] = '<a href="'.$course['course_public_url'].'?id_session='.$sessionId.'">'.$course['name'].'</a>';
1218
                    }
1219
1220
                    $row['exercise_url'] = null;
1221
1222
                    if (!empty($row['exercise_id'])) {
1223
                        $exerciseTitle = ExerciseLib::getExerciseTitleById($row['exercise_id']);
0 ignored issues
show
Bug introduced by
The method getExerciseTitleById() does not exist on ExerciseLib. ( Ignorable by Annotation )

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

1223
                        /** @scrutinizer ignore-call */ 
1224
                        $exerciseTitle = ExerciseLib::getExerciseTitleById($row['exercise_id']);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1224
                        $dataExercise = [
1225
                            'cidReq' => $course['code'],
1226
                            'id_session' => $sessionId,
1227
                            'exerciseId' => $row['exercise_id'],
1228
                        ];
1229
                        $urlParamsExercise = http_build_query($dataExercise);
1230
1231
                        $row['exercise_url'] = '<a href="'.api_get_path(WEB_CODE_PATH).'exercise/overview.php?'.$urlParamsExercise.'">'.$exerciseTitle.'</a>';
1232
                    }
1233
1234
                    $row['lp_url'] = null;
1235
1236
                    if (!empty($row['lp_id'])) {
1237
                        $lpName = learnpath::getLpNameById($row['lp_id']);
0 ignored issues
show
Bug introduced by
The method getLpNameById() does not exist on learnpath. ( Ignorable by Annotation )

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

1237
                        /** @scrutinizer ignore-call */ 
1238
                        $lpName = learnpath::getLpNameById($row['lp_id']);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
1238
                        $dataLp = [
1239
                            'cidReq' => $course['code'],
1240
                            'id_session' => $sessionId,
1241
                            'lp_id' => $row['lp_id'],
1242
                            'action' => 'view',
1243
                        ];
1244
                        $urlParamsLp = http_build_query($dataLp);
1245
1246
                        $row['lp_url'] = '<a href="'.api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.$urlParamsLp.'">'.$lpName.'</a>';
1247
                    }
1248
                }
1249
1250
                $userInfo = api_get_user_info($row['sys_insert_user_id']);
1251
                $row['user_url'] = '<a href="'.api_get_path(WEB_PATH).'main/admin/user_information.php?user_id='.$userInfo['user_id'].'">
1252
                '.$userInfo['complete_name'].'</a>';
1253
                $ticket['usuario'] = $userInfo;
1254
                $ticket['ticket'] = $row;
1255
            }
1256
1257
            $sql = "SELECT *, message.id as message_id 
1258
                    FROM $table_support_messages message 
1259
                    INNER JOIN $table_main_user user
1260
                    ON (message.sys_insert_user_id = user.user_id)
1261
                    WHERE
1262
                        message.ticket_id = '$ticketId' ";
1263
            $result = Database::query($sql);
1264
            $ticket['messages'] = [];
1265
            $attach_icon = Display::return_icon('attachment.gif', '');
1266
            $webPath = api_get_path(WEB_CODE_PATH);
1267
            while ($row = Database::fetch_assoc($result)) {
1268
                $message = $row;
1269
                $message['admin'] = UserManager::is_admin($message['user_id']);
1270
                $message['user_info'] = api_get_user_info($message['user_id']);
1271
                $sql = "SELECT *
1272
                        FROM $table_support_message_attachments
1273
                        WHERE
1274
                            message_id = ".$row['message_id']." AND
1275
                            ticket_id = $ticketId";
1276
1277
                $result_attach = Database::query($sql);
1278
                while ($row2 = Database::fetch_assoc($result_attach)) {
1279
                    $archiveURL = $webPath.'ticket/download.php?ticket_id='.$ticketId.'&id='.$row2['id'];
1280
                    $row2['attachment_link'] = $attach_icon.
1281
                        '&nbsp;<a href="'.$archiveURL.'">'.$row2['filename'].'</a>&nbsp;('.$row2['size'].')';
1282
                    $message['attachments'][] = $row2;
1283
                }
1284
                $ticket['messages'][] = $message;
1285
            }
1286
        }
1287
1288
        return $ticket;
1289
    }
1290
1291
    /**
1292
     * @param int $ticketId
1293
     * @param int $userId
1294
     *
1295
     * @return bool
1296
     */
1297
    public static function update_message_status($ticketId, $userId)
1298
    {
1299
        $ticketId = (int) $ticketId;
1300
        $userId = (int) $userId;
1301
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1302
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1303
        $now = api_get_utc_datetime();
1304
        $sql = "UPDATE $table_support_messages
1305
                SET
1306
                    status = 'LEI',
1307
                    sys_lastedit_user_id ='".api_get_user_id()."',
1308
                    sys_lastedit_datetime ='".$now."'
1309
                WHERE ticket_id ='$ticketId' ";
1310
1311
        if (api_is_platform_admin()) {
1312
            $sql .= " AND sys_insert_user_id = '$userId'";
1313
        } else {
1314
            $sql .= " AND sys_insert_user_id != '$userId'";
1315
        }
1316
        $result = Database::query($sql);
1317
        if (Database::affected_rows($result) > 0) {
1318
            Database::query(
1319
                "UPDATE $table_support_tickets SET
1320
                    status_id = '".self::STATUS_PENDING."'
1321
                 WHERE id ='$ticketId' AND status_id = '".self::STATUS_NEW."'"
1322
            );
1323
1324
            return true;
1325
        }
1326
1327
        return false;
1328
    }
1329
1330
    /**
1331
     * Send notification to a user through the internal messaging system.
1332
     *
1333
     * @param int    $ticketId
1334
     * @param string $title
1335
     * @param string $message
1336
     * @param int    $onlyToUserId
1337
     *
1338
     * @return bool
1339
     */
1340
    public static function sendNotification($ticketId, $title, $message, $onlyToUserId = 0)
1341
    {
1342
        $ticketInfo = self::get_ticket_detail_by_id($ticketId);
1343
1344
        if (empty($ticketInfo)) {
1345
            return false;
1346
        }
1347
1348
        $assignedUserInfo = api_get_user_info($ticketInfo['ticket']['assigned_last_user']);
1349
        $requestUserInfo = $ticketInfo['usuario'];
1350
        $ticketCode = $ticketInfo['ticket']['code'];
1351
        $status = $ticketInfo['ticket']['status'];
1352
        $priority = $ticketInfo['ticket']['priority'];
1353
1354
        // Subject
1355
        $titleEmail = "[$ticketCode] $title";
1356
1357
        // Content
1358
        $href = api_get_path(WEB_CODE_PATH).'/ticket/ticket_details.php?ticket_id='.$ticketId;
1359
        $ticketUrl = Display::url($ticketCode, $href);
1360
        $messageEmail = get_lang('TicketNum').": $ticketUrl <br />";
1361
        $messageEmail .= get_lang('Status').": $status <br />";
1362
        $messageEmail .= get_lang('Priority').": $priority <br />";
1363
        $messageEmail .= '<hr /><br />';
1364
        $messageEmail .= $message;
1365
        $currentUserId = api_get_user_id();
1366
        $attachmentList = [];
1367
        $attachments = self::getTicketMessageAttachmentsByTicketId($ticketId);
1368
        if (!empty($attachments)) {
1369
            /** @var MessageAttachment $attachment */
1370
            foreach ($attachments as $attachment) {
1371
                $file = api_get_uploaded_file(
1372
                    'ticket_attachment',
1373
                    $ticketId,
1374
                    $attachment->getPath()
1375
                );
1376
                if (!empty($file)) {
1377
                    $attachmentList[] = [
1378
                        'tmp_name' => api_get_uploaded_file(
1379
                            'ticket_attachment',
1380
                            $ticketId,
1381
                            $attachment->getPath()
1382
                        ),
1383
                        'size' => $attachment->getSize(),
1384
                        'name' => $attachment->getFilename(),
1385
                        'error' => 0,
1386
                    ];
1387
                }
1388
            }
1389
        }
1390
1391
        if (!empty($onlyToUserId)) {
1392
            // Send only to specific user
1393
            if ($currentUserId != $onlyToUserId) {
1394
                MessageManager::send_message_simple(
1395
                    $onlyToUserId,
1396
                    $titleEmail,
1397
                    $messageEmail,
1398
                    0,
1399
                    false,
1400
                    false,
1401
                    [],
1402
                    false,
1403
                    $attachmentList
1404
                );
1405
            }
1406
        } else {
1407
            // Send to assigned user and to author
1408
            if ($requestUserInfo && $currentUserId != $requestUserInfo['id']) {
1409
                MessageManager::send_message_simple(
1410
                    $requestUserInfo['id'],
1411
                    $titleEmail,
1412
                    $messageEmail,
1413
                    0,
1414
                    false,
1415
                    false,
1416
                    [],
1417
                    false,
1418
                    $attachmentList
1419
                );
1420
            }
1421
1422
            if ($assignedUserInfo &&
1423
                $requestUserInfo['id'] != $assignedUserInfo['id'] &&
1424
                $currentUserId != $assignedUserInfo['id']
1425
            ) {
1426
                MessageManager::send_message_simple(
1427
                    $assignedUserInfo['id'],
1428
                    $titleEmail,
1429
                    $messageEmail,
1430
                    0,
1431
                    false,
1432
                    false,
1433
                    [],
1434
                    false,
1435
                    $attachmentList
1436
                );
1437
            }
1438
        }
1439
    }
1440
1441
    /**
1442
     * @param array $params
1443
     * @param int   $ticketId
1444
     * @param int   $userId
1445
     *
1446
     * @return bool
1447
     */
1448
    public static function updateTicket(
1449
        $params,
1450
        $ticketId,
1451
        $userId
1452
    ) {
1453
        $now = api_get_utc_datetime();
1454
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
1455
        $newParams = [
1456
            'priority_id' => isset($params['priority_id']) ? (int) $params['priority_id'] : '',
1457
            'status_id' => isset($params['status_id']) ? (int) $params['status_id'] : '',
1458
            'sys_lastedit_user_id' => (int) $userId,
1459
            'sys_lastedit_datetime' => $now,
1460
        ];
1461
        Database::update($table, $newParams, ['id = ? ' => $ticketId]);
1462
1463
        return true;
1464
    }
1465
1466
    /**
1467
     * @param int $status_id
1468
     * @param int $ticketId
1469
     * @param int $userId
1470
     *
1471
     * @return bool
1472
     */
1473
    public static function update_ticket_status(
1474
        $status_id,
1475
        $ticketId,
1476
        $userId
1477
    ) {
1478
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1479
1480
        $ticketId = (int) $ticketId;
1481
        $status_id = (int) $status_id;
1482
        $userId = (int) $userId;
1483
        $now = api_get_utc_datetime();
1484
1485
        $sql = "UPDATE $table_support_tickets
1486
                SET
1487
                    status_id = '$status_id',
1488
                    sys_lastedit_user_id ='$userId',
1489
                    sys_lastedit_datetime ='".$now."'
1490
                WHERE id ='$ticketId'";
1491
        $result = Database::query($sql);
1492
1493
        if (Database::affected_rows($result) > 0) {
1494
            self::sendNotification(
1495
                $ticketId,
1496
                get_lang('TicketUpdated'),
1497
                get_lang('TicketUpdated')
1498
            );
1499
1500
            return true;
1501
        }
1502
1503
        return false;
1504
    }
1505
1506
    /**
1507
     * @return mixed
1508
     */
1509
    public static function getNumberOfMessages()
1510
    {
1511
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1512
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1513
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1514
        $table_main_admin = Database::get_main_table(TABLE_MAIN_ADMIN);
1515
        $user_info = api_get_user_info();
1516
        $userId = $user_info['user_id'];
1517
        $sql = "SELECT COUNT(DISTINCT ticket.id) AS unread
1518
                FROM $table_support_tickets ticket,
1519
                $table_support_messages message ,
1520
                $table_main_user user
1521
                WHERE
1522
                    ticket.id = message.ticket_id AND
1523
                    message.status = 'NOL' AND
1524
                    user.user_id = message.sys_insert_user_id ";
1525
        if (!api_is_platform_admin()) {
1526
            $sql .= " AND ticket.request_user = '$userId'
1527
                      AND user_id IN (SELECT user_id FROM $table_main_admin)  ";
1528
        } else {
1529
            $sql .= " AND user_id NOT IN (SELECT user_id FROM $table_main_admin)
1530
                      AND ticket.status_id != '".self::STATUS_FORWARDED."'";
1531
        }
1532
        $sql .= "  AND ticket.project_id != '' ";
1533
        $res = Database::query($sql);
1534
        $obj = Database::fetch_object($res);
1535
1536
        return $obj->unread;
1537
    }
1538
1539
    /**
1540
     * @param int $ticketId
1541
     * @param int $userId
1542
     */
1543
    public static function send_alert($ticketId, $userId)
1544
    {
1545
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1546
        $now = api_get_utc_datetime();
1547
1548
        $ticketId = (int) $ticketId;
1549
        $userId = (int) $userId;
1550
1551
        $sql = "UPDATE $table_support_tickets SET
1552
                  priority_id = '".self::PRIORITY_HIGH."',
1553
                  sys_lastedit_user_id = $userId,
1554
                  sys_lastedit_datetime = '$now'
1555
                WHERE id = $ticketId";
1556
        Database::query($sql);
1557
    }
1558
1559
    /**
1560
     * @param int $ticketId
1561
     * @param int $userId
1562
     */
1563
    public static function close_ticket($ticketId, $userId)
1564
    {
1565
        $ticketId = (int) $ticketId;
1566
        $userId = (int) $userId;
1567
1568
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1569
        $now = api_get_utc_datetime();
1570
        $sql = "UPDATE $table_support_tickets SET
1571
                    status_id = '".self::STATUS_CLOSE."',
1572
                    sys_lastedit_user_id ='$userId',
1573
                    sys_lastedit_datetime ='".$now."',
1574
                    end_date ='$now'
1575
                WHERE id ='$ticketId'";
1576
        Database::query($sql);
1577
1578
        self::sendNotification(
1579
            $ticketId,
1580
            get_lang('TicketClosed'),
1581
            get_lang('TicketClosed')
1582
        );
1583
    }
1584
1585
    /**
1586
     * Close old tickets.
1587
     */
1588
    public static function close_old_tickets()
1589
    {
1590
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
1591
        $now = api_get_utc_datetime();
1592
        $userId = api_get_user_id();
1593
        $sql = "UPDATE $table
1594
                SET
1595
                    status_id = '".self::STATUS_CLOSE."',
1596
                    sys_lastedit_user_id ='$userId',
1597
                    sys_lastedit_datetime ='$now',
1598
                    end_date = '$now'
1599
                WHERE
1600
                    DATEDIFF('$now', sys_lastedit_datetime) > 7 AND
1601
                    status_id != '".self::STATUS_CLOSE."' AND
1602
                    status_id != '".self::STATUS_NEW."' AND
1603
                    status_id != '".self::STATUS_FORWARDED."'";
1604
        Database::query($sql);
1605
    }
1606
1607
    /**
1608
     * @param int $ticketId
1609
     *
1610
     * @return array
1611
     */
1612
    public static function get_assign_log($ticketId)
1613
    {
1614
        $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
1615
        $ticketId = (int) $ticketId;
1616
1617
        $sql = "SELECT * FROM $table
1618
                WHERE ticket_id = $ticketId
1619
                ORDER BY assigned_date DESC";
1620
        $result = Database::query($sql);
1621
        $history = [];
1622
        $webpath = api_get_path(WEB_PATH);
1623
        while ($row = Database::fetch_assoc($result)) {
1624
            if ($row['user_id'] != 0) {
1625
                $assignuser = api_get_user_info($row['user_id']);
1626
                $row['assignuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['user_id'].'"  target="_blank">'.
1627
                $assignuser['username'].'</a>';
1628
            } else {
1629
                $row['assignuser'] = get_lang('Unassign');
1630
            }
1631
            $row['assigned_date'] = Display::dateToStringAgoAndLongDate($row['assigned_date']);
1632
            $insertuser = api_get_user_info($row['sys_insert_user_id']);
1633
            $row['insertuser'] = '<a href="'.$webpath.'main/admin/user_information.php?user_id='.$row['sys_insert_user_id'].'"  target="_blank">'.
1634
                $insertuser['username'].'</a>';
1635
            $history[] = $row;
1636
        }
1637
1638
        return $history;
1639
    }
1640
1641
    /**
1642
     * @param $from
1643
     * @param $number_of_items
1644
     * @param $column
1645
     * @param $direction
1646
     * @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...
1647
     *
1648
     * @return array
1649
     */
1650
    public static function export_tickets_by_user_id(
1651
        $from,
1652
        $number_of_items,
1653
        $column,
1654
        $direction,
1655
        $userId = null
1656
    ) {
1657
        $from = (int) $from;
1658
        $number_of_items = (int) $number_of_items;
1659
        $table_support_category = Database::get_main_table(
1660
            TABLE_TICKET_CATEGORY
1661
        );
1662
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1663
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1664
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1665
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1666
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1667
1668
        if (is_null($direction)) {
1669
            $direction = 'DESC';
1670
        }
1671
        if (is_null($userId) || $userId == 0) {
1672
            $userId = api_get_user_id();
1673
        }
1674
1675
        $sql = "SELECT
1676
                    ticket.code,
1677
                    ticket.sys_insert_datetime,
1678
                    ticket.sys_lastedit_datetime,
1679
                    cat.name as category,
1680
                    CONCAT(user.lastname,' ', user.firstname) AS fullname,
1681
                    status.name as status,
1682
                    ticket.total_messages as messages,
1683
                    ticket.assigned_last_user as responsable
1684
                FROM $table_support_tickets ticket,
1685
                $table_support_category cat ,
1686
                $table_support_priority priority,
1687
                $table_support_status status ,
1688
                $table_main_user user
1689
                WHERE
1690
                    cat.id = ticket.category_id
1691
                    AND ticket.priority_id = priority.id
1692
                    AND ticket.status_id = status.id
1693
                    AND user.user_id = ticket.request_user ";
1694
        // Search simple
1695
        if (isset($_GET['submit_simple'])) {
1696
            if ($_GET['keyword'] !== '') {
1697
                $keyword = Database::escape_string(trim($_GET['keyword']));
1698
                $sql .= " AND (ticket.code = '$keyword'
1699
                          OR user.firstname LIKE '%$keyword%'
1700
                          OR user.lastname LIKE '%$keyword%'
1701
                          OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword%'
1702
                          OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword%'
1703
                          OR user.username LIKE '%$keyword%')  ";
1704
            }
1705
        }
1706
        // Search advanced
1707
        if (isset($_GET['submit_advanced'])) {
1708
            $keyword_category = Database::escape_string(
1709
                trim($_GET['keyword_category'])
1710
            );
1711
            $keyword_request_user = Database::escape_string(
1712
                trim($_GET['keyword_request_user'])
1713
            );
1714
            $keywordAssignedTo = (int) $_GET['keyword_assigned_to'];
1715
            $keyword_start_date_start = Database::escape_string(
1716
                trim($_GET['keyword_start_date_start'])
1717
            );
1718
            $keyword_start_date_end = Database::escape_string(
1719
                trim($_GET['keyword_start_date_end'])
1720
            );
1721
            $keyword_status = Database::escape_string(
1722
                trim($_GET['keyword_status'])
1723
            );
1724
            $keyword_source = Database::escape_string(
1725
                trim($_GET['keyword_source'])
1726
            );
1727
            $keyword_priority = Database::escape_string(
1728
                trim($_GET['keyword_priority'])
1729
            );
1730
            $keyword_range = Database::escape_string(
1731
                trim($_GET['keyword_dates'])
1732
            );
1733
            $keyword_unread = Database::escape_string(
1734
                trim($_GET['keyword_unread'])
1735
            );
1736
            $keyword_course = Database::escape_string(
1737
                trim($_GET['keyword_course'])
1738
            );
1739
1740
            if ($keyword_category != '') {
1741
                $sql .= " AND ticket.category_id = '$keyword_category'  ";
1742
            }
1743
            if ($keyword_request_user != '') {
1744
                $sql .= " AND (ticket.request_user = '$keyword_request_user'
1745
                          OR user.firstname LIKE '%$keyword_request_user%'
1746
                          OR user.official_code LIKE '%$keyword_request_user%'
1747
                          OR user.lastname LIKE '%$keyword_request_user%'
1748
                          OR concat(user.firstname,' ',user.lastname) LIKE '%$keyword_request_user%'
1749
                          OR concat(user.lastname,' ',user.firstname) LIKE '%$keyword_request_user%'
1750
                          OR user.username LIKE '%$keyword_request_user%') ";
1751
            }
1752
            if (!empty($keywordAssignedTo)) {
1753
                $sql .= " AND ticket.assigned_last_user = $keywordAssignedTo ";
1754
            }
1755
            if ($keyword_status != '') {
1756
                $sql .= " AND ticket.status_id = '$keyword_status'  ";
1757
            }
1758
            if ($keyword_range == '' && $keyword_start_date_start != '') {
1759
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
1760
            }
1761
            if ($keyword_range == '1' && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
1762
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
1763
                          AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
1764
            }
1765
            if ($keyword_priority != '') {
1766
                $sql .= " AND ticket.priority_id = '$keyword_priority'  ";
1767
            }
1768
            if ($keyword_source != '') {
1769
                $sql .= " AND ticket.source = '$keyword_source' ";
1770
            }
1771
            if ($keyword_priority != '') {
1772
                $sql .= " AND ticket.priority_id = '$keyword_priority' ";
1773
            }
1774
            if ($keyword_course != '') {
1775
                $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1776
                $sql .= " AND ticket.course_id IN ( ";
1777
                $sql .= "SELECT id
1778
                         FROM $course_table
1779
                         WHERE (title LIKE '%$keyword_course%'
1780
                         OR code LIKE '%$keyword_course%'
1781
                         OR visual_code LIKE '%$keyword_course%' )) ";
1782
            }
1783
            if ($keyword_unread == 'yes') {
1784
                $sql .= " AND ticket.id IN (
1785
                          SELECT ticket.id
1786
                          FROM $table_support_tickets ticket,
1787
                          $table_support_messages message,
1788
                          $table_main_user user
1789
                          WHERE ticket.id = message.ticket_id
1790
                          AND message.status = 'NOL'
1791
                          AND message.sys_insert_user_id = user.user_id
1792
                          AND user.status != 1   AND ticket.status_id != '".self::STATUS_FORWARDED."'
1793
                          GROUP BY ticket.id)";
1794
            } else {
1795
                if ($keyword_unread == 'no') {
1796
                    $sql .= " AND ticket.id NOT IN (
1797
                              SELECT ticket.id
1798
                              FROM  $table_support_tickets ticket,
1799
                              $table_support_messages message,
1800
                              $table_main_user user
1801
                              WHERE ticket.id = message.ticket_id
1802
                              AND message.status = 'NOL'
1803
                              AND message.sys_insert_user_id = user.user_id
1804
                              AND user.status != 1
1805
                              AND ticket.status_id != '".self::STATUS_FORWARDED."'
1806
                             GROUP BY ticket.id)";
1807
                }
1808
            }
1809
        }
1810
1811
        $sql .= " LIMIT $from,$number_of_items";
1812
1813
        $result = Database::query($sql);
1814
        $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...
1815
            utf8_decode('Ticket#'),
1816
            utf8_decode('Fecha'),
1817
            utf8_decode('Fecha Edicion'),
1818
            utf8_decode('Categoria'),
1819
            utf8_decode('Usuario'),
1820
            utf8_decode('Estado'),
1821
            utf8_decode('Mensajes'),
1822
            utf8_decode('Responsable'),
1823
            utf8_decode('Programa'),
1824
        ];
1825
1826
        while ($row = Database::fetch_assoc($result)) {
1827
            if ($row['responsable'] != 0) {
1828
                $row['responsable'] = api_get_user_info($row['responsable']);
1829
                $row['responsable'] = $row['responsable']['firstname'].' '.$row['responsable']['lastname'];
1830
            }
1831
            $row['sys_insert_datetime'] = api_format_date(
1832
                $row['sys_insert_datetime'],
1833
                '%d/%m/%y - %I:%M:%S %p'
1834
            );
1835
            $row['sys_lastedit_datetime'] = api_format_date(
1836
                $row['sys_lastedit_datetime'],
1837
                '%d/%m/%y - %I:%M:%S %p'
1838
            );
1839
            $row['category'] = utf8_decode($row['category']);
1840
            $row['programa'] = utf8_decode($row['fullname']);
1841
            $row['fullname'] = utf8_decode($row['fullname']);
1842
            $row['responsable'] = utf8_decode($row['responsable']);
1843
            $tickets[] = $row;
1844
        }
1845
1846
        return $tickets;
1847
    }
1848
1849
    /**
1850
     * @param string $url
1851
     * @param int    $projectId
1852
     *
1853
     * @return FormValidator
1854
     */
1855
    public static function getCategoryForm($url, $projectId)
1856
    {
1857
        $form = new FormValidator('category', 'post', $url);
1858
        $form->addText('name', get_lang('Name'));
1859
        $form->addHtmlEditor('description', get_lang('Description'));
1860
        $form->addHidden('project_id', $projectId);
1861
        $form->addButtonUpdate(get_lang('Save'));
1862
1863
        return $form;
1864
    }
1865
1866
    /**
1867
     * @return array
1868
     */
1869
    public static function getStatusList()
1870
    {
1871
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
1872
1873
        $list = [];
1874
        /** @var Status $row */
1875
        foreach ($items as $row) {
1876
            $list[$row->getId()] = $row->getName();
1877
        }
1878
1879
        return $list;
1880
    }
1881
1882
    /**
1883
     * @param array $criteria
1884
     *
1885
     * @return array
1886
     */
1887
    public static function getTicketsFromCriteria($criteria)
1888
    {
1889
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Ticket')->findBy($criteria);
1890
1891
        $list = [];
1892
        /** @var Ticket $row */
1893
        foreach ($items as $row) {
1894
            $list[$row->getId()] = $row->getCode();
1895
        }
1896
1897
        return $list;
1898
    }
1899
1900
    /**
1901
     * @param string $code
1902
     *
1903
     * @return int
1904
     */
1905
    public static function getStatusIdFromCode($code)
1906
    {
1907
        $item = Database::getManager()
1908
            ->getRepository('ChamiloTicketBundle:Status')
1909
            ->findOneBy(['code' => $code])
1910
        ;
1911
1912
        if ($item) {
1913
            return $item->getId();
1914
        }
1915
1916
        return 0;
1917
    }
1918
1919
    /**
1920
     * @return array
1921
     */
1922
    public static function getPriorityList()
1923
    {
1924
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
1925
1926
        $list = [];
1927
        /** @var Priority $row */
1928
        foreach ($projects as $row) {
1929
            $list[$row->getId()] = $row->getName();
1930
        }
1931
1932
        return $list;
1933
    }
1934
1935
    /**
1936
     * @return array
1937
     */
1938
    public static function getProjects()
1939
    {
1940
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
1941
1942
        $list = [];
1943
        /** @var Project $row */
1944
        foreach ($projects as $row) {
1945
            $list[] = [
1946
                'id' => $row->getId(),
1947
                '0' => $row->getId(),
1948
                '1' => $row->getName(),
1949
                '2' => $row->getDescription(),
1950
                '3' => $row->getId(),
1951
            ];
1952
        }
1953
1954
        return $list;
1955
    }
1956
1957
    /**
1958
     * @return array
1959
     */
1960
    public static function getProjectsSimple()
1961
    {
1962
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->findAll();
1963
1964
        $list = [];
1965
        /** @var Project $row */
1966
        foreach ($projects as $row) {
1967
            $list[] = [
1968
                'id' => $row->getId(),
1969
                '0' => $row->getId(),
1970
                '1' => Display::url(
1971
                    $row->getName(),
1972
                    api_get_path(WEB_CODE_PATH).'ticket/tickets.php?project_id='.$row->getId()
1973
                ),
1974
                '2' => $row->getDescription(),
1975
            ];
1976
        }
1977
1978
        return $list;
1979
    }
1980
1981
    /**
1982
     * @return int
1983
     */
1984
    public static function getProjectsCount()
1985
    {
1986
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Project')->createQueryBuilder('p')
1987
            ->select('COUNT(p.id)')
1988
            ->getQuery()
1989
            ->getSingleScalarResult();
1990
1991
        return $count;
1992
    }
1993
1994
    /**
1995
     * @param array $params
1996
     */
1997
    public static function addProject($params)
1998
    {
1999
        $project = new Project();
2000
        $project->setName($params['name']);
2001
        $project->setDescription($params['description']);
2002
        $project->setInsertUserId(api_get_user_id());
2003
2004
        Database::getManager()->persist($project);
2005
        Database::getManager()->flush();
2006
    }
2007
2008
    /**
2009
     * @param int $id
2010
     *
2011
     * @return Project
2012
     */
2013
    public static function getProject($id)
2014
    {
2015
        return Database::getManager()->getRepository('ChamiloTicketBundle:Project')->find($id);
2016
    }
2017
2018
    /**
2019
     * @param int   $id
2020
     * @param array $params
2021
     */
2022
    public static function updateProject($id, $params)
2023
    {
2024
        $project = self::getProject($id);
2025
        $project->setName($params['name']);
2026
        $project->setDescription($params['description']);
2027
        $project->setLastEditDateTime(new DateTime($params['sys_lastedit_datetime']));
2028
        $project->setLastEditUserId($params['sys_lastedit_user_id']);
2029
2030
        Database::getManager()->merge($project);
2031
        Database::getManager()->flush();
2032
    }
2033
2034
    /**
2035
     * @param int $id
2036
     */
2037
    public static function deleteProject($id)
2038
    {
2039
        $project = self::getProject($id);
2040
        if ($project) {
0 ignored issues
show
introduced by
$project is of type Chamilo\TicketBundle\Entity\Project, thus it always evaluated to true.
Loading history...
2041
            Database::getManager()->remove($project);
2042
            Database::getManager()->flush();
2043
        }
2044
    }
2045
2046
    /**
2047
     * @param string $url
2048
     *
2049
     * @return FormValidator
2050
     */
2051
    public static function getProjectForm($url)
2052
    {
2053
        $form = new FormValidator('project', 'post', $url);
2054
        $form->addText('name', get_lang('Name'));
2055
        $form->addHtmlEditor('description', get_lang('Description'));
2056
        $form->addButtonUpdate(get_lang('Save'));
2057
2058
        return $form;
2059
    }
2060
2061
    /**
2062
     * @return array
2063
     */
2064
    public static function getStatusAdminList()
2065
    {
2066
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
2067
2068
        $list = [];
2069
        /** @var Status $row */
2070
        foreach ($items as $row) {
2071
            $list[] = [
2072
                'id' => $row->getId(),
2073
                'code' => $row->getCode(),
2074
                '0' => $row->getId(),
2075
                '1' => $row->getName(),
2076
                '2' => $row->getDescription(),
2077
                '3' => $row->getId(),
2078
            ];
2079
        }
2080
2081
        return $list;
2082
    }
2083
2084
    /**
2085
     * @return array
2086
     */
2087
    public static function getStatusSimple()
2088
    {
2089
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->findAll();
2090
2091
        $list = [];
2092
        /** @var Project $row */
2093
        foreach ($projects as $row) {
2094
            $list[] = [
2095
                'id' => $row->getId(),
2096
                '0' => $row->getId(),
2097
                '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

2097
                '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...
2098
                '2' => $row->getDescription(),
2099
            ];
2100
        }
2101
2102
        return $list;
2103
    }
2104
2105
    /**
2106
     * @return int
2107
     */
2108
    public static function getStatusCount()
2109
    {
2110
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->createQueryBuilder('p')
2111
            ->select('COUNT(p.id)')
2112
            ->getQuery()
2113
            ->getSingleScalarResult();
2114
2115
        return $count;
2116
    }
2117
2118
    /**
2119
     * @param array $params
2120
     */
2121
    public static function addStatus($params)
2122
    {
2123
        $item = new Status();
2124
        $item->setCode(URLify::filter($params['name']));
2125
        $item->setName($params['name']);
2126
        $item->setDescription($params['description']);
2127
2128
        Database::getManager()->persist($item);
2129
        Database::getManager()->flush();
2130
    }
2131
2132
    /**
2133
     * @param $id
2134
     *
2135
     * @return Project
2136
     */
2137
    public static function getStatus($id)
2138
    {
2139
        return Database::getManager()->getRepository('ChamiloTicketBundle:Status')->find($id);
2140
    }
2141
2142
    /**
2143
     * @param int   $id
2144
     * @param array $params
2145
     */
2146
    public static function updateStatus($id, $params)
2147
    {
2148
        $item = self::getStatus($id);
2149
        $item->setName($params['name']);
2150
        $item->setDescription($params['description']);
2151
2152
        Database::getManager()->merge($item);
2153
        Database::getManager()->flush();
2154
    }
2155
2156
    /**
2157
     * @param int $id
2158
     */
2159
    public static function deleteStatus($id)
2160
    {
2161
        $item = self::getStatus($id);
2162
        if ($item) {
0 ignored issues
show
introduced by
$item is of type Chamilo\TicketBundle\Entity\Project, thus it always evaluated to true.
Loading history...
2163
            Database::getManager()->remove($item);
2164
            Database::getManager()->flush();
2165
        }
2166
    }
2167
2168
    /**
2169
     * @param string $url
2170
     *
2171
     * @return FormValidator
2172
     */
2173
    public static function getStatusForm($url)
2174
    {
2175
        $form = new FormValidator('status', 'post', $url);
2176
        $form->addText('name', get_lang('Name'));
2177
        $form->addHtmlEditor('description', get_lang('Description'));
2178
        $form->addButtonUpdate(get_lang('Save'));
2179
2180
        return $form;
2181
    }
2182
2183
    /**
2184
     * @return array
2185
     */
2186
    public static function getPriorityAdminList()
2187
    {
2188
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2189
2190
        $list = [];
2191
        /** @var Status $row */
2192
        foreach ($items as $row) {
2193
            $list[] = [
2194
                'id' => $row->getId(),
2195
                'code' => $row->getCode(),
2196
                '0' => $row->getId(),
2197
                '1' => $row->getName(),
2198
                '2' => $row->getDescription(),
2199
                '3' => $row->getId(),
2200
            ];
2201
        }
2202
2203
        return $list;
2204
    }
2205
2206
    /**
2207
     * @return array
2208
     */
2209
    public static function getPrioritySimple()
2210
    {
2211
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2212
2213
        $list = [];
2214
        /** @var Priority $row */
2215
        foreach ($projects as $row) {
2216
            $list[] = [
2217
                'id' => $row->getId(),
2218
                '0' => $row->getId(),
2219
                '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

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