Passed
Push — master ( 9d7978...5faf0b )
by Julito
10:24
created

Auth::subscribe_user()   B

Complexity

Conditions 10
Paths 10

Size

Total Lines 60
Code Lines 43

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 43
nc 10
nop 1
dl 0
loc 60
rs 7.6666
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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