Passed
Push — 1.11.x ( 03e8c2...2a4008 )
by Yannick
13:02 queued 15s
created

UserGroup::getUserGroupNotInCourse()   F

Complexity

Conditions 15
Paths 514

Size

Total Lines 97
Code Lines 58

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 15
eloc 58
nc 514
nop 3
dl 0
loc 97
rs 2.425
c 0
b 0
f 0

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
        return $sessions;
1011
    }
1012
1013
    /**
1014
     * Subscribes courses to a group (also adding the members of the group in the course).
1015
     *
1016
     * @param int   $usergroup_id  usergroup id
1017
     * @param array $list          list of course ids (integers)
1018
     * @param bool  $delete_groups
1019
     */
1020
    public function subscribe_courses_to_usergroup($usergroup_id, $list, $delete_groups = true)
1021
    {
1022
        $current_list = $this->get_courses_by_usergroup($usergroup_id);
1023
        $user_list = $this->get_users_by_usergroup($usergroup_id);
1024
1025
        $delete_items = $new_items = [];
1026
        if (!empty($list)) {
1027
            foreach ($list as $id) {
1028
                if (!in_array($id, $current_list)) {
1029
                    $new_items[] = $id;
1030
                }
1031
            }
1032
        }
1033
1034
        if (!empty($current_list)) {
1035
            foreach ($current_list as $id) {
1036
                if (!in_array($id, $list)) {
1037
                    $delete_items[] = $id;
1038
                }
1039
            }
1040
        }
1041
1042
        if ($delete_groups) {
1043
            $this->unsubscribe_courses_from_usergroup($usergroup_id, $delete_items);
1044
        }
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
     * @param int   $usergroup_id
1129
     * @param array $delete_items
1130
     */
1131
    public function unsubscribe_courses_from_usergroup($usergroup_id, $delete_items)
1132
    {
1133
        $courses = [];
1134
        // Deleting items.
1135
        if (!empty($delete_items)) {
1136
            $user_list = $this->get_users_by_usergroup($usergroup_id);
1137
            foreach ($delete_items as $course_id) {
1138
                $course_info = api_get_course_info_by_id($course_id);
1139
                if ($course_info) {
1140
                    if (!api_get_configuration_value('usergroup_do_not_unsubscribe_users_from_course_on_course_unsubscribe')) {
1141
                        if (!empty($user_list)) {
1142
                            foreach ($user_list as $user_id) {
1143
                                CourseManager::unsubscribe_user(
1144
                                    $user_id,
1145
                                    $course_info['code']
1146
                                );
1147
                            }
1148
                        }
1149
                    }
1150
                    Database::delete(
1151
                        $this->usergroup_rel_course_table,
1152
                        [
1153
                            'usergroup_id = ? AND course_id = ?' => [
1154
                                $usergroup_id,
1155
                                $course_id,
1156
                            ],
1157
                        ]
1158
                    );
1159
                    $courses[] = $course_id;
1160
                }
1161
            }
1162
            // Add event to system log
1163
            Event::addEvent(
1164
                LOG_GROUP_PORTAL_COURSE_UNSUBSCRIBED,
1165
                LOG_GROUP_PORTAL_ID,
1166
                'gid: '.$usergroup_id.' - cids: '.implode(',', $courses),
1167
                api_get_utc_datetime(),
1168
                api_get_user_id()
1169
            );
1170
        }
1171
1172
        return $courses;
1173
    }
1174
1175
    /**
1176
     * Unsubscribe a usergroup from a list of sessions
1177
     * @param int   $groupId
1178
     * @param array $items Session IDs to remove from the group
1179
     * @return array The list of session IDs that have been unsubscribed from the group
1180
     */
1181
    public function unsubscribeSessionsFromUserGroup($groupId, $items)
1182
    {
1183
        // Deleting items.
1184
        $sessions = [];
1185
        if (!empty($items)) {
1186
            $users = $this->get_users_by_usergroup($groupId);
1187
            foreach ($items as $sessionId) {
1188
                if (SessionManager::isValidId($sessionId)) {
1189
                    if (!api_get_configuration_value('usergroup_do_not_unsubscribe_users_from_session_on_session_unsubscribe')) {
1190
                        if (!empty($users)) {
1191
                            foreach ($users as $userId) {
1192
                                SessionManager::unsubscribe_user_from_session(
1193
                                    $sessionId,
1194
                                    $userId
1195
                                );
1196
                            }
1197
                        }
1198
                    }
1199
                    Database::delete(
1200
                        $this->usergroup_rel_session_table,
1201
                        [
1202
                            'usergroup_id = ? AND session_id = ?' => [
1203
                                $groupId,
1204
                                $sessionId,
1205
                            ],
1206
                        ]
1207
                    );
1208
                    $sessions[] = $sessionId;
1209
                }
1210
            }
1211
            // Add event to system log
1212
            Event::addEvent(
1213
                LOG_GROUP_PORTAL_SESSION_UNSUBSCRIBED,
1214
                LOG_GROUP_PORTAL_ID,
1215
                'gid: '.$groupId.' - sids: '.implode(',', $sessions),
1216
                api_get_utc_datetime(),
1217
                api_get_user_id()
1218
            );
1219
        }
1220
1221
        return $sessions;
1222
    }
1223
1224
    /**
1225
     * Subscribe users to a group.
1226
     *
1227
     * @param int   $usergroup_id                     usergroup id
1228
     * @param array $list                             list of user ids
1229
     * @param bool  $delete_users_not_present_in_list
1230
     * @param int   $relationType
1231
     */
1232
    public function subscribe_users_to_usergroup(
1233
        $usergroup_id,
1234
        $list,
1235
        $delete_users_not_present_in_list = true,
1236
        $relationType = 0
1237
    ) {
1238
        $current_list = $this->get_users_by_usergroup($usergroup_id);
1239
        $course_list = $this->get_courses_by_usergroup($usergroup_id);
1240
        $session_list = $this->get_sessions_by_usergroup($usergroup_id);
1241
        $session_list = array_filter($session_list);
1242
        $relationType = (int) $relationType;
1243
1244
        $delete_items = [];
1245
        $new_items = [];
1246
        if (!empty($list)) {
1247
            foreach ($list as $user_id) {
1248
                if (!in_array($user_id, $current_list)) {
1249
                    $new_items[] = $user_id;
1250
                }
1251
            }
1252
        }
1253
1254
        if (!empty($current_list)) {
1255
            foreach ($current_list as $user_id) {
1256
                if (!in_array($user_id, $list)) {
1257
                    $delete_items[] = $user_id;
1258
                }
1259
            }
1260
        }
1261
1262
        // Deleting items
1263
        if (!empty($delete_items) && $delete_users_not_present_in_list) {
1264
            foreach ($delete_items as $user_id) {
1265
                if (!api_get_configuration_value('usergroup_do_not_unsubscribe_users_from_course_nor_session_on_user_unsubscribe')) {
1266
                    // Removing courses
1267
                    if (!empty($course_list)) {
1268
                        foreach ($course_list as $course_id) {
1269
                            $course_info = api_get_course_info_by_id($course_id);
1270
                            CourseManager::unsubscribe_user($user_id, $course_info['code']);
1271
                        }
1272
                    }
1273
                    // Removing sessions
1274
                    if (!empty($session_list)) {
1275
                        foreach ($session_list as $session_id) {
1276
                            SessionManager::unsubscribe_user_from_session($session_id, $user_id);
1277
                        }
1278
                    }
1279
                }
1280
1281
                if (empty($relationType)) {
1282
                    Database::delete(
1283
                        $this->usergroup_rel_user_table,
1284
                        [
1285
                            'usergroup_id = ? AND user_id = ? AND (relation_type = "0" OR relation_type IS NULL OR relation_type = "")' => [
1286
                                $usergroup_id,
1287
                                $user_id,
1288
                            ],
1289
                        ]
1290
                    );
1291
                } else {
1292
                    Database::delete(
1293
                        $this->usergroup_rel_user_table,
1294
                        [
1295
                            'usergroup_id = ? AND user_id = ? AND relation_type = ?' => [
1296
                                $usergroup_id,
1297
                                $user_id,
1298
                                $relationType,
1299
                            ],
1300
                        ]
1301
                    );
1302
                }
1303
                // Add event to system log
1304
                Event::addEvent(
1305
                    LOG_GROUP_PORTAL_USER_UNSUBSCRIBED,
1306
                    LOG_GROUP_PORTAL_ID,
1307
                    'gid: '.$usergroup_id.' - uid: '.$user_id,
1308
                    api_get_utc_datetime(),
1309
                    api_get_user_id()
1310
                );
1311
            }
1312
        }
1313
1314
        // Adding new relationships
1315
        if (!empty($new_items)) {
1316
            // Adding sessions
1317
            if (!empty($session_list)) {
1318
                foreach ($session_list as $session_id) {
1319
                    SessionManager::subscribeUsersToSession($session_id, $new_items, null, false);
1320
                }
1321
            }
1322
1323
            foreach ($new_items as $user_id) {
1324
                // Adding courses
1325
                if (!empty($course_list)) {
1326
                    $messageError = [];
1327
                    $messageOk = [];
1328
                    foreach ($course_list as $course_id) {
1329
                        $course_info = api_get_course_info_by_id($course_id);
1330
                        $subscribed = CourseManager::subscribeUser(
1331
                            $user_id,
1332
                            $course_info['code'],
1333
                            STUDENT,
1334
                            0,
1335
                            0,
1336
                            true,
1337
                            false
1338
                        );
1339
                        $userInfo = api_get_user_info($user_id);
1340
                        if (!$subscribed) {
1341
                            $messageError[] = sprintf(
1342
                                get_lang('UserXNotSubscribedToCourseX'),
1343
                                $userInfo['complete_name_with_username'],
1344
                                $course_info['title']
1345
                            );
1346
                        } else {
1347
                            $messageOk[] = sprintf(
1348
                                get_lang('UserXAddedToCourseX'),
1349
                                $userInfo['complete_name_with_username'],
1350
                                $course_info['title']
1351
                            );
1352
                        }
1353
                    }
1354
                    if (!empty($messageError)) {
1355
                        $strMessagesError = implode('<br>', $messageError);
1356
                        Display::addFlash(
1357
                            Display::return_message(
1358
                                $strMessagesError,
1359
                                'error',
1360
                                false
1361
                            )
1362
                        );
1363
                    }
1364
                    if (!empty($messageOk)) {
1365
                        $strMessagesOk = implode('<br>', $messageOk);
1366
                        Display::addFlash(
1367
                            Display::return_message(
1368
                                $strMessagesOk,
1369
                                'normal',
1370
                                false
1371
                            )
1372
                        );
1373
                    }
1374
                }
1375
                $params = [
1376
                    'user_id' => $user_id,
1377
                    'usergroup_id' => $usergroup_id,
1378
                    'relation_type' => $relationType,
1379
                ];
1380
                Database::insert($this->usergroup_rel_user_table, $params);
1381
                // Add event to system log
1382
                Event::addEvent(
1383
                    LOG_GROUP_PORTAL_USER_SUBSCRIBED,
1384
                    LOG_GROUP_PORTAL_ID,
1385
                    'gid: '.$usergroup_id.' - uid: '.$user_id,
1386
                    api_get_utc_datetime(),
1387
                    api_get_user_id()
1388
                );
1389
            }
1390
        }
1391
    }
1392
1393
    /**
1394
     * @param string $name
1395
     *
1396
     * @return bool
1397
     */
1398
    public function usergroup_exists($name)
1399
    {
1400
        $name = Database::escape_string($name);
1401
        if ($this->getUseMultipleUrl()) {
1402
            $urlId = api_get_current_access_url_id();
1403
            $sql = "SELECT * FROM $this->table u
1404
                    INNER JOIN {$this->access_url_rel_usergroup} a
1405
                    ON (a.usergroup_id = u.id)
1406
                    WHERE name = '".$name."' AND access_url_id = $urlId";
1407
        } else {
1408
            $sql = "SELECT * FROM $this->table WHERE name = '".$name."'";
1409
        }
1410
1411
        $res = Database::query($sql);
1412
1413
        return 0 != Database::num_rows($res);
1414
    }
1415
1416
    /**
1417
     * Returns whether teachers can access the classes, as per 'allow_teachers_to_classes' setting
1418
     *
1419
     * @return bool
1420
     */
1421
    public function allowTeachers()
1422
    {
1423
        return true === api_get_configuration_value('allow_teachers_to_classes');
1424
    }
1425
1426
    /**
1427
     * @param int    $sidx
1428
     * @param int    $sord
1429
     * @param int    $start
1430
     * @param int    $limit
1431
     * @param string $extraWhereCondition
1432
     *
1433
     * @return array
1434
     */
1435
    public function getUsergroupsPagination($sidx, $sord, $start, $limit, $extraWhereCondition = '')
1436
    {
1437
        $sord = in_array(strtolower($sord), ['asc', 'desc']) ? $sord : 'desc';
1438
1439
        $start = (int) $start;
1440
        $limit = (int) $limit;
1441
1442
        $sqlFrom = "{$this->table} u ";
1443
        $sqlWhere = '1 = 1 ';
1444
1445
        if ($this->getUseMultipleUrl()) {
1446
            $urlId = api_get_current_access_url_id();
1447
            $sqlFrom .= " INNER JOIN {$this->access_url_rel_usergroup} a ON (u.id = a.usergroup_id) ";
1448
            $sqlWhere .= " AND a.access_url_id = $urlId ";
1449
        }
1450
1451
        if ($this->allowTeachers()) {
1452
            if (!api_is_platform_admin()) {
1453
                $userId = api_get_user_id();
1454
                $sqlWhere .= " AND author_id = $userId ";
1455
            }
1456
        }
1457
1458
        if ($extraWhereCondition) {
1459
            $sqlWhere .= " AND $extraWhereCondition ";
1460
        }
1461
1462
        $result = Database::store_result(
1463
            Database::query("SELECT u.* FROM $sqlFrom WHERE $sqlWhere ORDER BY name $sord LIMIT $start, $limit")
1464
        );
1465
1466
        $new_result = [];
1467
        if (!empty($result)) {
1468
            foreach ($result as $group) {
1469
                $group['sessions'] = count($this->get_sessions_by_usergroup($group['id']));
1470
                $group['courses'] = count($this->get_courses_by_usergroup($group['id']));
1471
                $roles = [];
1472
                switch ($group['group_type']) {
1473
                    case 0:
1474
                        $group['group_type'] = Display::label(get_lang('Class'), 'info');
1475
                        $roles = [0];
1476
                        break;
1477
                    case 1:
1478
                        $group['group_type'] = Display::label(get_lang('Social'), 'success');
1479
                        $roles = [
1480
                            GROUP_USER_PERMISSION_ADMIN,
1481
                            GROUP_USER_PERMISSION_READER,
1482
                            GROUP_USER_PERMISSION_MODERATOR,
1483
                            GROUP_USER_PERMISSION_HRM,
1484
                        ];
1485
                        break;
1486
                }
1487
                $group['users'] = Display::url(
1488
                    count($this->get_users_by_usergroup($group['id'], $roles)),
1489
                    api_get_path(WEB_CODE_PATH).'admin/usergroup_users.php?id='.$group['id']
1490
                );
1491
                $new_result[] = $group;
1492
            }
1493
            $result = $new_result;
1494
        }
1495
        $columns = ['name', 'users', 'courses', 'sessions', 'group_type'];
1496
1497
        if (!in_array($sidx, $columns)) {
1498
            $sidx = 'name';
1499
        }
1500
1501
        // Multidimensional sort
1502
        $result = msort($result, $sidx, $sord);
1503
1504
        return $result;
1505
    }
1506
1507
    /**
1508
     * @param array $options
1509
     *
1510
     * @return array
1511
     */
1512
    public function getDataToExport($options = [])
1513
    {
1514
        $and = '';
1515
        if (!empty($options) && !empty($options['where'])) {
1516
            $and = ' AND ';
1517
        }
1518
        if ($this->getUseMultipleUrl()) {
1519
            $urlId = api_get_current_access_url_id();
1520
            $from = $this->table." u
1521
                    INNER JOIN {$this->access_url_rel_usergroup} a
1522
                    ON (u.id = a.usergroup_id)";
1523
            $options['where'][$and.' access_url_id = ? '] = $urlId;
1524
            if ($this->allowTeachers()) {
1525
                $options['where'] = [' AND author_id = ? ' => api_get_user_id()];
1526
            }
1527
            $classes = Database::select('u.id, name, description, group_type, visibility', $from, $options);
1528
        } else {
1529
            if ($this->allowTeachers()) {
1530
                $options['where'] = [$and.' author_id = ? ' => api_get_user_id()];
1531
            }
1532
            $classes = Database::select('id, name, description, group_type, visibility', $this->table, $options);
1533
        }
1534
1535
        $result = [];
1536
        if (!empty($classes)) {
1537
            foreach ($classes as $data) {
1538
                $users = $this->getUserListByUserGroup($data['id']);
1539
                $userToString = null;
1540
                if (!empty($users)) {
1541
                    $userNameList = [];
1542
                    foreach ($users as $userData) {
1543
                        $userNameList[] = $userData['username'];
1544
                    }
1545
                    $userToString = implode(',', $userNameList);
1546
                }
1547
1548
                $courses = $this->get_courses_by_usergroup($data['id'], true);
1549
                $coursesToString = '';
1550
                if (!empty($courses)) {
1551
                    $coursesToString = implode(', ', array_column($courses, 'code'));
1552
                }
1553
1554
                $sessions = $this->get_sessions_by_usergroup($data['id']);
1555
                $sessionsToString = '';
1556
                if (!empty($sessions)) {
1557
                    $sessionList = [];
1558
                    foreach ($sessions as $sessionId) {
1559
                        $sessionList[] = api_get_session_info($sessionId)['name'];
1560
                    }
1561
                    $sessionsToString = implode(', ', $sessionList);
1562
                }
1563
1564
                $data['users'] = $userToString;
1565
                $data['courses'] = $coursesToString;
1566
                $data['sessions'] = $sessionsToString;
1567
                $result[] = $data;
1568
            }
1569
        }
1570
1571
        return $result;
1572
    }
1573
1574
    /**
1575
     * @param string $firstLetter
1576
     * @param int    $limit
1577
     *
1578
     * @return array
1579
     */
1580
    public function filterByFirstLetter($firstLetter, $limit = 0)
1581
    {
1582
        $firstLetter = Database::escape_string($firstLetter);
1583
        $limit = (int) $limit;
1584
1585
        $sql = ' SELECT g.id, name ';
1586
1587
        $urlCondition = '';
1588
        if ($this->getUseMultipleUrl()) {
1589
            $urlId = api_get_current_access_url_id();
1590
            $sql .= " FROM $this->table g
1591
                    INNER JOIN $this->access_url_rel_usergroup a
1592
                    ON (g.id = a.usergroup_id) ";
1593
            $urlCondition = " AND access_url_id = $urlId ";
1594
        } else {
1595
            $sql = " FROM $this->table g ";
1596
        }
1597
        $sql .= "
1598
		        WHERE
1599
		            name LIKE '".$firstLetter."%' OR
1600
		            name LIKE '".api_strtolower($firstLetter)."%'
1601
		            $urlCondition
1602
		        ORDER BY name DESC ";
1603
1604
        if (!empty($limit)) {
1605
            $sql .= " LIMIT $limit ";
1606
        }
1607
1608
        $result = Database::query($sql);
1609
1610
        return Database::store_result($result);
1611
    }
1612
1613
    /**
1614
     * Select user group not in list.
1615
     *
1616
     * @param array $list
1617
     *
1618
     * @return array
1619
     */
1620
    public function getUserGroupNotInList($list)
1621
    {
1622
        if (empty($list)) {
1623
            return [];
1624
        }
1625
1626
        $list = array_map('intval', $list);
1627
        $listToString = implode("','", $list);
1628
        $sql = "SELECT * FROM $this->table g WHERE g.id NOT IN ('$listToString')";
1629
        $result = Database::query($sql);
1630
1631
        return Database::store_result($result, 'ASSOC');
1632
    }
1633
1634
    /**
1635
     * @param $params
1636
     * @param bool $show_query
1637
     *
1638
     * @return bool|int
1639
     */
1640
    public function save($params, $show_query = false)
1641
    {
1642
        $params['updated_at'] = $params['created_at'] = api_get_utc_datetime();
1643
        $params['group_type'] = !empty($params['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
1644
        $params['allow_members_leave_group'] = isset($params['allow_members_leave_group']) ? 1 : 0;
1645
1646
        $groupExists = $this->usergroup_exists(trim($params['name']));
1647
        if (false == $groupExists) {
1648
            if ($this->allowTeachers()) {
1649
                $params['author_id'] = api_get_user_id();
1650
            }
1651
            $id = parent::save($params, $show_query);
1652
            if ($id) {
1653
                if ($this->getUseMultipleUrl()) {
1654
                    $this->subscribeToUrl($id, api_get_current_access_url_id());
1655
                }
1656
1657
                if (self::SOCIAL_CLASS == $params['group_type']) {
1658
                    $this->add_user_to_group(
1659
                        api_get_user_id(),
1660
                        $id,
1661
                        GROUP_USER_PERMISSION_ADMIN
1662
                    );
1663
                }
1664
                $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
1665
                $picture = $this->manageFileUpload($id, $picture);
1666
                if ($picture) {
1667
                    $params = [
1668
                        'id' => $id,
1669
                        'picture' => $picture,
1670
                        'group_type' => $params['group_type'],
1671
                    ];
1672
                    $this->update($params);
1673
                }
1674
            }
1675
            // Add event to system log
1676
            Event::addEvent(
1677
                LOG_GROUP_PORTAL_CREATED,
1678
                LOG_GROUP_PORTAL_ID,
1679
                'id: '.$id,
1680
                api_get_utc_datetime(),
1681
                api_get_user_id()
1682
            );
1683
1684
            return $id;
1685
        }
1686
1687
        return false;
1688
    }
1689
1690
    /**
1691
     * {@inheritdoc}
1692
     */
1693
    public function update($values, $showQuery = false)
1694
    {
1695
        $values['updated_on'] = api_get_utc_datetime();
1696
        $values['group_type'] = !empty($values['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
1697
        $values['allow_members_leave_group'] = isset($values['allow_members_leave_group']) ? 1 : 0;
1698
1699
        if (isset($values['id'])) {
1700
            $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
1701
            if (!empty($picture)) {
1702
                $picture = $this->manageFileUpload($values['id'], $picture);
1703
                if ($picture) {
1704
                    $values['picture'] = $picture;
1705
                }
1706
            }
1707
1708
            if (isset($values['delete_picture'])) {
1709
                $values['picture'] = null;
1710
            }
1711
        }
1712
1713
        parent::update($values, $showQuery);
1714
1715
        if (isset($values['delete_picture'])) {
1716
            $this->delete_group_picture($values['id']);
1717
        }
1718
        // Add event to system log
1719
        Event::addEvent(
1720
            LOG_GROUP_PORTAL_UPDATED,
1721
            LOG_GROUP_PORTAL_ID,
1722
            'id: '.$values['id'],
1723
            api_get_utc_datetime(),
1724
            api_get_user_id()
1725
        );
1726
1727
        return true;
1728
    }
1729
1730
    /**
1731
     * @param int    $groupId
1732
     * @param string $picture
1733
     *
1734
     * @return bool|string
1735
     */
1736
    public function manageFileUpload($groupId, $picture)
1737
    {
1738
        if (!empty($picture['name'])) {
1739
            return $this->update_group_picture(
1740
                $groupId,
1741
                $picture['name'],
1742
                $picture['tmp_name']
1743
            );
1744
        }
1745
1746
        return false;
1747
    }
1748
1749
    /**
1750
     * @param int $groupId
1751
     *
1752
     * @return string
1753
     */
1754
    public function delete_group_picture($groupId)
1755
    {
1756
        return $this->update_group_picture($groupId);
1757
    }
1758
1759
    /**
1760
     * Creates new group pictures in various sizes of a user, or deletes user pfotos.
1761
     * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php.
1762
     *
1763
     * @param    int    The group id
1764
     * @param string $file The common file name for the newly created photos.
1765
     *                     It will be checked and modified for compatibility with the file system.
1766
     *                     If full name is provided, path component is ignored.
1767
     *                     If an empty name is provided, then old user photos are deleted only,
1768
     *
1769
     * @see UserManager::delete_user_picture() as the prefered way for deletion.
1770
     *
1771
     * @param string $source_file the full system name of the image from which user photos will be created
1772
     *
1773
     * @return mixed Returns the resulting common file name of created images which usually should be stored in database.
1774
     *               When an image is removed the function returns an empty string.
1775
     *               In case of internal error or negative validation it returns FALSE.
1776
     */
1777
    public function update_group_picture($group_id, $file = null, $source_file = null)
1778
    {
1779
        $group_id = (int) $group_id;
1780
1781
        if (empty($group_id)) {
1782
            return false;
1783
        }
1784
        $delete = empty($file);
1785
        if (empty($source_file)) {
1786
            $source_file = $file;
1787
        }
1788
1789
        // User-reserved directory where photos have to be placed.
1790
        $path_info = $this->get_group_picture_path_by_id($group_id, 'system', true);
1791
1792
        $path = $path_info['dir'];
1793
1794
        // If this directory does not exist - we create it.
1795
        if (!is_dir($path)) {
1796
            $res = @mkdir($path, api_get_permissions_for_new_directories(), true);
1797
            if ($res === false) {
1798
                // There was an issue creating the directory $path, probably
1799
                // permissions-related
1800
                return false;
1801
            }
1802
        }
1803
1804
        // The old photos (if any).
1805
        $old_file = $path_info['file'];
1806
1807
        // Let us delete them.
1808
        if (!empty($old_file)) {
1809
            if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
1810
                $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
1811
                @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
1812
                @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
1813
                @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
1814
                @rename($path.$old_file, $path.$prefix.$old_file);
1815
            } else {
1816
                @unlink($path.'small_'.$old_file);
1817
                @unlink($path.'medium_'.$old_file);
1818
                @unlink($path.'big_'.$old_file);
1819
                @unlink($path.$old_file);
1820
            }
1821
        }
1822
1823
        // Exit if only deletion has been requested. Return an empty picture name.
1824
        if ($delete) {
1825
            return '';
1826
        }
1827
1828
        // Validation 2.
1829
        $allowed_types = ['jpg', 'jpeg', 'png', 'gif'];
1830
        $file = str_replace('\\', '/', $file);
1831
        $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
1832
        $extension = strtolower(substr(strrchr($filename, '.'), 1));
1833
        if (!in_array($extension, $allowed_types)) {
1834
            return false;
1835
        }
1836
1837
        // This is the common name for the new photos.
1838
        if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
1839
            $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
1840
            $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
1841
            $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
1842
        } else {
1843
            $filename = api_replace_dangerous_char($filename);
1844
            if (PREFIX_IMAGE_FILENAME_WITH_UID) {
1845
                $filename = uniqid('').'_'.$filename;
1846
            }
1847
            // We always prefix user photos with user ids, so on setting
1848
            // api_get_setting('split_users_upload_directory') === 'true'
1849
            // the correspondent directories to be found successfully.
1850
            $filename = $group_id.'_'.$filename;
1851
        }
1852
1853
        // Storing the new photos in 4 versions with various sizes.
1854
1855
        /*$image->resize(
1856
        // get original size and set width (widen) or height (heighten).
1857
        // width or height will be set maintaining aspect ratio.
1858
            $image->getSize()->widen( 700 )
1859
        );*/
1860
1861
        // Usign the Imagine service
1862
        $imagine = new Imagine\Gd\Imagine();
1863
        $image = $imagine->open($source_file);
1864
1865
        $options = [
1866
            'quality' => 90,
1867
        ];
1868
1869
        //$image->resize(new Imagine\Image\Box(200, 200))->save($path.'big_'.$filename);
1870
        $image->resize($image->getSize()->widen(200))->save($path.'big_'.$filename, $options);
1871
1872
        $image = $imagine->open($source_file);
1873
        $image->resize(new Imagine\Image\Box(85, 85))->save($path.'medium_'.$filename, $options);
1874
1875
        $image = $imagine->open($source_file);
1876
        $image->resize(new Imagine\Image\Box(22, 22))->save($path.'small_'.$filename);
1877
1878
        /*
1879
        $small  = self::resize_picture($source_file, 22);
1880
        $medium = self::resize_picture($source_file, 85);
1881
        $normal = self::resize_picture($source_file, 200);
1882
1883
        $big = new Image($source_file); // This is the original picture.
1884
        $ok = $small && $small->send_image($path.'small_'.$filename)
1885
            && $medium && $medium->send_image($path.'medium_'.$filename)
1886
            && $normal && $normal->send_image($path.'big_'.$filename)
1887
            && $big && $big->send_image($path.$filename);
1888
        return $ok ? $filename : false;*/
1889
        return $filename;
1890
    }
1891
1892
    /**
1893
     * @return mixed
1894
     */
1895
    public function getGroupType()
1896
    {
1897
        return $this->groupType;
1898
    }
1899
1900
    /**
1901
     * @param int $id
1902
     *
1903
     * @return bool|void
1904
     */
1905
    public function delete($id)
1906
    {
1907
        $id = (int) $id;
1908
        if ($this->getUseMultipleUrl()) {
1909
            $this->unsubscribeToUrl($id, api_get_current_access_url_id());
1910
        }
1911
1912
        $sql = "DELETE FROM $this->usergroup_rel_user_table
1913
                WHERE usergroup_id = $id";
1914
        Database::query($sql);
1915
1916
        $sql = "DELETE FROM $this->usergroup_rel_course_table
1917
                WHERE usergroup_id = $id";
1918
        Database::query($sql);
1919
1920
        $sql = "DELETE FROM $this->usergroup_rel_session_table
1921
                WHERE usergroup_id = $id";
1922
        Database::query($sql);
1923
1924
        $res = parent::delete($id);
1925
        // Add event to system log
1926
        if ($res) {
1927
            Event::addEvent(
1928
                LOG_GROUP_PORTAL_DELETED,
1929
                LOG_GROUP_PORTAL_ID,
1930
                'id: '.$id,
1931
                api_get_utc_datetime(),
1932
                api_get_user_id()
1933
            );
1934
        }
1935
        return $res;
1936
    }
1937
1938
    /**
1939
     * @param int $id
1940
     * @param int $urlId
1941
     */
1942
    public function subscribeToUrl($id, $urlId)
1943
    {
1944
        Database::insert(
1945
            $this->access_url_rel_usergroup,
1946
            [
1947
                'access_url_id' => $urlId,
1948
                'usergroup_id' => $id,
1949
            ]
1950
        );
1951
    }
1952
1953
    /**
1954
     * @param int $id
1955
     * @param int $urlId
1956
     */
1957
    public function unsubscribeToUrl($id, $urlId)
1958
    {
1959
        Database::delete(
1960
            $this->access_url_rel_usergroup,
1961
            [
1962
                'access_url_id = ? AND usergroup_id = ? ' => [$urlId, $id],
1963
            ]
1964
        );
1965
    }
1966
1967
    /**
1968
     * @param $needle
1969
     *
1970
     * @return xajaxResponse
1971
     */
1972
    public static function searchUserGroupAjax($needle)
1973
    {
1974
        $response = new xajaxResponse();
1975
        $return = '';
1976
1977
        if (!empty($needle)) {
1978
            // xajax send utf8 datas... datas in db can be non-utf8 datas
1979
            $charset = api_get_system_encoding();
1980
            $needle = api_convert_encoding($needle, $charset, 'utf-8');
1981
            $needle = Database::escape_string($needle);
1982
1983
            $sql = 'SELECT id, name
1984
                    FROM '.Database::get_main_table(TABLE_USERGROUP).' u
1985
                    WHERE name LIKE "'.$needle.'%"
1986
                    ORDER BY name
1987
                    LIMIT 11';
1988
            $result = Database::query($sql);
1989
            $i = 0;
1990
            while ($data = Database::fetch_array($result)) {
1991
                $i++;
1992
                if ($i <= 10) {
1993
                    $return .= '<a
1994
                    href="javascript: void(0);"
1995
                    onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['name']).' \')">'.$data['name'].' </a><br />';
1996
                } else {
1997
                    $return .= '...<br />';
1998
                }
1999
            }
2000
        }
2001
        $response->addAssign('ajax_list_courses', 'innerHTML', api_utf8_encode($return));
2002
2003
        return $response;
2004
    }
2005
2006
    /**
2007
     * Get user list by usergroup.
2008
     *
2009
     * @param int    $id
2010
     * @param string $orderBy
2011
     *
2012
     * @return array
2013
     */
2014
    public function getUserListByUserGroup($id, $orderBy = '')
2015
    {
2016
        $id = (int) $id;
2017
        $sql = "SELECT u.* FROM $this->table_user u
2018
                INNER JOIN $this->usergroup_rel_user_table c
2019
                ON c.user_id = u.id
2020
                WHERE c.usergroup_id = $id"
2021
                ;
2022
2023
        if (!empty($orderBy)) {
2024
            $orderBy = Database::escape_string($orderBy);
2025
            $sql .= " ORDER BY $orderBy ";
2026
        }
2027
        $result = Database::query($sql);
2028
2029
        return Database::store_result($result);
2030
    }
2031
2032
    /**
2033
     * @param FormValidator $form
2034
     * @param string        $type
2035
     * @param array         $data
2036
     */
2037
    public function setForm($form, $type = 'add', $data = [])
2038
    {
2039
        $header = '';
2040
        switch ($type) {
2041
            case 'add':
2042
                $header = get_lang('Add');
2043
                break;
2044
            case 'edit':
2045
                $header = get_lang('Edit');
2046
                break;
2047
        }
2048
2049
        $form->addHeader($header);
2050
2051
        // Name
2052
        $form->addText('name', get_lang('Name'), true, ['maxlength' => 255]);
2053
        $form->addRule('name', '', 'maxlength', 255);
2054
2055
        // Description
2056
        $form->addTextarea('description', get_lang('Description'), ['cols' => 58]);
2057
        $form->applyFilter('description', 'trim');
2058
2059
        if ($this->showGroupTypeSetting) {
2060
            $form->addElement(
2061
                'checkbox',
2062
                'group_type',
2063
                null,
2064
                get_lang('SocialGroup')
2065
            );
2066
        }
2067
2068
        // url
2069
        $form->addText('url', get_lang('Url'), false);
2070
2071
        // Picture
2072
        $allowed_picture_types = $this->getAllowedPictureExtensions();
2073
2074
        $form->addFile('picture', get_lang('AddPicture'));
2075
        $form->addRule(
2076
            'picture',
2077
            get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
2078
            'filetype',
2079
            $allowed_picture_types
2080
        );
2081
2082
        if (isset($data['picture']) && strlen($data['picture']) > 0) {
2083
            $picture = $this->get_picture_group($data['id'], $data['picture'], 80);
2084
            $img = '<img src="'.$picture['file'].'" />';
2085
            $form->addLabel(null, $img);
2086
            $form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
2087
        }
2088
2089
        $form->addElement('select', 'visibility', get_lang('GroupPermissions'), $this->getGroupStatusList());
2090
        $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
2091
        $form->addElement('checkbox', 'allow_members_leave_group', '', get_lang('AllowMemberLeaveGroup'));
2092
2093
        // Setting the form elements
2094
        if ($type === 'add') {
2095
            $form->addButtonCreate($header);
2096
        } else {
2097
            $form->addButtonUpdate($header);
2098
        }
2099
    }
2100
2101
    /**
2102
     * Gets the current group image.
2103
     *
2104
     * @param string $id group id
2105
     * @param string picture group name
2106
     * @param string height
2107
     * @param string $size_picture picture size it can be small_,  medium_  or  big_
2108
     * @param string style css
2109
     *
2110
     * @return array with the file and the style of an image i.e $array['file'] $array['style']
2111
     */
2112
    public function get_picture_group(
2113
        $id,
2114
        $picture_file,
2115
        $height,
2116
        $size_picture = GROUP_IMAGE_SIZE_MEDIUM,
2117
        $style = ''
2118
    ) {
2119
        $picture = [];
2120
        if ($picture_file === 'unknown.jpg') {
2121
            $picture['file'] = Display::returnIconPath($picture_file);
2122
2123
            return $picture;
2124
        }
2125
2126
        switch ($size_picture) {
2127
            case GROUP_IMAGE_SIZE_ORIGINAL:
2128
                $size_picture = '';
2129
                break;
2130
            case GROUP_IMAGE_SIZE_BIG:
2131
                $size_picture = 'big_';
2132
                break;
2133
            case GROUP_IMAGE_SIZE_MEDIUM:
2134
                $size_picture = 'medium_';
2135
                break;
2136
            case GROUP_IMAGE_SIZE_SMALL:
2137
                $size_picture = 'small_';
2138
                break;
2139
            default:
2140
                $size_picture = 'medium_';
2141
        }
2142
2143
        $image_array_sys = $this->get_group_picture_path_by_id($id, 'system', false, true);
2144
        $image_array = $this->get_group_picture_path_by_id($id, 'web', false, true);
2145
        $file = $image_array_sys['dir'].$size_picture.$picture_file;
2146
        if (file_exists($file)) {
2147
            $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
2148
            if ($height > 0) {
2149
                $dimension = api_getimagesize($picture['file']);
2150
                $margin = ($height - $dimension['width']) / 2;
2151
                //@ todo the padding-top should not be here
2152
            }
2153
        } else {
2154
            $file = $image_array_sys['dir'].$picture_file;
2155
            if (file_exists($file) && !is_dir($file)) {
2156
                $picture['file'] = $image_array['dir'].$picture_file;
2157
            } else {
2158
                $picture['file'] = Display::returnIconPath('group_na.png', 64);
2159
            }
2160
        }
2161
2162
        return $picture;
2163
    }
2164
2165
    /**
2166
     * Gets the group picture URL or path from group ID (returns an array).
2167
     * The return format is a complete path, enabling recovery of the directory
2168
     * with dirname() or the file with basename(). This also works for the
2169
     * functions dealing with the user's productions, as they are located in
2170
     * the same directory.
2171
     *
2172
     * @param    int    User ID
2173
     * @param    string    Type of path to return (can be 'none', 'system', 'rel', 'web')
2174
     * @param    bool    Whether we want to have the directory name returned 'as if'
2175
     * there was a file or not (in the case we want to know which directory to create -
2176
     * otherwise no file means no split subdir)
2177
     * @param    bool    If we want that the function returns the /main/img/unknown.jpg image set it at true
2178
     *
2179
     * @return array Array of 2 elements: 'dir' and 'file' which contain the dir
2180
     *               and file as the name implies if image does not exist it will return the unknown
2181
     *               image if anonymous parameter is true if not it returns an empty er's
2182
     */
2183
    public function get_group_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false)
2184
    {
2185
        switch ($type) {
2186
            case 'system': // Base: absolute system path.
2187
                $base = api_get_path(SYS_UPLOAD_PATH);
2188
                break;
2189
            case 'rel': // Base: semi-absolute web path (no server base).
2190
                $base = api_get_path(REL_CODE_PATH);
2191
                break;
2192
            case 'web': // Base: absolute web path.
2193
                $base = api_get_path(WEB_UPLOAD_PATH);
2194
                break;
2195
            case 'none':
2196
            default: // Base: empty, the result path below will be relative.
2197
                $base = '';
2198
        }
2199
        $id = (int) $id;
2200
2201
        if (empty($id) || empty($type)) {
2202
            return $anonymous ? ['dir' => $base.'img/', 'file' => 'unknown.jpg'] : ['dir' => '', 'file' => ''];
2203
        }
2204
2205
        $group_table = Database::get_main_table(TABLE_USERGROUP);
2206
        $sql = "SELECT picture FROM $group_table WHERE id = ".$id;
2207
        $res = Database::query($sql);
2208
2209
        if (!Database::num_rows($res)) {
2210
            return $anonymous ? ['dir' => $base.'img/', 'file' => 'unknown.jpg'] : ['dir' => '', 'file' => ''];
2211
        }
2212
        $user = Database::fetch_array($res);
2213
        $picture_filename = trim($user['picture']);
2214
2215
        if (api_get_setting('split_users_upload_directory') === 'true') {
2216
            if (!empty($picture_filename)) {
2217
                $dir = $base.'groups/'.substr($picture_filename, 0, 1).'/'.$id.'/';
2218
            } elseif ($preview) {
2219
                $dir = $base.'groups/'.substr((string) $id, 0, 1).'/'.$id.'/';
2220
            } else {
2221
                $dir = $base.'groups/'.$id.'/';
2222
            }
2223
        } else {
2224
            $dir = $base.'groups/'.$id.'/';
2225
        }
2226
2227
        return ['dir' => $dir, 'file' => $picture_filename];
2228
    }
2229
2230
    /**
2231
     * @return array
2232
     */
2233
    public function getAllowedPictureExtensions()
2234
    {
2235
        return ['jpg', 'jpeg', 'png', 'gif'];
2236
    }
2237
2238
    /**
2239
     * @return array
2240
     */
2241
    public function getGroupStatusList()
2242
    {
2243
        $status = [
2244
            GROUP_PERMISSION_OPEN => get_lang('Open'),
2245
            GROUP_PERMISSION_CLOSED => get_lang('Closed'),
2246
        ];
2247
2248
        return $status;
2249
    }
2250
2251
    /**
2252
     * @param int $type
2253
     */
2254
    public function setGroupType($type)
2255
    {
2256
        $this->groupType = (int) $type;
2257
    }
2258
2259
    /**
2260
     * @param int $group_id
2261
     * @param int $user_id
2262
     *
2263
     * @return bool
2264
     */
2265
    public function is_group_admin($group_id, $user_id = 0)
2266
    {
2267
        if (empty($user_id)) {
2268
            $user_id = api_get_user_id();
2269
        }
2270
        $user_role = $this->get_user_group_role($user_id, $group_id);
2271
        if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN])) {
2272
            return true;
2273
        } else {
2274
            return false;
2275
        }
2276
    }
2277
2278
    /**
2279
     * @param int $group_id
2280
     * @param int $user_id
2281
     *
2282
     * @return bool
2283
     */
2284
    public function isGroupModerator($group_id, $user_id = 0)
2285
    {
2286
        if (empty($user_id)) {
2287
            $user_id = api_get_user_id();
2288
        }
2289
        $user_role = $this->get_user_group_role($user_id, $group_id);
2290
        if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR])) {
2291
            return true;
2292
        } else {
2293
            return false;
2294
        }
2295
    }
2296
2297
    /**
2298
     * @param int $group_id
2299
     * @param int $user_id
2300
     *
2301
     * @return bool
2302
     */
2303
    public function is_group_member($group_id, $user_id = 0)
2304
    {
2305
        if (api_is_platform_admin()) {
2306
            return true;
2307
        }
2308
        if (empty($user_id)) {
2309
            $user_id = api_get_user_id();
2310
        }
2311
        $roles = [
2312
            GROUP_USER_PERMISSION_ADMIN,
2313
            GROUP_USER_PERMISSION_MODERATOR,
2314
            GROUP_USER_PERMISSION_READER,
2315
            GROUP_USER_PERMISSION_HRM,
2316
        ];
2317
        $user_role = $this->get_user_group_role($user_id, $group_id);
2318
        if (in_array($user_role, $roles)) {
2319
            return true;
2320
        } else {
2321
            return false;
2322
        }
2323
    }
2324
2325
    /**
2326
     * Gets the relationship between a group and a User.
2327
     *
2328
     * @author Julio Montoya
2329
     *
2330
     * @param int $user_id
2331
     * @param int $group_id
2332
     *
2333
     * @return int 0 if there are not relationship otherwise returns the user group
2334
     * */
2335
    public function get_user_group_role($user_id, $group_id)
2336
    {
2337
        $table_group_rel_user = $this->usergroup_rel_user_table;
2338
        $return_value = 0;
2339
        $user_id = (int) $user_id;
2340
        $group_id = (int) $group_id;
2341
2342
        if (!empty($user_id) && !empty($group_id)) {
2343
            $sql = "SELECT relation_type
2344
                    FROM $table_group_rel_user
2345
                    WHERE
2346
                        usergroup_id = $group_id AND
2347
                        user_id = $user_id ";
2348
            $result = Database::query($sql);
2349
            if (Database::num_rows($result) > 0) {
2350
                $row = Database::fetch_array($result, 'ASSOC');
2351
                $return_value = $row['relation_type'];
2352
            }
2353
        }
2354
2355
        return $return_value;
2356
    }
2357
2358
    /**
2359
     * @param int $userId
2360
     * @param int $groupId
2361
     *
2362
     * @return string
2363
     */
2364
    public function getUserRoleToString($userId, $groupId)
2365
    {
2366
        $role = $this->get_user_group_role($userId, $groupId);
2367
        $roleToString = '';
2368
2369
        switch ($role) {
2370
            case GROUP_USER_PERMISSION_ADMIN:
2371
                $roleToString = get_lang('Admin');
2372
                break;
2373
            case GROUP_USER_PERMISSION_READER:
2374
                $roleToString = get_lang('Reader');
2375
                break;
2376
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
2377
                $roleToString = get_lang('PendingInvitation');
2378
                break;
2379
            case GROUP_USER_PERMISSION_MODERATOR:
2380
                $roleToString = get_lang('Moderator');
2381
                break;
2382
            case GROUP_USER_PERMISSION_HRM:
2383
                $roleToString = get_lang('Drh');
2384
                break;
2385
        }
2386
2387
        return $roleToString;
2388
    }
2389
2390
    /**
2391
     * Add a group of users into a group of URLs.
2392
     *
2393
     * @author Julio Montoya
2394
     *
2395
     * @param array $user_list
2396
     * @param array $group_list
2397
     * @param int   $relation_type
2398
     *
2399
     * @return array
2400
     */
2401
    public function add_users_to_groups($user_list, $group_list, $relation_type = GROUP_USER_PERMISSION_READER)
2402
    {
2403
        $table_url_rel_group = $this->usergroup_rel_user_table;
2404
        $result_array = [];
2405
        $relation_type = (int) $relation_type;
2406
2407
        if (is_array($user_list) && is_array($group_list)) {
2408
            foreach ($group_list as $group_id) {
2409
                $usersList = '';
2410
                foreach ($user_list as $user_id) {
2411
                    $user_id = (int) $user_id;
2412
                    $group_id = (int) $group_id;
2413
2414
                    $role = $this->get_user_group_role($user_id, $group_id);
2415
                    if ($role == 0) {
2416
                        $sql = "INSERT INTO $table_url_rel_group
2417
		               			SET
2418
		               			    user_id = $user_id ,
2419
		               			    usergroup_id = $group_id ,
2420
		               			    relation_type = $relation_type ";
2421
2422
                        $result = Database::query($sql);
2423
                        if ($result) {
2424
                            $result_array[$group_id][$user_id] = 1;
2425
                        } else {
2426
                            $result_array[$group_id][$user_id] = 0;
2427
                        }
2428
                    }
2429
                    $usersList .= $user_id.',';
2430
                }
2431
                // Add event to system log
2432
                Event::addEvent(
2433
                    LOG_GROUP_PORTAL_USER_SUBSCRIBED,
2434
                    LOG_GROUP_PORTAL_ID,
2435
                    'gid: '.$group_id.' - uids: '.substr($usersList, 0, -1),
2436
                    api_get_utc_datetime(),
2437
                    api_get_user_id()
2438
                );
2439
            }
2440
        }
2441
2442
        return $result_array;
2443
    }
2444
2445
    /**
2446
     * Deletes the subscription of a user to a usergroup
2447
     *
2448
     * @author Julio Montoya
2449
     *
2450
     * @param int $userId
2451
     * @param int $groupId
2452
     *
2453
     * @return bool true on success
2454
     * */
2455
    public function delete_user_rel_group($userId, $groupId)
2456
    {
2457
        $userId = (int) $userId;
2458
        $groupId = (int) $groupId;
2459
        if (empty($userId) || empty($groupId)) {
2460
            return false;
2461
        }
2462
2463
        $table = $this->usergroup_rel_user_table;
2464
        $sql = "DELETE FROM $table
2465
                WHERE
2466
                    user_id = $userId AND
2467
                    usergroup_id = $groupId";
2468
2469
        $result = Database::query($sql);
2470
        // Add event to system log
2471
        Event::addEvent(
2472
            LOG_GROUP_PORTAL_USER_UNSUBSCRIBED,
2473
            LOG_GROUP_PORTAL_ID,
2474
            'gid: '.$groupId.' - uid: '.$userId,
2475
            api_get_utc_datetime(),
2476
            api_get_user_id()
2477
        );
2478
2479
        return $result;
2480
    }
2481
2482
    /**
2483
     * Add a user into a group.
2484
     *
2485
     * @author Julio Montoya
2486
     *
2487
     * @param int $user_id
2488
     * @param int $group_id
2489
     * @param int $relation_type
2490
     *
2491
     * @return bool true if success
2492
     */
2493
    public function add_user_to_group($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
2494
    {
2495
        $table_url_rel_group = $this->usergroup_rel_user_table;
2496
        $user_id = (int) $user_id;
2497
        $group_id = (int) $group_id;
2498
        $relation_type = (int) $relation_type;
2499
        if (!empty($user_id) && !empty($group_id)) {
2500
            $role = $this->get_user_group_role($user_id, $group_id);
2501
2502
            if ($role == 0) {
2503
                $sql = "INSERT INTO $table_url_rel_group
2504
           				SET
2505
           				    user_id = ".$user_id.",
2506
           				    usergroup_id = ".$group_id.",
2507
           				    relation_type = ".$relation_type;
2508
                Database::query($sql);
2509
                // Add event to system log
2510
                Event::addEvent(
2511
                    LOG_GROUP_PORTAL_USER_SUBSCRIBED,
2512
                    LOG_GROUP_PORTAL_ID,
2513
                    'gid: '.$group_id.' - uid: '.$user_id,
2514
                    api_get_utc_datetime(),
2515
                    api_get_user_id()
2516
                );
2517
            } elseif ($role == GROUP_USER_PERMISSION_PENDING_INVITATION) {
2518
                //if somebody already invited me I can be added
2519
                self::update_user_role($user_id, $group_id, GROUP_USER_PERMISSION_READER);
2520
            }
2521
        }
2522
2523
        return true;
2524
    }
2525
2526
    /**
2527
     * Updates the group_rel_user table  with a given user and group ids.
2528
     *
2529
     * @author Julio Montoya
2530
     *
2531
     * @param int $user_id
2532
     * @param int $group_id
2533
     * @param int $relation_type
2534
     */
2535
    public function update_user_role($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
2536
    {
2537
        $table_group_rel_user = $this->usergroup_rel_user_table;
2538
        $group_id = (int) $group_id;
2539
        $user_id = (int) $user_id;
2540
        $relation_type = (int) $relation_type;
2541
2542
        $sql = "UPDATE $table_group_rel_user
2543
   				SET relation_type = $relation_type
2544
                WHERE user_id = $user_id AND usergroup_id = $group_id";
2545
        Database::query($sql);
2546
    }
2547
2548
    /**
2549
     * Gets the inner join from users and group table.
2550
     *
2551
     * @return array Database::store_result of the result
2552
     *
2553
     * @author Julio Montoya
2554
     * */
2555
    public function get_groups_by_user($user_id, $relationType = GROUP_USER_PERMISSION_READER, $with_image = false)
2556
    {
2557
        $table_group_rel_user = $this->usergroup_rel_user_table;
2558
        $tbl_group = $this->table;
2559
        $user_id = (int) $user_id;
2560
2561
        if ($relationType == 0) {
2562
            $relationCondition = '';
2563
        } else {
2564
            if (is_array($relationType)) {
2565
                $relationType = array_map('intval', $relationType);
2566
                $relationType = implode("','", $relationType);
2567
                $relationCondition = " AND ( gu.relation_type IN ('$relationType')) ";
2568
            } else {
2569
                $relationType = (int) $relationType;
2570
                $relationCondition = " AND gu.relation_type = $relationType ";
2571
            }
2572
        }
2573
2574
        $sql = 'SELECT
2575
                    g.picture,
2576
                    g.name,
2577
                    g.description,
2578
                    g.id ,
2579
                    gu.relation_type';
2580
2581
        $urlCondition = '';
2582
        if ($this->getUseMultipleUrl()) {
2583
            $sql .= " FROM $tbl_group g
2584
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2585
                    ON (g.id = a.usergroup_id)
2586
                    INNER JOIN $table_group_rel_user gu
2587
                    ON gu.usergroup_id = g.id";
2588
            $urlId = api_get_current_access_url_id();
2589
            $urlCondition = " AND access_url_id = $urlId ";
2590
        } else {
2591
            $sql .= " FROM $tbl_group g
2592
                    INNER JOIN $table_group_rel_user gu
2593
                    ON gu.usergroup_id = g.id";
2594
        }
2595
2596
        $sql .= " WHERE
2597
				    g.group_type = ".self::SOCIAL_CLASS." AND
2598
                    gu.user_id = $user_id
2599
                    $relationCondition
2600
                    $urlCondition
2601
                ORDER BY created_at DESC ";
2602
        $result = Database::query($sql);
2603
        $array = [];
2604
        if (Database::num_rows($result) > 0) {
2605
            while ($row = Database::fetch_array($result, 'ASSOC')) {
2606
                if ($with_image) {
2607
                    $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2608
                    $img = '<img src="'.$picture['file'].'" />';
2609
                    $row['picture'] = $img;
2610
                }
2611
                $array[$row['id']] = $row;
2612
            }
2613
        }
2614
2615
        return $array;
2616
    }
2617
2618
    /**
2619
     * Gets the inner join of users and group table.
2620
     *
2621
     * @param int  quantity of records
2622
     * @param bool show groups with image or not
2623
     *
2624
     * @return array with group content
2625
     *
2626
     * @author Julio Montoya
2627
     * */
2628
    public function get_groups_by_popularity($num = 6, $with_image = true)
2629
    {
2630
        $table_group_rel_user = $this->usergroup_rel_user_table;
2631
        $tbl_group = $this->table;
2632
        if (empty($num)) {
2633
            $num = 6;
2634
        } else {
2635
            $num = (int) $num;
2636
        }
2637
        // only show admins and readers
2638
        $whereCondition = " WHERE
2639
                              g.group_type = ".self::SOCIAL_CLASS." AND
2640
                              gu.relation_type IN
2641
                              ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
2642
2643
        $sql = 'SELECT DISTINCT count(user_id) as count, g.picture, g.name, g.description, g.id ';
2644
2645
        $urlCondition = '';
2646
        if ($this->getUseMultipleUrl()) {
2647
            $sql .= " FROM $tbl_group g
2648
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2649
                    ON (g.id = a.usergroup_id)
2650
                    INNER JOIN $table_group_rel_user gu
2651
                    ON gu.usergroup_id = g.id";
2652
            $urlId = api_get_current_access_url_id();
2653
            $urlCondition = " AND access_url_id = $urlId ";
2654
        } else {
2655
            $sql .= " FROM $tbl_group g
2656
                    INNER JOIN $table_group_rel_user gu
2657
                    ON gu.usergroup_id = g.id";
2658
        }
2659
2660
        $sql .= "
2661
				$whereCondition
2662
				$urlCondition
2663
				GROUP BY g.id
2664
				ORDER BY count DESC
2665
				LIMIT $num";
2666
2667
        $result = Database::query($sql);
2668
        $array = [];
2669
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2670
            if ($with_image) {
2671
                $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2672
                $img = '<img src="'.$picture['file'].'" />';
2673
                $row['picture'] = $img;
2674
            }
2675
            if (empty($row['id'])) {
2676
                continue;
2677
            }
2678
            $array[$row['id']] = $row;
2679
        }
2680
2681
        return $array;
2682
    }
2683
2684
    /**
2685
     * Gets the last groups created.
2686
     *
2687
     * @param int  $num       quantity of records
2688
     * @param bool $withImage show groups with image or not
2689
     *
2690
     * @return array with group content
2691
     *
2692
     * @author Julio Montoya
2693
     * */
2694
    public function get_groups_by_age($num = 6, $withImage = true)
2695
    {
2696
        $table_group_rel_user = $this->usergroup_rel_user_table;
2697
        $tbl_group = $this->table;
2698
2699
        if (empty($num)) {
2700
            $num = 6;
2701
        } else {
2702
            $num = (int) $num;
2703
        }
2704
2705
        $where = " WHERE
2706
                        g.group_type = ".self::SOCIAL_CLASS." AND
2707
                        gu.relation_type IN
2708
                        ('".GROUP_USER_PERMISSION_ADMIN."' ,
2709
                        '".GROUP_USER_PERMISSION_READER."',
2710
                        '".GROUP_USER_PERMISSION_MODERATOR."',
2711
                        '".GROUP_USER_PERMISSION_HRM."')
2712
                    ";
2713
        $sql = 'SELECT DISTINCT
2714
                  count(user_id) as count,
2715
                  g.picture,
2716
                  g.name,
2717
                  g.description,
2718
                  g.id ';
2719
2720
        $urlCondition = '';
2721
        if ($this->getUseMultipleUrl()) {
2722
            $sql .= " FROM $tbl_group g
2723
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2724
                    ON (g.id = a.usergroup_id)
2725
                    INNER JOIN $table_group_rel_user gu
2726
                    ON gu.usergroup_id = g.id";
2727
            $urlId = api_get_current_access_url_id();
2728
            $urlCondition = " AND access_url_id = $urlId ";
2729
        } else {
2730
            $sql .= " FROM $tbl_group g
2731
                    INNER JOIN $table_group_rel_user gu
2732
                    ON gu.usergroup_id = g.id";
2733
        }
2734
        $sql .= "
2735
                $where
2736
                $urlCondition
2737
                GROUP BY g.id
2738
                ORDER BY created_at DESC
2739
                LIMIT $num ";
2740
2741
        $result = Database::query($sql);
2742
        $array = [];
2743
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2744
            if ($withImage) {
2745
                $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2746
                $img = '<img src="'.$picture['file'].'" />';
2747
                $row['picture'] = $img;
2748
            }
2749
            if (empty($row['id'])) {
2750
                continue;
2751
            }
2752
            $array[$row['id']] = $row;
2753
        }
2754
2755
        return $array;
2756
    }
2757
2758
    /**
2759
     * Gets the group's members.
2760
     *
2761
     * @param int group id
2762
     * @param bool show image or not of the group
2763
     * @param array list of relation type use constants
2764
     * @param int from value
2765
     * @param int limit
2766
     * @param array image configuration, i.e array('height'=>'20px', 'size'=> '20px')
2767
     *
2768
     * @return array list of users in a group
2769
     */
2770
    public function get_users_by_group(
2771
        $group_id,
2772
        $withImage = false,
2773
        $relation_type = [],
2774
        $from = null,
2775
        $limit = null
2776
    ) {
2777
        $table_group_rel_user = $this->usergroup_rel_user_table;
2778
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2779
        $group_id = (int) $group_id;
2780
2781
        if (empty($group_id)) {
2782
            return [];
2783
        }
2784
2785
        $limit_text = '';
2786
        if (isset($from) && isset($limit)) {
2787
            $from = (int) $from;
2788
            $limit = (int) $limit;
2789
            $limit_text = "LIMIT $from, $limit";
2790
        }
2791
2792
        if (count($relation_type) == 0) {
2793
            $where_relation_condition = '';
2794
        } else {
2795
            $new_relation_type = [];
2796
            foreach ($relation_type as $rel) {
2797
                $rel = (int) $rel;
2798
                $new_relation_type[] = "'$rel'";
2799
            }
2800
            $relation_type = implode(',', $new_relation_type);
2801
            if (!empty($relation_type)) {
2802
                $where_relation_condition = "AND gu.relation_type IN ($relation_type) ";
2803
            }
2804
        }
2805
2806
        $sql = "SELECT
2807
                    picture_uri as image,
2808
                    u.id,
2809
                    CONCAT (u.firstname,' ', u.lastname) as fullname,
2810
                    relation_type
2811
    		    FROM $tbl_user u
2812
    		    INNER JOIN $table_group_rel_user gu
2813
    			ON (gu.user_id = u.id)
2814
    			WHERE
2815
    			    gu.usergroup_id= $group_id
2816
    			    $where_relation_condition
2817
    			ORDER BY relation_type, firstname
2818
    			$limit_text";
2819
2820
        $result = Database::query($sql);
2821
        $array = [];
2822
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2823
            if ($withImage) {
2824
                $userInfo = api_get_user_info($row['id']);
2825
                $userPicture = UserManager::getUserPicture($row['id']);
2826
                $row['image'] = '<img src="'.$userPicture.'"  />';
2827
                $row['user_info'] = $userInfo;
2828
            }
2829
2830
            $row['user_id'] = $row['id'];
2831
            $array[$row['id']] = $row;
2832
        }
2833
2834
        return $array;
2835
    }
2836
2837
    /**
2838
     * Gets all the members of a group no matter the relationship for
2839
     * more specifications use get_users_by_group.
2840
     *
2841
     * @param int group id
2842
     *
2843
     * @return array
2844
     */
2845
    public function get_all_users_by_group($group_id)
2846
    {
2847
        $table_group_rel_user = $this->usergroup_rel_user_table;
2848
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2849
        $group_id = (int) $group_id;
2850
2851
        if (empty($group_id)) {
2852
            return [];
2853
        }
2854
2855
        $sql = "SELECT u.id, u.firstname, u.lastname, gu.relation_type
2856
                FROM $tbl_user u
2857
			    INNER JOIN $table_group_rel_user gu
2858
			    ON (gu.user_id = u.id)
2859
			    WHERE gu.usergroup_id= $group_id
2860
			    ORDER BY relation_type, firstname";
2861
2862
        $result = Database::query($sql);
2863
        $array = [];
2864
        while ($row = Database::fetch_array($result, 'ASSOC')) {
2865
            $array[$row['id']] = $row;
2866
        }
2867
2868
        return $array;
2869
    }
2870
2871
    /**
2872
     * Shows the left column of the group page.
2873
     *
2874
     * @param int    $group_id
2875
     * @param int    $user_id
2876
     * @param string $show
2877
     *
2878
     * @return string
2879
     */
2880
    public function show_group_column_information($group_id, $user_id, $show = '')
2881
    {
2882
        $html = '';
2883
        $group_info = $this->get($group_id);
2884
2885
        //my relation with the group is set here
2886
        $my_group_role = $this->get_user_group_role($user_id, $group_id);
2887
2888
        // Loading group permission
2889
        $links = '';
2890
        switch ($my_group_role) {
2891
            case GROUP_USER_PERMISSION_READER:
2892
                // I'm just a reader
2893
                $relation_group_title = get_lang('IAmAReader');
2894
                $links .= '<li class="'.($show == 'invite_friends' ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
2895
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2896
                if (self::canLeave($group_info)) {
2897
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2898
                        Display::return_icon('group_leave.png', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2899
                }
2900
                break;
2901
            case GROUP_USER_PERMISSION_ADMIN:
2902
                $relation_group_title = get_lang('IAmAnAdmin');
2903
                $links .= '<li class="'.($show == 'group_edit' ? 'active' : '').'"><a href="group_edit.php?id='.$group_id.'">'.
2904
                            Display::return_icon('group_edit.png', get_lang('EditGroup')).get_lang('EditGroup').'</a></li>';
2905
                $links .= '<li class="'.($show == 'member_list' ? 'active' : '').'"><a href="group_waiting_list.php?id='.$group_id.'">'.
2906
                            Display::return_icon('waiting_list.png', get_lang('WaitingList')).get_lang('WaitingList').'</a></li>';
2907
                $links .= '<li class="'.($show == 'invite_friends' ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
2908
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2909
                if (self::canLeave($group_info)) {
2910
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2911
                        Display::return_icon('group_leave.png', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2912
                }
2913
                break;
2914
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
2915
//				$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>';
2916
                break;
2917
            case GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER:
2918
                $relation_group_title = get_lang('WaitingForAdminResponse');
2919
                break;
2920
            case GROUP_USER_PERMISSION_MODERATOR:
2921
                $relation_group_title = get_lang('IAmAModerator');
2922
                //$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>';
2923
                //$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>';
2924
                //$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>';
2925
                if ($group_info['visibility'] == GROUP_PERMISSION_CLOSED) {
2926
                    $links .= '<li><a href="group_waiting_list.php?id='.$group_id.'">'.
2927
                                Display::return_icon('waiting_list.png', get_lang('WaitingList')).get_lang('WaitingList').'</a></li>';
2928
                }
2929
                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
2930
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2931
                if (self::canLeave($group_info)) {
2932
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2933
                        Display::return_icon('group_leave.png', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2934
                }
2935
                break;
2936
            case GROUP_USER_PERMISSION_HRM:
2937
                $relation_group_title = get_lang('IAmAHRM');
2938
                $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').'">'.
2939
                            Display::return_icon('new-message.png', get_lang('NewTopic')).get_lang('NewTopic').'</a></li>';
2940
                $links .= '<li><a href="group_view.php?id='.$group_id.'">'.
2941
                            Display::return_icon('message_list.png', get_lang('MessageList')).get_lang('MessageList').'</a></li>';
2942
                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
2943
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends')).get_lang('InviteFriends').'</a></li>';
2944
                $links .= '<li><a href="group_members.php?id='.$group_id.'">'.
2945
                            Display::return_icon('member_list.png', get_lang('MemberList')).get_lang('MemberList').'</a></li>';
2946
                $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2947
                            Display::return_icon('delete_data.gif', get_lang('LeaveGroup')).get_lang('LeaveGroup').'</a></li>';
2948
                break;
2949
            default:
2950
                //$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>';
2951
                break;
2952
        }
2953
        if (!empty($links)) {
2954
            $list = '<ul class="nav nav-pills">';
2955
            $list .= $links;
2956
            $list .= '</ul>';
2957
            $html .= Display::panelCollapse(
2958
                get_lang('SocialGroups'),
2959
                $list,
2960
                'sm-groups',
2961
                [],
2962
                'groups-acordeon',
2963
                'groups-collapse'
2964
            );
2965
        }
2966
2967
        return $html;
2968
    }
2969
2970
    /**
2971
     * @param int $group_id
2972
     * @param int $topic_id
2973
     */
2974
    public function delete_topic($group_id, $topic_id)
2975
    {
2976
        $table_message = Database::get_main_table(TABLE_MESSAGE);
2977
        $topic_id = (int) $topic_id;
2978
        $group_id = (int) $group_id;
2979
2980
        $sql = "UPDATE $table_message SET
2981
                    msg_status = 3
2982
                WHERE
2983
                    group_id = $group_id AND
2984
                    (id = '$topic_id' OR parent_id = $topic_id)
2985
                ";
2986
        Database::query($sql);
2987
    }
2988
2989
    /**
2990
     * @param string $user_id
2991
     * @param string $relation_type
2992
     * @param bool   $with_image
2993
     *
2994
     * @deprecated
2995
     *
2996
     * @return int
2997
     */
2998
    public function get_groups_by_user_count(
2999
        $user_id = '',
3000
        $relation_type = GROUP_USER_PERMISSION_READER,
3001
        $with_image = false
3002
    ) {
3003
        $table_group_rel_user = $this->usergroup_rel_user_table;
3004
        $tbl_group = $this->table;
3005
        $user_id = intval($user_id);
3006
3007
        if ($relation_type == 0) {
3008
            $where_relation_condition = '';
3009
        } else {
3010
            $relation_type = intval($relation_type);
3011
            $where_relation_condition = "AND gu.relation_type = $relation_type ";
3012
        }
3013
3014
        $sql = "SELECT count(g.id) as count
3015
				FROM $tbl_group g
3016
				INNER JOIN $table_group_rel_user gu
3017
				ON gu.usergroup_id = g.id
3018
				WHERE gu.user_id = $user_id $where_relation_condition ";
3019
3020
        $result = Database::query($sql);
3021
        if (Database::num_rows($result) > 0) {
3022
            $row = Database::fetch_array($result, 'ASSOC');
3023
3024
            return $row['count'];
3025
        }
3026
3027
        return 0;
3028
    }
3029
3030
    /**
3031
     * @param string $tag
3032
     * @param int    $from
3033
     * @param int    $number_of_items
3034
     *
3035
     * @return array
3036
     */
3037
    public function get_all_group_tags($tag = '', $from = 0, $number_of_items = 10, $getCount = false)
3038
    {
3039
        $group_table = $this->table;
3040
        $tag = Database::escape_string($tag);
3041
        $from = (int) $from;
3042
        $number_of_items = (int) $number_of_items;
3043
        $return = [];
3044
3045
        $keyword = $tag;
3046
        $sql = 'SELECT  g.id, g.name, g.description, g.url, g.picture ';
3047
        $urlCondition = '';
3048
        if ($this->getUseMultipleUrl()) {
3049
            $urlId = api_get_current_access_url_id();
3050
            $sql .= " FROM $this->table g
3051
                    INNER JOIN $this->access_url_rel_usergroup a
3052
                    ON (g.id = a.usergroup_id)";
3053
            $urlCondition = " AND access_url_id = $urlId ";
3054
        } else {
3055
            $sql .= " FROM $group_table g";
3056
        }
3057
        if (isset($keyword)) {
3058
            $sql .= " WHERE (
3059
                        g.name LIKE '%".$keyword."%' OR
3060
                        g.description LIKE '%".$keyword."%' OR
3061
                        g.url LIKE '%".$keyword."%'
3062
                     ) $urlCondition
3063
                     ";
3064
        } else {
3065
            $sql .= " WHERE 1 = 1 $urlCondition ";
3066
        }
3067
3068
        $direction = 'ASC';
3069
        if (!in_array($direction, ['ASC', 'DESC'])) {
3070
            $direction = 'ASC';
3071
        }
3072
3073
        $from = (int) $from;
3074
        $number_of_items = (int) $number_of_items;
3075
        $sql .= " LIMIT $from, $number_of_items";
3076
3077
        $res = Database::query($sql);
3078
        if (Database::num_rows($res) > 0) {
3079
            while ($row = Database::fetch_array($res, 'ASSOC')) {
3080
                if (!in_array($row['id'], $return)) {
3081
                    $return[$row['id']] = $row;
3082
                }
3083
            }
3084
        }
3085
3086
        return $return;
3087
    }
3088
3089
    /**
3090
     * @param int $group_id
3091
     *
3092
     * @return array
3093
     */
3094
    public static function get_parent_groups($group_id)
3095
    {
3096
        $t_rel_group = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
3097
        $group_id = (int) $group_id;
3098
3099
        $max_level = 10;
3100
        $select_part = 'SELECT ';
3101
        $cond_part = '';
3102
        for ($i = 1; $i <= $max_level; $i++) {
3103
            $rg_number = $i - 1;
3104
            if ($i == $max_level) {
3105
                $select_part .= "rg$rg_number.group_id as id_$rg_number ";
3106
            } else {
3107
                $select_part .= "rg$rg_number.group_id as id_$rg_number, ";
3108
            }
3109
            if ($i == 1) {
3110
                $cond_part .= "FROM $t_rel_group rg0
3111
                               LEFT JOIN $t_rel_group rg$i
3112
                               ON rg$rg_number.group_id = rg$i.subgroup_id ";
3113
            } else {
3114
                $cond_part .= " LEFT JOIN $t_rel_group rg$i
3115
                                ON rg$rg_number.group_id = rg$i.subgroup_id ";
3116
            }
3117
        }
3118
        $sql = $select_part.' '.$cond_part."WHERE rg0.subgroup_id='$group_id'";
3119
        $res = Database::query($sql);
3120
        $temp_arr = Database::fetch_array($res, 'NUM');
3121
        $toReturn = [];
3122
        if (is_array($temp_arr)) {
3123
            foreach ($temp_arr as $elt) {
3124
                if (isset($elt)) {
3125
                    $toReturn[] = $elt;
3126
                }
3127
            }
3128
        }
3129
3130
        return $toReturn;
3131
    }
3132
3133
    /**
3134
     * Get the group member list by a user and his group role.
3135
     *
3136
     * @param int  $userId                The user ID
3137
     * @param int  $relationType          Optional. The relation type. GROUP_USER_PERMISSION_ADMIN by default
3138
     * @param bool $includeSubgroupsUsers Optional. Whether include the users from subgroups
3139
     *
3140
     * @return array
3141
     */
3142
    public function getGroupUsersByUser(
3143
        $userId,
3144
        $relationType = GROUP_USER_PERMISSION_ADMIN,
3145
        $includeSubgroupsUsers = true
3146
    ) {
3147
        $userId = (int) $userId;
3148
        $groups = $this->get_groups_by_user($userId, $relationType);
3149
        $groupsId = array_keys($groups);
3150
        $subgroupsId = [];
3151
        $userIdList = [];
3152
3153
        if ($includeSubgroupsUsers) {
3154
            foreach ($groupsId as $groupId) {
3155
                $subgroupsId = array_merge($subgroupsId, self::getGroupsByDepthLevel($groupId));
3156
            }
3157
3158
            $groupsId = array_merge($groupsId, $subgroupsId);
3159
        }
3160
3161
        $groupsId = array_unique($groupsId);
3162
3163
        if (empty($groupsId)) {
3164
            return [];
3165
        }
3166
3167
        foreach ($groupsId as $groupId) {
3168
            $groupUsers = $this->get_users_by_group($groupId);
3169
3170
            if (empty($groupUsers)) {
3171
                continue;
3172
            }
3173
3174
            foreach ($groupUsers as $member) {
3175
                if ($member['user_id'] == $userId) {
3176
                    continue;
3177
                }
3178
3179
                $userIdList[] = (int) $member['user_id'];
3180
            }
3181
        }
3182
3183
        return array_unique($userIdList);
3184
    }
3185
3186
    /**
3187
     * Get the subgroups ID from a group.
3188
     * The default $levels value is 10 considering it as a extensive level of depth.
3189
     *
3190
     * @param int $groupId The parent group ID
3191
     * @param int $levels  The depth levels
3192
     *
3193
     * @return array The list of ID
3194
     */
3195
    public static function getGroupsByDepthLevel($groupId, $levels = 10)
3196
    {
3197
        $groups = [];
3198
        $groupId = (int) $groupId;
3199
3200
        $groupTable = Database::get_main_table(TABLE_USERGROUP);
3201
        $groupRelGroupTable = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
3202
3203
        $select = 'SELECT ';
3204
        $from = "FROM $groupTable g1 ";
3205
3206
        for ($i = 1; $i <= $levels; $i++) {
3207
            $tableIndexNumber = $i;
3208
            $tableIndexJoinNumber = $i - 1;
3209
            $select .= "g$i.id as id_$i ";
3210
            $select .= $i != $levels ? ', ' : null;
3211
3212
            if ($i == 1) {
3213
                $from .= " INNER JOIN $groupRelGroupTable gg0
3214
                           ON g1.id = gg0.subgroup_id and gg0.group_id = $groupId ";
3215
            } else {
3216
                $from .= "LEFT JOIN $groupRelGroupTable gg$tableIndexJoinNumber ";
3217
                $from .= " ON g$tableIndexJoinNumber.id = gg$tableIndexJoinNumber.group_id ";
3218
                $from .= "LEFT JOIN $groupTable g$tableIndexNumber ";
3219
                $from .= " ON gg$tableIndexJoinNumber.subgroup_id = g$tableIndexNumber.id ";
3220
            }
3221
        }
3222
3223
        $result = Database::query("$select $from");
3224
3225
        while ($item = Database::fetch_assoc($result)) {
3226
            foreach ($item as $myGroupId) {
3227
                if (!empty($myGroupId)) {
3228
                    $groups[] = $myGroupId;
3229
                }
3230
            }
3231
        }
3232
3233
        return array_map('intval', $groups);
3234
    }
3235
3236
    /**
3237
     * Set a parent group.
3238
     *
3239
     * @param int $group_id
3240
     * @param int $parent_group_id if 0, we delete the parent_group association
3241
     * @param int $relation_type
3242
     *
3243
     * @return \Doctrine\DBAL\Statement
3244
     */
3245
    public function setParentGroup($group_id, $parent_group_id, $relation_type = 1)
3246
    {
3247
        $table = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
3248
        $group_id = (int) $group_id;
3249
        $parent_group_id = (int) $parent_group_id;
3250
        if ($parent_group_id == 0) {
3251
            $sql = "DELETE FROM $table WHERE subgroup_id = $group_id";
3252
        } else {
3253
            $sql = "SELECT group_id FROM $table WHERE subgroup_id = $group_id";
3254
            $res = Database::query($sql);
3255
            if (Database::num_rows($res) == 0) {
3256
                $sql = "INSERT INTO $table SET
3257
                        group_id = $parent_group_id,
3258
                        subgroup_id = $group_id,
3259
                        relation_type = $relation_type";
3260
            } else {
3261
                $sql = "UPDATE $table SET
3262
                        group_id = $parent_group_id,
3263
                        relation_type = $relation_type
3264
                        WHERE subgroup_id = $group_id";
3265
            }
3266
        }
3267
        $res = Database::query($sql);
3268
3269
        return $res;
3270
    }
3271
3272
    /**
3273
     * Filter the groups/classes info to get a name list only.
3274
     *
3275
     * @param int $userId       The user ID
3276
     * @param int $filterByType Optional. The type of group
3277
     *
3278
     * @return array
3279
     */
3280
    public function getNameListByUser($userId, $filterByType = null)
3281
    {
3282
        $userClasses = $this->getUserGroupListByUser($userId, $filterByType);
3283
3284
        return array_column($userClasses, 'name');
3285
    }
3286
3287
    /**
3288
     * Get the HTML necessary for display the groups/classes name list.
3289
     *
3290
     * @param int $userId       The user ID
3291
     * @param int $filterByType Optional. The type of group
3292
     *
3293
     * @return string
3294
     */
3295
    public function getLabelsFromNameList($userId, $filterByType = null)
3296
    {
3297
        $groupsNameListParsed = $this->getNameListByUser($userId, $filterByType);
3298
3299
        if (empty($groupsNameListParsed)) {
3300
            return '';
3301
        }
3302
3303
        $nameList = '<ul class="list-unstyled">';
3304
        foreach ($groupsNameListParsed as $name) {
3305
            $nameList .= '<li>'.Display::span($name, ['class' => 'label label-info']).'</li>';
3306
        }
3307
3308
        $nameList .= '</ul>';
3309
3310
        return $nameList;
3311
    }
3312
3313
    /**
3314
     * @param array $groupInfo
3315
     *
3316
     * @return bool
3317
     */
3318
    public static function canLeave($groupInfo)
3319
    {
3320
        return $groupInfo['allow_members_leave_group'] == 1 ? true : false;
3321
    }
3322
3323
    /**
3324
     * Check permissions and blocks the page.
3325
     *
3326
     * @param array $userGroupInfo
3327
     * @param bool  $checkAuthor
3328
     * @param bool  $checkCourseIsAllow
3329
     */
3330
    public function protectScript($userGroupInfo = [], $checkAuthor = true, $checkCourseIsAllow = false)
3331
    {
3332
        api_block_anonymous_users();
3333
3334
        if (api_is_platform_admin()) {
3335
            return true;
3336
        }
3337
3338
        if ($checkCourseIsAllow) {
3339
            if (api_is_allowed_to_edit()) {
3340
                return true;
3341
            }
3342
        }
3343
3344
        if ($this->allowTeachers() && api_is_teacher()) {
3345
            if ($checkAuthor && !empty($userGroupInfo)) {
3346
                if (isset($userGroupInfo['author_id']) && $userGroupInfo['author_id'] != api_get_user_id()) {
3347
                    api_not_allowed(true);
3348
                }
3349
            }
3350
3351
            return true;
3352
        } else {
3353
            api_protect_admin_script(true);
3354
            api_protect_limit_for_session_admin();
3355
        }
3356
    }
3357
3358
    public function getGroupsByLp($lpId, $courseId, $sessionId)
3359
    {
3360
        $lpId = (int) $lpId;
3361
        $courseId = (int) $courseId;
3362
        $sessionId = (int) $sessionId;
3363
        $sessionCondition = api_get_session_condition($sessionId, true);
3364
        $table = Database::get_course_table(TABLE_LP_REL_USERGROUP);
3365
        $sql = "SELECT usergroup_id FROM $table
3366
                WHERE
3367
                    c_id = $courseId AND
3368
                    lp_id = $lpId
3369
                    $sessionCondition
3370
                    ";
3371
        $result = Database::query($sql);
3372
3373
        return Database::store_result($result, 'ASSOC');
3374
    }
3375
3376
    public function getGroupsByLpCategory($categoryId, $courseId, $sessionId)
3377
    {
3378
        $categoryId = (int) $categoryId;
3379
        $courseId = (int) $courseId;
3380
        $sessionId = (int) $sessionId;
3381
        $sessionCondition = api_get_session_condition($sessionId, true);
3382
3383
        $table = Database::get_course_table(TABLE_LP_CATEGORY_REL_USERGROUP);
3384
        $sql = "SELECT usergroup_id FROM $table
3385
                WHERE
3386
                    c_id = $courseId AND
3387
                    lp_category_id = $categoryId
3388
                    $sessionCondition
3389
                ";
3390
        $result = Database::query($sql);
3391
3392
        return Database::store_result($result, 'ASSOC');
3393
    }
3394
}
3395