Passed
Pull Request — master (#6881)
by
unknown
16:36 queued 06:54
created

unsubscribe_only_courses_from_usergroup()   B

Complexity

Conditions 7
Paths 11

Size

Total Lines 25
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

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