Completed
Push — master ( ae5621...ef667c )
by Julito
13:23
created

Auth::countSessions()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 27
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 19
nc 4
nop 1
dl 0
loc 27
rs 8.5806
c 0
b 0
f 0
1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\ExtraField;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, ExtraField. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use Doctrine\Common\Collections\Criteria;
6
use Doctrine\ORM\Query\Expr\Join;
7
8
/**
9
 * Class Auth
10
 * Auth can be used to instantiate objects or as a library to manage courses
11
 * This file contains a class used like library provides functions for auth tool.
12
 * It's also used like model to courses_controller (MVC pattern).
13
 *
14
 * @author Christian Fasanando <[email protected]>
15
 *
16
 * @package chamilo.auth
17
 */
18
class Auth
19
{
20
    /**
21
     * Constructor.
22
     */
23
    public function __construct()
24
    {
25
    }
26
27
    /**
28
     * retrieves all the courses that the user has already subscribed to.
29
     *
30
     * @param int $user_id
31
     *
32
     * @return array an array containing all the information of the courses of the given user
33
     */
34
    public function get_courses_of_user($user_id)
35
    {
36
        $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
37
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
38
        $avoidCoursesCondition = CoursesAndSessionsCatalog::getAvoidCourseCondition();
39
40
        // Secondly we select the courses that are in a category (user_course_cat<>0) and
41
        // sort these according to the sort of the category
42
        $user_id = intval($user_id);
43
        $sql = "SELECT
44
                    course.code k,
45
                    course.visual_code vc,
46
                    course.subscribe subscr,
47
                    course.unsubscribe unsubscr,
48
                    course.title i,
49
                    course.tutor_name t,
50
                    course.category_code cat,
51
                    course.directory dir,
52
                    course_rel_user.status status,
53
                    course_rel_user.sort sort,
54
                    course_rel_user.user_course_cat user_course_cat
55
                FROM $TABLECOURS course, $TABLECOURSUSER  course_rel_user
56
                WHERE
57
                    course.id = course_rel_user.c_id AND
58
                    course_rel_user.relation_type<>".COURSE_RELATION_TYPE_RRHH." AND
59
                    course_rel_user.user_id = '".$user_id."' 
60
                    $avoidCoursesCondition
61
                ORDER BY course_rel_user.sort ASC";
62
        $result = Database::query($sql);
63
        $courses = [];
64
        while ($row = Database::fetch_array($result)) {
65
            //we only need the database name of the course
66
            $courses[] = [
67
                'code' => $row['k'],
68
                'visual_code' => $row['vc'],
69
                'title' => $row['i'],
70
                'directory' => $row['dir'],
71
                'status' => $row['status'],
72
                'tutor' => $row['t'],
73
                'subscribe' => $row['subscr'],
74
                'category' => $row['cat'],
75
                'unsubscribe' => $row['unsubscr'],
76
                'sort' => $row['sort'],
77
                'user_course_category' => $row['user_course_cat'],
78
            ];
79
        }
80
81
        return $courses;
82
    }
83
84
    /**
85
     * This function get all the courses in the particular user category;.
86
     *
87
     * @return string The name of the user defined course category
88
     */
89
    public function get_courses_in_category()
90
    {
91
        $user_id = api_get_user_id();
92
93
        // table definitions
94
        $TABLECOURS = Database::get_main_table(TABLE_MAIN_COURSE);
95
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
96
        $avoidCoursesCondition = CoursesAndSessionsCatalog::getAvoidCourseCondition();
97
98
        $sql = "SELECT
99
                    course.code, course.visual_code, course.subscribe subscr, course.unsubscribe unsubscr,
100
                    course.title title, course.tutor_name tutor, course.directory, course_rel_user.status status,
101
                    course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
102
                FROM $TABLECOURS course,
103
                $TABLECOURSUSER  course_rel_user
104
                WHERE
105
                    course.id = course_rel_user.c_id AND
106
                    course_rel_user.user_id = '".$user_id."' AND
107
                    course_rel_user.relation_type <> ".COURSE_RELATION_TYPE_RRHH."
108
                    $avoidCoursesCondition
109
                ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
110
        $result = Database::query($sql);
111
        $data = [];
112
        while ($course = Database::fetch_array($result)) {
113
            $data[$course['user_course_cat']][] = $course;
114
        }
115
116
        return $data;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $data returns the type array which is incompatible with the documented return type string.
Loading history...
117
    }
118
119
    /**
120
     * stores  the changes in a course category
121
     * (moving a course to a different course category).
122
     *
123
     * @param int $courseId
124
     * @param  int       Category id
125
     *
126
     * @return bool True if it success
127
     */
128
    public function updateCourseCategory($courseId, $newcategory)
129
    {
130
        $courseId = intval($courseId);
131
        $newcategory = intval($newcategory);
132
        $current_user = api_get_user_id();
133
134
        $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
135
        $max_sort_value = api_max_sort_value($newcategory, $current_user);
136
        $sql = "UPDATE $table SET
137
                    user_course_cat='".$newcategory."',
138
                    sort='".($max_sort_value + 1)."'
139
                WHERE
140
                    c_id ='".$courseId."' AND
141
                    user_id='".$current_user."' AND
142
                    relation_type<>".COURSE_RELATION_TYPE_RRHH;
143
        $resultQuery = Database::query($sql);
144
145
        $result = false;
146
        if (Database::affected_rows($resultQuery)) {
147
            $result = true;
148
        }
149
150
        return $result;
151
    }
152
153
    /**
154
     * moves the course one place up or down.
155
     *
156
     * @param   string    Direction (up/down)
157
     * @param   string    Course code
158
     * @param   int       Category id
159
     *
160
     * @return bool True if it success
161
     */
162
    public function move_course($direction, $course2move, $category)
163
    {
164
        // definition of tables
165
        $table = Database::get_main_table(TABLE_MAIN_COURSE_USER);
166
167
        $current_user_id = api_get_user_id();
168
        $all_user_courses = $this->get_courses_of_user($current_user_id);
169
170
        // we need only the courses of the category we are moving in
171
        $user_courses = [];
172
        foreach ($all_user_courses as $key => $course) {
173
            if ($course['user_course_category'] == $category) {
174
                $user_courses[] = $course;
175
            }
176
        }
177
178
        $target_course = [];
179
        foreach ($user_courses as $count => $course) {
180
            if ($course2move == $course['code']) {
181
                // source_course is the course where we clicked the up or down icon
182
                $source_course = $course;
183
                // target_course is the course before/after the source_course (depending on the up/down icon)
184
                if ($direction == 'up') {
185
                    $target_course = $user_courses[$count - 1];
186
                } else {
187
                    $target_course = $user_courses[$count + 1];
188
                }
189
                break;
190
            }
191
        }
192
193
        $result = false;
194
        if (count($target_course) > 0 && count($source_course) > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $source_course does not seem to be defined for all execution paths leading up to this point.
Loading history...
195
            $courseInfo = api_get_course_info($source_course['code']);
196
            $courseId = $courseInfo['real_id'];
197
198
            $targetCourseInfo = api_get_course_info($target_course['code']);
199
            $targetCourseId = $targetCourseInfo['real_id'];
200
201
            $sql = "UPDATE $table
202
                    SET sort='".$target_course['sort']."'
203
                    WHERE
204
                        c_id = '".$courseId."' AND
205
                        user_id = '".$current_user_id."' AND
206
                        relation_type<>".COURSE_RELATION_TYPE_RRHH;
207
208
            $result1 = Database::query($sql);
209
210
            $sql = "UPDATE $table SET sort='".$source_course['sort']."'
211
                    WHERE
212
                        c_id ='".$targetCourseId."' AND
213
                        user_id='".$current_user_id."' AND
214
                        relation_type<>".COURSE_RELATION_TYPE_RRHH;
215
216
            $result2 = Database::query($sql);
217
218
            if (Database::affected_rows($result1) && Database::affected_rows($result2)) {
219
                $result = true;
220
            }
221
        }
222
223
        return $result;
224
    }
225
226
    /**
227
     * Moves the course one place up or down.
228
     *
229
     * @param string $direction     Direction up/down
230
     * @param string $category2move Category id
231
     *
232
     * @return bool True If it success
233
     */
234
    public function move_category($direction, $category2move)
235
    {
236
        $userId = api_get_user_id();
237
        $userCategories = CourseManager::get_user_course_categories(api_get_user_id());
238
        $categories = array_values($userCategories);
239
240
        $previous = null;
241
        $target_category = [];
242
        foreach ($categories as $key => $category) {
243
            $category_id = $category['id'];
244
            if ($category2move == $category_id) {
245
                // source_course is the course where we clicked the up or down icon
246
                $source_category = $userCategories[$category2move];
247
                // target_course is the course before/after the source_course (depending on the up/down icon)
248
                if ($direction == 'up') {
249
                    if (isset($categories[$key - 1])) {
250
                        $target_category = $userCategories[$categories[$key - 1]['id']];
251
                    }
252
                } else {
253
                    if (isset($categories[$key + 1])) {
254
                        $target_category = $userCategories[$categories[$key + 1]['id']];
255
                    }
256
                }
257
            }
258
        }
259
260
        $result = false;
261
        if (count($target_category) > 0 && count($source_category) > 0) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $source_category does not seem to be defined for all execution paths leading up to this point.
Loading history...
262
            $table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
263
            $sql = "UPDATE $table SET 
264
                    sort = '".Database::escape_string($target_category['sort'])."'
265
                    WHERE id='".intval($source_category['id'])."' AND user_id='".$userId."'";
266
            $resultFirst = Database::query($sql);
267
            $sql = "UPDATE $table SET 
268
                    sort = '".Database::escape_string($source_category['sort'])."'
269
                    WHERE id='".intval($target_category['id'])."' AND user_id='".$userId."'";
270
            $resultSecond = Database::query($sql);
271
            if (Database::affected_rows($resultFirst) && Database::affected_rows($resultSecond)) {
272
                $result = true;
273
            }
274
        }
275
276
        return $result;
277
    }
278
279
    /**
280
     * Updates the user course category in the chamilo_user database.
281
     *
282
     * @param   string  Category title
283
     * @param   int     Category id
284
     *
285
     * @return bool True if it success
286
     */
287
    public function store_edit_course_category($title, $category_id)
288
    {
289
        // protect data
290
        $title = Database::escape_string($title);
291
        $category_id = intval($category_id);
292
        $result = false;
293
        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
294
        $sql = "UPDATE $tucc
295
                SET title='".api_htmlentities($title, ENT_QUOTES, api_get_system_encoding())."'
296
                WHERE id='".$category_id."'";
297
        $resultQuery = Database::query($sql);
298
        if (Database::affected_rows($resultQuery)) {
299
            $result = true;
300
        }
301
302
        return $result;
303
    }
304
305
    /**
306
     * deletes a course category and moves all the courses that were in this category to main category.
307
     *
308
     * @param   int     Category id
309
     *
310
     * @return bool True if it success
311
     */
312
    public function delete_course_category($category_id)
313
    {
314
        $current_user_id = api_get_user_id();
315
        $tucc = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
316
        $TABLECOURSUSER = Database::get_main_table(TABLE_MAIN_COURSE_USER);
317
        $category_id = intval($category_id);
318
        $result = false;
319
        $sql = "DELETE FROM $tucc
320
                WHERE 
321
                    id='".$category_id."' AND 
322
                    user_id='".$current_user_id."'";
323
        $resultQuery = Database::query($sql);
324
        if (Database::affected_rows($resultQuery)) {
325
            $result = true;
326
        }
327
        $sql = "UPDATE $TABLECOURSUSER
328
                SET user_course_cat='0'
329
                WHERE
330
                    user_course_cat='".$category_id."' AND
331
                    user_id='".$current_user_id."' AND
332
                    relation_type<>".COURSE_RELATION_TYPE_RRHH." ";
333
        Database::query($sql);
334
335
        return $result;
336
    }
337
338
    /**
339
     * unsubscribe the user from a given course.
340
     *
341
     * @param string $course_code
342
     *
343
     * @return bool True if it success
344
     */
345
    public function remove_user_from_course($course_code)
346
    {
347
        $tbl_course_user = Database::get_main_table(TABLE_MAIN_COURSE_USER);
348
349
        // protect variables
350
        $current_user_id = api_get_user_id();
351
        $course_code = Database::escape_string($course_code);
352
        $result = true;
353
354
        $courseInfo = api_get_course_info($course_code);
355
        $courseId = $courseInfo['real_id'];
356
357
        // we check (once again) if the user is not course administrator
358
        // because the course administrator cannot unsubscribe himself
359
        // (s)he can only delete the course
360
        $sql = "SELECT * FROM $tbl_course_user
361
                WHERE
362
                    user_id='".$current_user_id."' AND
363
                    c_id ='".$courseId."' AND
364
                    status='1' ";
365
        $result_check = Database::query($sql);
366
        $number_of_rows = Database::num_rows($result_check);
367
        if ($number_of_rows > 0) {
368
            $result = false;
369
        }
370
371
        CourseManager::unsubscribe_user($current_user_id, $course_code);
372
373
        return $result;
374
    }
375
376
    /**
377
     * stores the user course category in the chamilo_user database.
378
     *
379
     * @param   string  Category title
380
     *
381
     * @return bool True if it success
382
     */
383
    public function store_course_category($category_title)
384
    {
385
        $table = Database::get_main_table(TABLE_USER_COURSE_CATEGORY);
386
387
        // protect data
388
        $current_user_id = api_get_user_id();
389
        $category_title = Database::escape_string($category_title);
390
        $result = false;
391
392
        // step 1: we determine the max value of the user defined course categories
393
        $sql = "SELECT sort FROM $table 
394
                WHERE user_id='".$current_user_id."' 
395
                ORDER BY sort DESC";
396
        $rs_sort = Database::query($sql);
397
        $maxsort = Database::fetch_array($rs_sort);
398
        $nextsort = $maxsort['sort'] + 1;
399
400
        // step 2: we check if there is already a category with this name,
401
        // if not we store it, else we give an error.
402
        $sql = "SELECT * FROM $table 
403
                WHERE 
404
                    user_id='".$current_user_id."' AND 
405
                    title='".$category_title."'
406
                ORDER BY sort DESC";
407
        $rs = Database::query($sql);
408
        if (Database::num_rows($rs) == 0) {
409
            $sql = "INSERT INTO $table (user_id, title,sort)
410
                    VALUES ('".$current_user_id."', '".api_htmlentities($category_title, ENT_QUOTES, api_get_system_encoding())."', '".$nextsort."')";
411
            $resultQuery = Database::query($sql);
412
            if (Database::affected_rows($resultQuery)) {
413
                $result = true;
414
            }
415
        } else {
416
            $result = false;
417
        }
418
419
        return $result;
420
    }
421
422
    /**
423
     * Subscribe the user to a given course.
424
     *
425
     * @param string $course_code Course code
426
     *
427
     * @return string Message about results
428
     */
429
    public function subscribe_user($course_code)
430
    {
431
        $user_id = api_get_user_id();
432
        $all_course_information = CourseManager::get_course_information($course_code);
0 ignored issues
show
Deprecated Code introduced by
The function CourseManager::get_course_information() has been deprecated: Use api_get_course_info() instead ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

432
        $all_course_information = /** @scrutinizer ignore-deprecated */ CourseManager::get_course_information($course_code);

This function has been deprecated. The supplier of the function has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed and what other function to use instead.

Loading history...
433
434
        if ($all_course_information['registration_code'] == '' ||
435
            (
436
                isset($_POST['course_registration_code']) &&
437
                $_POST['course_registration_code'] == $all_course_information['registration_code']
438
            )
439
        ) {
440
            if (api_is_platform_admin()) {
441
                $status_user_in_new_course = COURSEMANAGER;
442
            } else {
443
                $status_user_in_new_course = null;
444
            }
445
            if (CourseManager::add_user_to_course($user_id, $course_code, $status_user_in_new_course)) {
446
                $send = api_get_course_setting('email_alert_to_teacher_on_new_user_in_course', $course_code);
447
                if ($send == 1) {
448
                    CourseManager::email_to_tutor(
449
                        $user_id,
450
                        $all_course_information['real_id'],
451
                        $send_to_tutor_also = false
452
                    );
453
                } elseif ($send == 2) {
454
                    CourseManager::email_to_tutor(
455
                        $user_id,
456
                        $all_course_information['real_id'],
457
                        $send_to_tutor_also = true
458
                    );
459
                }
460
                $url = Display::url($all_course_information['title'], api_get_course_url($course_code));
461
                $message = sprintf(get_lang('EnrollToCourseXSuccessful'), $url);
462
            } else {
463
                $message = get_lang('ErrorContactPlatformAdmin');
464
            }
465
466
            return ['message' => $message];
0 ignored issues
show
Bug Best Practice introduced by
The expression return array('message' => $message) returns the type array<string,string> which is incompatible with the documented return type string.
Loading history...
467
        } else {
468
            if (isset($_POST['course_registration_code']) &&
469
                $_POST['course_registration_code'] != $all_course_information['registration_code']
470
            ) {
471
                return false;
0 ignored issues
show
Bug Best Practice introduced by
The expression return false returns the type false which is incompatible with the documented return type string.
Loading history...
472
            }
473
            $message = get_lang('CourseRequiresPassword').'<br />';
474
            $message .= $all_course_information['title'].' ('.$all_course_information['visual_code'].') ';
475
476
            $action = api_get_path(WEB_CODE_PATH)."auth/courses.php?action=subscribe_user_with_password&sec_token=".Security::getTokenFromSession();
477
            $form = new FormValidator(
478
                'subscribe_user_with_password',
479
                'post',
480
                $action
481
            );
482
            $form->addElement('hidden', 'sec_token', Security::getTokenFromSession());
483
            $form->addElement('hidden', 'subscribe_user_with_password', $all_course_information['code']);
484
            $form->addElement('text', 'course_registration_code');
485
            $form->addButtonSave(get_lang('SubmitRegistrationCode'));
486
            $content = $form->returnForm();
487
488
            return ['message' => $message, 'content' => $content];
0 ignored issues
show
Bug Best Practice introduced by
The expression return array('message' =... 'content' => $content) returns the type array<string,string> which is incompatible with the documented return type string.
Loading history...
489
        }
490
    }
491
}
492