Passed
Push — master ( d3b47f...951609 )
by Angel Fernando Quiroz
18:41
created

UrlManager::relation_url_user_exist()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 6
nc 1
nop 2
dl 0
loc 9
rs 10
c 0
b 0
f 0
1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\AccessUrl;
6
use Chamilo\CoreBundle\Entity\AccessUrlRelCourse;
7
use Chamilo\CoreBundle\Entity\AccessUrlRelSession;
8
use Chamilo\CoreBundle\Entity\AccessUrlRelUser;
9
use Chamilo\CoreBundle\Entity\AccessUrlRelUserGroup;
10
use Chamilo\CoreBundle\Framework\Container;
11
use Doctrine\ORM\NonUniqueResultException;
12
use Doctrine\ORM\NoResultException;
13
14
/**
15
 * Class UrlManager
16
 * This library provides functions for the access_url management.
17
 * Include/require it in your code to use its functionality.
18
 */
19
class UrlManager
20
{
21
    /**
22
     * Creates a new url access.
23
     *
24
     * @author Julio Montoya <[email protected]>,
25
     *
26
     * @param string $url         The URL of the site
27
     * @param string $description The description of the site
28
     * @param int    $active      is active or not
29
     */
30
    public static function add($url, $description, $active, bool $isLoginOnly = false): ?AccessUrl
31
    {
32
        $repo = Container::getAccessUrlRepository();
33
34
        if (!$repo->exists($url)) {
35
            return null;
36
        }
37
38
        $accessUrl = new AccessUrl();
39
        $accessUrl
40
            ->setDescription($description)
41
            ->setActive($active)
42
            ->setUrl($url)
43
            ->setCreatedBy(api_get_user_id())
44
            ->setIsLoginOnly($isLoginOnly)
45
        ;
46
47
        $repo->create($accessUrl);
48
49
        return $accessUrl;
50
    }
51
52
    /**
53
     * Updates an URL access.
54
     *
55
     * @author Julio Montoya <[email protected]>,
56
     *
57
     * @param int    $urlId       The url id
58
     * @param string $url
59
     * @param string $description The description of the site
60
     * @param int    $active      is active or not
61
     *
62
     * @return bool if success
63
     */
64
    public static function update($urlId, $url, $description, $active, bool $isLoginOnly = false)
65
    {
66
        $urlId = (int) $urlId;
67
        $active = (int) $active;
68
69
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
70
71
        return Database::update(
0 ignored issues
show
Bug Best Practice introduced by
The expression return Database::update(...= ?' => array($urlId))) also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
72
            $table,
73
            [
74
                'url' => $url,
75
                'description' => $description,
76
                'active' => $active,
77
                'created_by' => api_get_user_id(),
78
                'tms' => api_get_utc_datetime(),
79
                'is_login_only' => $isLoginOnly,
80
            ],
81
            ['id = ?' => [$urlId]]
82
        );
83
    }
84
85
    /**
86
     * Deletes an url.
87
     *
88
     * @author Julio Montoya
89
     *
90
     * @param int $id url id
91
     *
92
     * @return bool true if success
93
     * */
94
    public static function delete($id)
95
    {
96
        $id = (int) $id;
97
98
        /*
99
         * $tableCourseCategory = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
100
        $sql = "DELETE FROM $tableCourseCategory WHERE access_url_id = ".$id;
101
        Database::query($sql);
102
        */
103
        $em = Container::getEntityManager();
104
105
        $relEntities = [
106
            AccessUrlRelCourse::class,
107
            AccessUrlRelSession::class,
108
            AccessUrlRelUserGroup::class,
109
            AccessUrlRelUser::class,
110
        ];
111
112
        foreach ($relEntities as $relEntity) {
113
            $qb = $em->createQueryBuilder();
114
115
            $em
116
                ->createQueryBuilder()
117
                ->delete($relEntity, 'rel')
118
                ->where($qb->expr()->eq('rel.url', ':id'))
119
                ->setParameter('id', $id)
120
                ->getQuery()
121
                ->execute()
122
            ;
123
        }
124
125
        $qb = $em->createQueryBuilder();
126
127
        $em
128
            ->createQueryBuilder()
129
            ->delete(AccessUrl::class, 'au')
130
            ->where($qb->expr()->eq('au.id', ':id'))
131
            ->setParameter('id', $id)
132
            ->getQuery()
133
            ->execute()
134
        ;
135
136
        return true;
137
    }
138
139
    /**
140
     * This function get the quantity of URLs.
141
     *
142
     * @author Julio Montoya
143
     *
144
     * @return int count of urls
145
     * */
146
    public static function url_count()
147
    {
148
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
149
        $sql = "SELECT count(id) as count_result FROM $table";
150
        $res = Database::query($sql);
151
        $url = Database::fetch_assoc($res);
152
        $result = $url['count_result'];
153
154
        return $result;
155
    }
156
157
    /**
158
     * Gets the id, url, description, and active status of ALL URLs.
159
     *
160
     * @author Julio Montoya
161
     *
162
     * @param int $urlId
163
     *
164
     * @return array
165
     * */
166
    public static function get_url_data_from_id($urlId)
167
    {
168
        $urlId = (int) $urlId;
169
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
170
        $sql = "SELECT id, url, description, active
171
                FROM $table
172
                WHERE id = ".$urlId;
173
        $res = Database::query($sql);
174
175
        return Database::fetch_array($res);
176
    }
177
178
    /**
179
     * Gets the inner join of users and urls table.
180
     *
181
     * @author Julio Montoya
182
     *
183
     * @param int  access url id
184
     * @param string $order_by
185
     *
186
     * @return array Database::store_result of the result
187
     */
188
    public static function get_url_rel_user_data($urlId = 0, $order_by = null)
189
    {
190
        $urlId = (int) $urlId;
191
        $where = ' WHERE u.active <> '.USER_SOFT_DELETED.' ';
192
        $table_url_rel_user = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
193
        $tbl_user = Database::get_main_table(TABLE_MAIN_USER);
194
        if (!empty($urlId)) {
195
            $where = " AND $table_url_rel_user.access_url_id = ".$urlId;
196
        }
197
        if (empty($order_by)) {
198
            $order_clause = api_sort_by_first_name(
199
            ) ? ' ORDER BY firstname, lastname, username' : ' ORDER BY lastname, firstname, username';
200
        } else {
201
            $order_clause = $order_by;
202
        }
203
        $sql = "SELECT u.id as user_id, lastname, firstname, username, official_code, access_url_id
204
                FROM $tbl_user u
205
                INNER JOIN $table_url_rel_user
206
                ON $table_url_rel_user.user_id = u.id
207
                $where  $order_clause";
208
        $result = Database::query($sql);
209
210
        return Database::store_result($result);
211
    }
212
213
    /**
214
     * Gets the inner join of access_url and the course table.
215
     *
216
     * @author Julio Montoya
217
     *
218
     * @param int  access url id
219
     *
220
     * @return array Database::store_result of the result
221
     */
222
    public static function get_url_rel_course_data($urlId = 0)
223
    {
224
        $where = '';
225
        $urlId = (int) $urlId;
226
        $table_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
227
        $tbl_course = Database::get_main_table(TABLE_MAIN_COURSE);
228
229
        if (!empty($urlId)) {
230
            $where = " WHERE uc.access_url_id = $urlId ";
231
        }
232
233
        $sql = "SELECT u.id, c_id, title, uc.access_url_id
234
                FROM $tbl_course u
235
                INNER JOIN $table_url_rel_course uc
236
                ON uc.c_id = u.id
237
                $where
238
                ORDER BY title, code";
239
240
        $result = Database::query($sql);
241
        $courses = Database::store_result($result);
242
243
        return $courses;
244
    }
245
246
    /**
247
     * Gets the number of rows with a specific course_code in access_url_rel_course table.
248
     *
249
     * @author Yoselyn Castillo
250
     *
251
     * @param int $courseId
252
     *
253
     * @return int Database::num_rows($res);
254
     */
255
    public static function getCountUrlRelCourse($courseId)
256
    {
257
        $courseId = (int) $courseId;
258
        $tableUrlRelCourse = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
259
        $sql = "SELECT *
260
                FROM $tableUrlRelCourse
261
                WHERE c_id = '$courseId'";
262
        $res = Database::query($sql);
263
264
        return Database::num_rows($res);
265
    }
266
267
    /**
268
     * Gets the inner join of access_url and the session table.
269
     *
270
     * @author Julio Montoya
271
     *
272
     * @param int $urlId access url id
273
     *
274
     * @return array Database::store_result of the result
275
     */
276
    public static function get_url_rel_session_data($urlId = 0)
277
    {
278
        $urlId = (int) $urlId;
279
        $where = '';
280
        $table_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
281
        $tbl_session = Database::get_main_table(TABLE_MAIN_SESSION);
282
283
        if (!empty($urlId)) {
284
            $where = "WHERE $table_url_rel_session.access_url_id = ".$urlId;
285
        }
286
287
        $sql = "SELECT id, name, access_url_id
288
                FROM $tbl_session u
289
                INNER JOIN $table_url_rel_session
290
                ON $table_url_rel_session.session_id = id
291
                $where
292
                ORDER BY name, id";
293
294
        $result = Database::query($sql);
295
        $sessions = Database::store_result($result);
296
297
        return $sessions;
298
    }
299
300
    /**
301
     * Gets the inner join of access_url and the usergroup table.
302
     *
303
     * @author Julio Montoya
304
     *
305
     * @param int $urlId
306
     *
307
     * @return array Database::store_result of the result
308
     */
309
    public static function get_url_rel_usergroup_data($urlId = 0)
310
    {
311
        $where = '';
312
        $table_url_rel_usergroup = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
313
        $table_user_group = Database::get_main_table(TABLE_USERGROUP);
314
315
        $urlId = (int) $urlId;
316
        if (!empty($urlId)) {
317
            $where = " WHERE $table_url_rel_usergroup.access_url_id = ".$urlId;
318
        }
319
320
        $sql = "SELECT u.id, u.title, access_url_id
321
                FROM $table_user_group u
322
                INNER JOIN $table_url_rel_usergroup
323
                ON $table_url_rel_usergroup.usergroup_id = u.id
324
                $where
325
                ORDER BY u.title";
326
327
        $result = Database::query($sql);
328
        $courses = Database::store_result($result);
329
330
        return $courses;
331
    }
332
333
    /**
334
     * Gets the inner join of access_url and the usergroup table.
335
     *
336
     * @author Julio Montoya
337
     *
338
     * @param int $urlId
339
     *
340
     * @return array Database::store_result of the result
341
     */
342
    public static function getUrlRelCourseCategory($urlId = 0)
343
    {
344
        $table_url_rel = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
345
        $table = Database::get_main_table(TABLE_MAIN_CATEGORY);
346
        $where = ' WHERE 1=1 ';
347
348
        $urlId = (int) $urlId;
349
        if (!empty($urlId)) {
350
            $where .= " AND $table_url_rel.access_url_id = ".$urlId;
351
        }
352
        $where .= ' AND (parent_id IS NULL) ';
353
354
        $sql = "SELECT u.id, u.title, access_url_id
355
                FROM $table u
356
                INNER JOIN $table_url_rel
357
                ON $table_url_rel.course_category_id = u.id
358
                $where
359
                ORDER BY u.title";
360
361
        $result = Database::query($sql);
362
        $courses = Database::store_result($result, 'ASSOC');
363
364
        return $courses;
365
    }
366
367
    /**
368
     * Sets the status of an URL 1 or 0.
369
     *
370
     * @author Julio Montoya
371
     *
372
     * @param string $status lock || unlock
373
     * @param int url id
374
     * */
375
    public static function set_url_status($status, $urlId)
376
    {
377
        $url_table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
378
        if ('lock' == $status) {
379
            $status_db = '0';
380
        }
381
        if ('unlock' == $status) {
382
            $status_db = '1';
383
        }
384
        if (('1' == $status_db || '0' == $status_db) && is_numeric($urlId)) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $status_db does not seem to be defined for all execution paths leading up to this point.
Loading history...
385
            $sql = "UPDATE $url_table SET active='".intval($status_db)."'
386
                    WHERE id='".intval($urlId)."'";
387
            Database::query($sql);
388
        }
389
    }
390
391
    /**
392
     * Checks the relationship between an URL and a User (return the num_rows).
393
     *
394
     * @author Julio Montoya
395
     *
396
     * @param int user id
397
     * @param int url id
398
     *
399
     * @return bool true if success
400
     * */
401
    public static function relation_url_user_exist($user_id, $urlId)
402
    {
403
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
404
        $sql = "SELECT user_id FROM $table
405
               WHERE access_url_id = ".intval($urlId)." AND user_id = ".intval($user_id)." ";
406
        $result = Database::query($sql);
407
        $num = Database::num_rows($result);
408
409
        return $num;
410
    }
411
412
    /**
413
     * Checks the relationship between an URL and a Course (return the num_rows).
414
     *
415
     * @author Julio Montoya
416
     *
417
     * @param int $courseId
418
     * @param int $urlId
419
     *
420
     * @return bool true if success
421
     * */
422
    public static function relation_url_course_exist($courseId, $urlId)
423
    {
424
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
425
        $sql = "SELECT c_id FROM $table
426
               WHERE
427
                    access_url_id = ".intval($urlId)." AND
428
                    c_id = '".intval($courseId)."'";
429
        $result = Database::query($sql);
430
        $num = Database::num_rows($result);
431
432
        return $num;
433
    }
434
435
    /**
436
     * Checks the relationship between an URL and a UserGr
437
     * oup (return the num_rows).
438
     *
439
     * @author Julio Montoya
440
     *
441
     * @param int $userGroupId
442
     * @param int $urlId
443
     *
444
     * @return bool true if success
445
     * */
446
    public static function relationUrlUsergroupExist($userGroupId, $urlId)
447
    {
448
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
449
        $sql = "SELECT usergroup_id FROM $table
450
               WHERE
451
                    access_url_id = ".intval($urlId)." AND
452
                    usergroup_id = ".intval($userGroupId);
453
        $result = Database::query($sql);
454
        $num = Database::num_rows($result);
455
456
        return $num;
457
    }
458
459
    /**
460
     * Checks the relationship between an URL and a Session (return the num_rows).
461
     *
462
     * @author Julio Montoya
463
     *
464
     * @param int $sessionId
465
     * @param int $urlId
466
     *
467
     * @return bool true if success
468
     * */
469
    public static function relation_url_session_exist($sessionId, $urlId)
470
    {
471
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
472
        $sessionId = (int) $sessionId;
473
        $urlId = (int) $urlId;
474
        $sql = "SELECT session_id FROM $table
475
                WHERE
476
                    access_url_id = $urlId AND
477
                    session_id = $sessionId ";
478
        $result = Database::query($sql);
479
        $num = Database::num_rows($result);
480
481
        return $num;
482
    }
483
484
    /**
485
     * Add a group of users into a group of URLs.
486
     *
487
     * @author Julio Montoya
488
     *
489
     * @param  array of user_ids
490
     * @param  array of url_ids
491
     *
492
     * @return array
493
     *
494
     * @throws Exception
495
     */
496
    public static function add_users_to_urls($user_list, $url_list): array
497
    {
498
        $result_array = [];
499
500
        if (is_array($user_list) && is_array($url_list)) {
501
            foreach ($url_list as $urlId) {
502
                foreach ($user_list as $user_id) {
503
                    $result = self::add_user_to_url($user_id, $urlId, true);
504
505
                    if ($result) {
506
                        $result_array[$urlId][$user_id] = 1;
507
                    } else {
508
                        $result_array[$urlId][$user_id] = 0;
509
                    }
510
                }
511
            }
512
513
            Database::getManager()->flush();
514
515
            return $result_array;
516
        }
517
518
        return [];
519
    }
520
521
    public static function remove_users_from_urls(array $userIds, array $urlIds): void
522
    {
523
        if (empty($userIds) || empty($urlIds)) {
524
            return;
525
        }
526
527
        $conn = Database::getManager()->getConnection();
528
        $placeholdersUsers = implode(',', array_fill(0, count($userIds), '?'));
529
        $placeholdersUrls = implode(',', array_fill(0, count($urlIds), '?'));
530
531
        $sql = "DELETE FROM access_url_rel_user
532
            WHERE user_id IN ($placeholdersUsers)
533
            AND access_url_id IN ($placeholdersUrls)";
534
535
        $conn->executeQuery($sql, array_merge($userIds, $urlIds));
536
    }
537
538
    /**
539
     * Add a group of courses into a group of URLs.
540
     *
541
     * @author Julio Montoya
542
     *
543
     * @param array $course_list of course ids
544
     * @param array $url_list    of url_ids
545
     *
546
     * @return array
547
     */
548
    public static function add_courses_to_urls($course_list, $url_list)
549
    {
550
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
551
        $result_array = [];
552
553
        if (is_array($course_list) && is_array($url_list)) {
554
            foreach ($url_list as $urlId) {
555
                foreach ($course_list as $course_code) {
556
                    $courseInfo = api_get_course_info($course_code);
557
                    $courseId = $courseInfo['real_id'];
558
559
                    $count = self::relation_url_course_exist($courseId, $urlId);
560
                    if (0 == $count) {
561
                        $sql = "INSERT INTO $table
562
                                SET c_id = '".$courseId."', access_url_id = ".intval($urlId);
563
                        $result = Database::query($sql);
564
                        if ($result) {
565
                            $result_array[$urlId][$course_code] = 1;
566
                        } else {
567
                            $result_array[$urlId][$course_code] = 0;
568
                        }
569
                    }
570
                }
571
            }
572
        }
573
574
        return $result_array;
575
    }
576
577
    /**
578
     * Add a group of user group into a group of URLs.
579
     *
580
     * @author Julio Montoya
581
     *
582
     * @param array $userGroupList of course ids
583
     * @param array $urlList       of url_ids
584
     *
585
     * @return array
586
     */
587
    public static function addUserGroupListToUrl($userGroupList, $urlList)
588
    {
589
        $resultArray = [];
590
        if (is_array($userGroupList) && is_array($urlList)) {
591
            foreach ($urlList as $urlId) {
592
                foreach ($userGroupList as $userGroupId) {
593
                    $count = self::relationUrlUsergroupExist(
594
                        $userGroupId,
595
                        $urlId
596
                    );
597
                    if (0 == $count) {
598
                        $result = self::addUserGroupToUrl($userGroupId, $urlId);
599
                        if ($result) {
600
                            $resultArray[$urlId][$userGroupId] = 1;
601
                        } else {
602
                            $resultArray[$urlId][$userGroupId] = 0;
603
                        }
604
                    }
605
                }
606
            }
607
        }
608
609
        return $resultArray;
610
    }
611
612
    /**
613
     * Remove a list of user groups from a list of URLs.
614
     *
615
     * @param array $userGroupList List of user group IDs
616
     * @param array $urlList       List of access_url IDs
617
     *
618
     * @return void
619
     */
620
    public static function removeUserGroupListFromUrl(array $userGroupList, array $urlList): void
621
    {
622
        if (empty($userGroupList) || empty($urlList)) {
623
            return;
624
        }
625
626
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
627
628
        $placeholdersGroups = implode(',', array_fill(0, count($userGroupList), '?'));
629
        $placeholdersUrls = implode(',', array_fill(0, count($urlList), '?'));
630
631
        $sql = "DELETE FROM $table
632
            WHERE usergroup_id IN ($placeholdersGroups)
633
            AND access_url_id IN ($placeholdersUrls)";
634
635
        $params = array_merge($userGroupList, $urlList);
636
        Database::getManager()->getConnection()->executeQuery($sql, $params);
637
    }
638
639
    /**
640
     * Add a group of user group into a group of URLs.
641
     *
642
     * @author Julio Montoya
643
     *
644
     * @param  array of course ids
645
     * @param  array of url_ids
646
     *
647
     * @return array
648
     */
649
    public static function addCourseCategoryListToUrl($courseCategoryList, $urlList)
650
    {
651
        $resultArray = [];
652
        if (is_array($courseCategoryList) && is_array($urlList)) {
653
            foreach ($urlList as $urlId) {
654
                foreach ($courseCategoryList as $categoryCourseId) {
655
                    $count = self::relationUrlCourseCategoryExist($categoryCourseId, $urlId);
656
                    if (0 == $count) {
657
                        $result = self::addCourseCategoryToUrl($categoryCourseId, $urlId);
658
                        if ($result) {
659
                            $resultArray[$urlId][$categoryCourseId] = 1;
660
                        } else {
661
                            $resultArray[$urlId][$categoryCourseId] = 0;
662
                        }
663
                    }
664
                }
665
            }
666
        }
667
668
        return $resultArray;
669
    }
670
671
    /**
672
     * Checks the relationship between an URL and a UserGr
673
     * oup (return the num_rows).
674
     *
675
     * @author Julio Montoya
676
     *
677
     * @param int $categoryCourseId
678
     * @param int $urlId
679
     *
680
     * @return bool true if success
681
     * */
682
    public static function relationUrlCourseCategoryExist($categoryCourseId, $urlId)
683
    {
684
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
685
        $sql = "SELECT course_category_id FROM $table
686
                WHERE
687
                    access_url_id = ".intval($urlId)." AND
688
                    course_category_id = ".intval($categoryCourseId);
689
        $result = Database::query($sql);
690
        $num = Database::num_rows($result);
691
692
        return $num;
693
    }
694
695
    /**
696
     * @param int $userGroupId
697
     * @param int $urlId
698
     *
699
     * @return int
700
     */
701
    public static function addUserGroupToUrl($userGroupId, $urlId)
702
    {
703
        $urlRelUserGroupTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
704
        $sql = "INSERT INTO $urlRelUserGroupTable
705
                SET
706
                usergroup_id = '".intval($userGroupId)."',
707
                access_url_id = ".intval($urlId);
708
        Database::query($sql);
709
710
        return Database::insert_id();
711
    }
712
713
    /**
714
     * @param int $categoryId
715
     * @param int $urlId
716
     *
717
     * @return int
718
     */
719
    public static function addCourseCategoryToUrl($categoryId, $urlId)
720
    {
721
        $exists = self::relationUrlCourseCategoryExist($categoryId, $urlId);
722
        if (empty($exists)) {
723
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
724
725
            $sql = "INSERT INTO $table
726
                    SET
727
                    course_category_id = '".intval($categoryId)."',
728
                    access_url_id = ".intval($urlId);
729
            Database::query($sql);
730
731
            return Database::insert_id();
732
        }
733
734
        return 0;
735
    }
736
737
    /**
738
     * Add a group of sessions into a group of URLs.
739
     *
740
     * @author Julio Montoya
741
     *
742
     * @param array $session_list of session ids
743
     * @param array $url_list     of url_ids
744
     *
745
     * @return array
746
     * */
747
    public static function add_sessions_to_urls($session_list, $url_list)
748
    {
749
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
750
        $result_array = [];
751
752
        if (is_array($session_list) && is_array($url_list)) {
753
            foreach ($url_list as $urlId) {
754
                foreach ($session_list as $session_id) {
755
                    $count = self::relation_url_session_exist($session_id, $urlId);
756
757
                    if (0 == $count) {
758
                        $sql = "INSERT INTO $table
759
                                SET
760
                                session_id = ".intval($session_id).",
761
                                access_url_id = ".intval($urlId);
762
                        $result = Database::query($sql);
763
                        if ($result) {
764
                            $result_array[$urlId][$session_id] = 1;
765
                        } else {
766
                            $result_array[$urlId][$session_id] = 0;
767
                        }
768
                    }
769
                }
770
            }
771
        }
772
773
        return $result_array;
774
    }
775
776
    /**
777
     * Add a user into a url.
778
     *
779
     * @author Julio Montoya
780
     *
781
     * @param int $user_id
782
     * @param int $urlId
783
     *
784
     * @return bool true if success
785
     *
786
     * @throws Exception
787
     */
788
    public static function add_user_to_url($user_id, $urlId = 1, bool $addAuthSource = false)
789
    {
790
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
791
        if (empty($urlId)) {
792
            $urlId = 1;
793
        }
794
        $count = self::relation_url_user_exist($user_id, $urlId);
795
        $result = true;
796
        if (empty($count)) {
797
            $sql = "INSERT INTO $table (user_id, access_url_id)
798
                    VALUES ('".intval($user_id)."', '".intval($urlId)."') ";
799
            $result = Database::query($sql);
800
        }
801
802
        if ($addAuthSource && $result) {
803
            /** @var AccessUrl|null $accessUrl */
804
            $accessUrl = Container::getAccessUrlRepository()->find($urlId);
805
            $user = api_get_user_entity($user_id);
806
807
            $authSources = $user->getAuthSourcesByUrl($accessUrl);
808
809
            if ($authSources->count() <= 0) {
810
                $firstAuthSource = $user->getAuthSources()->first();
811
812
                if ($firstAuthSource) {
813
                    $user->addAuthSourceByAuthentication(
814
                        $firstAuthSource->getAuthentication(),
815
                        $accessUrl
816
                    );
817
818
                    Database::getManager()->flush();
819
                }
820
            }
821
        }
822
823
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type Doctrine\DBAL\Result which is incompatible with the documented return type boolean.
Loading history...
824
    }
825
826
    /**
827
     * @param int $courseId
828
     * @param int $urlId
829
     *
830
     * @return resource
831
     */
832
    public static function add_course_to_url($courseId, $urlId = 1)
833
    {
834
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
835
        if (empty($urlId)) {
836
            $urlId = 1;
837
        }
838
        $count = self::relation_url_course_exist($courseId, $urlId);
839
        if (empty($count)) {
840
            $sql = "INSERT INTO $table
841
                    SET c_id = ".intval($courseId).", access_url_id = ".intval($urlId);
842
            Database::query($sql);
843
        }
844
845
        return true;
846
    }
847
848
    /**
849
     * Inserts a session to a URL (access_url_rel_session table).
850
     *
851
     * @param int $session_id Session ID
852
     * @param   int     URL ID
853
     *
854
     * @return bool True on success, false session already exists or insert failed
855
     */
856
    public static function add_session_to_url($session_id, $urlId = 1)
857
    {
858
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
859
        $session_id = (int) $session_id;
860
        $urlId = (int) $urlId;
861
862
        if (empty($urlId)) {
863
            $urlId = 1;
864
        }
865
        $result = false;
866
        $count = self::relation_url_session_exist($session_id, $urlId);
867
        if (empty($count) && !empty($session_id)) {
868
            $sql = "INSERT INTO $table
869
                    SET session_id = ".$session_id.", access_url_id = ".$urlId;
870
            try {
871
                Database::query($sql);
872
            } catch (Exception $e) {
873
                return false;
874
            }
875
876
            return true;
877
        }
878
879
        return $result;
880
    }
881
882
    /**
883
     * Deletes an url and user relationship.
884
     *
885
     * @author Julio Montoya
886
     *
887
     * @param int user id
888
     * @param int url id
889
     *
890
     * @return bool true if success
891
     * */
892
    public static function delete_url_rel_user($user_id, $urlId)
893
    {
894
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
895
        $result = true;
896
        if (!empty($user_id) && !empty($urlId)) {
897
            $sql = "DELETE FROM $table
898
                   WHERE
899
                        user_id = ".intval($user_id)." AND
900
                        access_url_id = ".intval($urlId);
901
            $result = Database::query($sql);
902
        }
903
904
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type Doctrine\DBAL\Result which is incompatible with the documented return type boolean.
Loading history...
905
    }
906
907
    /**
908
     * Deletes user from all portals.
909
     *
910
     * @author Julio Montoya
911
     *
912
     * @param int user id
913
     *
914
     * @return bool true if success
915
     * */
916
    public static function deleteUserFromAllUrls($userId)
917
    {
918
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
919
        $result = true;
920
        if (!empty($userId)) {
921
            $sql = "DELETE FROM $table
922
                   WHERE user_id = ".intval($userId);
923
            Database::query($sql);
924
        }
925
926
        return $result;
927
    }
928
929
    /**
930
     * Deletes an url and course relationship.
931
     *
932
     * @author Julio Montoya
933
     *
934
     * @param int $courseId
935
     * @param int $urlId
936
     *
937
     * @return bool true if success
938
     * */
939
    public static function delete_url_rel_course($courseId, $urlId)
940
    {
941
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
942
        $sql = "DELETE FROM $table
943
               WHERE c_id = '".intval($courseId)."' AND access_url_id=".intval($urlId)."  ";
944
        $result = Database::query($sql);
945
946
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type Doctrine\DBAL\Result which is incompatible with the documented return type boolean.
Loading history...
947
    }
948
949
    /**
950
     * Deletes an url and $userGroup relationship.
951
     *
952
     * @author Julio Montoya
953
     *
954
     * @param int $userGroupId
955
     * @param int $urlId
956
     *
957
     * @return bool true if success
958
     * */
959
    public static function delete_url_rel_usergroup($userGroupId, $urlId)
960
    {
961
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
962
        $sql = "DELETE FROM $table
963
                WHERE usergroup_id = '".intval($userGroupId)."' AND
964
                     access_url_id = ".intval($urlId);
965
        $result = Database::query($sql);
966
967
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type Doctrine\DBAL\Result which is incompatible with the documented return type boolean.
Loading history...
968
    }
969
970
    /**
971
     * Deletes an url and $userGroup relationship.
972
     *
973
     * @author Julio Montoya
974
     *
975
     * @param int $userGroupId
976
     * @param int $urlId
977
     *
978
     * @return bool true if success
979
     * */
980
    public static function deleteUrlRelCourseCategory($userGroupId, $urlId)
981
    {
982
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
983
        $sql = "DELETE FROM $table
984
                WHERE
985
                    course_category_id = '".intval($userGroupId)."' AND
986
                    access_url_id=".intval($urlId)."  ";
987
        $result = Database::query($sql);
988
989
        return $result;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $result also could return the type Doctrine\DBAL\Result which is incompatible with the documented return type boolean.
Loading history...
990
    }
991
992
    /**
993
     * Deletes an url and session relationship.
994
     *
995
     * @author Julio Montoya
996
     *
997
     * @param int $session_id
998
     * @param int $urlId
999
     *
1000
     * @return bool true if success
1001
     * */
1002
    public static function delete_url_rel_session($session_id, $urlId)
1003
    {
1004
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1005
        $sql = "DELETE FROM $table
1006
                WHERE
1007
                    session_id = ".intval($session_id)." AND
1008
                    access_url_id=".intval($urlId)."  ";
1009
        $result = Database::query($sql, 'ASSOC');
1010
1011
        return $result;
1012
    }
1013
1014
    /**
1015
     * Updates the access_url_rel_user table  with a given user list.
1016
     *
1017
     * @author Julio Montoya
1018
     *
1019
     * @param array $user_list
1020
     * @param int   $urlId
1021
     *
1022
     * @return bool|array
1023
     */
1024
    public static function update_urls_rel_user($user_list, $urlId, bool $updateAuthSource = false)
1025
    {
1026
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
1027
        $urlId = (int) $urlId;
1028
1029
        $sql = "SELECT user_id
1030
                FROM $table
1031
                WHERE access_url_id = $urlId";
1032
        $result = Database::query($sql);
1033
        $existing_users = [];
1034
1035
        // Getting all users
1036
        while ($row = Database::fetch_array($result)) {
1037
            $existing_users[] = $row['user_id'];
1038
        }
1039
1040
        // Adding users
1041
        $users_added = [];
1042
        foreach ($user_list as $user_id_to_add) {
1043
            if (!in_array($user_id_to_add, $existing_users)) {
1044
                $result = self::add_user_to_url($user_id_to_add, $urlId, $updateAuthSource);
1045
                if ($result) {
1046
                    $users_added[] = $user_id_to_add;
1047
                }
1048
            }
1049
        }
1050
1051
        $users_deleted = [];
1052
        // Deleting old users
1053
        foreach ($existing_users as $user_id_to_delete) {
1054
            if (!in_array($user_id_to_delete, $user_list)) {
1055
                $result = self::delete_url_rel_user($user_id_to_delete, $urlId);
1056
                if ($result) {
1057
                    $users_deleted[] = $user_id_to_delete;
1058
                }
1059
            }
1060
        }
1061
1062
        if (empty($users_added) && empty($users_deleted)) {
1063
            return false;
1064
        }
1065
1066
        return [
1067
            'users_added' => $users_added,
1068
            'users_deleted' => $users_deleted,
1069
        ];
1070
    }
1071
1072
    /**
1073
     * Updates the access_url_rel_course table  with a given user list.
1074
     *
1075
     * @author Julio Montoya
1076
     *
1077
     * @param array $course_list
1078
     * @param int   $urlId
1079
     * */
1080
    public static function update_urls_rel_course($course_list, $urlId)
1081
    {
1082
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
1083
1084
        $sql = "SELECT c_id FROM $table
1085
                WHERE access_url_id = ".intval($urlId);
1086
        $result = Database::query($sql);
1087
1088
        $existing_courses = [];
1089
        while ($row = Database::fetch_array($result)) {
1090
            $existing_courses[] = $row['c_id'];
1091
        }
1092
1093
        // Adding courses
1094
        foreach ($course_list as $courseId) {
1095
            self::add_course_to_url($courseId, $urlId);
1096
            CourseManager::update_course_ranking($courseId);
1097
        }
1098
1099
        // Deleting old courses
1100
        foreach ($existing_courses as $courseId) {
1101
            if (!in_array($courseId, $course_list)) {
1102
                self::delete_url_rel_course($courseId, $urlId);
1103
                CourseManager::update_course_ranking($courseId);
1104
            }
1105
        }
1106
    }
1107
1108
    /**
1109
     * Updates the access_url_rel_course table  with a given user list.
1110
     *
1111
     * @author Julio Montoya
1112
     *
1113
     * @param array $userGroupList user list
1114
     * @param int   $urlId
1115
     * */
1116
    public static function update_urls_rel_usergroup(array $userGroupList, int $urlId): void
1117
    {
1118
        if ($urlId <= 0) {
1119
            return;
1120
        }
1121
1122
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
1123
1124
        if (!is_array($userGroupList) || empty($userGroupList)) {
1125
            return;
1126
        }
1127
1128
        $sql = "SELECT usergroup_id FROM $table WHERE access_url_id = ".intval($urlId);
1129
        $result = Database::query($sql);
1130
1131
        $existingItems = array_map(
1132
            fn ($row) => $row['usergroup_id'],
1133
            Database::store_result($result)
1134
        );
1135
1136
        foreach ($userGroupList as $userGroupId) {
1137
            if (!in_array($userGroupId, $existingItems)) {
1138
                self::addUserGroupToUrl($userGroupId, $urlId);
1139
            }
1140
        }
1141
1142
        foreach ($existingItems as $userGroupId) {
1143
            if (!in_array($userGroupId, $userGroupList)) {
1144
                self::delete_url_rel_usergroup($userGroupId, $urlId);
1145
            }
1146
        }
1147
    }
1148
1149
    /**
1150
     * Updates the access_url_rel_course_category table with a given list.
1151
     *
1152
     * @author Julio Montoya
1153
     *
1154
     * @param array $list  course category list
1155
     * @param int   $urlId access_url_id
1156
     */
1157
    public static function updateUrlRelCourseCategory($list, $urlId)
1158
    {
1159
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
1160
        $sql = "SELECT course_category_id
1161
                FROM $table
1162
                WHERE access_url_id = ".intval($urlId);
1163
        $result = Database::query($sql);
1164
        $existingItems = [];
1165
1166
        while ($row = Database::fetch_array($result)) {
1167
            $existingItems[] = $row['course_category_id'];
1168
        }
1169
1170
        // Adding
1171
        foreach ($list as $id) {
1172
            self::addCourseCategoryToUrl($id, $urlId);
1173
            $categoryInfo = CourseCategory::getCategoryById($id);
1174
            $children = CourseCategory::getChildren($categoryInfo['code']);
1175
            if (!empty($children)) {
1176
                foreach ($children as $category) {
1177
                    self::addCourseCategoryToUrl($category['id'], $urlId);
1178
                }
1179
            }
1180
        }
1181
1182
        // Deleting old items
1183
        foreach ($existingItems as $id) {
1184
            if (!in_array($id, $list)) {
1185
                self::deleteUrlRelCourseCategory($id, $urlId);
1186
                $categoryInfo = CourseCategory::getCategoryById($id);
1187
1188
                $children = CourseCategory::getChildren($categoryInfo['code']);
1189
                if (!empty($children)) {
1190
                    foreach ($children as $category) {
1191
                        self::deleteUrlRelCourseCategory($category['id'], $urlId);
1192
                    }
1193
                }
1194
            }
1195
        }
1196
    }
1197
1198
    /**
1199
     * Updates the access_url_rel_session table with a given user list.
1200
     *
1201
     * @author Julio Montoya
1202
     *
1203
     * @param array $session_list
1204
     * @param int   $urlId
1205
     * */
1206
    public static function update_urls_rel_session($session_list, $urlId)
1207
    {
1208
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1209
1210
        $sql = "SELECT session_id FROM $table
1211
                WHERE access_url_id=".intval($urlId);
1212
        $result = Database::query($sql);
1213
        $existing_sessions = [];
1214
1215
        while ($row = Database::fetch_array($result)) {
1216
            $existing_sessions[] = $row['session_id'];
1217
        }
1218
1219
        // Adding users
1220
        foreach ($session_list as $session) {
1221
            if (!in_array($session, $existing_sessions)) {
1222
                if (!empty($session) && !empty($urlId)) {
1223
                    self::add_session_to_url($session, $urlId);
1224
                }
1225
            }
1226
        }
1227
1228
        // Deleting old users
1229
        foreach ($existing_sessions as $existing_session) {
1230
            if (!in_array($existing_session, $session_list)) {
1231
                if (!empty($existing_session) && !empty($urlId)) {
1232
                    self::delete_url_rel_session(
1233
                        $existing_session,
1234
                        $urlId
1235
                    );
1236
                }
1237
            }
1238
        }
1239
    }
1240
1241
    /**
1242
     * @param int $user_id
1243
     *
1244
     * @return array
1245
     */
1246
    public static function get_access_url_from_user($user_id)
1247
    {
1248
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
1249
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1250
        $sql = "SELECT url, access_url_id
1251
                FROM $table url_rel_user
1252
                INNER JOIN $table_url u
1253
                ON (url_rel_user.access_url_id = u.id)
1254
                WHERE user_id = ".intval($user_id);
1255
        $result = Database::query($sql);
1256
1257
        return Database::store_result($result, 'ASSOC');
1258
    }
1259
1260
    /**
1261
     * @param int $courseId
1262
     *
1263
     * @return array
1264
     */
1265
    public static function get_access_url_from_course($courseId)
1266
    {
1267
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
1268
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1269
        $courseId = (int) $courseId;
1270
        $sql = "SELECT url, access_url_id FROM $table c
1271
                INNER JOIN $table_url u
1272
                ON (c.access_url_id = u.id)
1273
                WHERE c_id = $courseId";
1274
1275
        $result = Database::query($sql);
1276
1277
        return Database::store_result($result, 'ASSOC');
1278
    }
1279
1280
    public static function getCountAccessUrlFromCourse($courseId)
1281
    {
1282
        $courseId = (int) $courseId;
1283
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
1284
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1285
        $sql = "SELECT count(u.id) count FROM $table c
1286
                INNER JOIN $table_url u
1287
                ON (c.access_url_id = u.id)
1288
                WHERE c_id = $courseId ";
1289
1290
        $result = Database::query($sql);
1291
        if ($result) {
1292
            $row = Database::fetch_assoc($result);
1293
1294
            return (int) $row['count'];
1295
        }
1296
1297
        return 0;
1298
    }
1299
1300
    /**
1301
     * @param $sessionId
1302
     *
1303
     * @return array
1304
     */
1305
    public static function get_access_url_from_session($sessionId)
1306
    {
1307
        $table_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1308
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1309
        $sql = "SELECT url, access_url_id
1310
                FROM $table_url_rel_session url_rel_session
1311
                INNER JOIN $table_url u
1312
                ON (url_rel_session.access_url_id = u.id)
1313
                WHERE session_id = ".intval($sessionId);
1314
        $result = Database::query($sql);
1315
        $url_list = Database::store_result($result);
1316
1317
        return $url_list;
1318
    }
1319
1320
    /**
1321
     * @param string $url
1322
     *
1323
     * @return bool|mixed|null
1324
     */
1325
    public static function get_url_id($url)
1326
    {
1327
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1328
        $sql = "SELECT id FROM $table
1329
                WHERE url = '".Database::escape_string($url)."'";
1330
        $result = Database::query($sql);
1331
        $urlId = Database::result($result, 0, 0);
1332
1333
        return $urlId;
1334
    }
1335
1336
    /**
1337
     * @param string $needle
1338
     *
1339
     * @return XajaxResponse
1340
     */
1341
    public static function searchCourseCategoryAjax($needle)
1342
    {
1343
        $response = new xajaxResponse();
1344
        $return = '';
1345
1346
        if (!empty($needle)) {
1347
            // xajax send utf8 datas... datas in db can be non-utf8 datas
1348
            $charset = api_get_system_encoding();
1349
            $needle = api_convert_encoding($needle, $charset, 'utf-8');
1350
            $needle = Database::escape_string($needle);
1351
            // search courses where username or firstname or lastname begins likes $needle
1352
            $sql = 'SELECT id, u.title
1353
                    FROM '.Database::get_main_table(TABLE_MAIN_CATEGORY).' u
1354
                    WHERE
1355
                        u.title LIKE "'.$needle.'%" AND
1356
                        (parent_id IS NULL or parent_id = 0)
1357
                    ORDER BY u.title
1358
                    LIMIT 11';
1359
            $result = Database::query($sql);
1360
            $i = 0;
1361
            while ($data = Database::fetch_array($result)) {
1362
                $i++;
1363
                if ($i <= 10) {
1364
                    $return .= '<a
1365
                    href="javascript: void(0);"
1366
                    onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['title']).' \')">'.$data['title'].' </a><br />';
1367
                } else {
1368
                    $return .= '...<br />';
1369
                }
1370
            }
1371
        }
1372
1373
        $response->addAssign(
1374
            'ajax_list_courses',
1375
            'innerHTML',
1376
            api_utf8_encode($return)
1377
        );
1378
1379
        return $response;
1380
    }
1381
1382
    public static function remove_courses_from_urls(array $courseCodes, array $urlIds): void
1383
    {
1384
        if (empty($courseCodes) || empty($urlIds)) {
1385
            return;
1386
        }
1387
1388
        $conn = Database::getManager()->getConnection();
1389
        $placeholdersCourses = implode(',', array_fill(0, count($courseCodes), '?'));
1390
        $placeholdersUrls = implode(',', array_fill(0, count($urlIds), '?'));
1391
1392
        $sql = "DELETE FROM access_url_rel_course
1393
            WHERE c_id IN (
1394
                SELECT id FROM course WHERE code IN ($placeholdersCourses)
1395
            )
1396
            AND access_url_id IN ($placeholdersUrls)";
1397
1398
        $conn->executeQuery($sql, array_merge($courseCodes, $urlIds));
1399
    }
1400
1401
    public static function searchCoursesByTitleOrCode(string $needle): array
1402
    {
1403
        $tbl = Database::get_main_table(TABLE_MAIN_COURSE);
1404
        $charset = api_get_system_encoding();
1405
        $needle = api_convert_encoding($needle, $charset, 'utf-8');
1406
        $needle = Database::escape_string($needle);
1407
1408
        $sql = "
1409
        SELECT id, code, title
1410
        FROM $tbl
1411
        WHERE title LIKE '$needle%' OR code LIKE '$needle%'
1412
        ORDER BY title, code
1413
        LIMIT 11
1414
    ";
1415
1416
        return Database::store_result(Database::query($sql));
1417
    }
1418
}
1419