Completed
Push — master ( 4fc9f8...d0e06e )
by Julito
12:04
created

Auth::remove_user_from_course()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 29
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

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