Passed
Push — master ( 56ef21...f90fc8 )
by
unknown
07:53 queued 16s
created

UserGroupModel::getAllUserGroups()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 3
nc 1
nop 0
dl 0
loc 7
rs 10
c 1
b 0
f 0
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
    public function getUserGroupNotInList(array $list, int $accessUrlId): array
1519
    {
1520
        $params = [];
1521
1522
        $sql = "SELECT g.*
1523
            FROM {$this->table} g";
1524
1525
        if ($this->getUseMultipleUrl()) {
1526
            $sql .= " LEFT JOIN {$this->access_url_rel_usergroup} a
1527
                  ON (g.id = a.usergroup_id AND a.access_url_id = ?)";
1528
            $params[] = $accessUrlId;
1529
            $sql .= " WHERE a.usergroup_id IS NULL";
1530
        } else {
1531
            $sql .= " WHERE 1=1";
1532
        }
1533
1534
        if (!empty($list)) {
1535
            $placeholders = implode(',', array_fill(0, count($list), '?'));
1536
            $sql .= " AND g.id NOT IN ($placeholders)";
1537
            $params = array_merge($params, array_map('intval', $list));
1538
        }
1539
1540
        $sql .= " ORDER BY g.title";
1541
1542
        $stmt = Database::getManager()->getConnection()->executeQuery($sql, $params);
1543
1544
        return Database::store_result($stmt, 'ASSOC');
1545
    }
1546
1547
    /**
1548
     * @param $params
1549
     * @param bool $showQuery
1550
     *
1551
     * @return bool|int
1552
     */
1553
    public function save($params, $showQuery = false)
1554
    {
1555
        $params['updated_at'] = $params['created_at'] = api_get_utc_datetime();
1556
        $params['group_type'] = isset($params['group_type']) ? Usergroup::SOCIAL_CLASS : Usergroup::NORMAL_CLASS;
1557
        $params['allow_members_leave_group'] = isset($params['allow_members_leave_group']) ? 1 : 0;
1558
        $params['url'] = isset($params['url']) ? $params['url'] : "";
1559
        $params['visibility'] = isset($params['visibility']) ? $params['visibility'] : Usergroup::GROUP_PERMISSION_OPEN;
1560
1561
        $userGroupExists = $this->usergroup_exists(trim($params['title']));
1562
        if (false === $userGroupExists) {
1563
            $userGroup = new Usergroup();
1564
            $repo = Container::getUsergroupRepository();
1565
            $userGroup
1566
                ->setTitle(trim($params['title']))
1567
                ->setDescription($params['description'])
1568
                ->setUrl($params['url'])
1569
                ->setVisibility($params['visibility'])
1570
                ->setGroupType($params['group_type'])
1571
                ->setAllowMembersToLeaveGroup($params['allow_members_leave_group'])
1572
            ;
1573
            if ($this->allowTeachers()) {
1574
                $userGroup->setAuthorId(api_get_user_id());
1575
            }
1576
1577
            $repo->create($userGroup);
1578
1579
            $id = $userGroup->getId();
1580
            if ($id) {
1581
                if ($this->getUseMultipleUrl()) {
1582
                    $this->subscribeToUrl($id, api_get_current_access_url_id());
1583
                }
1584
1585
                if (Usergroup::SOCIAL_CLASS == $params['group_type']) {
1586
                    $this->add_user_to_group(
1587
                        api_get_user_id(),
1588
                        $id,
1589
                        $params['group_type']
1590
                    );
1591
                }
1592
                $request = Container::getRequest();
1593
                $file = $request->files->get('picture');
1594
                if (null !== $file) {
1595
                    $this->manageFileUpload($userGroup, $file);
1596
                }
1597
            }
1598
1599
            return $id;
1600
        }
1601
1602
        return false;
1603
    }
1604
1605
    public function update($params, $showQuery = false): bool
1606
    {
1607
        $em = Database::getManager();
1608
        $repo = Container::getUsergroupRepository();
1609
        /** @var Usergroup $userGroup */
1610
        $userGroup = $repo->find($params['id']);
1611
        if (null === $userGroup) {
1612
            return false;
1613
        }
1614
1615
        if (isset($params['title'])) {
1616
            $userGroup->setTitle($params['title']);
1617
        }
1618
1619
        if (isset($params['description'])) {
1620
            $userGroup->setDescription($params['description']);
1621
        }
1622
1623
        if (isset($params['visibility'])) {
1624
            $userGroup->setVisibility($params['visibility']);
1625
        }
1626
1627
        if (isset($params['url'])) {
1628
            $userGroup->setUrl($params['url']);
1629
        }
1630
1631
        $userGroup
1632
            ->setGroupType(isset($params['group_type']) ? Usergroup::SOCIAL_CLASS : Usergroup::NORMAL_CLASS)
1633
            ->setAllowMembersToLeaveGroup(isset($params['allow_members_leave_group']) ? 1 : 0)
1634
        ;
1635
        $cropImage = $params['picture_crop_result'] ?? null;
1636
        $picture = $_FILES['picture'] ?? null;
1637
        if (!empty($picture)) {
1638
            $request = Container::getRequest();
1639
            $file = $request->files->get('picture');
1640
            if (null !== $file) {
1641
                $this->manageFileUpload($userGroup, $file, $cropImage);
1642
            }
1643
        }
1644
1645
        $em->persist($userGroup);
1646
        $em->flush();
1647
1648
        if (isset($params['delete_picture'])) {
1649
            $this->delete_group_picture($params['id']);
1650
        }
1651
1652
        return true;
1653
    }
1654
1655
    public function manageFileUpload(
1656
        Usergroup $userGroup,
1657
        UploadedFile $picture,
1658
        string $cropParameters = ''
1659
    ): ?ResourceFile {
1660
        $illustrationRepo = Container::getIllustrationRepository();
1661
1662
        return $illustrationRepo->addIllustration($userGroup, api_get_user_entity(), $picture, $cropParameters);
1663
    }
1664
1665
    /**
1666
     * @param int $groupId
1667
     *
1668
     * @return string
1669
     */
1670
    public function delete_group_picture($groupId)
1671
    {
1672
        $repo = Container::getUsergroupRepository();
1673
        $userGroup = $repo->find($groupId);
1674
        if ($userGroup) {
1675
            $illustrationRepo = Container::getIllustrationRepository();
1676
            $illustrationRepo->deleteIllustration($userGroup);
1677
        }
1678
    }
1679
1680
    /**
1681
     * @return mixed
1682
     */
1683
    public function getGroupType()
1684
    {
1685
        return $this->groupType;
1686
    }
1687
1688
    /**
1689
     * @param int $id
1690
     *
1691
     * @return bool|void
1692
     */
1693
    public function delete($id)
1694
    {
1695
        $id = (int) $id;
1696
        if ($this->getUseMultipleUrl()) {
1697
            $this->unsubscribeToUrl($id, api_get_current_access_url_id());
1698
        }
1699
1700
        $sql = "DELETE FROM $this->usergroup_rel_user_table
1701
                WHERE usergroup_id = $id";
1702
        Database::query($sql);
1703
1704
        $sql = "DELETE FROM $this->usergroup_rel_course_table
1705
                WHERE usergroup_id = $id";
1706
        Database::query($sql);
1707
1708
        $sql = "DELETE FROM $this->usergroup_rel_session_table
1709
                WHERE usergroup_id = $id";
1710
        Database::query($sql);
1711
1712
        $repo = Container::getUsergroupRepository();
1713
        $userGroup = $repo->find($id);
1714
        $repo->delete($userGroup);
1715
    }
1716
1717
    /**
1718
     * @param int $id
1719
     * @param int $urlId
1720
     */
1721
    public function subscribeToUrl($id, $urlId)
1722
    {
1723
        Database::insert(
1724
            $this->access_url_rel_usergroup,
1725
            [
1726
                'access_url_id' => $urlId,
1727
                'usergroup_id' => $id,
1728
            ]
1729
        );
1730
    }
1731
1732
    /**
1733
     * @param int $id
1734
     * @param int $urlId
1735
     */
1736
    public function unsubscribeToUrl($id, $urlId)
1737
    {
1738
        Database::delete(
1739
            $this->access_url_rel_usergroup,
1740
            [
1741
                'access_url_id = ? AND usergroup_id = ? ' => [$urlId, $id],
1742
            ]
1743
        );
1744
    }
1745
1746
    /**
1747
     * @param $needle
1748
     *
1749
     * @return xajaxResponse
1750
     */
1751
    public static function searchUserGroupAjax($needle)
1752
    {
1753
        $response = new xajaxResponse();
1754
        $return = '';
1755
1756
        if (!empty($needle)) {
1757
            // xajax send utf8 datas... datas in db can be non-utf8 datas
1758
            $charset = api_get_system_encoding();
1759
            $needle = api_convert_encoding($needle, $charset, 'utf-8');
1760
            $needle = Database::escape_string($needle);
1761
1762
            $sql = 'SELECT id, title
1763
                    FROM '.Database::get_main_table(TABLE_USERGROUP).' u
1764
                    WHERE title LIKE "'.$needle.'%"
1765
                    ORDER BY title
1766
                    LIMIT 11';
1767
            $result = Database::query($sql);
1768
            $i = 0;
1769
            while ($data = Database::fetch_array($result)) {
1770
                $i++;
1771
                if ($i <= 10) {
1772
                    $return .= '<a
1773
                    href="javascript: void(0);"
1774
                    onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['title']).' \')">'.$data['title'].' </a><br />';
1775
                } else {
1776
                    $return .= '...<br />';
1777
                }
1778
            }
1779
        }
1780
        $response->addAssign('ajax_list_courses', 'innerHTML', api_utf8_encode($return));
1781
1782
        return $response;
1783
    }
1784
1785
    /**
1786
     * Get user list by usergroup.
1787
     *
1788
     * @param int    $id
1789
     * @param string $orderBy
1790
     *
1791
     * @return array
1792
     */
1793
    public function getUserListByUserGroup($id, $orderBy = '')
1794
    {
1795
        $id = (int) $id;
1796
        $sql = "SELECT u.* FROM $this->table_user u
1797
                INNER JOIN $this->usergroup_rel_user_table c
1798
                ON c.user_id = u.id
1799
                WHERE u.active <> ".USER_SOFT_DELETED." AND c.usergroup_id = $id"
1800
                ;
1801
        if (!empty($orderBy)) {
1802
            $orderBy = Database::escape_string($orderBy);
1803
            $sql .= " ORDER BY $orderBy ";
1804
        }
1805
        $result = Database::query($sql);
1806
1807
        return Database::store_result($result);
1808
    }
1809
1810
    /**
1811
     * @param FormValidator $form
1812
     * @param string        $type
1813
     */
1814
    public function setForm($form, $type = 'add', Usergroup $userGroup = null)
1815
    {
1816
        $header = '';
1817
        switch ($type) {
1818
            case 'add':
1819
                $header = get_lang('Add');
1820
                break;
1821
            case 'edit':
1822
                $header = get_lang('Edit');
1823
                break;
1824
        }
1825
1826
        $form->addHeader($header);
1827
1828
        // Name
1829
        $form->addText('title', get_lang('Title'), true, ['maxlength' => 255]);
1830
        $form->addRule('title', '', 'maxlength', 255);
1831
1832
        // Description
1833
        $form->addHtmlEditor(
1834
            'description',
1835
            get_lang('Description'),
1836
            true,
1837
            false,
1838
            [
1839
            'ToolbarSet' => 'Minimal',
1840
            ]
1841
        );
1842
        $form->applyFilter('description', 'trim');
1843
1844
        if ($this->showGroupTypeSetting) {
1845
            $form->addElement(
1846
                'checkbox',
1847
                'group_type',
1848
                null,
1849
                get_lang('Social group')
1850
            );
1851
        }
1852
1853
        // url
1854
        $form->addText('url', get_lang('Url'), false);
1855
1856
        // Picture
1857
        //$allowed_picture_types = $this->getAllowedPictureExtensions();
1858
1859
        // Picture
1860
        $form->addFile(
1861
            'picture',
1862
            get_lang('Add a picture'),
1863
            ['id' => 'picture', 'class' => 'picture-form', 'crop_image' => true, 'crop_ratio' => '1 / 1']
1864
        );
1865
1866
        $repo = Container::getIllustrationRepository();
1867
        if ($userGroup && $repo->hasIllustration($userGroup)) {
1868
            $picture = $repo->getIllustrationUrl($userGroup);
1869
            $img = '<img src="'.$picture.'" />';
1870
            $form->addLabel(null, $img);
1871
            $form->addElement('checkbox', 'delete_picture', '', get_lang('Remove picture'));
1872
        }
1873
1874
        $form->addSelect('visibility', get_lang('Group Permissions'), $this->getGroupStatusList());
1875
        $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('Required field').'</small>');
1876
        $form->addElement('checkbox', 'allow_members_leave_group', '', get_lang('Allow members to leave group'));
1877
1878
        // Setting the form elements
1879
        if ('add' === $type) {
1880
            $form->addButtonCreate($header);
1881
        } else {
1882
            $form->addButtonUpdate($header);
1883
        }
1884
    }
1885
1886
    /**
1887
     * Gets the current group image.
1888
     *
1889
     * @param string $id group id
1890
     * @param string picture group name
1891
     * @param string height
1892
     * @param int $size_picture picture size it can be small_,  medium_  or  big_
1893
     * @param string style css
1894
     *
1895
     * @return string
1896
     */
1897
    public function get_picture_group(
1898
        $id,
1899
        $picture_file,
1900
        $height,
1901
        $size_picture = GROUP_IMAGE_SIZE_MEDIUM,
1902
        $style = ''
1903
    ) {
1904
        $repoIllustration = Container::getIllustrationRepository();
1905
        $repoUserGroup = Container::getUsergroupRepository();
1906
        $userGroup = $repoUserGroup->find($id);
1907
1908
        return $repoIllustration->getIllustrationUrl($userGroup);
1909
1910
        /*
1911
        $picture = [];
1912
        //$picture['style'] = $style;
1913
        if ('unknown.jpg' === $picture_file) {
1914
            $picture['file'] = Display::returnIconPath($picture_file);
1915
1916
            return $picture;
1917
        }
1918
1919
        switch ($size_picture) {
1920
            case GROUP_IMAGE_SIZE_ORIGINAL:
1921
                $size_picture = '';
1922
                break;
1923
            case GROUP_IMAGE_SIZE_BIG:
1924
                $size_picture = 'big_';
1925
                break;
1926
            case GROUP_IMAGE_SIZE_MEDIUM:
1927
                $size_picture = 'medium_';
1928
                break;
1929
            case GROUP_IMAGE_SIZE_SMALL:
1930
                $size_picture = 'small_';
1931
                break;
1932
            default:
1933
                $size_picture = 'medium_';
1934
        }
1935
1936
        $image_array_sys = $this->get_group_picture_path_by_id($id, 'system', false, true);
1937
        $image_array = $this->get_group_picture_path_by_id($id, 'web', false, true);
1938
        $file = $image_array_sys['dir'].$size_picture.$picture_file;
1939
        if (file_exists($file)) {
1940
            $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
1941
            //$picture['style'] = '';
1942
            if ($height > 0) {
1943
                $dimension = api_getimagesize($picture['file']);
1944
                $margin = ($height - $dimension['width']) / 2;
1945
                //@ todo the padding-top should not be here
1946
            }
1947
        } else {
1948
            $file = $image_array_sys['dir'].$picture_file;
1949
            if (file_exists($file) && !is_dir($file)) {
1950
                $picture['file'] = $image_array['dir'].$picture_file;
1951
            } else {
1952
                $picture['file'] = Display::returnIconPath('group_na.png', 64);
1953
            }
1954
        }
1955
1956
        return $picture;*/
1957
    }
1958
1959
    /**
1960
     * @return array
1961
     */
1962
    public function getAllowedPictureExtensions()
1963
    {
1964
        return ['jpg', 'jpeg', 'png', 'gif'];
1965
    }
1966
1967
    public function getGroupStatusList(): array
1968
    {
1969
        return [
1970
            GROUP_PERMISSION_OPEN => get_lang('Open'),
1971
            GROUP_PERMISSION_CLOSED => get_lang('Closed'),
1972
        ];
1973
    }
1974
1975
    /**
1976
     * @param int $type
1977
     */
1978
    public function setGroupType($type)
1979
    {
1980
        $this->groupType = (int) $type;
1981
    }
1982
1983
    /**
1984
     * @param int $group_id
1985
     * @param int $user_id
1986
     *
1987
     * @return bool
1988
     */
1989
    public function is_group_admin($group_id, $user_id = 0)
1990
    {
1991
        if (empty($user_id)) {
1992
            $user_id = api_get_user_id();
1993
        }
1994
        $user_role = $this->get_user_group_role($user_id, $group_id);
1995
        if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN])) {
1996
            return true;
1997
        }
1998
1999
        return false;
2000
    }
2001
2002
    /**
2003
     * @param int $group_id
2004
     * @param int $user_id
2005
     *
2006
     * @return bool
2007
     */
2008
    public function isGroupModerator($group_id, $user_id = 0)
2009
    {
2010
        if (empty($user_id)) {
2011
            $user_id = api_get_user_id();
2012
        }
2013
        $user_role = $this->get_user_group_role($user_id, $group_id);
2014
        if (in_array($user_role, [GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR])) {
2015
            return true;
2016
        } else {
2017
            return false;
2018
        }
2019
    }
2020
2021
    /**
2022
     * @param int $group_id
2023
     * @param int $user_id
2024
     *
2025
     * @return bool
2026
     */
2027
    public function is_group_member($group_id, $user_id = 0)
2028
    {
2029
        if (api_is_platform_admin()) {
2030
            return true;
2031
        }
2032
        if (empty($user_id)) {
2033
            $user_id = api_get_user_id();
2034
        }
2035
        $roles = [
2036
            GROUP_USER_PERMISSION_ADMIN,
2037
            GROUP_USER_PERMISSION_MODERATOR,
2038
            GROUP_USER_PERMISSION_READER,
2039
            GROUP_USER_PERMISSION_HRM,
2040
        ];
2041
        $user_role = $this->get_user_group_role($user_id, $group_id);
2042
        if (in_array($user_role, $roles)) {
2043
            return true;
2044
        } else {
2045
            return false;
2046
        }
2047
    }
2048
2049
    /**
2050
     * Gets the relationship between a group and a User.
2051
     *
2052
     * @author Julio Montoya
2053
     *
2054
     * @param int $user_id
2055
     * @param int $group_id
2056
     *
2057
     * @return int 0 if there are not relationship otherwise returns the user group
2058
     * */
2059
    public function get_user_group_role($user_id, $group_id)
2060
    {
2061
        $table_group_rel_user = $this->usergroup_rel_user_table;
2062
        $return_value = 0;
2063
        $user_id = (int) $user_id;
2064
        $group_id = (int) $group_id;
2065
2066
        if (!empty($user_id) && !empty($group_id)) {
2067
            $sql = "SELECT relation_type
2068
                    FROM $table_group_rel_user
2069
                    WHERE
2070
                        usergroup_id = $group_id AND
2071
                        user_id = $user_id ";
2072
            $result = Database::query($sql);
2073
            if (Database::num_rows($result) > 0) {
2074
                $row = Database::fetch_assoc($result);
2075
                $return_value = $row['relation_type'];
2076
            }
2077
        }
2078
2079
        return $return_value;
2080
    }
2081
2082
    /**
2083
     * @param int $userId
2084
     * @param int $groupId
2085
     *
2086
     * @return string
2087
     */
2088
    public function getUserRoleToString($userId, $groupId)
2089
    {
2090
        $role = $this->get_user_group_role($userId, $groupId);
2091
        $roleToString = '';
2092
2093
        switch ($role) {
2094
            case GROUP_USER_PERMISSION_ADMIN:
2095
                $roleToString = get_lang('Admin');
2096
                break;
2097
            case GROUP_USER_PERMISSION_READER:
2098
                $roleToString = get_lang('Reader');
2099
                break;
2100
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
2101
                $roleToString = get_lang('Pending invitation');
2102
                break;
2103
            case GROUP_USER_PERMISSION_MODERATOR:
2104
                $roleToString = get_lang('Moderator');
2105
                break;
2106
            case GROUP_USER_PERMISSION_HRM:
2107
                $roleToString = get_lang('Human Resources Manager');
2108
                break;
2109
        }
2110
2111
        return $roleToString;
2112
    }
2113
2114
    /**
2115
     * Add a group of users into a group of URLs.
2116
     *
2117
     * @author Julio Montoya
2118
     *
2119
     * @param array $user_list
2120
     * @param array $group_list
2121
     * @param int   $relation_type
2122
     *
2123
     * @return array
2124
     */
2125
    public function add_users_to_groups($user_list, $group_list, $relation_type = GROUP_USER_PERMISSION_READER)
2126
    {
2127
        $table_url_rel_group = $this->usergroup_rel_user_table;
2128
        $result_array = [];
2129
        $relation_type = (int) $relation_type;
2130
2131
        if (is_array($user_list) && is_array($group_list)) {
2132
            foreach ($group_list as $group_id) {
2133
                foreach ($user_list as $user_id) {
2134
                    $user_id = (int) $user_id;
2135
                    $group_id = (int) $group_id;
2136
2137
                    $role = $this->get_user_group_role($user_id, $group_id);
2138
                    if (0 == $role) {
2139
                        $sql = "INSERT INTO $table_url_rel_group
2140
		               			SET
2141
		               			    user_id = $user_id ,
2142
		               			    usergroup_id = $group_id ,
2143
		               			    relation_type = $relation_type ";
2144
2145
                        $result = Database::query($sql);
2146
                        if ($result) {
2147
                            $result_array[$group_id][$user_id] = 1;
2148
                        } else {
2149
                            $result_array[$group_id][$user_id] = 0;
2150
                        }
2151
                    }
2152
                }
2153
            }
2154
        }
2155
2156
        return $result_array;
2157
    }
2158
2159
    /**
2160
     * Deletes an url and session relationship.
2161
     *
2162
     * @author Julio Montoya
2163
     *
2164
     * @param int $userId
2165
     * @param int $groupId
2166
     *
2167
     * @return bool true if success
2168
     * */
2169
    public function delete_user_rel_group($userId, $groupId)
2170
    {
2171
        $userId = (int) $userId;
2172
        $groupId = (int) $groupId;
2173
        if (empty($userId) || empty($groupId)) {
2174
            return false;
2175
        }
2176
2177
        $table = $this->usergroup_rel_user_table;
2178
        $sql = "DELETE FROM $table
2179
                WHERE
2180
                    user_id = $userId AND
2181
                    usergroup_id = $groupId";
2182
2183
        $result = Database::query($sql);
2184
2185
        return $result;
2186
    }
2187
2188
    /**
2189
     * Add a user into a group.
2190
     *
2191
     * @author Julio Montoya
2192
     *
2193
     * @param int $user_id
2194
     * @param int $group_id
2195
     * @param int $relation_type
2196
     *
2197
     * @return bool true if success
2198
     */
2199
    public function add_user_to_group($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
2200
    {
2201
        $table_url_rel_group = $this->usergroup_rel_user_table;
2202
        if (!empty($user_id) && !empty($group_id)) {
2203
            $role = $this->get_user_group_role($user_id, $group_id);
2204
2205
            if (0 == $role) {
2206
                $sql = "INSERT INTO $table_url_rel_group
2207
           				SET
2208
           				    user_id = ".intval($user_id).",
2209
           				    usergroup_id = ".intval($group_id).",
2210
           				    relation_type = ".intval($relation_type);
2211
                Database::query($sql);
2212
            } elseif (GROUP_USER_PERMISSION_PENDING_INVITATION == $role) {
2213
                //if somebody already invited me I can be added
2214
                self::update_user_role($user_id, $group_id, GROUP_USER_PERMISSION_READER);
2215
            }
2216
        }
2217
2218
        return true;
2219
    }
2220
2221
    /**
2222
     * Updates the group_rel_user table  with a given user and group ids.
2223
     *
2224
     * @author Julio Montoya
2225
     *
2226
     * @param int $user_id
2227
     * @param int $group_id
2228
     * @param int $relation_type
2229
     */
2230
    public function update_user_role($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
2231
    {
2232
        $table_group_rel_user = $this->usergroup_rel_user_table;
2233
        $group_id = (int) $group_id;
2234
        $user_id = (int) $user_id;
2235
        $relation_type = (int) $relation_type;
2236
2237
        $sql = "UPDATE $table_group_rel_user
2238
   				SET relation_type = $relation_type
2239
                WHERE user_id = $user_id AND usergroup_id = $group_id";
2240
        Database::query($sql);
2241
    }
2242
2243
    /**
2244
     * Gets the inner join from users and group table.
2245
     *
2246
     * @return array|int Database::store_result of the result
2247
     *
2248
     * @author Julio Montoya
2249
     * */
2250
    public function get_groups_by_user($user_id, $relationType = GROUP_USER_PERMISSION_READER, $with_image = false)
2251
    {
2252
        $table_group_rel_user = $this->usergroup_rel_user_table;
2253
        $tbl_group = $this->table;
2254
        $user_id = (int) $user_id;
2255
2256
        if (0 == $relationType) {
2257
            $relationCondition = '';
2258
        } else {
2259
            if (is_array($relationType)) {
2260
                $relationType = array_map('intval', $relationType);
2261
                $relationType = implode("','", $relationType);
2262
                $relationCondition = " AND ( gu.relation_type IN ('$relationType')) ";
2263
            } else {
2264
                $relationType = (int) $relationType;
2265
                $relationCondition = " AND gu.relation_type = $relationType ";
2266
            }
2267
        }
2268
2269
        $sql = 'SELECT
2270
                    g.picture,
2271
                    g.title,
2272
                    g.description,
2273
                    g.id ,
2274
                    gu.relation_type';
2275
2276
        $urlCondition = '';
2277
        if ($this->getUseMultipleUrl()) {
2278
            $sql .= " FROM $tbl_group g
2279
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2280
                    ON (g.id = a.usergroup_id)
2281
                    INNER JOIN $table_group_rel_user gu
2282
                    ON gu.usergroup_id = g.id";
2283
            $urlId = api_get_current_access_url_id();
2284
            $urlCondition = " AND access_url_id = $urlId ";
2285
        } else {
2286
            $sql .= " FROM $tbl_group g
2287
                    INNER JOIN $table_group_rel_user gu
2288
                    ON gu.usergroup_id = g.id";
2289
        }
2290
2291
        $sql .= " WHERE
2292
				    g.group_type = ".Usergroup::SOCIAL_CLASS." AND
2293
                    gu.user_id = $user_id
2294
                    $relationCondition
2295
                    $urlCondition
2296
                ORDER BY created_at DESC ";
2297
        $result = Database::query($sql);
2298
        $array = [];
2299
        if (Database::num_rows($result) > 0) {
2300
            while ($row = Database::fetch_assoc($result)) {
2301
                if ($with_image) {
2302
                    $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2303
                    $img = '<img src="'.$picture['file'].'" />';
2304
                    $row['picture'] = $img;
2305
                }
2306
                $array[$row['id']] = $row;
2307
            }
2308
        }
2309
2310
        return $array;
2311
    }
2312
2313
    /** Gets the inner join of users and group table.
2314
     * @param int  quantity of records
2315
     * @param bool show groups with image or not
2316
     *
2317
     * @return array with group content
2318
     *
2319
     * @author Julio Montoya
2320
     * */
2321
    public function get_groups_by_popularity($num = 6, $with_image = true)
2322
    {
2323
        $table_group_rel_user = $this->usergroup_rel_user_table;
2324
        $tbl_group = $this->table;
2325
        if (empty($num)) {
2326
            $num = 6;
2327
        } else {
2328
            $num = (int) $num;
2329
        }
2330
        // only show admins and readers
2331
        $whereCondition = " WHERE
2332
                              g.group_type = ".Usergroup::SOCIAL_CLASS." AND
2333
                              gu.relation_type IN
2334
                              ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
2335
2336
        $sql = 'SELECT DISTINCT count(user_id) as count, g.picture, g.title, g.description, g.id ';
2337
2338
        $urlCondition = '';
2339
        if ($this->getUseMultipleUrl()) {
2340
            $sql .= " FROM $tbl_group g
2341
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2342
                    ON (g.id = a.usergroup_id)
2343
                    INNER JOIN $table_group_rel_user gu
2344
                    ON gu.usergroup_id = g.id";
2345
            $urlId = api_get_current_access_url_id();
2346
            $urlCondition = " AND access_url_id = $urlId ";
2347
        } else {
2348
            $sql .= " FROM $tbl_group g
2349
                    INNER JOIN $table_group_rel_user gu
2350
                    ON gu.usergroup_id = g.id";
2351
        }
2352
2353
        $sql .= "
2354
				$whereCondition
2355
				$urlCondition
2356
				GROUP BY g.id
2357
				ORDER BY count DESC
2358
				LIMIT $num";
2359
2360
        $result = Database::query($sql);
2361
        $array = [];
2362
        while ($row = Database::fetch_assoc($result)) {
2363
            if ($with_image) {
2364
                $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2365
                $img = '<img src="'.$picture['file'].'" />';
2366
                $row['picture'] = $img;
2367
            }
2368
            if (empty($row['id'])) {
2369
                continue;
2370
            }
2371
            $array[$row['id']] = $row;
2372
        }
2373
2374
        return $array;
2375
    }
2376
2377
    /** Gets the last groups created.
2378
     * @param int  $num       quantity of records
2379
     * @param bool $withImage show groups with image or not
2380
     *
2381
     * @return array with group content
2382
     *
2383
     * @author Julio Montoya
2384
     * */
2385
    public function get_groups_by_age($num = 6, $withImage = true)
2386
    {
2387
        $table_group_rel_user = $this->usergroup_rel_user_table;
2388
        $tbl_group = $this->table;
2389
2390
        if (empty($num)) {
2391
            $num = 6;
2392
        } else {
2393
            $num = (int) $num;
2394
        }
2395
2396
        $where = " WHERE
2397
                        g.group_type = ".Usergroup::SOCIAL_CLASS." AND
2398
                        gu.relation_type IN
2399
                        ('".GROUP_USER_PERMISSION_ADMIN."' ,
2400
                        '".GROUP_USER_PERMISSION_READER."',
2401
                        '".GROUP_USER_PERMISSION_MODERATOR."',
2402
                        '".GROUP_USER_PERMISSION_HRM."')
2403
                    ";
2404
        $sql = 'SELECT DISTINCT
2405
                  count(user_id) as count,
2406
                  g.picture,
2407
                  g.title,
2408
                  g.description,
2409
                  g.id ';
2410
2411
        $urlCondition = '';
2412
        if ($this->getUseMultipleUrl()) {
2413
            $sql .= " FROM $tbl_group g
2414
                    INNER JOIN ".$this->access_url_rel_usergroup." a
2415
                    ON (g.id = a.usergroup_id)
2416
                    INNER JOIN $table_group_rel_user gu
2417
                    ON gu.usergroup_id = g.id";
2418
            $urlId = api_get_current_access_url_id();
2419
            $urlCondition = " AND access_url_id = $urlId ";
2420
        } else {
2421
            $sql .= " FROM $tbl_group g
2422
                    INNER JOIN $table_group_rel_user gu
2423
                    ON gu.usergroup_id = g.id";
2424
        }
2425
        $sql .= "
2426
                $where
2427
                $urlCondition
2428
                GROUP BY g.id
2429
                ORDER BY created_at DESC
2430
                LIMIT $num ";
2431
2432
        $result = Database::query($sql);
2433
        $array = [];
2434
        while ($row = Database::fetch_assoc($result)) {
2435
            if ($withImage) {
2436
                $picture = $this->get_picture_group($row['id'], $row['picture'], 80);
2437
                $img = '<img src="'.$picture['file'].'" />';
2438
                $row['picture'] = $img;
2439
            }
2440
            if (empty($row['id'])) {
2441
                continue;
2442
            }
2443
            $array[$row['id']] = $row;
2444
        }
2445
2446
        return $array;
2447
    }
2448
2449
    /**
2450
     * Gets the group's members.
2451
     *
2452
     * @param int group id
2453
     * @param bool show image or not of the group
2454
     * @param array list of relation type use constants
2455
     * @param int from value
2456
     * @param int limit
2457
     * @param array image configuration, i.e array('height'=>'20px', 'size'=> '20px')
2458
     *
2459
     * @return array list of users in a group
2460
     */
2461
    public function get_users_by_group(
2462
        $group_id,
2463
        $withImage = false,
2464
        $relation_type = [],
2465
        $from = null,
2466
        $limit = null,
2467
        $image_conf = ['size' => USER_IMAGE_SIZE_MEDIUM, 'height' => 80]
2468
    ) {
2469
        $table_group_rel_user = $this->usergroup_rel_user_table;
2470
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2471
        $group_id = (int) $group_id;
2472
2473
        if (empty($group_id)) {
2474
            return [];
2475
        }
2476
2477
        $limit_text = '';
2478
        if (isset($from) && isset($limit)) {
2479
            $from = (int) $from;
2480
            $limit = (int) $limit;
2481
            $limit_text = "LIMIT $from, $limit";
2482
        }
2483
2484
        if (0 == count($relation_type)) {
2485
            $where_relation_condition = '';
2486
        } else {
2487
            $new_relation_type = [];
2488
            foreach ($relation_type as $rel) {
2489
                $rel = (int) $rel;
2490
                $new_relation_type[] = "'$rel'";
2491
            }
2492
            $relation_type = implode(',', $new_relation_type);
2493
            if (!empty($relation_type)) {
2494
                $where_relation_condition = "AND gu.relation_type IN ($relation_type) ";
2495
            }
2496
        }
2497
2498
        $sql = "SELECT
2499
                    picture_uri as image,
2500
                    u.id,
2501
                    CONCAT (u.firstname,' ', u.lastname) as fullname,
2502
                    relation_type
2503
    		    FROM $tbl_user u
2504
    		    INNER JOIN $table_group_rel_user gu
2505
    			ON (gu.user_id = u.id)
2506
    			WHERE
2507
    			    u.active <> ".USER_SOFT_DELETED." AND
2508
    			    gu.usergroup_id= $group_id
2509
    			    $where_relation_condition
2510
    			ORDER BY relation_type, firstname
2511
    			$limit_text";
2512
2513
        $result = Database::query($sql);
2514
        $array = [];
2515
        while ($row = Database::fetch_assoc($result)) {
2516
            if ($withImage) {
2517
                $userInfo = api_get_user_info($row['id']);
2518
                $userPicture = UserManager::getUserPicture($row['id']);
2519
                $row['image'] = '<img src="'.$userPicture.'"  />';
2520
                $row['user_info'] = $userInfo;
2521
            }
2522
2523
            $row['user_id'] = $row['id'];
2524
            $array[$row['id']] = $row;
2525
        }
2526
2527
        return $array;
2528
    }
2529
2530
    /**
2531
     * Gets all the members of a group no matter the relationship for
2532
     * more specifications use get_users_by_group.
2533
     *
2534
     * @param int group id
2535
     *
2536
     * @return array
2537
     */
2538
    public function get_all_users_by_group($group_id)
2539
    {
2540
        $table_group_rel_user = $this->usergroup_rel_user_table;
2541
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
2542
        $group_id = (int) $group_id;
2543
2544
        if (empty($group_id)) {
2545
            return [];
2546
        }
2547
2548
        $sql = "SELECT u.id, u.firstname, u.lastname, relation_type
2549
                FROM $tbl_user u
2550
			    INNER JOIN $table_group_rel_user gu
2551
			    ON (gu.user_id = u.id)
2552
			    WHERE u.active <> ".USER_SOFT_DELETED." AND gu.usergroup_id= $group_id
2553
			    ORDER BY relation_type, firstname";
2554
2555
        $result = Database::query($sql);
2556
        $array = [];
2557
        while ($row = Database::fetch_assoc($result)) {
2558
            $array[$row['id']] = $row;
2559
        }
2560
2561
        return $array;
2562
    }
2563
2564
    /**
2565
     * Shows the left column of the group page.
2566
     *
2567
     * @param int    $group_id
2568
     * @param int    $user_id
2569
     * @param string $show
2570
     *
2571
     * @return string
2572
     */
2573
    public function show_group_column_information($group_id, $user_id, $show = '')
2574
    {
2575
        $html = '';
2576
        $group_info = $this->get($group_id);
2577
2578
        //my relation with the group is set here
2579
        $my_group_role = $this->get_user_group_role($user_id, $group_id);
2580
2581
        // Loading group permission
2582
        $links = '';
2583
        switch ($my_group_role) {
2584
            case GROUP_USER_PERMISSION_READER:
2585
                // I'm just a reader
2586
                $relation_group_title = get_lang('I am a reader');
2587
                $links .= '<li class="'.('invite_friends' == $show ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
2588
                            Display::getMdiIcon(ObjectIcon::INVITATION, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
2589
                if (self::canLeave($group_info)) {
2590
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2591
                        Display::getMdiIcon(ActionIcon::EXIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Leave group')).get_lang('Leave group').'</a></li>';
2592
                }
2593
                break;
2594
            case GROUP_USER_PERMISSION_ADMIN:
2595
                $relation_group_title = get_lang('I am an admin');
2596
                $links .= '<li class="'.('group_edit' == $show ? 'active' : '').'"><a href="group_edit.php?id='.$group_id.'">'.
2597
                            Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_MEDIUM, get_lang('Edit this group')).get_lang('Edit this group').'</a></li>';
2598
                $links .= '<li class="'.('member_list' == $show ? 'active' : '').'"><a href="group_waiting_list.php?id='.$group_id.'">'.
2599
                            Display::getMdiIcon(ObjectIcon::WAITING_LIST, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Waiting list')).get_lang('Waiting list').'</a></li>';
2600
                $links .= '<li class="'.('invite_friends' == $show ? 'active' : '').'"><a href="group_invitation.php?id='.$group_id.'">'.
2601
                            Display::getMdiIcon(ObjectIcon::INVITATION, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
2602
                if (self::canLeave($group_info)) {
2603
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2604
                        Display::getMdiIcon(ActionIcon::EXIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Leave group')).get_lang('Leave group').'</a></li>';
2605
                }
2606
                break;
2607
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
2608
//				$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>';
2609
                break;
2610
            case GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER:
2611
                $relation_group_title = get_lang('Waiting for admin response');
2612
                break;
2613
            case GROUP_USER_PERMISSION_MODERATOR:
2614
                $relation_group_title = get_lang('I am a moderator');
2615
                //$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>';
2616
                //$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>';
2617
                //$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>';
2618
                if (GROUP_PERMISSION_CLOSED == $group_info['visibility']) {
2619
                    $links .= '<li><a href="group_waiting_list.php?id='.$group_id.'">'.
2620
                                Display::getMdiIcon(ObjectIcon::WAITING_LIST, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Waiting list')).get_lang('Waiting list').'</a></li>';
2621
                }
2622
                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
2623
                            Display::getMdiIcon(ObjectIcon::INVITATION, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
2624
                if (self::canLeave($group_info)) {
2625
                    $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2626
                        Display::getMdiIcon(ActionIcon::EXIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Leave group')).get_lang('Leave group').'</a></li>';
2627
                }
2628
                break;
2629
            case GROUP_USER_PERMISSION_HRM:
2630
                $relation_group_title = get_lang('I am a human resources manager');
2631
                $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').'">'.
2632
                            Display::getMdiIcon(ActionIcon::EDIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Create thread')).get_lang('Create thread').'</a></li>';
2633
                $links .= '<li><a href="group_view.php?id='.$group_id.'">'.
2634
                            Display::getMdiIcon(ToolIcon::MESSAGE, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Messages list')).get_lang('Messages list').'</a></li>';
2635
                $links .= '<li><a href="group_invitation.php?id='.$group_id.'">'.
2636
                            Display::getMdiIcon(ObjectIcon::INVITATION, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Invite friends')).get_lang('Invite friends').'</a></li>';
2637
                $links .= '<li><a href="group_members.php?id='.$group_id.'">'.
2638
                            Display::getMdiIcon(ObjectIcon::GROUP, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Members list')).get_lang('Members list').'</a></li>';
2639
                $links .= '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2640
                            Display::getMdiIcon(ActionIcon::EXIT, 'ch-tool-icon', null, ICON_SIZE_SMALL, get_lang('Leave group')).get_lang('Leave group').'</a></li>';
2641
                break;
2642
            default:
2643
                //$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>';
2644
                break;
2645
        }
2646
        if (!empty($links)) {
2647
            $list = '<ul class="nav nav-pills">';
2648
            $list .= $links;
2649
            $list .= '</ul>';
2650
            $html .= Display::panelCollapse(
2651
                get_lang('Social groups'),
2652
                $list,
2653
                'sm-groups',
2654
                [],
2655
                'groups-acordeon',
2656
                'groups-collapse'
2657
            );
2658
        }
2659
2660
        return $html;
2661
    }
2662
2663
    /**
2664
     * @param int $group_id
2665
     * @param int $topic_id
2666
     */
2667
    public function delete_topic($group_id, $topic_id)
2668
    {
2669
        $table_message = Database::get_main_table(TABLE_MESSAGE);
2670
        $topic_id = (int) $topic_id;
2671
        $group_id = (int) $group_id;
2672
2673
        $sql = "UPDATE $table_message SET
2674
                    msg_type = 3
2675
                WHERE
2676
                    group_id = $group_id AND
2677
                    (id = '$topic_id' OR parent_id = $topic_id)
2678
                ";
2679
        Database::query($sql);
2680
    }
2681
2682
    /**
2683
     * @param string $user_id
2684
     * @param int    $relation_type
2685
     * @param bool   $with_image
2686
     *
2687
     * @deprecated
2688
     *
2689
     * @return int
2690
     */
2691
    public function get_groups_by_user_count(
2692
        $user_id = '',
2693
        $relation_type = GROUP_USER_PERMISSION_READER,
2694
        $with_image = false
2695
    ) {
2696
        $table_group_rel_user = $this->usergroup_rel_user_table;
2697
        $tbl_group = $this->table;
2698
        $user_id = (int) $user_id;
2699
2700
        if (0 == $relation_type) {
2701
            $where_relation_condition = '';
2702
        } else {
2703
            $relation_type = (int) $relation_type;
2704
            $where_relation_condition = "AND gu.relation_type = $relation_type ";
2705
        }
2706
2707
        $sql = "SELECT count(g.id) as count
2708
				FROM $tbl_group g
2709
				INNER JOIN $table_group_rel_user gu
2710
				ON gu.usergroup_id = g.id
2711
				WHERE gu.user_id = $user_id $where_relation_condition ";
2712
2713
        $result = Database::query($sql);
2714
        if (Database::num_rows($result) > 0) {
2715
            $row = Database::fetch_assoc($result);
2716
2717
            return $row['count'];
2718
        }
2719
2720
        return 0;
2721
    }
2722
2723
    /**
2724
     * @param string $tag
2725
     * @param int    $from
2726
     * @param int    $number_of_items
2727
     *
2728
     * @return array
2729
     */
2730
    public function get_all_group_tags($tag, $from = 0, $number_of_items = 10, $getCount = false)
2731
    {
2732
        $group_table = $this->table;
2733
        $tag = Database::escape_string($tag);
2734
        $from = (int) $from;
2735
        $number_of_items = (int) $number_of_items;
2736
        $return = [];
2737
2738
        $keyword = $tag;
2739
        $sql = 'SELECT  g.id, g.title, g.description, g.url, g.picture ';
2740
        $urlCondition = '';
2741
        if ($this->getUseMultipleUrl()) {
2742
            $urlId = api_get_current_access_url_id();
2743
            $sql .= " FROM $this->table g
2744
                    INNER JOIN $this->access_url_rel_usergroup a
2745
                    ON (g.id = a.usergroup_id)";
2746
            $urlCondition = " AND access_url_id = $urlId ";
2747
        } else {
2748
            $sql .= " FROM $group_table g";
2749
        }
2750
        if (isset($keyword)) {
2751
            $sql .= " WHERE (
2752
                        g.title LIKE '%".$keyword."%' OR
2753
                        g.description LIKE '%".$keyword."%' OR
2754
                        g.url LIKE '%".$keyword."%'
2755
                     ) $urlCondition
2756
                     ";
2757
        } else {
2758
            $sql .= " WHERE 1 = 1 $urlCondition ";
2759
        }
2760
2761
        $direction = 'ASC';
2762
        if (!in_array($direction, ['ASC', 'DESC'])) {
2763
            $direction = 'ASC';
2764
        }
2765
2766
        $sql .= " LIMIT $from, $number_of_items";
2767
2768
        $res = Database::query($sql);
2769
        if (Database::num_rows($res) > 0) {
2770
            while ($row = Database::fetch_assoc($res)) {
2771
                if (!in_array($row['id'], $return)) {
2772
                    $return[$row['id']] = $row;
2773
                }
2774
            }
2775
        }
2776
2777
        return $return;
2778
    }
2779
2780
    /**
2781
     * @param int $group_id
2782
     *
2783
     * @return array
2784
     */
2785
    public static function get_parent_groups($group_id)
2786
    {
2787
        $t_rel_group = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
2788
        $group_id = (int) $group_id;
2789
2790
        $max_level = 10;
2791
        $select_part = 'SELECT ';
2792
        $cond_part = '';
2793
        for ($i = 1; $i <= $max_level; $i++) {
2794
            $rg_number = $i - 1;
2795
            if ($i == $max_level) {
2796
                $select_part .= "rg$rg_number.group_id as id_$rg_number ";
2797
            } else {
2798
                $select_part .= "rg$rg_number.group_id as id_$rg_number, ";
2799
            }
2800
            if (1 == $i) {
2801
                $cond_part .= "FROM $t_rel_group rg0
2802
                               LEFT JOIN $t_rel_group rg$i
2803
                               ON rg$rg_number.group_id = rg$i.subgroup_id ";
2804
            } else {
2805
                $cond_part .= " LEFT JOIN $t_rel_group rg$i
2806
                                ON rg$rg_number.group_id = rg$i.subgroup_id ";
2807
            }
2808
        }
2809
        $sql = $select_part.' '.$cond_part."WHERE rg0.subgroup_id='$group_id'";
2810
        $res = Database::query($sql);
2811
        $temp_arr = Database::fetch_array($res, 'NUM');
2812
        $toReturn = [];
2813
        if (is_array($temp_arr)) {
2814
            foreach ($temp_arr as $elt) {
2815
                if (isset($elt)) {
2816
                    $toReturn[] = $elt;
2817
                }
2818
            }
2819
        }
2820
2821
        return $toReturn;
2822
    }
2823
2824
    /**
2825
     * Get the group member list by a user and his group role.
2826
     *
2827
     * @param int  $userId                The user ID
2828
     * @param int  $relationType          Optional. The relation type. GROUP_USER_PERMISSION_ADMIN by default
2829
     * @param bool $includeSubgroupsUsers Optional. Whether include the users from subgroups
2830
     *
2831
     * @return array
2832
     */
2833
    public function getGroupUsersByUser(
2834
        $userId,
2835
        $relationType = GROUP_USER_PERMISSION_ADMIN,
2836
        $includeSubgroupsUsers = true
2837
    ) {
2838
        $userId = (int) $userId;
2839
        $groups = $this->get_groups_by_user($userId, $relationType);
2840
        $groupsId = array_keys($groups);
2841
        $subgroupsId = [];
2842
        $userIdList = [];
2843
2844
        if ($includeSubgroupsUsers) {
2845
            foreach ($groupsId as $groupId) {
2846
                $subgroupsId = array_merge($subgroupsId, self::getGroupsByDepthLevel($groupId));
2847
            }
2848
2849
            $groupsId = array_merge($groupsId, $subgroupsId);
2850
        }
2851
2852
        $groupsId = array_unique($groupsId);
2853
2854
        if (empty($groupsId)) {
2855
            return [];
2856
        }
2857
2858
        foreach ($groupsId as $groupId) {
2859
            $groupUsers = $this->get_users_by_group($groupId);
2860
2861
            if (empty($groupUsers)) {
2862
                continue;
2863
            }
2864
2865
            foreach ($groupUsers as $member) {
2866
                if ($member['user_id'] == $userId) {
2867
                    continue;
2868
                }
2869
2870
                $userIdList[] = (int) $member['user_id'];
2871
            }
2872
        }
2873
2874
        return array_unique($userIdList);
2875
    }
2876
2877
    /**
2878
     * Get the subgroups ID from a group.
2879
     * The default $levels value is 10 considering it as a extensive level of depth.
2880
     *
2881
     * @param int $groupId The parent group ID
2882
     * @param int $levels  The depth levels
2883
     *
2884
     * @return array The list of ID
2885
     */
2886
    public static function getGroupsByDepthLevel($groupId, $levels = 10)
2887
    {
2888
        $groups = [];
2889
        $groupId = (int) $groupId;
2890
2891
        $groupTable = Database::get_main_table(TABLE_USERGROUP);
2892
        $groupRelGroupTable = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
2893
2894
        $select = 'SELECT ';
2895
        $from = "FROM $groupTable g1 ";
2896
2897
        for ($i = 1; $i <= $levels; $i++) {
2898
            $tableIndexNumber = $i;
2899
            $tableIndexJoinNumber = $i - 1;
2900
            $select .= "g$i.id as id_$i ";
2901
            $select .= $i != $levels ? ', ' : null;
2902
2903
            if (1 == $i) {
2904
                $from .= " INNER JOIN $groupRelGroupTable gg0
2905
                           ON g1.id = gg0.subgroup_id and gg0.group_id = $groupId ";
2906
            } else {
2907
                $from .= "LEFT JOIN $groupRelGroupTable gg$tableIndexJoinNumber ";
2908
                $from .= " ON g$tableIndexJoinNumber.id = gg$tableIndexJoinNumber.group_id ";
2909
                $from .= "LEFT JOIN $groupTable g$tableIndexNumber ";
2910
                $from .= " ON gg$tableIndexJoinNumber.subgroup_id = g$tableIndexNumber.id ";
2911
            }
2912
        }
2913
2914
        $result = Database::query("$select $from");
2915
2916
        while ($item = Database::fetch_assoc($result)) {
2917
            foreach ($item as $myGroupId) {
2918
                if (!empty($myGroupId)) {
2919
                    $groups[] = $myGroupId;
2920
                }
2921
            }
2922
        }
2923
2924
        return array_map('intval', $groups);
2925
    }
2926
2927
    /**
2928
     * Set a parent group.
2929
     *
2930
     * @param int $group_id
2931
     * @param int $parent_group_id if 0, we delete the parent_group association
2932
     * @param int $relation_type
2933
     *
2934
     * @return \Doctrine\DBAL\Statement
2935
     */
2936
    public function setParentGroup($group_id, $parent_group_id, $relation_type = 1)
2937
    {
2938
        $table = Database::get_main_table(TABLE_USERGROUP_REL_USERGROUP);
2939
        $group_id = (int) $group_id;
2940
        $parent_group_id = (int) $parent_group_id;
2941
        if (0 == $parent_group_id) {
2942
            $sql = "DELETE FROM $table WHERE subgroup_id = $group_id";
2943
        } else {
2944
            $sql = "SELECT group_id FROM $table WHERE subgroup_id = $group_id";
2945
            $res = Database::query($sql);
2946
            if (0 == Database::num_rows($res)) {
2947
                $sql = "INSERT INTO $table SET
2948
                        group_id = $parent_group_id,
2949
                        subgroup_id = $group_id,
2950
                        relation_type = $relation_type";
2951
            } else {
2952
                $sql = "UPDATE $table SET
2953
                        group_id = $parent_group_id,
2954
                        relation_type = $relation_type
2955
                        WHERE subgroup_id = $group_id";
2956
            }
2957
        }
2958
        $res = Database::query($sql);
2959
2960
        return $res;
2961
    }
2962
2963
    /**
2964
     * Filter the groups/classes info to get a name list only.
2965
     *
2966
     * @param int $userId       The user ID
2967
     * @param int $filterByType Optional. The type of group
2968
     *
2969
     * @return array
2970
     */
2971
    public function getNameListByUser($userId, $filterByType = null)
2972
    {
2973
        $userClasses = $this->getUserGroupListByUser($userId, $filterByType);
2974
2975
        return array_column($userClasses, 'title');
2976
    }
2977
2978
    /**
2979
     * Get the HTML necessary for display the groups/classes name list.
2980
     *
2981
     * @param int $userId       The user ID
2982
     * @param int $filterByType Optional. The type of group
2983
     *
2984
     * @return string
2985
     */
2986
    public function getLabelsFromNameList($userId, $filterByType = null)
2987
    {
2988
        $groupsNameListParsed = $this->getNameListByUser($userId, $filterByType);
2989
2990
        if (empty($groupsNameListParsed)) {
2991
            return '';
2992
        }
2993
2994
        $nameList = '<ul class="list-unstyled">';
2995
        foreach ($groupsNameListParsed as $name) {
2996
            $nameList .= '<li>'.Display::span($name, ['class' => 'label label-info']).'</li>';
2997
        }
2998
2999
        $nameList .= '</ul>';
3000
3001
        return $nameList;
3002
    }
3003
3004
    /**
3005
     * @param array $groupInfo
3006
     *
3007
     * @return bool
3008
     */
3009
    public static function canLeave($groupInfo)
3010
    {
3011
        return 1 == $groupInfo['allow_members_leave_group'] ? true : false;
3012
    }
3013
3014
    /**
3015
     * Check permissions and blocks the page.
3016
     *
3017
     * @param array $userGroupInfo
3018
     * @param bool  $checkAuthor
3019
     * @param bool  $checkCourseIsAllow
3020
     */
3021
    public function protectScript($userGroupInfo = [], $checkAuthor = true, $checkCourseIsAllow = false)
3022
    {
3023
        api_block_anonymous_users();
3024
3025
        if (api_is_platform_admin()) {
3026
            return true;
3027
        }
3028
3029
        if ($checkCourseIsAllow) {
3030
            if (api_is_allowed_to_edit()) {
3031
                return true;
3032
            }
3033
        }
3034
3035
        if ($this->allowTeachers() && api_is_teacher()) {
3036
            if ($checkAuthor && !empty($userGroupInfo)) {
3037
                if (isset($userGroupInfo['author_id']) && $userGroupInfo['author_id'] != api_get_user_id()) {
3038
                    api_not_allowed(true);
3039
                }
3040
            }
3041
3042
            return true;
3043
        } else {
3044
            api_protect_admin_script(true);
3045
            api_protect_limit_for_session_admin();
3046
        }
3047
    }
3048
3049
    public function getGroupsByLp($lpId, $courseId, $sessionId)
3050
    {
3051
        $lpId = (int) $lpId;
3052
        $courseId = (int) $courseId;
3053
        $sessionId = (int) $sessionId;
3054
        $sessionCondition = api_get_session_condition($sessionId, true);
3055
        $table = Database::get_course_table(TABLE_LP_REL_USERGROUP);
3056
        $sql = "SELECT usergroup_id FROM $table
3057
                WHERE
3058
                    c_id = $courseId AND
3059
                    lp_id = $lpId
3060
                    $sessionCondition
3061
                    ";
3062
        $result = Database::query($sql);
3063
3064
        return Database::store_result($result, 'ASSOC');
3065
    }
3066
3067
    public function getGroupsByLpCategory($categoryId, $courseId, $sessionId)
3068
    {
3069
        $categoryId = (int) $categoryId;
3070
        $courseId = (int) $courseId;
3071
        $sessionId = (int) $sessionId;
3072
        $sessionCondition = api_get_session_condition($sessionId, true);
3073
3074
        $table = Database::get_course_table(TABLE_LP_CATEGORY_REL_USERGROUP);
3075
        $sql = "SELECT usergroup_id FROM $table
3076
                WHERE
3077
                    c_id = $courseId AND
3078
                    lp_category_id = $categoryId
3079
                    $sessionCondition
3080
                ";
3081
        $result = Database::query($sql);
3082
3083
        return Database::store_result($result, 'ASSOC');
3084
    }
3085
3086
    public static function getRoleName($relation)
3087
    {
3088
        switch ((int) $relation) {
3089
            case GROUP_USER_PERMISSION_ADMIN:
3090
                return get_lang('Admin');
3091
            case GROUP_USER_PERMISSION_READER:
3092
                return get_lang('Reader');
3093
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
3094
                return get_lang('Pending invitation');
3095
            case GROUP_USER_PERMISSION_MODERATOR:
3096
                return get_lang('Moderator');
3097
            case GROUP_USER_PERMISSION_HRM:
3098
                return get_lang('Human Resources Manager');
3099
            default:
3100
                return get_lang('Undefined role');
3101
        }
3102
    }
3103
}
3104