Passed
Push — 1.11.x ( 234566...95de4c )
by Julito
13:47 queued 01:32
created

Auth::store_course_category()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 40
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

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