Passed
Push — master ( 5f08e8...58d249 )
by Julito
11:37 queued 01:28
created

UserGroup::update()   B

Complexity

Conditions 8
Paths 80

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

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