Completed
Push — master ( 1fcdba...966b12 )
by Julito
12:06
created

Auth::get_courses_of_user()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 55
Code Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 30
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 55
rs 9.44

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