Passed
Pull Request — master (#6352)
by
unknown
08:16
created

UserGroupModel::getGroupsByLpCategory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

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