Passed
Push — 1.10.x ( 961375...f74e4d )
by
unknown
96:51 queued 46:53
created

Auth::search_courses()   C

Complexity

Conditions 7
Paths 24

Size

Total Lines 90
Code Lines 60

Duplication

Lines 6
Ratio 6.67 %
Metric Value
dl 6
loc 90
rs 6.5083
cc 7
eloc 60
nc 24
nop 2

How to fix   Long Method   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
/**
5
 * Class Auth
6
 * Auth can be used to instantiate objects or as a library to manage courses
7
 * This file contains a class used like library provides functions for auth tool.
8
 * It's also used like model to courses_controller (MVC pattern)
9
 * @author Christian Fasanando <[email protected]>
10
 *
11
 * @package chamilo.auth
12
 */
13
class Auth
14
{
15
    /**
16
     * Constructor
17
     */
18
    public function __construct()
19
    {
20
    }
21
22
    /**
23
     * retrieves all the courses that the user has already subscribed to
24
     * @param   int $user_id
25
     * @return  array an array containing all the information of the courses of the given user
26
     */
27
    public function get_courses_of_user($user_id)
28
    {
29
        $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
30
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
31
        $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_EXTRA_FIELD);
32
        $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
33
34
        $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE;
35
        // get course list auto-register
36
        $sql = "SELECT item_id FROM $TABLE_COURSE_FIELD_VALUE tcfv
37
                INNER JOIN $TABLE_COURSE_FIELD tcf
38
                ON tcfv.field_id =  tcf.id
39
                WHERE
40
                    tcf.extra_field_type = $extraFieldType AND
41
                    tcf.variable = 'special_course' AND
42
                    tcfv.value = 1
43
                ";
44
45
        $result = Database::query($sql);
46
        $special_course_list = array();
47 View Code Duplication
        if (Database::num_rows($result) > 0) {
48
            while ($result_row = Database::fetch_array($result)) {
49
                $special_course_list[] = '"' . $result_row['item_id'] . '"';
50
            }
51
        }
52
        $without_special_courses = '';
53
        if (!empty($special_course_list)) {
54
            $without_special_courses = ' AND course.id NOT IN (' . implode(',', $special_course_list) . ')';
55
        }
56
57
        // Secondly we select the courses that are in a category (user_course_cat<>0) and sort these according to the sort of the category
58
        $user_id = intval($user_id);
59
        $sql = "SELECT
60
                    course.code k,
61
                    course.visual_code vc,
62
                    course.subscribe subscr,
63
                    course.unsubscribe unsubscr,
64
                    course.title i,
65
                    course.tutor_name t,
66
                    course.directory dir,
67
                    course_rel_user.status status,
68
                    course_rel_user.sort sort,
69
                    course_rel_user.user_course_cat user_course_cat
70
                FROM $TABLECOURS course, $TABLECOURSUSER  course_rel_user
71
                WHERE
72
                    course.id = course_rel_user.c_id AND
73
                    course_rel_user.relation_type<>" . COURSE_RELATION_TYPE_RRHH . " AND
74
                    course_rel_user.user_id = '" . $user_id . "' $without_special_courses
75
                ORDER BY course_rel_user.sort ASC";
76
        $result = Database::query($sql);
77
        $courses = array();
78
        while ($row = Database::fetch_array($result)) {
79
            //we only need the database name of the course
80
            $courses[] = array(
81
                'code' => $row['k'],
82
                'visual_code' => $row['vc'],
83
                'title' => $row['i'],
84
                'directory' => $row['dir'],
85
                'status' => $row['status'],
86
                'tutor' => $row['t'],
87
                'subscribe' => $row['subscr'],
88
                'unsubscribe' => $row['unsubscr'],
89
                'sort' => $row['sort'],
90
                'user_course_category' => $row['user_course_cat']
91
            );
92
        }
93
94
        return $courses;
95
    }
96
97
    /**
98
     * retrieves the user defined course categories
99
     * @return array containing all the IDs of the user defined courses categories, sorted by the "sort" field
100
     */
101
    public function get_user_course_categories()
102
    {
103
        $user_id = api_get_user_id();
104
        $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
105
        $sql = "SELECT * FROM " . $table_category . "
106
                WHERE user_id=$user_id
107
                ORDER BY sort ASC";
108
        $result = Database::query($sql);
109
        $output = array();
110
        while ($row = Database::fetch_array($result)) {
111
            $output[] = $row;
112
        }
113
114
        return $output;
115
    }
116
117
    /**
118
     * This function get all the courses in the particular user category;
119
     * @return string: the name of the user defined course category
0 ignored issues
show
Documentation introduced by
The doc-type string: could not be parsed: Unknown type name "string:" at position 0. (view supported doc-types)

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

Loading history...
120
     */
121
    public function get_courses_in_category()
122
    {
123
        $user_id = api_get_user_id();
124
125
        // table definitions
126
        $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
127
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
128
        $TABLE_COURSE_FIELD = Database::get_main_table(TABLE_EXTRA_FIELD);
129
        $TABLE_COURSE_FIELD_VALUE = Database::get_main_table(TABLE_EXTRA_FIELD_VALUES);
130
131
        $extraFieldType = \Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE;
132
133
        // get course list auto-register
134
        $sql = "SELECT item_id
135
                FROM $TABLE_COURSE_FIELD_VALUE tcfv
136
                INNER JOIN $TABLE_COURSE_FIELD tcf
137
                ON tcfv.field_id =  tcf.id
138
                WHERE
139
                    tcf.extra_field_type = $extraFieldType AND
140
                    tcf.variable = 'special_course' AND
141
                    tcfv.value = 1 ";
142
143
        $result = Database::query($sql);
144
        $special_course_list = array();
145 View Code Duplication
        if (Database::num_rows($result) > 0) {
146
            while ($result_row = Database::fetch_array($result)) {
147
                $special_course_list[] = '"' . $result_row['item_id'] . '"';
148
            }
149
        }
150
151
        $without_special_courses = '';
152
        if (!empty($special_course_list)) {
153
            $without_special_courses = ' AND course.id NOT IN (' . implode(',', $special_course_list) . ')';
154
        }
155
156
        $sql = "SELECT
157
                    course.code, course.visual_code, course.subscribe subscr, course.unsubscribe unsubscr,
158
                    course.title title, course.tutor_name tutor, course.directory, course_rel_user.status status,
159
                    course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
160
                FROM $TABLECOURS course,
161
                $TABLECOURSUSER  course_rel_user
162
                WHERE
163
                    course.id = course_rel_user.c_id AND
164
                    course_rel_user.user_id = '" . $user_id . "' AND
165
                    course_rel_user.relation_type <> " . COURSE_RELATION_TYPE_RRHH . "
166
                    $without_special_courses
167
                ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
168
        $result = Database::query($sql);
169
        $number_of_courses = Database::num_rows($result);
170
        $data = array();
171
        while ($course = Database::fetch_array($result)) {
172
            $data[$course['user_course_cat']][] = $course;
173
        }
174
175
        return $data;
176
    }
177
178
    /**
179
     * stores  the changes in a course category
180
     * (moving a course to a different course category)
181
     * @param  int    $courseId
182
     * @param  int       Category id
183
     * @return bool      True if it success
184
     */
185
    public function updateCourseCategory($courseId, $newcategory)
186
    {
187
        $courseId = intval($courseId);
188
        $newcategory = intval($newcategory);
189
        $current_user = api_get_user_id();
190
191
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
192
        $max_sort_value = api_max_sort_value($newcategory, $current_user);
193
        $sql = "UPDATE $TABLECOURSUSER SET
194
                    user_course_cat='" . $newcategory . "',
195
                    sort='" . ($max_sort_value + 1) . "'
196
                WHERE
197
                    c_id ='" . $courseId . "' AND
198
                    user_id='" . $current_user . "' AND
199
                    relation_type<>" . COURSE_RELATION_TYPE_RRHH;
200
        $resultQuery = Database::query($sql);
201
202
        $result = false;
203
        if (Database::affected_rows($resultQuery)) {
204
            $result = true;
205
        }
206
207
        return $result;
208
    }
209
210
    /**
211
     * moves the course one place up or down
212
     * @param   string    Direction (up/down)
213
     * @param   string    Course code
214
     * @param   int       Category id
215
     * @return  bool      True if it success
216
     */
217
    public function move_course($direction, $course2move, $category)
218
    {
219
        // definition of tables
220
        $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
221
222
        $current_user_id = api_get_user_id();
223
        $all_user_courses = $this->get_courses_of_user($current_user_id);
224
225
        // we need only the courses of the category we are moving in
226
        $user_courses = array();
227
        foreach ($all_user_courses as $key => $course) {
228
            if ($course['user_course_category'] == $category) {
229
                $user_courses[] = $course;
230
            }
231
        }
232
233
        $target_course = array();
234
        foreach ($user_courses as $count => $course) {
235
            if ($course2move == $course['code']) {
236
                // source_course is the course where we clicked the up or down icon
237
                $source_course = $course;
238
                // target_course is the course before/after the source_course (depending on the up/down icon)
239
                if ($direction == 'up') {
240
                    $target_course = $user_courses[$count - 1];
241
                } else {
242
                    $target_course = $user_courses[$count + 1];
243
                }
244
                break;
245
            }
246
        }
247
248
        $result = false;
249
        if (count($target_course) > 0 && count($source_course) > 0) {
250
            $courseInfo = api_get_course_info($source_course['code']);
251
            $courseId = $courseInfo['real_id'];
252
253
            $targetCourseInfo = api_get_course_info($target_course['code']);
254
            $targetCourseId = $targetCourseInfo['real_id'];
255
256
            $sql = "UPDATE $table
257
                    SET sort='" . $target_course['sort'] . "'
258
                    WHERE
259
                        c_id = '" . $courseId . "' AND
260
                        user_id = '" . $current_user_id . "' AND
261
                        relation_type<>" . COURSE_RELATION_TYPE_RRHH;
262
263
            $result1 = Database::query($sql);
264
265
            $sql = "UPDATE $table SET sort='" . $source_course['sort'] . "'
266
                    WHERE
267
                        c_id ='" . $targetCourseId . "' AND
268
                        user_id='" . $current_user_id . "' AND
269
                        relation_type<>" . COURSE_RELATION_TYPE_RRHH;
270
271
            $result2 = Database::query($sql);
272
273
            if (Database::affected_rows($result1) && Database::affected_rows($result2)) {
274
                $result = true;
275
            }
276
        }
277
278
        return $result;
279
    }
280
281
    /**
282
     * Moves the course one place up or down
283
     * @param string    Direction up/down
284
     * @param string    Category id
285
     * @return bool     True If it success
286
     */
287
    public function move_category($direction, $category2move)
288
    {
289
        // the database definition of the table that stores the user defined course categories
290
        $table_user_defined_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
291
292
        $current_user_id = api_get_user_id();
293
        $user_coursecategories = $this->get_user_course_categories();
294
        $user_course_categories_info = $this->get_user_course_categories_info();
295
        $result = false;
296
297
        foreach ($user_coursecategories as $key => $category) {
298
            $category_id = $category['id'];
299
            if ($category2move == $category_id) {
300
                // source_course is the course where we clicked the up or down icon
301
                $source_category = $user_course_categories_info[$category2move];
302
                // target_course is the course before/after the source_course (depending on the up/down icon)
303
                if ($direction == 'up') {
304
                    $target_category = $user_course_categories_info[$user_coursecategories[$key - 1]['id']];
305
                } else {
306
                    $target_category = $user_course_categories_info[$user_coursecategories[$key + 1]['id']];
307
                }
308
            }
309
        }
310
311
        if (count($target_category) > 0 && count($source_category) > 0) {
312
            $sql_update1 = "UPDATE $table_user_defined_category SET sort='" . Database::escape_string($target_category['sort']) . "'
313
                            WHERE id='" . intval($source_category['id']) . "' AND user_id='" . $current_user_id . "'";
314
            $sql_update2 = "UPDATE $table_user_defined_category SET sort='" . Database::escape_string($source_category['sort']) . "'
315
                            WHERE id='" . intval($target_category['id']) . "' AND user_id='" . $current_user_id . "'";
316
317
            $result1 = Database::query($sql_update2);
318
            $result2 = Database::query($sql_update1);
319
            if (Database::affected_rows($result1) && Database::affected_rows($result2)) {
320
                $result = true;
321
            }
322
        }
323
        return $result;
324
    }
325
326
    /**
327
     * Retrieves the user defined course categories and all the info that goes with it
328
     * @return array containing all the info of the user defined courses categories with the id as key of the array
329
     */
330
    public function get_user_course_categories_info()
331
    {
332
        $current_user_id = api_get_user_id();
333
        $table_category = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
334
        $sql = "SELECT * FROM " . $table_category . "
335
                WHERE user_id='" . $current_user_id . "'
336
                ORDER BY sort ASC";
337
        $result = Database::query($sql);
338
        while ($row = Database::fetch_array($result)) {
339
            $output[$row['id']] = $row;
340
        }
341
        return $output;
342
    }
343
344
    /**
345
     * Updates the user course category in the chamilo_user database
346
     * @param   string  Category title
347
     * @param   int     Category id
348
     * @return  bool    True if it success
349
     */
350 View Code Duplication
    public function store_edit_course_category($title, $category_id)
351
    {
352
        // protect data
353
        $title = Database::escape_string($title);
354
        $category_id = intval($category_id);
355
        $result = false;
356
        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
357
        $sql = "UPDATE $tucc
358
                SET title='" . api_htmlentities($title, ENT_QUOTES, api_get_system_encoding()) . "'
359
                WHERE id='" . $category_id . "'";
360
        $resultQuery = Database::query($sql);
361
        if (Database::affected_rows($resultQuery)) {
362
            $result = true;
363
        }
364
        return $result;
365
    }
366
367
    /**
368
     * deletes a course category and moves all the courses that were in this category to main category
369
     * @param   int     Category id
370
     * @return  bool    True if it success
371
     */
372
    public function delete_course_category($category_id)
373
    {
374
        $current_user_id = api_get_user_id();
375
        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
376
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
377
        $category_id = intval($category_id);
378
        $result = false;
379
        $sql_delete = "DELETE FROM $tucc
380
                      WHERE id='" . $category_id . "' and user_id='" . $current_user_id . "'";
381
        $resultQuery = Database::query($sql_delete);
382
       if (Database::affected_rows($resultQuery)) {
383
            $result = true;
384
        }
385
        $sql = "UPDATE $TABLECOURSUSER
386
                SET user_course_cat='0'
387
                WHERE
388
                    user_course_cat='" . $category_id . "' AND
389
                    user_id='" . $current_user_id . "' AND
390
                    relation_type<>" . COURSE_RELATION_TYPE_RRHH . " ";
391
        Database::query($sql);
392
393
        return $result;
394
    }
395
396
    /**
397
     * Search the courses database for a course that matches the search term.
398
     * The search is done on the code, title and tutor field of the course table.
399
     * @param string $search_term The string that the user submitted, what we are looking for
400
     * @param array $limit
401
     * @return array An array containing a list of all the courses matching the the search term.
402
     */
403
    public function search_courses($search_term, $limit)
404
    {
405
        $courseTable = Database::get_main_table(TABLE_MAIN_COURSE);
406
        $extraFieldTable = Database :: get_main_table(TABLE_EXTRA_FIELD);
407
        $extraFieldValuesTable = Database :: get_main_table(TABLE_EXTRA_FIELD_VALUES);
408
409
        $limitFilter = getLimitFilterFromArray($limit);
410
411
        // get course list auto-register
412
        $sql = "SELECT item_id
413
                FROM $extraFieldValuesTable tcfv
414
                INNER JOIN $extraFieldTable tcf ON tcfv.field_id =  tcf.id
415
                WHERE
416
                    tcf.variable = 'special_course' AND
417
                    tcfv.value = 1 ";
418
419
        $special_course_result = Database::query($sql);
420 View Code Duplication
        if (Database::num_rows($special_course_result) > 0) {
421
            $special_course_list = array();
422
            while ($result_row = Database::fetch_array($special_course_result)) {
423
                $special_course_list[] = '"' . $result_row['item_id'] . '"';
424
            }
425
        }
426
        $without_special_courses = '';
427
        if (!empty($special_course_list)) {
428
            $without_special_courses = ' AND course.code NOT IN (' . implode(',', $special_course_list) . ')';
429
        }
430
431
        $search_term_safe = Database::escape_string($search_term);
432
        $sql_find = "SELECT * FROM $courseTable
433
                    WHERE (
434
                            code LIKE '%" . $search_term_safe . "%' OR
435
                            title LIKE '%" . $search_term_safe . "%' OR
436
                            tutor_name LIKE '%" . $search_term_safe . "%'
437
                        )
438
                        $without_special_courses
439
                    ORDER BY title, visual_code ASC
440
                    $limitFilter
441
                    ";
442
443
        if (api_is_multiple_url_enabled()) {
444
            $url_access_id = api_get_current_access_url_id();
445
            if ($url_access_id != -1) {
446
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
447
                $sql_find = "SELECT *
448
                            FROM $courseTable as course
449
                            INNER JOIN $tbl_url_rel_course as url_rel_course
450
                            ON (url_rel_course.c_id = course.id)
451
                            WHERE
452
                                access_url_id = $url_access_id AND (
453
                                    code LIKE '%" . $search_term_safe . "%' OR
454
                                    title LIKE '%" . $search_term_safe . "%' OR
455
                                    tutor_name LIKE '%" . $search_term_safe . "%'
456
                                )
457
                                $without_special_courses
458
                            ORDER BY title, visual_code ASC
459
                            $limitFilter
460
                            ";
461
            }
462
        }
463
        $result_find = Database::query($sql_find);
464
        $courses = array();
465
        while ($row = Database::fetch_array($result_find)) {
466
            $row['registration_code'] = !empty($row['registration_code']);
467
            $count_users = count(CourseManager::get_user_list_from_course_code($row['code']));
468
            $count_connections_last_month = Tracking::get_course_connections_count(
469
                    $row['id'], 0, api_get_utc_datetime(time() - (30 * 86400))
470
            );
471
472
            $point_info = CourseManager::get_course_ranking($row['id'], 0);
473
474
            $courses[] = array(
475
                'real_id' => $row['id'],
476
                'point_info' => $point_info,
477
                'code' => $row['code'],
478
                'directory' => $row['directory'],
479
                'visual_code' => $row['visual_code'],
480
                'title' => $row['title'],
481
                'tutor' => $row['tutor_name'],
482
                'subscribe' => $row['subscribe'],
483
                'unsubscribe' => $row['unsubscribe'],
484
                'registration_code' => $row['registration_code'],
485
                'creation_date' => $row['creation_date'],
486
                'visibility' => $row['visibility'],
487
                'count_users' => $count_users,
488
                'count_connections' => $count_connections_last_month
489
            );
490
        }
491
        return $courses;
492
    }
493
494
    /**
495
     * unsubscribe the user from a given course
496
     * @param   string  Course code
497
     * @return  bool    True if it success
498
     */
499
    public function remove_user_from_course($course_code)
500
    {
501
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
502
503
        // protect variables
504
        $current_user_id = api_get_user_id();
505
        $course_code = Database::escape_string($course_code);
506
        $result = true;
507
508
        $courseInfo = api_get_course_info($course_code);
509
        $courseId = $courseInfo['real_id'];
510
511
        // we check (once again) if the user is not course administrator
512
        // because the course administrator cannot unsubscribe himself
513
        // (s)he can only delete the course
514
        $sql = "SELECT * FROM $tbl_course_user
515
                WHERE
516
                    user_id='" . $current_user_id . "' AND
517
                    c_id ='" . $courseId . "' AND
518
                    status='1' ";
519
        $result_check = Database::query($sql);
520
        $number_of_rows = Database::num_rows($result_check);
521
        if ($number_of_rows > 0) {
522
            $result = false;
523
        }
524
525
        CourseManager::unsubscribe_user($current_user_id, $course_code);
526
        return $result;
527
    }
528
529
    /**
530
     * stores the user course category in the chamilo_user database
531
     * @param   string  Category title
532
     * @return  bool    True if it success
533
     */
534
    public function store_course_category($category_title)
535
    {
536
        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
537
538
        // protect data
539
        $current_user_id = api_get_user_id();
540
        $category_title = Database::escape_string($category_title);
541
        $result = false;
542
543
        // step 1: we determine the max value of the user defined course categories
544
        $sql = "SELECT sort FROM $tucc WHERE user_id='" . $current_user_id . "' ORDER BY sort DESC";
545
        $rs_sort = Database::query($sql);
546
        $maxsort = Database::fetch_array($rs_sort);
547
        $nextsort = $maxsort['sort'] + 1;
548
549
        // step 2: we check if there is already a category with this name, if not we store it, else we give an error.
550
        $sql = "SELECT * FROM $tucc WHERE user_id='" . $current_user_id . "' AND title='" . $category_title . "'ORDER BY sort DESC";
551
        $rs = Database::query($sql);
552
        if (Database::num_rows($rs) == 0) {
553
            $sql_insert = "INSERT INTO $tucc (user_id, title,sort)
554
                           VALUES ('" . $current_user_id . "', '" . api_htmlentities($category_title, ENT_QUOTES, api_get_system_encoding()) . "', '" . $nextsort . "')";
555
            $resultQuery = Database::query($sql_insert);
556
            if (Database::affected_rows($resultQuery)) {
557
                $result = true;
558
            }
559
        } else {
560
            $result = false;
561
        }
562
        return $result;
563
    }
564
565
    /**
566
     * Counts the number of courses in a given course category
567
     * @param   string $categoryCode Category code
568
     * @param $searchTerm
569
     * @return  int     Count of courses
570
     */
571
    public function count_courses_in_category($categoryCode, $searchTerm = '')
572
    {
573
        return countCoursesInCategory($categoryCode, $searchTerm);
574
    }
575
576
    /**
577
     * get the browsing of the course categories (faculties)
578
     * @return array    array containing a list with all the categories and subcategories(if needed)
579
     */
580
    public function browse_course_categories()
581
    {
582
        return browseCourseCategories();
583
    }
584
585
    /**
586
     * Display all the courses in the given course category. I could have used a parameter here
587
     * @param string $categoryCode Category code
588
     * @param int $randomValue
589
     * @param array $limit will be used if $random_value is not set.
590
     * This array should contains 'start' and 'length' keys
591
     * @return array Courses data
592
     */
593
    public function browse_courses_in_category($categoryCode, $randomValue = null, $limit = array())
594
    {
595
        return browseCoursesInCategory($categoryCode, $randomValue, $limit);
596
    }
597
598
    /**
599
     * Subscribe the user to a given course
600
     * @param string Course code
601
     * @return string  Message about results
602
     */
603
    public function subscribe_user($course_code)
604
    {
605
        $user_id = api_get_user_id();
606
        $all_course_information = CourseManager::get_course_information($course_code);
607
608
        if (
609
            $all_course_information['registration_code'] == '' ||
610
            (
611
                isset($_POST['course_registration_code']) &&
612
                $_POST['course_registration_code'] == $all_course_information['registration_code']
613
            )
614
        ) {
615
            if (api_is_platform_admin()) {
616
                $status_user_in_new_course = COURSEMANAGER;
617
            } else {
618
                $status_user_in_new_course = null;
619
            }
620
            if (CourseManager::add_user_to_course($user_id, $course_code, $status_user_in_new_course)) {
621
                $send = api_get_course_setting('email_alert_to_teacher_on_new_user_in_course', $course_code);
622
                if ($send == 1) {
623
                    CourseManager::email_to_tutor($user_id, $all_course_information['real_id'], $send_to_tutor_also = false);
624
                } else if ($send == 2) {
625
                    CourseManager::email_to_tutor($user_id, $all_course_information['real_id'], $send_to_tutor_also = true);
626
                }
627
                $url = Display::url($all_course_information['title'], api_get_course_url($course_code));
628
                $message = sprintf(get_lang('EnrollToCourseXSuccessful'), $url);
629
            } else {
630
                $message = get_lang('ErrorContactPlatformAdmin');
631
            }
632
            return array('message' => $message);
633
        } else {
634
            if (isset($_POST['course_registration_code']) && $_POST['course_registration_code'] != $all_course_information['registration_code']) {
635
                return false;
636
            }
637
            $message = get_lang('CourseRequiresPassword') . '<br />';
638
            $message .= $all_course_information['title'].' ('.$all_course_information['visual_code'].') ';
639
640
            $action  = api_get_path(WEB_CODE_PATH) . "auth/courses.php?action=subscribe_user_with_password&sec_token=" . $_SESSION['sec_token'];
641
            $form = new FormValidator('subscribe_user_with_password', 'post', $action);
642
            $form->addElement('hidden', 'sec_token', $_SESSION['sec_token']);
643
            $form->addElement('hidden', 'subscribe_user_with_password', $all_course_information['code']);
644
            $form->addElement('text', 'course_registration_code');
645
            $form->addButton('submit', get_lang('SubmitRegistrationCode'));
646
            $content = $form->returnForm();
647
648
            return array('message' => $message, 'content' => $content);
649
        }
650
    }
651
652
    /**
653
     * List the sessions
654
     * @param string $date (optional) The date of sessions
655
     * @param array $limit
656
     * @return array The session list
657
     */
658
    public function browseSessions($date = null, $limit = array())
659
    {
660
        $em = Database::getManager();
661
        $qb = $em->createQueryBuilder();
662
663
        $_sessions = $qb->select('s')
664
            ->from('ChamiloCoreBundle:Session', 's');
665
666
        if (!empty($limit)) {
667
            $_sessions->setFirstResult($limit['start'])
668
                ->setMaxResults($limit['length']);
669
        }
670
671
        $_sessions->where(
672
            $qb->expr()->gt('s.nbrCourses', 0)
673
        );
674
675
        if (!is_null($date)) {
676
            $_sessions
677
                ->andWhere(
678
                    $qb->expr()->orX(
679
                        $qb->expr()->between(':date', 's.accessStartDate', 's.accessEndDate'),
680
                        $qb->expr()->isNull('s.accessEndDate'),
681
                        $qb->expr()->andX(
682
                            $qb->expr()->isNull('s.accessStartDate'),
683
                            $qb->expr()->isNotNull('s.accessEndDate'),
684
                            $qb->expr()->gt('s.accessEndDate', ':date')
685
                        )
686
                    )
687
                )
688
                ->setParameter('date', $date);
689
        }
690
691
        return $_sessions->getQuery()->getResult();
692
    }
693
694
    /**
695
     * Return a COUNT from Session table
696
     * @param string $date in Y-m-d format
697
     * @return int
698
     */
699
    function countSessions($date = null)
700
    {
701
        $count = 0;
702
        $sessionTable = Database::get_main_table(TABLE_MAIN_SESSION);
703
        $date = Database::escape_string($date);
704
        $dateFilter = '';
705
        if (!empty($date)) {
706
            $dateFilter = <<<SQL
707
                AND ('$date' BETWEEN s.access_start_date AND s.access_end_date)
708
                OR (s.access_end_date IS NULL)
709
                OR (s.access_start_date IS NULL AND
710
                s.access_end_date IS NOT NULL AND s.access_end_date > '$date')
711
SQL;
712
        }
713
        $sql = "SELECT COUNT(*) FROM $sessionTable s WHERE 1 = 1 $dateFilter";
714
        $res = Database::query($sql);
715
        if ($res !== false && Database::num_rows($res) > 0) {
716
            $count = current(Database::fetch_row($res));
717
        }
718
719
        return $count;
720
    }
721
722
    /**
723
     * Search sessions by the tags in their courses
724
     * @param string $termTag Term for search in tags
725
     * @param array $limit Limit info
726
     * @return array The sessions
727
     */
728
    public function browseSessionsByTags($termTag, array $limit)
729
    {
730
        $em = Database::getManager();
731
        $qb = $em->createQueryBuilder();
732
733
        $sessions = $qb->select('s')
734
            ->distinct(true)
735
            ->from('ChamiloCoreBundle:Session', 's')
736
            ->innerJoin(
737
                'ChamiloCoreBundle:SessionRelCourse',
738
                'src',
739
                \Doctrine\ORM\Query\Expr\Join::WITH,
740
                's.id = src.session'
741
            )
742
            ->innerJoin(
743
                'ChamiloCoreBundle:ExtraFieldRelTag',
744
                'frt',
745
                \Doctrine\ORM\Query\Expr\Join::WITH,
746
                'src.course = frt.itemId'
747
            )
748
            ->innerJoin(
749
                'ChamiloCoreBundle:Tag',
750
                't',
751
                \Doctrine\ORM\Query\Expr\Join::WITH,
752
                'frt.tagId = t.id'
753
            )
754
            ->innerJoin(
755
                'ChamiloCoreBundle:ExtraField',
756
                'f',
757
                \Doctrine\ORM\Query\Expr\Join::WITH,
758
                'frt.fieldId = f.id'
759
            )
760
            ->where(
761
                $qb->expr()->like('t.tag', ":tag")
762
            )
763
            ->andWhere(
764
                $qb->expr()->eq('f.extraFieldType', Chamilo\CoreBundle\Entity\ExtraField::COURSE_FIELD_TYPE)
765
            )
766
            ->setFirstResult($limit['start'])
767
            ->setMaxResults($limit['length'])
768
            ->setParameter('tag', "$termTag%")
769
            ->getQuery()
770
            ->getResult();
771
772
        $sessionsToBrowse = [];
773
774
        foreach ($sessions as $session) {
775
            if ($session->getNbrCourses() === 0) {
776
                continue;
777
            }
778
779
            $sessionsToBrowse[] = $session;
780
        }
781
782
        return $sessionsToBrowse;
783
    }
784
785
    /**
786
     * Search sessions by searched term by session name
787
     * @param string $queryTerm Term for search
788
     * @param array $limit Limit info
789
     * @return array The sessions
790
     */
791
    public function browseSessionsBySearch($queryTerm, array $limit)
792
    {
793
        $sessionsToBrowse = [];
794
795
        $criteria = Doctrine\Common\Collections\Criteria::create()
796
            ->where(
797
                Doctrine\Common\Collections\Criteria::expr()->contains('name', $queryTerm)
798
            )
799
            ->setFirstResult($limit['start'])
800
            ->setMaxResults($limit['length']);
801
802
        $sessions = Database::getManager()
803
                ->getRepository('ChamiloCoreBundle:Session')
804
                ->matching($criteria);
805
806
        foreach ($sessions as $session) {
807
            if ($session->getNbrCourses() === 0) {
808
                continue;
809
            }
810
811
            $sessionsToBrowse[] = $session;
812
        }
813
814
        return $sessionsToBrowse;
815
    }
816
}
817