Passed
Push — master ( e9ca2e...c0ef74 )
by Angel Fernando Quiroz
09:12
created

UrlManager::searchCourseCategoryAjax()   A

Complexity

Conditions 4
Paths 2

Size

Total Lines 39
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 23
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 39
rs 9.552
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
    public static function add_users_to_urls($user_list, $url_list)
495
    {
496
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
497
        $result_array = [];
498
499
        if (is_array($user_list) && is_array($url_list)) {
500
            foreach ($url_list as $urlId) {
501
                foreach ($user_list as $user_id) {
502
                    $count = self::relation_url_user_exist($user_id, $urlId);
503
                    if (0 == $count) {
504
                        $sql = "INSERT INTO $table
505
                                SET
506
                                    user_id = ".intval($user_id).",
507
                                    access_url_id = ".intval($urlId);
508
                        $result = Database::query($sql);
509
                        if ($result) {
510
                            $result_array[$urlId][$user_id] = 1;
511
                        } else {
512
                            $result_array[$urlId][$user_id] = 0;
513
                        }
514
                    }
515
                }
516
            }
517
        }
518
519
        return $result_array;
520
    }
521
522
    public static function remove_users_from_urls(array $userIds, array $urlIds): void
523
    {
524
        if (empty($userIds) || empty($urlIds)) {
525
            return;
526
        }
527
528
        $conn = Database::getManager()->getConnection();
529
        $placeholdersUsers = implode(',', array_fill(0, count($userIds), '?'));
530
        $placeholdersUrls = implode(',', array_fill(0, count($urlIds), '?'));
531
532
        $sql = "DELETE FROM access_url_rel_user
533
            WHERE user_id IN ($placeholdersUsers)
534
            AND access_url_id IN ($placeholdersUrls)";
535
536
        $conn->executeQuery($sql, array_merge($userIds, $urlIds));
537
    }
538
539
    /**
540
     * Add a group of courses into a group of URLs.
541
     *
542
     * @author Julio Montoya
543
     *
544
     * @param array $course_list of course ids
545
     * @param array $url_list    of url_ids
546
     *
547
     * @return array
548
     */
549
    public static function add_courses_to_urls($course_list, $url_list)
550
    {
551
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
552
        $result_array = [];
553
554
        if (is_array($course_list) && is_array($url_list)) {
555
            foreach ($url_list as $urlId) {
556
                foreach ($course_list as $course_code) {
557
                    $courseInfo = api_get_course_info($course_code);
558
                    $courseId = $courseInfo['real_id'];
559
560
                    $count = self::relation_url_course_exist($courseId, $urlId);
561
                    if (0 == $count) {
562
                        $sql = "INSERT INTO $table
563
                                SET c_id = '".$courseId."', access_url_id = ".intval($urlId);
564
                        $result = Database::query($sql);
565
                        if ($result) {
566
                            $result_array[$urlId][$course_code] = 1;
567
                        } else {
568
                            $result_array[$urlId][$course_code] = 0;
569
                        }
570
                    }
571
                }
572
            }
573
        }
574
575
        return $result_array;
576
    }
577
578
    /**
579
     * Add a group of user group into a group of URLs.
580
     *
581
     * @author Julio Montoya
582
     *
583
     * @param array $userGroupList of course ids
584
     * @param array $urlList       of url_ids
585
     *
586
     * @return array
587
     */
588
    public static function addUserGroupListToUrl($userGroupList, $urlList)
589
    {
590
        $resultArray = [];
591
        if (is_array($userGroupList) && is_array($urlList)) {
592
            foreach ($urlList as $urlId) {
593
                foreach ($userGroupList as $userGroupId) {
594
                    $count = self::relationUrlUsergroupExist(
595
                        $userGroupId,
596
                        $urlId
597
                    );
598
                    if (0 == $count) {
599
                        $result = self::addUserGroupToUrl($userGroupId, $urlId);
600
                        if ($result) {
601
                            $resultArray[$urlId][$userGroupId] = 1;
602
                        } else {
603
                            $resultArray[$urlId][$userGroupId] = 0;
604
                        }
605
                    }
606
                }
607
            }
608
        }
609
610
        return $resultArray;
611
    }
612
613
    /**
614
     * Remove a list of user groups from a list of URLs.
615
     *
616
     * @param array $userGroupList List of user group IDs
617
     * @param array $urlList       List of access_url IDs
618
     *
619
     * @return void
620
     */
621
    public static function removeUserGroupListFromUrl(array $userGroupList, array $urlList): void
622
    {
623
        if (empty($userGroupList) || empty($urlList)) {
624
            return;
625
        }
626
627
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
628
629
        $placeholdersGroups = implode(',', array_fill(0, count($userGroupList), '?'));
630
        $placeholdersUrls = implode(',', array_fill(0, count($urlList), '?'));
631
632
        $sql = "DELETE FROM $table
633
            WHERE usergroup_id IN ($placeholdersGroups)
634
            AND access_url_id IN ($placeholdersUrls)";
635
636
        $params = array_merge($userGroupList, $urlList);
637
        Database::getManager()->getConnection()->executeQuery($sql, $params);
638
    }
639
640
    /**
641
     * Add a group of user group into a group of URLs.
642
     *
643
     * @author Julio Montoya
644
     *
645
     * @param  array of course ids
646
     * @param  array of url_ids
647
     *
648
     * @return array
649
     */
650
    public static function addCourseCategoryListToUrl($courseCategoryList, $urlList)
651
    {
652
        $resultArray = [];
653
        if (is_array($courseCategoryList) && is_array($urlList)) {
654
            foreach ($urlList as $urlId) {
655
                foreach ($courseCategoryList as $categoryCourseId) {
656
                    $count = self::relationUrlCourseCategoryExist($categoryCourseId, $urlId);
657
                    if (0 == $count) {
658
                        $result = self::addCourseCategoryToUrl($categoryCourseId, $urlId);
659
                        if ($result) {
660
                            $resultArray[$urlId][$categoryCourseId] = 1;
661
                        } else {
662
                            $resultArray[$urlId][$categoryCourseId] = 0;
663
                        }
664
                    }
665
                }
666
            }
667
        }
668
669
        return $resultArray;
670
    }
671
672
    /**
673
     * Checks the relationship between an URL and a UserGr
674
     * oup (return the num_rows).
675
     *
676
     * @author Julio Montoya
677
     *
678
     * @param int $categoryCourseId
679
     * @param int $urlId
680
     *
681
     * @return bool true if success
682
     * */
683
    public static function relationUrlCourseCategoryExist($categoryCourseId, $urlId)
684
    {
685
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
686
        $sql = "SELECT course_category_id FROM $table
687
                WHERE
688
                    access_url_id = ".intval($urlId)." AND
689
                    course_category_id = ".intval($categoryCourseId);
690
        $result = Database::query($sql);
691
        $num = Database::num_rows($result);
692
693
        return $num;
694
    }
695
696
    /**
697
     * @param int $userGroupId
698
     * @param int $urlId
699
     *
700
     * @return int
701
     */
702
    public static function addUserGroupToUrl($userGroupId, $urlId)
703
    {
704
        $urlRelUserGroupTable = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
705
        $sql = "INSERT INTO $urlRelUserGroupTable
706
                SET
707
                usergroup_id = '".intval($userGroupId)."',
708
                access_url_id = ".intval($urlId);
709
        Database::query($sql);
710
711
        return Database::insert_id();
712
    }
713
714
    /**
715
     * @param int $categoryId
716
     * @param int $urlId
717
     *
718
     * @return int
719
     */
720
    public static function addCourseCategoryToUrl($categoryId, $urlId)
721
    {
722
        $exists = self::relationUrlCourseCategoryExist($categoryId, $urlId);
723
        if (empty($exists)) {
724
            $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
725
726
            $sql = "INSERT INTO $table
727
                    SET
728
                    course_category_id = '".intval($categoryId)."',
729
                    access_url_id = ".intval($urlId);
730
            Database::query($sql);
731
732
            return Database::insert_id();
733
        }
734
735
        return 0;
736
    }
737
738
    /**
739
     * Add a group of sessions into a group of URLs.
740
     *
741
     * @author Julio Montoya
742
     *
743
     * @param array $session_list of session ids
744
     * @param array $url_list     of url_ids
745
     *
746
     * @return array
747
     * */
748
    public static function add_sessions_to_urls($session_list, $url_list)
749
    {
750
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
751
        $result_array = [];
752
753
        if (is_array($session_list) && is_array($url_list)) {
754
            foreach ($url_list as $urlId) {
755
                foreach ($session_list as $session_id) {
756
                    $count = self::relation_url_session_exist($session_id, $urlId);
757
758
                    if (0 == $count) {
759
                        $sql = "INSERT INTO $table
760
                                SET
761
                                session_id = ".intval($session_id).",
762
                                access_url_id = ".intval($urlId);
763
                        $result = Database::query($sql);
764
                        if ($result) {
765
                            $result_array[$urlId][$session_id] = 1;
766
                        } else {
767
                            $result_array[$urlId][$session_id] = 0;
768
                        }
769
                    }
770
                }
771
            }
772
        }
773
774
        return $result_array;
775
    }
776
777
    /**
778
     * Add a user into a url.
779
     *
780
     * @author Julio Montoya
781
     *
782
     * @param int $user_id
783
     * @param int $urlId
784
     *
785
     * @return bool true if success
786
     * */
787
    public static function add_user_to_url($user_id, $urlId = 1)
788
    {
789
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
790
        if (empty($urlId)) {
791
            $urlId = 1;
792
        }
793
        $count = self::relation_url_user_exist($user_id, $urlId);
794
        $result = true;
795
        if (empty($count)) {
796
            $sql = "INSERT INTO $table (user_id, access_url_id)
797
                    VALUES ('".intval($user_id)."', '".intval($urlId)."') ";
798
            $result = Database::query($sql);
799
        }
800
801
        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...
802
    }
803
804
    /**
805
     * @param int $courseId
806
     * @param int $urlId
807
     *
808
     * @return resource
809
     */
810
    public static function add_course_to_url($courseId, $urlId = 1)
811
    {
812
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
813
        if (empty($urlId)) {
814
            $urlId = 1;
815
        }
816
        $count = self::relation_url_course_exist($courseId, $urlId);
817
        if (empty($count)) {
818
            $sql = "INSERT INTO $table
819
                    SET c_id = ".intval($courseId).", access_url_id = ".intval($urlId);
820
            Database::query($sql);
821
        }
822
823
        return true;
824
    }
825
826
    /**
827
     * Inserts a session to a URL (access_url_rel_session table).
828
     *
829
     * @param int $session_id Session ID
830
     * @param   int     URL ID
831
     *
832
     * @return bool True on success, false session already exists or insert failed
833
     */
834
    public static function add_session_to_url($session_id, $urlId = 1)
835
    {
836
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
837
        $session_id = (int) $session_id;
838
        $urlId = (int) $urlId;
839
840
        if (empty($urlId)) {
841
            $urlId = 1;
842
        }
843
        $result = false;
844
        $count = self::relation_url_session_exist($session_id, $urlId);
845
        if (empty($count) && !empty($session_id)) {
846
            $sql = "INSERT INTO $table
847
                    SET session_id = ".$session_id.", access_url_id = ".$urlId;
848
            try {
849
                Database::query($sql);
850
            } catch (Exception $e) {
851
                return false;
852
            }
853
854
            return true;
855
        }
856
857
        return $result;
858
    }
859
860
    /**
861
     * Deletes an url and user relationship.
862
     *
863
     * @author Julio Montoya
864
     *
865
     * @param int user id
866
     * @param int url id
867
     *
868
     * @return bool true if success
869
     * */
870
    public static function delete_url_rel_user($user_id, $urlId)
871
    {
872
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
873
        $result = true;
874
        if (!empty($user_id) && !empty($urlId)) {
875
            $sql = "DELETE FROM $table
876
                   WHERE
877
                        user_id = ".intval($user_id)." AND
878
                        access_url_id = ".intval($urlId);
879
            $result = Database::query($sql);
880
        }
881
882
        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...
883
    }
884
885
    /**
886
     * Deletes user from all portals.
887
     *
888
     * @author Julio Montoya
889
     *
890
     * @param int user id
891
     *
892
     * @return bool true if success
893
     * */
894
    public static function deleteUserFromAllUrls($userId)
895
    {
896
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
897
        $result = true;
898
        if (!empty($userId)) {
899
            $sql = "DELETE FROM $table
900
                   WHERE user_id = ".intval($userId);
901
            Database::query($sql);
902
        }
903
904
        return $result;
905
    }
906
907
    /**
908
     * Deletes an url and course relationship.
909
     *
910
     * @author Julio Montoya
911
     *
912
     * @param int $courseId
913
     * @param int $urlId
914
     *
915
     * @return bool true if success
916
     * */
917
    public static function delete_url_rel_course($courseId, $urlId)
918
    {
919
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
920
        $sql = "DELETE FROM $table
921
               WHERE c_id = '".intval($courseId)."' AND access_url_id=".intval($urlId)."  ";
922
        $result = Database::query($sql);
923
924
        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...
925
    }
926
927
    /**
928
     * Deletes an url and $userGroup relationship.
929
     *
930
     * @author Julio Montoya
931
     *
932
     * @param int $userGroupId
933
     * @param int $urlId
934
     *
935
     * @return bool true if success
936
     * */
937
    public static function delete_url_rel_usergroup($userGroupId, $urlId)
938
    {
939
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
940
        $sql = "DELETE FROM $table
941
                WHERE usergroup_id = '".intval($userGroupId)."' AND
942
                     access_url_id = ".intval($urlId);
943
        $result = Database::query($sql);
944
945
        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...
946
    }
947
948
    /**
949
     * Deletes an url and $userGroup relationship.
950
     *
951
     * @author Julio Montoya
952
     *
953
     * @param int $userGroupId
954
     * @param int $urlId
955
     *
956
     * @return bool true if success
957
     * */
958
    public static function deleteUrlRelCourseCategory($userGroupId, $urlId)
959
    {
960
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
961
        $sql = "DELETE FROM $table
962
                WHERE
963
                    course_category_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 session relationship.
972
     *
973
     * @author Julio Montoya
974
     *
975
     * @param int $session_id
976
     * @param int $urlId
977
     *
978
     * @return bool true if success
979
     * */
980
    public static function delete_url_rel_session($session_id, $urlId)
981
    {
982
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
983
        $sql = "DELETE FROM $table
984
                WHERE
985
                    session_id = ".intval($session_id)." AND
986
                    access_url_id=".intval($urlId)."  ";
987
        $result = Database::query($sql, 'ASSOC');
988
989
        return $result;
990
    }
991
992
    /**
993
     * Updates the access_url_rel_user table  with a given user list.
994
     *
995
     * @author Julio Montoya
996
     *
997
     * @param array $user_list
998
     * @param int   $urlId
999
     *
1000
     * @return bool|array
1001
     */
1002
    public static function update_urls_rel_user($user_list, $urlId)
1003
    {
1004
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
1005
        $urlId = (int) $urlId;
1006
1007
        $sql = "SELECT user_id
1008
                FROM $table
1009
                WHERE access_url_id = $urlId";
1010
        $result = Database::query($sql);
1011
        $existing_users = [];
1012
1013
        // Getting all users
1014
        while ($row = Database::fetch_array($result)) {
1015
            $existing_users[] = $row['user_id'];
1016
        }
1017
1018
        // Adding users
1019
        $users_added = [];
1020
        foreach ($user_list as $user_id_to_add) {
1021
            if (!in_array($user_id_to_add, $existing_users)) {
1022
                $result = self::add_user_to_url($user_id_to_add, $urlId);
1023
                if ($result) {
1024
                    $users_added[] = $user_id_to_add;
1025
                }
1026
            }
1027
        }
1028
1029
        $users_deleted = [];
1030
        // Deleting old users
1031
        foreach ($existing_users as $user_id_to_delete) {
1032
            if (!in_array($user_id_to_delete, $user_list)) {
1033
                $result = self::delete_url_rel_user($user_id_to_delete, $urlId);
1034
                if ($result) {
1035
                    $users_deleted[] = $user_id_to_delete;
1036
                }
1037
            }
1038
        }
1039
1040
        if (empty($users_added) && empty($users_deleted)) {
1041
            return false;
1042
        }
1043
1044
        return [
1045
            'users_added' => $users_added,
1046
            'users_deleted' => $users_deleted,
1047
        ];
1048
    }
1049
1050
    /**
1051
     * Updates the access_url_rel_course table  with a given user list.
1052
     *
1053
     * @author Julio Montoya
1054
     *
1055
     * @param array $course_list
1056
     * @param int   $urlId
1057
     * */
1058
    public static function update_urls_rel_course($course_list, $urlId)
1059
    {
1060
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
1061
1062
        $sql = "SELECT c_id FROM $table
1063
                WHERE access_url_id = ".intval($urlId);
1064
        $result = Database::query($sql);
1065
1066
        $existing_courses = [];
1067
        while ($row = Database::fetch_array($result)) {
1068
            $existing_courses[] = $row['c_id'];
1069
        }
1070
1071
        // Adding courses
1072
        foreach ($course_list as $courseId) {
1073
            self::add_course_to_url($courseId, $urlId);
1074
            CourseManager::update_course_ranking($courseId);
1075
        }
1076
1077
        // Deleting old courses
1078
        foreach ($existing_courses as $courseId) {
1079
            if (!in_array($courseId, $course_list)) {
1080
                self::delete_url_rel_course($courseId, $urlId);
1081
                CourseManager::update_course_ranking($courseId);
1082
            }
1083
        }
1084
    }
1085
1086
    /**
1087
     * Updates the access_url_rel_course table  with a given user list.
1088
     *
1089
     * @author Julio Montoya
1090
     *
1091
     * @param array $userGroupList user list
1092
     * @param int   $urlId
1093
     * */
1094
    public static function update_urls_rel_usergroup(array $userGroupList, int $urlId): void
1095
    {
1096
        if ($urlId <= 0) {
1097
            return;
1098
        }
1099
1100
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USERGROUP);
1101
1102
        if (!is_array($userGroupList) || empty($userGroupList)) {
1103
            return;
1104
        }
1105
1106
        $sql = "SELECT usergroup_id FROM $table WHERE access_url_id = ".intval($urlId);
1107
        $result = Database::query($sql);
1108
1109
        $existingItems = array_map(
1110
            fn ($row) => $row['usergroup_id'],
1111
            Database::store_result($result)
1112
        );
1113
1114
        foreach ($userGroupList as $userGroupId) {
1115
            if (!in_array($userGroupId, $existingItems)) {
1116
                self::addUserGroupToUrl($userGroupId, $urlId);
1117
            }
1118
        }
1119
1120
        foreach ($existingItems as $userGroupId) {
1121
            if (!in_array($userGroupId, $userGroupList)) {
1122
                self::delete_url_rel_usergroup($userGroupId, $urlId);
1123
            }
1124
        }
1125
    }
1126
1127
    /**
1128
     * Updates the access_url_rel_course_category table with a given list.
1129
     *
1130
     * @author Julio Montoya
1131
     *
1132
     * @param array $list  course category list
1133
     * @param int   $urlId access_url_id
1134
     */
1135
    public static function updateUrlRelCourseCategory($list, $urlId)
1136
    {
1137
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE_CATEGORY);
1138
        $sql = "SELECT course_category_id
1139
                FROM $table
1140
                WHERE access_url_id = ".intval($urlId);
1141
        $result = Database::query($sql);
1142
        $existingItems = [];
1143
1144
        while ($row = Database::fetch_array($result)) {
1145
            $existingItems[] = $row['course_category_id'];
1146
        }
1147
1148
        // Adding
1149
        foreach ($list as $id) {
1150
            self::addCourseCategoryToUrl($id, $urlId);
1151
            $categoryInfo = CourseCategory::getCategoryById($id);
1152
            $children = CourseCategory::getChildren($categoryInfo['code']);
1153
            if (!empty($children)) {
1154
                foreach ($children as $category) {
1155
                    self::addCourseCategoryToUrl($category['id'], $urlId);
1156
                }
1157
            }
1158
        }
1159
1160
        // Deleting old items
1161
        foreach ($existingItems as $id) {
1162
            if (!in_array($id, $list)) {
1163
                self::deleteUrlRelCourseCategory($id, $urlId);
1164
                $categoryInfo = CourseCategory::getCategoryById($id);
1165
1166
                $children = CourseCategory::getChildren($categoryInfo['code']);
1167
                if (!empty($children)) {
1168
                    foreach ($children as $category) {
1169
                        self::deleteUrlRelCourseCategory($category['id'], $urlId);
1170
                    }
1171
                }
1172
            }
1173
        }
1174
    }
1175
1176
    /**
1177
     * Updates the access_url_rel_session table with a given user list.
1178
     *
1179
     * @author Julio Montoya
1180
     *
1181
     * @param array $session_list
1182
     * @param int   $urlId
1183
     * */
1184
    public static function update_urls_rel_session($session_list, $urlId)
1185
    {
1186
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1187
1188
        $sql = "SELECT session_id FROM $table
1189
                WHERE access_url_id=".intval($urlId);
1190
        $result = Database::query($sql);
1191
        $existing_sessions = [];
1192
1193
        while ($row = Database::fetch_array($result)) {
1194
            $existing_sessions[] = $row['session_id'];
1195
        }
1196
1197
        // Adding users
1198
        foreach ($session_list as $session) {
1199
            if (!in_array($session, $existing_sessions)) {
1200
                if (!empty($session) && !empty($urlId)) {
1201
                    self::add_session_to_url($session, $urlId);
1202
                }
1203
            }
1204
        }
1205
1206
        // Deleting old users
1207
        foreach ($existing_sessions as $existing_session) {
1208
            if (!in_array($existing_session, $session_list)) {
1209
                if (!empty($existing_session) && !empty($urlId)) {
1210
                    self::delete_url_rel_session(
1211
                        $existing_session,
1212
                        $urlId
1213
                    );
1214
                }
1215
            }
1216
        }
1217
    }
1218
1219
    /**
1220
     * @param int $user_id
1221
     *
1222
     * @return array
1223
     */
1224
    public static function get_access_url_from_user($user_id)
1225
    {
1226
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_USER);
1227
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1228
        $sql = "SELECT url, access_url_id
1229
                FROM $table url_rel_user
1230
                INNER JOIN $table_url u
1231
                ON (url_rel_user.access_url_id = u.id)
1232
                WHERE user_id = ".intval($user_id);
1233
        $result = Database::query($sql);
1234
1235
        return Database::store_result($result, 'ASSOC');
1236
    }
1237
1238
    /**
1239
     * @param int $courseId
1240
     *
1241
     * @return array
1242
     */
1243
    public static function get_access_url_from_course($courseId)
1244
    {
1245
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
1246
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1247
        $courseId = (int) $courseId;
1248
        $sql = "SELECT url, access_url_id FROM $table c
1249
                INNER JOIN $table_url u
1250
                ON (c.access_url_id = u.id)
1251
                WHERE c_id = $courseId";
1252
1253
        $result = Database::query($sql);
1254
1255
        return Database::store_result($result, 'ASSOC');
1256
    }
1257
1258
    public static function getCountAccessUrlFromCourse($courseId)
1259
    {
1260
        $courseId = (int) $courseId;
1261
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
1262
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1263
        $sql = "SELECT count(u.id) count FROM $table c
1264
                INNER JOIN $table_url u
1265
                ON (c.access_url_id = u.id)
1266
                WHERE c_id = $courseId ";
1267
1268
        $result = Database::query($sql);
1269
        if ($result) {
1270
            $row = Database::fetch_assoc($result);
1271
1272
            return (int) $row['count'];
1273
        }
1274
1275
        return 0;
1276
    }
1277
1278
    /**
1279
     * @param $sessionId
1280
     *
1281
     * @return array
1282
     */
1283
    public static function get_access_url_from_session($sessionId)
1284
    {
1285
        $table_url_rel_session = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_SESSION);
1286
        $table_url = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1287
        $sql = "SELECT url, access_url_id
1288
                FROM $table_url_rel_session url_rel_session
1289
                INNER JOIN $table_url u
1290
                ON (url_rel_session.access_url_id = u.id)
1291
                WHERE session_id = ".intval($sessionId);
1292
        $result = Database::query($sql);
1293
        $url_list = Database::store_result($result);
1294
1295
        return $url_list;
1296
    }
1297
1298
    /**
1299
     * @param string $url
1300
     *
1301
     * @return bool|mixed|null
1302
     */
1303
    public static function get_url_id($url)
1304
    {
1305
        $table = Database::get_main_table(TABLE_MAIN_ACCESS_URL);
1306
        $sql = "SELECT id FROM $table
1307
                WHERE url = '".Database::escape_string($url)."'";
1308
        $result = Database::query($sql);
1309
        $urlId = Database::result($result, 0, 0);
1310
1311
        return $urlId;
1312
    }
1313
1314
    /**
1315
     * @param string $needle
1316
     *
1317
     * @return XajaxResponse
1318
     */
1319
    public static function searchCourseCategoryAjax($needle)
1320
    {
1321
        $response = new xajaxResponse();
1322
        $return = '';
1323
1324
        if (!empty($needle)) {
1325
            // xajax send utf8 datas... datas in db can be non-utf8 datas
1326
            $charset = api_get_system_encoding();
1327
            $needle = api_convert_encoding($needle, $charset, 'utf-8');
1328
            $needle = Database::escape_string($needle);
1329
            // search courses where username or firstname or lastname begins likes $needle
1330
            $sql = 'SELECT id, u.title
1331
                    FROM '.Database::get_main_table(TABLE_MAIN_CATEGORY).' u
1332
                    WHERE
1333
                        u.title LIKE "'.$needle.'%" AND
1334
                        (parent_id IS NULL or parent_id = 0)
1335
                    ORDER BY u.title
1336
                    LIMIT 11';
1337
            $result = Database::query($sql);
1338
            $i = 0;
1339
            while ($data = Database::fetch_array($result)) {
1340
                $i++;
1341
                if ($i <= 10) {
1342
                    $return .= '<a
1343
                    href="javascript: void(0);"
1344
                    onclick="javascript: add_user_to_url(\''.addslashes($data['id']).'\',\''.addslashes($data['title']).' \')">'.$data['title'].' </a><br />';
1345
                } else {
1346
                    $return .= '...<br />';
1347
                }
1348
            }
1349
        }
1350
1351
        $response->addAssign(
1352
            'ajax_list_courses',
1353
            'innerHTML',
1354
            api_utf8_encode($return)
1355
        );
1356
1357
        return $response;
1358
    }
1359
1360
    public static function remove_courses_from_urls(array $courseCodes, array $urlIds): void
1361
    {
1362
        if (empty($courseCodes) || empty($urlIds)) {
1363
            return;
1364
        }
1365
1366
        $conn = Database::getManager()->getConnection();
1367
        $placeholdersCourses = implode(',', array_fill(0, count($courseCodes), '?'));
1368
        $placeholdersUrls = implode(',', array_fill(0, count($urlIds), '?'));
1369
1370
        $sql = "DELETE FROM access_url_rel_course
1371
            WHERE c_id IN (
1372
                SELECT id FROM course WHERE code IN ($placeholdersCourses)
1373
            )
1374
            AND access_url_id IN ($placeholdersUrls)";
1375
1376
        $conn->executeQuery($sql, array_merge($courseCodes, $urlIds));
1377
    }
1378
1379
    public static function searchCoursesByTitleOrCode(string $needle): array
1380
    {
1381
        $tbl = Database::get_main_table(TABLE_MAIN_COURSE);
1382
        $charset = api_get_system_encoding();
1383
        $needle = api_convert_encoding($needle, $charset, 'utf-8');
1384
        $needle = Database::escape_string($needle);
1385
1386
        $sql = "
1387
        SELECT id, code, title
1388
        FROM $tbl
1389
        WHERE title LIKE '$needle%' OR code LIKE '$needle%'
1390
        ORDER BY title, code
1391
        LIMIT 11
1392
    ";
1393
1394
        return Database::store_result(Database::query($sql));
1395
    }
1396
}
1397