Issues (2128)

learning_calendar/LearningCalendarPlugin.php (2 issues)

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

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