Test Setup Failed
Push — master ( ec638a...cb9435 )
by Julito
51:10
created

TicketManager::deleteUserFromTicketSystem()   D

Complexity

Conditions 9
Paths 256

Size

Total Lines 69
Code Lines 43

Duplication

Lines 42
Ratio 60.87 %

Importance

Changes 0
Metric Value
cc 9
eloc 43
nc 256
nop 1
dl 42
loc 69
rs 4.3212
c 0
b 0
f 0

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\TicketBundle\Entity\Project;
5
use Chamilo\TicketBundle\Entity\Status;
6
use Chamilo\TicketBundle\Entity\Priority;
7
use Chamilo\TicketBundle\Entity\Ticket;
8
9
/**
10
 * Class TicketManager
11
 * @package chamilo.plugin.ticket
12
 */
13
class TicketManager
14
{
15
    const PRIORITY_NORMAL = 'NRM';
16
    const PRIORITY_HIGH = 'HGH';
17
    const PRIORITY_LOW = 'LOW';
18
19
    const SOURCE_EMAIL = 'MAI';
20
    const SOURCE_PHONE = 'TEL';
21
    const SOURCE_PLATFORM = 'PLA';
22
    const SOURCE_PRESENTIAL = 'PRE';
23
24
    const STATUS_NEW = 'NAT';
25
    const STATUS_PENDING = 'PND';
26
    const STATUS_UNCONFIRMED = 'XCF';
27
    const STATUS_CLOSE = 'CLS';
28
    const STATUS_FORWARDED = 'REE';
29
30
    /**
31
     * Constructor
32
     */
33
    public function __construct()
34
    {
35
    }
36
37
    /**
38
     * Get categories of tickets
39
     *
40
     * @param int $projectId
41
     * @param string $order
42
     *
43
     * @return array
44
     */
45
    public static function get_all_tickets_categories($projectId, $order = '')
46
    {
47
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
48
        $table_support_project = Database::get_main_table(TABLE_TICKET_PROJECT);
49
50
        $order = empty($order) ? 'category.total_tickets DESC' : $order;
51
        $projectId = (int) $projectId;
52
53
        $sql = "SELECT 
54
                    category.*, 
55
                    category.id category_id,
56
                    project.other_area, 
57
                    project.email
58
                FROM 
59
                $table_support_category category 
60
                INNER JOIN $table_support_project project
61
                ON project.id = category.project_id
62
                WHERE project.id  = $projectId
63
                ORDER BY $order";
64
        $result = Database::query($sql);
65
        $types = array();
66
        while ($row = Database::fetch_assoc($result)) {
67
            $types[] = $row;
68
        }
69
70
        return $types;
71
    }
72
73
    /**
74
     * @param $from
75
     * @param $numberItems
76
     * @param $column
77
     * @param $direction
78
     * @return array
79
     */
80
    public static function getCategories($from, $numberItems, $column, $direction)
81
    {
82
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
83
        $sql = "SELECT id, name, description, total_tickets
84
                FROM $table";
85
86
        if (!in_array($direction, array('ASC','DESC'))) {
87
            $direction = 'ASC';
88
        }
89
        $column = intval($column);
90
        $from = intval($from);
91
        $numberItems = intval($numberItems);
92
93
        //$sql .= " ORDER BY col$column $direction ";
94
        $sql .= " LIMIT $from,$numberItems";
95
96
        $result = Database::query($sql);
97
        $types = array();
98
        while ($row = Database::fetch_array($result)) {
99
            $types[] = $row;
100
        }
101
102
        return $types;
103
    }
104
105
    /**
106
     * @param int $id
107
     * @return array|mixed
108
     */
109 View Code Duplication
    public static function getCategory($id)
110
    {
111
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
112
        $id = intval($id);
113
        $sql = "SELECT id, name, description, total_tickets
114
                FROM $table WHERE id = $id";
115
116
        $result = Database::query($sql);
117
        $category = Database::fetch_array($result);
118
119
        return $category;
120
    }
121
122
    /**
123
     * @return int
124
     */
125 View Code Duplication
    public static function getCategoriesCount()
126
    {
127
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
128
129
        $sql = "SELECT count(id) count
130
                FROM $table ";
131
132
        $result = Database::query($sql);
133
        $category = Database::fetch_array($result);
134
135
        return $category['count'];
136
    }
137
138
    /**
139
     * @param int $id
140
     * @param array $params
141
     */
142
    public static function updateCategory($id, $params)
143
    {
144
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
145
        $id = intval($id);
146
        Database::update($table, $params, ['id = ?' => $id]);
147
    }
148
149
    /**
150
     * @param array $params
151
     */
152
    public static function addCategory($params)
153
    {
154
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
155
        Database::insert($table, $params);
156
    }
157
158
    /**
159
     * @param int $id
160
     *
161
     * @return bool
162
     */
163 View Code Duplication
    public static function deleteCategory($id)
164
    {
165
        $id = intval($id);
166
        if (empty($id)) {
167
            return false;
168
        }
169
170
        $table = Database::get_main_table(TABLE_TICKET_TICKET);
171
        $sql = "UPDATE $table SET category_id = NULL WHERE category_id = $id";
172
        Database::query($sql);
173
174
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY);
175
        $sql = "DELETE FROM $table WHERE id = $id";
176
        Database::query($sql);
177
178
        return true;
179
    }
180
181
    /**
182
     * @param int $categoryId
183
     * @param array $users
184
     *
185
     * @return bool
186
     */
187
    public static function addUsersToCategory($categoryId, $users)
188
    {
189
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
190
        if (empty($users) || empty($categoryId)) {
191
            return false;
192
        }
193
194
        foreach ($users as $userId) {
195
            if (self::userIsAssignedToCategory($userId, $categoryId) == false) {
196
                $params = [
197
                    'category_id' => $categoryId,
198
                    'user_id' => $userId
199
                ];
200
                Database::insert($table, $params);
201
            }
202
        }
203
204
        return true;
205
    }
206
207
    /**
208
     * @param int $userId
209
     * @param int $categoryId
210
     *
211
     * @return bool
212
     */
213
    public static function userIsAssignedToCategory($userId, $categoryId)
214
    {
215
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
216
        $userId = intval($userId);
217
        $categoryId = intval($categoryId);
218
        $sql = "SELECT * FROM $table 
219
                WHERE category_id = $categoryId AND user_id = $userId";
220
        $result = Database::query($sql);
221
222
        return Database::num_rows($result) > 0;
223
    }
224
225
    /**
226
     * @param int $categoryId
227
     *
228
     * @return array
229
     */
230 View Code Duplication
    public static function getUsersInCategory($categoryId)
231
    {
232
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
233
        $categoryId = intval($categoryId);
234
        $sql = "SELECT * FROM $table WHERE category_id = $categoryId";
235
        $result = Database::query($sql);
236
237
        return Database::store_result($result);
238
    }
239
240
    /**
241
     * @param int $categoryId
242
     */
243 View Code Duplication
    public static function deleteAllUserInCategory($categoryId)
244
    {
245
        $table = Database::get_main_table(TABLE_TICKET_CATEGORY_REL_USER);
246
        $categoryId = intval($categoryId);
247
        $sql = "DELETE FROM $table WHERE category_id = $categoryId";
248
        Database::query($sql);
249
    }
250
251
    /**
252
     * Get all possible tickets statuses
253
     * @return array
254
     */
255
    public static function get_all_tickets_status()
256
    {
257
        $table = Database::get_main_table(TABLE_TICKET_STATUS);
258
        $sql = "SELECT * FROM " . $table;
259
        $result = Database::query($sql);
260
        $types = array();
261
        while ($row = Database::fetch_assoc($result)) {
262
            $types[] = $row;
263
        }
264
265
        return $types;
266
    }
267
268
    /**
269
     * Inserts a new ticket in the corresponding tables
270
     * @param int $category_id
271
     * @param int $course_id
272
     * @param int $sessionId
273
     * @param int $project_id
274
     * @param string $other_area
275
     * @param string $subject
276
     * @param string $content
277
     * @param string $personalEmail
278
     * @param $file_attachments
279
     * @param string $source
280
     * @param string $priority
281
     * @param string $status
282
     * @param int $assignedUserId
283
     *
284
     * @return bool
285
     */
286
    public static function add(
287
        $category_id,
288
        $course_id,
289
        $sessionId,
290
        $project_id,
291
        $other_area,
292
        $subject,
293
        $content,
294
        $personalEmail = '',
295
        $file_attachments = [],
296
        $source = '',
297
        $priority = '',
298
        $status = '',
299
        $assignedUserId = 0
300
    ) {
301
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
302
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
303
304
        if (empty($category_id)) {
305
            return false;
306
        }
307
308
        $currentUserId = api_get_user_id();
309
        $currentUserInfo = api_get_user_info();
310
        $now = api_get_utc_datetime();
311
        $course_id = intval($course_id);
312
        $category_id = intval($category_id);
313
        $project_id = intval($project_id);
314
        $priority = empty($priority) ? self::PRIORITY_NORMAL : $priority;
315
316
        if ($status === '') {
317
            $status = self::STATUS_NEW;
318
            if ($other_area > 0) {
319
                $status = self::STATUS_FORWARDED;
320
            }
321
        }
322
323
        if (!empty($category_id)) {
324
            if (empty($assignedUserId)) {
325
                $usersInCategory = self::getUsersInCategory($category_id);
326
                if (!empty($usersInCategory) && count($usersInCategory) > 0) {
327
                    $userCategoryInfo = $usersInCategory[0];
328
                    if (isset($userCategoryInfo['user_id'])) {
329
                        $assignedUserId = $userCategoryInfo['user_id'];
330
                    }
331
                }
332
            }
333
        }
334
335
        $assignedUserInfo = [];
336
        if (!empty($assignedUserId)) {
337
            $assignedUserInfo = api_get_user_info($assignedUserId);
338
            if (empty($assignedUserInfo)) {
339
                return false;
340
            }
341
        }
342
343
344
        // insert_ticket
345
        $params = [
346
            'project_id' => $project_id,
347
            'category_id' => $category_id,
348
            'priority_id' => $priority,
349
            'personal_email' => $personalEmail,
350
            'status_id' => $status,
351
            'start_date' => $now,
352
            'sys_insert_user_id' => $currentUserId,
353
            'sys_insert_datetime' => $now,
354
            'sys_lastedit_user_id' => $currentUserId,
355
            'sys_lastedit_datetime' => $now,
356
            'source' => $source,
357
            'assigned_last_user' => $assignedUserId,
358
            'subject' => $subject,
359
            'message' => $content
360
        ];
361
362
        if (!empty($course_id)) {
363
            $params['course_id'] = $course_id;
364
        }
365
366
        if (!empty($sessionId)) {
367
            $params['session_id'] = $sessionId;
368
        }
369
        $ticketId = Database::insert($table_support_tickets, $params);
370
371
        if ($ticketId) {
372
            $ticket_code = "A" . str_pad($ticketId, 11, '0', STR_PAD_LEFT);
373
            $titleCreated = sprintf(
374
                get_lang('TicketXCreated'),
375
                $ticket_code
376
            );
377
378
            Display::addFlash(Display::return_message(
379
                $titleCreated,
380
                'normal',
381
                false
382
            ));
383
384
            if ($assignedUserId != 0) {
385
                self::assignTicketToUser(
386
                    $ticketId,
387
                    $assignedUserId
388
                );
389
390
                Display::addFlash(Display::return_message(
391
                    sprintf(
392
                        get_lang('TicketXAssignedToUserX'),
393
                        $ticket_code,
394
                        $assignedUserInfo['complete_name']
395
                    ),
396
                    'normal',
397
                    false
398
                ));
399
            }
400
401
            if (!empty($file_attachments)) {
402
                $attachmentCount = 0;
403
                foreach ($file_attachments as $attach) {
404
                    if (!empty($attach['tmp_name'])) {
405
                        $attachmentCount++;
406
                    }
407
                }
408
                if ($attachmentCount > 0) {
409
                    self::insertMessage(
410
                        $ticketId,
411
                        '',
412
                        '',
413
                        $file_attachments,
414
                        $currentUserId
415
                    );
416
                }
417
            }
418
419
            // Update code
420
            $sql = "UPDATE $table_support_tickets
421
                    SET code = '$ticket_code'
422
                    WHERE id = '$ticketId'";
423
            Database::query($sql);
424
425
            // Update total
426
            $sql = "UPDATE $table_support_category
427
                    SET total_tickets = total_tickets + 1
428
                    WHERE id = $category_id";
429
            Database::query($sql);
430
431
            $helpDeskMessage =
432
                '<table>
433
                        <tr>
434
                            <td width="100px"><b>' . get_lang('User') . '</b></td>
435
                            <td width="400px">' . $currentUserInfo['complete_name']. '</td>
436
                        </tr>
437
                        <tr>
438
                            <td width="100px"><b>' . get_lang('Username') . '</b></td>
439
                            <td width="400px">' . $currentUserInfo['username'] . '</td>
440
                        </tr>
441
                        <tr>
442
                            <td width="100px"><b>' . get_lang('Email') . '</b></td>
443
                            <td width="400px">' . $currentUserInfo['email'] . '</td>
444
                        </tr>
445
                        <tr>
446
                            <td width="100px"><b>' . get_lang('Phone') . '</b></td>
447
                            <td width="400px">' . $currentUserInfo['phone'] . '</td>
448
                        </tr>
449
                        <tr>
450
                            <td width="100px"><b>' . get_lang('Date') . '</b></td>
451
                            <td width="400px">' . api_convert_and_format_date($now, DATE_TIME_FORMAT_LONG) . '</td>
452
                        </tr>
453
                        <tr>
454
                            <td width="100px"><b>' . get_lang('Title') . '</b></td>
455
                            <td width="400px">' . $subject . '</td>
456
                        </tr>
457
                        <tr>
458
                            <td width="100px"><b>' . get_lang('Description') . '</b></td>
459
                            <td width="400px">' . $content . '</td>
460
                        </tr>
461
                    </table>';
462
463
            if ($assignedUserId != 0) {
464
                $href = api_get_path(WEB_CODE_PATH).'/ticket/ticket_details.php?ticket_id='.$ticketId;
465
                $helpDeskMessage .= sprintf(
466
                    get_lang('TicketAssignedToXCheckZAtLinkY'),
467
                    $assignedUserInfo['complete_name'],
468
                    $href,
469
                    $ticketId
470
                );
471
            }
472
473
            if (empty($category_id)) {
474
                if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
475
                    $warningSubject = sprintf(
476
                        get_lang('TicketXCreatedWithNoCategory'),
477
                        $ticket_code
478
                    );
479
                    Display::addFlash(Display::return_message($warningSubject));
480
481
                    $admins = UserManager::get_all_administrators();
482
                    foreach ($admins as $userId => $data) {
483
                        if ($data['active']) {
484
                            self::send_message_simple(
485
                                $userId,
486
                                $warningSubject,
487
                                $helpDeskMessage
488
                            );
489
                        }
490
                    }
491
                }
492
            } else {
493
                $categoryInfo = self::getCategory($category_id);
494
                $usersInCategory = self::getUsersInCategory($category_id);
495
496
                $message = '<h2>'.get_lang('TicketInformation').'</h2><br />'.$helpDeskMessage;
497
498
                if (api_get_setting('ticket_warn_admin_no_user_in_category') === 'true') {
499
                    $usersInCategory = self::getUsersInCategory($category_id);
500
                    if (empty($usersInCategory)) {
501
                        $subject = sprintf(
502
                            get_lang('WarningCategoryXDoesntHaveUsers'),
503
                            $categoryInfo['name']
504
                        );
505
506
                        if (api_get_setting('ticket_send_warning_to_all_admins') === 'true') {
507
                            Display::addFlash(Display::return_message(
508
                                sprintf(
509
                                    get_lang('CategoryWithNoUserNotificationSentToAdmins'),
510
                                    $categoryInfo['name']
511
                                ),
512
                                null,
513
                                false
514
                            ));
515
516
                            $admins = UserManager::get_all_administrators();
517
                            foreach ($admins as $userId => $data) {
518
                                if ($data['active']) {
519
                                    self::sendNotification(
520
                                        $ticketId,
521
                                        $subject,
522
                                        $message,
523
                                        $userId
524
                                    );
525
                                }
526
                            }
527
                        } else {
528
                            Display::addFlash(Display::return_message($subject));
529
                        }
530
                    }
531
                }
532
533
                // Send notification to all users
534
                if (!empty($usersInCategory)) {
535
                    foreach ($usersInCategory as $data) {
536
                        if ($data['user_id']) {
537
                            self::sendNotification(
538
                                $ticketId,
539
                                $subject,
540
                                $message,
541
                                $data['user_id']
542
                            );
543
                        }
544
                    }
545
                }
546
            }
547
548
            if (!empty($personalEmail)) {
549
                api_mail_html(
550
                    get_lang('VirtualSupport'),
551
                    $personalEmail,
552
                    get_lang('IncidentResentToVirtualSupport'),
553
                    $helpDeskMessage
554
                );
555
            }
556
557
            self::sendNotification(
558
                $ticketId,
559
                $titleCreated,
560
                $helpDeskMessage
561
            );
562
563
            return true;
564
        } else {
565
            return false;
566
        }
567
    }
568
569
    /**
570
     * Assign ticket to admin
571
     *
572
     * @param int $ticketId
573
     * @param int $userId
574
     *
575
     * @return bool
576
     */
577
    public static function assignTicketToUser(
578
        $ticketId,
579
        $userId
580
    ) {
581
        $ticketId = intval($ticketId);
582
        $userId = intval($userId);
583
584
        if (empty($ticketId)) {
585
            return false;
586
        }
587
588
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
589
        $ticket = self::get_ticket_detail_by_id($ticketId);
590
591
        if ($ticket) {
592
            $sql = "UPDATE $table_support_tickets
593
                    SET assigned_last_user = $userId
594
                    WHERE id = $ticketId";
595
            Database::query($sql);
596
597
            $table = Database::get_main_table(TABLE_TICKET_ASSIGNED_LOG);
598
            $params = [
599
                'ticket_id' => $ticketId,
600
                'user_id' => $userId,
601
                'sys_insert_user_id' => api_get_user_id(),
602
                'assigned_date' => api_get_utc_datetime()
603
            ];
604
            Database::insert($table, $params);
605
606
            return true;
607
        } else {
608
            return false;
609
        }
610
    }
611
612
    /**
613
     * Insert message between Users and Admins
614
     * @param int $ticketId
615
     * @param string $subject
616
     * @param string $content
617
     * @param array $file_attachments
618
     * @param int $userId
619
     * @param string $status
620
     * @param bool $sendConfirmation
621
     *
622
     * @return bool
623
     */
624
    public static function insertMessage(
625
        $ticketId,
626
        $subject,
627
        $content,
628
        $file_attachments,
629
        $userId,
630
        $status = 'NOL',
631
        $sendConfirmation = false
632
    ) {
633
        $ticketId = intval($ticketId);
634
        $userId = intval($userId);
635
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
636
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
637
        if ($sendConfirmation) {
638
            $form = '<form action="ticket_details.php?ticket_id=' . $ticketId . '" id="confirmticket" method="POST" >
639
                         <p>' . get_lang('TicketWasThisAnswerSatisfying') . '</p>
640
                         <button class="btn btn-primary responseyes" name="response" id="responseyes" value="1">' . get_lang('Yes') . '</button>
641
                         <button class="btn btn-danger responseno" name="response" id="responseno" value="0">' . get_lang('No') . '</button>
642
                     </form>';
643
            $content .= $form;
644
        }
645
646
        $now = api_get_utc_datetime();
647
648
        $params = [
649
            'ticket_id' => $ticketId,
650
            'subject' => $subject,
651
            'message' => $content,
652
            'ip_address' => $_SERVER['REMOTE_ADDR'],
653
            'sys_insert_user_id' => $userId,
654
            'sys_insert_datetime' => $now,
655
            'sys_lastedit_user_id' => $userId,
656
            'sys_lastedit_datetime' => $now,
657
            'status' => $status
658
        ];
659
        $messageId = Database::insert($table_support_messages, $params);
660
        if ($messageId) {
661
            // update_total_message
662
            $sql = "UPDATE $table_support_tickets
663
                    SET 
664
                        sys_lastedit_user_id ='$userId',
665
                        sys_lastedit_datetime ='$now',
666
                        total_messages = (
667
                            SELECT COUNT(*) as total_messages
668
                            FROM $table_support_messages
669
                            WHERE ticket_id ='$ticketId'
670
                        )
671
                    WHERE id = $ticketId ";
672
            Database::query($sql);
673
674
            if (is_array($file_attachments)) {
675
                foreach ($file_attachments as $file_attach) {
676
                    if ($file_attach['error'] == 0) {
677
                        self::save_message_attachment_file(
678
                            $file_attach,
679
                            $ticketId,
680
                            $messageId
681
                        );
682
                    } else {
683
                        if ($file_attach['error'] != UPLOAD_ERR_NO_FILE) {
684
                            return false;
685
                        }
686
                    }
687
                }
688
            }
689
        }
690
691
        return true;
692
    }
693
694
    /**
695
     * Attachment files when a message is sent
696
     * @param $file_attach
697
     * @param $ticketId
698
     * @param $message_id
699
     * @return array
700
     */
701
    public static function save_message_attachment_file(
702
        $file_attach,
703
        $ticketId,
704
        $message_id
705
    ) {
706
        $now = api_get_utc_datetime();
707
        $userId = api_get_user_id();
708
        $ticketId = intval($ticketId);
709
        $new_file_name = add_ext_on_mime(
710
            stripslashes($file_attach['name']),
711
            $file_attach['type']
712
        );
713
        $file_name = $file_attach['name'];
714
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
715
        if (!filter_extension($new_file_name)) {
716
            Display::display_error_message(
0 ignored issues
show
Deprecated Code introduced by
The method Display::display_error_message() has been deprecated with message: use Display::addFlash(Display::return_message($message, 'error'));

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
717
                get_lang('UplUnableToSaveFileFilteredExtension')
718
            );
719
        } else {
720
            $new_file_name = uniqid('');
721
            $path_attachment = api_get_path(SYS_ARCHIVE_PATH);
722
            $path_message_attach = $path_attachment . 'plugin_ticket_messageattch/';
723
            if (!file_exists($path_message_attach)) {
724
                @mkdir($path_message_attach, api_get_permissions_for_new_directories(), true);
725
            }
726
            $new_path = $path_message_attach . $new_file_name;
727
            if (is_uploaded_file($file_attach['tmp_name'])) {
728
                @copy($file_attach['tmp_name'], $new_path);
729
            }
730
            $safe_file_name = Database::escape_string($file_name);
731
            $safe_new_file_name = Database::escape_string($new_file_name);
732
            $sql = "INSERT INTO $table_support_message_attachments (
733
                    filename,
734
                    path,
735
                    ticket_id,
736
                    message_id,
737
                    size,
738
                    sys_insert_user_id,
739
                    sys_insert_datetime,
740
                    sys_lastedit_user_id,
741
                    sys_lastedit_datetime
742
                ) VALUES (
743
                    '$safe_file_name',
744
                    '$safe_new_file_name',
745
                    '$ticketId',
746
                    '$message_id',
747
                    '" . $file_attach['size'] . "',
748
                    '$userId',
749
                    '$now',
750
                    '$userId',
751
                    '$now'
752
                )";
753
            Database::query($sql);
754
755
            return array(
756
                'path' => $path_message_attach . $safe_new_file_name,
757
                'filename' => $safe_file_name,
758
            );
759
        }
760
    }
761
762
    /**
763
     * Get tickets by userId
764
     * @param int $from
765
     * @param int  $number_of_items
766
     * @param $column
767
     * @param $direction
768
     * @param int $userId
769
     * @return array
770
     */
771
    public static function get_tickets_by_user_id(
772
        $from,
773
        $number_of_items,
774
        $column,
775
        $direction,
776
        $userId = 0
777
    ) {
778
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
779
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
780
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
781
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
782
        $direction = !empty($direction) ? $direction : 'DESC';
783
        $userId = !empty($userId) ? $userId : api_get_user_id();
784
        $isAdmin = UserManager::is_admin($userId);
785
786
        switch ($column) {
787
            case 0:
788
                $column = 'ticket_id';
789
                break;
790
            case 1:
791
                $column = 'status_name';
792
                break;
793
            case 2:
794
                $column = 'start_date';
795
                break;
796
            case 3:
797
                $column = 'sys_lastedit_datetime';
798
                break;
799
            case 4:
800
                $column = 'category_name';
801
                break;
802
            case 5:
803
                $column = 'sys_insert_user_id';
804
                break;
805
            case 6:
806
                $column = 'assigned_last_user';
807
                break;
808
            case 7:
809
                $column = 'total_messages';
810
                break;
811
            case 8:
812
                $column = 'subject';
813
                break;
814
            default:
815
                $column = 'ticket_id';
816
        }
817
818
        $sql = "SELECT DISTINCT 
819
                ticket.*,
820
                ticket.id ticket_id,
821
                status.name AS status_name,
822
                ticket.start_date,
823
                ticket.sys_lastedit_datetime,
824
                cat.name AS category_name,
825
                priority.name AS priority_name,                           
826
                ticket.total_messages AS total_messages,
827
                ticket.message AS message,
828
                ticket.subject AS subject,
829
                ticket.assigned_last_user
830
            FROM $table_support_tickets ticket 
831
            INNER JOIN $table_support_category cat
832
            ON (cat.id = ticket.category_id)
833
            INNER JOIN $table_support_priority priority
834
            ON (ticket.priority_id = priority.id)
835
            INNER JOIN $table_support_status status
836
            ON (ticket.status_id = status.id)
837
            WHERE 1=1                                
838
        ";
839
840
        if (!$isAdmin) {
841
            $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
842
        }
843
844
        // Search simple
845 View Code Duplication
        if (isset($_GET['submit_simple']) && $_GET['keyword'] != '') {
846
            $keyword = Database::escape_string(trim($_GET['keyword']));
847
            $sql .= " AND (
848
                      ticket.id LIKE '%$keyword%' OR
849
                      ticket.code LIKE '%$keyword%' OR
850
                      ticket.subject LIKE '%$keyword%' OR
851
                      ticket.message LIKE '%$keyword%' OR
852
                      ticket.keyword LIKE '%$keyword%' OR
853
                      ticket.source LIKE '%$keyword%' OR
854
                      ticket.personal_email LIKE '%$keyword%'                          
855
            )";
856
        }
857
858
        // Search advanced
859
        if (isset($_GET['submit_advanced'])) {
860
            $keyword_category = Database::escape_string(
861
                trim($_GET['keyword_category'])
862
            );
863
            $keyword_admin = Database::escape_string(
864
                trim($_GET['keyword_admin'])
865
            );
866
            $keyword_start_date_start = Database::escape_string(
867
                trim($_GET['keyword_start_date_start'])
868
            );
869
            $keyword_start_date_end = Database::escape_string(
870
                trim($_GET['keyword_start_date_end'])
871
            );
872
            $keyword_status = Database::escape_string(
873
                trim($_GET['keyword_status'])
874
            );
875
            $keyword_source = isset($_GET['keyword_source']) ? Database::escape_string(trim($_GET['keyword_source'])) : '';
876
            $keyword_priority = Database::escape_string(
877
                trim($_GET['keyword_priority'])
878
            );
879
880
            $keyword_range = !empty($keyword_start_date_start) && !empty($keyword_start_date_end);
881
            $keyword_course = Database::escape_string(trim($_GET['keyword_course']));
882
            if ($keyword_category != '') {
883
                $sql .= " AND ticket.category_id = '$keyword_category' ";
884
            }
885
886
            if ($keyword_admin != '') {
887
                $sql .= " AND ticket.assigned_last_user = '$keyword_admin' ";
888
            }
889
            if ($keyword_status != '') {
890
                $sql .= " AND ticket.status_id = '$keyword_status' ";
891
            }
892
893
            if ($keyword_range == false && $keyword_start_date_start != '') {
894
                $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start' ";
895
            }
896
            if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
897
                $sql .= " AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
898
                          AND DATE_FORMAT(ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
899
            }
900
            if ($keyword_priority != '') {
901
                $sql .= " AND ticket.priority_id = '$keyword_priority'  ";
902
            }
903
            if ($keyword_source != '') {
904
                $sql .= " AND ticket.source = '$keyword_source' ";
905
            }
906
            if ($keyword_course != '') {
907
                $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
908
                $sql .= " AND ticket.course_id IN ( 
909
                         SELECT id FROM $course_table
910
                         WHERE (
911
                            title LIKE '%$keyword_course%' OR 
912
                            code LIKE '%$keyword_course%' OR 
913
                            visual_code LIKE '%$keyword_course%'
914
                         )
915
                )";
916
            }
917
        }
918
919
        $sql .= " ORDER BY $column $direction";
920
        $sql .= " LIMIT $from, $number_of_items";
921
922
        $result = Database::query($sql);
923
        $tickets = array();
924
        $webPath = api_get_path(WEB_PATH);
925
        while ($row = Database::fetch_assoc($result)) {
926
            /*$sql_unread = "SELECT
927
                              COUNT(DISTINCT message.message_id) AS unread
928
                           FROM $table_support_tickets  ticket,
929
                                $table_support_messages message,
930
                                $table_main_user user
931
                           WHERE ticket.ticket_id = message.ticket_id
932
                           AND ticket.ticket_id = '{$row['col0']}'
933
                           AND message.status = 'NOL'
934
                           AND message.sys_insert_user_id = user.user_id ";
935
            if ($isAdmin) {
936
                $sql_unread .= " AND user.user_id
937
                                 NOT IN (SELECT user_id FROM $table_main_admin)
938
                                 AND ticket.status_id != '".self::STATUS_FORWARDED."' ";
939
            } else {
940
                $sql_unread .= " AND user.user_id
941
                                 IN (SELECT user_id FROM $table_main_admin) ";
942
            }
943
            $result_unread = Database::query($sql_unread);
944
            $unread = Database::fetch_object($result_unread)->unread;*/
945
946
            $userInfo = api_get_user_info($row['sys_insert_user_id']);
947
            $hrefUser = $webPath . 'main/admin/user_information.php?user_id=' . $userInfo['user_id'];
948
            $name = "<a href='$hrefUser'> {$userInfo['complete_name_with_username']} </a>";
949
            $actions = '';
950
951
            if ($row['assigned_last_user'] != 0) {
952
                $assignedUserInfo = api_get_user_info($row['assigned_last_user']);
953
                if (!empty($assignedUserInfo)) {
954
                    $hrefResp = $webPath . 'main/admin/user_information.php?user_id=' . $assignedUserInfo['user_id'];
955
                    $row['assigned_last_user'] = "<a href='$hrefResp'> {$assignedUserInfo['complete_name_with_username']} </a>";
956
                } else {
957
                    $row['assigned_last_user'] = get_lang('UnknownUser');
958
                }
959
            } else {
960
                if ($row['status_id'] !== self::STATUS_FORWARDED) {
961
                    $row['assigned_last_user'] = '<span style="color:#ff0000;">' . get_lang('ToBeAssigned') . '</span>';
962
                } else {
963
                    $row['assigned_last_user'] = '<span style="color:#00ff00;">' . get_lang('MessageResent') . '</span>';
964
                }
965
            }
966
967
            switch ($row['source']) {
968
                case self::SOURCE_PRESENTIAL:
969
                    $img_source = 'icons/32/user.png';
970
                    break;
971
                case self::SOURCE_EMAIL:
972
                    $img_source = 'icons/32/mail.png';
973
                    break;
974
                case self::SOURCE_PHONE:
975
                    $img_source = 'icons/32/event.png';
976
                    break;
977
                default:
978
                    $img_source = 'icons/32/course_home.png';
979
                    break;
980
            }
981
982
            $row['start_date'] = Display::dateToStringAgoAndLongDate($row['start_date']);
983
            $row['sys_lastedit_datetime'] = Display::dateToStringAgoAndLongDate($row['sys_lastedit_datetime']);
984
985
            $icon = Display::return_icon($img_source, get_lang('Info')).'<a href="ticket_details.php?ticket_id=' . $row['id'] . '">' . $row['code'] . '</a>';
986
987
            if ($isAdmin) {
988
                $ticket = array(
989
                    $icon.' '.$row['subject'],
990
                    $row['status_name'],
991
                    $row['start_date'],
992
                    $row['sys_lastedit_datetime'],
993
                    $row['category_name'],
994
                    $name,
995
                    $row['assigned_last_user'],
996
                    $row['total_messages']
997
                );
998
            } else {
999
                $actions = '';
1000
                /*
1001
                $now = api_strtotime(api_get_utc_datetime());
1002
                $last_edit_date = api_strtotime($row['sys_lastedit_datetime']);
1003
                $dif = $now - $last_edit_date;
1004
1005
                if ($dif > 172800 && $row['priority_id'] === self::PRIORITY_NORMAL && $row['status_id'] != self::STATUS_CLOSE) {
1006
                    $actions .= '<a href="'.api_get_path(WEB_CODE_PATH).'ticket/tickets.php?ticket_id=' . $row['ticket_id'] . '&amp;action=alert">
1007
                                 <img src="' . Display::returnIconPath('exclamation.png') . '" border="0" /></a>';
1008
                }
1009
                if ($row['priority_id'] === self::PRIORITY_HIGH) {
1010
                    $actions .= '<img src="' . Display::returnIconPath('admin_star.png') . '" border="0" />';
1011
                }*/
1012
                $ticket = array(
1013
                    $icon.' '.$row['subject'],
1014
                    $row['status_name'],
1015
                    $row['start_date'],
1016
                    $row['sys_lastedit_datetime'],
1017
                    $row['category_name']
1018
                );
1019
            }
1020
            /*if ($unread > 0) {
1021
                $ticket['0'] = $ticket['0'] . '&nbsp;&nbsp;(' . $unread . ')<a href="ticket_details.php?ticket_id=' . $row['ticket_id'] . '">
1022
                                <img src="' . Display::returnIconPath('message_new.png') . '" border="0" title="' . $unread . ' ' . get_lang('Messages') . '"/>
1023
                                </a>';
1024
            }*/
1025
            if ($isAdmin) {
1026
                $ticket['0'] .= '&nbsp;&nbsp;<a  href="javascript:void(0)" onclick="load_history_ticket(\'div_' . $row['ticket_id'] . '\',' . $row['ticket_id'] . ')">
1027
					<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') . '"/>
1028
					<div class="blackboard_hide" id="div_' . $row['ticket_id'] . '">&nbsp;&nbsp;</div>
1029
					</a>&nbsp;&nbsp;';
1030
            }
1031
            $tickets[] = $ticket;
1032
        }
1033
1034
        return $tickets;
1035
    }
1036
1037
    /**
1038
     * @param int $userId
1039
     * @return mixed
1040
     */
1041
    public static function get_total_tickets_by_user_id($userId = 0)
1042
    {
1043
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1044
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1045
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1046
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1047
1048
        $userId = api_get_user_id();
1049
1050
        $sql = "SELECT COUNT(ticket.id) AS total
1051
                FROM $table_support_tickets ticket
1052
                INNER JOIN $table_support_category cat
1053
                ON (cat.id = ticket.category_id)
1054
                INNER JOIN $table_support_priority priority
1055
                ON (ticket.priority_id = priority.id)
1056
                INNER JOIN $table_support_status status
1057
                ON (ticket.status_id = status.id)
1058
	        WHERE 1 = 1";
1059
1060
        if (!api_is_platform_admin()) {
1061
            $sql .= " AND (ticket.assigned_last_user = $userId OR ticket.sys_insert_user_id = $userId )";
1062
        }
1063
1064
        // Search simple
1065 View Code Duplication
        if (isset($_GET['submit_simple'])) {
1066
            if ($_GET['keyword'] != '') {
1067
                $keyword = Database::escape_string(trim($_GET['keyword']));
1068
                $sql .= " AND (
1069
                          ticket.code LIKE '%$keyword%' OR
1070
                          ticket.subject LIKE '%$keyword%' OR
1071
                          ticket.message LIKE '%$keyword%' OR
1072
                          ticket.keyword LIKE '%$keyword%' OR
1073
                          ticket.personal_email LIKE '%$keyword%' OR
1074
                          ticket.source LIKE '%$keyword%'
1075
                )";
1076
            }
1077
        }
1078
1079
        // Search advanced
1080
        if (isset($_GET['submit_advanced'])) {
1081
            $keyword_category = Database::escape_string(
1082
                trim($_GET['keyword_category'])
1083
            );
1084
            $keyword_admin = Database::escape_string(
1085
                trim($_GET['keyword_admin'])
1086
            );
1087
            $keyword_start_date_start = Database::escape_string(
1088
                trim($_GET['keyword_start_date_start'])
1089
            );
1090
            $keyword_start_date_end = Database::escape_string(
1091
                trim($_GET['keyword_start_date_end'])
1092
            );
1093
            $keyword_status = Database::escape_string(
1094
                trim($_GET['keyword_status'])
1095
            );
1096
            $keyword_source = isset($_GET['keyword_source']) ? Database::escape_string(trim($_GET['keyword_source'])) : '';
1097
            $keyword_priority = Database::escape_string(
1098
                trim($_GET['keyword_priority'])
1099
            );
1100
1101
            $keyword_range = isset($_GET['keyword_dates']) ? Database::escape_string(trim($_GET['keyword_dates'])) : '';
1102
            $keyword_course = Database::escape_string(
1103
                trim($_GET['keyword_course'])
1104
            );
1105
1106
            if ($keyword_category != '') {
1107
                $sql .= " AND ticket.category_id = '$keyword_category'  ";
1108
            }
1109
1110
            if ($keyword_admin != '') {
1111
                $sql .= " AND ticket.assigned_last_user = '$keyword_admin'  ";
1112
            }
1113
            if ($keyword_status != '') {
1114
                $sql .= " AND ticket.status_id = '$keyword_status'  ";
1115
            }
1116
            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...
1117
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') = '$keyword_start_date_start' ";
1118
            }
1119
            if ($keyword_range && $keyword_start_date_start != '' && $keyword_start_date_end != '') {
1120
                $sql .= " AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') >= '$keyword_start_date_start'
1121
                          AND DATE_FORMAT( ticket.start_date,'%d/%m/%Y') <= '$keyword_start_date_end'";
1122
            }
1123
            if ($keyword_priority != '') {
1124
                $sql .= " AND ticket.priority_id = '$keyword_priority'  ";
1125
            }
1126
            if ($keyword_source != '') {
1127
                $sql .= " AND ticket.source = '$keyword_source' ";
1128
            }
1129
            if ($keyword_priority != '') {
1130
                $sql .= " AND ticket.priority_id = '$keyword_priority' ";
1131
            }
1132
            if ($keyword_course != '') {
1133
                $course_table = Database::get_main_table(TABLE_MAIN_COURSE);
1134
                $sql .= " AND ticket.course_id IN ( ";
1135
                $sql .= "SELECT id
1136
                         FROM $course_table
1137
                         WHERE (title LIKE '%$keyword_course%'
1138
                         OR code LIKE '%$keyword_course%'
1139
                         OR visual_code LIKE '%$keyword_course%' )) ";
1140
            }
1141
        }
1142
        /*
1143
        if ($keyword_unread == 'yes') {
1144
            $sql .= " AND ticket.id IN ( ";
1145
            $sql .= "SELECT ticket.id
1146
                     FROM  $table_support_tickets ticket,
1147
                     $table_support_messages message,
1148
                     $table_main_user user
1149
                     WHERE ticket.id = message.ticket_id
1150
                     AND message.status = 'NOL'
1151
                     AND message.sys_insert_user_id = user.user_id
1152
                     AND user.user_id NOT IN (
1153
                        SELECT user_id FROM $table_main_admin
1154
                     ) AND ticket.status_id != '".self::STATUS_FORWARDED."'
1155
                     GROUP BY ticket.id)";
1156
        } else {
1157
            if ($keyword_unread == 'no') {
1158
                $sql .= " AND ticket.id NOT IN ( ";
1159
                $sql .= " SELECT ticket.id
1160
                          FROM  $table_support_tickets ticket,
1161
                          $table_support_messages message,
1162
                          $table_main_user user
1163
                          WHERE ticket.id = message.ticket_id
1164
                          AND message.status = 'NOL'
1165
                          AND message.sys_insert_user_id = user.user_id
1166
                          AND user.user_id NOT IN (SELECT user_id FROM $table_main_admin)
1167
                          AND ticket.status_id != '".self::STATUS_FORWARDED."'
1168
                          GROUP BY ticket.id)";
1169
            }
1170
        }*/
1171
        $res = Database::query($sql);
1172
        $obj = Database::fetch_object($res);
1173
1174
        return $obj->total;
1175
    }
1176
1177
    /**
1178
     * @param int $ticketId
1179
     * @return array
1180
     */
1181
    public static function get_ticket_detail_by_id($ticketId)
1182
    {
1183
        $ticketId = intval($ticketId);
1184
        $table_support_category = Database::get_main_table(TABLE_TICKET_CATEGORY);
1185
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1186
        $table_support_priority = Database::get_main_table(TABLE_TICKET_PRIORITY);
1187
        $table_support_status = Database::get_main_table(TABLE_TICKET_STATUS);
1188
        $table_support_messages = Database::get_main_table(TABLE_TICKET_MESSAGE);
1189
        $table_support_message_attachments = Database::get_main_table(TABLE_TICKET_MESSAGE_ATTACHMENTS);
1190
        $table_main_user = Database::get_main_table(TABLE_MAIN_USER);
1191
1192
        $sql = "SELECT
1193
                    ticket.*, 
1194
                    cat.name,
1195
                    status.name as status, 
1196
                    priority.name priority
1197
                FROM $table_support_tickets ticket
1198
                INNER JOIN $table_support_category cat
1199
                ON (cat.id = ticket.category_id)
1200
                INNER JOIN $table_support_priority priority
1201
                ON (priority.id = ticket.priority_id)
1202
                INNER JOIN $table_support_status status
1203
                ON (status.id = ticket.status_id)
1204
		        WHERE
1205
                    ticket.id = $ticketId ";
1206
        $result = Database::query($sql);
1207
        $ticket = array();
1208
        if (Database::num_rows($result) > 0) {
1209
            while ($row = Database::fetch_assoc($result)) {
1210
                $row['course'] = null;
1211
                $row['start_date_from_db'] = $row['start_date'];
1212
                $row['start_date'] = api_convert_and_format_date(api_get_local_time($row['start_date']), DATE_TIME_FORMAT_LONG, api_get_timezone());
1213
                $row['end_date_from_db'] = $row['end_date'];
1214
                $row['end_date'] = api_convert_and_format_date(api_get_local_time($row['end_date']), DATE_TIME_FORMAT_LONG, api_get_timezone());
1215
                $row['sys_lastedit_datetime_from_db'] = $row['sys_lastedit_datetime'];
1216
                $row['sys_lastedit_datetime'] = api_convert_and_format_date(api_get_local_time($row['sys_lastedit_datetime']), DATE_TIME_FORMAT_LONG, api_get_timezone());
1217
                $row['course_url'] = null;
1218
                if ($row['course_id'] != 0) {
1219
                    $course = api_get_course_info_by_id($row['course_id']);
1220
                    $sessionId = 0;
1221
                    if ($row['session_id']) {
1222
                        $sessionId = $row['session_id'];
1223
                    }
1224
                    if ($course) {
1225
                        $row['course_url'] = '<a href="'.$course['course_public_url'].'?id_session='.$sessionId.'">'.$course['name'].'</a>';
1226
                    }
1227
                }
1228
1229
                $userInfo = api_get_user_info($row['sys_insert_user_id']);
1230
                $row['user_url'] = '<a href="' . api_get_path(WEB_PATH) . 'main/admin/user_information.php?user_id=' . $userInfo['user_id'] . '">
1231
                ' . $userInfo['complete_name']. '</a>';
1232
                $ticket['usuario'] = $userInfo;
1233
                $ticket['ticket'] = $row;
1234
            }
1235
1236
            $sql = "SELECT *, message.id as message_id 
1237
                    FROM $table_support_messages message 
1238
                    INNER JOIN $table_main_user user
1239
                    ON (message.sys_insert_user_id = user.user_id)
1240
                    WHERE
1241
                        message.ticket_id = '$ticketId' ";
1242
            $result = Database::query($sql);
1243
            $ticket['messages'] = array();
1244
            $attach_icon = Display::return_icon('attachment.gif', '');
1245
            $webPath = api_get_path(WEB_CODE_PATH);
1246
            while ($row = Database::fetch_assoc($result)) {
1247
                $message = $row;
1248
                $completeName = api_get_person_name($row['firstname'], $row['lastname']);
1249
                $href = $webPath . 'main/admin/user_information.php?user_id=' . $row['user_id'];
1250
                $message['admin'] = UserManager::is_admin($message['user_id']);
1251
                $message['user_created'] = "<a href='$href'> $completeName </a>";
1252
                $sql = "SELECT *
1253
                        FROM $table_support_message_attachments
1254
                        WHERE
1255
                            message_id = " . $row['message_id'] . " AND
1256
                            ticket_id = $ticketId";
1257
1258
                $result_attach = Database::query($sql);
1259
                while ($row2 = Database::fetch_assoc($result_attach)) {
1260
                    $archiveURL = $archiveURL = $webPath . 'ticket/download.php?ticket_id=' . $ticketId . '&file=';
1261
                    $row2['attachment_link'] = $attach_icon . '&nbsp;<a href="' . $archiveURL . $row2['path'] . '&title=' . $row2['filename'] . '">' . $row2['filename'] . '</a>&nbsp;(' . $row2['size'] . ')';
1262
                    $message['attachments'][] = $row2;
1263
                }
1264
                $ticket['messages'][] = $message;
1265
            }
1266
        }
1267
1268
        return $ticket;
1269
    }
1270
1271
    /**
1272
     * @param int $ticketId
1273
     * @param int $userId
1274
     * @return bool
1275
     */
1276
    public static function update_message_status($ticketId, $userId)
1277
    {
1278
        $ticketId = intval($ticketId);
1279
        $userId = intval($userId);
1280
        $table_support_messages = Database::get_main_table(
1281
            TABLE_TICKET_MESSAGE
1282
        );
1283
        $table_support_tickets = Database::get_main_table(TABLE_TICKET_TICKET);
1284
        $now = api_get_utc_datetime();
1285
        $sql = "UPDATE $table_support_messages
1286
                SET
1287
                    status = 'LEI',
1288
                    sys_lastedit_user_id ='" . api_get_user_id() . "',
1289
                    sys_lastedit_datetime ='" . $now . "'
1290
                WHERE ticket_id ='$ticketId' ";
1291
1292
        if (api_is_platform_admin()) {
1293
            $sql .= " AND sys_insert_user_id = '$userId'";
1294
        } else {
1295
1296
            $sql .= " AND sys_insert_user_id != '$userId'";
1297
        }
1298
        $result = Database::query($sql);
1299
        if (Database::affected_rows($result) > 0) {
1300
            Database::query(
1301
                "UPDATE $table_support_tickets SET
1302
                    status_id = '".self::STATUS_PENDING."'
1303
                 WHERE id ='$ticketId' AND status_id = '".self::STATUS_NEW."'"
1304
            );
1305
            return true;
1306
        } else {
1307
            return false;
1308
        }
1309
    }
1310
1311
    /**
1312
     * @param int $ticketId
1313
     * @param int $userId
0 ignored issues
show
Documentation introduced by
There is no parameter named $userId. Did you maybe mean $onlyToUserId?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

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

This check looks for function calls that miss required arguments.

Loading history...
2031
                '2' => $row->getDescription()
2032
            ];
2033
        }
2034
2035
        return $list;
2036
    }
2037
2038
    /**
2039
     * @return int
2040
     */
2041
    public static function getStatusCount()
2042
    {
2043
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Status')->createQueryBuilder('p')
2044
            ->select('COUNT(p.id)')
2045
            ->getQuery()
2046
            ->getSingleScalarResult();
2047
2048
        return $count;
2049
    }
2050
2051
    /**
2052
     * @param array $params
2053
     */
2054
    public static function addStatus($params)
2055
    {
2056
        $item = new Status();
2057
        $item->setCode(URLify::filter($params['name']));
2058
        $item->setName($params['name']);
2059
        $item->setDescription($params['description']);
2060
2061
        Database::getManager()->persist($item);
2062
        Database::getManager()->flush();
2063
    }
2064
2065
    /**
2066
     * @param $id
2067
     * @return Project
2068
     */
2069
    public static function getStatus($id)
2070
    {
2071
        return Database::getManager()->getRepository('ChamiloTicketBundle:Status')->find($id);
2072
    }
2073
2074
    /**
2075
     * @param int $id
2076
     * @param array $params
2077
     */
2078 View Code Duplication
    public static function updateStatus($id, $params)
2079
    {
2080
        $item = self::getStatus($id);
2081
        $item->setName($params['name']);
2082
        $item->setDescription($params['description']);
2083
2084
        Database::getManager()->merge($item);
2085
        Database::getManager()->flush();
2086
    }
2087
2088
    /**
2089
     * @param int $id
2090
     */
2091
    public static function deleteStatus($id)
2092
    {
2093
        $item = self::getStatus($id);
2094
        if ($item) {
2095
            Database::getManager()->remove($item);
2096
            Database::getManager()->flush();
2097
        }
2098
    }
2099
2100
    /**
2101
     * @param string $url
2102
     * @return FormValidator
2103
     */
2104 View Code Duplication
    public static function getStatusForm($url)
2105
    {
2106
        $form = new FormValidator('status', 'post', $url);
2107
        $form->addText('name', get_lang('Name'));
2108
        $form->addHtmlEditor('description', get_lang('Description'));
2109
        $form->addButtonUpdate(get_lang('Save'));
2110
2111
        return $form;
2112
    }
2113
2114
    /**
2115
     * @return array
2116
     */
2117 View Code Duplication
    public static function getPriorityAdminList()
2118
    {
2119
        $items = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2120
2121
        $list = [];
2122
        /** @var Status $row */
2123
        foreach ($items as $row) {
2124
            $list[] = [
2125
                'id' => $row->getId(),
2126
                'code' => $row->getCode(),
2127
                '0' => $row->getId(),
2128
                '1' => $row->getName(),
2129
                '2' => $row->getDescription(),
2130
                '3' => $row->getId()
2131
            ];
2132
        }
2133
2134
        return $list;
2135
    }
2136
2137
    /**
2138
     * @return array
2139
     */
2140 View Code Duplication
    public static function getPrioritySimple()
2141
    {
2142
        $projects = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->findAll();
2143
2144
        $list = [];
2145
        /** @var Priority $row */
2146
        foreach ($projects as $row) {
2147
            $list[] = [
2148
                'id' => $row->getId(),
2149
                '0' => $row->getId(),
2150
                '1' => Display::url($row->getName()),
0 ignored issues
show
Bug introduced by
The call to url() misses a required argument $url.

This check looks for function calls that miss required arguments.

Loading history...
2151
                '2' => $row->getDescription()
2152
            ];
2153
        }
2154
2155
        return $list;
2156
    }
2157
2158
    /**
2159
     * @return int
2160
     */
2161
    public static function getPriorityCount()
2162
    {
2163
        $count = Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->createQueryBuilder('p')
2164
            ->select('COUNT(p.id)')
2165
            ->getQuery()
2166
            ->getSingleScalarResult();
2167
2168
        return $count;
2169
    }
2170
2171
    /**
2172
     * @param array $params
2173
     */
2174
    public static function addPriority($params)
2175
    {
2176
        $item = new Priority();
2177
        $item
2178
            ->setCode(URLify::filter($params['name']))
2179
            ->setName($params['name'])
2180
            ->setDescription($params['description'])
2181
            ->setColor('')
2182
            ->setInsertUserId(api_get_user_id())
2183
            ->setUrgency('')
2184
        ;
2185
2186
        Database::getManager()->persist($item);
2187
        Database::getManager()->flush();
2188
    }
2189
2190
    /**
2191
     * @param $id
2192
     * @return Priority
2193
     */
2194
    public static function getPriority($id)
2195
    {
2196
        return Database::getManager()->getRepository('ChamiloTicketBundle:Priority')->find($id);
2197
    }
2198
2199
    /**
2200
     * @param int $id
2201
     * @param array $params
2202
     */
2203 View Code Duplication
    public static function updatePriority($id, $params)
2204
    {
2205
        $item = self::getPriority($id);
2206
        $item->setName($params['name']);
2207
        $item->setDescription($params['description']);
2208
2209
        Database::getManager()->merge($item);
2210
        Database::getManager()->flush();
2211
    }
2212
2213
    /**
2214
     * @param int $id
2215
     */
2216
    public static function deletePriority($id)
2217
    {
2218
        $item = self::getPriority($id);
2219
        if ($item) {
2220
            Database::getManager()->remove($item);
2221
            Database::getManager()->flush();
2222
        }
2223
    }
2224
2225
    /**
2226
     * @param string $url
2227
     * @return FormValidator
2228
     */
2229 View Code Duplication
    public static function getPriorityForm($url)
2230
    {
2231
        $form = new FormValidator('priority', 'post', $url);
2232
        $form->addText('name', get_lang('Name'));
2233
        $form->addHtmlEditor('description', get_lang('Description'));
2234
        $form->addButtonUpdate(get_lang('Save'));
2235
2236
        return $form;
2237
    }
2238
2239
    /**
2240
     * @return string
2241
     */
2242
    public static function getSettingsMenu()
2243
    {
2244
        $items = [
2245
            [
2246
                'url' => 'projects.php',
2247
                'content' => get_lang('Projects')
2248
            ],
2249
            [
2250
                'url' => 'status.php',
2251
                'content' => get_lang('Status')
2252
            ],
2253
            [
2254
                'url' => 'priorities.php',
2255
                'content' => get_lang('Priority')
2256
            ]
2257
        ];
2258
2259
        echo Display::actions($items);
2260
    }
2261
2262
    /**
2263
     * @return array
2264
     */
2265 View Code Duplication
    public static function getDefaultStatusList()
2266
    {
2267
        return [
2268
            self::STATUS_NEW,
2269
            self::STATUS_PENDING,
2270
            self::STATUS_UNCONFIRMED,
2271
            self::STATUS_CLOSE,
2272
            self::STATUS_FORWARDED
2273
        ];
2274
    }
2275
2276
        /**
2277
     * @return array
2278
     */
2279 View Code Duplication
    public static function getDefaultPriorityList()
2280
    {
2281
        return [
2282
            self::PRIORITY_NORMAL,
2283
            self::PRIORITY_HIGH,
2284
            self::PRIORITY_LOW,
2285
            self::STATUS_CLOSE,
2286
            self::STATUS_FORWARDED
2287
        ];
2288
    }
2289
2290
    /**
2291
     * Deletes the user from all the ticket system
2292
     * @param int $userId
2293
     */
2294
    public static function deleteUserFromTicketSystem($userId)
2295
    {
2296
        $userId = (int) $userId;
2297
        $schema = Database::getManager()->getConnection()->getSchemaManager();
2298
2299 View Code Duplication
        if ($schema->tablesExist('ticket_assigned_log')) {
2300
            $sql = "UPDATE ticket_assigned_log SET user_id = NULL WHERE user_id = $userId";
2301
            Database::query($sql);
2302
2303
            $sql = "UPDATE ticket_assigned_log SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2304
            Database::query($sql);
2305
        }
2306
2307
        if ($schema->tablesExist('ticket_ticket')) {
2308
            $sql = "UPDATE ticket_ticket SET assigned_last_user = NULL WHERE assigned_last_user = $userId";
2309
            Database::query($sql);
2310
2311
            $sql = "UPDATE ticket_ticket SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2312
            Database::query($sql);
2313
2314
            $sql = "UPDATE ticket_ticket SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2315
            Database::query($sql);
2316
        }
2317
2318 View Code Duplication
        if ($schema->tablesExist('ticket_category')) {
2319
            $sql = "UPDATE ticket_category SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2320
            Database::query($sql);
2321
2322
            $sql = "UPDATE ticket_category SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2323
            Database::query($sql);
2324
        }
2325
2326
        if ($schema->tablesExist('ticket_category_rel_user')) {
2327
            $sql = "DELETE FROM ticket_category_rel_user WHERE user_id = $userId";
2328
            Database::query($sql);
2329
        }
2330
2331 View Code Duplication
        if ($schema->tablesExist('ticket_message')) {
2332
            $sql = "UPDATE ticket_message SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2333
            Database::query($sql);
2334
2335
            $sql = "UPDATE ticket_message SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2336
            Database::query($sql);
2337
        }
2338
2339 View Code Duplication
        if ($schema->tablesExist('ticket_message_attachments')) {
2340
            $sql = "UPDATE ticket_message_attachments SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2341
            Database::query($sql);
2342
2343
            $sql = "UPDATE ticket_message_attachments SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2344
            Database::query($sql);
2345
        }
2346
2347 View Code Duplication
        if ($schema->tablesExist('ticket_priority')) {
2348
            $sql = "UPDATE ticket_priority SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2349
            Database::query($sql);
2350
2351
            $sql = "UPDATE ticket_priority SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2352
            Database::query($sql);
2353
        }
2354
2355 View Code Duplication
        if ($schema->tablesExist('ticket_project')) {
2356
            $sql = "UPDATE ticket_project SET sys_insert_user_id = NULL WHERE sys_insert_user_id = $userId";
2357
            Database::query($sql);
2358
2359
            $sql = "UPDATE ticket_project SET sys_lastedit_user_id = NULL WHERE sys_lastedit_user_id = $userId";
2360
            Database::query($sql);
2361
        }
2362
    }
2363
}
2364