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

LearningCalendarPlugin::getPersonalEvents()   B

Complexity

Conditions 6
Paths 10

Size

Total Lines 44
Code Lines 31

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 31
c 1
b 0
f 0
nc 10
nop 3
dl 0
loc 44
rs 8.8017
1
<?php
2
/* For license terms, see /license.txt */
3
4
/**
5
 * Class LearningCalendarPlugin.
6
 */
7
class LearningCalendarPlugin extends Plugin
8
{
9
    const EVENT_TYPE_TAKEN = 1;
10
    const EVENT_TYPE_EXAM = 2;
11
    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;
0 ignored issues
show
Bug Best Practice introduced by
The expression return 0 returns the type integer which is incompatible with the documented return type array.
Loading history...
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
    /**
581
     * @param FormValidator $form
582
     */
583
    public function getForm(FormValidator &$form)
584
    {
585
        $form->addText('title', get_lang('Title'));
586
        $form->addText('total_hours', get_lang('TotalHours'));
587
        $form->addText('minutes_per_day', get_lang('MinutesPerDay'));
588
        $form->addHtmlEditor('description', get_lang('Description'), false);
589
    }
590
591
    /**
592
     * @param Agenda $agenda
593
     * @param int    $start
594
     * @param int    $end
595
     *
596
     * @return array
597
     */
598
    public function getPersonalEvents($agenda, $start, $end)
599
    {
600
        $userId = api_get_user_id();
601
        $events = $this->getUserEvents($userId, $start, $end);
602
603
        if (empty($events)) {
604
            return [];
605
        }
606
607
        $calendarInfo = $events['calendar'];
608
        $events = $events['events'];
609
610
        $list = [];
611
        $typeList = $this->getEventTypeColorList();
612
        foreach ($events as $row) {
613
            $event = [];
614
            $event['id'] = 'personal_'.$row['id'];
615
            $event['title'] = $calendarInfo['title'];
616
            $event['className'] = 'personal';
617
            $color = isset($typeList[$row['type']]) ? $typeList[$row['type']] : $typeList[self::EVENT_TYPE_FREE];
618
            $event['borderColor'] = $color;
619
            $event['backgroundColor'] = $color;
620
            $event['editable'] = false;
621
            $event['sent_to'] = get_lang('Me');
622
            $event['type'] = 'personal';
623
624
            if (!empty($row['start_date'])) {
625
                $event['start'] = $agenda->formatEventDate($row['start_date']);
626
                $event['start_date_localtime'] = api_get_local_time($row['start_date']);
627
            }
628
629
            if (!empty($row['end_date'])) {
630
                $event['end'] = $agenda->formatEventDate($row['end_date']);
631
                $event['end_date_localtime'] = api_get_local_time($row['end_date']);
632
            }
633
634
            $event['description'] = 'plugin';
635
            $event['allDay'] = 1;
636
            $event['parent_event_id'] = 0;
637
            $event['has_children'] = 0;
638
            $list[] = $event;
639
        }
640
641
        return $list;
642
    }
643
644
    /**
645
     * @param int   $userId
646
     * @param array $coursesAndSessions
647
     *
648
     * @return string
649
     */
650
    public function getGradebookEvaluationListToString($userId, $coursesAndSessions)
651
    {
652
        $list = $this->getGradebookEvaluationList($userId, $coursesAndSessions);
653
654
        $html = '';
655
        if (!empty($list)) {
656
            $html = implode('&nbsp;', array_column($list, 'name'));
657
        }
658
659
        return $html;
660
    }
661
662
    /**
663
     * @param int   $userId
664
     * @param array $coursesAndSessions
665
     *
666
     * @return array
667
     */
668
    public function getGradebookEvaluationList($userId, $coursesAndSessions)
669
    {
670
        $userId = (int) $userId;
671
672
        if (empty($coursesAndSessions)) {
673
            return 0;
0 ignored issues
show
Bug Best Practice introduced by
The expression return 0 returns the type integer which is incompatible with the documented return type array.
Loading history...
674
        }
675
676
        $courseSessionConditionToString = '';
677
        foreach ($coursesAndSessions as $sessionId => $courseList) {
678
            if (isset($courseList['course_list'])) {
679
                $courseList = array_keys($courseList['course_list']);
680
            }
681
            if (empty($courseList)) {
682
                continue;
683
            }
684
            //$courseListToString = implode("','", $courseList);
685
            /*if (empty($sessionId)) {
686
                $courseAndSessionCondition[] =
687
                    " c.id IN ('$courseListToString') ";
688
            } else {
689
                $courseAndSessionCondition[] = "
690
                    (
691
                        c.id IN ('$courseListToString')
692
                    )";
693
            }*/
694
            $courseSessionConditionToString = " AND c.id IN ('".implode("','", $courseList)."') ";
695
        }
696
697
        if (empty($courseSessionConditionToString)) {
698
            return 0;
0 ignored issues
show
Bug Best Practice introduced by
The expression return 0 returns the type integer which is incompatible with the documented return type array.
Loading history...
699
        }
700
701
        $tableEvaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
702
        $tableCourse = Database::get_main_table(TABLE_MAIN_COURSE);
703
        $tableResult = Database::get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
704
        $sql = "SELECT DISTINCT e.name, e.id
705
                FROM $tableEvaluation e 
706
                INNER JOIN $tableCourse c
707
                ON (course_code = c.code)
708
                INNER JOIN $tableResult r
709
                ON (r.evaluation_id = e.id)
710
                WHERE 
711
                  e.type = 'evaluation' AND
712
                  r.score > 0 AND
713
                  r.user_id = $userId   
714
                  $courseSessionConditionToString                  
715
        ";
716
        $result = Database::query($sql);
717
        $list = [];
718
        if (Database::num_rows($result)) {
719
            while ($row = Database::fetch_array($result, 'ASSOC')) {
720
                $list[$row['id']] = $row;
721
            }
722
        }
723
724
        return $list;
725
    }
726
727
    /**
728
     * @param int   $userId
729
     * @param array $coursesAndSessions
730
     *
731
     * @return int
732
     */
733
    public function getItemCountChecked($userId, $coursesAndSessions)
734
    {
735
        $userId = (int) $userId;
736
737
        if (empty($coursesAndSessions)) {
738
            return 0;
739
        }
740
741
        $tableItem = Database::get_course_table(TABLE_LP_ITEM);
742
        $tableLp = Database::get_course_table(TABLE_LP_MAIN);
743
        $tableLpItemView = Database::get_course_table(TABLE_LP_ITEM_VIEW);
744
        $tableLpView = Database::get_course_table(TABLE_LP_VIEW);
745
        $extraField = new ExtraField('lp_item');
746
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable('calendar');
747
748
        if (empty($fieldInfo)) {
749
            return 0;
750
        }
751
752
        $courseAndSessionCondition = [];
753
        foreach ($coursesAndSessions as $sessionId => $courseList) {
754
            if (isset($courseList['course_list'])) {
755
                $courseList = array_keys($courseList['course_list']);
756
            }
757
            if (empty($courseList)) {
758
                continue;
759
            }
760
            $courseListToString = implode("','", $courseList);
761
            if (empty($sessionId)) {
762
                $courseAndSessionCondition[] =
763
                    " ((l.session_id = 0 OR l.session_id is NULL) AND i.c_id IN ('$courseListToString'))";
764
            } else {
765
                $courseAndSessionCondition[] = " 
766
                    (
767
                        ((l.session_id = 0 OR l.session_id is NULL) OR l.session_id = $sessionId) AND 
768
                        i.c_id IN ('$courseListToString')
769
                    )";
770
            }
771
        }
772
773
        if (empty($courseAndSessionCondition)) {
774
            return 0;
775
        }
776
777
        $courseSessionConditionToString = 'AND ('.implode(' OR ', $courseAndSessionCondition).') ';
778
        $sql = "SELECT count(*) as count 
779
                FROM $tableItem i INNER JOIN $tableLp l
780
                ON (i.c_id = l.c_id AND i.lp_id = l.iid) 
781
                INNER JOIN $tableLpItemView iv
782
                ON (iv.c_id = l.c_id AND i.iid = iv.lp_item_id) 
783
                INNER JOIN $tableLpView v
784
                ON (v.c_id = l.c_id AND v.lp_id = l.iid AND iv.lp_view_id = v.iid)
785
                INNER JOIN extra_field_values e 
786
                ON (e.item_id = i.iid AND value = 1 AND field_id = ".$fieldInfo['id'].")
787
                WHERE                 
788
                    v.user_id = $userId AND 
789
                    status = 'completed' 
790
                    $courseSessionConditionToString
791
                GROUP BY iv.view_count
792
               ";
793
794
        $result = Database::query($sql);
795
796
        if (Database::num_rows($result)) {
797
            $row = Database::fetch_array($result, 'ASSOC');
798
799
            return $row['count'];
800
        }
801
802
        return 0;
803
    }
804
805
    /**
806
     * @param array $htmlHeadXtra
807
     */
808
    public function setJavaScript(&$htmlHeadXtra)
809
    {
810
        $htmlHeadXtra[] = api_get_js('jqplot/jquery.jqplot.js');
811
        $htmlHeadXtra[] = api_get_js('jqplot/plugins/jqplot.dateAxisRenderer.js');
812
        $htmlHeadXtra[] = api_get_js('jqplot/plugins/jqplot.canvasOverlay.js');
813
        $htmlHeadXtra[] = api_get_js('jqplot/plugins/jqplot.pointLabels.js');
814
        $htmlHeadXtra[] = api_get_css(api_get_path(WEB_LIBRARY_PATH).'javascript/jqplot/jquery.jqplot.css');
815
    }
816
817
    /**
818
     * @param int   $userId
819
     * @param array $courseAndSessionList
820
     *
821
     * @return string
822
     */
823
    public function getUserStatsPanel($userId, $courseAndSessionList)
824
    {
825
        // @todo use translation
826
        // get events from this year to today
827
        $stats = $this->getUserStats($userId, $courseAndSessionList);
828
        $html = $this->get_lang('NumberDaysAccumulatedInCalendar').$stats['user_event_count'];
829
        if (!empty($courseAndSessionList)) {
830
            $html .= '<br />';
831
            $html .= $this->get_lang('NumberDaysAccumulatedInLp').$stats['completed'];
832
            $html .= '<br />';
833
            $html .= $this->get_lang('NumberDaysInRetard').' '.($stats['completed'] - $stats['user_event_count']);
834
        }
835
836
        $controlList = $this->getControlPointsToPlot($userId);
837
838
        if (!empty($controlList)) {
839
            $listToString = json_encode($controlList);
840
            $date = $this->get_lang('Date');
841
            $controlPoint = $this->get_lang('NumberOfDays');
842
843
            $html .= '<div id="control_point_chart"></div>';
844
            $html .= '<script>
845
                $(document).ready(function(){
846
                    var cosPoints = '.$listToString.';
847
                    var plot1 = $.jqplot(\'control_point_chart\', [cosPoints], {  
848
                        //animate: !$.jqplot.use_excanvas,                      
849
                        series:[{
850
                            showMarker:true,
851
                            pointLabels: { show:true },
852
                        }],
853
                        axes:{
854
                            xaxis:{
855
                                label: "'.$date.'",
856
                                renderer: $.jqplot.DateAxisRenderer,
857
                                tickOptions:{formatString: "%Y-%m-%d"},
858
                                tickInterval: \'30 day\',                                
859
                            },
860
                            yaxis:{
861
                                label: "'.$controlPoint.'",
862
                                max: 20,
863
                                min: -20,    
864
                            }
865
                        },
866
                        canvasOverlay: {
867
                            show: true,
868
                            objects: [{
869
                                horizontalLine: {
870
                                    name: \'0 mark\',
871
                                    y: 0,
872
                                    lineWidth: 2,
873
                                    color: \'rgb(f, f, f)\',
874
                                    shadow: false
875
                                }
876
                            }]
877
                        },                     
878
                  });
879
                });
880
            </script>';
881
        }
882
883
        $html = Display::panel($html, $this->get_lang('LearningCalendar'));
884
885
        return $html;
886
    }
887
888
    /**
889
     * @param int   $userId
890
     * @param array $courseAndSessionList
891
     *
892
     * @return array
893
     */
894
    public function getUserStats($userId, $courseAndSessionList)
895
    {
896
        // Get events from this year to today
897
        $takenCount = $this->getUserEvents(
898
            $userId,
899
            strtotime(date('Y-01-01')),
900
            time(),
901
            self::EVENT_TYPE_TAKEN,
902
            true
903
        );
904
905
        $completed = 0;
906
        $diff = 0;
907
        if (!empty($courseAndSessionList)) {
908
            $completed = $this->getItemCountChecked($userId, $courseAndSessionList);
909
            $diff = $takenCount - $completed;
910
        }
911
912
        return [
913
            'user_event_count' => $takenCount,
914
            'completed' => $completed,
915
            'diff' => $diff,
916
        ];
917
    }
918
919
    /**
920
     * @param int $calendarId
921
     *
922
     * @return bool
923
     */
924
    public function copyCalendar($calendarId)
925
    {
926
        $item = $this->getCalendar($calendarId);
927
        $this->protectCalendar($item);
928
        $item['author_id'] = api_get_user_id();
929
930
        if (empty($item)) {
931
            return false;
932
        }
933
934
        $calendarId = (int) $calendarId;
935
936
        unset($item['id']);
937
        //$item['title'] = $item['title'];
938
939
        $newCalendarId = Database::insert('learning_calendar', $item);
940
        if (!empty($newCalendarId)) {
941
            $sql = "SELECT * FROM learning_calendar_events WHERE calendar_id = $calendarId";
942
            $result = Database::query($sql);
943
            while ($row = Database::fetch_array($result, 'ASSOC')) {
944
                unset($row['id']);
945
                $row['calendar_id'] = $newCalendarId;
946
                Database::insert('learning_calendar_events', $row);
947
            }
948
949
            return true;
950
        }
951
952
        return false;
953
    }
954
955
    /**
956
     * @param int $calendarId
957
     *
958
     * @return bool
959
     */
960
    public function deleteCalendar($calendarId)
961
    {
962
        $item = $this->getCalendar($calendarId);
963
        $this->protectCalendar($item);
964
965
        if (empty($item)) {
966
            return false;
967
        }
968
969
        $calendarId = (int) $calendarId;
970
971
        $sql = "DELETE FROM learning_calendar WHERE id = $calendarId";
972
        Database::query($sql);
973
974
        // Delete events
975
        $sql = "DELETE FROM learning_calendar_events WHERE calendar_id = $calendarId";
976
        Database::query($sql);
977
978
        return true;
979
    }
980
981
    /**
982
     * @param int    $calendarId
983
     * @param string $startDate
984
     */
985
    public function toogleDayType($calendarId, $startDate)
986
    {
987
        $startDate = Database::escape_string($startDate);
988
        $calendarId = (int) $calendarId;
989
990
        $eventTypeList = $this->getEventTypeColorList();
991
        // Remove the free type to loop correctly when toogle days.
992
        unset($eventTypeList[self::EVENT_TYPE_FREE]);
993
994
        $sql = "SELECT * FROM learning_calendar_events 
995
                WHERE start_date = '$startDate' AND calendar_id = $calendarId ";
996
        $result = Database::query($sql);
997
998
        if (Database::num_rows($result)) {
999
            $row = Database::fetch_array($result, 'ASSOC');
1000
            $currentType = $row['type'];
1001
            $currentType++;
1002
            if ($currentType > count($eventTypeList)) {
1003
                Database::delete(
1004
                    'learning_calendar_events',
1005
                    [' calendar_id = ? AND start_date = ?' => [$calendarId, $startDate]]
1006
                );
1007
            } else {
1008
                $params = [
1009
                    'type' => $currentType,
1010
                ];
1011
                Database::update(
1012
                    'learning_calendar_events',
1013
                    $params,
1014
                    [' calendar_id = ? AND start_date = ?' => [$calendarId, $startDate]]
1015
                );
1016
            }
1017
        } else {
1018
            $params = [
1019
                'name' => '',
1020
                'calendar_id' => $calendarId,
1021
                'start_date' => $startDate,
1022
                'end_date' => $startDate,
1023
                'type' => self::EVENT_TYPE_TAKEN,
1024
            ];
1025
            Database::insert('learning_calendar_events', $params);
1026
        }
1027
    }
1028
1029
    /**
1030
     * @param int $calendarId
1031
     *
1032
     * @return array
1033
     */
1034
    public function getEvents($calendarId)
1035
    {
1036
        $calendarId = (int) $calendarId;
1037
        $eventTypeList = $this->getEventTypeColorList();
1038
1039
        $sql = "SELECT * FROM learning_calendar_events 
1040
                WHERE calendar_id = $calendarId ";
1041
        $result = Database::query($sql);
1042
1043
        $list = [];
1044
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1045
            $list[] = [
1046
                'start_date' => $row['start_date'],
1047
                'end_date' => $row['start_date'],
1048
                'color' => $eventTypeList[$row['type']],
1049
            ];
1050
        }
1051
1052
        return $list;
1053
    }
1054
1055
    /**
1056
     * @param array $calendarInfo
1057
     */
1058
    public function protectCalendar(array $calendarInfo)
1059
    {
1060
        $allow = api_is_platform_admin() || api_is_teacher();
1061
1062
        if (!$allow) {
1063
            api_not_allowed(true);
1064
        }
1065
1066
        if (!empty($calendarInfo)) {
1067
            if (!api_is_platform_admin() && api_is_teacher()) {
1068
                if ($calendarInfo['author_id'] != api_get_user_id()) {
1069
                    api_not_allowed(true);
1070
                }
1071
            }
1072
        }
1073
    }
1074
1075
    /**
1076
     * @param int $userId
1077
     *
1078
     * @return array
1079
     */
1080
    public function getControlPoints($userId)
1081
    {
1082
        $userId = (int) $userId;
1083
        $sql = "SELECT control_date, control_value 
1084
                FROM learning_calendar_control_point 
1085
                WHERE user_id = $userId 
1086
                ORDER BY control_date";
1087
        $result = Database::query($sql);
1088
        $list = Database::store_result($result, 'ASSOC');
1089
1090
        return $list;
1091
    }
1092
1093
    /**
1094
     * @param int $userId
1095
     *
1096
     * @return array
1097
     */
1098
    public function getControlPointsToPlot($userId)
1099
    {
1100
        $list = $this->getControlPoints($userId);
1101
        $points = [];
1102
        foreach ($list as $item) {
1103
            $points[] = [$item['control_date'], $item['control_value']];
1104
        }
1105
1106
        return $points;
1107
    }
1108
1109
    /**
1110
     * @param int $userId
1111
     * @param int $value
1112
     */
1113
    public function addControlPoint($userId, $value)
1114
    {
1115
        $userId = (int) $userId;
1116
        $value = (int) $value;
1117
        $local = api_get_local_time();
1118
        $date = substr($local, 0, 10);
1119
1120
        $sql = "SELECT id 
1121
                FROM learning_calendar_control_point 
1122
                WHERE user_id = $userId AND control_date = '$date'";
1123
        $result = Database::query($sql);
1124
1125
        if (Database::num_rows($result)) {
1126
            $params = [
1127
                'control_value' => $value,
1128
                'updated_at' => api_get_utc_datetime(),
1129
            ];
1130
            $data = Database::fetch_array($result);
1131
            $id = $data['id'];
1132
            Database::update('learning_calendar_control_point', $params, ['id = ?' => $id]);
1133
        } else {
1134
            $params = [
1135
                'user_id' => $userId,
1136
                'control_date' => $date,
1137
                'control_value' => $value,
1138
                'created_at' => api_get_utc_datetime(),
1139
                'updated_at' => api_get_utc_datetime(),
1140
            ];
1141
            Database::insert('learning_calendar_control_point', $params);
1142
        }
1143
    }
1144
1145
    /**
1146
     * @param FormValidator $form
1147
     */
1148
    public function getAddUserToCalendarForm(FormValidator &$form)
1149
    {
1150
        $calendars = $this->getCalendars(0, 1000, '');
1151
1152
        if (empty($calendars)) {
1153
            echo Display::return_message(get_lang('NoData'), 'warning');
1154
            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...
1155
        }
1156
        $calendars = array_column($calendars, 'title', 'id');
1157
        $calendars = array_map('strip_tags', $calendars);
1158
1159
        $form->addSelect('calendar_id', get_lang('Calendar'), $calendars, ['disable_js' => true]);
1160
    }
1161
}
1162