Passed
Push — master ( 3fcb32...49d6fc )
by Julito
09:27
created

GroupManager::create_category()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 55
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 25
nc 2
nop 14
dl 0
loc 55
rs 9.52
c 0
b 0
f 0

How to fix   Long Method    Many Parameters   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\Course;
6
use Chamilo\CoreBundle\Framework\Container;
7
use Chamilo\CourseBundle\Entity\CGroup;
8
use Chamilo\CourseBundle\Entity\CGroupCategory;
9
10
/**
11
 * This library contains some functions for group-management.
12
 *
13
 * @author Bart Mollet
14
 *
15
 * @todo Add $course_code parameter to all functions. So this GroupManager can
16
 * be used outside a session.
17
 */
18
class GroupManager
19
{
20
    /* DEFAULT_GROUP_CATEGORY:
21
    When group categories aren't available (platform-setting),
22
    all groups are created in this 'dummy'-category*/
23
    public const DEFAULT_GROUP_CATEGORY = 2;
24
25
    /**
26
     * infinite.
27
     */
28
    public const INFINITE = 99999;
29
    /**
30
     * No limit on the number of users in a group.
31
     */
32
    public const MEMBER_PER_GROUP_NO_LIMIT = 0;
33
    /**
34
     * No limit on the number of groups per user.
35
     */
36
    public const GROUP_PER_MEMBER_NO_LIMIT = 0;
37
    /**
38
     * The tools of a group can have 3 states
39
     * - not available
40
     * - public
41
     * - private.
42
     */
43
    public const TOOL_NOT_AVAILABLE = 0;
44
    public const TOOL_PUBLIC = 1;
45
    public const TOOL_PRIVATE = 2;
46
    public const TOOL_PRIVATE_BETWEEN_USERS = 3;
47
48
    /**
49
     * Constants for the available group tools.
50
     */
51
    public const GROUP_TOOL_FORUM = 0;
52
    public const GROUP_TOOL_DOCUMENTS = 1;
53
    public const GROUP_TOOL_CALENDAR = 2;
54
    public const GROUP_TOOL_ANNOUNCEMENT = 3;
55
    public const GROUP_TOOL_WORK = 4;
56
    public const GROUP_TOOL_WIKI = 5;
57
    public const GROUP_TOOL_CHAT = 6;
58
59
    public const DOCUMENT_MODE_SHARE = 0; // By default
60
    public const DOCUMENT_MODE_READ_ONLY = 1;
61
    public const DOCUMENT_MODE_COLLABORATION = 2;
62
63
    public function __construct()
64
    {
65
    }
66
67
    /**
68
     * @param int $courseId
69
     *
70
     * @return CGroup[]
71
     */
72
    public static function get_groups($courseId = 0)
73
    {
74
        $repo = Container::getGroupRepository();
75
        $course = api_get_course_entity($courseId);
76
        if (null !== $course) {
77
            return [];
78
        }
79
80
        $qb = $repo->getResourcesByCourse($course);
81
82
        return $qb->getQuery()->getResult();
83
        /*$table_group = Database::get_course_table(TABLE_GROUP);
84
        $courseId = !empty($courseId) ? (int) $courseId : api_get_course_int_id();
85
86
        $sql = "SELECT * FROM $table_group WHERE c_id = $courseId  ";
87
        $result = Database::query($sql);
88
89
        return Database::store_result($result, 'ASSOC');*/
90
    }
91
92
    /**
93
     * Get list of groups for current course.
94
     *
95
     * @param int    $categoryId The id of the category from which the groups are
96
     *                           requested
97
     * @param Course $course     Default is current course
98
     * @param int    $status     group status
99
     * @param int    $sessionId
100
     * @param bool   $getCount
101
     * @param bool   $notInGroup Get groups not in a category
102
     *
103
     * @return array an array with all information about the groups
104
     */
105
    public static function get_group_list(
106
        $categoryId = null,
107
        $course = null,
108
        $status = null,
109
        $sessionId = 0,
110
        $getCount = false,
111
        $filterByKeyword = '',
112
        $returnEntityList = false
113
    ) {
114
        $course = $course ?? api_get_course_entity();
115
116
        if (null === $course) {
117
            return [];
118
        }
119
120
        $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
121
        $repo = Container::getGroupRepository();
122
        $session = api_get_session_entity($sessionId);
123
        $qb = $repo->findAllByCourse($course, $session, $filterByKeyword, $status);
124
125
        if ($getCount) {
126
            return $repo->getCount($qb);
127
        }
128
129
        if ($returnEntityList) {
130
            return $qb->getQuery()->getResult();
131
        }
132
133
        return $qb->getQuery()->getArrayResult();
134
        /*$table_group = Database::get_course_table(TABLE_GROUP);
135
        $select = ' g.iid,
136
                    g.name,
137
                    g.description,
138
                    g.category_id,
139
                    g.max_student maximum_number_of_members,
140
                    g.secret_directory,
141
                    g.self_registration_allowed,
142
                    g.self_unregistration_allowed,
143
                    g.status
144
                    ';
145
        if ($getCount) {
146
            $select = ' DISTINCT count(g.iid) as count ';
147
        }
148
149
        $sql = "SELECT
150
                $select
151
                FROM $table_group g
152
                WHERE 1 = 1 ";
153
154
        if (!is_null($categoryId)) {
155
            $sql .= " AND g.category_id = '".intval($categoryId)."' ";
156
            $session_condition = api_get_session_condition($sessionId);
157
            if (!empty($session_condition)) {
158
                //$sql .= $session_condition;
159
            }
160
        } else {
161
            $session_condition = api_get_session_condition($sessionId, true);
162
        }
163
164
        $session_condition = '';
165
166
        if (!is_null($status)) {
167
            $sql .= " AND g.status = '".intval($status)."' ";
168
        }
169
170
        //$sql .= " AND g.c_id = $course_id ";
171
        if ($notInGroup) {
172
            $sql .= "  AND (g.category_id IS NULL OR g.category_id = 0) ";
173
        }
174
175
        if (!empty($session_condition)) {
176
            $sql .= $session_condition;
177
        }
178
        $sql .= ' ORDER BY UPPER(g.name)';
179
180
        $result = Database::query($sql);
181
182
        if ($getCount) {
183
            $row = Database::fetch_array($result);
184
185
            return $row['count'];
186
        }
187
188
        $groups = [];
189
        while ($thisGroup = Database::fetch_array($result)) {
190
            $thisGroup['number_of_members'] = count(self::get_subscribed_users($thisGroup));
191
            if (0 != $thisGroup['session_id']) {
192
                $sql = 'SELECT name FROM '.Database::get_main_table(TABLE_MAIN_SESSION).'
193
                        WHERE id='.$thisGroup['session_id'];
194
                $rs_session = Database::query($sql);
195
                if (Database::num_rows($rs_session) > 0) {
196
                    $thisGroup['session_name'] = Database::result($rs_session, 0, 0);
197
                }
198
            }
199
            $groups[] = $thisGroup;
200
        }
201
202
        return $groups;*/
203
    }
204
205
    /**
206
     * Create a group.
207
     *
208
     * @param string $name        The name for this group
209
     * @param int    $category_id
210
     * @param int    $tutor       The user-id of the group's tutor
211
     * @param int    $places      How many people can subscribe to the new group
212
     *
213
     * @return int
214
     */
215
    public static function create_group($name, $category_id, $tutor, $places)
216
    {
217
        $_course = api_get_course_info();
218
        $session_id = api_get_session_id();
219
        $course_id = $_course['real_id'];
220
        $category = self::get_category($category_id);
221
        $places = (int) $places;
222
223
        // Default values
224
        $docState = self::TOOL_PRIVATE;
225
        $calendarState = self::TOOL_PRIVATE;
226
        $workState = self::TOOL_PRIVATE;
227
        $anonuncementState = self::TOOL_PRIVATE;
228
        $forumState = self::TOOL_PRIVATE;
229
        $wikiState = self::TOOL_PRIVATE;
230
        $chatState = self::TOOL_PRIVATE;
231
        $selfRegAllowed = 0;
232
        $selfUnregAllwoed = 0;
233
        $documentAccess = 0;
234
235
        if ($category) {
236
            if (0 == $places) {
237
                //if the amount of users per group is not filled in, use the setting from the category
238
                $places = $category['max_student'];
239
            } else {
240
                if ($places > $category['max_student'] && 0 != $category['max_student']) {
241
                    $places = $category['max_student'];
242
                }
243
            }
244
            $docState = $category['doc_state'];
245
            $calendarState = $category['calendar_state'];
246
            $workState = $category['work_state'];
247
            $anonuncementState = $category['announcements_state'];
248
            $forumState = $category['forum_state'];
249
            $wikiState = $category['wiki_state'];
250
            $chatState = $category['chat_state'];
251
            $selfRegAllowed = $category['self_reg_allowed'];
252
            $selfUnregAllwoed = $category['self_unreg_allowed'];
253
            $documentAccess = isset($category['document_access']) ? $category['document_access'] : 0;
254
        }
255
256
        $course = api_get_course_entity($course_id);
257
        $session = api_get_session_entity($session_id);
258
259
        $category = null;
260
        if (!empty($category_id)) {
261
            $category = Container::getGroupCategoryRepository()->find($category_id);
262
        }
263
264
        $group = new CGroup();
265
        $group
266
            ->setName($name)
267
            ->setCategory($category)
268
            ->setMaxStudent($places)
269
            ->setDocState($docState)
270
            ->setCalendarState($calendarState)
271
            ->setWorkState($workState)
272
            ->setForumState($forumState)
273
            ->setWikiState($wikiState)
274
            ->setAnnouncementsState($anonuncementState)
275
            ->setChatState($chatState)
276
            ->setSelfRegistrationAllowed(1 === (int) $selfRegAllowed)
277
            ->setSelfUnregistrationAllowed(1 === (int) $selfUnregAllwoed)
278
            ->setDocumentAccess((int) $documentAccess)
279
            ->setParent($course)
280
            ->addCourseLink($course, $session)
281
        ;
282
283
        $repo = Container::getGroupRepository();
284
        $repo->create($group);
285
        $lastId = $group->getIid();
286
287
        if ($lastId) {
288
            /*$desired_dir_name = '/'.api_replace_dangerous_char($name).'_groupdocs';
289
290
            $newFolderData = create_unexisting_directory(
291
                $_course,
292
                api_get_user_id(),
293
                $session_id,
294
                $lastId,
295
                null,
296
                null,
297
                    $desired_dir_name,
298
                $desired_dir_name,
299
                1
300
            );*/
301
302
            // create a forum if needed
303
            if ($forumState >= 0) {
304
                $forumName = get_lang('Group forums');
305
                $repo = Container::getForumCategoryRepository();
306
                $category = $repo->findResourceByTitle($forumName, $course->getResourceNode(), $course);
307
                /*$criteria = ['cId' => $course_id, 'catTitle' => $forumName];
308
                $category = $repo->findOneBy($criteria);*/
309
310
                if (empty($category)) {
311
                    $categoryId = store_forumcategory(['forum_category_title' => $forumName]);
312
                } else {
313
                    $categoryId = $category->getIid();
314
                }
315
316
                $values = [];
317
                $values['forum_title'] = $name;
318
                $values['group_id'] = $lastId;
319
                $values['forum_category'] = $categoryId;
320
                $values['allow_anonymous_group']['allow_anonymous'] = 0;
321
                $values['students_can_edit_group']['students_can_edit'] = 0;
322
                $values['approval_direct_group']['approval_direct'] = 0;
323
                $values['allow_attachments_group']['allow_attachments'] = 1;
324
                $values['allow_new_threads_group']['allow_new_threads'] = 1;
325
                $values['default_view_type_group']['default_view_type'] = api_get_setting('default_forum_view');
326
                $values['group_forum'] = $lastId;
327
                if ('1' == $forumState) {
328
                    $values['public_private_group_forum_group']['public_private_group_forum'] = 'public';
329
                } elseif ('2' == $forumState) {
330
                    $values['public_private_group_forum_group']['public_private_group_forum'] = 'private';
331
                } elseif ('0' == $forumState) {
332
                    $values['public_private_group_forum_group']['public_private_group_forum'] = 'unavailable';
333
                }
334
                store_forum($values);
335
            }
336
        }
337
338
        return $lastId;
339
    }
340
341
    /**
342
     * Create subgroups.
343
     * This function creates new groups based on an existing group. It will
344
     * create the specified number of groups and fill those groups with users
345
     * from the base group.
346
     *
347
     * @param int $group_id         the group from which subgroups have to be created
348
     * @param int $number_of_groups The number of groups that have to be created
349
     */
350
    public static function create_subgroups($group_id, $number_of_groups)
351
    {
352
        $courseId = api_get_course_int_id();
353
        $table_group = Database::get_course_table(TABLE_GROUP);
354
        $category_id = self::create_category(
355
            get_lang('Subgroups'),
356
            '',
357
            self::TOOL_PRIVATE,
358
            self::TOOL_PRIVATE,
359
            0,
360
            0,
361
            1,
362
            1
363
        );
364
        $users = self::get_users($group_id);
365
        $group_ids = [];
366
367
        for ($group_nr = 1; $group_nr <= $number_of_groups; $group_nr++) {
368
            $group_ids[] = self::create_group(
369
                get_lang('Subgroup').' '.$group_nr,
370
                $category_id,
371
                0,
372
                0
373
            );
374
        }
375
376
        $members = [];
377
        foreach ($users as $index => $user_id) {
378
            $groupId = $group_ids[$index % $number_of_groups];
379
            self::subscribeUsers(
380
                $user_id,
381
                api_get_group_entity($groupId)
382
            );
383
            $members[$group_ids[$groupId]]++;
384
        }
385
386
        foreach ($members as $group_id => $places) {
387
            $sql = "UPDATE $table_group SET max_student = $places
388
                    WHERE c_id = $courseId  AND id = $group_id";
389
            Database::query($sql);
390
        }
391
    }
392
393
    /**
394
     * Create a group for every class subscribed to the current course.
395
     *
396
     * @param int $categoryId The category in which the groups should be created
397
     *
398
     * @return array
399
     */
400
    public static function create_class_groups($categoryId)
401
    {
402
        $options['where'] = [' usergroup.course_id = ? ' => api_get_course_int_id()];
403
        $obj = new UserGroup();
404
        $classes = $obj->getUserGroupInCourse($options);
405
        $group_ids = [];
406
407
        foreach ($classes as $class) {
408
            $userList = $obj->get_users_by_usergroup($class['id']);
409
            $groupId = self::create_group(
410
                $class['name'],
411
                $categoryId,
412
                0,
413
                null
414
            );
415
416
            if ($groupId) {
417
                self::subscribeUsers($userList, api_get_group_entity($groupId));
418
                $group_ids[] = $groupId;
419
            }
420
        }
421
422
        return $group_ids;
423
    }
424
425
    /**
426
     * Deletes groups and their data.
427
     *
428
     * @author Christophe Gesche <[email protected]>
429
     * @author Hugues Peeters <[email protected]>
430
     * @author Bart Mollet
431
     *
432
     * @param string $course_code Default is current course
433
     *
434
     * @return int - number of groups deleted
435
     */
436
    public static function deleteGroup(CGroup $group, $course_code = null)
437
    {
438
        if (empty($group)) {
439
            return false;
440
        }
441
        $course_info = api_get_course_info($course_code);
442
        if (empty($course_info)) {
443
            return false;
444
        }
445
446
        $em = Database::getManager();
447
        $groupIid = $group->getIid();
448
449
        // Unsubscribe all users
450
        self::unsubscribeAllUsers($groupIid);
451
        self::unsubscribe_all_tutors($groupIid);
452
453
        $em
454
            ->createQuery(
455
                'DELETE FROM ChamiloCourseBundle:CForumForum f WHERE f.forumOfGroup = :group'
456
            )
457
            ->execute(['group' => $groupIid]);
458
459
        // delete the groups
460
        $repo = Container::getGroupRepository();
461
        $em->remove($group);
462
        $em->flush();
463
464
        return true;
465
    }
466
467
    /**
468
     * @deprecated Should be deleted by the resources.
469
     *
470
     * Function needed only when deleting a course, in order to be sure that all group ids are deleted.
471
     *
472
     * @param int $courseId
473
     *
474
     * @return bool
475
     */
476
    public static function deleteAllGroupsFromCourse($courseId)
477
    {
478
        $courseId = (int) $courseId;
479
480
        if (empty($courseId)) {
481
            return false;
482
        }
483
484
        $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
485
        $sql = "SELECT iid FROM $table
486
                WHERE c_id = $courseId ";
487
        Database::query($sql);
488
489
        // Database table definitions
490
        $table = Database::get_course_table(TABLE_GROUP_USER);
491
        $sql = "DELETE FROM $table
492
                WHERE c_id = $courseId";
493
        Database::query($sql);
494
495
        $table = Database::get_course_table(TABLE_GROUP_TUTOR);
496
        $sql = "DELETE FROM $table
497
                WHERE c_id = $courseId";
498
        Database::query($sql);
499
500
        $groupTable = Database::get_course_table(TABLE_GROUP);
501
        $sql = "DELETE FROM $groupTable
502
                WHERE c_id = $courseId";
503
        Database::query($sql);
504
505
        return true;
506
    }
507
508
    /**
509
     * Get group properties.
510
     *
511
     * @param int $group_id the group from which properties are requested
512
     *
513
     * @return array All properties. Array-keys are:
514
     *               name, tutor_id, description, maximum_number_of_students,
515
     *               directory and visibility of tools
516
     */
517
    public static function get_group_properties($group_id)
518
    {
519
        $group_id = (int) $group_id;
520
521
        if (empty($group_id)) {
522
            return null;
523
        }
524
525
        $table_group = Database::get_course_table(TABLE_GROUP);
526
527
        $sql = "SELECT * FROM $table_group
528
                WHERE iid = ".$group_id;
529
530
        $db_result = Database::query($sql);
531
        $db_object = Database::fetch_object($db_result);
532
533
        $result = [];
534
        if ($db_object) {
535
            $result['id'] = $db_object->iid;
536
            $result['iid'] = $db_object->iid;
537
            $result['name'] = $db_object->name;
538
            $result['status'] = $db_object->status;
539
            $result['description'] = $db_object->description;
540
            $result['maximum_number_of_students'] = $db_object->max_student;
541
            $result['max_student'] = $db_object->max_student;
542
            $result['doc_state'] = $db_object->doc_state;
543
            $result['work_state'] = $db_object->work_state;
544
            $result['calendar_state'] = $db_object->calendar_state;
545
            $result['announcements_state'] = $db_object->announcements_state;
546
            $result['forum_state'] = $db_object->forum_state;
547
            $result['wiki_state'] = $db_object->wiki_state;
548
            $result['chat_state'] = $db_object->chat_state;
549
            $result['self_registration_allowed'] = $db_object->self_registration_allowed;
550
            $result['self_unregistration_allowed'] = $db_object->self_unregistration_allowed;
551
            $result['count_users'] = count(
552
                self::get_subscribed_users($result)
553
            );
554
            /*$result['count_tutor'] = count(
555
                self::get_subscribed_tutors($result)
556
            );*/
557
            //$result['count_all'] = $result['count_users'] + $result['count_tutor'];
558
            $result['count_all'] = null;
559
            $result['document_access'] = isset($db_object->document_access) ? $db_object->document_access : self::DOCUMENT_MODE_SHARE;
560
        }
561
562
        return $result;
563
    }
564
565
    /**
566
     * @param string $name
567
     * @param string $courseCode
568
     * @param int    $sessionId
569
     *
570
     * @return array
571
     */
572
    public static function getGroupByName($name, $courseCode = null, $sessionId = 0)
573
    {
574
        $name = trim($name);
575
576
        if (empty($name)) {
577
            return [];
578
        }
579
580
        $course_info = api_get_course_info($courseCode);
581
        $course_id = $course_info['real_id'];
582
        $name = Database::escape_string($name);
583
        $sessionId = empty($sessionId) ? api_get_session_id() : (int) $sessionId;
584
        $sessionCondition = api_get_session_condition($sessionId);
585
586
        $table = Database::get_course_table(TABLE_GROUP);
587
        $sql = "SELECT * FROM $table
588
                WHERE
589
                  c_id = $course_id AND
590
                  name = '$name'
591
                  $sessionCondition
592
                LIMIT 1";
593
        $res = Database::query($sql);
594
        $group = [];
595
        if (Database::num_rows($res)) {
596
            $group = Database::fetch_array($res, 'ASSOC');
597
        }
598
599
        return $group;
600
    }
601
602
    /**
603
     * Set group properties
604
     * Changes the group's properties.
605
     *
606
     * @param int       Group Id
607
     * @param string    Group name
608
     * @param string    Group description
609
     * @param int       Max number of students in group
610
     * @param int       Document tool's visibility (0=none,1=private,2=public)
611
     * @param int       Work tool's visibility (0=none,1=private,2=public)
612
     * @param int       Calendar tool's visibility (0=none,1=private,2=public)
613
     * @param int       Announcement tool's visibility (0=none,1=private,2=public)
614
     * @param int       Forum tool's visibility (0=none,1=private,2=public)
615
     * @param int       Wiki tool's visibility (0=none,1=private,2=public)
616
     * @param int       Chat tool's visibility (0=none,1=private,2=public)
617
     * @param bool Whether self registration is allowed or not
618
     * @param bool Whether self unregistration is allowed or not
619
     * @param int $categoryId
620
     * @param int $documentAccess
621
     *
622
     * @return bool TRUE if properties are successfully changed, false otherwise
623
     */
624
    public static function set_group_properties(
625
        $group_id,
626
        $name,
627
        $description,
628
        $maxStudent,
629
        $docState,
630
        $workState,
631
        $calendarState,
632
        $anonuncementState,
633
        $forumState,
634
        $wikiState,
635
        $chatState,
636
        $selfRegistrationAllowed,
637
        $selfUnRegistrationAllowed,
638
        $categoryId = null,
639
        $documentAccess = 0
640
    ) {
641
        $table_forum = Database::get_course_table(TABLE_FORUM);
642
        $categoryId = (int) $categoryId;
643
        $group_id = (int) $group_id;
644
        $forumState = (int) $forumState;
645
        $repo = Container::getGroupRepository();
646
647
        /** @var CGroup $group */
648
        $group = $repo->find($group_id);
649
650
        $category = null;
651
        if (!empty($categoryId)) {
652
            $category = Container::getGroupCategoryRepository()->find($categoryId);
653
        }
654
655
        $group
656
            ->setName($name)
657
            ->setCategory($category)
658
            ->setMaxStudent($maxStudent)
659
            ->setDocState($docState)
660
            ->setCalendarState($calendarState)
661
            ->setWorkState($workState)
662
            ->setForumState($forumState)
663
            ->setWikiState($wikiState)
664
            ->setAnnouncementsState($anonuncementState)
665
            ->setChatState($chatState)
666
            ->setSelfRegistrationAllowed($selfRegistrationAllowed)
667
            ->setSelfUnregistrationAllowed($selfUnRegistrationAllowed)
668
            ->setDocumentAccess($documentAccess)
669
        ;
670
671
        $repo->update($group);
672
673
        /* Here we are updating a field in the table forum_forum that perhaps
674
        duplicates the table group_info.forum_state cvargas*/
675
        $sql2 = "UPDATE $table_forum SET ";
676
        if (1 === $forumState) {
677
            $sql2 .= " forum_group_public_private='public' ";
678
        } elseif (2 === $forumState) {
679
            $sql2 .= " forum_group_public_private='private' ";
680
        } elseif (0 === $forumState) {
681
            $sql2 .= " forum_group_public_private='unavailable' ";
682
        }
683
        $sql2 .= ' WHERE forum_of_group='.$group_id;
684
        Database::query($sql2);
685
686
        return true;
687
    }
688
689
    /**
690
     * Get the total number of groups for the current course.
691
     *
692
     * @return int the number of groups for the current course
693
     */
694
    public static function get_number_of_groups()
695
    {
696
        $repo = Container::getGroupRepository();
697
698
        $course = api_get_course_entity(api_get_course_int_id());
699
        if (null === $course) {
700
            return 0;
701
        }
702
703
        $session = api_get_session_entity(api_get_session_id());
704
        $group = api_get_group_entity(api_get_group_id());
705
        $qb = $repo->getResourcesByCourse($course, $session, $group);
706
        $qb->select('count(resource)');
707
708
        return $qb->getQuery()->getSingleScalarResult();
709
        /*$courseId = api_get_course_int_id();
710
        $table = Database::get_course_table(TABLE_GROUP);
711
        $sql = "SELECT COUNT(id) AS number_of_groups
712
                FROM $table
713
                WHERE c_id = $courseId ";
714
        $res = Database::query($sql);
715
        $obj = Database::fetch_object($res);
716
717
        return $obj->number_of_groups;*/
718
    }
719
720
    /**
721
     * Get all categories.
722
     */
723
    public static function get_categories(Course $course = null): array
724
    {
725
        $repo = Container::getGroupCategoryRepository();
726
727
        if (null === $course) {
728
            $course = api_get_course_entity(api_get_course_int_id());
729
        }
730
731
        $session = api_get_session_entity(api_get_session_id());
732
        //$group = api_get_group_entity(api_get_group_id());
733
        $group = null;
734
735
        $qb = $repo->getResourcesByCourse($course, $session, $group);
736
737
        return $qb->getQuery()->getArrayResult();
738
        /*$course_info = api_get_course_info($course_code);
739
        $courseId = $course_info['real_id'];
740
        $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
741
        $sql = "SELECT * FROM $table
742
                WHERE c_id = $courseId
743
                ORDER BY display_order";
744
        $res = Database::query($sql);
745
        $cats = [];
746
        while ($cat = Database::fetch_array($res)) {
747
            $cats[] = $cat;
748
        }
749
750
        return $cats;*/
751
    }
752
753
    /**
754
     * Get a group category.
755
     *
756
     * @param int    $id          The category id
757
     * @param string $course_code The course (default = current course)
758
     *
759
     * @return array
760
     */
761
    public static function get_category($id, $course_code = null)
762
    {
763
        if (empty($id)) {
764
            return [];
765
        }
766
767
        $courseInfo = api_get_course_info($course_code);
768
        $courseId = $courseInfo['real_id'];
769
        $id = (int) $id;
770
        $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
771
        $sql = "SELECT * FROM $table
772
                WHERE  iid = $id
773
                LIMIT 1";
774
        $res = Database::query($sql);
775
776
        return Database::fetch_array($res);
777
    }
778
779
    /**
780
     * Get a group category.
781
     *
782
     * @param string $title
783
     * @param string $course_code The course (default = current course)
784
     *
785
     * @return array
786
     */
787
    public static function getCategoryByTitle($title, $course_code = null)
788
    {
789
        $title = trim($title);
790
791
        if (empty($title)) {
792
            return [];
793
        }
794
795
        $course_info = api_get_course_info($course_code);
796
        $courseId = $course_info['real_id'];
797
        $title = Database::escape_string($title);
798
        $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
799
        $sql = "SELECT * FROM $table
800
                WHERE c_id = $courseId AND title = '$title'
801
                LIMIT 1";
802
        $res = Database::query($sql);
803
        $category = [];
804
        if (Database::num_rows($res)) {
805
            $category = Database::fetch_array($res, 'ASSOC');
806
        }
807
808
        return $category;
809
    }
810
811
    /**
812
     * Get the unique category of a given group.
813
     *
814
     * @param int    $group_id    The iid of the group
815
     * @param string $course_code The course in which the group is (default =
816
     *                            current course)
817
     *
818
     * @return array The category
819
     */
820
    public static function get_category_from_group($group_id, $course_code = '')
821
    {
822
        $table_group = Database::get_course_table(TABLE_GROUP);
823
        $table_group_cat = Database::get_course_table(TABLE_GROUP_CATEGORY);
824
825
        $group_id = (int) $group_id;
826
827
        if (empty($group_id)) {
828
            return [];
829
        }
830
831
        $course_info = api_get_course_info($course_code);
832
833
        if (empty($course_info)) {
834
            return false;
835
        }
836
837
        $sql = "SELECT gc.* FROM $table_group_cat gc
838
                INNER JOIN $table_group g
839
                ON (gc.iid = g.category_id)
840
                WHERE
841
                    g.iid = $group_id
842
                LIMIT 1";
843
        $res = Database::query($sql);
844
        $cat = [];
845
        if (Database::num_rows($res)) {
846
            $cat = Database::fetch_array($res);
847
        }
848
849
        return $cat;
850
    }
851
852
    /**
853
     * Delete a group category.
854
     *
855
     * @param int    $cat_id      The id of the category to delete
856
     * @param string $course_code The code in which the category should be
857
     *                            deleted (default = current course)
858
     *
859
     * @return bool
860
     */
861
    public static function delete_category($cat_id, $course_code = '')
862
    {
863
        $course_info = api_get_course_info($course_code);
864
        if (empty($course_info)) {
865
            return false;
866
        }
867
        $course_id = $course_info['real_id'];
868
869
        $table_group = Database::get_course_table(TABLE_GROUP);
870
        $table_group_cat = Database::get_course_table(TABLE_GROUP_CATEGORY);
871
        $cat_id = (int) $cat_id;
872
        $sql = "SELECT iid FROM $table_group
873
                WHERE category_id='".$cat_id."'";
874
        $res = Database::query($sql);
875
        if (Database::num_rows($res) > 0) {
876
            while ($group = Database::fetch_object($res)) {
877
                // Delete all groups in category
878
                /*$groupInfo = self::get_group_properties($group->iid, true);
879
                self::deleteGroup($groupInfo, $course_code);
880
                */
881
                // Set the category to NULL to avoid losing groups in sessions.
882
                $sql = "UPDATE $table_group SET category_id = NULL WHERE iid = ".$group->iid;
883
                Database::query($sql);
884
            }
885
        }
886
887
        $category = Database::getManager()->getRepository(CGroupCategory::class)->find($cat_id);
888
        if ($category) {
889
            Database::getManager()->remove($category);
890
            Database::getManager()->flush();
891
        }
892
893
        /*$sql = "DELETE FROM $table_group_cat
894
                WHERE iid='".$cat_id."'";
895
        Database::query($sql);*/
896
897
        return true;
898
    }
899
900
    /**
901
     * Create group category.
902
     *
903
     * @param string $title                     The title of the new category
904
     * @param string $description               The description of the new category
905
     * @param int    $selfRegistrationAllowed   allow users to self register
906
     * @param int    $selfUnRegistrationAllowed allow user to self unregister
907
     * @param int    $documentAccess            document access
908
     *
909
     * @return mixed
910
     */
911
    public static function create_category(
912
        $title,
913
        $description,
914
        $docState,
915
        $workState,
916
        $calendarState,
917
        $anonuncementState,
918
        $forumState,
919
        $wikiState,
920
        $chatState = 1,
921
        $selfRegistrationAllowed = 0,
922
        $selfUnRegistrationAllowed = 0,
923
        $maxStudent = 8,
924
        $groupsPerUser = 0,
925
        $documentAccess = 0
926
    ) {
927
        if (empty($title)) {
928
            return false;
929
        }
930
        /*$sql = "SELECT MAX(display_order)+1 as new_order
931
                FROM $table
932
                WHERE c_id = $course_id ";
933
        $res = Database::query($sql);
934
        $obj = Database::fetch_object($res);
935
        if (!isset($obj->new_order)) {
936
            $obj->new_order = 1;
937
        }*/
938
939
        $course = api_get_course_entity(api_get_course_int_id());
940
        $session = api_get_session_entity(api_get_session_id());
941
942
        $category = new CGroupCategory();
943
        $category
944
            ->setTitle($title)
945
            ->setDescription($description)
946
            ->setMaxStudent($maxStudent)
947
            ->setDocState($docState)
948
            ->setCalendarState($calendarState)
949
            ->setWorkState($workState)
950
            ->setForumState($forumState)
951
            ->setWikiState($wikiState)
952
            ->setAnnouncementsState($anonuncementState)
953
            ->setChatState($chatState)
954
            ->setSelfRegAllowed($selfRegistrationAllowed)
955
            ->setSelfUnregAllowed($selfUnRegistrationAllowed)
956
            ->setDocumentAccess($documentAccess)
957
            ->setGroupsPerUser($groupsPerUser)
958
            ->setParent($course)
959
            ->addCourseLink($course, $session)
960
        ;
961
962
        $repo = Container::getGroupCategoryRepository();
963
        $repo->create($category);
964
965
        return $category->getIid();
966
    }
967
968
    /**
969
     * Update group category.
970
     *
971
     * @param int    $id
972
     * @param string $title
973
     * @param string $description
974
     * @param $doc_state
975
     * @param $work_state
976
     * @param $calendar_state
977
     * @param $announcements_state
978
     * @param $forum_state
979
     * @param $wiki_state
980
     * @param $chat_state
981
     * @param $selfRegistrationAllowed
982
     * @param $selfUnRegistrationAllowed
983
     * @param $maximum_number_of_students
984
     * @param $groups_per_user
985
     * @param $documentAccess
986
     */
987
    public static function update_category(
988
        $id,
989
        $title,
990
        $description,
991
        $doc_state,
992
        $work_state,
993
        $calendar_state,
994
        $announcements_state,
995
        $forum_state,
996
        $wiki_state,
997
        $chat_state,
998
        $selfRegistrationAllowed,
999
        $selfUnRegistrationAllowed,
1000
        $maximum_number_of_students,
1001
        $groups_per_user,
1002
        $documentAccess
1003
    ) {
1004
        $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
1005
        $id = (int) $id;
1006
1007
        $allowDocumentAccess = api_get_configuration_value('group_category_document_access');
1008
        $documentCondition = '';
1009
        if ($allowDocumentAccess) {
1010
            $documentAccess = (int) $documentAccess;
1011
            $documentCondition = " document_access = $documentAccess, ";
1012
        }
1013
1014
        $sql = 'UPDATE '.$table." SET
1015
                    title='".Database::escape_string($title)."',
1016
                    description='".Database::escape_string($description)."',
1017
                    doc_state = '".Database::escape_string($doc_state)."',
1018
                    work_state = '".Database::escape_string($work_state)."',
1019
                    calendar_state = '".Database::escape_string($calendar_state)."',
1020
                    announcements_state = '".Database::escape_string($announcements_state)."',
1021
                    forum_state = '".Database::escape_string($forum_state)."',
1022
                    wiki_state = '".Database::escape_string($wiki_state)."',
1023
                    chat_state = '".Database::escape_string($chat_state)."',
1024
                    groups_per_user   = '".Database::escape_string($groups_per_user)."',
1025
                    self_reg_allowed = '".Database::escape_string($selfRegistrationAllowed)."',
1026
                    self_unreg_allowed = '".Database::escape_string($selfUnRegistrationAllowed)."',
1027
                    $documentCondition
1028
                    max_student = ".intval($maximum_number_of_students)."
1029
                WHERE iid = $id";
1030
        Database::query($sql);
1031
1032
        // Updating all groups inside this category
1033
        $groups = self::get_group_list($id);
1034
1035
        if (!empty($groups)) {
1036
            foreach ($groups as $group) {
1037
                self::set_group_properties(
1038
                    $group['iid'],
1039
                    $group['name'],
1040
                    $group['description'],
1041
                    $maximum_number_of_students,
1042
                    $doc_state,
1043
                    $work_state,
1044
                    $calendar_state,
1045
                    $announcements_state,
1046
                    $forum_state,
1047
                    $wiki_state,
1048
                    $chat_state,
1049
                    $selfRegistrationAllowed,
1050
                    $selfUnRegistrationAllowed,
1051
                    $id,
1052
                    $documentAccess
1053
                );
1054
            }
1055
        }
1056
    }
1057
1058
    /**
1059
     * Returns the number of groups of the user with the greatest number of
1060
     * subscriptions in the given category.
1061
     */
1062
    public static function get_current_max_groups_per_user($category_id = null, $course_code = null)
1063
    {
1064
        $course_info = api_get_course_info($course_code);
1065
        $group_table = Database::get_course_table(TABLE_GROUP);
1066
1067
        $group_user_table = Database::get_course_table(TABLE_GROUP_USER);
1068
        $sql = "SELECT COUNT(gu.group_id) AS current_max
1069
                FROM $group_user_table gu
1070
                INNER JOIN $group_table g
1071
                ON (gu.group_id = g.iid)
1072
                WHERE 1= 1 ";
1073
        if (null != $category_id) {
1074
            $category_id = intval($category_id);
1075
            $sql .= ' AND g.category_id = '.$category_id;
1076
        }
1077
        $sql .= ' GROUP BY gu.user_id
1078
                  ORDER BY current_max DESC LIMIT 1';
1079
1080
        $res = Database::query($sql);
1081
        $obj = Database::fetch_object($res);
1082
1083
        if ($obj) {
1084
            return $obj->current_max;
1085
        }
1086
1087
        return 0;
1088
    }
1089
1090
    /**
1091
     * Swaps the display-order of two categories.
1092
     *
1093
     * @param int $id1 The id of the first category
1094
     * @param int $id2 The id of the second category
1095
     */
1096
    public static function swap_category_order($id1, $id2)
1097
    {
1098
        $table = Database::get_course_table(TABLE_GROUP_CATEGORY);
1099
        $id1 = intval($id1);
1100
        $id2 = intval($id2);
1101
        $course_id = api_get_course_int_id();
1102
1103
        $sql = "SELECT id, display_order FROM $table
1104
                WHERE id IN ($id1,$id2) AND c_id = $course_id ";
1105
        $res = Database::query($sql);
1106
        $cat1 = Database::fetch_object($res);
1107
        $cat2 = Database::fetch_object($res);
1108
        if ($cat1 && $cat2) {
1109
            $sql = "UPDATE $table SET display_order=$cat2->display_order
1110
                    WHERE id = $cat1->id AND c_id = $course_id ";
1111
            Database::query($sql);
1112
1113
            $sql = "UPDATE $table SET display_order=$cat1->display_order
1114
                    WHERE id = $cat2->id AND c_id = $course_id ";
1115
            Database::query($sql);
1116
        }
1117
    }
1118
1119
    /**
1120
     * Get all users from a given group.
1121
     *
1122
     * @param int  $group_id        The group
1123
     * @param bool $load_extra_info
1124
     * @param int  $start
1125
     * @param int  $limit
1126
     * @param bool $getCount
1127
     * @param int  $courseId
1128
     * @param $column
1129
     * @param $direction
1130
     *
1131
     * @return array list of user id
1132
     */
1133
    public static function get_users(
1134
        $group_id,
1135
        $load_extra_info = false,
1136
        $start = null,
1137
        $limit = null,
1138
        $getCount = false,
1139
        $courseId = null,
1140
        $column = null,
1141
        $direction = null
1142
    ) {
1143
        $group_user_table = Database::get_course_table(TABLE_GROUP_USER);
1144
        $groupTable = Database::get_course_table(TABLE_GROUP);
1145
        $user_table = Database::get_main_table(TABLE_MAIN_USER);
1146
        $group_id = (int) $group_id;
1147
1148
        if (empty($courseId)) {
1149
            $courseId = api_get_course_int_id();
1150
        } else {
1151
            $courseId = (int) $courseId;
1152
        }
1153
1154
        $select = ' SELECT u.id, firstname, lastname ';
1155
        if ($getCount) {
1156
            $select = ' SELECT count(u.id) count';
1157
        }
1158
        $sql = "$select
1159
                FROM $group_user_table gu
1160
                INNER JOIN $groupTable g
1161
                ON (gu.group_id = g.iid)
1162
                INNER JOIN $user_table u
1163
                ON (u.id = gu.user_id)
1164
                WHERE
1165
                    g.iid = $group_id";
1166
1167
        if (!empty($column) && !empty($direction)) {
1168
            $column = Database::escape_string($column, null, false);
1169
            $direction = ('ASC' == $direction ? 'ASC' : 'DESC');
1170
            $sql .= " ORDER BY $column $direction";
1171
        }
1172
1173
        if (!empty($start) && !empty($limit)) {
1174
            $start = (int) $start;
1175
            $limit = (int) $limit;
1176
            $sql .= " LIMIT $start, $limit";
1177
        }
1178
        $res = Database::query($sql);
1179
        $users = [];
1180
        while ($obj = Database::fetch_object($res)) {
1181
            if ($getCount) {
1182
                return $obj->count;
1183
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1184
            }
1185
            if ($load_extra_info) {
1186
                $users[] = api_get_user_info($obj->id);
1187
            } else {
1188
                $users[] = $obj->id;
1189
            }
1190
        }
1191
1192
        return $users;
1193
    }
1194
1195
    /**
1196
     * @param int $group_id id
1197
     *
1198
     * @return array
1199
     */
1200
    public static function getStudentsAndTutors($group_id)
1201
    {
1202
        $group_user_table = Database::get_course_table(TABLE_GROUP_USER);
1203
        $tutor_user_table = Database::get_course_table(TABLE_GROUP_TUTOR);
1204
        $groupTable = Database::get_course_table(TABLE_GROUP);
1205
1206
        $course_id = api_get_course_int_id();
1207
        $group_id = (int) $group_id;
1208
1209
        $sql = "SELECT user_id
1210
                FROM $group_user_table gu
1211
                INNER JOIN $groupTable g
1212
                ON (gu.group_id = g.iid)
1213
                WHERE g.iid = $group_id";
1214
        $res = Database::query($sql);
1215
        $users = [];
1216
1217
        while ($obj = Database::fetch_object($res)) {
1218
            $users[] = api_get_user_info($obj->user_id);
1219
        }
1220
1221
        $sql = "SELECT user_id
1222
                FROM $tutor_user_table gu
1223
                INNER JOIN $groupTable g
1224
                ON (gu.group_id = g.iid)
1225
                WHERE g.iid = $group_id";
1226
        $res = Database::query($sql);
1227
        while ($obj = Database::fetch_object($res)) {
1228
            $users[] = api_get_user_info($obj->user_id);
1229
        }
1230
1231
        return $users;
1232
    }
1233
1234
    /**
1235
     * Get only tutors from a group.
1236
     *
1237
     * @param array $groupInfo
1238
     *
1239
     * @return array
1240
     */
1241
    public static function getTutors($groupInfo)
1242
    {
1243
        $groupTable = Database::get_course_table(TABLE_GROUP);
1244
        $tutor_user_table = Database::get_course_table(TABLE_GROUP_TUTOR);
1245
        $course_id = api_get_course_int_id();
1246
        $group_id = (int) $groupInfo['iid'];
1247
1248
        $sql = "SELECT user_id
1249
                FROM $tutor_user_table gu
1250
                INNER JOIN $groupTable g
1251
                ON (gu.group_id = g.iid)
1252
                WHERE g.iid = $group_id";
1253
        $res = Database::query($sql);
1254
1255
        $users = [];
1256
        while ($obj = Database::fetch_object($res)) {
1257
            $users[] = api_get_user_info($obj->user_id);
1258
        }
1259
1260
        return $users;
1261
    }
1262
1263
    /**
1264
     * Get only students from a group (not tutors).
1265
     *
1266
     * @param bool $filterOnlyActive
1267
     *
1268
     * @return array
1269
     */
1270
    public static function getStudents($groupId, $filterOnlyActive = false)
1271
    {
1272
        $groupId = (int) $groupId;
1273
        $activeCondition = $filterOnlyActive ? 'AND u.active = 1' : '';
1274
1275
        $em = Database::getManager();
1276
        $subscriptions = $em
1277
            ->createQuery("
1278
                SELECT u.id FROM ChamiloCoreBundle:User u
1279
                INNER JOIN ChamiloCourseBundle:CGroupRelUser gu
1280
                WITH u.id = gu.user
1281
                INNER JOIN ChamiloCourseBundle:CGroup g
1282
                WITH gu.group = g.iid
1283
                WHERE g.iid = :group
1284
                    $activeCondition
1285
            ")
1286
            ->setParameters([
1287
                'group' => $groupId,
1288
            ])
1289
            ->getResult();
1290
1291
        $users = [];
1292
        if (!empty($subscriptions)) {
1293
            foreach ($subscriptions as $subscription) {
1294
                $users[] = api_get_user_info($subscription['id']);
1295
            }
1296
        }
1297
1298
        return $users;
1299
    }
1300
1301
    public static function getStudentsCount($groupId, $filterOnlyActive = false)
1302
    {
1303
        $groupId = (int) $groupId;
1304
        $activeCondition = $filterOnlyActive ? 'AND u.active = 1' : '';
1305
1306
        $em = Database::getManager();
1307
1308
        return $em
1309
            ->createQuery("
1310
                SELECT COUNT(u.id) FROM ChamiloCoreBundle:User u
1311
                INNER JOIN ChamiloCourseBundle:CGroupRelUser gu
1312
                WITH u.id = gu.user
1313
                INNER JOIN ChamiloCourseBundle:CGroup g
1314
                WITH gu.group = g.iid
1315
                WHERE g.iid = :group
1316
                    $activeCondition
1317
            ")
1318
            ->setParameters([
1319
                'group' => $groupId,
1320
            ])
1321
            ->getSingleScalarResult();
1322
    }
1323
1324
    /**
1325
     * Returns users belonging to any of the group.
1326
     *
1327
     * @param array $groups list of group ids
1328
     *
1329
     * @return array list of user ids
1330
     */
1331
    public static function get_groups_users($groups = [])
1332
    {
1333
        $result = [];
1334
        $table = Database::get_course_table(TABLE_GROUP_USER);
1335
        $groups = array_map('intval', $groups);
1336
        // protect individual elements with surrounding quotes
1337
        $groups = implode(', ', $groups);
1338
        $sql = "SELECT DISTINCT user_id
1339
                FROM $table gu
1340
                WHERE gu.group_id IN ($groups)";
1341
        $rs = Database::query($sql);
1342
        while ($row = Database::fetch_array($rs)) {
1343
            $result[] = $row['user_id'];
1344
        }
1345
1346
        return $result;
1347
    }
1348
1349
    /**
1350
     * Fill the groups with students.
1351
     * The algorithm takes care to first fill the groups with the least # of users.
1352
     * Analysis
1353
     * There was a problem with the "ALL" setting.
1354
     * When max # of groups is set to all, the value is sometimes NULL and sometimes ALL
1355
     * and in both cased the query does not work as expected.
1356
     * Stupid solution (currently implemented: set ALL to a big number (INFINITE) and things are solved :)
1357
     * Better solution: that's up to you.
1358
     *
1359
     * Note
1360
     * Throughout Dokeos there is some confusion about "course id" and "course code"
1361
     * The code is e.g. TEST101, but sometimes a variable that is called courseID also contains a course code string.
1362
     * However, there is also a integer course_id that uniquely identifies the course.
1363
     * ywarnier:> Now the course_id has been removed (25/1/2005)
1364
     * The databases are als very inconsistent in this.
1365
     *
1366
     * @author Chrisptophe Gesche <[email protected]>,
1367
     *         Hugues Peeters     <[email protected]> - original version
1368
     * @author Roan Embrechts - virtual course support, code cleaning
1369
     * @author Bart Mollet - code cleaning, use other GroupManager-functions
1370
     *
1371
     * @return bool
1372
     */
1373
    public static function fillGroupWithUsers(CGroup $group)
1374
    {
1375
        $_course = api_get_course_info();
1376
        if (empty($_course) || empty($group)) {
1377
            return false;
1378
        }
1379
        $session_id = api_get_session_id();
1380
        $complete_user_list = CourseManager::get_user_list_from_course_code(
1381
            $_course['code'],
1382
            $session_id
1383
        );
1384
        $groupIid = $group->getIid();
1385
        $category = self::get_category_from_group($groupIid);
1386
1387
        // Getting max numbers of user from group
1388
        $maxNumberStudents = empty($group->getMaxStudent()) ? self::INFINITE : $group->getMaxStudent();
1389
        $groupsPerUser = self::INFINITE;
1390
        $categoryId = 0;
1391
        if ($category) {
1392
            $groupsPerUser = empty($category['groups_per_user']) ? self::INFINITE : $category['groups_per_user'];
1393
            $maxNumberStudentsCategory = empty($category['max_student']) ? self::INFINITE : $category['max_student'];
1394
            $categoryId = $category['iid'];
1395
            if ($maxNumberStudentsCategory < $maxNumberStudents) {
1396
                $maxNumberStudents = $maxNumberStudentsCategory;
1397
            }
1398
        }
1399
1400
        $usersToAdd = [];
1401
        foreach ($complete_user_list as $userInfo) {
1402
            $isSubscribed = self::is_subscribed($userInfo['user_id'], $group);
1403
            if ($isSubscribed) {
1404
                continue;
1405
            }
1406
            $numberOfGroups = self::user_in_number_of_groups(
1407
                $userInfo['user_id'],
1408
                $categoryId
1409
            );
1410
            if ($groupsPerUser > $numberOfGroups) {
1411
                $usersToAdd[] = $userInfo['user_id'];
1412
            }
1413
            if (count($usersToAdd) == $maxNumberStudents) {
1414
                break;
1415
            }
1416
        }
1417
1418
        foreach ($usersToAdd as $userId) {
1419
            self::subscribeUsers($userId, $group);
1420
        }
1421
    }
1422
1423
    /**
1424
     * Get the number of students in a group.
1425
     *
1426
     * @param int $group_id id
1427
     *
1428
     * @return int number of students in the given group
1429
     */
1430
    public static function number_of_students($group_id, $course_id = null)
1431
    {
1432
        $table = Database::get_course_table(TABLE_GROUP_USER);
1433
        $group_id = (int) $group_id;
1434
        $course_id = (int) $course_id;
1435
1436
        if (empty($course_id)) {
1437
            $course_id = api_get_course_int_id();
1438
        }
1439
        $sql = "SELECT COUNT(*) AS number_of_students
1440
                FROM $table
1441
                WHERE c_id = $course_id AND group_id = $group_id";
1442
        $result = Database::query($sql);
1443
        $db_object = Database::fetch_object($result);
1444
1445
        return $db_object->number_of_students;
1446
    }
1447
1448
    /**
1449
     * Maximum number of students in a group.
1450
     *
1451
     * @param int $group_id iid
1452
     *
1453
     * @return int maximum number of students in the given group
1454
     */
1455
    public static function maximum_number_of_students($group_id)
1456
    {
1457
        $table = Database::get_course_table(TABLE_GROUP);
1458
        $group_id = (int) $group_id;
1459
        $course_id = api_get_course_int_id();
1460
        $sql = "SELECT max_student FROM $table
1461
                WHERE iid = $group_id";
1462
        $db_result = Database::query($sql);
1463
        $db_object = Database::fetch_object($db_result);
1464
        if (0 == $db_object->max_student) {
1465
            return self::INFINITE;
1466
        }
1467
1468
        return $db_object->max_student;
1469
    }
1470
1471
    /**
1472
     * Number of groups of a user.
1473
     *
1474
     * @param int $user_id
1475
     * @param int $cat_id
1476
     *
1477
     * @return int the number of groups the user is subscribed in
1478
     */
1479
    public static function user_in_number_of_groups($user_id, $cat_id = 0)
1480
    {
1481
        $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
1482
        $table_group = Database::get_course_table(TABLE_GROUP);
1483
        $user_id = (int) $user_id;
1484
        $cat_id = (int) $cat_id;
1485
1486
        $course_id = api_get_course_int_id();
1487
        $cat_condition = '';
1488
        if (!empty($cat_id)) {
1489
            $cat_condition = " AND g.category_id =  $cat_id ";
1490
        }
1491
1492
        $sql = "SELECT COUNT(*) AS number_of_groups
1493
                FROM $table_group_user gu
1494
                INNER JOIN $table_group g
1495
                ON (g.iid = gu.group_id)
1496
                WHERE
1497
                    gu.user_id = $user_id
1498
                    $cat_condition";
1499
1500
        $result = Database::query($sql);
1501
        $db_object = Database::fetch_object($result);
1502
1503
        return $db_object->number_of_groups;
1504
    }
1505
1506
    /**
1507
     * Is sef-registration allowed?
1508
     *
1509
     * @param int $user_id
1510
     *
1511
     * @return bool TRUE if self-registration is allowed in the given group
1512
     */
1513
    public static function is_self_registration_allowed($user_id, CGroup $group)
1514
    {
1515
        if (empty($user_id)) {
1516
            return false;
1517
        }
1518
1519
        if ($group) {
1520
            if (0 == $group->getStatus() || 1 != $group->getSelfRegistrationAllowed()) {
1521
                return false;
1522
            }
1523
1524
            return self::canUserSubscribe($user_id, $group);
1525
        }
1526
1527
        return false;
1528
    }
1529
1530
    /**
1531
     * Is sef-unregistration allowed?
1532
     *
1533
     * @param int $user_id
1534
     *
1535
     * @return bool TRUE if self-unregistration is allowed in the given group
1536
     */
1537
    public static function is_self_unregistration_allowed($user_id, CGroup $group)
1538
    {
1539
        if (empty($user_id) || empty($group)) {
1540
            return false;
1541
        }
1542
        if (0 == $group->getStatus() || 1 != $group->getSelfUnregistrationAllowed()) {
1543
            return false;
1544
        }
1545
1546
        return self::is_subscribed($user_id, $group);
1547
    }
1548
1549
    /**
1550
     * Is user subscribed in group?
1551
     *
1552
     * @param int $user_id
1553
     *
1554
     * @return bool TRUE if given user is subscribed in given group
1555
     */
1556
    public static function is_subscribed($user_id, CGroup $group)
1557
    {
1558
        $course_id = api_get_course_int_id();
1559
        if (empty($user_id) || empty($group) || empty($course_id)) {
1560
            return false;
1561
        }
1562
        $table = Database::get_course_table(TABLE_GROUP_USER);
1563
        $group_id = $group->getIid();
1564
        $user_id = (int) $user_id;
1565
1566
        $sql = "SELECT 1 FROM $table
1567
                WHERE
1568
                    group_id = $group_id AND
1569
                    user_id = $user_id
1570
                ";
1571
        $result = Database::query($sql);
1572
1573
        return Database::num_rows($result) > 0;
1574
    }
1575
1576
    /**
1577
     * Can a user subscribe to a specified group in a course.
1578
     *
1579
     * @param int  $user_id
1580
     * @param bool $checkMaxNumberStudents
1581
     *
1582
     * @return bool true if success
1583
     */
1584
    public static function canUserSubscribe(
1585
        $user_id,
1586
        CGroup $group,
1587
        $checkMaxNumberStudents = true
1588
    ) {
1589
        $groupIid = $group->getIid();
1590
        if ($checkMaxNumberStudents) {
1591
            $category = self::get_category_from_group($group->getIid());
1592
            if ($category) {
1593
                if (self::GROUP_PER_MEMBER_NO_LIMIT == $category['groups_per_user']) {
1594
                    $category['groups_per_user'] = self::INFINITE;
1595
                }
1596
                $result = self::user_in_number_of_groups($user_id, $category['iid']) < $category['groups_per_user'];
1597
                if (false == $result) {
1598
                    return false;
1599
                }
1600
            }
1601
1602
            $result = self::number_of_students($groupIid) < self::maximum_number_of_students($groupIid);
1603
1604
            if (false == $result) {
1605
                return false;
1606
            }
1607
        }
1608
1609
        $result = self::isTutorOfGroup($user_id, $group);
1610
1611
        if ($result) {
1612
            return false;
1613
        }
1614
1615
        $result = self::is_subscribed($user_id, $group);
1616
1617
        if ($result) {
1618
            return false;
1619
        }
1620
1621
        return true;
1622
    }
1623
1624
    /**
1625
     * Get all subscribed users (members) from a group.
1626
     *
1627
     * @param array $groupInfo
1628
     *
1629
     * @return array An array with information of all users from the given group.
1630
     *               (user_id, firstname, lastname, email)
1631
     */
1632
    public static function get_subscribed_users($groupInfo)
1633
    {
1634
        if (empty($groupInfo)) {
1635
            return [];
1636
        }
1637
1638
        $table_user = Database::get_main_table(TABLE_MAIN_USER);
1639
        $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
1640
        $order_clause = api_sort_by_first_name() ? ' ORDER BY u.firstname, u.lastname' : ' ORDER BY u.lastname, u.firstname';
1641
        $orderListByOfficialCode = api_get_setting('order_user_list_by_official_code');
1642
        if ('true' === $orderListByOfficialCode) {
1643
            $order_clause = ' ORDER BY u.official_code, u.firstname, u.lastname';
1644
        }
1645
1646
        $group_id = (int) $groupInfo['iid'];
1647
1648
        if (empty($group_id)) {
1649
            return [];
1650
        }
1651
1652
        $course_id = api_get_course_int_id();
1653
1654
        $sql = "SELECT
1655
                    ug.iid,
1656
                    u.id as user_id,
1657
                    u.lastname,
1658
                    u.firstname,
1659
                    u.email,
1660
                    u.username
1661
                FROM $table_user u
1662
                INNER JOIN $table_group_user ug
1663
                ON (ug.user_id = u.id)
1664
                WHERE
1665
                      ug.group_id = $group_id
1666
                $order_clause";
1667
1668
        $db_result = Database::query($sql);
1669
        $users = [];
1670
        while ($user = Database::fetch_object($db_result)) {
1671
            $users[$user->user_id] = [
1672
                'user_id' => $user->user_id,
1673
                'firstname' => $user->firstname,
1674
                'lastname' => $user->lastname,
1675
                'email' => $user->email,
1676
                'username' => $user->username,
1677
            ];
1678
        }
1679
1680
        return $users;
1681
    }
1682
1683
    /**
1684
     * Subscribe user(s) to a specified group in current course (as a student).
1685
     *
1686
     * @param mixed  $userList  Can be an array with user-id's or a single user-id
1687
     * @param CGroup $group
1688
     * @param int    $course_id
1689
     *
1690
     * @return bool
1691
     */
1692
    public static function subscribeUsers($userList, CGroup $group = null, $course_id = null)
1693
    {
1694
        if (empty($group)) {
1695
            return false;
1696
        }
1697
        $userList = is_array($userList) ? $userList : [$userList];
1698
        $course_id = empty($course_id) ? api_get_course_int_id() : (int) $course_id;
1699
        $group_id = $group->getIid();
1700
1701
        if (!empty($userList)) {
1702
            $table = Database::get_course_table(TABLE_GROUP_USER);
1703
            foreach ($userList as $user_id) {
1704
                if (self::canUserSubscribe($user_id, $group)) {
1705
                    $user_id = (int) $user_id;
1706
                    $sql = "INSERT INTO $table (c_id, user_id, group_id, status, role)
1707
                            VALUES ('$course_id', '".$user_id."', '".$group_id."', 0, '')";
1708
                    Database::query($sql);
1709
                }
1710
            }
1711
        }
1712
1713
        return true;
1714
    }
1715
1716
    /**
1717
     * Subscribe tutor(s) to a specified group in current course.
1718
     *
1719
     * @param mixed $userList  Can be an array with user-id's or a single user-id
1720
     * @param array $groupInfo
1721
     * @param int   $course_id
1722
     */
1723
    public static function subscribeTutors($userList, CGroup $group = null, $course_id = 0)
1724
    {
1725
        if (empty($group)) {
1726
            return false;
1727
        }
1728
        $userList = is_array($userList) ? $userList : [$userList];
1729
        $result = true;
1730
        $course_id = isset($course_id) && !empty($course_id) ? intval($course_id) : api_get_course_int_id();
1731
        $table_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
1732
        $groupId = (int) $group->getIid();
1733
1734
        foreach ($userList as $user_id) {
1735
            $user_id = intval($user_id);
1736
            if (self::canUserSubscribe($user_id, $group, false)) {
1737
                $sql = 'INSERT INTO '.$table_group_tutor." (c_id, user_id, group_id)
1738
                        VALUES ('$course_id', '".$user_id."', '".$groupId."')";
1739
                $result = Database::query($sql);
1740
            }
1741
        }
1742
1743
        return $result;
1744
    }
1745
1746
    /**
1747
     * Unsubscribe user(s) from a specified group in current course.
1748
     *
1749
     * @param mixed $userList Can be an array with user-id's or a single user-id
1750
     *
1751
     * @return bool
1752
     */
1753
    public static function unsubscribeUsers($userList, CGroup $group = null)
1754
    {
1755
        if (empty($group)) {
1756
            return false;
1757
        }
1758
        $userList = is_array($userList) ? $userList : [$userList];
1759
        $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
1760
        $group_id = $group->getIid();
1761
        $course_id = api_get_course_int_id();
1762
        $sql = 'DELETE FROM '.$table_group_user.'
1763
                WHERE
1764
                    group_id = '.$group_id.' AND
1765
                    user_id IN ('.implode(',', $userList).')
1766
                ';
1767
        Database::query($sql);
1768
    }
1769
1770
    /**
1771
     * Unsubscribe all users from one or more groups.
1772
     *
1773
     * @param int $groupId
1774
     *
1775
     * @return bool
1776
     */
1777
    public static function unsubscribeAllUsers($groupId)
1778
    {
1779
        $groupId = (int) $groupId;
1780
        if (empty($groupId)) {
1781
            return false;
1782
        }
1783
1784
        $table = Database::get_course_table(TABLE_GROUP_USER);
1785
        $sql = "DELETE FROM $table
1786
                WHERE
1787
                    group_id = $groupId ";
1788
1789
        return Database::query($sql);
1790
    }
1791
1792
    /**
1793
     * Unsubscribe all tutors from one or more groups.
1794
     *
1795
     * @param int $groupId iid
1796
     *
1797
     * @see unsubscribe_all_users. This function is almost an exact copy of that function.
1798
     *
1799
     * @return bool TRUE if successful
1800
     *
1801
     * @author Patrick Cool <[email protected]>, Ghent University
1802
     */
1803
    public static function unsubscribe_all_tutors($groupId)
1804
    {
1805
        $courseId = api_get_course_int_id();
1806
        $groupId = (int) $groupId;
1807
1808
        if (empty($courseId) || empty($groupId)) {
1809
            return false;
1810
        }
1811
1812
        if (!empty($groupId)) {
1813
            $table_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
1814
            $sql = "DELETE FROM $table_group_tutor
1815
                    WHERE group_id = $groupId ";
1816
            Database::query($sql);
1817
        }
1818
1819
        return true;
1820
    }
1821
1822
    /**
1823
     * Is the user a tutor of this group?
1824
     *
1825
     * @todo replace this function with $group->isUserTutor
1826
     */
1827
    public static function isTutorOfGroup($userId, CGroup $group = null)
1828
    {
1829
        if (empty($group)) {
1830
            return false;
1831
        }
1832
1833
        $userId = (int) $userId;
1834
        $group_id = (int) $group->getIid();
1835
1836
        $table = Database::get_course_table(TABLE_GROUP_TUTOR);
1837
1838
        $sql = "SELECT * FROM $table
1839
                WHERE
1840
                    user_id = $userId AND
1841
                    group_id = $group_id";
1842
        $result = Database::query($sql);
1843
1844
        return Database::num_rows($result) > 0;
1845
    }
1846
1847
    /**
1848
     * Is the user part of this group? This can be a tutor or a normal member
1849
     * you should use this function if the access to a tool or functionality is
1850
     * restricted to the people who are actually in the group
1851
     * before you had to check if the user was
1852
     * 1. a member of the group OR
1853
     * 2. a tutor of the group. This function combines both.
1854
     */
1855
    public static function isUserInGroup($user_id, CGroup $group)
1856
    {
1857
        $member = self::is_subscribed($user_id, $group);
1858
        if ($member) {
1859
            return true;
1860
        }
1861
1862
        $tutor = self::isTutorOfGroup($user_id, $group);
1863
        if ($tutor) {
1864
            return true;
1865
        }
1866
1867
        return false;
1868
    }
1869
1870
    /**
1871
     * Get all group's from a given course in which a given user is unsubscribed.
1872
     *
1873
     * @author  Patrick Cool
1874
     *
1875
     * @param int $course_id retrieve the groups for
1876
     * @param int $user_id   the ID of the user you want to know all its group memberships
1877
     *
1878
     * @return array
1879
     */
1880
    public static function get_group_ids($course_id, $user_id)
1881
    {
1882
        $groups = [];
1883
        $tbl_group = Database::get_course_table(TABLE_GROUP_USER);
1884
        $tbl_group_tutor = Database::get_course_table(TABLE_GROUP_TUTOR);
1885
        $user_id = intval($user_id);
1886
        $course_id = intval($course_id);
1887
1888
        $sql = "SELECT group_id FROM $tbl_group
1889
                WHERE user_id = '$user_id'";
1890
        $result = Database::query($sql);
1891
1892
        if ($result) {
1893
            while ($row = Database::fetch_array($result)) {
1894
                $groups[] = $row['group_id'];
1895
            }
1896
        }
1897
1898
        //Also loading if i'm the tutor
1899
        $sql = "SELECT group_id FROM $tbl_group_tutor
1900
                WHERE user_id = '$user_id'";
1901
        $result = Database::query($sql);
1902
        if ($result) {
1903
            while ($row = Database::fetch_array($result)) {
1904
                $groups[] = $row['group_id'];
1905
            }
1906
        }
1907
        if (!empty($groups)) {
1908
            array_filter($groups);
1909
        }
1910
1911
        return $groups;
1912
    }
1913
1914
    /**
1915
     * Check if a user has access to a certain group tool.
1916
     *
1917
     * @param int    $user_id The user id
1918
     * @param CGroup $group
1919
     * @param string $tool    The tool to check the access rights. This should be
1920
     *                        one of constants: GROUP_TOOL_DOCUMENTS
1921
     *
1922
     * @return bool true if the given user has access to the given tool in the
1923
     *              given course
1924
     */
1925
    public static function userHasAccess($user_id, CGroup $group = null, $tool)
1926
    {
1927
        if (null === $group) {
1928
            return false;
1929
        }
1930
1931
        // Admin have access everywhere
1932
        if (api_is_platform_admin()) {
1933
            return true;
1934
        }
1935
1936
        // Course admin also have access to everything
1937
        if (api_is_allowed_to_edit(false, true, true)) {
1938
            return true;
1939
        }
1940
1941
        if (0 == $group->getStatus()) {
1942
            return false;
1943
        }
1944
1945
        switch ($tool) {
1946
            case self::GROUP_TOOL_FORUM:
1947
                $toolStatus = $group->getForumState();
1948
                break;
1949
            case self::GROUP_TOOL_DOCUMENTS:
1950
                $toolStatus = $group->getDocState();
1951
                break;
1952
            case self::GROUP_TOOL_CALENDAR:
1953
                $toolStatus = $group->getCalendarState();
1954
                break;
1955
            case self::GROUP_TOOL_ANNOUNCEMENT:
1956
                $toolStatus = $group->getAnnouncementsState();
1957
                break;
1958
            case self::GROUP_TOOL_WORK:
1959
                $toolStatus = $group->getWorkState();
1960
                break;
1961
            case self::GROUP_TOOL_WIKI:
1962
                $toolStatus = $group->getWikiState();
1963
                break;
1964
            case self::GROUP_TOOL_CHAT:
1965
                $toolStatus = $group->getChatState();
1966
                break;
1967
            default:
1968
                return false;
1969
        }
1970
1971
        switch ($toolStatus) {
1972
            case self::TOOL_NOT_AVAILABLE:
1973
                return false;
1974
                break;
0 ignored issues
show
Unused Code introduced by
break is not strictly necessary here and could be removed.

The break statement is not necessary if it is preceded for example by a return statement:

switch ($x) {
    case 1:
        return 'foo';
        break; // This break is not necessary and can be left off.
}

If you would like to keep this construct to be consistent with other case statements, you can safely mark this issue as a false-positive.

Loading history...
1975
            case self::TOOL_PUBLIC:
1976
                return true;
1977
                break;
1978
            case self::TOOL_PRIVATE:
1979
                $userIsInGroup = self::isUserInGroup($user_id, $group);
1980
                if ($userIsInGroup) {
1981
                    return true;
1982
                }
1983
                break;
1984
            case self::TOOL_PRIVATE_BETWEEN_USERS:
1985
                // Only works for announcements for now
1986
                $userIsInGroup = self::isUserInGroup($user_id, $group);
1987
                if ($userIsInGroup && self::GROUP_TOOL_ANNOUNCEMENT == $tool) {
1988
                    return true;
1989
                }
1990
                break;
1991
        }
1992
1993
        return false;
1994
    }
1995
1996
    /**
1997
     * @param int $userId
1998
     * @param int $sessionId
1999
     *
2000
     * @return bool
2001
     */
2002
    public static function userHasAccessToBrowse($userId, CGroup $group = null, $sessionId = 0)
2003
    {
2004
        if (null === $group) {
2005
            return false;
2006
        }
2007
2008
        if (api_is_platform_admin()) {
2009
            return true;
2010
        }
2011
2012
        if (api_is_allowed_to_edit(false, true, true)) {
2013
            return true;
2014
        }
2015
2016
        if (!empty($sessionId)) {
2017
            if (api_is_coach($sessionId, api_get_course_int_id())) {
2018
                return true;
2019
            }
2020
2021
            if (api_is_drh()) {
2022
                if (SessionManager::isUserSubscribedAsHRM($sessionId, $userId)) {
2023
                    return true;
2024
                }
2025
            }
2026
        }
2027
2028
        if (self::isTutorOfGroup($userId, $group)) {
2029
            return true;
2030
        }
2031
2032
        if (0 == $group->getStatus()) {
2033
            return false;
2034
        }
2035
2036
        if (self::userHasAccess($userId, $group, self::GROUP_TOOL_FORUM) ||
2037
            self::userHasAccess($userId, $group, self::GROUP_TOOL_DOCUMENTS) ||
2038
            self::userHasAccess($userId, $group, self::GROUP_TOOL_CALENDAR) ||
2039
            self::userHasAccess($userId, $group, self::GROUP_TOOL_ANNOUNCEMENT) ||
2040
            self::userHasAccess($userId, $group, self::GROUP_TOOL_WORK) ||
2041
            self::userHasAccess($userId, $group, self::GROUP_TOOL_WIKI) ||
2042
            self::userHasAccess($userId, $group, self::GROUP_TOOL_CHAT)
2043
        ) {
2044
            return true;
2045
        }
2046
        //@todo check group session id
2047
        $groupSessionId = null;
2048
2049
        if (api_is_session_general_coach() && $groupSessionId == $sessionId) {
2050
            return true;
2051
        }
2052
2053
        return false;
2054
    }
2055
2056
    /**
2057
     * Get all groups where a specific user is subscribed.
2058
     *
2059
     * @param int $user_id
2060
     *
2061
     * @return array
2062
     */
2063
    public static function get_user_group_name($user_id)
2064
    {
2065
        $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
2066
        $table_group = Database::get_course_table(TABLE_GROUP);
2067
        $user_id = intval($user_id);
2068
        $course_id = api_get_course_int_id();
2069
        $sql = "SELECT name
2070
                FROM $table_group g
2071
                INNER JOIN $table_group_user gu
2072
                ON (gu.group_id = g.iid)
2073
                WHERE
2074
                  gu.user_id = $user_id";
2075
        $res = Database::query($sql);
2076
        $groups = [];
2077
        while ($group = Database::fetch_array($res)) {
2078
            $groups[] .= $group['name'];
2079
        }
2080
2081
        return $groups;
2082
    }
2083
2084
    /**
2085
     * Get all groups where a specific user is subscribed.
2086
     *
2087
     * @param int      $user_id
2088
     * @param int      $courseId
2089
     * @param int|null $sessionId
2090
     *
2091
     * @return array
2092
     */
2093
    public static function getAllGroupPerUserSubscription($user_id, $courseId = 0, $sessionId = null)
2094
    {
2095
        $table_group_user = Database::get_course_table(TABLE_GROUP_USER);
2096
        $table_tutor_user = Database::get_course_table(TABLE_GROUP_TUTOR);
2097
        $table_group = Database::get_course_table(TABLE_GROUP);
2098
        $user_id = (int) $user_id;
2099
        $courseId = empty($courseId) ? api_get_course_int_id() : (int) $courseId;
2100
2101
        $sql = "SELECT DISTINCT g.*
2102
               FROM $table_group g
2103
               LEFT JOIN $table_group_user gu
2104
               ON (gu.group_id = g.iid)
2105
               LEFT JOIN $table_tutor_user tu
2106
               ON (tu.group_id = g.iid)
2107
               WHERE
2108
                  (gu.user_id = $user_id OR tu.user_id = $user_id) ";
2109
2110
        if (null !== $sessionId) {
2111
            $sessionId = (int) $sessionId;
2112
            $sql .= " AND g.session_id = $sessionId ";
2113
        }
2114
2115
        $res = Database::query($sql);
2116
        $groups = [];
2117
        while ($group = Database::fetch_array($res, 'ASSOC')) {
2118
            $groups[] = $group;
2119
        }
2120
2121
        return $groups;
2122
    }
2123
2124
    /**
2125
     * @param CGroup[] $groupList
2126
     * @param int      $category_id
2127
     *
2128
     * @return string
2129
     */
2130
    public static function processGroups($groupList, $category_id = 0)
2131
    {
2132
        $charset = 'UTF-8';
2133
        $category_id = (int) $category_id;
2134
        $totalRegistered = 0;
2135
        $group_data = [];
2136
        $user_info = api_get_user_info();
2137
        $session_id = api_get_session_id();
2138
        $user_id = $user_info['user_id'];
2139
        $hideGroup = api_get_setting('hide_course_group_if_no_tools_available');
2140
        $extraField = new ExtraField('survey');
2141
        $surveyGroupExists = $extraField->get_handler_field_info_by_field_variable('group_id') ? true : false;
2142
        $url = api_get_path(WEB_CODE_PATH).'group/';
2143
2144
        foreach ($groupList as $group) {
2145
            $groupId = $group->getIid();
2146
2147
            // Validation when belongs to a session
2148
            $session_img = '';
2149
            //$session_img = api_get_session_image($group['session_id'], $user_info['status']);
2150
2151
            // All the tutors of this group
2152
            $tutors = $group->getTutors();
2153
            $isMember = self::is_subscribed($user_id, $group);
2154
2155
            // Create a new table-row
2156
            $row = [];
2157
            // Checkbox
2158
            if (api_is_allowed_to_edit(false, true) && count($groupList) > 1) {
2159
                $row[] = $groupId;
2160
            }
2161
2162
            if (self::userHasAccessToBrowse($user_id, $group, $session_id)) {
2163
                // Group name
2164
                $groupNameClass = null;
2165
                if (0 == $group->getStatus()) {
2166
                    $groupNameClass = 'muted';
2167
                }
2168
2169
                $group_name = '<a
2170
                    class="'.$groupNameClass.'"
2171
                    href="group_space.php?'.api_get_cidreq(true, false).'&gid='.$groupId.'">'.
2172
                    Security::remove_XSS($group->getName()).'</a> ';
2173
2174
                $group_name2 = '';
2175
                if (api_get_configuration_value('extra')) {
2176
                    $group_name2 = '<a
2177
                        href="group_space_tracking.php?cid='.api_get_course_int_id().'&gid='.$groupId.'">'.
2178
                        get_lang('suivi_de').''.stripslashes($group->getName()).'</a>';
2179
                }
2180
2181
                /*
2182
                if (!empty($user_id) && !empty($this_group['id_tutor']) && $user_id == $this_group['id_tutor']) {
2183
                    $group_name .= Display::label(get_lang('my supervision'), 'success');
2184
                } elseif ($isMember) {
2185
                    $group_name .= Display::label(get_lang('my group'), 'success');
2186
                }*/
2187
2188
                /*if (api_is_allowed_to_edit() && !empty($this_group['session_name'])) {
2189
                    $group_name .= ' ('.$this_group['session_name'].')';
2190
                }
2191
                $group_name .= $session_img;*/
2192
2193
                $row[] = $group_name.$group_name2.'<br />'.stripslashes(trim($group->getDescription()));
2194
            } else {
2195
                if ('true' === $hideGroup) {
2196
                    continue;
2197
                }
2198
                $row[] = $group->getName().'<br />'.stripslashes(trim($group->getDescription()));
2199
            }
2200
2201
            // Tutor name
2202
            $tutor_info = '';
2203
            if (count($tutors) > 0) {
2204
                foreach ($tutors as $tutorGroup) {
2205
                    $tutor = $tutorGroup->getUser();
2206
                    $username = api_htmlentities(
2207
                        sprintf(get_lang('Login: %s'), $tutor->getUsername()),
2208
                        ENT_QUOTES
2209
                    );
2210
                    if ('true' === api_get_setting('show_email_addresses')) {
2211
                        $tutor_info .= Display::tag(
2212
                            'span',
2213
                            Display::encrypted_mailto_link(
2214
                                $tutor->getEmail(),
2215
                                UserManager::formatUserFullName($tutor)
2216
                            ),
2217
                            ['title' => $username]
2218
                        ).', ';
2219
                    } else {
2220
                        if (api_is_allowed_to_edit()) {
2221
                            $tutor_info .= Display::tag(
2222
                            'span',
2223
                                Display::encrypted_mailto_link(
2224
                                    $tutor->getEmail(),
2225
                                    UserManager::formatUserFullName($tutor)
2226
                                ),
2227
                                ['title' => $username]
2228
                            ).', ';
2229
                        } else {
2230
                            $tutor_info .= Display::tag(
2231
                                'span',
2232
                                    UserManager::formatUserFullName($tutor),
2233
                                ['title' => $username]
2234
                            ).', ';
2235
                        }
2236
                    }
2237
                }
2238
            }
2239
2240
            $tutor_info = api_substr(
2241
                $tutor_info,
2242
                0,
2243
                api_strlen($tutor_info) - 2
2244
            );
2245
            $row[] = $tutor_info;
2246
2247
            // Max number of members in group
2248
            $max_members = self::MEMBER_PER_GROUP_NO_LIMIT == $group->getMaxStudent() ? ' ' : ' / '.$group->getMaxStudent();
2249
            $registeredUsers = self::getStudentsCount($groupId);
2250
            // Number of members in group
2251
            $row[] = $registeredUsers.$max_members;
2252
            $confirmMessage = addslashes(
2253
                api_htmlentities(get_lang('Please confirm your choice'), ENT_QUOTES, $charset)
2254
            );
2255
            // Self-registration / unregistration
2256
            if (!api_is_allowed_to_edit(false, true)) {
2257
                if (self::is_self_registration_allowed($user_id, $group)) {
2258
                    $row[] = '<a
2259
                        class = "btn btn-default"
2260
                        href="group.php?'.api_get_cidreq().'&category='.$category_id.'&action=self_reg&group_id='.$groupId.'"
2261
                        onclick="javascript:if(!confirm('."'".$confirmMessage."'".')) return false;">'.get_lang('register').'</a>';
2262
                } elseif (self::is_self_unregistration_allowed($user_id, $group)) {
2263
                    $row[] = '<a
2264
                        class = "btn btn-default"
2265
                        href="group.php?'.api_get_cidreq().'&category='.$category_id.'&action=self_unreg&group_id='.$groupId.'"
2266
                        onclick="javascript:if(!confirm('."'".$confirmMessage."'".')) return false;">'.get_lang('unregister').'</a>';
2267
                } else {
2268
                    $row[] = '-';
2269
                }
2270
            }
2271
2272
            // @todo fix group session access.
2273
            $groupSessionId = null;
2274
2275
            // Edit-links
2276
            if (api_is_allowed_to_edit(false, true) &&
2277
                !(api_is_session_general_coach() && $groupSessionId != $session_id)
2278
            ) {
2279
                $edit_actions = '<a
2280
                    href="'.$url.'settings.php?'.api_get_cidreq(true, false).'&gid='.$groupId.'"
2281
                    title="'.get_lang('Edit').'">'.
2282
                    Display::return_icon('edit.png', get_lang('Edit this group'), '', ICON_SIZE_SMALL).
2283
                    '</a>&nbsp;';
2284
2285
                if (1 == $group->getStatus()) {
2286
                    $edit_actions .= '<a
2287
                        href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=set_invisible&group_id='.$groupId.'"
2288
                        title="'.get_lang('Hide').'">'.
2289
                        Display::return_icon('visible.png', get_lang('Hide'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
2290
                } else {
2291
                    $edit_actions .= '<a
2292
                        href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=set_visible&group_id='.$groupId.'"
2293
                        title="'.get_lang('Show').'">'.
2294
                        Display::return_icon('invisible.png', get_lang('Show'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
2295
                }
2296
2297
                $edit_actions .= '<a
2298
                    href="'.$url.'member_settings.php?'.api_get_cidreq(true, false).'&gid='.$groupId.'"
2299
                    title="'.get_lang('Group members').'">'.
2300
                    Display::return_icon('user.png', get_lang('Group members'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
2301
2302
                $edit_actions .= '<a
2303
                    href="'.$url.'group_overview.php?action=export&type=xls&'.api_get_cidreq(true, false).'&id='.$groupId.'"
2304
                    title="'.get_lang('Export users list').'">'.
2305
                    Display::return_icon('export_excel.png', get_lang('Export'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
2306
2307
                if ($surveyGroupExists) {
2308
                    $edit_actions .= Display::url(
2309
                        Display::return_icon('survey.png', get_lang('ExportSurveyResults'), '', ICON_SIZE_SMALL),
2310
                        $url.'group_overview.php?action=export_surveys&'.api_get_cidreq(true, false).'&id='.$groupId
2311
                    ).'&nbsp;';
2312
                }
2313
                $edit_actions .= '<a
2314
                    href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=fill_one&group_id='.$groupId.'"
2315
                    onclick="javascript: if(!confirm('."'".$confirmMessage."'".')) return false;" title="'.get_lang('FillGroup').'">'.
2316
                    Display::return_icon('fill.png', get_lang('FillGroup'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
2317
2318
                $edit_actions .= '<a
2319
                    href="'.api_get_self().'?'.api_get_cidreq(true, false).'&category='.$category_id.'&action=delete_one&group_id='.$groupId.'"
2320
                    onclick="javascript: if(!confirm('."'".$confirmMessage."'".')) return false;" title="'.get_lang('Delete').'">'.
2321
                    Display::return_icon('delete.png', get_lang('Delete'), '', ICON_SIZE_SMALL).'</a>&nbsp;';
2322
2323
                $row[] = $edit_actions;
2324
            }
2325
2326
            /*if (!empty($this_group['nbMember'])) {
2327
                $totalRegistered = $totalRegistered + $this_group['nbMember'];
2328
            }*/
2329
            $group_data[] = $row;
2330
        }
2331
2332
        // If no groups then don't show the table (only for students)
2333
        if (!api_is_allowed_to_edit(true, false)) {
2334
            if (empty($group_data)) {
2335
                return '';
2336
            }
2337
        }
2338
2339
        $table = new SortableTableFromArrayConfig(
2340
            $group_data,
2341
            1,
2342
            20,
2343
            'group_category_'.$category_id
2344
        );
2345
        $table->set_additional_parameters(['category' => $category_id]);
2346
        $column = 0;
2347
        if (api_is_allowed_to_edit(false, true) && count($groupList) > 1) {
2348
            $table->set_header($column++, '', false);
2349
        }
2350
        $table->set_header($column++, get_lang('Groups'));
2351
        $table->set_header($column++, get_lang('Group tutor'));
2352
        $table->set_header($column++, get_lang('Registered'), false);
2353
2354
        if (!api_is_allowed_to_edit(false, true)) {
2355
            // If self-registration allowed
2356
            $table->set_header($column++, get_lang('Registration'), false);
2357
        }
2358
2359
        if (api_is_allowed_to_edit(false, true)) {
2360
            // Only for course administrator
2361
            $table->set_header($column++, get_lang('Edit'), false);
2362
            $form_actions = [];
2363
            $form_actions['fill_selected'] = get_lang('Fill the group randomly with course students');
2364
            $form_actions['empty_selected'] = get_lang('unsubscribe all users');
2365
            $form_actions['delete_selected'] = get_lang('Delete');
2366
            if (count($groupList) > 1) {
2367
                $table->set_form_actions($form_actions, 'group');
2368
            }
2369
        }
2370
2371
        return $table->return_table();
2372
    }
2373
2374
    /**
2375
     * @param array $groupData
2376
     * @param bool  $deleteNotInArray
2377
     *
2378
     * @return array
2379
     */
2380
    public static function importCategoriesAndGroupsFromArray($groupData, $deleteNotInArray = false)
2381
    {
2382
        $result = [];
2383
        $elementsFound = [
2384
            'categories' => [],
2385
            'groups' => [],
2386
        ];
2387
2388
        $courseCode = api_get_course_id();
2389
        $sessionId = api_get_session_id();
2390
        $groupCategories = self::get_categories();
2391
2392
        if (empty($groupCategories)) {
2393
            $result['error'][] = get_lang('Create a category');
2394
2395
            return $result;
2396
        }
2397
2398
        foreach ($groupData as $data) {
2399
            $isCategory = empty($data['group']) ? true : false;
2400
            if ($isCategory) {
2401
                $categoryInfo = self::getCategoryByTitle($data['category']);
2402
                $categoryId = $categoryInfo['iid'];
2403
2404
                if (!empty($categoryInfo)) {
2405
                    // Update
2406
                    self::update_category(
2407
                        $categoryId,
2408
                        $data['category'],
2409
                        $data['description'],
2410
                        $data['doc_state'],
2411
                        $data['work_state'],
2412
                        $data['calendar_state'],
2413
                        $data['announcements_state'],
2414
                        $data['forum_state'],
2415
                        $data['wiki_state'],
2416
                        $data['chat_state'],
2417
                        $data['self_reg_allowed'],
2418
                        $data['self_unreg_allowed'],
2419
                        $data['max_student'],
2420
                        $data['groups_per_user'],
2421
                        $data['document_access']
2422
                    );
2423
                    $data['category_id'] = $categoryId;
2424
                    $result['updated']['category'][] = $data;
2425
                } else {
2426
                    // Add
2427
                    $categoryId = self::create_category(
2428
                        $data['category'],
2429
                        $data['description'],
2430
                        $data['doc_state'],
2431
                        $data['work_state'],
2432
                        $data['calendar_state'],
2433
                        $data['announcements_state'],
2434
                        $data['forum_state'],
2435
                        $data['wiki_state'],
2436
                        $data['chat_state'],
2437
                        $data['self_reg_allowed'],
2438
                        $data['self_unreg_allowed'],
2439
                        $data['max_student'],
2440
                        $data['groups_per_user']
2441
                    );
2442
2443
                    if ($categoryId) {
2444
                        $data['category_id'] = $categoryId;
2445
                        $result['added']['category'][] = $data;
2446
                    }
2447
                }
2448
                $elementsFound['categories'][] = $categoryId;
2449
            } else {
2450
                $groupInfo = self::getGroupByName($data['group']);
2451
                $categoryInfo = [];
2452
                if (isset($data['category'])) {
2453
                    $categoryInfo = self::getCategoryByTitle($data['category']);
2454
                }
2455
                $categoryId = null;
2456
                if (!empty($categoryInfo)) {
2457
                    $categoryId = $categoryInfo['iid'];
2458
                } else {
2459
                    if (!empty($groupCategories) && isset($groupCategories[0])) {
2460
                        $defaultGroupCategory = $groupCategories[0];
2461
                        $categoryId = $defaultGroupCategory['iid'];
2462
                    }
2463
                }
2464
2465
                if (empty($groupInfo)) {
2466
                    // Add
2467
                    $groupId = self::create_group(
2468
                        $data['group'],
2469
                        $categoryId,
2470
                        null,
2471
                        $data['max_student']
2472
                    );
2473
2474
                    if ($groupId) {
2475
                        self::set_group_properties(
2476
                            $groupId,
2477
                            $data['group'],
2478
                            $data['description'],
2479
                            $data['max_student'],
2480
                            $data['doc_state'],
2481
                            $data['work_state'],
2482
                            $data['calendar_state'],
2483
                            $data['announcements_state'],
2484
                            $data['forum_state'],
2485
                            $data['wiki_state'],
2486
                            $data['chat_state'],
2487
                            $data['self_reg_allowed'],
2488
                            $data['self_unreg_allowed'],
2489
                            $categoryId
2490
                        );
2491
                        $data['group_id'] = $groupId;
2492
                        $result['added']['group'][] = $data;
2493
                    }
2494
                    $groupInfo = self::get_group_properties($groupId, true);
2495
                } else {
2496
                    // Update
2497
                    $groupId = $groupInfo['iid'];
2498
                    self::set_group_properties(
2499
                        $groupId,
2500
                        $data['group'],
2501
                        $data['description'],
2502
                        $data['max_student'],
2503
                        $data['doc_state'],
2504
                        $data['work_state'],
2505
                        $data['calendar_state'],
2506
                        $data['announcements_state'],
2507
                        $data['forum_state'],
2508
                        $data['wiki_state'],
2509
                        $data['chat_state'],
2510
                        $data['self_reg_allowed'],
2511
                        $data['self_unreg_allowed'],
2512
                        $categoryId
2513
                    );
2514
2515
                    $data['group_id'] = $groupId;
2516
                    $result['updated']['group'][] = $data;
2517
                    $groupInfo = self::get_group_properties($groupId);
2518
                }
2519
2520
                $students = isset($data['students']) ? explode(',', $data['students']) : [];
2521
                if (!empty($students)) {
2522
                    $studentUserIdList = [];
2523
                    foreach ($students as $student) {
2524
                        $userInfo = api_get_user_info_from_username($student);
2525
2526
                        if (!$userInfo) {
2527
                            continue;
2528
                        }
2529
2530
                        if (!CourseManager::is_user_subscribed_in_course(
2531
                                $userInfo['user_id'],
2532
                                $courseCode,
2533
                                !empty($sessionId),
2534
                                $sessionId
2535
                            )
2536
                        ) {
2537
                            Display::addFlash(
2538
                                Display::return_message(
2539
                                    sprintf(
2540
                                        get_lang('Student %s is no subscribed to this course'),
2541
                                        $userInfo['complete_name']
2542
                                    ),
2543
                                    'warning'
2544
                                )
2545
                            );
2546
                            continue;
2547
                        }
2548
2549
                        $studentUserIdList[] = $userInfo['user_id'];
2550
                    }
2551
                    self::subscribeUsers($studentUserIdList, api_get_group_entity($groupInfo['iid']));
2552
                }
2553
2554
                $tutors = isset($data['tutors']) ? explode(',', $data['tutors']) : [];
2555
                if (!empty($tutors)) {
2556
                    $tutorIdList = [];
2557
                    foreach ($tutors as $tutor) {
2558
                        $userInfo = api_get_user_info_from_username($tutor);
2559
2560
                        if (!$userInfo) {
2561
                            continue;
2562
                        }
2563
2564
                        if (!CourseManager::is_user_subscribed_in_course(
2565
                                $userInfo['user_id'],
2566
                                $courseCode,
2567
                                !empty($sessionId),
2568
                                $sessionId
2569
                            )
2570
                        ) {
2571
                            Display::addFlash(
2572
                                Display::return_message(
2573
                                    sprintf(get_lang('Tutor %s is no subscribed to this course'), $userInfo['complete_name']),
2574
                                    'warning'
2575
                                )
2576
                            );
2577
2578
                            continue;
2579
                        }
2580
2581
                        $tutorIdList[] = $userInfo['user_id'];
2582
                    }
2583
                    self::subscribeTutors($tutorIdList, api_get_group_entity($groupInfo['iid']));
2584
                }
2585
2586
                $elementsFound['groups'][] = $groupId;
2587
            }
2588
        }
2589
2590
        if ($deleteNotInArray) {
2591
            // Check categories
2592
            $categories = self::get_categories();
2593
            foreach ($categories as $category) {
2594
                if (!in_array($category['iid'], $elementsFound['categories'])) {
2595
                    self::delete_category($category['iid']);
2596
                    $category['category'] = $category['title'];
2597
                    $result['deleted']['category'][] = $category;
2598
                }
2599
            }
2600
2601
            $groups = self::get_groups();
2602
            foreach ($groups as $group) {
2603
                if (!in_array($group->getIid(), $elementsFound['groups'])) {
2604
                    self::deleteGroup($group);
2605
                    $result['deleted']['group'][] = $group;
2606
                }
2607
            }
2608
        }
2609
2610
        return $result;
2611
    }
2612
2613
    /**
2614
     * Export all categories/group from a course to an array.
2615
     * This function works only in a context of a course.
2616
     *
2617
     * @param int  $groupId
2618
     * @param bool $loadUsers
2619
     *
2620
     * @return array
2621
     */
2622
    public static function exportCategoriesAndGroupsToArray($groupId = null, $loadUsers = false)
2623
    {
2624
        $data = [];
2625
        $data[] = [
2626
            'category',
2627
            'group',
2628
            'description',
2629
            'announcements_state',
2630
            'calendar_state',
2631
            'chat_state',
2632
            'doc_state',
2633
            'forum_state',
2634
            'work_state',
2635
            'wiki_state',
2636
            'max_student',
2637
            'self_reg_allowed',
2638
            'self_unreg_allowed',
2639
            'groups_per_user',
2640
        ];
2641
2642
        $count = 1;
2643
2644
        if ($loadUsers) {
2645
            $data[0][] = 'students';
2646
            $data[0][] = 'tutors';
2647
        }
2648
2649
        if (false == $loadUsers) {
2650
            $categories = self::get_categories();
2651
2652
            foreach ($categories as $categoryInfo) {
2653
                $data[$count] = [
2654
                    $categoryInfo['title'],
2655
                    null,
2656
                    $categoryInfo['description'],
2657
                    $categoryInfo['announcements_state'],
2658
                    $categoryInfo['calendar_state'],
2659
                    $categoryInfo['chat_state'],
2660
                    $categoryInfo['doc_state'],
2661
                    $categoryInfo['forum_state'],
2662
                    $categoryInfo['work_state'],
2663
                    $categoryInfo['wiki_state'],
2664
                    $categoryInfo['max_student'],
2665
                    $categoryInfo['self_reg_allowed'],
2666
                    $categoryInfo['self_unreg_allowed'],
2667
                    $categoryInfo['groups_per_user'],
2668
                ];
2669
                $count++;
2670
            }
2671
        }
2672
2673
        $groups = self::get_group_list();
2674
        foreach ($groups as $groupInfo) {
2675
            $groupId = $groupInfo['iid'];
2676
            $categoryTitle = null;
2677
            $categoryInfo = [];
2678
            if (isset($groupInfo['category'])) {
2679
                $categoryInfo = self::get_category($groupInfo['category']);
2680
            }
2681
2682
            $groupSettings = self::get_group_properties($groupId);
2683
            if (!empty($categoryInfo)) {
2684
                $categoryTitle = $categoryInfo['title'];
2685
            }
2686
2687
            $users = self::getStudents($groupId);
2688
            $userList = [];
2689
            foreach ($users as $user) {
2690
                $user = api_get_user_info($user['user_id']);
2691
                $userList[] = $user['username'];
2692
            }
2693
2694
            $tutors = self::getTutors($groupInfo);
2695
            $tutorList = [];
2696
            foreach ($tutors as $user) {
2697
                $user = api_get_user_info($user['user_id']);
2698
                $tutorList[] = $user['username'];
2699
            }
2700
2701
            $userListToString = null;
2702
            if (!empty($userList)) {
2703
                $userListToString = implode(',', $userList);
2704
            }
2705
2706
            $tutorListToString = null;
2707
            if (!empty($tutorList)) {
2708
                $tutorListToString = implode(',', $tutorList);
2709
            }
2710
2711
            $data[$count] = [
2712
                $categoryTitle,
2713
                $groupSettings['name'],
2714
                $groupSettings['description'],
2715
                $groupSettings['announcements_state'],
2716
                $groupSettings['calendar_state'],
2717
                $groupSettings['chat_state'],
2718
                $groupSettings['doc_state'],
2719
                $groupSettings['forum_state'],
2720
                $groupSettings['work_state'],
2721
                $groupSettings['wiki_state'],
2722
                $groupSettings['maximum_number_of_students'],
2723
                $groupSettings['self_registration_allowed'],
2724
                $groupSettings['self_unregistration_allowed'],
2725
                null,
2726
            ];
2727
2728
            if ($loadUsers) {
2729
                $data[$count][] = $userListToString;
2730
                $data[$count][] = $tutorListToString;
2731
            }
2732
2733
            if (!empty($groupId)) {
2734
                if ($groupId == $groupInfo['iid']) {
2735
                    break;
2736
                }
2737
            }
2738
            $count++;
2739
        }
2740
2741
        return $data;
2742
    }
2743
2744
    /**
2745
     * @param string $default
2746
     */
2747
    public static function getSettingBar($default)
2748
    {
2749
        $activeSettings = null;
2750
        $activeTutor = null;
2751
        $activeMember = null;
2752
2753
        switch ($default) {
2754
            case 'settings':
2755
                $activeSettings = 'active';
2756
                break;
2757
            case 'tutor':
2758
                $activeTutor = 'active';
2759
                break;
2760
            case 'member':
2761
                $activeMember = 'active';
2762
                break;
2763
        }
2764
2765
        $url = api_get_path(WEB_CODE_PATH).'group/%s?'.api_get_cidreq();
2766
2767
        echo '
2768
            <ul class="nav nav-tabs">
2769
                <li class="nav-item">
2770
                    <a class="nav-link '.$activeSettings.'"
2771
                        id="group_settings_tab" href="'.sprintf($url, 'settings.php').'">
2772
                    '.Display::return_icon('settings.png').' '.get_lang('Settings').'
2773
                    </a>
2774
                </li>
2775
                <li class="nav-item">
2776
                    <a class="nav-link '.$activeMember.'"
2777
                        id="group_members_tab" href="'.sprintf($url, 'member_settings.php').'">
2778
                    '.Display::return_icon('user.png').' '.get_lang('Group members').'</a>
2779
                </li>
2780
                <li class="nav-item">
2781
                    <a class="nav-link  '.$activeTutor.'"
2782
                        id="group_tutors_tab" href="'.sprintf($url, 'tutor_settings.php').'">
2783
                    '.Display::return_icon('teacher.png').' '.get_lang('Group tutors').'
2784
                    </a>
2785
                </li>
2786
            </ul>';
2787
    }
2788
2789
    public static function groupOverview($group, $url)
2790
    {
2791
        $groupId = $group['iid'];
2792
        $content = '<li>';
2793
        $content .= Display::tag(
2794
            'h3',
2795
            Display::url(
2796
                Security::remove_XSS($group['name']),
2797
                $url.'&gid='.$groupId
2798
            )
2799
        );
2800
        $users = self::getTutors($group);
2801
        if (!empty($users)) {
2802
            $content .= '<ul>';
2803
            $content .= "<li>".Display::tag('h4', get_lang('Tutors'))."</li><ul>";
2804
            foreach ($users as $user) {
2805
                $userInfo = api_get_user_info($user['user_id']);
2806
                $content .= '<li title="'.$userInfo['username'].'">'.
2807
                    $userInfo['complete_name_with_username'].
2808
                    '</li>';
2809
            }
2810
            $content .= '</ul>';
2811
            $content .= '</ul>';
2812
        }
2813
2814
        $users = self::getStudents($group['iid']);
2815
        if (!empty($users)) {
2816
            $content .= '<ul>';
2817
            $content .= "<li>".Display::tag('h4', get_lang('Students'))."</li><ul>";
2818
            foreach ($users as $user) {
2819
                $userInfo = api_get_user_info($user['user_id']);
2820
                $content .= '<li title="'.$userInfo['username'].'">'.
2821
                    $userInfo['complete_name_with_username'].
2822
                    '</li>';
2823
            }
2824
            $content .= '</ul>';
2825
            $content .= '</ul>';
2826
        }
2827
        $content .= '</li>';
2828
2829
        return $content;
2830
    }
2831
2832
    /**
2833
     * @param Course $course
2834
     * @param string $keyword
2835
     *
2836
     * @return string
2837
     */
2838
    public static function getOverview(Course $course, $keyword = '')
2839
    {
2840
        $content = null;
2841
        $categories = self::get_categories();
2842
        $url = api_get_path(WEB_CODE_PATH).'group/group_space.php?'.api_get_cidreq(true, false);
2843
        if (!empty($categories)) {
2844
            foreach ($categories as $category) {
2845
                if ('true' === api_get_setting('allow_group_categories')) {
2846
                    $content .= '<h2>'.$category['title'].'</h2>';
2847
                }
2848
                $groups = self::get_group_list($category['iid'], $course, null, 0, false, $keyword);
2849
                $content .= '<ul>';
2850
                if (!empty($groups)) {
2851
                    foreach ($groups as $group) {
2852
                        $content .= self::groupOverview($group, $url);
2853
                    }
2854
                }
2855
                $content .= '</ul>';
2856
            }
2857
        }
2858
2859
        // Check groups with no categories.
2860
        $groups = self::get_group_list(null, $course, null, api_get_session_id(), false, true);
2861
        if (!empty($groups)) {
2862
            $content .= '<h2>'.get_lang('NoCategorySelected').'</h2>';
2863
            $content .= '<ul>';
2864
            foreach ($groups as $group) {
2865
                if (!empty($group['category_id'])) {
2866
                    continue;
2867
                }
2868
                $content .= self::groupOverview($group, $url);
2869
            }
2870
            $content .= '</ul>';
2871
        }
2872
2873
        return $content;
2874
    }
2875
2876
    /**
2877
     * Returns the search form.
2878
     *
2879
     * @return string
2880
     */
2881
    public static function getSearchForm()
2882
    {
2883
        $url = api_get_path(WEB_CODE_PATH).'group/group_overview.php?'.api_get_cidreq();
2884
        $form = new FormValidator(
2885
            'search_groups',
2886
            'get',
2887
            $url,
2888
            null,
2889
            ['class' => 'form-search'],
2890
            FormValidator::LAYOUT_INLINE
2891
        );
2892
        $form->addElement('text', 'keyword');
2893
        $form->addCourseHiddenParams();
2894
        $form->addButtonSearch();
2895
2896
        return $form->toHtml();
2897
    }
2898
2899
    public static function setStatus(CGroup $group, $status)
2900
    {
2901
        $group->setStatus($status);
2902
        $em = Database::getManager();
2903
        $em->persist($group);
2904
        $em->flush();
2905
    }
2906
2907
    public static function setVisible(CGroup $group)
2908
    {
2909
        self::setStatus($group, true);
2910
    }
2911
2912
    public static function setInvisible(CGroup $group)
2913
    {
2914
        self::setStatus($group, false);
2915
    }
2916
2917
    /**
2918
     * @param int   $userId
2919
     * @param int   $courseId
2920
     * @param array $documentInfoToBeCheck
2921
     * @param bool  $blockPage
2922
     *
2923
     * @return bool
2924
     */
2925
    public static function allowUploadEditDocument(
2926
        $userId,
2927
        $courseId,
2928
        CGroup $group,
2929
        $documentInfoToBeCheck = null,
2930
        $blockPage = false
2931
    ) {
2932
        // Admin and teachers can make any change no matter what
2933
        if (api_is_platform_admin() || api_is_allowed_to_edit(false, true)) {
2934
            return true;
2935
        }
2936
2937
        if (empty($group)) {
2938
            if ($blockPage) {
2939
                api_not_allowed(true);
2940
            }
2941
2942
            return false;
2943
        }
2944
2945
        // Tutor can also make any change
2946
        $isTutor = self::isTutorOfGroup($userId, $group);
2947
2948
        if ($isTutor) {
2949
            return true;
2950
        }
2951
2952
        // Just in case also check if document in group is available
2953
        if (0 == $group->getDocState()) {
2954
            if ($blockPage) {
2955
                api_not_allowed(true);
2956
            }
2957
2958
            return false;
2959
        }
2960
2961
        // Default behaviour
2962
        $documentAccess = self::DOCUMENT_MODE_SHARE;
2963
2964
        // Check category document access
2965
        /*$allowCategoryGroupDocumentAccess = api_get_configuration_value('group_category_document_access');
2966
        if ($allowCategoryGroupDocumentAccess) {
2967
            $category = GroupManager::get_category_from_group($groupInfo['iid']);
2968
            if (!empty($category) && isset($category['document_access'])) {
2969
                $documentAccess = (int) $category['document_access'];
2970
            }
2971
        }*/
2972
2973
        // Check group document access
2974
        $allow = api_get_configuration_value('group_document_access');
2975
        if ($allow) {
2976
            $documentAccess = $group->getDocumentAccess();
2977
        }
2978
2979
        // Check access for students
2980
        $result = false;
2981
        switch ($documentAccess) {
2982
            case self::DOCUMENT_MODE_SHARE:
2983
                // Default chamilo behaviour
2984
                // Student can upload his own content, cannot modify another content.
2985
                $isMember = self::is_subscribed($userId, $group);
2986
                if ($isMember) {
2987
                    // No document to check, allow access to document feature.
2988
                    if (empty($documentInfoToBeCheck)) {
2989
                        $result = true;
2990
                    } else {
2991
                        // Member can only edit his own document
2992
                        $authorId = isset($documentInfoToBeCheck['insert_user_id']) ? $documentInfoToBeCheck['insert_user_id'] : 0;
2993
                        // If "insert_user_id" is not set, check the author id from c_item_property
2994
                        if (empty($authorId) && isset($documentInfoToBeCheck['id'])) {
2995
                            // @todo use resources
2996
                            /*$documentInfo = api_get_item_property_info(
2997
                                $courseId,
2998
                                'document',
2999
                                $documentInfoToBeCheck['id'],
3000
                                0
3001
                            );
3002
                            // Try to find this document in the session
3003
                            if (!empty($sessionId)) {
3004
                                $documentInfo = api_get_item_property_info(
3005
                                    $courseId,
3006
                                    'document',
3007
                                    $documentInfoToBeCheck['id'],
3008
                                    api_get_session_id()
3009
                                );
3010
                            }
3011
3012
                            if (!empty($documentInfo) && isset($documentInfo['insert_user_id'])) {
3013
                                $authorId = $documentInfo['insert_user_id'];
3014
                            }*/
3015
                        }
3016
3017
                        if ($authorId == $userId) {
3018
                            $result = true;
3019
                        }
3020
                    }
3021
                }
3022
                break;
3023
            case self::DOCUMENT_MODE_READ_ONLY:
3024
                // Student cannot upload content, cannot modify another content.
3025
                $result = false;
3026
                break;
3027
            case self::DOCUMENT_MODE_COLLABORATION:
3028
                // Student can upload content, can modify another content.
3029
                $isMember = self::is_subscribed($userId, $group);
3030
                if ($isMember) {
3031
                    $result = true;
3032
                }
3033
                break;
3034
        }
3035
3036
        if ($blockPage && false == $result) {
3037
            api_not_allowed(true);
3038
        }
3039
3040
        return $result;
3041
    }
3042
}
3043