Completed
Push — master ( 8b2aa0...562606 )
by Julito
09:06
created

Auth::getUserCourseCategory()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

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