Passed
Push — 1.11.x ( 3ecb3e...a1115b )
by Yannick
08:16
created

UserGroup::getUserGroupInCourse()   C

Complexity

Conditions 13
Paths 256

Size

Total Lines 85
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 49
c 0
b 0
f 0
nc 256
nop 3
dl 0
loc 85
rs 5.0833

How to fix   Long Method    Complexity   

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 licensing terms, see /license.txt */
4
5
/**
6
 * Class UserGroup.
7
 *
8
 * This class provides methods for the UserGroup management.
9
 * Include/require it in your code to use its features.
10
 */
11
class UserGroup extends Model
12
{
13
    public const SOCIAL_CLASS = 1;
14
    public const NORMAL_CLASS = 0;
15
    public $columns = [
16
        'id',
17
        'name',
18
        'description',
19
        'group_type',
20
        'picture',
21
        'url',
22
        'allow_members_leave_group',
23
        'visibility',
24
        'updated_at',
25
        'created_at',
26
    ];
27
28
    public $useMultipleUrl = false;
29
    public $groupType = 0;
30
    public $showGroupTypeSetting = false;
31
    public $usergroup_rel_user_table;
32
    public $usergroup_rel_course_table;
33
    public $usergroup;
34
    public $usergroup_rel_session_table;
35
    public $session_table;
36
    public $access_url_rel_usergroup;
37
    public $session_rel_course_table;
38
    public $access_url_rel_user;
39
    public $table_course;
40
    public $table_user;
41
42
    /**
43
     * Set ups DB tables.
44
     */
45
    public function __construct()
46
    {
47
        parent::__construct();
48
        $this->table = Database::get_main_table(TABLE_USERGROUP);
49
        $this->usergroup_rel_user_table = Database::get_main_table(TABLE_USERGROUP_REL_USER);
50
        $this->usergroup_rel_course_table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
51
        $this->usergroup_rel_session_table = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
52
        $this->session_table = Database::get_main_table(TABLE_MAIN_SESSION);
53
        $this->usergroup_table = Database::get_main_table(TABLE_USERGROUP);
54
        $this->access_url_rel_usergroup = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
55
        $this->session_rel_course_table = Database::get_main_table(TABLE_MAIN_SESSION_COURSE);
56
        $this->access_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
57
        $this->table_course = Database::get_main_table(TABLE_MAIN_COURSE);
58
        $this->table_user = Database::get_main_table(TABLE_MAIN_USER);
59
        $this->useMultipleUrl = api_get_configuration_value('multiple_access_urls');
60
        if ($this->allowTeachers()) {
61
            $this->columns[] = 'author_id';
62
        }
63
    }
64
65
    /**
66
     * @return bool
67
     */
68
    public function getUseMultipleUrl()
69
    {
70
        return $this->useMultipleUrl;
71
    }
72
73
    /**
74
     * @return int
75
     */
76
    public function getTotalCount()
77
    {
78
        $options = [];
79
        $from = $this->table;
80
81
        if ($this->getUseMultipleUrl()) {
82
            $urlId = api_get_current_access_url_id();
83
            $options = [
84
                'where' => [
85
                    'access_url_id = ?' => [
86
                        $urlId,
87
                    ],
88
                ],
89
            ];
90
            $from = " $this->table u
91
                      INNER JOIN $this->access_url_rel_usergroup a
92
                      ON (u.id = a.usergroup_id) ";
93
        }
94
        $row = Database::select('count(*) as count', $from, $options, 'first');
95
96
        return $row['count'];
97
    }
98
99
    /**
100
     * @param int  $id       user group id
101
     * @param bool $getCount
102
     *
103
     * @return array|int
104
     */
105
    public function getUserGroupUsers($id, $getCount = false, $start = 0, $limit = 0)
106
    {
107
        $id = (int) $id;
108
        $start = (int) $start;
109
        $limit = (int) $limit;
110
111
        $select = ' u.* ';
112
        if ($getCount) {
113
            $select = 'COUNT(u.id) count ';
114
        }
115
116
        if ($this->getUseMultipleUrl()) {
117
            $urlId = api_get_current_access_url_id();
118
            $sql = "SELECT $select
119
                    FROM $this->usergroup_rel_user_table u
120
                    INNER JOIN $this->access_url_rel_user a
121
                    ON (u.user_id = a.user_id)
122
                    WHERE u.usergroup_id = $id AND access_url_id = $urlId ";
123
        } else {
124
            $sql = "SELECT $select
125
                    FROM $this->usergroup_rel_user_table u
126
                    WHERE u.usergroup_id = $id";
127
        }
128
        $limitCondition = '';
129
        if (!empty($start) && !empty($limit)) {
130
            $limitCondition = " LIMIT $start, $limit";
131
        }
132
133
        $sql .= $limitCondition;
134
135
        $result = Database::query($sql);
136
137
        if ($getCount) {
138
            if (Database::num_rows($result)) {
139
                $row = Database::fetch_array($result);
140
141
                return $row['count'];
142
            }
143
144
            return 0;
145
        } else {
146
            $list = [];
147
            $showCalendar = 'true' === api_get_plugin_setting('learning_calendar', 'enabled');
148
            $calendarPlugin = null;
149
            if ($showCalendar) {
150
                $calendarPlugin = LearningCalendarPlugin::create();
151
            }
152
            $url = api_get_path(WEB_PLUGIN_PATH).'learning_calendar/calendar.php?';
153
            while ($data = Database::fetch_array($result)) {
154
                $userId = $data['user_id'];
155
                $userInfo = api_get_user_info($userId);
156
                $data['name'] = $userInfo['complete_name_with_username'];
157
158
                if ($showCalendar) {
159
                    $calendar = $calendarPlugin->getUserCalendar($userId);
160
                    $data['calendar_id'] = 0;
161
                    $data['calendar'] = '';
162
                    if (!empty($calendar)) {
163
                        $calendarInfo = $calendarPlugin->getCalendar($calendar['calendar_id']);
164
                        if ($calendarInfo) {
165
                            $data['calendar_id'] = $calendar['calendar_id'];
166
                            $data['calendar'] = Display::url(
167
                                $calendarInfo['title'],
168
                                $url.'&id='.$calendar['calendar_id']
169
                            );
170
                        }
171
                    }
172
173
                    $courseAndSessionList = Tracking::showUserProgress(
174
                        $userId,
175
                        0,
176
                        '',
177
                        true,
178
                        true,
179
                        true
180
                    );
181
182
                    $stats = $calendarPlugin->getUserStats($userId, $courseAndSessionList);
183
                    $evaluations = $calendarPlugin->getGradebookEvaluationListToString($userId, $courseAndSessionList);
184
                    $data['gradebook_items'] = $evaluations;
185
                    $totalTime = 0;
186
                    foreach ($courseAndSessionList as $sessionId => $course) {
187
                        foreach ($course as $courseId) {
188
                            $totalTime += Tracking::get_time_spent_on_the_course($userId, $courseId, $sessionId);
189
                        }
190
                    }
191
192
                    $data['time_spent'] = api_time_to_hms($totalTime);
193
                    $data['lp_day_completed'] = $stats['completed'];
194
                    $data['days_diff'] = $stats['completed'] - $stats['user_event_count'];
195
                }
196
                $data['id'] = $data['user_id'];
197
                $list[] = $data;
198
            }
199
200
            return $list;
201
        }
202
    }
203
204
    /**
205
     * @param string $extraWhereCondition
206
     *
207
     * @return int
208
     */
209
    public function get_count($extraWhereCondition = '')
210
    {
211
        $authorCondition = '';
212
213
        if ($this->allowTeachers()) {
214
            if (!api_is_platform_admin()) {
215
                $userId = api_get_user_id();
216
                $authorCondition = " AND author_id = $userId";
217
            }
218
        }
219
220
        if ($this->getUseMultipleUrl()) {
221
            $urlId = api_get_current_access_url_id();
222
            $sql = "SELECT count(u.id) as count
223
                    FROM $this->table u
224
                    INNER JOIN $this->access_url_rel_usergroup a
225
                    ON (u.id = a.usergroup_id)
226
                    WHERE access_url_id = $urlId $authorCondition
227
                    AND $extraWhereCondition
228
            ";
229
230
            $result = Database::query($sql);
231
            if (Database::num_rows($result)) {
232
                $row = Database::fetch_array($result);
233
234
                return $row['count'];
235
            }
236
        } else {
237
            $sql = "SELECT count(a.id) as count
238
                    FROM {$this->table} a
239
                    WHERE 1 = 1
240
                    $authorCondition
241
                    AND $extraWhereCondition
242
            ";
243
            $result = Database::query($sql);
244
            if (Database::num_rows($result)) {
245
                $row = Database::fetch_array($result);
246
247
                return $row['count'];
248
            }
249
        }
250
251
        return 0;
252
    }
253
254
    /**
255
     * @param int $course_id
256
     * @param int $type
257
     *
258
     * @return mixed
259
     */
260
    public function getUserGroupByCourseWithDataCount($course_id, $type = -1)
261
    {
262
        if ($this->getUseMultipleUrl()) {
263
            $course_id = (int) $course_id;
264
            $urlId = api_get_current_access_url_id();
265
            $sql = "SELECT count(c.usergroup_id) as count
266
                    FROM {$this->usergroup_rel_course_table} c
267
                    INNER JOIN {$this->access_url_rel_usergroup} a
268
                    ON (c.usergroup_id = a.usergroup_id)
269
                    WHERE access_url_id = $urlId AND course_id = $course_id
270
            ";
271
            $result = Database::query($sql);
272
            if (Database::num_rows($result)) {
273
                $row = Database::fetch_array($result);
274
275
                return $row['count'];
276
            }
277
278
            return 0;
279
        } else {
280
            $typeCondition = '';
281
            if ($type != -1) {
282
                $type = (int) $type;
283
                $typeCondition = " AND group_type = $type ";
284
            }
285
            $sql = "SELECT count(c.usergroup_id) as count
286
                    FROM {$this->usergroup_rel_course_table} c
287
                    INNER JOIN {$this->table} a
288
                    ON (c.usergroup_id = a.id)
289
                    WHERE
290
                        course_id = $course_id
291
                        $typeCondition
292
            ";
293
            $result = Database::query($sql);
294
            if (Database::num_rows($result)) {
295
                $row = Database::fetch_array($result);
296
297
                return $row['count'];
298
            }
299
300
            return 0;
301
        }
302
    }
303
304
    /**
305
     * @param string $name
306
     *
307
     * @return int
308
     */
309
    public function getIdByName($name)
310
    {
311
        $row = Database::select(
312
            'id',
313
            $this->table,
314
            ['where' => ['name = ?' => $name]],
315
            'first'
316
        );
317
318
        if ($row) {
319
            return (int) $row['id'];
320
        }
321
322
        return 0;
323
    }
324
325
    /**
326
     * Displays the title + grid.
327
     */
328
    public function returnGrid()
329
    {
330
        // action links
331
        $html = '<div class="actions">';
332
        if (api_is_platform_admin()) {
333
            $html .= '<a href="../admin/index.php">'.
334
                Display::return_icon(
335
                    'back.png',
336
                    get_lang('BackTo').' '.get_lang('PlatformAdmin'),
337
                    '',
338
                    ICON_SIZE_MEDIUM
339
                ).
340
                '</a>';
341
        }
342
343
        $html .= '<a href="'.api_get_self().'?action=add">'.
344
            Display::return_icon('new_class.png', get_lang('AddClasses'), '', ICON_SIZE_MEDIUM).
345
            '</a>';
346
        $html .= Display::url(
347
            Display::return_icon('import_csv.png', get_lang('Import'), [], ICON_SIZE_MEDIUM),
348
            'usergroup_import.php'
349
        );
350
        $html .= Display::url(
351
            Display::return_icon('export_csv.png', get_lang('Export'), [], ICON_SIZE_MEDIUM),
352
            'usergroup_export.php'
353
        );
354
        $html .= '</div>';
355
        $html .= Display::grid_html('usergroups');
356
357
        return $html;
358
    }
359
360
    /**
361
     * Displays the title + grid.
362
     */
363
    public function displayToolBarUserGroupUsers()
364
    {
365
        // action links
366
        echo '<div class="actions">';
367
        $courseInfo = api_get_course_info();
368
        if (empty($courseInfo)) {
369
            echo '<a href="../admin/usergroups.php">'.
370
                Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'), '', '32').
371
                '</a>';
372
        } else {
373
            echo Display::url(
374
                Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'), '', '32'),
375
                api_get_path(WEB_CODE_PATH).'user/class.php?'.api_get_cidreq()
376
            );
377
        }
378
379
        echo '</div>';
380
        echo Display::grid_html('usergroups');
381
    }
382
383
    /**
384
     * Get HTML grid.
385
     */
386
    public function display_teacher_view()
387
    {
388
        echo Display::grid_html('usergroups');
389
    }
390
391
    /**
392
     * Gets a list of course ids by user group.
393
     *
394
     * @param int  $id             user group id
395
     * @param bool $loadCourseData
396
     *
397
     * @return array
398
     */
399
    public function get_courses_by_usergroup($id, $loadCourseData = false)
400
    {
401
        if ($this->getUseMultipleUrl()) {
402
            $urlId = api_get_current_access_url_id();
403
            $from = $this->usergroup_rel_course_table." c
404
                    INNER JOIN {$this->access_url_rel_usergroup} a
405
                    ON (a.usergroup_id = c.usergroup_id) ";
406
            $whereConditionSql = 'a.usergroup_id = ? AND access_url_id = ? ';
407
            $whereConditionValues = [$id, $urlId];
408
        } else {
409
            $whereConditionSql = 'usergroup_id = ?';
410
            $whereConditionValues = [$id];
411
            $from = $this->usergroup_rel_course_table.' c ';
412
        }
413
414
        if ($loadCourseData) {
415
            $from .= " INNER JOIN {$this->table_course} as course ON c.course_id = course.id";
416
        }
417
418
        $where = ['where' => [$whereConditionSql => $whereConditionValues]];
419
420
        $select = 'course_id';
421
        if ($loadCourseData) {
422
            $select = 'course.*';
423
        }
424
425
        $results = Database::select(
426
            $select,
427
            $from,
428
            $where
429
        );
430
431
        $array = [];
432
        if (!empty($results)) {
433
            foreach ($results as $row) {
434
                if ($loadCourseData) {
435
                    $array[$row['id']] = $row;
436
                } else {
437
                    $array[] = $row['course_id'];
438
                }
439
            }
440
        }
441
442
        return $array;
443
    }
444
445
    /**
446
     * Gets all users that are part of a group or class.
447
     *
448
     * @param array $options
449
     * @param int   $type    0 = classes / 1 = social groups
450
     *
451
     * @return array
452
     */
453
    public function getUserGroupInCourse($options = [], $type = -1, $getCount = false)
454
    {
455
        $select = 'DISTINCT u.*';
456
        if ($getCount) {
457
            $select = 'count(u.id) as count';
458
        }
459
460
        $sessionCheck = false;
461
        if (isset($options['session_id']) && !empty($options['session_id'])) {
462
            $sessionCheck = true;
463
        }
464
465
        if ($this->getUseMultipleUrl()) {
466
            if (false === $sessionCheck) {
467
                $sql = "SELECT $select
468
                        FROM {$this->usergroup_rel_course_table} usergroup
469
                        INNER JOIN {$this->table} u
470
                        ON (u.id = usergroup.usergroup_id)
471
                        INNER JOIN {$this->table_course} c
472
                        ON (usergroup.course_id = c.id)
473
                        INNER JOIN {$this->access_url_rel_usergroup} a
474
                        ON (a.usergroup_id = u.id)
475
                   ";
476
            } else {
477
                $sql = "SELECT $select
478
                        FROM {$this->usergroup_rel_session_table} usergroup
479
                        INNER JOIN {$this->table} u
480
                        ON (u.id = usergroup.usergroup_id)
481
                        INNER JOIN {$this->session_table} s
482
                        ON (usergroup.session_id = s.id)
483
                        INNER JOIN {$this->access_url_rel_usergroup} a
484
                        ON (a.usergroup_id = u.id)
485
                   ";
486
            }
487
        } else {
488
            if (false === $sessionCheck) {
489
                $sql = "SELECT $select
490
                        FROM {$this->usergroup_rel_course_table} usergroup
491
                        INNER JOIN {$this->table} u
492
                        ON (u.id = usergroup.usergroup_id)
493
                        INNER JOIN {$this->table_course} c
494
                        ON (usergroup.course_id = c.id)
495
                       ";
496
            } else {
497
                $sql = "SELECT $select
498
                        FROM {$this->usergroup_rel_session_table} usergroup
499
                        INNER JOIN {$this->table} u
500
                        ON (u.id = usergroup.usergroup_id)
501
                        INNER JOIN {$this->session_table} s
502
                        ON (usergroup.session_id = s.id)
503
                       ";
504
            }
505
        }
506
507
        if (-1 != $type) {
508
            $type = (int) $type;
509
            $options['where']['AND group_type = ? '] = $type;
510
        }
511
        if ($this->getUseMultipleUrl()) {
512
            $urlId = api_get_current_access_url_id();
513
            $options['where']['AND access_url_id = ? '] = $urlId;
514
        }
515
516
        $conditions = Database::parse_conditions($options);
517
        $sql .= $conditions;
518
        $result = Database::query($sql);
519
520
        if ($getCount) {
521
            if (Database::num_rows($result)) {
522
                $row = Database::fetch_array($result);
523
524
                return (int) $row['count'];
525
            }
526
527
            return 0;
528
        }
529
530
        $data = [];
531
        if (Database::num_rows($result) > 0) {
532
            while ($row = Database::fetch_array($result, 'ASSOC')) {
533
                $data[] = $row;
534
            }
535
        }
536
537
        return $data;
538
    }
539
540
    /**
541
     * @param array $options
542
     * @param int   $type
543
     * @param bool  $getCount
544
     *
545
     * @return array|bool
546
     */
547
    public function getUserGroupNotInCourse($options = [], $type = -1, $getCount = false)
548
    {
549
        $courseId = 0;
550
        if (isset($options['course_id'])) {
551
            $courseId = (int) $options['course_id'];
552
            unset($options['course_id']);
553
        }
554
555
        if (empty($courseId)) {
556
            return false;
557
        }
558
559
        $select = 'DISTINCT u.*';
560
        if ($getCount) {
561
            $select = 'count(u.id) as count';
562
        }
563
564
        $sessionCheck = false;
565
        $sessionId = 0;
566
        if (isset($options['session_id']) && !empty($options['session_id'])) {
567
            $sessionCheck = true;
568
            $sessionId = (int) $options['session_id'];
569
        }
570
571
        if ($this->getUseMultipleUrl()) {
572
            if (false === $sessionCheck) {
573
                $sql = "SELECT $select
574
                        FROM {$this->table} u
575
                        INNER JOIN {$this->access_url_rel_usergroup} a
576
                        ON (a.usergroup_id = u.id)
577
                        LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
578
                        ON (u.id = urc.usergroup_id AND course_id = $courseId)
579
                ";
580
            } else {
581
                $sql = "SELECT $select
582
                        FROM {$this->table} u
583
                        INNER JOIN {$this->access_url_rel_usergroup} a
584
                        ON (a.usergroup_id = u.id)
585
                        LEFT OUTER JOIN {$this->usergroup_rel_session_table} urs
586
                        ON (u.id = urs.usergroup_id AND session_id = $sessionId)
587
                ";
588
            }
589
        } else {
590
            if (false === $sessionCheck) {
591
                $sql = "SELECT $select
592
                        FROM {$this->table} u
593
                        LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
594
                        ON (u.id = urc.usergroup_id AND course_id = $courseId)
595
                ";
596
            } else {
597
                $sql = "SELECT $select
598
                        FROM {$this->table} u
599
                        LEFT OUTER JOIN {$this->usergroup_rel_session_table} urc
600
                        ON (u.id = urc.usergroup_id AND session_id = $sessionId)
601
                ";
602
            }
603
        }
604
605
        if (-1 != $type) {
606
            $type = (int) $type;
607
            $options['where']['AND group_type = ? '] = $type;
608
        }
609
        if ($this->getUseMultipleUrl()) {
610
            $urlId = api_get_current_access_url_id();
611
            $options['where']['AND access_url_id = ? '] = $urlId;
612
        }
613
614
        /*if ($this->allowTeachers()) {
615
            if (!api_is_platform_admin()) {
616
                $userId = api_get_user_id();
617
                $options['where']['AND author_id = ? '] = $userId;
618
            }
619
        }*/
620
621
        $conditions = Database::parse_conditions($options);
622
        $sql .= $conditions;
623
        $result = Database::query($sql);
624
625
        if ($getCount) {
626
            $result = Database::query($sql);
627
            if (Database::num_rows($result)) {
628
                $array = Database::fetch_array($result, 'ASSOC');
629
630
                return $array['count'];
631
            }
632
633
            return 0;
634
        }
635
636
        $data = [];
637
        if (Database::num_rows($result) > 0) {
638
            while ($row = Database::fetch_array($result, 'ASSOC')) {
639
                $data[] = $row;
640
            }
641
        }
642
643
        return $data;
644
    }
645
646
    /**
647
     * @param int $course_id
648
     *
649
     * @deprecated  ?
650
     *
651
     * @return array
652
     */
653
    public function get_usergroup_by_course($course_id)
654
    {
655
        if ($this->getUseMultipleUrl()) {
656
            $urlId = api_get_current_access_url_id();
657
            $options = [
658
                'where' => [
659
                    'c.course_id = ? AND access_url_id = ?' => [
660
                        $course_id,
661
                        $urlId,
662
                    ],
663
                ],
664
            ];
665
            $from = " $this->usergroup_rel_course_table as c
666
                    INNER JOIN $this->access_url_rel_usergroup a
667
                    ON c.usergroup_id = a.usergroup_id ";
668
        } else {
669
            $options = ['where' => ['c.course_id = ?' => $course_id]];
670
            $from = $this->usergroup_rel_course_table." c";
671
        }
672
673
        $results = Database::select('c.usergroup_id', $from, $options);
674
        $array = [];
675
        if (!empty($results)) {
676
            foreach ($results as $row) {
677
                $array[] = $row['usergroup_id'];
678
            }
679
        }
680
681
        return $array;
682
    }
683
684
    /**
685
     * @param int $usergroup_id
686
     * @param int $course_id
687
     *
688
     * @return bool
689
     */
690
    public function usergroup_was_added_in_course(
691
        $usergroup_id,
692
        $course_id,
693
        $Session = 0
694
    ) {
695
        $Session = (int) $Session;
696
697
        $results = Database::select(
698
            'usergroup_id',
699
            $this->usergroup_rel_course_table,
700
            ['where' => ['course_id = ? AND usergroup_id = ?' => [$course_id, $usergroup_id]]]
701
        );
702
703
        $resultSession = Database::select(
704
            'usergroup_id',
705
            $this->usergroup_rel_session_table,
706
            ['where' => ['session_id = ? AND usergroup_id = ?' => [$Session, $usergroup_id]]]
707
        );
708
709
        if (empty($results) && $Session == 0) {
710
            return false;
711
        }
712
        if ((empty($resultSession)) && $Session != 0) {
713
            return false;
714
        }
715
716
        return true;
717
    }
718
719
    /**
720
     * Gets a list of session ids by user group.
721
     *
722
     * @param int  $id                group id
723
     * @param bool $returnSessionData Whether to return an array with info (true) or just the session ID (false)
724
     *
725
     * @return array
726
     */
727
    public function get_sessions_by_usergroup($id, $returnSessionData = false)
728
    {
729
        if ($returnSessionData) {
730
            $results = Database::select(
731
                'g.session_id, s.name, s.description, s.nbr_users, s.nbr_courses',
732
                $this->usergroup_rel_session_table." g, ".$this->session_table." s",
733
                ['where' => ['g.session_id = s.id AND g.usergroup_id = ?' => $id]]
734
            );
735
        } else {
736
            $results = Database::select(
737
                'session_id',
738
                $this->usergroup_rel_session_table,
739
                ['where' => ['usergroup_id = ?' => $id]]
740
            );
741
        }
742
743
        $array = [];
744
        if (!empty($results)) {
745
            foreach ($results as $row) {
746
                if ($returnSessionData) {
747
                    $array[$row['session_id']] = $row;
748
                } else {
749
                    $array[] = $row['session_id'];
750
                }
751
            }
752
        }
753
754
        return $array;
755
    }
756
757
    /**
758
     * Gets a list of user ids by user group.
759
     *
760
     * @param int   $id    user group id
761
     * @param array $roles
762
     *
763
     * @return array with a list of user ids
764
     */
765
    public function get_users_by_usergroup($id = null, $roles = [])
766
    {
767
        $relationCondition = '';
768
        if (!empty($roles)) {
769
            $relationConditionArray = [];
770
            foreach ($roles as $relation) {
771
                $relation = (int) $relation;
772
                if (empty($relation)) {
773
                    $relationConditionArray[] = " (relation_type = 0 OR relation_type IS NULL OR relation_type = '') ";
774
                } else {
775
                    $relationConditionArray[] = " relation_type = $relation ";
776
                }
777
            }
778
            $relationCondition = ' AND ( ';
779
            $relationCondition .= implode('OR', $relationConditionArray);
780
            $relationCondition .= ' ) ';
781
        }
782
783
        if (empty($id)) {
784
            $conditions = [];
785
        } else {
786
            $conditions = ['where' => ["usergroup_id = ? $relationCondition " => $id]];
787
        }
788
789
        $results = Database::select(
790
            'user_id',
791
            $this->usergroup_rel_user_table,
792
            $conditions
793
        );
794
795
        $array = [];
796
        if (!empty($results)) {
797
            foreach ($results as $row) {
798
                $array[] = $row['user_id'];
799
            }
800
        }
801
802
        return $array;
803
    }
804
805
    /**
806
     * Gets a list of user ids by user group.
807
     *
808
     * @param int $id       user group id
809
     * @param int $relation
810
     *
811
     * @return array with a list of user ids
812
     */
813
    public function getUsersByUsergroupAndRelation($id, $relation = 0)
814
    {
815
        $relation = (int) $relation;
816
        if (empty($relation)) {
817
            $conditions = ['where' => ['usergroup_id = ? AND (relation_type = 0 OR relation_type IS NULL OR relation_type = "") ' => [$id]]];
818
        } else {
819
            $conditions = ['where' => ['usergroup_id = ? AND relation_type = ?' => [$id, $relation]]];
820
        }
821
822
        $results = Database::select(
823
            'user_id',
824
            $this->usergroup_rel_user_table,
825
            $conditions
826
        );
827
828
        $array = [];
829
        if (!empty($results)) {
830
            foreach ($results as $row) {
831
                $array[] = $row['user_id'];
832
            }
833
        }
834
835
        return $array;
836
    }
837
838
    /**
839
     * Get the group list for a user.
840
     *
841
     * @param int $userId       The user ID
842
     * @param int $filterByType Optional. The type of group
843
     *
844
     * @return array
845
     */
846
    public function getUserGroupListByUser($userId, $filterByType = null)
847
    {
848
        $userId = (int) $userId;
849
        if ($this->getUseMultipleUrl()) {
850
            $urlId = api_get_current_access_url_id();
851
            $from = $this->usergroup_rel_user_table." u
852
                INNER JOIN {$this->access_url_rel_usergroup} a
853
                ON (a.usergroup_id AND u.usergroup_id)
854
                INNER JOIN {$this->table} g
855
                ON (u.usergroup_id = g.id)
856
                ";
857
            $where = ['where' => ['user_id = ? AND access_url_id = ? ' => [$userId, $urlId]]];
858
        } else {
859
            $from = $this->usergroup_rel_user_table." u
860
                INNER JOIN {$this->table} g
861
                ON (u.usergroup_id = g.id)
862
                ";
863
            $where = ['where' => ['user_id = ?' => $userId]];
864
        }
865
866
        if (null !== $filterByType) {
867
            $where['where'][' AND g.group_type = ?'] = (int) $filterByType;
868
        }
869
870
        $results = Database::select(
871
            'g.*',
872
            $from,
873
            $where
874
        );
875
        $array = [];
876
        if (!empty($results)) {
877
            foreach ($results as $row) {
878
                $array[] = $row;
879
            }
880
        }
881
882
        return $array;
883
    }
884
885
    /**
886
     * Gets the usergroup id list by user id.
887
     *
888
     * @param int $userId user id
889
     *
890
     * @return array
891
     */
892
    public function get_usergroup_by_user($userId)
893
    {
894
        $userId = (int) $userId;
895
        if ($this->getUseMultipleUrl()) {
896
            $urlId = api_get_current_access_url_id();
897
            $from = $this->usergroup_rel_user_table." u
898
                    INNER JOIN {$this->access_url_rel_usergroup} a
899
                    ON (a.usergroup_id = u.usergroup_id) ";
900
            $where = ['where' => ['user_id = ? AND access_url_id = ? ' => [$userId, $urlId]]];
901
        } else {
902
            $from = $this->usergroup_rel_user_table.' u ';
903
            $where = ['where' => ['user_id = ?' => $userId]];
904
        }
905
906
        $results = Database::select(
907
            'u.usergroup_id',
908
            $from,
909
            $where
910
        );
911
912
        $array = [];
913
        if (!empty($results)) {
914
            foreach ($results as $row) {
915
                $array[] = $row['usergroup_id'];
916
            }
917
        }
918
919
        return $array;
920
    }
921
922
    /**
923
     * Subscribes sessions to a group  (also adding the members of the group in the session and course).
924
     *
925
     * @param int   $usergroup_id          usergroup id
926
     * @param array $list                  list of session ids
927
     * @param bool  $deleteCurrentSessions Optional. Empty the session list for the usergroup (class)
928
     *
929
     * @return array List of IDs of the sessions added to the usergroup
930
     */
931
    public function subscribe_sessions_to_usergroup($usergroup_id, $list, $deleteCurrentSessions = true): array
932
    {
933
        $current_list = $this->get_sessions_by_usergroup($usergroup_id);
934
        $user_list = $this->get_users_by_usergroup($usergroup_id);
935
936
        $delete_items = $new_items = [];
937
        if (!empty($list)) {
938
            foreach ($list as $session_id) {
939
                if (SessionManager::isValidId($session_id)) {
940
                    // Only if the session IDs given are not bogus
941
                    if (!in_array($session_id, $current_list)) {
942
                        $new_items[] = $session_id;
943
                    }
944
                }
945
            }
946
        }
947
        if ($deleteCurrentSessions) {
948
            if (!empty($current_list)) {
949
                foreach ($current_list as $session_id) {
950
                    if (!in_array($session_id, $list)) {
951
                        $delete_items[] = $session_id;
952
                    }
953
                }
954
            }
955
956
            // Deleting items
957
            if (!empty($delete_items)) {
958
                $sessions = '';
959
                foreach ($delete_items as $session_id) {
960
                    if (!api_get_configuration_value('usergroup_do_not_unsubscribe_users_from_session_on_session_unsubscribe')) {
961
                        if (!empty($user_list)) {
962
                            foreach ($user_list as $user_id) {
963
                                SessionManager::unsubscribe_user_from_session($session_id, $user_id);
964
                            }
965
                        }
966
                    }
967
                    Database::delete(
968
                        $this->usergroup_rel_session_table,
969
                        ['usergroup_id = ? AND session_id = ?' => [$usergroup_id, $session_id]]
970
                    );
971
                    $sessions .= $session_id.',';
972
                }
973
                // Add event to system log
974
                Event::addEvent(
975
                    LOG_GROUP_PORTAL_SESSION_UNSUBSCRIBED,
976
                    LOG_GROUP_PORTAL_ID,
977
                    'gid: '.$usergroup_id.' - sids: '.substr($sessions, 0, -1),
978
                    api_get_utc_datetime(),
979
                    api_get_user_id()
980
                );
981
            }
982
        }
983
984
        $sessions = [];
985
        // Adding new relationships.
986
        if (!empty($new_items)) {
987
            foreach ($new_items as $session_id) {
988
                $params = ['session_id' => $session_id, 'usergroup_id' => $usergroup_id];
989
                Database::insert($this->usergroup_rel_session_table, $params);
990
991
                if (!empty($user_list)) {
992
                    SessionManager::subscribeUsersToSession(
993
                        $session_id,
994
                        $user_list,
995
                        null,
996
                        false
997
                    );
998
                    $sessions[] = $session_id;
999
                }
1000
            }
1001
            // Add event to system log
1002
            Event::addEvent(
1003
                LOG_GROUP_PORTAL_SESSION_SUBSCRIBED,
1004
                LOG_GROUP_PORTAL_ID,
1005
                'gid: '.$usergroup_id.' - sids: '.implode(',', $sessions),
1006
                api_get_utc_datetime(),
1007
                api_get_user_id()
1008
            );
1009
        }
1010
1011
        return $sessions;
1012
    }
1013
1014
    /**
1015
     * Subscribes courses to a group (also adding the members of the group in the course).
1016
     *
1017
     * @param int   $usergroup_id  usergroup id
1018
     * @param array $list          list of course ids (integers)
1019
     * @param bool  $delete_groups
1020
     */
1021
    public function subscribe_courses_to_usergroup($usergroup_id, $list, $delete_groups = true)
1022
    {
1023
        $current_list = $this->get_courses_by_usergroup($usergroup_id);
1024
        $user_list = $this->get_users_by_usergroup($usergroup_id);
1025
1026
        $delete_items = $new_items = [];
1027
        if (!empty($list)) {
1028
            foreach ($list as $id) {
1029
                if (!in_array($id, $current_list)) {
1030
                    $new_items[] = $id;
1031
                }
1032
            }
1033
        }
1034
1035
        if (!empty($current_list)) {
1036
            foreach ($current_list as $id) {
1037
                if (!in_array($id, $list)) {
1038
                    $delete_items[] = $id;
1039
                }
1040
            }
1041
        }
1042
1043
        if ($delete_groups) {
1044
            $this->unsubscribe_courses_from_usergroup($usergroup_id, $delete_items);
1045
        }
1046
1047
        $courses = [];
1048
        // Adding new relationships
1049
        if (!empty($new_items)) {
1050
            foreach ($new_items as $course_id) {
1051
                $course_info = api_get_course_info_by_id($course_id);
1052
                if ($course_info) {
1053
                    if (!empty($user_list)) {
1054
                        $messageError = [];
1055
                        $messageOk = [];
1056
                        foreach ($user_list as $user_id) {
1057
                            $subscribed = CourseManager::subscribeUser(
1058
                                $user_id,
1059
                                $course_info['code'],
1060
                                STUDENT,
1061
                                0,
1062
                                0,
1063
                                true,
1064
                                false
1065
                            );
1066
                            $userInfo = api_get_user_info($user_id);
1067
                            if (!$subscribed) {
1068
                                $messageError[] = sprintf(
1069
                                    get_lang('UserXNotSubscribedToCourseX'),
1070
                                    $userInfo['complete_name_with_username'],
1071
                                    $course_info['title']
1072
                                );
1073
                            } else {
1074
                                $messageOk[] = sprintf(
1075
                                    get_lang('UserXAddedToCourseX'),
1076
                                    $userInfo['complete_name_with_username'],
1077
                                    $course_info['title']
1078
                                );
1079
                            }
1080
                        }
1081
                        if (!empty($messageError)) {
1082
                            $strMessagesError = implode('<br>', $messageError);
1083
                            Display::addFlash(
1084
                                Display::return_message(
1085
                                    $strMessagesError,
1086
                                    'error',
1087
                                    false
1088
                                )
1089
                            );
1090
                        }
1091
                        if (!empty($messageOk)) {
1092
                            $strMessagesOk = implode('<br>', $messageOk);
1093
                            Display::addFlash(
1094
                                Display::return_message(
1095
                                    $strMessagesOk,
1096
                                    'normal',
1097
                                    false
1098
                                )
1099
                            );
1100
                        }
1101
                    }
1102
                    $params = [
1103
                        'course_id' => $course_id,
1104
                        'usergroup_id' => $usergroup_id,
1105
                    ];
1106
                    Database::insert(
1107
                        $this->usergroup_rel_course_table,
1108
                        $params
1109
                    );
1110
                }
1111
                $courses[] = $course_id;
1112
            }
1113
            // Add event to system log
1114
            Event::addEvent(
1115
                LOG_GROUP_PORTAL_COURSE_SUBSCRIBED,
1116
                LOG_GROUP_PORTAL_ID,
1117
                'gid: '.$usergroup_id.' - cids: '.implode(',', $courses),
1118
                api_get_utc_datetime(),
1119
                api_get_user_id()
1120
            );
1121
        }
1122
1123
        return $courses;
1124
    }
1125
1126
    /**
1127
     * Unsubscribe a usergroup from a list of courses.
1128
     *
1129
     * @param int   $usergroup_id
1130
     * @param array $delete_items
1131
     */
1132
    public function unsubscribe_courses_from_usergroup($usergroup_id, $delete_items)
1133
    {
1134
        $courses = [];
1135
        // Deleting items.
1136
        if (!empty($delete_items)) {
1137
            $user_list = $this->get_users_by_usergroup($usergroup_id);
1138
            foreach ($delete_items as $course_id) {
1139
                $course_info = api_get_course_info_by_id($course_id);
1140
                if ($course_info) {
1141
                    if (!api_get_configuration_value('usergroup_do_not_unsubscribe_users_from_course_on_course_unsubscribe')) {
1142
                        if (!empty($user_list)) {
1143
                            foreach ($user_list as $user_id) {
1144
                                CourseManager::unsubscribe_user(
1145
                                    $user_id,
1146
                                    $course_info['code']
1147
                                );
1148
                            }
1149
                        }
1150
                    }
1151
                    Database::delete(
1152
                        $this->usergroup_rel_course_table,
1153
                        [
1154
                            'usergroup_id = ? AND course_id = ?' => [
1155
                                $usergroup_id,
1156
                                $course_id,
1157
                            ],
1158
                        ]
1159
                    );
1160
                    $courses[] = $course_id;
1161
                }
1162
            }
1163
            // Add event to system log
1164
            Event::addEvent(
1165
                LOG_GROUP_PORTAL_COURSE_UNSUBSCRIBED,
1166
                LOG_GROUP_PORTAL_ID,
1167
                'gid: '.$usergroup_id.' - cids: '.implode(',', $courses),
1168
                api_get_utc_datetime(),
1169
                api_get_user_id()
1170
            );
1171
        }
1172
1173
        return $courses;
1174
    }
1175
1176
    /**
1177
     * Unsubscribe a usergroup from a list of sessions.
1178
     *
1179
     * @param int   $groupId
1180
     * @param array $items   Session IDs to remove from the group
1181
     *
1182
     * @return array The list of session IDs that have been unsubscribed from the group
1183
     */
1184
    public function unsubscribeSessionsFromUserGroup($groupId, $items)
1185
    {
1186
        // Deleting items.
1187
        $sessions = [];
1188
        if (!empty($items)) {
1189
            $users = $this->get_users_by_usergroup($groupId);
1190
            foreach ($items as $sessionId) {
1191
                if (SessionManager::isValidId($sessionId)) {
1192
                    if (!api_get_configuration_value('usergroup_do_not_unsubscribe_users_from_session_on_session_unsubscribe')) {
1193
                        if (!empty($users)) {
1194
                            foreach ($users as $userId) {
1195
                                SessionManager::unsubscribe_user_from_session(
1196
                                    $sessionId,
1197
                                    $userId
1198
                                );
1199
                            }
1200
                        }
1201
                    }
1202
                    Database::delete(
1203
                        $this->usergroup_rel_session_table,
1204
                        [
1205
                            'usergroup_id = ? AND session_id = ?' => [
1206
                                $groupId,
1207
                                $sessionId,
1208
                            ],
1209
                        ]
1210
                    );
1211
                    $sessions[] = $sessionId;
1212
                }
1213
            }
1214
            // Add event to system log
1215
            Event::addEvent(
1216
                LOG_GROUP_PORTAL_SESSION_UNSUBSCRIBED,
1217
                LOG_GROUP_PORTAL_ID,
1218
                'gid: '.$groupId.' - sids: '.implode(',', $sessions),
1219
                api_get_utc_datetime(),
1220
                api_get_user_id()
1221
            );
1222
        }
1223
1224
        return $sessions;
1225
    }
1226
1227
    /**
1228
     * Subscribe users to a group.
1229
     *
1230
     * @param int   $usergroup_id                     usergroup id
1231
     * @param array $list                             list of user ids
1232
     * @param bool  $delete_users_not_present_in_list
1233
     * @param int   $relationType
1234
     */
1235
    public function subscribe_users_to_usergroup(
1236
        $usergroup_id,
1237
        $list,
1238
        $delete_users_not_present_in_list = true,
1239
        $relationType = 0
1240
    ) {
1241
        $current_list = $this->get_users_by_usergroup($usergroup_id);
1242
        $course_list = $this->get_courses_by_usergroup($usergroup_id);
1243
        $session_list = $this->get_sessions_by_usergroup($usergroup_id);
1244
        $session_list = array_filter($session_list);
1245
        $relationType = (int) $relationType;
1246
1247
        $delete_items = [];
1248
        $new_items = [];
1249
        if (!empty($list)) {
1250
            foreach ($list as $user_id) {
1251
                if (!in_array($user_id, $current_list)) {
1252
                    $new_items[] = $user_id;
1253
                }
1254
            }
1255
        }
1256
1257
        if (!empty($current_list)) {
1258
            foreach ($current_list as $user_id) {
1259
                if (!in_array($user_id, $list)) {
1260
                    $delete_items[] = $user_id;
1261
                }
1262
            }
1263
        }
1264
1265
        // Deleting items
1266
        if (!empty($delete_items) && $delete_users_not_present_in_list) {
1267
            foreach ($delete_items as $user_id) {
1268
                if (!api_get_configuration_value('usergroup_do_not_unsubscribe_users_from_course_nor_session_on_user_unsubscribe')) {
1269
                    // Removing courses
1270
                    if (!empty($course_list)) {
1271
                        foreach ($course_list as $course_id) {
1272
                            $course_info = api_get_course_info_by_id($course_id);
1273
                            CourseManager::unsubscribe_user($user_id, $course_info['code']);
1274
                        }
1275
                    }
1276
                    // Removing sessions
1277
                    if (!empty($session_list)) {
1278
                        foreach ($session_list as $session_id) {
1279
                            SessionManager::unsubscribe_user_from_session($session_id, $user_id);
1280
                        }
1281
                    }
1282
                }
1283
1284
                if (empty($relationType)) {
1285
                    Database::delete(
1286
                        $this->usergroup_rel_user_table,
1287
                        [
1288
                            'usergroup_id = ? AND user_id = ? AND (relation_type = "0" OR relation_type IS NULL OR relation_type = "")' => [
1289
                                $usergroup_id,
1290
                                $user_id,
1291
                            ],
1292
                        ]
1293
                    );
1294
                } else {
1295
                    Database::delete(
1296
                        $this->usergroup_rel_user_table,
1297
                        [
1298
                            'usergroup_id = ? AND user_id = ? AND relation_type = ?' => [
1299
                                $usergroup_id,
1300
                                $user_id,
1301
                                $relationType,
1302
                            ],
1303
                        ]
1304
                    );
1305
                }
1306
                // Add event to system log
1307
                Event::addEvent(
1308
                    LOG_GROUP_PORTAL_USER_UNSUBSCRIBED,
1309
                    LOG_GROUP_PORTAL_ID,
1310
                    'gid: '.$usergroup_id.' - uid: '.$user_id,
1311
                    api_get_utc_datetime(),
1312
                    api_get_user_id()
1313
                );
1314
            }
1315
        }
1316
1317
        // Adding new relationships
1318
        if (!empty($new_items)) {
1319
            // Adding sessions
1320
            if (!empty($session_list)) {
1321
                foreach ($session_list as $session_id) {
1322
                    SessionManager::subscribeUsersToSession($session_id, $new_items, null, false);
1323
                }
1324
            }
1325
1326
            foreach ($new_items as $user_id) {
1327
                // Adding courses
1328
                if (!empty($course_list)) {
1329
                    $messageError = [];
1330
                    $messageOk = [];
1331
                    foreach ($course_list as $course_id) {
1332
                        $course_info = api_get_course_info_by_id($course_id);
1333
                        $subscribed = CourseManager::subscribeUser(
1334
                            $user_id,
1335
                            $course_info['code'],
1336
                            STUDENT,
1337
                            0,
1338
                            0,
1339
                            true,
1340
                            false
1341
                        );
1342
                        $userInfo = api_get_user_info($user_id);
1343
                        if (!$subscribed) {
1344
                            $messageError[] = sprintf(
1345
                                get_lang('UserXNotSubscribedToCourseX'),
1346
                                $userInfo['complete_name_with_username'],
1347
                                $course_info['title']
1348
                            );
1349
                        } else {
1350
                            $messageOk[] = sprintf(
1351
                                get_lang('UserXAddedToCourseX'),
1352
                                $userInfo['complete_name_with_username'],
1353
                                $course_info['title']
1354
                            );
1355
                        }
1356
                    }
1357
                    if (!empty($messageError)) {
1358
                        $strMessagesError = implode('<br>', $messageError);
1359
                        Display::addFlash(
1360
                            Display::return_message(
1361
                                $strMessagesError,
1362
                                'error',
1363
                                false
1364
                            )
1365
                        );
1366
                    }
1367
                    if (!empty($messageOk)) {
1368
                        $strMessagesOk = implode('<br>', $messageOk);
1369
                        Display::addFlash(
1370
                            Display::return_message(
1371
                                $strMessagesOk,
1372
                                'normal',
1373
                                false
1374
                            )
1375
                        );
1376
                    }
1377
                }
1378
                $params = [
1379
                    'user_id' => $user_id,
1380
                    'usergroup_id' => $usergroup_id,
1381
                    'relation_type' => $relationType,
1382
                ];
1383
                Database::insert($this->usergroup_rel_user_table, $params);
1384
                // Add event to system log
1385
                Event::addEvent(
1386
                    LOG_GROUP_PORTAL_USER_SUBSCRIBED,
1387
                    LOG_GROUP_PORTAL_ID,
1388
                    'gid: '.$usergroup_id.' - uid: '.$user_id,
1389
                    api_get_utc_datetime(),
1390
                    api_get_user_id()
1391
                );
1392
            }
1393
        }
1394
    }
1395
1396
    /**
1397
     * @param string $name
1398
     *
1399
     * @return bool
1400
     */
1401
    public function usergroup_exists($name)
1402
    {
1403
        $name = Database::escape_string($name);
1404
        if ($this->getUseMultipleUrl()) {
1405
            $urlId = api_get_current_access_url_id();
1406
            $sql = "SELECT * FROM $this->table u
1407
                    INNER JOIN {$this->access_url_rel_usergroup} a
1408
                    ON (a.usergroup_id = u.id)
1409
                    WHERE name = '".$name."' AND access_url_id = $urlId";
1410
        } else {
1411
            $sql = "SELECT * FROM $this->table WHERE name = '".$name."'";
1412
        }
1413
1414
        $res = Database::query($sql);
1415
1416
        return 0 != Database::num_rows($res);
1417
    }
1418
1419
    /**
1420
     * Returns whether teachers can access the classes, as per 'allow_teachers_to_classes' setting.
1421
     *
1422
     * @return bool
1423
     */
1424
    public function allowTeachers()
1425
    {
1426
        return true === api_get_configuration_value('allow_teachers_to_classes');
1427
    }
1428
1429
    /**
1430
     * @param int    $sidx
1431
     * @param int    $sord
1432
     * @param int    $start
1433
     * @param int    $limit
1434
     * @param string $extraWhereCondition
1435
     *
1436
     * @return array
1437
     */
1438
    public function getUsergroupsPagination($sidx, $sord, $start, $limit, $extraWhereCondition = '')
1439
    {
1440
        $sord = in_array(strtolower($sord), ['asc', 'desc']) ? $sord : 'desc';
1441
1442
        $start = (int) $start;
1443
        $limit = (int) $limit;
1444
1445
        $sqlFrom = "{$this->table} u ";
1446
        $sqlWhere = '1 = 1 ';
1447
1448
        if ($this->getUseMultipleUrl()) {
1449
            $urlId = api_get_current_access_url_id();
1450
            $sqlFrom .= " INNER JOIN {$this->access_url_rel_usergroup} a ON (u.id = a.usergroup_id) ";
1451
            $sqlWhere .= " AND a.access_url_id = $urlId ";
1452
        }
1453
1454
        if ($this->allowTeachers()) {
1455
            if (!api_is_platform_admin()) {
1456
                $userId = api_get_user_id();
1457
                $sqlWhere .= " AND author_id = $userId ";
1458
            }
1459
        }
1460
1461
        if ($extraWhereCondition) {
1462
            $sqlWhere .= " AND $extraWhereCondition ";
1463
        }
1464
1465
        $result = Database::store_result(
1466
            Database::query("SELECT u.* FROM $sqlFrom WHERE $sqlWhere ORDER BY name $sord LIMIT $start, $limit")
1467
        );
1468
1469
        $new_result = [];
1470
        if (!empty($result)) {
1471
            foreach ($result as $group) {
1472
                $group['sessions'] = count($this->get_sessions_by_usergroup($group['id']));
1473
                $group['courses'] = count($this->get_courses_by_usergroup($group['id']));
1474
                $roles = [];
1475
                switch ($group['group_type']) {
1476
                    case 0:
1477
                        $group['group_type'] = Display::label(get_lang('Class'), 'info');
1478
                        $roles = [0];
1479
                        break;
1480
                    case 1:
1481
                        $group['group_type'] = Display::label(get_lang('Social'), 'success');
1482
                        $roles = [
1483
                            GROUP_USER_PERMISSION_ADMIN,
1484
                            GROUP_USER_PERMISSION_READER,
1485
                            GROUP_USER_PERMISSION_MODERATOR,
1486
                            GROUP_USER_PERMISSION_HRM,
1487
                        ];
1488
                        break;
1489
                }
1490
                $group['users'] = Display::url(
1491
                    count($this->get_users_by_usergroup($group['id'], $roles)),
1492
                    api_get_path(WEB_CODE_PATH).'admin/usergroup_users.php?id='.$group['id']
1493
                );
1494
                $new_result[] = $group;
1495
            }
1496
            $result = $new_result;
1497
        }
1498
        $columns = ['name', 'users', 'courses', 'sessions', 'group_type'];
1499
1500
        if (!in_array($sidx, $columns)) {
1501
            $sidx = 'name';
1502
        }
1503
1504
        // Multidimensional sort
1505
        $result = msort($result, $sidx, $sord);
1506
1507
        return $result;
1508
    }
1509
1510
    /**
1511
     * @param array $options
1512
     *
1513
     * @return array
1514
     */
1515
    public function getDataToExport($options = [])
1516
    {
1517
        $and = '';
1518
        if (!empty($options) && !empty($options['where'])) {
1519
            $and = ' AND ';
1520
        }
1521
        if ($this->getUseMultipleUrl()) {
1522
            $urlId = api_get_current_access_url_id();
1523
            $from = $this->table." u
1524
                    INNER JOIN {$this->access_url_rel_usergroup} a
1525
                    ON (u.id = a.usergroup_id)";
1526
            $options['where'][$and.' access_url_id = ? '] = $urlId;
1527
            if ($this->allowTeachers()) {
1528
                $options['where'] = [' AND author_id = ? ' => api_get_user_id()];
1529
            }
1530
            $classes = Database::select('u.id, name, description, group_type, visibility', $from, $options);
1531
        } else {
1532
            if ($this->allowTeachers()) {
1533
                $options['where'] = [$and.' author_id = ? ' => api_get_user_id()];
1534
            }
1535
            $classes = Database::select('id, name, description, group_type, visibility', $this->table, $options);
1536
        }
1537
1538
        $result = [];
1539
        if (!empty($classes)) {
1540
            foreach ($classes as $data) {
1541
                $users = $this->getUserListByUserGroup($data['id']);
1542
                $userToString = null;
1543
                if (!empty($users)) {
1544
                    $userNameList = [];
1545
                    foreach ($users as $userData) {
1546
                        $userNameList[] = $userData['username'];
1547
                    }
1548
                    $userToString = implode(',', $userNameList);
1549
                }
1550
1551
                $courses = $this->get_courses_by_usergroup($data['id'], true);
1552
                $coursesToString = '';
1553
                if (!empty($courses)) {
1554
                    $coursesToString = implode(', ', array_column($courses, 'code'));
1555
                }
1556
1557
                $sessions = $this->get_sessions_by_usergroup($data['id']);
1558
                $sessionsToString = '';
1559
                if (!empty($sessions)) {
1560
                    $sessionList = [];
1561
                    foreach ($sessions as $sessionId) {
1562
                        $sessionList[] = api_get_session_info($sessionId)['name'];
1563
                    }
1564
                    $sessionsToString = implode(', ', $sessionList);
1565
                }
1566
1567
                $data['users'] = $userToString;
1568
                $data['courses'] = $coursesToString;
1569
                $data['sessions'] = $sessionsToString;
1570
                $result[] = $data;
1571
            }
1572
        }
1573
1574
        return $result;
1575
    }
1576
1577
    /**
1578
     * @param string $firstLetter
1579
     * @param int    $limit
1580
     *
1581
     * @return array
1582
     */
1583
    public function filterByFirstLetter($firstLetter, $limit = 0)
1584
    {
1585
        $firstLetter = Database::escape_string($firstLetter);
1586
        $limit = (int) $limit;
1587
1588
        $sql = ' SELECT g.id, name ';
1589
1590
        $urlCondition = '';
1591
        if ($this->getUseMultipleUrl()) {
1592
            $urlId = api_get_current_access_url_id();
1593
            $sql .= " FROM $this->table g
1594
                    INNER JOIN $this->access_url_rel_usergroup a
1595
                    ON (g.id = a.usergroup_id) ";
1596
            $urlCondition = " AND access_url_id = $urlId ";
1597
        } else {
1598
            $sql = " FROM $this->table g ";
1599
        }
1600
        $sql .= "
1601
		        WHERE
1602
		            name LIKE '".$firstLetter."%' OR
1603
		            name LIKE '".api_strtolower($firstLetter)."%'
1604
		            $urlCondition
1605
		        ORDER BY name DESC ";
1606
1607
        if (!empty($limit)) {
1608
            $sql .= " LIMIT $limit ";
1609
        }
1610
1611
        $result = Database::query($sql);
1612
1613
        return Database::store_result($result);
1614
    }
1615
1616
    /**
1617
     * Select user group not in list.
1618
     *
1619
     * @param array $list
1620
     *
1621
     * @return array
1622
     */
1623
    public function getUserGroupNotInList($list)
1624
    {
1625
        if (empty($list)) {
1626
            return [];
1627
        }
1628
1629
        $list = array_map('intval', $list);
1630
        $listToString = implode("','", $list);
1631
        $sql = "SELECT * FROM $this->table g WHERE g.id NOT IN ('$listToString')";
1632
        $result = Database::query($sql);
1633
1634
        return Database::store_result($result, 'ASSOC');
1635
    }
1636
1637
    /**
1638
     * @param $params
1639
     * @param bool $show_query
1640
     *
1641
     * @return bool|int
1642
     */
1643
    public function save($params, $show_query = false)
1644
    {
1645
        $params['updated_at'] = $params['created_at'] = api_get_utc_datetime();
1646
        $params['group_type'] = !empty($params['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
1647
        $params['allow_members_leave_group'] = isset($params['allow_members_leave_group']) ? 1 : 0;
1648
1649
        $groupExists = $this->usergroup_exists(trim($params['name']));
1650
        if (false == $groupExists) {
1651
            if ($this->allowTeachers()) {
1652
                $params['author_id'] = api_get_user_id();
1653
            }
1654
            $id = parent::save($params, $show_query);
1655
            if ($id) {
1656
                if ($this->getUseMultipleUrl()) {
1657
                    $this->subscribeToUrl($id, api_get_current_access_url_id());
1658
                }
1659
1660
                if (self::SOCIAL_CLASS == $params['group_type']) {
1661
                    $this->add_user_to_group(
1662
                        api_get_user_id(),
1663
                        $id,
1664
                        GROUP_USER_PERMISSION_ADMIN
1665
                    );
1666
                }
1667
                $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
1668
                $picture = $this->manageFileUpload($id, $picture);
1669
                if ($picture) {
1670
                    $params = [
1671
                        'id' => $id,
1672
                        'picture' => $picture,
1673
                        'group_type' => $params['group_type'],
1674
                    ];
1675
                    $this->update($params);
1676
                }
1677
            }
1678
            // Add event to system log
1679
            Event::addEvent(
1680
                LOG_GROUP_PORTAL_CREATED,
1681
                LOG_GROUP_PORTAL_ID,
1682
                'id: '.$id,
1683
                api_get_utc_datetime(),
1684
                api_get_user_id()
1685
            );
1686
1687
            return $id;
1688
        }
1689
1690
        return false;
1691
    }
1692
1693
    /**
1694
     * {@inheritdoc}
1695
     */
1696
    public function update($values, $showQuery = false)
1697
    {
1698
        $values['updated_on'] = api_get_utc_datetime();
1699
        $values['group_type'] = !empty($values['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
1700
        $values['allow_members_leave_group'] = isset($values['allow_members_leave_group']) ? 1 : 0;
1701
1702
        if (isset($values['id'])) {
1703
            $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
1704
            if (!empty($picture)) {
1705
                $picture = $this->manageFileUpload($values['id'], $picture);
1706
                if ($picture) {
1707
                    $values['picture'] = $picture;
1708
                }
1709
            }
1710
1711
            if (isset($values['delete_picture'])) {
1712
                $values['picture'] = null;
1713
            }
1714
        }
1715
1716
        parent::update($values, $showQuery);
1717
1718
        if (isset($values['delete_picture'])) {
1719
            $this->delete_group_picture($values['id']);
1720
        }
1721
        // Add event to system log
1722
        Event::addEvent(
1723
            LOG_GROUP_PORTAL_UPDATED,
1724
            LOG_GROUP_PORTAL_ID,
1725
            'id: '.$values['id'],
1726
            api_get_utc_datetime(),
1727
            api_get_user_id()
1728
        );
1729
1730
        return true;
1731
    }
1732
1733
    /**
1734
     * @param int    $groupId
1735
     * @param string $picture
1736
     *
1737
     * @return bool|string
1738
     */
1739
    public function manageFileUpload($groupId, $picture)
1740
    {
1741
        if (!empty($picture['name'])) {
1742
            return $this->update_group_picture(
1743
                $groupId,
1744
                $picture['name'],
1745
                $picture['tmp_name']
1746
            );
1747
        }
1748
1749
        return false;
1750
    }
1751
1752
    /**
1753
     * @param int $groupId
1754
     *
1755
     * @return string
1756
     */
1757
    public function delete_group_picture($groupId)
1758
    {
1759
        return $this->update_group_picture($groupId);
1760
    }
1761
1762
    /**
1763
     * Creates new group pictures in various sizes of a user, or deletes user pfotos.
1764
     * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php.
1765
     *
1766
     * @param    int    The group id
1767
     * @param string $file The common file name for the newly created photos.
1768
     *                     It will be checked and modified for compatibility with the file system.
1769
     *                     If full name is provided, path component is ignored.
1770
     *                     If an empty name is provided, then old user photos are deleted only,
1771
     *
1772
     * @see UserManager::delete_user_picture() as the prefered way for deletion.
1773
     *
1774
     * @param string $source_file the full system name of the image from which user photos will be created
1775
     *
1776
     * @return mixed Returns the resulting common file name of created images which usually should be stored in database.
1777
     *               When an image is removed the function returns an empty string.
1778
     *               In case of internal error or negative validation it returns FALSE.
1779
     */
1780
    public function update_group_picture($group_id, $file = null, $source_file = null)
1781
    {
1782
        $group_id = (int) $group_id;
1783
1784
        if (empty($group_id)) {
1785
            return false;
1786
        }
1787
        $delete = empty($file);
1788
        if (empty($source_file)) {
1789
            $source_file = $file;
1790
        }
1791
1792
        // User-reserved directory where photos have to be placed.
1793
        $path_info = $this->get_group_picture_path_by_id($group_id, 'system', true);
1794
1795
        $path = $path_info['dir'];
1796
1797
        // If this directory does not exist - we create it.
1798
        if (!is_dir($path)) {
1799
            $res = @mkdir($path, api_get_permissions_for_new_directories(), true);
1800
            if ($res === false) {
1801
                // There was an issue creating the directory $path, probably
1802
                // permissions-related
1803
                return false;
1804
            }
1805
        }
1806
1807
        // The old photos (if any).
1808
        $old_file = $path_info['file'];
1809
1810
        // Let us delete them.
1811
        if (!empty($old_file)) {
1812
            if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
1813
                $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
1814
                @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
1815
                @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
1816
                @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
1817
                @rename($path.$old_file, $path.$prefix.$old_file);
1818
            } else {
1819
                @unlink($path.'small_'.$old_file);
1820
                @unlink($path.'medium_'.$old_file);
1821
                @unlink($path.'big_'.$old_file);
1822
                @unlink($path.$old_file);
1823
            }
1824
        }
1825
1826
        // Exit if only deletion has been requested. Return an empty picture name.
1827
        if ($delete) {
1828
            return '';
1829
        }
1830
1831
        // Validation 2.
1832
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
1833
        $file = str_replace('\\', '/', $file);
1834
        $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
1835
        $extension = strtolower(substr(strrchr($filename, '.'), 1));
1836
        if (!in_array($extension, $allowed_types)) {
1837
            return false;
1838
        }
1839
1840
        // This is the common name for the new photos.
1841
        if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
1842
            $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
1843
            $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
1844
            $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
1845
        } else {
1846
            $filename = api_replace_dangerous_char($filename);
1847
            if (PREFIX_IMAGE_FILENAME_WITH_UID) {
1848
                $filename = uniqid('').'_'.$filename;
1849
            }
1850
            // We always prefix user photos with user ids, so on setting
1851
            // api_get_setting('split_users_upload_directory') === 'true'
1852
            // the correspondent directories to be found successfully.
1853
            $filename = $group_id.'_'.$filename;
1854
        }
1855
1856
        // Storing the new photos in 4 versions with various sizes.
1857
1858
        /*$image->resize(
1859
        // get original size and set width (widen) or height (heighten).
1860
        // width or height will be set maintaining aspect ratio.
1861
            $image->getSize()->widen( 700 )
1862
        );*/
1863
1864
        // Usign the Imagine service
1865
        $imagine = new Imagine\Gd\Imagine();
1866
        $image = $imagine->open($source_file);
1867
1868
        $options = [
1869
            'quality' => 90,
1870
        ];
1871
1872
        //$image->resize(new Imagine\Image\Box(200, 200))->save($path.'big_'.$filename);
1873
        $image->resize($image->getSize()->widen(200))->save($path.'big_'.$filename, $options);
1874
1875
        $image = $imagine->open($source_file);
1876
        $image->resize(new Imagine\Image\Box(85, 85))->save($path.'medium_'.$filename, $options);
1877
1878
        $image = $imagine->open($source_file);
1879
        $image->resize(new Imagine\Image\Box(22, 22))->save($path.'small_'.$filename);
1880
1881
        /*
1882
        $small  = self::resize_picture($source_file, 22);
1883
        $medium = self::resize_picture($source_file, 85);
1884
        $normal = self::resize_picture($source_file, 200);
1885
1886
        $big = new Image($source_file); // This is the original picture.
1887
        $ok = $small && $small->send_image($path.'small_'.$filename)
1888
            && $medium && $medium->send_image($path.'medium_'.$filename)
1889
            && $normal && $normal->send_image($path.'big_'.$filename)
1890
            && $big && $big->send_image($path.$filename);
1891
        return $ok ? $filename : false;*/
1892
        return $filename;
1893
    }
1894
1895
    /**
1896
     * @return mixed
1897
     */
1898
    public function getGroupType()
1899
    {
1900
        return $this->groupType;
1901
    }
1902
1903
    /**
1904
     * @param int $id
1905
     *
1906
     * @return bool|void
1907
     */
1908
    public function delete($id)
1909
    {
1910
        $id = (int) $id;
1911
        if ($this->getUseMultipleUrl()) {
1912
            $this->unsubscribeToUrl($id, api_get_current_access_url_id());
1913
        }
1914
1915
        $sql = "DELETE FROM $this->usergroup_rel_user_table
1916
                WHERE usergroup_id = $id";
1917
        Database::query($sql);
1918
1919
        $sql = "DELETE FROM $this->usergroup_rel_course_table
1920
                WHERE usergroup_id = $id";
1921
        Database::query($sql);
1922
1923
        $sql = "DELETE FROM $this->usergroup_rel_session_table
1924
                WHERE usergroup_id = $id";
1925
        Database::query($sql);
1926
1927
        $res = parent::delete($id);
1928
        // Add event to system log
1929
        if ($res) {
1930
            Event::addEvent(
1931
                LOG_GROUP_PORTAL_DELETED,
1932
                LOG_GROUP_PORTAL_ID,
1933
                'id: '.$id,
1934
                api_get_utc_datetime(),
1935
                api_get_user_id()
1936
            );
1937
        }
1938
1939
        return $res;
1940
    }
1941
1942
    /**
1943
     * @param int $id
1944
     * @param int $urlId
1945
     */
1946
    public function subscribeToUrl($id, $urlId)
1947
    {
1948
        Database::insert(
1949
            $this->access_url_rel_usergroup,
1950
            [
1951
                'access_url_id' => $urlId,
1952
                'usergroup_id' => $id,
1953
            ]
1954
        );
1955
    }
1956
1957
    /**
1958
     * @param int $id
1959
     * @param int $urlId
1960
     */
1961
    public function unsubscribeToUrl($id, $urlId)
1962
    {
1963
        Database::delete(
1964
            $this->access_url_rel_usergroup,
1965
            [
1966
                'access_url_id = ? AND usergroup_id = ? ' => [$urlId, $id],
1967
            ]
1968
        );
1969
    }
1970
1971
    /**
1972
     * @param $needle
1973
     *
1974
     * @return xajaxResponse
1975
     */
1976
    public static function searchUserGroupAjax($needle)
1977
    {
1978
        $response = new xajaxResponse();
1979
        $return = '';
1980
1981
        if (!empty($needle)) {
1982
            // xajax send utf8 datas... datas in db can be non-utf8 datas
1983
            $charset = api_get_system_encoding();
1984
            $needle = api_convert_encoding($needle, $charset, 'utf-8');
1985
            $needle = Database::escape_string($needle);
1986
1987
            $sql = 'SELECT id, name
1988
                    FROM '.Database::get_main_table(TABLE_USERGROUP).' u
1989
                    WHERE name LIKE "'.$needle.'%"
1990
                    ORDER BY name
1991
                    LIMIT 11';
1992
            $result = Database::query($sql);
1993
            $i = 0;
1994
            while ($data = Database::fetch_array($result)) {
1995
                $i++;
1996
                if ($i <= 10) {
1997
                    $return .= '<a
1998
                    href="javascript: void(0);"
1999
                    onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['name']).' \')">'.$data['name'].' </a><br />';
2000
                } else {
2001
                    $return .= '...<br />';
2002
                }
2003
            }
2004
        }
2005
        $response->addAssign('ajax_list_courses', 'innerHTML', api_utf8_encode($return));
2006
2007
        return $response;
2008
    }
2009
2010
    /**
2011
     * Get user list by usergroup.
2012
     *
2013
     * @param int    $id
2014
     * @param string $orderBy
2015
     *
2016
     * @return array
2017
     */
2018
    public function getUserListByUserGroup($id, $orderBy = '')
2019
    {
2020
        $id = (int) $id;
2021
        $sql = "SELECT u.* FROM $this->table_user u
2022
                INNER JOIN $this->usergroup_rel_user_table c
2023
                ON c.user_id = u.id
2024
                WHERE c.usergroup_id = $id"
2025
                ;
2026
2027
        if (!empty($orderBy)) {
2028
            $orderBy = Database::escape_string($orderBy);
2029
            $sql .= " ORDER BY $orderBy ";
2030
        }
2031
        $result = Database::query($sql);
2032
2033
        return Database::store_result($result);
2034
    }
2035
2036
    /**
2037
     * @param FormValidator $form
2038
     * @param string        $type
2039
     * @param array         $data
2040
     */
2041
    public function setForm($form, $type = 'add', $data = [])
2042
    {
2043
        $header = '';
2044
        switch ($type) {
2045
            case 'add':
2046
                $header = get_lang('Add');
2047
                break;
2048
            case 'edit':
2049
                $header = get_lang('Edit');
2050
                break;
2051
        }
2052
2053
        $form->addHeader($header);
2054
2055
        // Name
2056
        $form->addText('name', get_lang('Name'), true, ['maxlength' => 255]);
2057
        $form->addRule('name', '', 'maxlength', 255);
2058
2059
        // Description
2060
        $form->addTextarea('description', get_lang('Description'), ['cols' => 58]);
2061
        $form->applyFilter('description', 'trim');
2062
2063
        if ($this->showGroupTypeSetting) {
2064
            $form->addElement(
2065
                'checkbox',
2066
                'group_type',
2067
                null,
2068
                get_lang('SocialGroup')
2069
            );
2070
        }
2071
2072
        // url
2073
        $form->addText('url', get_lang('Url'), false);
2074
2075
        // Picture
2076
        $allowed_picture_types = $this->getAllowedPictureExtensions();
2077
2078
        $form->addFile('picture', get_lang('AddPicture'));
2079
        $form->addRule(
2080
            'picture',
2081
            get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
2082
            'filetype',
2083
            $allowed_picture_types
2084
        );
2085
2086
        if (isset($data['picture']) && strlen($data['picture']) > 0) {
2087
            $picture = $this->get_picture_group($data['id'], $data['picture'], 80);
2088
            $img = '<img src="'.$picture['file'].'" />';
2089
            $form->addLabel(null, $img);
2090
            $form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
2091
        }
2092
2093
        $form->addElement('select', 'visibility', get_lang('GroupPermissions'), $this->getGroupStatusList());
2094
        $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
2095
        $form->addElement('checkbox', 'allow_members_leave_group', '', get_lang('AllowMemberLeaveGroup'));
2096
2097
        // Setting the form elements
2098
        if ($type === 'add') {
2099
            $form->addButtonCreate($header);
2100
        } else {
2101
            $form->addButtonUpdate($header);
2102
        }
2103
    }
2104
2105
    /**
2106
     * Gets the current group image.
2107
     *
2108
     * @param string $id group id
2109
     * @param string picture group name
2110
     * @param string height
2111
     * @param string $size_picture picture size it can be small_,  medium_  or  big_
2112
     * @param string style css
2113
     *
2114
     * @return array with the file and the style of an image i.e $array['file'] $array['style']
2115
     */
2116
    public function get_picture_group(
2117
        $id,
2118
        $picture_file,
2119
        $height,
2120
        $size_picture = GROUP_IMAGE_SIZE_MEDIUM,
2121
        $style = ''
2122
    ) {
2123
        $picture = [];
2124
        if ($picture_file === 'unknown.jpg') {
2125
            $picture['file'] = Display::returnIconPath($picture_file);
2126
2127
            return $picture;
2128
        }
2129
2130
        switch ($size_picture) {
2131
            case GROUP_IMAGE_SIZE_ORIGINAL:
2132
                $size_picture = '';
2133
                break;
2134
            case GROUP_IMAGE_SIZE_BIG:
2135
                $size_picture = 'big_';
2136
                break;
2137
            case GROUP_IMAGE_SIZE_MEDIUM:
2138
                $size_picture = 'medium_';
2139
                break;
2140
            case GROUP_IMAGE_SIZE_SMALL:
2141
                $size_picture = 'small_';
2142
                break;
2143
            default:
2144
                $size_picture = 'medium_';
2145
        }
2146
2147
        $image_array_sys = $this->get_group_picture_path_by_id($id, 'system', false, true);
2148
        $image_array = $this->get_group_picture_path_by_id($id, 'web', false, true);
2149
        $file = $image_array_sys['dir'].$size_picture.$picture_file;
2150
        if (file_exists($file)) {
2151
            $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
2152
            if ($height > 0) {
2153
                $dimension = api_getimagesize($picture['file']);
2154
                $margin = ($height - $dimension['width']) / 2;
2155
                //@ todo the padding-top should not be here
2156
            }
2157
        } else {
2158
            $file = $image_array_sys['dir'].$picture_file;
2159
            if (file_exists($file) && !is_dir($file)) {
2160
                $picture['file'] = $image_array['dir'].$picture_file;
2161
            } else {
2162
                $picture['file'] = Display::returnIconPath('group_na.png', 64);
2163
            }
2164
        }
2165
2166
        return $picture;
2167
    }
2168
2169
    /**
2170
     * Gets the group picture URL or path from group ID (returns an array).
2171
     * The return format is a complete path, enabling recovery of the directory
2172
     * with dirname() or the file with basename(). This also works for the
2173
     * functions dealing with the user's productions, as they are located in
2174
     * the same directory.
2175
     *
2176
     * @param    int    User ID
2177
     * @param    string    Type of path to return (can be 'none', 'system', 'rel', 'web')
2178
     * @param    bool    Whether we want to have the directory name returned 'as if'
2179
     * there was a file or not (in the case we want to know which directory to create -
2180
     * otherwise no file means no split subdir)
2181
     * @param    bool    If we want that the function returns the /main/img/unknown.jpg image set it at true
2182
     *
2183
     * @return array Array of 2 elements: 'dir' and 'file' which contain the dir
2184
     *               and file as the name implies if image does not exist it will return the unknown
2185
     *               image if anonymous parameter is true if not it returns an empty er's
2186
     */
2187
    public function get_group_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false)
2188
    {
2189
        switch ($type) {
2190
            case 'system': // Base: absolute system path.
2191
                $base = api_get_path(SYS_UPLOAD_PATH);
2192
                break;
2193
            case 'rel': // Base: semi-absolute web path (no server base).
2194
                $base = api_get_path(REL_CODE_PATH);
2195
                break;
2196
            case 'web': // Base: absolute web path.
2197
                $base = api_get_path(WEB_UPLOAD_PATH);
2198
                break;
2199
            case 'none':
2200
            default: // Base: empty, the result path below will be relative.
2201
                $base = '';
2202
        }
2203
        $id = (int) $id;
2204
2205
        if (empty($id) || empty($type)) {
2206
            return $anonymous ? ['dir' => $base.'img/', 'file' => 'unknown.jpg'] : ['dir' => '', 'file' => ''];
2207
        }
2208
2209
        $group_table = Database::get_main_table(TABLE_USERGROUP);
2210
        $sql = "SELECT picture FROM $group_table WHERE id = ".$id;
2211
        $res = Database::query($sql);
2212
2213
        if (!Database::num_rows($res)) {
2214
            return $anonymous ? ['dir' => $base.'img/', 'file' => 'unknown.jpg'] : ['dir' => '', 'file' => ''];
2215
        }
2216
        $user = Database::fetch_array($res);
2217
        $picture_filename = trim($user['picture']);
2218
2219
        if (api_get_setting('split_users_upload_directory') === 'true') {
2220
            if (!empty($picture_filename)) {
2221
                $dir = $base.'groups/'.substr($picture_filename, 0, 1).'/'.$id.'/';
2222
            } elseif ($preview) {
2223
                $dir = $base.'groups/'.substr((string) $id, 0, 1).'/'.$id.'/';
2224
            } else {
2225
                $dir = $base.'groups/'.$id.'/';
2226
            }
2227
        } else {
2228
            $dir = $base.'groups/'.$id.'/';
2229
        }
2230
2231
        return ['dir' => $dir, 'file' => $picture_filename];
2232
    }
2233
2234
    /**
2235
     * @return array
2236
     */
2237
    public function getAllowedPictureExtensions()
2238
    {
2239
        return ['jpg', 'jpeg', 'png', 'gif'];
2240
    }
2241
2242
    /**
2243
     * @return array
2244
     */
2245
    public function getGroupStatusList()
2246
    {
2247
        $status = [
2248
            GROUP_PERMISSION_OPEN => get_lang('Open'),
2249
            GROUP_PERMISSION_CLOSED => get_lang('Closed'),
2250
        ];
2251
2252
        return $status;
2253
    }
2254
2255
    /**
2256
     * @param int $type
2257
     */
2258
    public function setGroupType($type)
2259
    {
2260
        $this->groupType = (int) $type;
2261
    }
2262
2263
    /**
2264
     * @param int $group_id
2265
     * @param int $user_id
2266
     *
2267
     * @return bool
2268
     */
2269
    public function is_group_admin($group_id, $user_id = 0)
2270
    {
2271
        if (empty($user_id)) {
2272
            $user_id = api_get_user_id();
2273
        }
2274
        $user_role = $this->get_user_group_role($user_id, $group_id);
2275
        if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN])) {
2276
            return true;
2277
        } else {
2278
            return false;
2279
        }
2280
    }
2281
2282
    /**
2283
     * @param int $group_id
2284
     * @param int $user_id
2285
     *
2286
     * @return bool
2287
     */
2288
    public function isGroupModerator($group_id, $user_id = 0)
2289
    {
2290
        if (empty($user_id)) {
2291
            $user_id = api_get_user_id();
2292
        }
2293
        $user_role = $this->get_user_group_role($user_id, $group_id);
2294
        if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR])) {
2295
            return true;
2296
        } else {
2297
            return false;
2298
        }
2299
    }
2300
2301
    /**
2302
     * @param int $group_id
2303
     * @param int $user_id
2304
     *
2305
     * @return bool
2306
     */
2307
    public function is_group_member($group_id, $user_id = 0)
2308
    {
2309
        if (api_is_platform_admin()) {
2310
            return true;
2311
        }
2312
        if (empty($user_id)) {
2313
            $user_id = api_get_user_id();
2314
        }
2315
        $roles = [
2316
            GROUP_USER_PERMISSION_ADMIN,
2317
            GROUP_USER_PERMISSION_MODERATOR,
2318
            GROUP_USER_PERMISSION_READER,
2319
            GROUP_USER_PERMISSION_HRM,
2320
        ];
2321
        $user_role = $this->get_user_group_role($user_id, $group_id);
2322
        if (in_array($user_role, $roles)) {
2323
            return true;
2324
        } else {
2325
            return false;
2326
        }
2327
    }
2328
2329
    /**
2330
     * Gets the relationship between a group and a User.
2331
     *
2332
     * @author Julio Montoya
2333
     *
2334
     * @param int $user_id
2335
     * @param int $group_id
2336
     *
2337
     * @return int 0 if there are not relationship otherwise returns the user group
2338
     * */
2339
    public function get_user_group_role($user_id, $group_id)
2340
    {
2341
        $table_group_rel_user = $this->usergroup_rel_user_table;
2342
        $return_value = 0;
2343
        $user_id = (int) $user_id;
2344
        $group_id = (int) $group_id;
2345
2346
        if (!empty($user_id) && !empty($group_id)) {
2347
            $sql = "SELECT relation_type
2348
                    FROM $table_group_rel_user
2349
                    WHERE
2350
                        usergroup_id = $group_id AND
2351
                        user_id = $user_id ";
2352
            $result = Database::query($sql);
2353
            if (Database::num_rows($result) > 0) {
2354
                $row = Database::fetch_array($result, 'ASSOC');
2355
                $return_value = $row['relation_type'];
2356
            }
2357
        }
2358
2359
        return $return_value;
2360
    }
2361
2362
    /**
2363
     * @param int $userId
2364
     * @param int $groupId
2365
     *
2366
     * @return string
2367
     */
2368
    public function getUserRoleToString($userId, $groupId)
2369
    {
2370
        $role = $this->get_user_group_role($userId, $groupId);
2371
        $roleToString = '';
2372
2373
        switch ($role) {
2374
            case GROUP_USER_PERMISSION_ADMIN:
2375
                $roleToString = get_lang('Admin');
2376
                break;
2377
            case GROUP_USER_PERMISSION_READER:
2378
                $roleToString = get_lang('Reader');
2379
                break;
2380
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
2381
                $roleToString = get_lang('PendingInvitation');
2382
                break;
2383
            case GROUP_USER_PERMISSION_MODERATOR:
2384
                $roleToString = get_lang('Moderator');
2385
                break;
2386
            case GROUP_USER_PERMISSION_HRM:
2387
                $roleToString = get_lang('Drh');
2388
                break;
2389
        }
2390
2391
        return $roleToString;
2392
    }
2393
2394
    /**
2395
     * Add a group of users into a group of URLs.
2396
     *
2397
     * @author Julio Montoya
2398
     *
2399
     * @param array $user_list
2400
     * @param array $group_list
2401
     * @param int   $relation_type
2402
     *
2403
     * @return array
2404
     */
2405
    public function add_users_to_groups($user_list, $group_list, $relation_type = GROUP_USER_PERMISSION_READER)
2406
    {
2407
        $table_url_rel_group = $this->usergroup_rel_user_table;
2408
        $result_array = [];
2409
        $relation_type = (int) $relation_type;
2410
2411
        if (is_array($user_list) && is_array($group_list)) {
2412
            foreach ($group_list as $group_id) {
2413
                $usersList = '';
2414
                foreach ($user_list as $user_id) {
2415
                    $user_id = (int) $user_id;
2416
                    $group_id = (int) $group_id;
2417
2418
                    $role = $this->get_user_group_role($user_id, $group_id);
2419
                    if ($role == 0) {
2420
                        $sql = "INSERT INTO $table_url_rel_group
2421
		               			SET
2422
		               			    user_id = $user_id ,
2423
		               			    usergroup_id = $group_id ,
2424
		               			    relation_type = $relation_type ";
2425
2426
                        $result = Database::query($sql);
2427
                        if ($result) {
2428
                            $result_array[$group_id][$user_id] = 1;
2429
                        } else {
2430
                            $result_array[$group_id][$user_id] = 0;
2431
                        }
2432
                    }
2433
                    $usersList .= $user_id.',';
2434
                }
2435
                // Add event to system log
2436
                Event::addEvent(
2437
                    LOG_GROUP_PORTAL_USER_SUBSCRIBED,
2438
                    LOG_GROUP_PORTAL_ID,
2439
                    'gid: '.$group_id.' - uids: '.substr($usersList, 0, -1),
2440
                    api_get_utc_datetime(),
2441
                    api_get_user_id()
2442
                );
2443
            }
2444
        }
2445
2446
        return $result_array;
2447
    }
2448
2449
    /**
2450
     * Deletes the subscription of a user to a usergroup.
2451
     *
2452
     * @author Julio Montoya
2453
     *
2454
     * @param int $userId
2455
     * @param int $groupId
2456
     *
2457
     * @return bool true on success
2458
     * */
2459
    public function delete_user_rel_group($userId, $groupId)
2460
    {
2461
        $userId = (int) $userId;
2462
        $groupId = (int) $groupId;
2463
        if (empty($userId) || empty($groupId)) {
2464
            return false;
2465
        }
2466
2467
        $table = $this->usergroup_rel_user_table;
2468
        $sql = "DELETE FROM $table
2469
                WHERE
2470
                    user_id = $userId AND
2471
                    usergroup_id = $groupId";
2472
2473
        $result = Database::query($sql);
2474
        // Add event to system log
2475
        Event::addEvent(
2476
            LOG_GROUP_PORTAL_USER_UNSUBSCRIBED,
2477
            LOG_GROUP_PORTAL_ID,
2478
            'gid: '.$groupId.' - uid: '.$userId,
2479
            api_get_utc_datetime(),
2480
            api_get_user_id()
2481
        );
2482
2483
        return $result;
2484
    }
2485
2486
    /**
2487
     * Add a user into a group.
2488
     *
2489
     * @author Julio Montoya
2490
     *
2491
     * @param int $user_id
2492
     * @param int $group_id
2493
     * @param int $relation_type
2494
     *
2495
     * @return bool true if success
2496
     */
2497
    public function add_user_to_group($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
2498
    {
2499
        $table_url_rel_group = $this->usergroup_rel_user_table;
2500
        $user_id = (int) $user_id;
2501
        $group_id = (int) $group_id;
2502
        $relation_type = (int) $relation_type;
2503
        // Temporary hack to avoid issues with roles - see #4980
2504
        if ($relation_type == GROUP_USER_PERMISSION_READER) {
2505
            $relation_type = 0;
2506
        }
2507
        if (!empty($user_id) && !empty($group_id)) {
2508
            $role = $this->get_user_group_role($user_id, $group_id);
2509
2510
            if ($role == 0) {
2511
                $sql = "INSERT INTO $table_url_rel_group
2512
           				SET
2513
           				    user_id = ".$user_id.",
2514
           				    usergroup_id = ".$group_id.",
2515
           				    relation_type = ".$relation_type;
2516
                Database::query($sql);
2517
                // Add event to system log
2518
                Event::addEvent(
2519
                    LOG_GROUP_PORTAL_USER_SUBSCRIBED,
2520
                    LOG_GROUP_PORTAL_ID,
2521
                    'gid: '.$group_id.' - uid: '.$user_id,
2522
                    api_get_utc_datetime(),
2523
                    api_get_user_id()
2524
                );
2525
            } elseif ($role == GROUP_USER_PERMISSION_PENDING_INVITATION) {
2526
                //if somebody already invited me I can be added
2527
                self::update_user_role($user_id, $group_id, GROUP_USER_PERMISSION_READER);
2528
            }
2529
        }
2530
2531
        return true;
2532
    }
2533
2534
    /**
2535
     * Updates the group_rel_user table  with a given user and group ids.
2536
     *
2537
     * @author Julio Montoya
2538
     *
2539
     * @param int $user_id
2540
     * @param int $group_id
2541
     * @param int $relation_type
2542
     */
2543
    public function update_user_role($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
2544
    {
2545
        $table_group_rel_user = $this->usergroup_rel_user_table;
2546
        $group_id = (int) $group_id;
2547
        $user_id = (int) $user_id;
2548
        $relation_type = (int) $relation_type;
2549
2550
        $sql = "UPDATE $table_group_rel_user
2551
   				SET relation_type = $relation_type
2552
                WHERE user_id = $user_id AND usergroup_id = $group_id";
2553
        Database::query($sql);
2554
    }
2555
2556
    /**
2557
     * Gets the inner join from users and group table.
2558
     *
2559
     * @return array Database::store_result of the result
2560
     *
2561
     * @author Julio Montoya
2562
     * */
2563
    public function get_groups_by_user($user_id, $relationType = GROUP_USER_PERMISSION_READER, $with_image = false)
2564
    {
2565
        $table_group_rel_user = $this->usergroup_rel_user_table;
2566
        $tbl_group = $this->table;
2567
        $user_id = (int) $user_id;
2568
2569
        if ($relationType == 0) {
2570
            $relationCondition = '';
2571
        } else {
2572
            if (is_array($relationType)) {
2573
                $relationType = array_map('intval', $relationType);
2574
                $relationType = implode("','", $relationType);
2575
                $relationCondition = " AND ( gu.relation_type IN ('$relationType')) ";
2576
            } else {
2577
                $relationType = (int) $relationType;
2578
                $relationCondition = " AND gu.relation_type = $relationType ";
2579
            }
2580
        }
2581
2582
        $sql = 'SELECT
2583
                    g.picture,
2584
                    g.name,
2585
                    g.description,
2586
                    g.id ,
2587
                    gu.relation_type';
2588
2589
        $urlCondition = '';
2590
        if ($this->getUseMultipleUrl()) {
2591
            $sql .= " FROM $tbl_group g
2592
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2593
                    ON (g.id = a.usergroup_id)
2594
                    INNER JOIN $table_group_rel_user gu
2595
                    ON gu.usergroup_id = g.id";
2596
            $urlId = api_get_current_access_url_id();
2597
            $urlCondition = " AND access_url_id = $urlId ";
2598
        } else {
2599
            $sql .= " FROM $tbl_group g
2600
                    INNER JOIN $table_group_rel_user gu
2601
                    ON gu.usergroup_id = g.id";
2602
        }
2603
2604
        $sql .= " WHERE
2605
				    g.group_type = ".self::SOCIAL_CLASS." AND
2606
                    gu.user_id = $user_id
2607
                    $relationCondition
2608
                    $urlCondition
2609
                ORDER BY created_at DESC ";
2610
        $result = Database::query($sql);
2611
        $array = [];
2612
        if (Database::num_rows($result) > 0) {
2613
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2614
                if ($with_image) {
2615
                    $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2616
                    $img = '<img src="'.$picture['file'].'" />';
2617
                    $row['picture'] = $img;
2618
                }
2619
                $array[$row['id']] = $row;
2620
            }
2621
        }
2622
2623
        return $array;
2624
    }
2625
2626
    /**
2627
     * Gets the inner join of users and group table.
2628
     *
2629
     * @param int  quantity of records
2630
     * @param bool show groups with image or not
2631
     *
2632
     * @return array with group content
2633
     *
2634
     * @author Julio Montoya
2635
     * */
2636
    public function get_groups_by_popularity($num = 6, $with_image = true)
2637
    {
2638
        $table_group_rel_user = $this->usergroup_rel_user_table;
2639
        $tbl_group = $this->table;
2640
        if (empty($num)) {
2641
            $num = 6;
2642
        } else {
2643
            $num = (int) $num;
2644
        }
2645
        // only show admins and readers
2646
        $whereCondition = " WHERE
2647
                              g.group_type = ".self::SOCIAL_CLASS." AND
2648
                              gu.relation_type IN
2649
                              ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
2650
2651
        $sql = 'SELECT DISTINCT count(user_id) as count, g.picture, g.name, g.description, g.id ';
2652
2653
        $urlCondition = '';
2654
        if ($this->getUseMultipleUrl()) {
2655
            $sql .= " FROM $tbl_group g
2656
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2657
                    ON (g.id = a.usergroup_id)
2658
                    INNER JOIN $table_group_rel_user gu
2659
                    ON gu.usergroup_id = g.id";
2660
            $urlId = api_get_current_access_url_id();
2661
            $urlCondition = " AND access_url_id = $urlId ";
2662
        } else {
2663
            $sql .= " FROM $tbl_group g
2664
                    INNER JOIN $table_group_rel_user gu
2665
                    ON gu.usergroup_id = g.id";
2666
        }
2667
2668
        $sql .= "
2669
				$whereCondition
2670
				$urlCondition
2671
				GROUP BY g.id
2672
				ORDER BY count DESC
2673
				LIMIT $num";
2674
2675
        $result = Database::query($sql);
2676
        $array = [];
2677
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2678
            if ($with_image) {
2679
                $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2680
                $img = '<img src="'.$picture['file'].'" />';
2681
                $row['picture'] = $img;
2682
            }
2683
            if (empty($row['id'])) {
2684
                continue;
2685
            }
2686
            $array[$row['id']] = $row;
2687
        }
2688
2689
        return $array;
2690
    }
2691
2692
    /**
2693
     * Gets the last groups created.
2694
     *
2695
     * @param int  $num       quantity of records
2696
     * @param bool $withImage show groups with image or not
2697
     *
2698
     * @return array with group content
2699
     *
2700
     * @author Julio Montoya
2701
     * */
2702
    public function get_groups_by_age($num = 6, $withImage = true)
2703
    {
2704
        $table_group_rel_user = $this->usergroup_rel_user_table;
2705
        $tbl_group = $this->table;
2706
2707
        if (empty($num)) {
2708
            $num = 6;
2709
        } else {
2710
            $num = (int) $num;
2711
        }
2712
2713
        $where = " WHERE
2714
                        g.group_type = ".self::SOCIAL_CLASS." AND
2715
                        gu.relation_type IN
2716
                        ('".GROUP_USER_PERMISSION_ADMIN."' ,
2717
                        '".GROUP_USER_PERMISSION_READER."',
2718
                        '".GROUP_USER_PERMISSION_MODERATOR."',
2719
                        '".GROUP_USER_PERMISSION_HRM."')
2720
                    ";
2721
        $sql = 'SELECT DISTINCT
2722
                  count(user_id) as count,
2723
                  g.picture,
2724
                  g.name,
2725
                  g.description,
2726
                  g.id ';
2727
2728
        $urlCondition = '';
2729
        if ($this->getUseMultipleUrl()) {
2730
            $sql .= " FROM $tbl_group g
2731
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2732
                    ON (g.id = a.usergroup_id)
2733
                    INNER JOIN $table_group_rel_user gu
2734
                    ON gu.usergroup_id = g.id";
2735
            $urlId = api_get_current_access_url_id();
2736
            $urlCondition = " AND access_url_id = $urlId ";
2737
        } else {
2738
            $sql .= " FROM $tbl_group g
2739
                    INNER JOIN $table_group_rel_user gu
2740
                    ON gu.usergroup_id = g.id";
2741
        }
2742
        $sql .= "
2743
                $where
2744
                $urlCondition
2745
                GROUP BY g.id
2746
                ORDER BY created_at DESC
2747
                LIMIT $num ";
2748
2749
        $result = Database::query($sql);
2750
        $array = [];
2751
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2752
            if ($withImage) {
2753
                $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2754
                $img = '<img src="'.$picture['file'].'" />';
2755
                $row['picture'] = $img;
2756
            }
2757
            if (empty($row['id'])) {
2758
                continue;
2759
            }
2760
            $array[$row['id']] = $row;
2761
        }
2762
2763
        return $array;
2764
    }
2765
2766
    /**
2767
     * Gets the group's members.
2768
     *
2769
     * @param int group id
2770
     * @param bool show image or not of the group
2771
     * @param array list of relation type use constants
2772
     * @param int from value
2773
     * @param int limit
2774
     * @param array image configuration, i.e array('height'=>'20px', 'size'=> '20px')
2775
     *
2776
     * @return array list of users in a group
2777
     */
2778
    public function get_users_by_group(
2779
        $group_id,
2780
        $withImage = false,
2781
        $relation_type = [],
2782
        $from = null,
2783
        $limit = null
2784
    ) {
2785
        $table_group_rel_user = $this->usergroup_rel_user_table;
2786
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2787
        $group_id = (int) $group_id;
2788
2789
        if (empty($group_id)) {
2790
            return [];
2791
        }
2792
2793
        $limit_text = '';
2794
        if (isset($from) && isset($limit)) {
2795
            $from = (int) $from;
2796
            $limit = (int) $limit;
2797
            $limit_text = "LIMIT $from, $limit";
2798
        }
2799
2800
        if (count($relation_type) == 0) {
2801
            $where_relation_condition = '';
2802
        } else {
2803
            $new_relation_type = [];
2804
            foreach ($relation_type as $rel) {
2805
                $rel = (int) $rel;
2806
                $new_relation_type[] = "'$rel'";
2807
            }
2808
            $relation_type = implode(',', $new_relation_type);
2809
            if (!empty($relation_type)) {
2810
                $where_relation_condition = "AND gu.relation_type IN ($relation_type) ";
2811
            }
2812
        }
2813
2814
        $sql = "SELECT
2815
                    picture_uri as image,
2816
                    u.id,
2817
                    CONCAT (u.firstname,' ', u.lastname) as fullname,
2818
                    relation_type
2819
    		    FROM $tbl_user u
2820
    		    INNER JOIN $table_group_rel_user gu
2821
    			ON (gu.user_id = u.id)
2822
    			WHERE
2823
    			    gu.usergroup_id= $group_id
2824
    			    $where_relation_condition
2825
    			ORDER BY relation_type, firstname
2826
    			$limit_text";
2827
2828
        $result = Database::query($sql);
2829
        $array = [];
2830
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2831
            if ($withImage) {
2832
                $userInfo = api_get_user_info($row['id']);
2833
                $userPicture = UserManager::getUserPicture($row['id']);
2834
                $row['image'] = '<img src="'.$userPicture.'"  />';
2835
                $row['user_info'] = $userInfo;
2836
            }
2837
2838
            $row['user_id'] = $row['id'];
2839
            $array[$row['id']] = $row;
2840
        }
2841
2842
        return $array;
2843
    }
2844
2845
    /**
2846
     * Gets all the members of a group no matter the relationship for
2847
     * more specifications use get_users_by_group.
2848
     *
2849
     * @param int group id
2850
     *
2851
     * @return array
2852
     */
2853
    public function get_all_users_by_group($group_id)
2854
    {
2855
        $table_group_rel_user = $this->usergroup_rel_user_table;
2856
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2857
        $group_id = (int) $group_id;
2858
2859
        if (empty($group_id)) {
2860
            return [];
2861
        }
2862
2863
        $sql = "SELECT u.id, u.firstname, u.lastname, gu.relation_type
2864
                FROM $tbl_user u
2865
			    INNER JOIN $table_group_rel_user gu
2866
			    ON (gu.user_id = u.id)
2867
			    WHERE gu.usergroup_id= $group_id
2868
			    ORDER BY relation_type, firstname";
2869
2870
        $result = Database::query($sql);
2871
        $array = [];
2872
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2873
            $array[$row['id']] = $row;
2874
        }
2875
2876
        return $array;
2877
    }
2878
2879
    /**
2880
     * Shows the left column of the group page.
2881
     *
2882
     * @param int    $group_id
2883
     * @param int    $user_id
2884
     * @param string $show
2885
     *
2886
     * @return string
2887
     */
2888
    public function show_group_column_information($group_id, $user_id, $show = '')
2889
    {
2890
        $html = '';
2891
        $group_info = $this->get($group_id);
2892
2893
        //my relation with the group is set here
2894
        $my_group_role = $this->get_user_group_role($user_id, $group_id);
2895
2896
        // Loading group permission
2897
        $links = '';
2898
        switch ($my_group_role) {
2899
            case GROUP_USER_PERMISSION_READER:
2900
                // I'm just a reader
2901
                $relation_group_title = get_lang('IAmAReader');
2902
                $links .= '<li class="'.($show == 'invite_friends' ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
2903
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2904
                if (self::canLeave($group_info)) {
2905
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2906
                        Display::return_icon('group_leave.png', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2907
                }
2908
                break;
2909
            case GROUP_USER_PERMISSION_ADMIN:
2910
                $relation_group_title = get_lang('IAmAnAdmin');
2911
                $links .= '<li class="'.($show == 'group_edit' ? 'active' : '').'"><a href="group_edit.php?id='.$group_id.'">'.
2912
                            Display::return_icon('group_edit.png', get_lang('EditGroup')).get_lang('EditGroup').'</a></li>';
2913
                $links .= '<li class="'.($show == 'member_list' ? 'active' : '').'"><a href="group_waiting_list.php?id='.$group_id.'">'.
2914
                            Display::return_icon('waiting_list.png', get_lang('WaitingList')).get_lang('WaitingList').'</a></li>';
2915
                $links .= '<li class="'.($show == 'invite_friends' ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
2916
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2917
                if (self::canLeave($group_info)) {
2918
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2919
                        Display::return_icon('group_leave.png', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2920
                }
2921
                break;
2922
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
2923
//				$links .=  '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('YouHaveBeenInvitedJoinNow'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('YouHaveBeenInvitedJoinNow').'</span></a></li>';
2924
                break;
2925
            case GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER:
2926
                $relation_group_title = get_lang('WaitingForAdminResponse');
2927
                break;
2928
            case GROUP_USER_PERMISSION_MODERATOR:
2929
                $relation_group_title = get_lang('IAmAModerator');
2930
                //$links .=  '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="thickbox" title="'.get_lang('ComposeMessage').'">'.Display::return_icon('compose_message.png', get_lang('NewTopic'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('NewTopic').'</span></a></li>';
2931
                //$links .=  '<li><a href="groups.php?id='.$group_id.'">'.				Display::return_icon('message_list.png', get_lang('MessageList'), array('hspace'=>'6')).'<span class="'.($show=='messages_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('MessageList').'</span></a></li>';
2932
                //$links .=  '<li><a href="group_members.php?id='.$group_id.'">'.		Display::return_icon('member_list.png', get_lang('MemberList'), array('hspace'=>'6')).'<span class="'.($show=='member_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('MemberList').'</span></a></li>';
2933
                if ($group_info['visibility'] == GROUP_PERMISSION_CLOSED) {
2934
                    $links .= '<li><a href="group_waiting_list.php?id='.$group_id.'">'.
2935
                                Display::return_icon('waiting_list.png', get_lang('WaitingList')).get_lang('WaitingList').'</a></li>';
2936
                }
2937
                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
2938
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2939
                if (self::canLeave($group_info)) {
2940
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2941
                        Display::return_icon('group_leave.png', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2942
                }
2943
                break;
2944
            case GROUP_USER_PERMISSION_HRM:
2945
                $relation_group_title = get_lang('IAmAHRM');
2946
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="ajax" title="'.get_lang('ComposeMessage').'" data-size="lg" data-title="'.get_lang('ComposeMessage').'">'.
2947
                            Display::return_icon('new-message.png', get_lang('NewTopic')).get_lang('NewTopic').'</a></li>';
2948
                $links .= '<li><a href="group_view.php?id='.$group_id.'">'.
2949
                            Display::return_icon('message_list.png', get_lang('MessageList')).get_lang('MessageList').'</a></li>';
2950
                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
2951
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2952
                $links .= '<li><a href="group_members.php?id='.$group_id.'">'.
2953
                            Display::return_icon('member_list.png', get_lang('MemberList')).get_lang('MemberList').'</a></li>';
2954
                $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2955
                            Display::return_icon('delete_data.gif', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2956
                break;
2957
            default:
2958
                //$links .=  '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('JoinGroup'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('JoinGroup').'</a></span></li>';
2959
                break;
2960
        }
2961
        if (!empty($links)) {
2962
            $list = '<ul class="nav nav-pills">';
2963
            $list .= $links;
2964
            $list .= '</ul>';
2965
            $html .= Display::panelCollapse(
2966
                get_lang('SocialGroups'),
2967
                $list,
2968
                'sm-groups',
2969
                [],
2970
                'groups-acordeon',
2971
                'groups-collapse'
2972
            );
2973
        }
2974
2975
        return $html;
2976
    }
2977
2978
    /**
2979
     * @param int $group_id
2980
     * @param int $topic_id
2981
     */
2982
    public function delete_topic($group_id, $topic_id)
2983
    {
2984
        $table_message = Database::get_main_table(TABLE_MESSAGE);
2985
        $topic_id = (int) $topic_id;
2986
        $group_id = (int) $group_id;
2987
2988
        $sql = "UPDATE $table_message SET
2989
                    msg_status = 3
2990
                WHERE
2991
                    group_id = $group_id AND
2992
                    (id = '$topic_id' OR parent_id = $topic_id)
2993
                ";
2994
        Database::query($sql);
2995
    }
2996
2997
    /**
2998
     * @param string $user_id
2999
     * @param string $relation_type
3000
     * @param bool   $with_image
3001
     *
3002
     * @deprecated
3003
     *
3004
     * @return int
3005
     */
3006
    public function get_groups_by_user_count(
3007
        $user_id = '',
3008
        $relation_type = GROUP_USER_PERMISSION_READER,
3009
        $with_image = false
3010
    ) {
3011
        $table_group_rel_user = $this->usergroup_rel_user_table;
3012
        $tbl_group = $this->table;
3013
        $user_id = intval($user_id);
3014
3015
        if ($relation_type == 0) {
3016
            $where_relation_condition = '';
3017
        } else {
3018
            $relation_type = intval($relation_type);
3019
            $where_relation_condition = "AND gu.relation_type = $relation_type ";
3020
        }
3021
3022
        $sql = "SELECT count(g.id) as count
3023
				FROM $tbl_group g
3024
				INNER JOIN $table_group_rel_user gu
3025
				ON gu.usergroup_id = g.id
3026
				WHERE gu.user_id = $user_id $where_relation_condition ";
3027
3028
        $result = Database::query($sql);
3029
        if (Database::num_rows($result) > 0) {
3030
            $row = Database::fetch_array($result, 'ASSOC');
3031
3032
            return $row['count'];
3033
        }
3034
3035
        return 0;
3036
    }
3037
3038
    /**
3039
     * @param string $tag
3040
     * @param int    $from
3041
     * @param int    $number_of_items
3042
     *
3043
     * @return array
3044
     */
3045
    public function get_all_group_tags($tag = '', $from = 0, $number_of_items = 10, $getCount = false)
3046
    {
3047
        $group_table = $this->table;
3048
        $tag = Database::escape_string($tag);
3049
        $from = (int) $from;
3050
        $number_of_items = (int) $number_of_items;
3051
        $return = [];
3052
3053
        $keyword = $tag;
3054
        $sql = 'SELECT  g.id, g.name, g.description, g.url, g.picture ';
3055
        $urlCondition = '';
3056
        if ($this->getUseMultipleUrl()) {
3057
            $urlId = api_get_current_access_url_id();
3058
            $sql .= " FROM $this->table g
3059
                    INNER JOIN $this->access_url_rel_usergroup a
3060
                    ON (g.id = a.usergroup_id)";
3061
            $urlCondition = " AND access_url_id = $urlId ";
3062
        } else {
3063
            $sql .= " FROM $group_table g";
3064
        }
3065
        if (isset($keyword)) {
3066
            $sql .= " WHERE (
3067
                        g.name LIKE '%".$keyword."%' OR
3068
                        g.description LIKE '%".$keyword."%' OR
3069
                        g.url LIKE '%".$keyword."%'
3070
                     ) $urlCondition
3071
                     ";
3072
        } else {
3073
            $sql .= " WHERE 1 = 1 $urlCondition ";
3074
        }
3075
3076
        $direction = 'ASC';
3077
        if (!in_array($direction, ['ASC', 'DESC'])) {
3078
            $direction = 'ASC';
3079
        }
3080
3081
        $from = (int) $from;
3082
        $number_of_items = (int) $number_of_items;
3083
        $sql .= " LIMIT $from, $number_of_items";
3084
3085
        $res = Database::query($sql);
3086
        if (Database::num_rows($res) > 0) {
3087
            while ($row = Database::fetch_array($res, 'ASSOC')) {
3088
                if (!in_array($row['id'], $return)) {
3089
                    $return[$row['id']] = $row;
3090
                }
3091
            }
3092
        }
3093
3094
        return $return;
3095
    }
3096
3097
    /**
3098
     * @param int $group_id
3099
     *
3100
     * @return array
3101
     */
3102
    public static function get_parent_groups($group_id)
3103
    {
3104
        $t_rel_group = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
3105
        $group_id = (int) $group_id;
3106
3107
        $max_level = 10;
3108
        $select_part = 'SELECT ';
3109
        $cond_part = '';
3110
        for ($i = 1; $i <= $max_level; $i++) {
3111
            $rg_number = $i - 1;
3112
            if ($i == $max_level) {
3113
                $select_part .= "rg$rg_number.group_id as id_$rg_number ";
3114
            } else {
3115
                $select_part .= "rg$rg_number.group_id as id_$rg_number, ";
3116
            }
3117
            if ($i == 1) {
3118
                $cond_part .= "FROM $t_rel_group rg0
3119
                               LEFT JOIN $t_rel_group rg$i
3120
                               ON rg$rg_number.group_id = rg$i.subgroup_id ";
3121
            } else {
3122
                $cond_part .= " LEFT JOIN $t_rel_group rg$i
3123
                                ON rg$rg_number.group_id = rg$i.subgroup_id ";
3124
            }
3125
        }
3126
        $sql = $select_part.' '.$cond_part."WHERE rg0.subgroup_id='$group_id'";
3127
        $res = Database::query($sql);
3128
        $temp_arr = Database::fetch_array($res, 'NUM');
3129
        $toReturn = [];
3130
        if (is_array($temp_arr)) {
3131
            foreach ($temp_arr as $elt) {
3132
                if (isset($elt)) {
3133
                    $toReturn[] = $elt;
3134
                }
3135
            }
3136
        }
3137
3138
        return $toReturn;
3139
    }
3140
3141
    /**
3142
     * Get the group member list by a user and his group role.
3143
     *
3144
     * @param int  $userId                The user ID
3145
     * @param int  $relationType          Optional. The relation type. GROUP_USER_PERMISSION_ADMIN by default
3146
     * @param bool $includeSubgroupsUsers Optional. Whether include the users from subgroups
3147
     *
3148
     * @return array
3149
     */
3150
    public function getGroupUsersByUser(
3151
        $userId,
3152
        $relationType = GROUP_USER_PERMISSION_ADMIN,
3153
        $includeSubgroupsUsers = true
3154
    ) {
3155
        $userId = (int) $userId;
3156
        $groups = $this->get_groups_by_user($userId, $relationType);
3157
        $groupsId = array_keys($groups);
3158
        $subgroupsId = [];
3159
        $userIdList = [];
3160
3161
        if ($includeSubgroupsUsers) {
3162
            foreach ($groupsId as $groupId) {
3163
                $subgroupsId = array_merge($subgroupsId, self::getGroupsByDepthLevel($groupId));
3164
            }
3165
3166
            $groupsId = array_merge($groupsId, $subgroupsId);
3167
        }
3168
3169
        $groupsId = array_unique($groupsId);
3170
3171
        if (empty($groupsId)) {
3172
            return [];
3173
        }
3174
3175
        foreach ($groupsId as $groupId) {
3176
            $groupUsers = $this->get_users_by_group($groupId);
3177
3178
            if (empty($groupUsers)) {
3179
                continue;
3180
            }
3181
3182
            foreach ($groupUsers as $member) {
3183
                if ($member['user_id'] == $userId) {
3184
                    continue;
3185
                }
3186
3187
                $userIdList[] = (int) $member['user_id'];
3188
            }
3189
        }
3190
3191
        return array_unique($userIdList);
3192
    }
3193
3194
    /**
3195
     * Get the subgroups ID from a group.
3196
     * The default $levels value is 10 considering it as a extensive level of depth.
3197
     *
3198
     * @param int $groupId The parent group ID
3199
     * @param int $levels  The depth levels
3200
     *
3201
     * @return array The list of ID
3202
     */
3203
    public static function getGroupsByDepthLevel($groupId, $levels = 10)
3204
    {
3205
        $groups = [];
3206
        $groupId = (int) $groupId;
3207
3208
        $groupTable = Database::get_main_table(TABLE_USERGROUP);
3209
        $groupRelGroupTable = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
3210
3211
        $select = 'SELECT ';
3212
        $from = "FROM $groupTable g1 ";
3213
3214
        for ($i = 1; $i <= $levels; $i++) {
3215
            $tableIndexNumber = $i;
3216
            $tableIndexJoinNumber = $i - 1;
3217
            $select .= "g$i.id as id_$i ";
3218
            $select .= $i != $levels ? ', ' : null;
3219
3220
            if ($i == 1) {
3221
                $from .= " INNER JOIN $groupRelGroupTable gg0
3222
                           ON g1.id = gg0.subgroup_id and gg0.group_id = $groupId ";
3223
            } else {
3224
                $from .= "LEFT JOIN $groupRelGroupTable gg$tableIndexJoinNumber ";
3225
                $from .= " ON g$tableIndexJoinNumber.id = gg$tableIndexJoinNumber.group_id ";
3226
                $from .= "LEFT JOIN $groupTable g$tableIndexNumber ";
3227
                $from .= " ON gg$tableIndexJoinNumber.subgroup_id = g$tableIndexNumber.id ";
3228
            }
3229
        }
3230
3231
        $result = Database::query("$select $from");
3232
3233
        while ($item = Database::fetch_assoc($result)) {
3234
            foreach ($item as $myGroupId) {
3235
                if (!empty($myGroupId)) {
3236
                    $groups[] = $myGroupId;
3237
                }
3238
            }
3239
        }
3240
3241
        return array_map('intval', $groups);
3242
    }
3243
3244
    /**
3245
     * Set a parent group.
3246
     *
3247
     * @param int $group_id
3248
     * @param int $parent_group_id if 0, we delete the parent_group association
3249
     * @param int $relation_type
3250
     *
3251
     * @return \Doctrine\DBAL\Statement
3252
     */
3253
    public function setParentGroup($group_id, $parent_group_id, $relation_type = 1)
3254
    {
3255
        $table = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
3256
        $group_id = (int) $group_id;
3257
        $parent_group_id = (int) $parent_group_id;
3258
        if ($parent_group_id == 0) {
3259
            $sql = "DELETE FROM $table WHERE subgroup_id = $group_id";
3260
        } else {
3261
            $sql = "SELECT group_id FROM $table WHERE subgroup_id = $group_id";
3262
            $res = Database::query($sql);
3263
            if (Database::num_rows($res) == 0) {
3264
                $sql = "INSERT INTO $table SET
3265
                        group_id = $parent_group_id,
3266
                        subgroup_id = $group_id,
3267
                        relation_type = $relation_type";
3268
            } else {
3269
                $sql = "UPDATE $table SET
3270
                        group_id = $parent_group_id,
3271
                        relation_type = $relation_type
3272
                        WHERE subgroup_id = $group_id";
3273
            }
3274
        }
3275
        $res = Database::query($sql);
3276
3277
        return $res;
3278
    }
3279
3280
    /**
3281
     * Filter the groups/classes info to get a name list only.
3282
     *
3283
     * @param int $userId       The user ID
3284
     * @param int $filterByType Optional. The type of group
3285
     *
3286
     * @return array
3287
     */
3288
    public function getNameListByUser($userId, $filterByType = null)
3289
    {
3290
        $userClasses = $this->getUserGroupListByUser($userId, $filterByType);
3291
3292
        return array_column($userClasses, 'name');
3293
    }
3294
3295
    /**
3296
     * Get the HTML necessary for display the groups/classes name list.
3297
     *
3298
     * @param int $userId       The user ID
3299
     * @param int $filterByType Optional. The type of group
3300
     *
3301
     * @return string
3302
     */
3303
    public function getLabelsFromNameList($userId, $filterByType = null)
3304
    {
3305
        $groupsNameListParsed = $this->getNameListByUser($userId, $filterByType);
3306
3307
        if (empty($groupsNameListParsed)) {
3308
            return '';
3309
        }
3310
3311
        $nameList = '<ul class="list-unstyled">';
3312
        foreach ($groupsNameListParsed as $name) {
3313
            $nameList .= '<li>'.Display::span($name, ['class' => 'label label-info']).'</li>';
3314
        }
3315
3316
        $nameList .= '</ul>';
3317
3318
        return $nameList;
3319
    }
3320
3321
    /**
3322
     * @param array $groupInfo
3323
     *
3324
     * @return bool
3325
     */
3326
    public static function canLeave($groupInfo)
3327
    {
3328
        return $groupInfo['allow_members_leave_group'] == 1 ? true : false;
3329
    }
3330
3331
    /**
3332
     * Check permissions and blocks the page.
3333
     *
3334
     * @param array $userGroupInfo
3335
     * @param bool  $checkAuthor
3336
     * @param bool  $checkCourseIsAllow
3337
     */
3338
    public function protectScript($userGroupInfo = [], $checkAuthor = true, $checkCourseIsAllow = false)
3339
    {
3340
        api_block_anonymous_users();
3341
3342
        if (api_is_platform_admin()) {
3343
            return true;
3344
        }
3345
3346
        if ($checkCourseIsAllow) {
3347
            if (api_is_allowed_to_edit()) {
3348
                return true;
3349
            }
3350
        }
3351
3352
        if ($this->allowTeachers() && api_is_teacher()) {
3353
            if ($checkAuthor && !empty($userGroupInfo)) {
3354
                if (isset($userGroupInfo['author_id']) && $userGroupInfo['author_id'] != api_get_user_id()) {
3355
                    api_not_allowed(true);
3356
                }
3357
            }
3358
3359
            return true;
3360
        } else {
3361
            api_protect_admin_script(true);
3362
            api_protect_limit_for_session_admin();
3363
        }
3364
    }
3365
3366
    public function getGroupsByLp($lpId, $courseId, $sessionId)
3367
    {
3368
        $lpId = (int) $lpId;
3369
        $courseId = (int) $courseId;
3370
        $sessionId = (int) $sessionId;
3371
        $sessionCondition = api_get_session_condition($sessionId, true);
3372
        $table = Database::get_course_table(TABLE_LP_REL_USERGROUP);
3373
        $sql = "SELECT usergroup_id FROM $table
3374
                WHERE
3375
                    c_id = $courseId AND
3376
                    lp_id = $lpId
3377
                    $sessionCondition
3378
                    ";
3379
        $result = Database::query($sql);
3380
3381
        return Database::store_result($result, 'ASSOC');
3382
    }
3383
3384
    public function getGroupsByLpCategory($categoryId, $courseId, $sessionId)
3385
    {
3386
        $categoryId = (int) $categoryId;
3387
        $courseId = (int) $courseId;
3388
        $sessionId = (int) $sessionId;
3389
        $sessionCondition = api_get_session_condition($sessionId, true);
3390
3391
        $table = Database::get_course_table(TABLE_LP_CATEGORY_REL_USERGROUP);
3392
        $sql = "SELECT usergroup_id FROM $table
3393
                WHERE
3394
                    c_id = $courseId AND
3395
                    lp_category_id = $categoryId
3396
                    $sessionCondition
3397
                ";
3398
        $result = Database::query($sql);
3399
3400
        return Database::store_result($result, 'ASSOC');
3401
    }
3402
3403
    /**
3404
     * Check the given ID matches an existing group.
3405
     *
3406
     * @return bool
3407
     */
3408
    public function groupExists(int $groupId)
3409
    {
3410
        $sql = "SELECT id FROM ".$this->table." WHERE id = ".$groupId;
3411
        $result = Database::query($sql);
3412
        if (Database::num_rows($result) === 1) {
3413
            return true;
3414
        }
3415
3416
        return false;
3417
    }
3418
3419
    /**
3420
     * Check the given ID matches an existing user.
3421
     *
3422
     * @return bool
3423
     */
3424
    public function userExists(int $userId)
3425
    {
3426
        $sql = "SELECT id FROM ".$this->table_user." WHERE id = ".$userId;
3427
        $result = Database::query($sql);
3428
        if (Database::num_rows($result) === 1) {
3429
            return true;
3430
        }
3431
3432
        return false;
3433
    }
3434
}
3435