LearningCalendarPlugin::getCalendarsEventsByDate()   B
last analyzed

Complexity

Conditions 9
Paths 50

Size

Total Lines 53
Code Lines 32

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 32
nc 50
nop 5
dl 0
loc 53
rs 8.0555
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
3
/* For license terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Enums\ActionIcon;
6
7
/**
8
 * Class LearningCalendarPlugin.
9
 */
10
class LearningCalendarPlugin extends Plugin
11
{
12
    const EVENT_TYPE_TAKEN = 1;
13
    const EVENT_TYPE_EXAM = 2;
14
    const EVENT_TYPE_FREE = 3;
15
16
    /**
17
     * Class constructor.
18
     */
19
    protected function __construct()
20
    {
21
        $version = '0.1';
22
        $author = 'Julio Montoya';
23
        parent::__construct($version, $author, ['enabled' => 'boolean']);
24
        $this->setHasPersonalEvents(true);
25
    }
26
27
    /**
28
     * Event definition.
29
     *
30
     * @return array
31
     */
32
    public function getEventTypeList()
33
    {
34
        return [
35
            self::EVENT_TYPE_TAKEN => ['color' => 'red', 'name' => self::get_lang('EventTypeTaken')],
36
            self::EVENT_TYPE_EXAM => ['color' => 'yellow', 'name' => self::get_lang('EventTypeExam')],
37
            self::EVENT_TYPE_FREE => ['color' => 'green', 'name' => self::get_lang('EventTypeFree')],
38
        ];
39
    }
40
41
    /**
42
     * @return array
43
     */
44
    public function getEventTypeColorList()
45
    {
46
        $list = $this->getEventTypeList();
47
        $newList = [];
48
        foreach ($list as $eventId => $event) {
49
            $newList[$eventId] = $event['color'];
50
        }
51
52
        return $newList;
53
    }
54
55
    /**
56
     * Get the class instance.
57
     *
58
     * @return $this
59
     */
60
    public static function create()
61
    {
62
        static $result = null;
63
64
        return $result ?: $result = new self();
65
    }
66
67
    /**
68
     * Install the plugin. Setup the database.
69
     */
70
    public function install()
71
    {
72
        $sql = "
73
            CREATE TABLE IF NOT EXISTS learning_calendar(
74
              id int not null AUTO_INCREMENT primary key,
75
              title varchar(255) not null default '',
76
              description longtext default null,
77
              total_hours int not null default 0,
78
              minutes_per_day int not null default 0,
79
              disabled int default 0,
80
              author_id int(11) not null
81
            )
82
        ";
83
        Database::query($sql);
84
85
        $sql = "
86
            CREATE TABLE IF NOT EXISTS learning_calendar_events(
87
              id int not null AUTO_INCREMENT primary key,
88
              title varchar(255) default '',
89
              calendar_id int not null,
90
              start_date date not null,
91
              end_date date not null,
92
              type int not null
93
            )
94
        ";
95
        Database::query($sql);
96
97
        $sql = '
98
            CREATE TABLE IF NOT EXISTS learning_calendar_user(
99
              id int not null AUTO_INCREMENT primary key,
100
              user_id int(11) not null,
101
              calendar_id int not null
102
            )
103
        ';
104
        Database::query($sql);
105
106
        $sql = '
107
            CREATE TABLE IF NOT EXISTS learning_calendar_control_point(
108
              id int not null AUTO_INCREMENT primary key,
109
              user_id int(11) not null,
110
              control_date date not null,
111
              control_value int not null,
112
              created_at datetime not null,
113
              updated_at datetime not null
114
            )
115
        ';
116
        Database::query($sql);
117
118
        $extraField = new ExtraField('lp_item');
119
        $params = [
120
            'display_text' => $this->get_lang('Learning calendar one day marker'),
121
            'variable' => 'calendar',
122
            'visible_to_self' => 1,
123
            'changeable' => 1,
124
            'visible_to_others' => 1,
125
            'value_type' => ExtraField::FIELD_TYPE_CHECKBOX,
126
        ];
127
128
        $extraField->save($params);
129
130
        $extraField = new ExtraField('course');
131
        $params = [
132
            'display_text' => $this->get_lang('Course duration (h)'),
133
            'variable' => 'course_hours_duration',
134
            'visible_to_self' => 1,
135
            'changeable' => 1,
136
            'visible_to_others' => 1,
137
            'value_type' => ExtraField::FIELD_TYPE_TEXT,
138
        ];
139
140
        $extraField->save($params);
141
142
        return true;
143
    }
144
145
    /**
146
     * Uninstall the plugin.
147
     */
148
    public function uninstall()
149
    {
150
        $tables = [
151
            'learning_calendar',
152
            'learning_calendar_events',
153
            'learning_calendar_user',
154
        ];
155
156
        foreach ($tables as $table) {
157
            $sql = "DROP TABLE IF EXISTS $table";
158
            Database::query($sql);
159
        }
160
161
        $extraField = new ExtraField('lp_item');
162
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable('calendar');
163
164
        if ($fieldInfo) {
165
            $extraField->delete($fieldInfo['id']);
166
        }
167
168
        $extraField = new ExtraField('course');
169
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable('course_hours_duration');
170
        if ($fieldInfo) {
171
            $extraField->delete($fieldInfo['id']);
172
        }
173
174
        return true;
175
    }
176
177
    /**
178
     * @param int    $from
179
     * @param int    $numberOfItems
180
     * @param int    $column
181
     * @param string $direction
182
     *
183
     * @return array
184
     */
185
    public function getCalendars(
186
        $from,
187
        $numberOfItems,
188
        $column,
189
        $direction = 'DESC'
190
    ) {
191
        $column = (int) $column;
192
        $from = (int) $from;
193
        $numberOfItems = (int) $numberOfItems;
194
        $direction = strtoupper($direction);
195
196
        if (!in_array($direction, ['ASC', 'DESC'])) {
197
            $direction = 'DESC';
198
        }
199
200
        if (api_is_platform_admin()) {
201
            $sql = 'SELECT * FROM learning_calendar';
202
        } else {
203
            $userId = api_get_user_id();
204
            $sql = "SELECT * FROM learning_calendar WHERE author_id = $userId";
205
        }
206
207
        $sql .= " LIMIT $from, $numberOfItems ";
208
209
        $result = Database::query($sql);
210
        $list = [];
211
        $link = api_get_path(WEB_PLUGIN_PATH).'LearningCalendar/start.php';
212
        while ($row = Database::fetch_array($result)) {
213
            $id = $row['id'];
214
            $row['title'] = Display::url(
215
                $row['title'],
216
                api_get_path(WEB_PLUGIN_PATH).'LearningCalendar/calendar.php?id='.$id
217
            );
218
            $actions = Display::url(
219
                Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Edit')),
220
                $link.'?action=edit&id='.$id
221
            );
222
223
            $actions .= Display::url(
224
                Display::getMdiIcon(ActionIcon::COPY_CONTENT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Copy')),
225
                $link.'?action=copy&id='.$id
226
            );
227
228
            $actions .= Display::url(
229
                Display::getMdiIcon(ActionIcon::DELETE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Delete')),
230
                $link.'?action=delete&id='.$id
231
            );
232
            $row['actions'] = $actions;
233
            $list[] = $row;
234
        }
235
236
        return $list;
237
    }
238
239
    /**
240
     * @param array $calendarInfo
241
     * @param int   $start
242
     * @param int   $end
243
     * @param int   $type
244
     * @param bool  $getCount
245
     *
246
     * @return array
247
     */
248
    public function getCalendarsEventsByDate($calendarInfo, $start, $end, $type = 0, $getCount = false)
249
    {
250
        if (empty($calendarInfo)) {
251
            if ($getCount) {
252
                return 0;
253
            }
254
255
            return [];
256
        }
257
258
        $calendarId = (int) $calendarInfo['id'];
259
        $start = (int) $start;
260
        $end = (int) $end;
261
262
        $startCondition = '';
263
        $endCondition = '';
264
        $typeCondition = '';
265
266
        if (0 !== $start) {
267
            $start = api_get_utc_datetime($start);
268
            $startCondition = "AND start_date >= '".$start."'";
269
        }
270
        if (0 !== $end) {
271
            $end = api_get_utc_datetime($end);
272
            $endCondition = "AND (end_date <= '".$end."' OR end_date IS NULL)";
273
        }
274
275
        if (!empty($type)) {
276
            $type = (int) $type;
277
            $typeCondition = " AND type = $type ";
278
        }
279
280
        $select = '*';
281
        if ($getCount) {
282
            $select = 'count(id) count ';
283
        }
284
285
        $sql = "SELECT $select FROM learning_calendar_events
286
                WHERE calendar_id = $calendarId $startCondition $endCondition $typeCondition";
287
        $result = Database::query($sql);
288
289
        if ($getCount) {
290
            $row = Database::fetch_assoc($result);
291
292
            return $row['count'];
293
        }
294
295
        $list = [];
296
        while ($row = Database::fetch_assoc($result)) {
297
            $list[] = $row;
298
        }
299
300
        return ['calendar' => $calendarInfo, 'events' => $list];
301
    }
302
303
    /**
304
     * @param array $calendarInfo
305
     *
306
     * @return array
307
     */
308
    public function getFirstCalendarDate($calendarInfo)
309
    {
310
        if (empty($calendarInfo)) {
311
            return [];
312
        }
313
314
        $calendarId = (int) $calendarInfo['id'];
315
316
        /*if (!empty($type)) {
317
            $type = (int) $type;
318
            $typeCondition = " AND type = $type ";
319
        }*/
320
321
        $sql = "SELECT start_date FROM learning_calendar_events
322
                WHERE calendar_id = $calendarId ORDER BY start_date LIMIT 1";
323
        $result = Database::query($sql);
324
        $row = Database::fetch_assoc($result);
325
326
        return $row['start_date'];
327
    }
328
329
    /**
330
     * @return int
331
     */
332
    public function getCalendarCount()
333
    {
334
        if (api_is_platform_admin()) {
335
            $sql = 'select count(*) as count FROM learning_calendar';
336
        } else {
337
            $userId = api_get_user_id();
338
            $sql = "select count(*) as count FROM learning_calendar WHERE author_id = $userId";
339
        }
340
        $result = Database::query($sql);
341
        $result = Database::fetch_array($result);
342
343
        return (int) $result['count'];
344
    }
345
346
    /**
347
     * @param int $calendarId
348
     *
349
     * @return array
350
     */
351
    public function getUsersPerCalendar($calendarId)
352
    {
353
        $calendarId = (int) $calendarId;
354
        $sql = "SELECT * FROM learning_calendar_user
355
                WHERE calendar_id = $calendarId";
356
        $result = Database::query($sql);
357
        $list = [];
358
        while ($row = Database::fetch_assoc($result)) {
359
            $userInfo = api_get_user_info($row['user_id']);
360
            $userInfo['exam'] = 'exam';
361
            $list[] = $userInfo;
362
        }
363
364
        return $list;
365
    }
366
367
    /**
368
     * @param int $calendarId
369
     *
370
     * @return int
371
     */
372
    public function getUsersPerCalendarCount($calendarId)
373
    {
374
        $calendarId = (int) $calendarId;
375
        $sql = "SELECT count(id) as count FROM learning_calendar_user
376
                WHERE calendar_id = $calendarId";
377
        $result = Database::query($sql);
378
        $row = Database::fetch_assoc($result);
379
380
        return (int) $row['count'];
381
    }
382
383
    /**
384
     * @param int $id
385
     */
386
    public function toggleVisibility($id)
387
    {
388
        $extraField = new ExtraField('lp_item');
389
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable('calendar');
390
        if ($fieldInfo) {
391
            $itemInfo = $this->getItemVisibility($id);
392
            if (empty($itemInfo)) {
393
                $extraField = new ExtraFieldValue('lp_item');
394
                $value = 1;
395
                $params = [
396
                    'field_id' => $fieldInfo['id'],
397
                    'value' => $value,
398
                    'item_id' => $id,
399
                ];
400
                $extraField->save($params);
401
            } else {
402
                $newValue = 1 === (int) $itemInfo['value'] ? 0 : 1;
403
                $extraField = new ExtraFieldValue('lp_item');
404
                $params = [
405
                    'id' => $itemInfo['id'],
406
                    'value' => $newValue,
407
                ];
408
                $extraField->update($params);
409
            }
410
        }
411
    }
412
413
    /**
414
     * @param int $id
415
     *
416
     * @return array
417
     */
418
    public function getItemVisibility($id)
419
    {
420
        $extraField = new ExtraFieldValue('lp_item');
421
        $values = $extraField->get_values_by_handler_and_field_variable($id, 'calendar');
422
423
        if (empty($values)) {
424
            return [];
425
        }
426
427
        return $values;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $values also could return the type boolean which is incompatible with the documented return type array.
Loading history...
428
    }
429
430
    /**
431
     * @param int $calendarId
432
     *
433
     * @return array|mixed
434
     */
435
    public function getCalendar($calendarId)
436
    {
437
        $calendarId = (int) $calendarId;
438
        $sql = "SELECT * FROM learning_calendar WHERE id = $calendarId";
439
        $result = Database::query($sql);
440
441
        return Database::fetch_assoc($result);
442
    }
443
444
    /**
445
     * @param int $userId
446
     *
447
     * @return array|mixed
448
     */
449
    public function getUserCalendar($userId)
450
    {
451
        $userId = (int) $userId;
452
        $sql = "SELECT * FROM learning_calendar_user WHERE user_id = $userId";
453
        $result = Database::query($sql);
454
455
        return Database::fetch_assoc($result);
456
    }
457
458
    /**
459
     * @param int  $userId
460
     * @param int  $start
461
     * @param int  $end
462
     * @param int  $type
463
     * @param bool $getCount
464
     *
465
     * @return array|int
466
     */
467
    public function getUserEvents($userId, $start, $end, $type = 0, $getCount = false)
468
    {
469
        $calendarRelUser = $this->getUserCalendar($userId);
470
        if (!empty($calendarRelUser)) {
471
            $calendar = $this->getCalendar($calendarRelUser['calendar_id']);
472
473
            return $this->getCalendarsEventsByDate($calendar, $start, $end, $type, $getCount);
474
        }
475
476
        if ($getCount) {
477
            return 0;
478
        }
479
480
        return [];
481
    }
482
483
    /**
484
     * @param int $userId
485
     *
486
     * @return mixed|string
487
     */
488
    public function getUserCalendarToString($userId)
489
    {
490
        $calendar = $this->getUserCalendar($userId);
491
        if ($calendar) {
492
            $calendarInfo = $this->getCalendar($calendar['calendar_id']);
493
494
            return $calendarInfo['title'];
495
        }
496
497
        return '';
498
    }
499
500
    /**
501
     * @param int $calendarId
502
     * @param int $userId
503
     *
504
     * @return bool
505
     */
506
    public function addUserToCalendar($calendarId, $userId)
507
    {
508
        $calendar = $this->getUserCalendar($userId);
509
        if (empty($calendar)) {
510
            $params = [
511
                'calendar_id' => $calendarId,
512
                'user_id' => $userId,
513
            ];
514
515
            Database::insert('learning_calendar_user', $params);
516
517
            return true;
518
        }
519
520
        return false;
521
    }
522
523
    /**
524
     * @param int $calendarId
525
     * @param int $userId
526
     *
527
     * @return bool
528
     */
529
    public function updateUserToCalendar($calendarId, $userId)
530
    {
531
        $calendar = $this->getUserCalendar($userId);
532
        if (!empty($calendar)) {
533
            $params = [
534
                'calendar_id' => $calendarId,
535
                'user_id' => $userId,
536
            ];
537
538
            Database::update('learning_calendar_user', $params, ['id = ?' => $calendar['id']]);
539
        }
540
541
        return true;
542
    }
543
544
    /**
545
     * @param int $calendarId
546
     * @param int $userId
547
     *
548
     * @return bool
549
     */
550
    public function deleteAllCalendarFromUser($calendarId, $userId)
551
    {
552
        $calendarId = (int) $calendarId;
553
        $userId = (int) $userId;
554
        $sql = "DELETE FROM learning_calendar_user
555
                WHERE user_id = $userId AND calendar_id = $calendarId";
556
        Database::query($sql);
557
558
        return true;
559
    }
560
561
    /*public static function getUserCalendar($calendarId, $userId)
562
    {
563
        $params = [
564
            'calendar_id' => $calendarId,
565
            'user_id' => $calendarId,
566
        ];
567
568
        Database::insert('learning_calendar_user', $params);
569
570
        return true;
571
    }*/
572
573
    public function getForm(FormValidator &$form)
574
    {
575
        $form->addText('title', get_lang('Title'));
576
        $form->addText('total_hours', get_lang('Total hours'));
577
        $form->addText('minutes_per_day', get_lang('Minutes per day'));
578
        $form->addHtmlEditor('description', get_lang('Description'), false);
579
    }
580
581
    /**
582
     * @param Agenda $agenda
583
     * @param int    $start
584
     * @param int    $end
585
     *
586
     * @return array
587
     */
588
    public function getPersonalEvents($agenda, $start, $end)
589
    {
590
        $userId = api_get_user_id();
591
        $events = $this->getUserEvents($userId, $start, $end);
592
593
        if (empty($events)) {
594
            return [];
595
        }
596
597
        $calendarInfo = $events['calendar'];
598
        $events = $events['events'];
599
600
        $list = [];
601
        $typeList = $this->getEventTypeColorList();
602
        foreach ($events as $row) {
603
            $event = [];
604
            $event['id'] = 'personal_'.$row['id'];
605
            $event['title'] = $calendarInfo['title'];
606
            $event['className'] = 'personal';
607
            $color = isset($typeList[$row['type']]) ? $typeList[$row['type']] : $typeList[self::EVENT_TYPE_FREE];
608
            $event['borderColor'] = $color;
609
            $event['backgroundColor'] = $color;
610
            $event['editable'] = false;
611
            $event['sent_to'] = get_lang('Me');
612
            $event['type'] = 'personal';
613
614
            if (!empty($row['start_date'])) {
615
                $event['start'] = $agenda->formatEventDate($row['start_date']);
616
                $event['start_date_localtime'] = api_get_local_time($row['start_date']);
617
            }
618
619
            if (!empty($row['end_date'])) {
620
                $event['end'] = $agenda->formatEventDate($row['end_date']);
621
                $event['end_date_localtime'] = api_get_local_time($row['end_date']);
622
            }
623
624
            $event['description'] = 'plugin';
625
            $event['allDay'] = 1;
626
            $event['parent_event_id'] = 0;
627
            $event['has_children'] = 0;
628
            $list[] = $event;
629
        }
630
631
        return $list;
632
    }
633
634
    /**
635
     * @param int   $userId
636
     * @param array $coursesAndSessions
637
     *
638
     * @return string
639
     */
640
    public function getGradebookEvaluationListToString($userId, $coursesAndSessions)
641
    {
642
        $list = $this->getGradebookEvaluationList($userId, $coursesAndSessions);
643
644
        $html = '';
645
        if (!empty($list)) {
646
            $html = implode('&nbsp;', array_column($list, 'title'));
647
        }
648
649
        return $html;
650
    }
651
652
    /**
653
     * @param int   $userId
654
     * @param array $coursesAndSessions
655
     *
656
     * @return array
657
     */
658
    public function getGradebookEvaluationList($userId, $coursesAndSessions)
659
    {
660
        $userId = (int) $userId;
661
662
        if (empty($coursesAndSessions)) {
663
            return 0;
664
        }
665
666
        $courseSessionConditionToString = '';
667
        foreach ($coursesAndSessions as $sessionId => $courseList) {
668
            if (isset($courseList['course_list'])) {
669
                $courseList = array_keys($courseList['course_list']);
670
            }
671
            if (empty($courseList)) {
672
                continue;
673
            }
674
            //$courseListToString = implode("','", $courseList);
675
            /*if (empty($sessionId)) {
676
                $courseAndSessionCondition[] =
677
                    " c.id IN ('$courseListToString') ";
678
            } else {
679
                $courseAndSessionCondition[] = "
680
                    (
681
                        c.id IN ('$courseListToString')
682
                    )";
683
            }*/
684
            $courseSessionConditionToString = " AND c.id IN ('".implode("','", $courseList)."') ";
685
        }
686
687
        if (empty($courseSessionConditionToString)) {
688
            return 0;
689
        }
690
691
        $tableEvaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
692
        $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
693
        $tableResult = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
694
        $sql = "SELECT DISTINCT e.title, e.id
695
                FROM $tableEvaluation e
696
                INNER JOIN $tableCourse c
697
                ON (course_code = c.code)
698
                INNER JOIN $tableResult r
699
                ON (r.evaluation_id = e.id)
700
                WHERE
701
                  e.type = 'evaluation' AND
702
                  r.score >= 2 AND
703
                  r.user_id = $userId
704
                  $courseSessionConditionToString
705
        ";
706
        $result = Database::query($sql);
707
        $list = [];
708
        if (Database::num_rows($result)) {
709
            while ($row = Database::fetch_assoc($result)) {
710
                $list[$row['id']] = $row;
711
            }
712
        }
713
714
        return $list;
715
    }
716
717
    /**
718
     * @param int   $userId
719
     * @param array $coursesAndSessions
720
     *
721
     * @return int
722
     */
723
    public function getItemCountChecked($userId, $coursesAndSessions)
724
    {
725
        $userId = (int) $userId;
726
727
        if (empty($coursesAndSessions)) {
728
            return 0;
729
        }
730
731
        $tableItem = Database::get_course_table(TABLE_LP_ITEM);
732
        $tableLp = Database::get_course_table(TABLE_LP_MAIN);
733
        $tableLpItemView = Database::get_course_table(TABLE_LP_ITEM_VIEW);
734
        $tableLpView = Database::get_course_table(TABLE_LP_VIEW);
735
        $extraField = new ExtraField('lp_item');
736
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable('calendar');
737
738
        if (empty($fieldInfo)) {
739
            return 0;
740
        }
741
742
        $courseAndSessionCondition = [];
743
        foreach ($coursesAndSessions as $sessionId => $courseList) {
744
            if (isset($courseList['course_list'])) {
745
                $courseList = array_keys($courseList['course_list']);
746
            }
747
            if (empty($courseList)) {
748
                continue;
749
            }
750
            $courseListToString = implode("','", $courseList);
751
            if (empty($sessionId)) {
752
                $courseAndSessionCondition[] =
753
                    " ((l.session_id = 0 OR l.session_id is NULL) AND i.c_id IN ('$courseListToString'))";
754
            } else {
755
                $courseAndSessionCondition[] = "
756
                    (
757
                        ((l.session_id = 0 OR l.session_id is NULL) OR l.session_id = $sessionId) AND
758
                        i.c_id IN ('$courseListToString')
759
                    )";
760
            }
761
        }
762
763
        if (empty($courseAndSessionCondition)) {
764
            return 0;
765
        }
766
767
        $courseSessionConditionToString = 'AND ('.implode(' OR ', $courseAndSessionCondition).') ';
768
        $sql = "SELECT count(*) as count
769
                FROM $tableItem i INNER JOIN $tableLp l
770
                ON (i.c_id = l.c_id AND i.lp_id = l.iid)
771
                INNER JOIN $tableLpItemView iv
772
                ON (iv.c_id = l.c_id AND i.iid = iv.lp_item_id)
773
                INNER JOIN $tableLpView v
774
                ON (v.c_id = l.c_id AND v.lp_id = l.iid AND iv.lp_view_id = v.iid)
775
                INNER JOIN extra_field_values e
776
                ON (e.item_id = i.iid AND value = 1 AND field_id = ".$fieldInfo['id'].")
777
                WHERE
778
                    v.user_id = $userId AND
779
                    status = 'completed'
780
                    $courseSessionConditionToString
781
                GROUP BY iv.view_count
782
               ";
783
784
        $result = Database::query($sql);
785
786
        if (Database::num_rows($result)) {
787
            $row = Database::fetch_assoc($result);
788
789
            return $row['count'];
790
        }
791
792
        return 0;
793
    }
794
795
    public function setJavaScript()
796
    {
797
        global $htmlHeadXtra;
798
799
        $htmlHeadXtra[] = api_get_js('jqplot/jquery.jqplot.js');
800
        $htmlHeadXtra[] = api_get_js('jqplot/plugins/jqplot.dateAxisRenderer.js');
801
        $htmlHeadXtra[] = api_get_js('jqplot/plugins/jqplot.canvasOverlay.js');
802
        $htmlHeadXtra[] = api_get_js('jqplot/plugins/jqplot.pointLabels.js');
803
        $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/jqplot/jquery.jqplot.css');
804
    }
805
806
    /**
807
     * @param int   $userId
808
     * @param array $courseAndSessionList
809
     *
810
     * @return string
811
     */
812
    public function getUserStatsPanel($userId, $courseAndSessionList)
813
    {
814
        // @todo use translation
815
        // get events from this year to today
816
        $stats = $this->getUserStats($userId, $courseAndSessionList);
817
        $html = $this->get_lang('Number of days accumulated in calendar').$stats['user_event_count'];
0 ignored issues
show
Bug introduced by
Are you sure $stats['user_event_count'] of type array|integer can be used in concatenation? ( Ignorable by Annotation )

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

817
        $html = $this->get_lang('Number of days accumulated in calendar')./** @scrutinizer ignore-type */ $stats['user_event_count'];
Loading history...
818
        if (!empty($courseAndSessionList)) {
819
            $html .= '<br />';
820
            $html .= $this->get_lang('NumberDaysAccumulatedInLp').$stats['completed'];
821
            $html .= '<br />';
822
            $html .= $this->get_lang('NumberDaysInRetard').' '.($stats['completed'] - $stats['user_event_count']);
823
        }
824
825
        $controlList = $this->getControlPointsToPlot($userId);
826
827
        if (!empty($controlList)) {
828
            $listToString = json_encode($controlList);
829
            $date = get_lang('Date');
830
            $controlPoint = get_lang('Number of days');
831
832
            $html .= '<div id="control_point_chart"></div>';
833
            $html .= '<script>
834
                $(document).ready(function(){
835
                    var cosPoints = '.$listToString.';
836
                    var plot1 = $.jqplot(\'control_point_chart\', [cosPoints], {
837
                        //animate: !$.jqplot.use_excanvas,
838
                        series:[{
839
                            showMarker:true,
840
                            pointLabels: { show:true },
841
                        }],
842
                        axes:{
843
                            xaxis:{
844
                                label: "'.$date.'",
845
                                renderer: $.jqplot.DateAxisRenderer,
846
                                tickOptions:{formatString: "%Y-%m-%d"},
847
                                tickInterval: \'30 day\',
848
                            },
849
                            yaxis:{
850
                                label: "'.$controlPoint.'",
851
                                max: 20,
852
                                min: -20,
853
                            }
854
                        },
855
                        canvasOverlay: {
856
                            show: true,
857
                            objects: [{
858
                                horizontalLine: {
859
                                    name: \'0 mark\',
860
                                    y: 0,
861
                                    lineWidth: 2,
862
                                    color: \'rgb(f, f, f)\',
863
                                    shadow: false
864
                                }
865
                            }]
866
                        },
867
                  });
868
                });
869
            </script>';
870
        }
871
872
        return Display::panel($html, $this->get_lang('Learning calendar'));
873
    }
874
875
    /**
876
     * @param int   $userId
877
     * @param array $courseAndSessionList
878
     *
879
     * @return array
880
     */
881
    public function getUserStats($userId, $courseAndSessionList)
882
    {
883
        // Get events from this year to today
884
        $takenCount = $this->getUserEvents(
885
            $userId,
886
            strtotime(date('Y-01-01')),
887
            time(),
888
            self::EVENT_TYPE_TAKEN,
889
            true
890
        );
891
892
        $completed = 0;
893
        $diff = 0;
894
        if (!empty($courseAndSessionList)) {
895
            $completed = $this->getItemCountChecked($userId, $courseAndSessionList);
896
            $diff = $takenCount - $completed;
897
        }
898
899
        return [
900
            'user_event_count' => $takenCount,
901
            'completed' => $completed,
902
            'diff' => $diff,
903
        ];
904
    }
905
906
    /**
907
     * @param int $calendarId
908
     *
909
     * @return bool
910
     */
911
    public function copyCalendar($calendarId)
912
    {
913
        $item = $this->getCalendar($calendarId);
914
        $this->protectCalendar($item);
915
        $item['author_id'] = api_get_user_id();
916
917
        if (empty($item)) {
918
            return false;
919
        }
920
921
        $calendarId = (int) $calendarId;
922
923
        unset($item['id']);
924
        //$item['title'] = $item['title'];
925
926
        $newCalendarId = Database::insert('learning_calendar', $item);
927
        if (!empty($newCalendarId)) {
928
            $sql = "SELECT * FROM learning_calendar_events WHERE calendar_id = $calendarId";
929
            $result = Database::query($sql);
930
            while ($row = Database::fetch_assoc($result)) {
931
                unset($row['id']);
932
                $row['calendar_id'] = $newCalendarId;
933
                Database::insert('learning_calendar_events', $row);
934
            }
935
936
            return true;
937
        }
938
939
        return false;
940
    }
941
942
    /**
943
     * @param int $calendarId
944
     *
945
     * @return bool
946
     */
947
    public function deleteCalendar($calendarId)
948
    {
949
        $item = $this->getCalendar($calendarId);
950
        $this->protectCalendar($item);
951
952
        if (empty($item)) {
953
            return false;
954
        }
955
956
        $calendarId = (int) $calendarId;
957
958
        $sql = "DELETE FROM learning_calendar WHERE id = $calendarId";
959
        Database::query($sql);
960
961
        // Delete events
962
        $sql = "DELETE FROM learning_calendar_events WHERE calendar_id = $calendarId";
963
        Database::query($sql);
964
965
        return true;
966
    }
967
968
    /**
969
     * @param int    $calendarId
970
     * @param string $startDate
971
     */
972
    public function toogleDayType($calendarId, $startDate)
973
    {
974
        $startDate = Database::escape_string($startDate);
975
        $calendarId = (int) $calendarId;
976
977
        $eventTypeList = $this->getEventTypeColorList();
978
        // Remove the free type to loop correctly when toogle days.
979
        unset($eventTypeList[self::EVENT_TYPE_FREE]);
980
981
        $sql = "SELECT * FROM learning_calendar_events
982
                WHERE start_date = '$startDate' AND calendar_id = $calendarId ";
983
        $result = Database::query($sql);
984
985
        if (Database::num_rows($result)) {
986
            $row = Database::fetch_assoc($result);
987
            $currentType = $row['type'];
988
            $currentType++;
989
            if ($currentType > count($eventTypeList)) {
990
                Database::delete(
991
                    'learning_calendar_events',
992
                    [' calendar_id = ? AND start_date = ?' => [$calendarId, $startDate]]
993
                );
994
            } else {
995
                $params = [
996
                    'type' => $currentType,
997
                ];
998
                Database::update(
999
                    'learning_calendar_events',
1000
                    $params,
1001
                    [' calendar_id = ? AND start_date = ?' => [$calendarId, $startDate]]
1002
                );
1003
            }
1004
        } else {
1005
            $params = [
1006
                'title' => '',
1007
                'calendar_id' => $calendarId,
1008
                'start_date' => $startDate,
1009
                'end_date' => $startDate,
1010
                'type' => self::EVENT_TYPE_TAKEN,
1011
            ];
1012
            Database::insert('learning_calendar_events', $params);
1013
        }
1014
    }
1015
1016
    /**
1017
     * @param int $calendarId
1018
     *
1019
     * @return array
1020
     */
1021
    public function getEvents($calendarId)
1022
    {
1023
        $calendarId = (int) $calendarId;
1024
        $eventTypeList = $this->getEventTypeColorList();
1025
1026
        $sql = "SELECT * FROM learning_calendar_events
1027
                WHERE calendar_id = $calendarId ";
1028
        $result = Database::query($sql);
1029
1030
        $list = [];
1031
        while ($row = Database::fetch_assoc($result)) {
1032
            $list[] = [
1033
                'start_date' => $row['start_date'],
1034
                'end_date' => $row['start_date'],
1035
                'color' => $eventTypeList[$row['type']],
1036
            ];
1037
        }
1038
1039
        return $list;
1040
    }
1041
1042
    public function protectCalendar(array $calendarInfo)
1043
    {
1044
        $allow = api_is_platform_admin() || api_is_teacher();
1045
1046
        if (!$allow) {
1047
            api_not_allowed(true);
1048
        }
1049
1050
        if (!empty($calendarInfo)) {
1051
            if (!api_is_platform_admin() && api_is_teacher()) {
1052
                if ($calendarInfo['author_id'] != api_get_user_id()) {
1053
                    api_not_allowed(true);
1054
                }
1055
            }
1056
        }
1057
    }
1058
1059
    /**
1060
     * @param int $userId
1061
     *
1062
     * @return array
1063
     */
1064
    public function getControlPoints($userId)
1065
    {
1066
        $userId = (int) $userId;
1067
        $sql = "SELECT control_date, control_value
1068
                FROM learning_calendar_control_point
1069
                WHERE user_id = $userId
1070
                ORDER BY control_date";
1071
        $result = Database::query($sql);
1072
1073
        return Database::store_result($result, 'ASSOC');
1074
    }
1075
1076
    /**
1077
     * @param int $userId
1078
     *
1079
     * @return array
1080
     */
1081
    public function getControlPointsToPlot($userId)
1082
    {
1083
        $list = $this->getControlPoints($userId);
1084
        $points = [];
1085
        foreach ($list as $item) {
1086
            $points[] = [$item['control_date'], $item['control_value']];
1087
        }
1088
1089
        return $points;
1090
    }
1091
1092
    /**
1093
     * @param int $userId
1094
     * @param int $value
1095
     */
1096
    public function addControlPoint($userId, $value)
1097
    {
1098
        $userId = (int) $userId;
1099
        $value = (int) $value;
1100
        $local = api_get_local_time();
1101
        $date = substr($local, 0, 10);
1102
1103
        $sql = "SELECT id
1104
                FROM learning_calendar_control_point
1105
                WHERE user_id = $userId AND control_date = '$date'";
1106
        $result = Database::query($sql);
1107
1108
        if (Database::num_rows($result)) {
1109
            $params = [
1110
                'control_value' => $value,
1111
                'updated_at' => api_get_utc_datetime(),
1112
            ];
1113
            $data = Database::fetch_array($result);
1114
            $id = $data['id'];
1115
            Database::update('learning_calendar_control_point', $params, ['id = ?' => $id]);
1116
        } else {
1117
            $params = [
1118
                'user_id' => $userId,
1119
                'control_date' => $date,
1120
                'control_value' => $value,
1121
                'created_at' => api_get_utc_datetime(),
1122
                'updated_at' => api_get_utc_datetime(),
1123
            ];
1124
            Database::insert('learning_calendar_control_point', $params);
1125
        }
1126
    }
1127
1128
    public function getAddUserToCalendarForm(FormValidator &$form)
1129
    {
1130
        $calendars = $this->getCalendars(0, 1000, '');
1131
1132
        if (empty($calendars)) {
1133
            echo Display::return_message(get_lang('No data available'), 'warning');
1134
            exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
1135
        }
1136
        $calendars = array_column($calendars, 'title', 'id');
1137
        $calendars = array_map('strip_tags', $calendars);
1138
1139
        $form->addSelect('calendar_id', get_lang('Calendar'), $calendars, ['disable_js' => true]);
1140
    }
1141
}
1142