Passed
Push — 1.10.x ( 266392...06c156 )
by Angel Fernando Quiroz
80:58 queued 32:34
created

UserGroup   F

Complexity

Total Complexity 331

Size/Duplication

Total Lines 2386
Duplicated Lines 25.27 %

Coupling/Cohesion

Components 1
Dependencies 11

Importance

Changes 3
Bugs 1 Features 2
Metric Value
wmc 331
c 3
b 1
f 2
lcom 1
cbo 11
dl 603
loc 2386
rs 3.9999

68 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 13 1
A getUseMultipleUrl() 0 4 1
A getTotalCount() 0 6 1
B get_count() 18 36 5
B getUserGroupByCourseWithDataCount() 22 41 5
A get_id_by_name() 0 6 1
A display() 0 11 1
A display_teacher_view() 0 4 1
B get_courses_by_usergroup() 0 57 7
B getUserGroupInCourse() 7 55 8
C getUserGroupNotInCourse() 7 60 10
B get_usergroup_by_course() 29 29 4
A usergroup_was_added_in_course() 0 14 2
A get_sessions_by_usergroup() 0 17 3
B get_users_by_usergroup() 0 22 4
A getUsersByUsergroupAndRelation() 0 18 3
B get_usergroup_by_user() 26 26 4
C subscribe_sessions_to_usergroup() 7 48 14
C subscribe_courses_to_usergroup() 19 40 12
B unsubscribe_courses_from_usergroup() 15 19 5
C subscribe_users_to_usergroup() 7 70 20
A usergroup_exists() 0 14 2
C getUsergroupsPagination() 8 50 8
B getDataToExport() 0 31 6
A filterByFirstLetter() 0 12 1
A getUserGroupNotInList() 0 13 2
B getUserGroupListByUser() 0 37 5
C save() 0 38 8
C update() 0 27 8
A manageFileUpload() 0 7 2
A delete_group_picture() 0 4 1
D update_group_picture() 28 108 14
A getGroupType() 0 4 1
B delete() 0 26 3
A subscribeToUrl() 0 10 1
A unsubscribeToUrl() 0 9 1
B searchUserGroupAjax() 32 32 4
A getUserListByUserGroup() 0 12 1
C setForm() 0 69 7
C get_group_picture_path_by_id() 11 46 13
A getAllowedPictureExtensions() 0 4 1
A getGroupStatusList() 0 9 1
A setGroupType() 0 4 1
A is_group_admin() 0 12 3
A is_group_moderator() 12 12 3
A is_group_member() 21 21 4
A get_user_group_role() 0 18 4
B getUserRoleToString() 0 25 6
C add_users_to_groups() 0 29 7
A delete_user_rel_group() 0 11 1
B add_user_to_group() 0 21 5
A update_user_role() 0 11 1
B get_groups_by_user() 10 40 5
B get_groups_by_popularity() 36 36 5
B get_groups_by_age() 41 41 5
C get_users_by_group() 17 60 9
B get_all_users_by_group() 0 24 3
D show_group_column_information() 46 81 18
A delete_topic() 0 13 1
B get_groups_by_user_count() 6 26 3
B get_all_group_tags() 0 68 6
C get_parent_groups() 34 34 7
C getGroupUsersByUser() 45 45 8
C getGroupsByDepthLevel() 41 41 7
B set_parent_group() 25 25 3
C get_picture_group() 33 48 10
A getNameListByUser() 0 6 1
A getLabelsFromNameList() 0 18 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like UserGroup often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use UserGroup, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class UserGroup
6
 *
7
 * This class provides methods for the UserGroup management.
8
 * Include/require it in your code to use its features.
9
 * @package chamilo.library
10
 *
11
 */
12
class UserGroup extends Model
13
{
14
    public $columns = array(
15
        'id',
16
        'name',
17
        'description',
18
        'group_type',
19
        'picture',
20
        'url',
21
        'visibility',
22
        'updated_at',
23
        'created_at'
24
    );
25
26
    public $useMultipleUrl = false;
27
28
    const SOCIAL_CLASS = 1;
29
    const NORMAL_CLASS = 0;
30
    public $groupType = 0;
31
    public $showGroupTypeSetting = false;
32
33
    /**
34
     * Set ups DB tables
35
     */
36
    public function __construct()
37
    {
38
        $this->table = Database::get_main_table(TABLE_USERGROUP);
39
40
        $this->usergroup_rel_user_table = Database::get_main_table(TABLE_USERGROUP_REL_USER);
41
        $this->usergroup_rel_course_table = Database::get_main_table(TABLE_USERGROUP_REL_COURSE);
42
        $this->usergroup_rel_session_table = Database::get_main_table(TABLE_USERGROUP_REL_SESSION);
43
        $this->access_url_rel_usergroup = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
44
        $this->table_course = Database::get_main_table(TABLE_MAIN_COURSE);
45
        $this->table_user = Database::get_main_table(TABLE_MAIN_USER);
46
47
        $this->useMultipleUrl = api_get_configuration_value('enable_multiple_url_support_for_classes');
48
    }
49
50
    /**
51
     * @return bool
52
     */
53
    public function getUseMultipleUrl()
54
    {
55
        return $this->useMultipleUrl;
56
    }
57
58
    /**
59
     * @return int
60
     */
61
    public function getTotalCount()
62
    {
63
        $row = Database::select('count(*) as count', $this->table, array(), 'first');
64
65
        return $row['count'];
66
    }
67
68
    /**
69
     * @param int $type
70
     *
71
     * @return int
72
     */
73
    public function get_count($type = -1)
74
    {
75
        if ($this->useMultipleUrl) {
76
            $urlId = api_get_current_access_url_id();
77
            $sql = "SELECT count(u.id) as count FROM ".$this->table." u
78
                    INNER JOIN ".$this->access_url_rel_usergroup." a
79
                        ON (u.id = a.usergroup_id)
80
                    WHERE access_url_id = $urlId
81
            ";
82
            $result = Database::query($sql);
83
            if (Database::num_rows($result)) {
84
                $row  = Database::fetch_array($result);
85
86
                return $row['count'];
87
            }
88
89
            return 0;
90 View Code Duplication
        } else {
91
92
            $typeCondition = '';
93
            if ($type != -1) {
94
                $type = intval($type);
95
                $typeCondition = " WHERE group_type = $type ";
96
            }
97
98
            $sql = "SELECT count(a.id) as count
99
                    FROM {$this->table} a
100
                    $typeCondition
101
            ";
102
            $result = Database::query($sql);
103
            if (Database::num_rows($result)) {
104
                $row  = Database::fetch_array($result);
105
                return $row['count'];
106
            }
107
        }
108
    }
109
110
    /**
111
     * @param int $course_id
112
     * @param int $type
113
     *
114
     * @return mixed
115
     */
116
    public function getUserGroupByCourseWithDataCount($course_id, $type = -1)
117
    {
118
        if ($this->useMultipleUrl) {
119
            $course_id = intval($course_id);
120
            $urlId = api_get_current_access_url_id();
121
            $sql = "SELECT count(c.usergroup_id) as count
122
                    FROM {$this->usergroup_rel_course_table} c
123
                    INNER JOIN {$this->access_url_rel_usergroup} a
124
                    ON (c.usergroup_id = a.usergroup_id)
125
                    WHERE access_url_id = $urlId AND course_id = $course_id
126
            ";
127
            $result = Database::query($sql);
128
            if (Database::num_rows($result)) {
129
                $row  = Database::fetch_array($result);
130
                return $row['count'];
131
            }
132
133
            return 0;
134 View Code Duplication
        } else {
135
            $typeCondition = '';
136
            if ($type != -1) {
137
                $type = intval($type);
138
                $typeCondition = " AND group_type = $type ";
139
            }
140
            $sql = "SELECT count(c.usergroup_id) as count
141
                    FROM {$this->usergroup_rel_course_table} c
142
                    INNER JOIN {$this->table} a
143
                    ON (c.usergroup_id = a.id)
144
                    WHERE
145
                        course_id = $course_id
146
                        $typeCondition
147
            ";
148
            $result = Database::query($sql);
149
            if (Database::num_rows($result)) {
150
                $row  = Database::fetch_array($result);
151
                return $row['count'];
152
            }
153
154
            return 0;
155
        }
156
    }
157
158
    /**
159
     * @param string $name
160
     *
161
     * @return mixed
162
     */
163
    public function get_id_by_name($name)
164
    {
165
        $row = Database::select('id', $this->table, array('where' => array('name = ?' => $name)), 'first');
166
167
        return $row['id'];
168
    }
169
170
    /**
171
     * Displays the title + grid
172
     */
173
    public function display()
174
    {
175
        // action links
176
        echo '<div class="actions">';
177
        echo '<a href="../admin/index.php">'.Display::return_icon('back.png', get_lang('BackTo').' '.get_lang('PlatformAdmin'), '', '32').'</a>';
178
        echo '<a href="'.api_get_self().'?action=add">'.Display::return_icon('new_class.png', get_lang('AddClasses'), '', '32').'</a>';
179
        echo Display::url(Display::return_icon('import_csv.png', get_lang('Import'), array(), ICON_SIZE_MEDIUM), 'usergroup_import.php');
180
        echo Display::url(Display::return_icon('export_csv.png', get_lang('Export'), array(), ICON_SIZE_MEDIUM), 'usergroup_export.php');
181
        echo '</div>';
182
        echo Display::grid_html('usergroups');
183
    }
184
185
    /**
186
     * Get HTML grid
187
     */
188
    public function display_teacher_view()
189
    {
190
        echo Display::grid_html('usergroups');
191
    }
192
193
    /**
194
     * Gets a list of course ids by user group
195
     * @param int $id user group id
196
     * @param array $loadCourseData
197
     *
198
     * @return  array
199
     */
200
    public function get_courses_by_usergroup($id, $loadCourseData = false)
201
    {
202
        if ($this->useMultipleUrl) {
203
            $urlId = api_get_current_access_url_id();
204
            $from = $this->usergroup_rel_course_table." c
205
                    INNER JOIN {$this->access_url_rel_usergroup} a
206
                    ON (a.usergroup_id = c.usergroup_id) ";
207
            $whereConditionSql = 'a.usergroup_id = ? AND access_url_id = ? ';
208
            $whereConditionValues = array($id, $urlId);
209
        } else {
210
            $whereConditionSql = 'usergroup_id = ?';
211
            $whereConditionValues = array($id);
212
            $from = $this->usergroup_rel_course_table." c ";
213
        }
214
215
        if ($loadCourseData) {
216
            $from .= " INNER JOIN {$this->table_course} as course ON c.course_id = course.id";
217
        }
218
219
        /*
220
        if (!empty($conditionsLike)) {
221
            $from .= " INNER JOIN {$this->table_course} as course ON c.course_id = course.id";
222
            $conditionSql = array();
223
            foreach ($conditionsLike as $field => $value) {
224
                $conditionSql[] = $field.' LIKE %?%';
225
                $whereConditionValues[] = $value;
226
            }
227
            $whereConditionSql .= ' AND '.implode(' AND ', $conditionSql);
228
        }*/
229
230
        $where = array('where' => array($whereConditionSql => $whereConditionValues));
231
232
        if ($loadCourseData) {
233
            $select = 'course.*';
234
        } else {
235
            $select = 'course_id';
236
        }
237
238
        $results = Database::select(
239
            $select,
240
            $from,
241
            $where
242
        );
243
244
        $array = array();
245
        if (!empty($results)) {
246
            foreach ($results as $row) {
247
                if ($loadCourseData) {
248
                    $array[$row['id']] = $row;
249
                } else {
250
                    $array[] = $row['course_id'];
251
                }
252
            }
253
        }
254
255
        return $array;
256
    }
257
258
    /**
259
     * @param array $options
260
     *
261
     * @return array
262
     */
263
    public function getUserGroupInCourse($options = array(), $type = -1)
264
    {
265
        if ($this->useMultipleUrl) {
266
            $sql = "SELECT u.* FROM {$this->usergroup_rel_course_table} usergroup
267
                    INNER JOIN  {$this->table} u
268
                    ON (u.id = usergroup.usergroup_id)
269
                    INNER JOIN {$this->table_course} c
270
                    ON (usergroup.course_id = c.id)
271
                    INNER JOIN {$this->access_url_rel_usergroup} a
272
                    ON (a.usergroup_id = u.id)
273
                   ";
274
        } else {
275
            $sql = "SELECT u.* FROM {$this->usergroup_rel_course_table} usergroup
276
                    INNER JOIN  {$this->table} u
277
                    ON (u.id = usergroup.usergroup_id)
278
                    INNER JOIN {$this->table_course} c
279
                    ON (usergroup.course_id = c.id)
280
                   ";
281
        }
282
283
        $conditions = Database::parse_conditions($options);
284
285
        $typeCondition = '';
286
        if ($type != -1) {
287
            $type = intval($type);
288
            $typeCondition = " AND group_type = $type ";
289
        }
290
291
        if (empty($conditions)) {
292
            $conditions .= "WHERE 1 = 1 $typeCondition ";
293
        } else {
294
            $conditions .= " $typeCondition ";
295
        }
296
297
        $sql .= $conditions;
298
299
        if ($this->useMultipleUrl) {
300
            $urlId = api_get_current_access_url_id();
301
            $sql .= " AND access_url_id = $urlId ";
302
        }
303
304
305 View Code Duplication
        if (isset($options['LIMIT'])) {
306
            $limits = explode(',', $options['LIMIT']);
307
            $limits = array_map('intval', $limits);
308
            if (isset($limits[0]) && isset($limits[1])) {
309
                $sql .= " LIMIT ".$limits[0].', '.$limits[1];
310
            }
311
        }
312
313
        $result = Database::query($sql);
314
        $array = Database::store_result($result, 'ASSOC');
315
316
        return $array;
317
    }
318
319
    /**
320
     * @param array $options
321
     * @param int   $type
322
     *
323
     * @return array|bool
324
     */
325
    public function getUserGroupNotInCourse($options = array(), $type = -1)
326
    {
327
        $course_id = null;
328
        if (isset($options['course_id'])) {
329
            $course_id = intval($options['course_id']);
330
            unset($options['course_id']);
331
        }
332
333
        if (empty($course_id)) {
334
            return false;
335
        }
336
337
        $typeCondition = '';
338
        if ($type != -1) {
339
            $type = intval($type);
340
            $typeCondition = " AND group_type = $type ";
341
        }
342
343
        if ($this->useMultipleUrl) {
344
            $urlId = api_get_current_access_url_id();
345
            $sql = "SELECT DISTINCT u.*
346
                    FROM {$this->table} u
347
                    INNER JOIN {$this->access_url_rel_usergroup} a
348
                    ON (a.usergroup_id = u.id)
349
                    LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
350
                    ON (u.id = urc.usergroup_id AND course_id = $course_id)
351
            ";
352
        } else {
353
            $sql = "SELECT DISTINCT u.*
354
                    FROM {$this->table} u
355
                    LEFT OUTER JOIN {$this->usergroup_rel_course_table} urc
356
                    ON (u.id = urc.usergroup_id AND course_id = $course_id)
357
            ";
358
        }
359
        $conditions = Database::parse_conditions($options);
360
361
        if (empty($conditions)) {
362
            $conditions .= "WHERE 1 = 1 $typeCondition ";
363
        } else {
364
            $conditions .= " $typeCondition ";
365
        }
366
367
        $sql .= $conditions;
368
369
        if ($this->useMultipleUrl) {
370
            $sql .= " AND access_url_id = $urlId";
371
        }
372
373 View Code Duplication
        if (isset($options['LIMIT'])) {
374
            $limits = explode(',', $options['LIMIT']);
375
            $limits = array_map('intval', $limits);
376
            if (isset($limits[0]) && isset($limits[1])) {
377
                $sql .= " LIMIT ".$limits[0].', '.$limits[1];
378
            }
379
        }
380
        $result = Database::query($sql);
381
        $array = Database::store_result($result, 'ASSOC');
382
383
        return $array;
384
    }
385
386
    /**
387
     * @param int $course_id
388
     * @return array
389
     */
390 View Code Duplication
    public function get_usergroup_by_course($course_id)
391
    {
392
        if ($this->useMultipleUrl) {
393
            $urlId = api_get_current_access_url_id();
394
            $options = array(
395
                'where' => array(
396
                    'c.course_id = ? AND access_url_id = ?' => array(
397
                        $course_id,
398
                        $urlId,
399
                    ),
400
                ),
401
            );
402
            $from = $this->usergroup_rel_course_table." as c INNER JOIN ".$this->access_url_rel_usergroup." a
403
                    ON c.usergroup_id = a.usergroup_id";
404
        } else {
405
            $options = array('where' => array('c.course_id = ?' => $course_id));
406
            $from = $this->usergroup_rel_course_table." c";
407
        }
408
409
        $results = Database::select('c.usergroup_id', $from, $options);
410
        $array = array();
411
        if (!empty($results)) {
412
            foreach ($results as $row) {
413
                $array[] = $row['usergroup_id'];
414
            }
415
        }
416
417
        return $array;
418
    }
419
420
    /**
421
     * @param int $usergroup_id
422
     * @param int $course_id
423
     * @return bool
424
     */
425
    public function usergroup_was_added_in_course($usergroup_id, $course_id)
426
    {
427
        $results = Database::select(
428
            'usergroup_id',
429
            $this->usergroup_rel_course_table,
430
            array('where' => array('course_id = ? AND usergroup_id = ?' => array($course_id, $usergroup_id)))
431
        );
432
433
        if (empty($results)) {
434
            return false;
435
        }
436
437
        return true;
438
    }
439
440
    /**
441
     * Gets a list of session ids by user group
442
     * @param   int  $id   user group id
443
     * @return  array
444
     */
445
    public function get_sessions_by_usergroup($id)
446
    {
447
        $results = Database::select(
448
            'session_id',
449
            $this->usergroup_rel_session_table,
450
            array('where' => array('usergroup_id = ?' => $id))
451
        );
452
453
        $array = array();
454
        if (!empty($results)) {
455
            foreach ($results as $row) {
456
                $array[] = $row['session_id'];
457
            }
458
        }
459
460
        return $array;
461
    }
462
463
    /**
464
     * Gets a list of user ids by user group
465
     * @param   int    $id user group id
466
     * @return  array   with a list of user ids
467
     */
468
    public function get_users_by_usergroup($id = null, $relation = '')
469
    {
470
        if (empty($id)) {
471
            $conditions = array();
472
        } else {
473
            $conditions = array('where' => array('usergroup_id = ?' => $id));
474
        }
475
        $results = Database::select(
476
            'user_id',
477
            $this->usergroup_rel_user_table,
478
            $conditions,
479
            true
480
        );
481
        $array = array();
482
        if (!empty($results)) {
483
            foreach ($results as $row) {
484
                $array[] = $row['user_id'];
485
            }
486
        }
487
488
        return $array;
489
    }
490
491
    /**
492
     * Gets a list of user ids by user group
493
     * @param   int    $id user group id
494
     * @return  array   with a list of user ids
495
     */
496
    public function getUsersByUsergroupAndRelation($id, $relation = '')
497
    {
498
        $conditions = array('where' => array('usergroup_id = ? AND relation_type = ?' => [$id, $relation]));
499
        $results = Database::select(
500
            'user_id',
501
            $this->usergroup_rel_user_table,
502
            $conditions,
503
            true
504
        );
505
        $array = array();
506
        if (!empty($results)) {
507
            foreach ($results as $row) {
508
                $array[] = $row['user_id'];
509
            }
510
        }
511
512
        return $array;
513
    }
514
515
    /**
516
     * Get the group list for a user
517
     * @param int $userId The user ID
518
     * @param int $filterByType Optional. The type of group
519
     * @return array
520
     */
521
    public function getUserGroupListByUser($userId, $filterByType = null)
522
    {
523
        if ($this->useMultipleUrl) {
524
            $urlId = api_get_current_access_url_id();
525
            $from = $this->usergroup_rel_user_table." u
526
                INNER JOIN {$this->access_url_rel_usergroup} a
527
                ON (a.usergroup_id AND u.usergroup_id)
528
                INNER JOIN {$this->table} g
529
                ON (u.usergroup_id = g.id)
530
                ";
531
            $where =  array('where' => array('user_id = ? AND access_url_id = ? ' => array($userId, $urlId)));
532
        } else {
533
            $from = $this->usergroup_rel_user_table." u
534
                INNER JOIN {$this->table} g
535
                ON (u.usergroup_id = g.id)
536
                ";
537
            $where =  array('where' => array('user_id = ?' => $userId));
538
        }
539
540
        if ($filterByType !== null) {
541
            $where['where'][' AND g.group_type = ?'] = intval($filterByType);
542
        }
543
544
        $results = Database::select(
545
            'g.*',
546
            $from,
547
            $where
548
        );
549
        $array = array();
550
        if (!empty($results)) {
551
            foreach ($results as $row) {
552
                $array[] = $row;
553
            }
554
        }
555
556
        return $array;
557
    }
558
559
    /**
560
     * Gets the usergroup id list by user id
561
     * @param   int $userId user id
562
     * @return array
563
     */
564 View Code Duplication
    public function get_usergroup_by_user($userId)
565
    {
566
        if ($this->useMultipleUrl) {
567
            $urlId = api_get_current_access_url_id();
568
            $from = $this->usergroup_rel_user_table." u
569
                    INNER JOIN {$this->access_url_rel_usergroup} a ON (a.usergroup_id AND u.usergroup_id)";
570
            $where =  array('where' => array('user_id = ? AND access_url_id = ? ' => array($userId, $urlId)));
571
        } else {
572
            $from = $this->usergroup_rel_user_table." u ";
573
            $where =  array('where' => array('user_id = ?' => $userId));
574
        }
575
576
        $results = Database::select(
577
            'u.usergroup_id',
578
            $from,
579
            $where
580
        );
581
        $array = array();
582
        if (!empty($results)) {
583
            foreach ($results as $row) {
584
                $array[] = $row['usergroup_id'];
585
            }
586
        }
587
588
        return $array;
589
    }
590
591
    /**
592
     * Subscribes sessions to a group  (also adding the members of the group in the session and course)
593
     * @param   int   $usergroup_id  usergroup id
594
     * @param   array  $list list of session ids
595
     */
596
    public function subscribe_sessions_to_usergroup($usergroup_id, $list)
597
    {
598
        $current_list = self::get_sessions_by_usergroup($usergroup_id);
599
        $user_list = self::get_users_by_usergroup($usergroup_id);
600
601
        $delete_items = $new_items = array();
602
        if (!empty($list)) {
603
            foreach ($list as $session_id) {
604
                if (!in_array($session_id, $current_list)) {
605
                    $new_items[] = $session_id;
606
                }
607
            }
608
        }
609 View Code Duplication
        if (!empty($current_list)) {
610
            foreach ($current_list as $session_id) {
611
                if (!in_array($session_id, $list)) {
612
                    $delete_items[] = $session_id;
613
                }
614
            }
615
        }
616
617
        // Deleting items
618
        if (!empty($delete_items)) {
619
            foreach ($delete_items as $session_id) {
620
                if (!empty($user_list)) {
621
                    foreach ($user_list as $user_id) {
622
                        SessionManager::unsubscribe_user_from_session($session_id, $user_id);
623
                    }
624
                }
625
                Database::delete(
626
                    $this->usergroup_rel_session_table,
627
                    array('usergroup_id = ? AND session_id = ?' => array($usergroup_id, $session_id))
628
                );
629
            }
630
        }
631
632
        // Adding new relationships.
633
        if (!empty($new_items)) {
634
            foreach ($new_items as $session_id) {
635
                $params = array('session_id' => $session_id, 'usergroup_id' => $usergroup_id);
636
                Database::insert($this->usergroup_rel_session_table, $params);
637
638
                if (!empty($user_list)) {
639
                    SessionManager::suscribe_users_to_session($session_id, $user_list, null, false);
640
                }
641
            }
642
        }
643
    }
644
645
    /**
646
     * Subscribes courses to a group (also adding the members of the group in the course)
647
     * @param int   $usergroup_id  usergroup id
648
     * @param array $list  list of course ids (integers)
649
     * @param bool $delete_groups
650
     */
651
    public function subscribe_courses_to_usergroup($usergroup_id, $list, $delete_groups = true)
652
    {
653
        $current_list = self::get_courses_by_usergroup($usergroup_id);
654
        $user_list = self::get_users_by_usergroup($usergroup_id);
655
656
        $delete_items = $new_items = array();
657
        if (!empty($list)) {
658
            foreach ($list as $id) {
659
                if (!in_array($id, $current_list)) {
660
                    $new_items[] = $id;
661
                }
662
            }
663
        }
664
665 View Code Duplication
        if (!empty($current_list)) {
666
            foreach ($current_list as $id) {
667
                if (!in_array($id, $list)) {
668
                    $delete_items[] = $id;
669
                }
670
            }
671
        }
672
673
        if ($delete_groups) {
674
            self::unsubscribe_courses_from_usergroup($usergroup_id, $delete_items);
675
        }
676
677
        // Adding new relationships
678 View Code Duplication
        if (!empty($new_items)) {
679
            foreach ($new_items as $course_id) {
680
                $course_info = api_get_course_info_by_id($course_id);
681
                if (!empty($user_list)) {
682
                    foreach ($user_list as $user_id) {
683
                        CourseManager::subscribe_user($user_id, $course_info['code']);
684
                    }
685
                }
686
                $params = array('course_id' => $course_id, 'usergroup_id' => $usergroup_id);
687
                Database::insert($this->usergroup_rel_course_table, $params);
688
            }
689
        }
690
    }
691
692
    /**
693
     * @param int $usergroup_id
694
     * @param bool $delete_items
695
     */
696
    public function unsubscribe_courses_from_usergroup($usergroup_id, $delete_items)
697
    {
698
        // Deleting items.
699 View Code Duplication
        if (!empty($delete_items)) {
700
            $user_list = self::get_users_by_usergroup($usergroup_id);
701
            foreach ($delete_items as $course_id) {
0 ignored issues
show
Bug introduced by
The expression $delete_items of type boolean is not traversable.
Loading history...
702
                $course_info = api_get_course_info_by_id($course_id);
703
                if (!empty($user_list)) {
704
                    foreach ($user_list as $user_id) {
705
                        CourseManager::unsubscribe_user($user_id, $course_info['code']);
706
                    }
707
                }
708
                Database::delete(
709
                    $this->usergroup_rel_course_table,
710
                    array('usergroup_id = ? AND course_id = ?' => array($usergroup_id, $course_id))
711
                );
712
            }
713
        }
714
    }
715
716
    /**
717
     * Subscribe users to a group
718
     * @param int     $usergroup_id usergroup id
719
     * @param array   $list list of user ids     *
720
     * @param bool $delete_users_not_present_in_list
721
     * @param array $relationType
722
     */
723
    public function subscribe_users_to_usergroup($usergroup_id, $list, $delete_users_not_present_in_list = true, $relationType = '')
724
    {
725
        $current_list = self::get_users_by_usergroup($usergroup_id);
726
        $course_list = self::get_courses_by_usergroup($usergroup_id);
727
        $session_list = self::get_sessions_by_usergroup($usergroup_id);
728
729
        $delete_items = array();
730
        $new_items = array();
731
732
        if (!empty($list)) {
733
            foreach ($list as $user_id) {
734
                if (!in_array($user_id, $current_list)) {
735
                    $new_items[] = $user_id;
736
                }
737
            }
738
        }
739
740 View Code Duplication
        if (!empty($current_list)) {
741
            foreach ($current_list as $user_id) {
742
                if (!in_array($user_id, $list)) {
743
                    $delete_items[] = $user_id;
744
                }
745
            }
746
        }
747
748
        // Deleting items
749
        if (!empty($delete_items) && $delete_users_not_present_in_list) {
750
            foreach ($delete_items as $user_id) {
751
                // Removing courses
752
                if (!empty($course_list)) {
753
                    foreach ($course_list as $course_id) {
754
                        $course_info = api_get_course_info_by_id($course_id);
755
                        CourseManager::unsubscribe_user($user_id, $course_info['code']);
756
                    }
757
                }
758
                // Removing sessions
759
                if (!empty($session_list)) {
760
                    foreach ($session_list as $session_id) {
761
                        SessionManager::unsubscribe_user_from_session($session_id, $user_id);
762
                    }
763
                }
764
                Database::delete(
765
                    $this->usergroup_rel_user_table,
766
                    array('usergroup_id = ? AND user_id = ? AND relation_type = ?' => array($usergroup_id, $user_id, $relationType))
767
                );
768
            }
769
        }
770
771
        // Adding new relationships
772
        if (!empty($new_items)) {
773
            // Adding sessions
774
            if (!empty($session_list)) {
775
                foreach ($session_list as $session_id) {
776
                    SessionManager::suscribe_users_to_session($session_id, $new_items, null, false);
777
                }
778
            }
779
780
            foreach ($new_items as $user_id) {
781
                // Adding courses
782
                if (!empty($course_list)) {
783
                    foreach ($course_list as $course_id) {
784
                        $course_info = api_get_course_info_by_id($course_id);
785
                        CourseManager::subscribe_user($user_id, $course_info['code']);
786
                    }
787
                }
788
                $params = array('user_id' => $user_id, 'usergroup_id' => $usergroup_id, 'relation_type' => $relationType);
789
                Database::insert($this->usergroup_rel_user_table, $params);
790
            }
791
        }
792
    }
793
794
    /**
795
     * @param string $name
796
     * @return bool
797
     */
798
    public function usergroup_exists($name)
799
    {
800
        if ($this->useMultipleUrl) {
801
            $urlId = api_get_current_access_url_id();
802
            $sql = "SELECT * FROM $this->table u
803
                    INNER JOIN {$this->access_url_rel_usergroup} a ON (a.usergroup_id = u.id)
804
                    WHERE name = '".Database::escape_string($name)."' AND access_url_id = $urlId";
805
        } else {
806
            $sql = "SELECT * FROM $this->table WHERE name = '".Database::escape_string($name)."'";
807
        }
808
        $res = Database::query($sql);
809
810
        return Database::num_rows($res) != 0;
811
    }
812
813
    /**
814
     * @param int $sidx
815
     * @param int $sord
816
     * @param int $start
817
     * @param int $limit
818
     * @return array
819
     */
820
    public function getUsergroupsPagination($sidx, $sord, $start, $limit)
821
    {
822
        $sord = in_array(strtolower($sord), array('asc', 'desc')) ? $sord : 'desc';
823
824
        $start = intval($start);
825
        $limit = intval($limit);
826
        if ($this->useMultipleUrl) {
827
            $urlId = api_get_current_access_url_id();
828
            $from = $this->table." u INNER JOIN {$this->access_url_rel_usergroup} a ON (u.id = a.usergroup_id)";
829
            $where = array(' access_url_id = ?' => $urlId);
830
        } else {
831
            $from = $this->table." u ";
832
            $where = array();
833
        }
834
835
        $result = Database::select(
836
            'u.*',
837
            $from,
838
            array('where' => $where, 'order'=> "name $sord", 'LIMIT'=> "$start , $limit")
839
        );
840
841
        $new_result = array();
842
        if (!empty($result)) {
843
            foreach ($result as $group) {
844
                $group['sessions'] = count($this->get_sessions_by_usergroup($group['id']));
845
                $group['courses'] = count($this->get_courses_by_usergroup($group['id']));
846
                $group['users'] = count($this->get_users_by_usergroup($group['id']));
847 View Code Duplication
                switch ($group['group_type']) {
848
                    case 0:
849
                        $group['group_type'] = Display::label(get_lang('Class'), 'info');
850
                        break;
851
                    case 1:
852
                        $group['group_type'] = Display::label(get_lang('Social'), 'success');
853
                        break;
854
                }
855
                $new_result[] = $group;
856
            }
857
            $result = $new_result;
858
        }
859
        $columns = array('name', 'users', 'courses','sessions', 'group_type');
860
861
        if (!in_array($sidx, $columns)) {
862
            $sidx = 'name';
863
        }
864
865
        // Multidimensional sort
866
        $result = msort($result, $sidx, $sord);
867
868
        return $result;
869
    }
870
871
    /**
872
     * @param array $options
873
     * @return array
874
     */
875
    public function getDataToExport($options = array())
876
    {
877
        if ($this->useMultipleUrl) {
878
            $urlId = api_get_current_access_url_id();
879
            $from = $this->table." u INNER JOIN {$this->access_url_rel_usergroup} a
880
                    ON (u.id = a.usergroup_id)";
881
            $options = array('where' => array('access_url_id = ? ' => $urlId));
882
            $classes = Database::select('a.id, name, description', $from, $options);
883
        } else {
884
            $classes = Database::select('id, name, description', $this->table, $options);
885
        }
886
887
        $result = array();
888
        if (!empty($classes)) {
889
            foreach ($classes as $data) {
890
                $users = self::getUserListByUserGroup($data['id']);
891
                $userToString = null;
892
                if (!empty($users)) {
893
                    $userNameList = array();
894
                    foreach ($users as $userData) {
895
                        $userNameList[] = $userData['username'];
896
                    }
897
                    $userToString = implode(',', $userNameList);
898
                }
899
                $data['users'] = $userToString;
900
                $result[] = $data;
901
            }
902
        }
903
904
        return $result;
905
    }
906
907
    /**
908
     * @param string $firstLetter
909
     * @return array
910
     */
911
    public function filterByFirstLetter($firstLetter)
912
    {
913
        $firstLetter = Database::escape_string($firstLetter);
914
        $sql = "SELECT id, name FROM $this->table
915
		        WHERE
916
		            name LIKE '".$firstLetter."%' OR
917
		            name LIKE '".api_strtolower($firstLetter)."%'
918
		        ORDER BY name DESC ";
919
920
        $result = Database::query($sql);
921
        return Database::store_result($result);
922
    }
923
924
    /**
925
     * Select user group not in list
926
     * @param array $list
927
     * @return array
928
     */
929
    public function getUserGroupNotInList($list)
930
    {
931
        if (empty($list)) {
932
            return array();
933
        }
934
935
        $list = array_map('intval', $list);
936
        $listToString = implode("','", $list);
937
938
        $sql = "SELECT * FROM {$this->table} WHERE id NOT IN ('$listToString')";
939
        $result = Database::query($sql);
940
        return Database::store_result($result, 'ASSOC');
941
    }
942
943
    /**
944
     * @param $params
945
     * @param bool $show_query
946
     * @return bool|int
947
     */
948
    public function save($params, $show_query = false)
949
    {
950
        $params['updated_at'] = $params['created_at'] = api_get_utc_datetime();
951
        $params['group_type'] = isset($params['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
952
953
        $groupExists = $this->usergroup_exists(trim($params['name']));
954
        if ($groupExists == false) {
955
956
            $id = parent::save($params, $show_query);
957
            if ($id) {
958
                if ($this->useMultipleUrl) {
959
                    $this->subscribeToUrl($id, api_get_current_access_url_id());
960
                }
961
962
                if ($params['group_type'] == self::SOCIAL_CLASS) {
963
                    $this->add_user_to_group(
964
                        api_get_user_id(),
965
                        $id,
966
                        $params['group_type']
967
                    );
968
                }
969
                $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
970
                $picture = $this->manageFileUpload($id, $picture);
971
                if ($picture) {
972
                    $params = array(
973
                        'id' => $id,
974
                        'picture' => $picture,
975
                        'group_type' => $params['group_type']
976
                    );
977
                    $this->update($params);
978
                }
979
            }
980
981
            return $id;
982
        }
983
984
        return false;
985
    }
986
987
    /**
988
     * @inheritdoc
989
     */
990
    public function update($values)
991
    {
992
        $values['updated_on'] = api_get_utc_datetime();
993
        $values['group_type'] = isset($values['group_type']) ? self::SOCIAL_CLASS : self::NORMAL_CLASS;
994
995
        if (isset($values['id'])) {
996
            $picture = isset($_FILES['picture']) ? $_FILES['picture'] : null;
997
            if (!empty($picture)) {
998
                $picture = $this->manageFileUpload($values['id'], $picture);
999
                if ($picture) {
1000
                    $values['picture'] = $picture;
1001
                }
1002
            }
1003
1004
            if (isset($values['delete_picture'])) {
1005
                $values['picture'] = null;
1006
            }
1007
        }
1008
1009
        parent::update($values);
1010
1011
        if (isset($values['delete_picture'])) {
1012
            $this->delete_group_picture($values['id']);
1013
        }
1014
1015
        return true;
1016
    }
1017
1018
    /**
1019
     * @param int    $groupId
1020
     * @param string $picture
1021
     *
1022
     * @return bool|string
1023
     */
1024
    public function manageFileUpload($groupId, $picture)
1025
    {
1026
        if (!empty($picture['name'])) {
1027
            return $this->update_group_picture($groupId, $picture['name'], $picture['tmp_name']);
1028
        }
1029
        return false;
1030
    }
1031
1032
    /**
1033
     * @param $group_id
1034
     * @return string
1035
     */
1036
    public function delete_group_picture($group_id)
1037
    {
1038
        return self::update_group_picture($group_id);
1039
    }
1040
1041
    /**
1042
     * Creates new group pictures in various sizes of a user, or deletes user pfotos.
1043
     * Note: This method relies on configuration setting from main/inc/conf/profile.conf.php
1044
     * @param	int	The group id
1045
     * @param	string $file			The common file name for the newly created photos.
1046
     * It will be checked and modified for compatibility with the file system.
1047
     * If full name is provided, path component is ignored.
1048
     * If an empty name is provided, then old user photos are deleted only,
1049
     * @see UserManager::delete_user_picture() as the prefered way for deletion.
1050
     * @param	string		$source_file	The full system name of the image from which user photos will be created.
1051
     * @return	string/bool	Returns the resulting common file name of created images which usually should be stored in database.
0 ignored issues
show
Documentation introduced by
The doc-type string/bool could not be parsed: Unknown type name "string/bool" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
1052
     * When an image is removed the function returns an empty string. In case of internal error or negative validation it returns FALSE.
1053
     */
1054
    public function update_group_picture($group_id, $file = null, $source_file = null)
1055
    {
1056
        // Validation 1.
1057
        if (empty($group_id)) {
1058
            return false;
1059
        }
1060
        $delete = empty($file);
1061
        if (empty($source_file)) {
1062
            $source_file = $file;
1063
        }
1064
1065
        // User-reserved directory where photos have to be placed.
1066
        $path_info = self::get_group_picture_path_by_id($group_id, 'system', true);
1067
1068
        $path = $path_info['dir'];
1069
1070
        // If this directory does not exist - we create it.
1071
        if (!file_exists($path)) {
1072
            @mkdir($path, api_get_permissions_for_new_directories(), true);
1073
        }
1074
1075
        // The old photos (if any).
1076
        $old_file = $path_info['file'];
1077
1078
        // Let us delete them.
1079 View Code Duplication
        if (!empty($old_file)) {
1080
            if (KEEP_THE_OLD_IMAGE_AFTER_CHANGE) {
1081
                $prefix = 'saved_'.date('Y_m_d_H_i_s').'_'.uniqid('').'_';
1082
                @rename($path.'small_'.$old_file, $path.$prefix.'small_'.$old_file);
1083
                @rename($path.'medium_'.$old_file, $path.$prefix.'medium_'.$old_file);
1084
                @rename($path.'big_'.$old_file, $path.$prefix.'big_'.$old_file);
1085
                @rename($path.$old_file, $path.$prefix.$old_file);
1086
            } else {
1087
                @unlink($path.'small_'.$old_file);
1088
                @unlink($path.'medium_'.$old_file);
1089
                @unlink($path.'big_'.$old_file);
1090
                @unlink($path.$old_file);
1091
            }
1092
        }
1093
1094
        // Exit if only deletion has been requested. Return an empty picture name.
1095
        if ($delete) {
1096
            return '';
1097
        }
1098
1099
        // Validation 2.
1100
        $allowed_types = array('jpg', 'jpeg', 'png', 'gif');
1101
        $file = str_replace('\\', '/', $file);
1102
        $filename = (($pos = strrpos($file, '/')) !== false) ? substr($file, $pos + 1) : $file;
1103
        $extension = strtolower(substr(strrchr($filename, '.'), 1));
1104
        if (!in_array($extension, $allowed_types)) {
1105
            return false;
1106
        }
1107
1108
        // This is the common name for the new photos.
1109 View Code Duplication
        if (KEEP_THE_NAME_WHEN_CHANGE_IMAGE && !empty($old_file)) {
1110
            $old_extension = strtolower(substr(strrchr($old_file, '.'), 1));
1111
            $filename = in_array($old_extension, $allowed_types) ? substr($old_file, 0, -strlen($old_extension)) : $old_file;
1112
            $filename = (substr($filename, -1) == '.') ? $filename.$extension : $filename.'.'.$extension;
1113
        } else {
1114
            $filename = api_replace_dangerous_char($filename);
1115
            if (PREFIX_IMAGE_FILENAME_WITH_UID) {
1116
                $filename = uniqid('').'_'.$filename;
1117
            }
1118
            // We always prefix user photos with user ids, so on setting
1119
            // api_get_setting('split_users_upload_directory') === 'true'
1120
            // the correspondent directories to be found successfully.
1121
            $filename = $group_id.'_'.$filename;
1122
        }
1123
1124
        // Storing the new photos in 4 versions with various sizes.
1125
1126
        /*$image->resize(
1127
        // get original size and set width (widen) or height (heighten).
1128
        // width or height will be set maintaining aspect ratio.
1129
            $image->getSize()->widen( 700 )
1130
        );*/
1131
1132
        // Usign the Imagine service
1133
        $imagine = new Imagine\Gd\Imagine();
1134
        $image = $imagine->open($source_file);
1135
1136
        $options = array(
1137
            'quality' => 90,
1138
        );
1139
1140
        //$image->resize(new Imagine\Image\Box(200, 200))->save($path.'big_'.$filename);
1141
        $image->resize($image->getSize()->widen(200))->save($path.'big_'.$filename, $options);
1142
1143
        $image = $imagine->open($source_file);
1144
        $image->resize(new Imagine\Image\Box(85, 85))->save($path.'medium_'.$filename, $options);
1145
1146
        $image = $imagine->open($source_file);
1147
        $image->resize(new Imagine\Image\Box(22, 22))->save($path.'small_'.$filename);
1148
1149
        /*
1150
        $small  = self::resize_picture($source_file, 22);
1151
        $medium = self::resize_picture($source_file, 85);
1152
        $normal = self::resize_picture($source_file, 200);
1153
1154
        $big = new Image($source_file); // This is the original picture.
1155
        $ok = $small && $small->send_image($path.'small_'.$filename)
1156
            && $medium && $medium->send_image($path.'medium_'.$filename)
1157
            && $normal && $normal->send_image($path.'big_'.$filename)
1158
            && $big && $big->send_image($path.$filename);
1159
        return $ok ? $filename : false;*/
1160
        return $filename;
1161
    }
1162
1163
    /**
1164
     * @return mixed
1165
     */
1166
    public function getGroupType()
1167
    {
1168
        return $this->groupType;
1169
    }
1170
1171
    /**
1172
     * @param int $id
1173
     * @return bool|void
1174
     */
1175
    public function delete($id)
1176
    {
1177
        if ($this->useMultipleUrl) {
1178
            if ($result) {
0 ignored issues
show
Bug introduced by
The variable $result seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
1179
                $this->unsubscribeToUrl($id, api_get_current_access_url_id());
1180
            }
1181
        }
1182
1183
        $sql = "DELETE FROM $this->usergroup_rel_user_table
1184
                WHERE usergroup_id = $id";
1185
        Database::query($sql);
1186
1187
        $sql = "DELETE FROM $this->usergroup_rel_course_table
1188
                WHERE usergroup_id = $id";
1189
        Database::query($sql);
1190
1191
        $sql = "DELETE FROM $this->usergroup_rel_session_table
1192
                WHERE usergroup_id = $id";
1193
        Database::query($sql);
1194
1195
        /*$sql = "DELETE FROM $this->usergroup_rel_
1196
                WHERE usergroup_id = $id";
1197
        Database::query($sql);*/
1198
1199
        $result = parent::delete($id);
1200
    }
1201
1202
    /**
1203
     * @param int $id
1204
     * @param int $urlId
1205
     */
1206
    public function subscribeToUrl($id, $urlId)
1207
    {
1208
        Database::insert(
1209
            $this->access_url_rel_usergroup,
1210
            array(
1211
                'access_url_id' => $urlId,
1212
                'usergroup_id' =>$id
1213
            )
1214
        );
1215
    }
1216
1217
    /**
1218
     * @param int $id
1219
     * @param int $urlId
1220
     */
1221
    public function unsubscribeToUrl($id, $urlId)
1222
    {
1223
        Database::delete(
1224
            $this->access_url_rel_usergroup,
1225
            array(
1226
                'access_url_id = ? AND usergroup_id = ? ' => array($urlId, $id)
1227
            )
1228
        );
1229
    }
1230
1231
    /**
1232
     * @param $needle
1233
     * @return xajaxResponse
1234
     */
1235 View Code Duplication
    public static function searchUserGroupAjax($needle)
1236
    {
1237
        $response = new xajaxResponse();
1238
        $return = '';
1239
1240
        if (!empty($needle)) {
1241
            // xajax send utf8 datas... datas in db can be non-utf8 datas
1242
            $charset = api_get_system_encoding();
1243
            $needle = api_convert_encoding($needle, $charset, 'utf-8');
1244
            $needle = Database::escape_string($needle);
1245
            // search courses where username or firstname or lastname begins likes $needle
1246
            $sql = 'SELECT id, name FROM '.Database::get_main_table(TABLE_USERGROUP).' u
1247
                    WHERE name LIKE "'.$needle.'%"
1248
                    ORDER BY name
1249
                    LIMIT 11';
1250
            $result = Database::query($sql);
1251
            $i = 0;
1252
            while ($data = Database::fetch_array($result)) {
1253
                $i++;
1254
                if ($i <= 10) {
1255
                    $return .= '<a
1256
                    href="javascript: void(0);"
1257
                    onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['name']).' \')">'.$data['name'].' </a><br />';
1258
                } else {
1259
                    $return .= '...<br />';
1260
                }
1261
            }
1262
        }
1263
        $response->addAssign('ajax_list_courses','innerHTML', api_utf8_encode($return));
1264
1265
        return $response;
1266
    }
1267
1268
    /**
1269
     * Get user list by usergroup
1270
     * @param $id
1271
     * @return array
1272
     */
1273
    public function getUserListByUserGroup($id)
1274
    {
1275
        $id = intval($id);
1276
        $sql = "SELECT u.* FROM ".$this->table_user." u
1277
                INNER JOIN ".$this->usergroup_rel_user_table." c
1278
                ON c.user_id = u.id
1279
                WHERE c.usergroup_id = $id"
1280
                ;
1281
        $result = Database::query($sql);
1282
1283
        return Database::store_result($result);
1284
    }
1285
1286
    /**
1287
     * @param FormValidator $form
1288
     * @param string        $type
1289
     * @param array         $data
1290
     */
1291
    public function setForm($form, $type = 'add', $data = array())
1292
    {
1293
        switch ($type) {
1294
            case 'add':
1295
                $header = get_lang('Add');
1296
                break;
1297
            case 'edit':
1298
                $header = get_lang('Edit');
1299
                break;
1300
        }
1301
1302
        $form->addElement('header', $header);
1303
1304
        //Name
1305
        $form->addElement('text', 'name', get_lang('Name'), array('maxlength'=>255));
1306
        $form->applyFilter('name', 'html_filter');
1307
        $form->applyFilter('name', 'trim');
1308
1309
        $form->addRule('name', get_lang('ThisFieldIsRequired'), 'required');
1310
        $form->addRule('name', '', 'maxlength', 255);
1311
1312
        // Description
1313
        $form->addElement('textarea', 'description', get_lang('Description'), array('cols' => 58));
1314
        $form->applyFilter('description', 'html_filter');
1315
        $form->applyFilter('description', 'trim');
1316
1317
        if ($this->showGroupTypeSetting) {
1318
1319
            $form->addElement(
1320
                'checkbox',
1321
                'group_type',
1322
                null,
1323
                get_lang('SocialGroup')
1324
            );
1325
        }
1326
1327
        // url
1328
        $form->addElement('text', 'url', get_lang('Url'));
1329
        $form->applyFilter('url', 'html_filter');
1330
        $form->applyFilter('url', 'trim');
1331
1332
        // Picture
1333
        $allowed_picture_types = $this->getAllowedPictureExtensions();
1334
1335
        $form->addElement('file', 'picture', get_lang('AddPicture'));
1336
        $form->addRule(
1337
            'picture',
1338
            get_lang('OnlyImagesAllowed').' ('.implode(',', $allowed_picture_types).')',
1339
            'filetype',
1340
            $allowed_picture_types
1341
        );
1342
1343
        if (isset($data['picture']) && strlen($data['picture']) > 0) {
1344
            $picture = $this->get_picture_group($data['id'], $data['picture'], 80);
1345
            $img = '<img src="'.$picture['file'].'" />';
1346
            $form->addElement('label', null, $img);
1347
            $form->addElement('checkbox', 'delete_picture', '', get_lang('DelImage'));
1348
        }
1349
1350
        $form->addElement('select', 'visibility', get_lang('GroupPermissions'), $this->getGroupStatusList());
1351
        $form->setRequiredNote('<span class="form_required">*</span> <small>'.get_lang('ThisFieldIsRequired').'</small>');
1352
1353
        // Setting the form elements
1354
        if ($type == 'add') {
1355
            $form->addButtonCreate($header);
1356
        } else {
1357
            $form->addButtonUpdate($header);
1358
        }
1359
    }
1360
1361
    /**
1362
     * Gets the current group image
1363
     * @param string group id
1364
     * @param string picture group name
1365
     * @param string height
1366
     * @param string picture size it can be small_,  medium_  or  big_
1367
     * @param string style css
1368
     * @return array with the file and the style of an image i.e $array['file'] $array['style']
1369
     */
1370
    public function get_picture_group($id, $picture_file, $height, $size_picture = GROUP_IMAGE_SIZE_MEDIUM , $style = '')
1371
    {
1372
        $picture = array();
1373
        $picture['style'] = $style;
1374
        if ($picture_file == 'unknown.jpg') {
1375
            $picture['file'] = Display::returnIconPath($picture_file);
1376
            return $picture;
1377
        }
1378
1379 View Code Duplication
        switch ($size_picture) {
1380
            case GROUP_IMAGE_SIZE_ORIGINAL :
1381
                $size_picture = '';
1382
                break;
1383
            case GROUP_IMAGE_SIZE_BIG :
1384
                $size_picture = 'big_';
1385
                break;
1386
            case GROUP_IMAGE_SIZE_MEDIUM :
1387
                $size_picture = 'medium_';
1388
                break;
1389
            case GROUP_IMAGE_SIZE_SMALL :
1390
                $size_picture = 'small_';
1391
                break;
1392
            default:
1393
                $size_picture = 'medium_';
1394
        }
1395
1396
        $image_array_sys = $this->get_group_picture_path_by_id($id, 'system', false, true);
1397
        $image_array = $this->get_group_picture_path_by_id($id, 'web', false, true);
1398
        $file = $image_array_sys['dir'].$size_picture.$picture_file;
1399 View Code Duplication
        if (file_exists($file)) {
1400
            $picture['file'] = $image_array['dir'].$size_picture.$picture_file;
1401
            $picture['style'] = '';
1402
            if ($height > 0) {
1403
                $dimension = api_getimagesize($picture['file']);
1404
                $margin = (($height - $dimension['width']) / 2);
1405
                //@ todo the padding-top should not be here
1406
                $picture['style'] = ' style="padding-top:'.$margin.'px; width:'.$dimension['width'].'px; height:'.$dimension['height'].';" ';
1407
            }
1408
        } else {
1409
            $file = $image_array_sys['dir'].$picture_file;
1410
            if (file_exists($file) && !is_dir($file)) {
1411
                $picture['file'] = $image_array['dir'].$picture_file;
1412
            } else {
1413
                $picture['file'] = Display::returnIconPath('unknown_group.png');
1414
            }
1415
        }
1416
        return $picture;
1417
    }
1418
1419
    /**
1420
     * Gets the group picture URL or path from group ID (returns an array).
1421
     * The return format is a complete path, enabling recovery of the directory
1422
     * with dirname() or the file with basename(). This also works for the
1423
     * functions dealing with the user's productions, as they are located in
1424
     * the same directory.
1425
     * @param	integer	User ID
1426
     * @param	string	Type of path to return (can be 'none', 'system', 'rel', 'web')
1427
     * @param	bool	Whether we want to have the directory name returned 'as if' there was a file or not (in the case we want to know which directory to create - otherwise no file means no split subdir)
1428
     * @param	bool	If we want that the function returns the /main/img/unknown.jpg image set it at true
1429
     * @return	array 	Array of 2 elements: 'dir' and 'file' which contain the dir and file as the name implies if image does not exist it will return the unknow image if anonymous parameter is true if not it returns an empty er's
1430
     */
1431
    public function get_group_picture_path_by_id($id, $type = 'none', $preview = false, $anonymous = false)
1432
    {
1433
        switch ($type) {
1434
            case 'system': // Base: absolute system path.
1435
                $base = api_get_path(SYS_UPLOAD_PATH);
1436
                break;
1437
            case 'rel': // Base: semi-absolute web path (no server base).
1438
                $base = api_get_path(REL_CODE_PATH);
1439
                break;
1440
            case 'web': // Base: absolute web path.
1441
                $base = api_get_path(WEB_UPLOAD_PATH);
1442
                break;
1443
            case 'none':
1444
            default: // Base: empty, the result path below will be relative.
1445
                $base = '';
1446
        }
1447
1448
        if (empty($id) || empty($type)) {
1449
            return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
1450
        }
1451
1452
        $id = intval($id);
1453
        $group_table = Database :: get_main_table(TABLE_USERGROUP);
1454
        $sql = "SELECT picture FROM $group_table WHERE id = ".$id;
1455
        $res = Database::query($sql);
1456
1457
        if (!Database::num_rows($res)) {
1458
            return $anonymous ? array('dir' => $base.'img/', 'file' => 'unknown.jpg') : array('dir' => '', 'file' => '');
1459
        }
1460
        $user = Database::fetch_array($res);
1461
        $picture_filename = trim($user['picture']);
1462
1463 View Code Duplication
        if (api_get_setting('split_users_upload_directory') === 'true') {
1464
            if (!empty($picture_filename)) {
1465
                $dir = $base.'groups/'.substr($picture_filename, 0, 1).'/'.$id.'/';
1466
            } elseif ($preview) {
1467
                $dir = $base.'groups/'.substr((string) $id, 0, 1).'/'.$id.'/';
1468
            } else {
1469
                $dir = $base.'groups/'.$id.'/';
1470
            }
1471
        } else {
1472
            $dir = $base.'groups/'.$id.'/';
1473
        }
1474
1475
        return array('dir' => $dir, 'file' => $picture_filename);
1476
    }
1477
1478
    /**
1479
     * @return array
1480
     */
1481
    public function getAllowedPictureExtensions()
1482
    {
1483
        return $allowed_picture_types = array ('jpg', 'jpeg', 'png', 'gif');
1484
    }
1485
1486
    /**
1487
     * @return array
1488
     */
1489
    public function getGroupStatusList()
1490
    {
1491
        $status = [
1492
            GROUP_PERMISSION_OPEN => get_lang('Open'),
1493
            GROUP_PERMISSION_CLOSED => get_lang('Closed')
1494
        ];
1495
1496
        return $status;
1497
    }
1498
1499
    /**
1500
     * @param int $type
1501
     */
1502
    public function setGroupType($type)
1503
    {
1504
        $this->groupType = intval($type);
1505
    }
1506
1507
    /**
1508
     * @param int $group_id
1509
     * @param int $user_id
1510
     * @return bool
1511
     */
1512
    public function is_group_admin($group_id, $user_id = 0)
1513
    {
1514
        if (empty($user_id)) {
1515
            $user_id = api_get_user_id();
1516
        }
1517
        $user_role	= $this->get_user_group_role($user_id, $group_id);
1518
        if (in_array($user_role, array(GROUP_USER_PERMISSION_ADMIN))) {
1519
            return true;
1520
        } else {
1521
            return false;
1522
        }
1523
    }
1524
1525
    /**
1526
     * @param int $group_id
1527
     * @param int $user_id
1528
     * @return bool
1529
     */
1530 View Code Duplication
    public function is_group_moderator($group_id, $user_id = 0)
1531
    {
1532
        if (empty($user_id)) {
1533
            $user_id = api_get_user_id();
1534
        }
1535
        $user_role	= $this->get_user_group_role($user_id, $group_id);
1536
        if (in_array($user_role, array(GROUP_USER_PERMISSION_ADMIN, GROUP_USER_PERMISSION_MODERATOR))) {
1537
            return true;
1538
        } else {
1539
            return false;
1540
        }
1541
    }
1542
1543
    /**
1544
     * @param int $group_id
1545
     * @param int $user_id
1546
     * @return bool
1547
     */
1548 View Code Duplication
    public function is_group_member($group_id, $user_id = 0)
1549
    {
1550
        if (api_is_platform_admin()) {
1551
            return true;
1552
        }
1553
        if (empty($user_id)) {
1554
            $user_id = api_get_user_id();
1555
        }
1556
        $roles = array(
1557
            GROUP_USER_PERMISSION_ADMIN,
1558
            GROUP_USER_PERMISSION_MODERATOR,
1559
            GROUP_USER_PERMISSION_READER,
1560
            GROUP_USER_PERMISSION_HRM,
1561
        );
1562
        $user_role	= self::get_user_group_role($user_id, $group_id);
1563
        if (in_array($user_role, $roles)) {
1564
            return true;
1565
        } else {
1566
            return false;
1567
        }
1568
    }
1569
1570
    /**
1571
     * Gets the relationship between a group and a User
1572
     * @author Julio Montoya
1573
     * @param int $user_id
1574
     * @param int $group_id
1575
     * @return int 0 if there are not relationship otherwise returns the user group
1576
     * */
1577
    public function get_user_group_role($user_id, $group_id)
1578
    {
1579
        $table_group_rel_user= $this->usergroup_rel_user_table;
1580
        $return_value = 0;
1581
        if (!empty($user_id) && !empty($group_id)) {
1582
            $sql = "SELECT relation_type FROM $table_group_rel_user
1583
                    WHERE
1584
                        usergroup_id = ".intval($group_id)." AND
1585
                        user_id = ".intval($user_id)." ";
1586
            $result = Database::query($sql);
1587
            if (Database::num_rows($result)>0) {
1588
                $row = Database::fetch_array($result,'ASSOC');
1589
                $return_value = $row['relation_type'];
1590
            }
1591
        }
1592
1593
        return $return_value;
1594
    }
1595
1596
    /**
1597
     * @param int $userId
1598
     * @param int $groupId
1599
     * @return string
1600
     */
1601
    public function getUserRoleToString($userId, $groupId)
1602
    {
1603
        $role = self::get_user_group_role($userId, $groupId);
1604
        $roleToString = '';
1605
1606
        switch ($role) {
1607
            case GROUP_USER_PERMISSION_ADMIN:
1608
                $roleToString = get_lang('Admin');
1609
                break;
1610
            case GROUP_USER_PERMISSION_READER:
1611
                $roleToString = get_lang('Reader');
1612
                break;
1613
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
1614
                $roleToString = get_lang('PendingInvitation');
1615
                break;
1616
            case GROUP_USER_PERMISSION_MODERATOR:
1617
                $roleToString = get_lang('Moderator');
1618
                break;
1619
            case GROUP_USER_PERMISSION_HRM:
1620
                $roleToString = get_lang('Drh');
1621
                break;
1622
        }
1623
1624
        return $roleToString;
1625
    }
1626
1627
    /**
1628
     * Add a group of users into a group of URLs
1629
     * @author Julio Montoya
1630
     * @param array $user_list
1631
     * @param array $group_list
1632
     * @param int   $relation_type
1633
     * */
1634
    public function add_users_to_groups($user_list, $group_list, $relation_type = GROUP_USER_PERMISSION_READER)
1635
    {
1636
        $table_url_rel_group = $this->usergroup_rel_user_table;
1637
        $result_array = array();
1638
        $relation_type = intval($relation_type);
1639
1640
        if (is_array($user_list) && is_array($group_list)) {
1641
            foreach ($group_list as $group_id) {
1642
                foreach ($user_list as $user_id) {
1643
                    $role = self::get_user_group_role($user_id,$group_id);
1644
                    if ($role == 0) {
1645
                        $sql = "INSERT INTO $table_url_rel_group
1646
		               			SET
1647
		               			    user_id = ".intval($user_id).",
1648
		               			    usergroup_id = ".intval($group_id).",
1649
		               			    relation_type = ".intval($relation_type);
1650
1651
                        $result = Database::query($sql);
1652
                        if ($result) {
1653
                            $result_array[$group_id][$user_id] = 1;
1654
                        } else {
1655
                            $result_array[$group_id][$user_id] = 0;
1656
                        }
1657
                    }
1658
                }
1659
            }
1660
        }
1661
        return 	$result_array;
1662
    }
1663
1664
    /**
1665
     * Deletes an url and session relationship
1666
     * @author Julio Montoya
1667
     * @param  int  $user_id
1668
     * @param  int $group_id
1669
     * @return boolean true if success
1670
     * */
1671
    public function delete_user_rel_group($user_id, $group_id)
1672
    {
1673
        $table = $this->usergroup_rel_user_table;
1674
        $sql= "DELETE FROM $table
1675
               WHERE
1676
                user_id = ".intval($user_id)." AND
1677
                usergroup_id = ".intval($group_id)."  ";
1678
        $result = Database::query($sql);
1679
1680
        return $result;
1681
    }
1682
1683
    /**
1684
     * Add a user into a group
1685
     * @author Julio Montoya
1686
     * @param  int $user_id
1687
     * @param  int $group_id
1688
     * @param  int $relation_type
1689
     *
1690
     * @return boolean true if success
1691
     * */
1692
    public function add_user_to_group($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
1693
    {
1694
        $table_url_rel_group = $this->usergroup_rel_user_table;
1695
        if (!empty($user_id) && !empty($group_id)) {
1696
            $role = self::get_user_group_role($user_id, $group_id);
1697
1698
            if ($role == 0) {
1699
                $sql = "INSERT INTO $table_url_rel_group
1700
           				SET
1701
           				    user_id = ".intval($user_id).",
1702
           				    usergroup_id = ".intval($group_id).",
1703
           				    relation_type = ".intval($relation_type);
1704
                Database::query($sql);
1705
            } elseif ($role == GROUP_USER_PERMISSION_PENDING_INVITATION) {
1706
                //if somebody already invited me I can be added
1707
                self::update_user_role($user_id, $group_id, GROUP_USER_PERMISSION_READER);
1708
            }
1709
        }
1710
1711
        return true;
1712
    }
1713
1714
    /**
1715
     * Updates the group_rel_user table  with a given user and group ids
1716
     * @author Julio Montoya
1717
     * @param int $user_id
1718
     * @param int $group_id
1719
     * @param int $relation_type
1720
     *
1721
     **/
1722
    public function update_user_role($user_id, $group_id, $relation_type = GROUP_USER_PERMISSION_READER)
1723
    {
1724
        $table_group_rel_user = $this->usergroup_rel_user_table;
1725
        $group_id = intval($group_id);
1726
        $user_id = intval($user_id);
1727
1728
        $sql = "UPDATE $table_group_rel_user
1729
   				SET relation_type = ".intval($relation_type)."
1730
                WHERE user_id = $user_id AND usergroup_id = $group_id" ;
1731
        Database::query($sql);
1732
    }
1733
1734
    /**
1735
     * Gets the inner join from users and group table
1736
     *
1737
     * @return array   Database::store_result of the result
1738
     *
1739
     * @author Julio Montoya
1740
     * */
1741
    public function get_groups_by_user($user_id = '', $relation_type = GROUP_USER_PERMISSION_READER, $with_image = false)
1742
    {
1743
        $table_group_rel_user = $this->usergroup_rel_user_table;
1744
        $tbl_group = $this->table;
1745
1746
        if ($relation_type == 0) {
1747
            $relationCondition = '';
1748
        } else {
1749
            $relation_type = intval($relation_type);
1750
            $relationCondition = " AND gu.relation_type = $relation_type ";
1751
        }
1752
1753
        $sql = "SELECT
1754
                    g.picture,
1755
                    g.name,
1756
                    g.description,
1757
                    g.id ,
1758
                    gu.relation_type
1759
				FROM $tbl_group g
1760
				INNER JOIN $table_group_rel_user gu
1761
				ON gu.usergroup_id = g.id
1762
				WHERE
1763
				    g.group_type = ".self::SOCIAL_CLASS." AND
1764
                    gu.user_id = $user_id
1765
                    $relationCondition
1766
                ORDER BY created_at DESC ";
1767
        $result = Database::query($sql);
1768
        $array = array();
1769 View Code Duplication
        if (Database::num_rows($result) > 0) {
1770
            while ($row = Database::fetch_array($result, 'ASSOC')) {
1771
                if ($with_image) {
1772
                    $picture = self::get_picture_group($row['id'], $row['picture'],80);
1773
                    $img = '<img src="'.$picture['file'].'" />';
1774
                    $row['picture'] = $img;
1775
                }
1776
                $array[$row['id']] = $row;
1777
            }
1778
        }
1779
        return $array;
1780
    }
1781
1782
    /** Gets the inner join of users and group table
1783
     * @param int  quantity of records
1784
     * @param bool show groups with image or not
1785
     * @return array  with group content
1786
     * @author Julio Montoya
1787
     * */
1788 View Code Duplication
    public function get_groups_by_popularity($num = 6, $with_image = true)
1789
    {
1790
        $table_group_rel_user = $this->usergroup_rel_user_table;
1791
        $tbl_group = $this->table;
1792
        if (empty($num)) {
1793
            $num = 6;
1794
        } else {
1795
            $num = intval($num);
1796
        }
1797
        // only show admins and readers
1798
        $where_relation_condition = " WHERE g.group_type = ".self::SOCIAL_CLASS." AND
1799
                                      gu.relation_type IN ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
1800
        $sql = "SELECT DISTINCT count(user_id) as count, g.picture, g.name, g.description, g.id
1801
				FROM $tbl_group g
1802
				INNER JOIN $table_group_rel_user gu
1803
				ON gu.usergroup_id = g.id $where_relation_condition
1804
				GROUP BY g.id
1805
				ORDER BY count DESC
1806
				LIMIT $num";
1807
1808
        $result=Database::query($sql);
1809
        $array = array();
1810
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1811
            if ($with_image) {
1812
                $picture = self::get_picture_group($row['id'], $row['picture'],80);
1813
                $img = '<img src="'.$picture['file'].'" />';
1814
                $row['picture'] = $img;
1815
            }
1816
            if (empty($row['id'])) {
1817
                continue;
1818
            }
1819
            $array[$row['id']] = $row;
1820
        }
1821
1822
        return $array;
1823
    }
1824
1825
    /** Gets the last groups created
1826
     * @param int  quantity of records
1827
     * @param bool show groups with image or not
1828
     * @return array  with group content
1829
     * @author Julio Montoya
1830
     * */
1831 View Code Duplication
    public function get_groups_by_age($num = 6, $with_image = true)
1832
    {
1833
        $table_group_rel_user = $this->usergroup_rel_user_table;
1834
        $tbl_group = $this->table;
1835
1836
        if (empty($num)) {
1837
            $num = 6;
1838
        } else {
1839
            $num = intval($num);
1840
        }
1841
        $where_relation_condition = " WHERE g.group_type = ".self::SOCIAL_CLASS." AND
1842
                                      gu.relation_type IN ('".GROUP_USER_PERMISSION_ADMIN."' , '".GROUP_USER_PERMISSION_READER."', '".GROUP_USER_PERMISSION_HRM."') ";
1843
        $sql = "SELECT DISTINCT
1844
                  count(user_id) as count,
1845
                  g.picture,
1846
                  g.name,
1847
                  g.description,
1848
                  g.id
1849
                FROM $tbl_group g
1850
                INNER JOIN $table_group_rel_user gu
1851
                ON gu.usergroup_id = g.id
1852
                $where_relation_condition
1853
                GROUP BY g.id
1854
                ORDER BY created_at DESC
1855
                LIMIT $num ";
1856
1857
        $result=Database::query($sql);
1858
        $array = array();
1859
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1860
            if ($with_image) {
1861
                $picture = self::get_picture_group($row['id'], $row['picture'],80);
1862
                $img = '<img src="'.$picture['file'].'" />';
1863
                $row['picture'] = $img;
1864
            }
1865
            if (empty($row['id'])) {
1866
                continue;
1867
            }
1868
            $array[$row['id']] = $row;
1869
        }
1870
        return $array;
1871
    }
1872
1873
    /**
1874
     * Gets the group's members
1875
     * @param int group id
1876
     * @param bool show image or not of the group
1877
     * @param array list of relation type use constants
1878
     * @param int from value
1879
     * @param int limit
1880
     * @param array image configuration, i.e array('height'=>'20px', 'size'=> '20px')
1881
     * @return array list of users in a group
1882
     */
1883
    public function get_users_by_group(
1884
        $group_id,
1885
        $with_image = false,
1886
        $relation_type = array(),
1887
        $from = null,
1888
        $limit = null,
1889
        $image_conf = array('size' => USER_IMAGE_SIZE_MEDIUM, 'height' => 80)
1890
    ) {
1891
        $table_group_rel_user = $this->usergroup_rel_user_table;
1892
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1893
        $group_id = intval($group_id);
1894
1895
        if (empty($group_id)){
1896
            return array();
1897
        }
1898
1899
        $limit_text = '';
1900 View Code Duplication
        if (isset($from) && isset($limit)) {
1901
            $from = intval($from);
1902
            $limit = intval($limit);
1903
            $limit_text = "LIMIT $from, $limit";
1904
        }
1905
1906 View Code Duplication
        if (count($relation_type) == 0) {
1907
            $where_relation_condition = '';
1908
        } else {
1909
            $new_relation_type = array();
1910
            foreach($relation_type as $rel) {
1911
                $rel = intval($rel);
1912
                $new_relation_type[] ="'$rel'";
1913
            }
1914
            $relation_type = implode(',', $new_relation_type);
1915
            if (!empty($relation_type))
1916
                $where_relation_condition = "AND gu.relation_type IN ($relation_type) ";
1917
        }
1918
1919
        $sql = "SELECT picture_uri as image, u.id, u.firstname, u.lastname, relation_type
1920
    		    FROM $tbl_user u
1921
    		    INNER JOIN $table_group_rel_user gu
1922
    			ON (gu.user_id = u.id)
1923
    			WHERE
1924
    			    gu.usergroup_id= $group_id
1925
    			    $where_relation_condition
1926
    			ORDER BY relation_type, firstname
1927
    			$limit_text";
1928
1929
        $result = Database::query($sql);
1930
        $array  = array();
1931
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1932
            if ($with_image) {
1933
                $userInfo = api_get_user_info($row['id']);
1934
                $userPicture = UserManager::getUserPicture($row['id']);
1935
1936
                $row['image'] = '<img src="'.$userPicture.'"  />';
1937
                $row['user_info'] = $userInfo;
1938
            }
1939
            $array[$row['id']] = $row;
1940
        }
1941
        return $array;
1942
    }
1943
1944
    /**
1945
     * Gets all the members of a group no matter the relationship for
1946
     * more specifications use get_users_by_group
1947
     * @param int group id
1948
     * @return array
1949
     */
1950
    public function get_all_users_by_group($group_id)
1951
    {
1952
        $table_group_rel_user = $this->usergroup_rel_user_table;
1953
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
1954
        $group_id = intval($group_id);
1955
1956
        if (empty($group_id)){
1957
            return array();
1958
        }
1959
1960
        $sql = "SELECT u.id, u.firstname, u.lastname, relation_type
1961
                FROM $tbl_user u
1962
			    INNER JOIN $table_group_rel_user gu
1963
			    ON (gu.user_id = u.id)
1964
			    WHERE gu.usergroup_id= $group_id
1965
			    ORDER BY relation_type, firstname";
1966
1967
        $result=Database::query($sql);
1968
        $array = array();
1969
        while ($row = Database::fetch_array($result, 'ASSOC')) {
1970
            $array[$row['id']] = $row;
1971
        }
1972
        return $array;
1973
    }
1974
1975
    /**
1976
     * Shows the left column of the group page
1977
     * @param int group id
1978
     * @param int user id
1979
     *
1980
     */
1981
    public function show_group_column_information($group_id, $user_id, $show = '')
1982
    {
1983
        $html = '';
1984
        $group_info = $this->get($group_id);
1985
1986
        //my relation with the group is set here
1987
        $my_group_role = self::get_user_group_role($user_id, $group_id);
1988
1989
        // Loading group permission
1990
1991
        $links = '';
1992
        switch ($my_group_role) {
1993 View Code Duplication
            case GROUP_USER_PERMISSION_READER:
1994
                // I'm just a reader
1995
                $relation_group_title = get_lang('IAmAReader');
1996
                $links .=  '<li><a href="group_invitation.php?id='.$group_id.'">'.
1997
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace'=>'6')).'<span class="'.($show=='invite_friends'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
1998
                $links .=  '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
1999
                            Display::return_icon('group_leave.png', get_lang('LeaveGroup'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
2000
                break;
2001 View Code Duplication
            case GROUP_USER_PERMISSION_ADMIN:
2002
                $relation_group_title = get_lang('IAmAnAdmin');
2003
                $links .=  '<li><a href="group_edit.php?id='.$group_id.'">'.
2004
                            Display::return_icon('group_edit.png', get_lang('EditGroup'), array('hspace'=>'6')).'<span class="'.($show=='group_edit'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('EditGroup').'</span></a></li>';
2005
                $links .=  '<li><a href="group_waiting_list.php?id='.$group_id.'">'.
2006
                            Display::return_icon('waiting_list.png', get_lang('WaitingList'), array('hspace'=>'6')).'<span class="'.($show=='waiting_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('WaitingList').'</span></a></li>';
2007
                $links .=  '<li><a href="group_invitation.php?id='.$group_id.'">'.
2008
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace'=>'6')).'<span class="'.($show=='invite_friends'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
2009
                $links .=  '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2010
                            Display::return_icon('group_leave.png', get_lang('LeaveGroup'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
2011
                break;
2012
            case GROUP_USER_PERMISSION_PENDING_INVITATION:
2013
//				$links .=  '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('YouHaveBeenInvitedJoinNow'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('YouHaveBeenInvitedJoinNow').'</span></a></li>';
2014
                break;
2015
            case GROUP_USER_PERMISSION_PENDING_INVITATION_SENT_BY_USER:
2016
                $relation_group_title =  get_lang('WaitingForAdminResponse');
2017
                break;
2018 View Code Duplication
            case GROUP_USER_PERMISSION_MODERATOR:
2019
                $relation_group_title = get_lang('IAmAModerator');
2020
                //$links .=  '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="thickbox" title="'.get_lang('ComposeMessage').'">'.Display::return_icon('compose_message.png', get_lang('NewTopic'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('NewTopic').'</span></a></li>';
2021
                //$links .=  '<li><a href="groups.php?id='.$group_id.'">'.				Display::return_icon('message_list.png', get_lang('MessageList'), array('hspace'=>'6')).'<span class="'.($show=='messages_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('MessageList').'</span></a></li>';
2022
                //$links .=  '<li><a href="group_members.php?id='.$group_id.'">'.		Display::return_icon('member_list.png', get_lang('MemberList'), array('hspace'=>'6')).'<span class="'.($show=='member_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('MemberList').'</span></a></li>';
2023
                if ($group_info['visibility'] == GROUP_PERMISSION_CLOSED) {
2024
                    $links .=  '<li><a href="group_waiting_list.php?id='.$group_id.'">'.
2025
                                Display::return_icon('waiting_list.png', get_lang('WaitingList'), array('hspace'=>'6')).'<span class="'.($show=='waiting_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('WaitingList').'</span></a></li>';
2026
                }
2027
                $links .=  '<li><a href="group_invitation.php?id='.$group_id.'">'.
2028
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace'=>'6')).'<span class="'.($show=='invite_friends'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
2029
                $links .=  '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2030
                            Display::return_icon('group_leave.png', get_lang('LeaveGroup'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
2031
                break;
2032 View Code Duplication
            case GROUP_USER_PERMISSION_HRM:
2033
                $relation_group_title = get_lang('IAmAHRM');
2034
                $links .= '<li><a href="'.api_get_path(WEB_CODE_PATH).'social/message_for_group_form.inc.php?view_panel=1&height=400&width=610&&user_friend='.api_get_user_id().'&group_id='.$group_id.'&action=add_message_group" class="ajax" title="'.get_lang('ComposeMessage').'" data-size="lg" data-title="'.get_lang('ComposeMessage').'">'.
2035
                            Display::return_icon('new-message.png', get_lang('NewTopic'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('NewTopic').'</span></a></li>';
2036
                $links .=  '<li><a href="group_view.php?id='.$group_id.'">'.
2037
                            Display::return_icon('message_list.png', get_lang('MessageList'), array('hspace'=>'6')).'<span class="'.($show=='messages_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('MessageList').'</span></a></li>';
2038
                $links .=  '<li><a href="group_invitation.php?id='.$group_id.'">'.
2039
                            Display::return_icon('invitation_friend.png', get_lang('InviteFriends'), array('hspace'=>'6')).'<span class="'.($show=='invite_friends'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('InviteFriends').'</span></a></li>';
2040
                $links .=  '<li><a href="group_members.php?id='.$group_id.'">'.
2041
                            Display::return_icon('member_list.png', get_lang('MemberList'), array('hspace'=>'6')).'<span class="'.($show=='member_list'?'social-menu-text-active':'social-menu-text4').'" >'.get_lang('MemberList').'</span></a></li>';
2042
                $links .=  '<li><a href="group_view.php?id='.$group_id.'&action=leave&u='.api_get_user_id().'">'.
2043
                            Display::return_icon('delete_data.gif', get_lang('LeaveGroup'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('LeaveGroup').'</span></a></li>';
2044
                break;
2045
            default:
2046
                //$links .=  '<li><a href="groups.php?id='.$group_id.'&action=join&u='.api_get_user_id().'">'.Display::return_icon('addd.gif', get_lang('JoinGroup'), array('hspace'=>'6')).'<span class="social-menu-text4" >'.get_lang('JoinGroup').'</a></span></li>';
2047
                break;
2048
        }
2049
2050
        if (!empty($links)) {
2051
            $html .= '<div class="panel panel-default">';
2052
            $html .= '<div class="panel-body">';
2053
            $html .= '<ul class="nav nav-pills nav-stacked">';
2054
            $html .= $links;
2055
            $html .= '</ul>';
2056
            $html .= '</div>';
2057
            $html .= '</div>';
2058
        }
2059
2060
        return $html;
2061
    }
2062
2063
    public function delete_topic($group_id, $topic_id)
2064
    {
2065
        $table_message = Database::get_main_table(TABLE_MESSAGE);
2066
        $topic_id = intval($topic_id);
2067
        $group_id = intval($group_id);
2068
        $sql = "UPDATE $table_message SET
2069
                msg_status = 3
2070
                WHERE
2071
                    group_id = $group_id AND
2072
                    (id = '$topic_id' OR parent_id = $topic_id)
2073
                ";
2074
        Database::query($sql);
2075
    }
2076
2077
    /**
2078
     * @param string $user_id
2079
     * @param string $relation_type
2080
     * @param bool $with_image
2081
     * @return int
2082
     */
2083
    public function get_groups_by_user_count($user_id = '', $relation_type = GROUP_USER_PERMISSION_READER, $with_image = false)
2084
    {
2085
        $table_group_rel_user	= $this->usergroup_rel_user_table;
2086
        $tbl_group				= $this->table;
2087
        $user_id 				= intval($user_id);
2088
2089 View Code Duplication
        if ($relation_type == 0) {
2090
            $where_relation_condition = '';
2091
        } else {
2092
            $relation_type 			= intval($relation_type);
2093
            $where_relation_condition = "AND gu.relation_type = $relation_type ";
2094
        }
2095
2096
        $sql = "SELECT count(g.id) as count
2097
				FROM $tbl_group g
2098
				INNER JOIN $table_group_rel_user gu
2099
				ON gu.usergroup_id = g.id
2100
				WHERE gu.user_id = $user_id $where_relation_condition ";
2101
2102
        $result = Database::query($sql);
2103
        if (Database::num_rows($result) > 0) {
2104
            $row = Database::fetch_array($result, 'ASSOC');
2105
            return $row['count'];
2106
        }
2107
        return 0;
2108
    }
2109
2110
    /**
2111
     * @param string $tag
2112
     * @param int    $from
2113
     * @param int    $number_of_items
2114
     *
2115
     * @return array
2116
     */
2117
    public function get_all_group_tags($tag, $from = 0, $number_of_items = 10, $getCount = false)
2118
    {
2119
        $group_table = $this->table;
2120
        $table_tag = Database::get_main_table(TABLE_MAIN_TAG);
2121
        //$table_group_tag_values	= Database::get_main_table(TABLE_USERGROUP_REL_TAG);
2122
2123
        $field_id = 5;
2124
        $tag = Database::escape_string($tag);
2125
        $from = intval($from);
2126
        $number_of_items = intval($number_of_items);
2127
        $return = array();
2128
2129
        // all the information of the field
2130
        /*$select = "SELECT g.id, g.name, g.description, g.picture";
2131
2132
        $sql = "$select
2133
                FROM $table_tag t
2134
                INNER JOIN $table_group_tag_values tv
2135
                ON (tv.tag_id=t.id)
2136
                INNER JOIN $group_table g
2137
                ON (tv.usergroup_id =g.id)
2138
				WHERE
2139
				    tag LIKE '$tag%' AND
2140
				    field_id= $field_id
2141
                ORDER BY tag";
2142
2143
        $sql .= " LIMIT $from, $number_of_items";
2144
2145
        $result = Database::query($sql);
2146
2147
        if (Database::num_rows($result)> 0) {
2148
            while ($row = Database::fetch_array($result,'ASSOC')) {
2149
                $return[$row['id']] = $row;
2150
            }
2151
        }*/
2152
2153
        $keyword = $tag;
2154
        $sql = "SELECT  g.id, g.name, g.description, g.url, g.picture
2155
                FROM $group_table g";
2156
        if (isset ($keyword)) {
2157
            $sql .= " WHERE (
2158
                        g.name LIKE '%".$keyword."%' OR
2159
                        g.description LIKE '%".$keyword."%' OR
2160
                        g.url LIKE '%".$keyword."%'
2161
                     )";
2162
        }
2163
2164
        $direction = 'ASC';
2165
        if (!in_array($direction, array('ASC','DESC'))) {
2166
            $direction = 'ASC';
2167
        }
2168
2169
        $from = intval($from);
2170
        $number_of_items = intval($number_of_items);
2171
2172
        //$sql .= " ORDER BY col$column $direction ";
2173
        $sql .= " LIMIT $from,$number_of_items";
2174
2175
        $res = Database::query($sql);
2176
        if (Database::num_rows($res)> 0) {
2177
            while ($row = Database::fetch_array($res,'ASSOC')) {
2178
                if (!in_array($row['id'], $return)) {
2179
                    $return[$row['id']] = $row;
2180
                }
2181
            }
2182
        }
2183
        return $return;
2184
    }
2185
2186
    /**
2187
     * @param int $group_id
2188
     * @return array
2189
     */
2190 View Code Duplication
    public static function get_parent_groups($group_id)
2191
    {
2192
        $t_rel_group = Database :: get_main_table(TABLE_USERGROUP_REL_USERGROUP);
2193
        $max_level = 10;
2194
        $select_part = "SELECT ";
2195
        $cond_part = '';
2196
        for ($i = 1; $i <= $max_level; $i++) {
2197
            $g_number = $i;
2198
            $rg_number = $i - 1;
2199
            if ($i == $max_level) {
2200
                $select_part .= "rg$rg_number.group_id as id_$rg_number ";
2201
            } else {
2202
                $select_part .="rg$rg_number.group_id as id_$rg_number, ";
2203
            }
2204
            if ($i == 1) {
2205
                $cond_part .= "FROM $t_rel_group rg0 LEFT JOIN $t_rel_group rg$i on rg$rg_number.group_id = rg$i.subgroup_id ";
2206
            } else {
2207
                $cond_part .= " LEFT JOIN $t_rel_group rg$i on rg$rg_number.group_id = rg$i.subgroup_id ";
2208
            }
2209
        }
2210
        $sql = $select_part.' '.$cond_part."WHERE rg0.subgroup_id='$group_id'";
2211
        $res = Database::query($sql);
2212
        $temp_arr = Database::fetch_array($res, 'NUM');
2213
        $toReturn = array();
2214
        if (is_array($temp_arr)) {
2215
            foreach ($temp_arr as $elt) {
2216
                if (isset($elt)) {
2217
                    $toReturn[] = $elt;
2218
                }
2219
            }
2220
        }
2221
2222
        return $toReturn;
2223
    }
2224
2225
    /**
2226
     * Get the group member list by a user and his group role
2227
     * @param int $userId The user ID
2228
     * @param int $relationType Optional. The relation type. GROUP_USER_PERMISSION_ADMIN by default
2229
     * @param boolean $includeSubgroupsUsers Optional. Whether include the users from subgroups
2230
     * @return array
2231
     */
2232 View Code Duplication
    public function getGroupUsersByUser(
2233
        $userId,
2234
        $relationType = GROUP_USER_PERMISSION_ADMIN,
2235
        $includeSubgroupsUsers = true
2236
    ) {
2237
        $userId = intval($userId);
2238
2239
        $groups = $this->get_groups_by_user($userId, $relationType);
2240
2241
        $groupsId = array_keys($groups);
2242
        $subgroupsId = [];
2243
        $userIdList = [];
2244
2245
        if ($includeSubgroupsUsers) {
2246
            foreach ($groupsId as $groupId) {
2247
                $subgroupsId = array_merge($subgroupsId, self::getGroupsByDepthLevel($groupId));
2248
            }
2249
2250
            $groupsId = array_merge($groupsId, $subgroupsId);
2251
        }
2252
2253
        $groupsId = array_unique($groupsId);
2254
2255
        if (empty($groupsId)) {
2256
            return [];
2257
        }
2258
2259
        foreach ($groupsId as $groupId) {
2260
            $groupUsers = self::get_users_by_group($groupId);
2261
2262
            if (empty($groupUsers)) {
2263
                continue;
2264
            }
2265
2266
            foreach ($groupUsers as $member) {
2267
                if ($member['user_id'] == $userId) {
2268
                    continue;
2269
                }
2270
2271
                $userIdList[] = intval($member['user_id']);
2272
            }
2273
        }
2274
2275
        return array_unique($userIdList);
2276
    }
2277
2278
    /**
2279
     * Get the subgroups ID from a group.
2280
     * The default $levels value is 10 considering it as a extensive level of depth
2281
     * @param int $groupId The parent group ID
2282
     * @param int $levels The depth levels
2283
     * @return array The list of ID
2284
     */
2285 View Code Duplication
    public static function getGroupsByDepthLevel($groupId, $levels = 10)
2286
    {
2287
        $groups = array();
2288
        $groupId = intval($groupId);
2289
2290
        $groupTable = Database::get_main_table(TABLE_USERGROUP);
2291
        $groupRelGroupTable = Database :: get_main_table(TABLE_USERGROUP_REL_USERGROUP);
2292
2293
        $select = "SELECT ";
2294
        $from = "FROM $groupTable g1 ";
2295
2296
        for ($i = 1; $i <= $levels; $i++) {
2297
            $tableIndexNumber = $i;
2298
            $tableIndexJoinNumber = $i - 1;
2299
2300
            $select .= "g$i.id as id_$i ";
2301
2302
            $select .= ($i != $levels ? ", " : null);
2303
2304
            if ($i == 1) {
2305
                $from .= "INNER JOIN $groupRelGroupTable gg0 ON g1.id = gg0.subgroup_id and gg0.group_id = $groupId ";
2306
            } else {
2307
                $from .= "LEFT JOIN $groupRelGroupTable gg$tableIndexJoinNumber ";
2308
                $from .= " ON g$tableIndexJoinNumber.id = gg$tableIndexJoinNumber.group_id ";
2309
                $from .= "LEFT JOIN $groupTable g$tableIndexNumber ";
2310
                $from .= " ON gg$tableIndexJoinNumber.subgroup_id = g$tableIndexNumber.id ";
2311
            }
2312
        }
2313
2314
        $result = Database::query("$select $from");
2315
2316
        while ($item = Database::fetch_assoc($result)) {
2317
            foreach ($item as $groupId) {
2318
                if (!empty($groupId)) {
2319
                    $groups[] = $groupId;
2320
                }
2321
            }
2322
        }
2323
2324
        return array_map('intval', $groups);
2325
    }
2326
2327
    /**
2328
     * Set a parent group
2329
     * @param int $group_id
2330
     * @param int $parent_group_id if 0, we delete the parent_group association
2331
     * @param int $relation_type
2332
     * @return resource
2333
     **/
2334 View Code Duplication
    public static function set_parent_group($group_id, $parent_group_id, $relation_type = 1)
2335
    {
2336
        $table = Database :: get_main_table(TABLE_USERGROUP_REL_USERGROUP);
2337
        $group_id = intval($group_id);
2338
        $parent_group_id = intval($parent_group_id);
2339
        if ($parent_group_id == 0) {
2340
            $sql = "DELETE FROM $table WHERE subgroup_id = $group_id";
2341
        } else {
2342
            $sql = "SELECT group_id FROM $table WHERE subgroup_id = $group_id";
2343
            $res = Database::query($sql);
2344
            if (Database::num_rows($res) == 0) {
2345
                $sql = "INSERT INTO $table SET
2346
                        group_id = $parent_group_id,
2347
                        subgroup_id = $group_id,
2348
                        relation_type = $relation_type";
2349
            } else {
2350
                $sql = "UPDATE $table SET
2351
                        group_id = $parent_group_id,
2352
                        relation_type = $relation_type
2353
                        WHERE subgroup_id = $group_id";
2354
            }
2355
        }
2356
        $res = Database::query($sql);
2357
        return $res;
2358
    }
2359
2360
    /**
2361
     * Filter the groups/classes info to get a name list only
2362
     * @param int $userId The user ID
2363
     * @param int $filterByType Optional. The type of group
2364
     * @return array
2365
     */
2366
    public function getNameListByUser($userId, $filterByType = null)
2367
    {
2368
        $userClasses = $this->getUserGroupListByUser($userId, $filterByType);
2369
2370
        return array_column($userClasses, 'name');
2371
    }
2372
2373
    /**
2374
     * Get the HTML necessary for display the groups/classes name list
2375
     * @param int $userId The user ID
2376
     * @param int $filterByType Optional. The type of group
2377
     * @return string
2378
     */
2379
    public function getLabelsFromNameList($userId, $filterByType = null)
2380
    {
2381
        $groupsNameListParsed = $this->getNameListByUser($userId, $filterByType);
2382
2383
        if (empty($groupsNameListParsed)) {
2384
            return '';
2385
        }
2386
2387
        $nameList = '<ul class="list-unstyled">';
2388
2389
        foreach ($groupsNameListParsed as $name) {
2390
            $nameList .= '<li>' . Display::span($name, ['class' => 'label label-info']) . '</li>';
2391
        }
2392
2393
        $nameList .= '</ul>';
2394
2395
        return $nameList;
2396
    }
2397
}
2398
2399