Completed
Push — master ( 27e209...a08afa )
by Julito
186:04 queued 150:53
created

Rest   F

Complexity

Total Complexity 139

Size/Duplication

Total Lines 1282
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 1282
rs 0.6314
c 0
b 0
f 0
wmc 139

32 Methods

Rating   Name   Duplication   Size   Complexity  
B getCourseAgenda() 0 49 4
A setCourse() 0 17 3
A showLearningPath() 0 23 2
D addUser() 0 117 12
A decodeParams() 0 12 2
B getUserProfile() 0 27 2
A getUserCourses() 0 21 2
B getCourseForum() 0 34 5
A saveForumThread() 0 11 2
A getCourseNotebooks() 0 22 1
A encodeParams() 0 11 1
A init() 0 10 2
D getCourseLearnPaths() 0 104 17
B getMessageUsers() 0 25 3
A setSession() 0 17 3
A saveCourseNotebook() 0 14 2
A saveUserMessage() 0 8 2
B getUserMessages() 0 25 2
B getCourseAnnouncement() 0 26 3
B getCourseForumThread() 0 30 3
A getCourseInfo() 0 21 2
A saveForumPost() 0 9 1
A validate() 0 9 2
A __construct() 0 3 1
A getCourseDescriptions() 0 15 2
A setGcmId() 0 9 1
B getUserSessions() 0 47 5
F addCourse() 0 128 29
C getCourseForumCategories() 0 62 8
C getCourseDocuments() 0 69 8
B getCourseAnnouncements() 0 32 2
B subscribeUserToCourse() 0 17 5

How to fix   Complexity   

Complex Class

Complex classes like Rest often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Rest, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\Course;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, Course. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
5
use Chamilo\CoreBundle\Entity\ExtraFieldValues;
6
use Chamilo\CourseBundle\Entity\Repository\CAnnouncementRepository;
7
use Chamilo\CourseBundle\Entity\Repository\CNotebookRepository;
8
use Chamilo\CourseBundle\Entity\CLpCategory;
9
use Chamilo\CoreBundle\Entity\Session;
10
use Chamilo\UserBundle\Entity\User;
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, User. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
11
use Chamilo\CourseBundle\Entity\CNotebook;
12
13
/**
14
 * Class RestApi
15
 */
16
class Rest extends WebService
17
{
18
    const SERVIVE_NAME = 'MsgREST';
19
    const EXTRA_FIELD_GCM_REGISTRATION = 'gcm_registration_id';
20
21
    const GET_AUTH = 'authenticate';
22
    const GET_USER_MESSAGES = 'user_messages';
23
    const SAVE_GCM_ID = 'gcm_id';
24
    const GET_USER_COURSES = 'user_courses';
25
    const GET_PROFILE = 'user_profile';
26
    const GET_COURSE_INFO = 'course_info';
27
    const GET_COURSE_DESCRIPTIONS = 'course_descriptions';
28
    const GET_COURSE_DOCUMENTS = 'course_documents';
29
    const GET_COURSE_ANNOUNCEMENTS = 'course_announcements';
30
    const GET_COURSE_ANNOUNCEMENT = 'course_announcement';
31
    const GET_COURSE_AGENDA = 'course_agenda';
32
    const GET_COURSE_NOTEBOOKS = 'course_notebooks';
33
    const GET_COURSE_FORUM_CATEGORIES = 'course_forumcategories';
34
    const GET_COURSE_FORUM = 'course_forum';
35
    const GET_COURSE_FORUM_THREAD = 'course_forumthread';
36
    const GET_COURSE_LEARNPATHS = 'course_learnpaths';
37
    const GET_COURSE_LEARNPATH = 'course_learnpath';
38
    const SAVE_FORUM_POST = 'save_forum_post';
39
    const GET_USER_SESSIONS = 'user_sessions';
40
    const SAVE_USER_MESSAGE = 'save_user_message';
41
    const GET_MESSAGE_USERS = 'message_users';
42
    const SAVE_COURSE_NOTEBOOK = 'save_course_notebook';
43
    const SAVE_FORUM_THREAD = 'save_forum_thread';
44
    const SAVE_COURSE = 'save_course';
45
    const SAVE_USER = 'save_user';
46
    const SUBSCRIBE_USER_TO_COURSE = 'subscribe_user_to_course';
47
    const EXTRAFIELD_GCM_ID = 'gcm_registration_id';
48
49
    /**
50
     * @var Session
51
     */
52
    private $session;
53
    /**
54
     * @var Course
55
     */
56
    private $course;
57
58
    /**
59
     * Rest constructor.
60
     * @param string $username
61
     * @param string $apiKey
62
     */
63
    public function __construct($username, $apiKey)
64
    {
65
        parent::__construct($username, $apiKey);
66
    }
67
68
    /**
69
     * Set the current course
70
     * @param int $id
71
     * @throws Exception
72
     */
73
    public function setCourse($id)
74
    {
75
        if (!$id) {
76
            $this->course = null;
77
78
            return;
79
        }
80
81
        $em = Database::getManager();
82
        /** @var Course $course */
83
        $course = $em->find('ChamiloCoreBundle:Course', $id);
84
85
        if (!$course) {
86
            throw new Exception(get_lang('NoCourse'));
87
        }
88
89
        $this->course = $course;
90
    }
91
92
    /** Set the current session
93
     * @param int $id
94
     * @throws Exception
95
     */
96
    public function setSession($id)
97
    {
98
        if (!$id) {
99
            $this->session = null;
100
101
            return;
102
        }
103
104
        $em = Database::getManager();
105
        /** @var Session $session */
106
        $session = $em->find('ChamiloCoreBundle:Session', $id);
107
108
        if (!$session) {
109
            throw new Exception(get_lang('NoSession'));
110
        }
111
112
        $this->session = $session;
113
    }
114
115
    /**
116
     * @param string $username
117
     * @param string $apiKeyToValidate
118
     * @return Rest
119
     * @throws Exception
120
     */
121
    public static function validate($username, $apiKeyToValidate)
122
    {
123
        $apiKey = self::findUserApiKey($username, self::SERVIVE_NAME);
124
125
        if ($apiKey != $apiKeyToValidate) {
126
            throw new Exception(get_lang('InvalidApiKey'));
127
        }
128
129
        return new self($username, $apiKey);
130
    }
131
132
    /**
133
     * Create the gcm_registration_id extra field for users
134
     */
135
    public static function init()
136
    {
137
        $extraField = new ExtraField('user');
138
        $fieldInfo = $extraField->get_handler_field_info_by_field_variable(self::EXTRA_FIELD_GCM_REGISTRATION);
139
140
        if (empty($fieldInfo)) {
141
            $extraField->save([
142
                'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
143
                'field_type' => ExtraField::FIELD_TYPE_TEXT,
144
                'display_text' => self::EXTRA_FIELD_GCM_REGISTRATION
145
            ]);
146
        }
147
    }
148
149
    /**
150
     * @param string $registrationId
151
     * @return bool
152
     */
153
    public function setGcmId($registrationId)
154
    {
155
        $registrationId = Security::remove_XSS($registrationId);
156
        $extraFieldValue = new ExtraFieldValue('user');
157
158
        return $extraFieldValue->save([
0 ignored issues
show
Bug Best Practice introduced by
The expression return $extraFieldValue-... $this->user->getId())) also could return the type integer which is incompatible with the documented return type boolean.
Loading history...
159
            'variable' => self::EXTRA_FIELD_GCM_REGISTRATION,
160
            'value' => $registrationId,
161
            'item_id' => $this->user->getId()
162
        ]);
163
    }
164
165
    /**
166
     * @param int $lastMessageId
167
     * @return array
168
     */
169
    public function getUserMessages($lastMessageId = 0)
170
    {
171
        $lastMessages = MessageManager::getMessagesFromLastReceivedMessage($this->user->getId(), $lastMessageId);
172
        $messages = [];
173
174
        foreach ($lastMessages as $message) {
175
            $hasAttachments = MessageManager::hasAttachments($message['id']);
176
177
            $messages[] = [
178
                'id' => $message['id'],
179
                'title' => $message['title'],
180
                'sender' => [
181
                    'id' => $message['user_id'],
182
                    'lastname' => $message['lastname'],
183
                    'firstname' => $message['firstname'],
184
                    'completeName' => api_get_person_name($message['firstname'], $message['lastname']),
185
                ],
186
                'sendDate' => $message['send_date'],
187
                'content' => $message['content'],
188
                'hasAttachments' => $hasAttachments,
189
                'url' => ''
190
            ];
191
        }
192
193
        return $messages;
194
    }
195
196
    /**
197
     * Get the user courses
198
     * @return array
199
     */
200
    public function getUserCourses()
201
    {
202
        $courses = CourseManager::get_courses_list_by_user_id($this->user->getId());
203
        $data = [];
204
205
        foreach ($courses as $courseId) {
206
            /** @var Course $course */
207
            $course = Database::getManager()->find('ChamiloCoreBundle:Course', $courseId['real_id']);
208
            $teachers = CourseManager::getTeacherListFromCourseCodeToString($course->getCode());
209
210
            $data[] = [
211
                'id' => $course->getId(),
212
                'title' => $course->getTitle(),
213
                'code' => $course->getCode(),
214
                'directory' => $course->getDirectory(),
215
                'urlPicture' => $course->getPicturePath(true),
216
                'teachers' => $teachers
217
            ];
218
        }
219
220
        return $data;
221
    }
222
223
    /**
224
     * @return array
225
     * @throws Exception
226
     */
227
    public function getCourseInfo()
228
    {
229
        $teachers = CourseManager::getTeacherListFromCourseCodeToString($this->course->getCode());
230
        $tools = CourseHome::get_tools_category(
231
            TOOL_STUDENT_VIEW,
232
            $this->course->getId(),
233
            $this->session ? $this->session->getId() : 0
234
        );
235
236
        return [
237
            'id' => $this->course->getId(),
238
            'title' => $this->course->getTitle(),
239
            'code' => $this->course->getCode(),
240
            'directory' => $this->course->getDirectory(),
241
            'urlPicture' => $this->course->getPicturePath(true),
242
            'teachers' => $teachers,
243
            'tools' => array_map(
244
                function ($tool) {
245
                    return ['type' => $tool['name']];
246
                },
247
                $tools
248
            )
249
        ];
250
    }
251
252
    /**
253
     * Get the course descriptions
254
     * @return array
255
     * @throws Exception
256
     */
257
    public function getCourseDescriptions()
258
    {
259
        $descriptions = CourseDescription::get_descriptions($this->course->getId());
260
        $results = [];
261
262
        /** @var CourseDescription $description */
263
        foreach ($descriptions as $description) {
264
            $results[] = [
265
                'id' => $description->get_description_type(),
266
                'title' => $description->get_title(),
267
                'content' => str_replace('src="/', 'src="'.api_get_path(WEB_PATH), $description->get_content())
268
            ];
269
        }
270
271
        return $results;
272
    }
273
274
    /**
275
     * @param int $directoryId
276
     * @return array
277
     * @throws Exception
278
     */
279
    public function getCourseDocuments($directoryId = 0)
280
    {
281
        /** @var string $path */
282
        $path = '/';
283
        $sessionId = $this->session ? $this->session->getId() : 0;
284
285
        if ($directoryId) {
286
            $directory = DocumentManager::get_document_data_by_id(
287
                $directoryId,
288
                $this->course->getCode(),
289
                false,
290
                $sessionId
291
            );
292
293
            if (!$directory) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $directory of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
294
                throw new Exception('NoDataAvailable');
295
            }
296
297
            $path = $directory['path'];
298
        }
299
300
        $courseInfo = api_get_course_info_by_id($this->course->getId());
301
        $documents = DocumentManager::get_all_document_data(
302
            $courseInfo,
303
            $path,
304
            0,
305
            null,
306
            false,
307
            false,
308
            $sessionId
309
        );
310
        $results = [];
311
312
        if (is_array($documents)) {
313
            $webPath = api_get_path(WEB_CODE_PATH).'document/document.php?';
314
315
            /** @var array $document */
316
            foreach ($documents as $document) {
317
                if ($document['visibility'] != '1') {
318
                    continue;
319
                }
320
321
                $icon = $document['filetype'] == 'file'
322
                    ? choose_image($document['path'])
323
                    : chooseFolderIcon($document['path']);
324
325
                $results[] = [
326
                    'id' => $document['id'],
327
                    'type' => $document['filetype'],
328
                    'title' => $document['title'],
329
                    'path' => $document['path'],
330
                    'url' => $webPath.http_build_query([
331
                        'username' => $this->user->getUsername(),
332
                        'api_key' => $this->apiKey,
333
                        'cidReq' => $this->course->getCode(),
334
                        'id_session' => $sessionId,
335
                        'gidReq' => 0,
336
                        'gradebook' => 0,
337
                        'origin' => '',
338
                        'action' => 'download',
339
                        'id' => $document['id']
340
                    ]),
341
                    'icon' => $icon,
342
                    'size' => format_file_size($document['size'])
343
                ];
344
            }
345
        }
346
347
        return $results;
348
    }
349
350
    /**
351
     * @return array
352
     * @throws Exception
353
     */
354
    public function getCourseAnnouncements()
355
    {
356
        $sessionId = $this->session ? $this->session->getId() : 0;
357
358
        $announcements = AnnouncementManager::getAnnouncements(
359
            null,
360
            null,
361
            false,
362
            null,
363
            null,
364
            null,
365
            null,
366
            null,
367
            0,
368
            $this->user->getId(),
369
            $this->course->getId(),
370
            $sessionId
371
        );
372
373
        $announcements = array_map(
374
            function ($announcement) {
375
                return [
376
                    'id' => intval($announcement['id']),
377
                    'title' => strip_tags($announcement['title']),
378
                    'creatorName' => strip_tags($announcement['username']),
379
                    'date' => strip_tags($announcement['insert_date']),
380
                ];
381
            },
382
            $announcements
383
        );
384
385
        return $announcements;
386
    }
387
388
    /**
389
     * @param int $announcementId
390
     * @return array
391
     * @throws Exception
392
     */
393
    public function getCourseAnnouncement($announcementId)
394
    {
395
        $sessionId = $this->session ? $this->session->getId() : 0;
396
        $announcement = AnnouncementManager::getAnnouncementInfoById(
397
            $announcementId,
398
            $this->course->getId(),
399
            $this->user->getId()
400
        );
401
402
        if (!$announcement) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $announcement of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
403
            throw new Exception(get_lang('NoAnnouncement'));
404
        }
405
406
        return [
407
            'id' => intval($announcement['announcement']->getIid()),
408
            'title' => $announcement['announcement']->getTitle(),
409
            'creatorName' => $announcement['item_property']->getInsertUser()->getCompleteName(),
410
            'date' => api_convert_and_format_date(
411
                $announcement['item_property']->getInsertDate(),
412
                DATE_TIME_FORMAT_LONG_24H
413
            ),
414
            'content' => AnnouncementManager::parse_content(
415
                $this->user->getId(),
416
                $announcement['announcement']->getContent(),
417
                $this->course->getCode(),
418
                $sessionId
419
            )
420
        ];
421
    }
422
423
    /**
424
     * @return array
425
     * @throws Exception
426
     */
427
    public function getCourseAgenda()
428
    {
429
        $sessionId = $this->session ? $this->session->getId() : 0;
430
431
        $agenda = new Agenda(
432
            'course',
433
            $this->user->getId(),
434
            $this->course->getId(),
435
            $sessionId
436
        );
437
        $result = $agenda->parseAgendaFilter(null);
438
439
        $start = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
440
        $start->modify('first day of this month');
441
        $start->setTime(0, 0, 0);
442
        $end = new DateTime(api_get_utc_datetime(), new DateTimeZone('UTC'));
443
        $end->modify('last day of this month');
444
        $end->setTime(23, 59, 59);
445
446
        $groupId = current($result['groups']);
447
        $userId = current($result['users']);
448
449
        $events = $agenda->getEvents(
450
            $start->getTimestamp(),
451
            $end->getTimestamp(),
452
            $this->course->getId(),
453
            $groupId,
454
            $userId,
455
            'array'
456
        );
457
458
        if (!is_array($events)) {
459
            return [];
460
        }
461
462
        $webPath = api_get_path(WEB_PATH);
463
464
        return array_map(
465
            function ($event) use ($webPath) {
466
                return [
467
                    'id' => intval($event['unique_id']),
468
                    'title' => $event['title'],
469
                    'content' => str_replace('src="/', 'src="'.$webPath, $event['description']),
470
                    'startDate' => $event['start_date_localtime'],
471
                    'endDate' => $event['end_date_localtime'],
472
                    'isAllDay' => $event['allDay'] ? true : false
473
                ];
474
            },
475
            $events
476
        );
477
    }
478
479
    /**
480
     * @return array
481
     * @throws Exception
482
     */
483
    public function getCourseNotebooks()
484
    {
485
        $em = Database::getManager();
486
        /** @var CNotebookRepository $notebooksRepo */
487
        $notebooksRepo = $em->getRepository('ChamiloCourseBundle:CNotebook');
488
        $notebooks = $notebooksRepo->findByUser($this->user, $this->course, $this->session);
489
490
        return array_map(
491
            function (CNotebook $notebook) {
492
                return [
493
                    'id' => $notebook->getIid(),
494
                    'title' => $notebook->getTitle(),
495
                    'description' => $notebook->getDescription(),
496
                    'creationDate' => api_format_date(
497
                        $notebook->getCreationDate()->getTimestamp()
498
                    ),
499
                    'updateDate' => api_format_date(
500
                        $notebook->getUpdateDate()->getTimestamp()
501
                    )
502
                ];
503
            },
504
            $notebooks
505
        );
506
    }
507
508
    /**
509
     * @return array
510
     * @throws Exception
511
     */
512
    public function getCourseForumCategories()
513
    {
514
        $sessionId = $this->session ? $this->session->getId() : 0;
515
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
516
517
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
518
519
        $categoriesFullData = get_forum_categories('', $this->course->getId(), $sessionId);
520
        $categories = [];
521
        $includeGroupsForums = api_get_setting('display_groups_forum_in_general_tool') === 'true';
522
        $forumsFullData = get_forums('', $this->course->getCode(), $includeGroupsForums, $sessionId);
523
        $forums = [];
524
525
        foreach ($forumsFullData as $forumId => $forumInfo) {
526
            $forum = [
527
                'id' => intval($forumInfo['iid']),
528
                'catId' => intval($forumInfo['forum_category']),
529
                'title' => $forumInfo['forum_title'],
530
                'description' => $forumInfo['forum_comment'],
531
                'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
532
                'numberOfThreads' => isset($forumInfo['number_of_threads']) ? intval($forumInfo['number_of_threads']) : 0,
533
                'lastPost' => null
534
            ];
535
536
            $lastPostInfo = get_last_post_information($forumId, false, $this->course->getId(), $sessionId);
537
538
            if ($lastPostInfo) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $lastPostInfo of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
539
                $forum['lastPost'] = [
540
                    'date' => api_convert_and_format_date($lastPostInfo['last_post_date']),
541
                    'user' => api_get_person_name(
542
                        $lastPostInfo['last_poster_firstname'],
543
                        $lastPostInfo['last_poster_lastname']
544
                    )
545
                ];
546
            }
547
548
            $forums[] = $forum;
549
        }
550
551
        foreach ($categoriesFullData as $category) {
552
            $categoryForums = array_filter(
553
                $forums,
554
                function (array $forum) use ($category) {
555
                    if ($forum['catId'] != $category['cat_id']) {
556
                        return false;
557
                    }
558
559
                    return true;
560
                }
561
            );
562
563
            $categories[] = [
564
                'id' => intval($category['iid']),
565
                'title' => $category['cat_title'],
566
                'catId' => intval($category['cat_id']),
567
                'description' => $category['cat_comment'],
568
                'forums' => $categoryForums,
569
                'courseId' => $this->course->getId()
570
            ];
571
        }
572
573
        return $categories;
574
    }
575
576
    /**
577
     * @param int $forumId
578
     * @return array
579
     * @throws Exception
580
     */
581
    public function getCourseForum($forumId)
582
    {
583
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
584
585
        $sessionId = $this->session ? $this->session->getId() : 0;
586
        $forumInfo = get_forums($forumId, $this->course->getCode(), true, $sessionId);
587
588
        if (!isset($forumInfo['iid'])) {
589
            throw new Exception(get_lang('NoForum'));
590
        }
591
592
        $webCoursePath = api_get_path(WEB_COURSE_PATH).$this->course->getDirectory().'/upload/forum/images/';
593
        $forum = [
594
            'id' => $forumInfo['iid'],
595
            'title' => $forumInfo['forum_title'],
596
            'description' => $forumInfo['forum_comment'],
597
            'image' => $forumInfo['forum_image'] ? ($webCoursePath.$forumInfo['forum_image']) : '',
598
            'threads' => []
599
        ];
600
601
        $threads = get_threads($forumInfo['iid'], $this->course->getId(), $sessionId);
602
603
        foreach ($threads as $thread) {
604
            $forum['threads'][] = [
605
                'id' => $thread['iid'],
606
                'title' => $thread['thread_title'],
607
                'lastEditDate' => api_convert_and_format_date($thread['lastedit_date'], DATE_TIME_FORMAT_LONG_24H),
608
                'numberOfReplies' => $thread['thread_replies'],
609
                'numberOfViews' => $thread['thread_views'],
610
                'author' => api_get_person_name($thread['firstname'], $thread['lastname'])
611
            ];
612
        }
613
614
        return $forum;
615
    }
616
617
    /**
618
     * @param int $forumId
619
     * @param int $threadId
620
     * @return array
621
     */
622
    public function getCourseForumThread($forumId, $threadId)
623
    {
624
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
625
626
        $sessionId = $this->session ? $this->session->getId() : 0;
627
        $threadInfo = get_thread_information($forumId, $threadId, $sessionId);
628
629
        $thread = [
630
            'id' => intval($threadInfo['iid']),
631
            'cId' => intval($threadInfo['c_id']),
632
            'title' => $threadInfo['thread_title'],
633
            'forumId' => intval($threadInfo['forum_id']),
634
            'posts' => []
635
        ];
636
637
        $forumInfo = get_forums($threadInfo['forum_id'], $this->course->getCode(), true, $sessionId);
638
        $postsInfo = getPosts($forumInfo, $threadInfo['iid'], 'ASC');
639
640
        foreach ($postsInfo as $postInfo) {
641
            $thread['posts'][] = [
642
                'id' => $postInfo['iid'],
643
                'title' => $postInfo['post_title'],
644
                'text' => $postInfo['post_text'],
645
                'author' => api_get_person_name($postInfo['firstname'], $postInfo['lastname']),
646
                'date' => api_convert_and_format_date($postInfo['post_date'], DATE_TIME_FORMAT_LONG_24H),
647
                'parentId' => $postInfo['post_parent_id']
648
            ];
649
        }
650
651
        return $thread;
652
    }
653
654
    /**
655
     * @return array
656
     */
657
    public function getUserProfile()
658
    {
659
        $pictureInfo = UserManager::get_user_picture_path_by_id($this->user->getId(), 'web');
660
661
        $result = [
662
            'pictureUri' => $pictureInfo['dir'].$pictureInfo['file'],
663
            'fullName' => $this->user->getCompleteName(),
664
            'username' => $this->user->getUsername(),
665
            'officialCode' => $this->user->getOfficialCode(),
666
            'phone' => $this->user->getPhone(),
667
            'extra' => []
668
        ];
669
670
        $fieldValue = new ExtraFieldValue('user');
671
        $extraInfo = $fieldValue->getAllValuesForAnItem($this->user->getId(), true);
672
673
        foreach ($extraInfo as $extra) {
674
            /** @var ExtraFieldValues $extraValue */
675
            $extraValue = $extra['value'];
676
677
            $result['extra'][] = [
678
                'title' => $extraValue->getField()->getDisplayText(true),
679
                'value' => $extraValue->getValue()
0 ignored issues
show
Bug introduced by
The method getValue() does not exist on Chamilo\CoreBundle\Entity\ExtraFieldValues. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

679
                'value' => $extraValue->/** @scrutinizer ignore-call */ getValue()

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
680
            ];
681
        }
682
683
        return $result;
684
    }
685
686
    /**
687
     * @return array
688
     * @throws Exception
689
     */
690
    public function getCourseLearnPaths()
691
    {
692
        $sessionId = $this->session ? $this->session->getId() : 0;
693
        $categoriesTempList = learnpath::getCategories($this->course->getId());
694
695
        $categoryNone = new CLpCategory();
696
        $categoryNone->setId(0);
697
        $categoryNone->setName(get_lang('WithOutCategory'));
698
        $categoryNone->setPosition(0);
699
700
        $categories = array_merge([$categoryNone], $categoriesTempList);
701
        $categoryData = [];
702
703
        /** @var CLpCategory $category */
704
        foreach ($categories as $category) {
705
            $learnPathList = new LearnpathList(
706
                $this->user->getId(),
707
                $this->course->getCode(),
708
                $sessionId,
709
                null,
710
                false,
711
                $category->getId()
712
            );
713
714
            $flatLpList = $learnPathList->get_flat_list();
715
716
            if (empty($flatLpList)) {
717
                continue;
718
            }
719
720
            $listData = [];
721
722
            foreach ($flatLpList as $lpId => $lpDetails) {
723
                if ($lpDetails['lp_visibility'] == 0) {
724
                    continue;
725
                }
726
727
                if (!learnpath::is_lp_visible_for_student(
728
                    $lpId,
729
                    $this->user->getId(),
730
                    $this->course->getCode(),
731
                    $sessionId
732
                )) {
733
                    continue;
734
                }
735
736
                $timeLimits = false;
737
738
                // This is an old LP (from a migration 1.8.7) so we do nothing
739
                if (empty($lpDetails['created_on']) && empty($lpDetails['modified_on'])) {
740
                    $timeLimits = false;
741
                }
742
743
                // Checking if expired_on is ON
744
                if (!empty($lpDetails['expired_on'])) {
745
                    $timeLimits = true;
746
                }
747
748
                if ($timeLimits) {
749
                    if (!empty($lpDetails['publicated_on']) && !empty($lpDetails['expired_on'])) {
750
                        $startTime = api_strtotime($lpDetails['publicated_on'], 'UTC');
751
                        $endTime = api_strtotime($lpDetails['expired_on'], 'UTC');
752
                        $now = time();
753
                        $isActivedTime = false;
754
755
                        if ($now > $startTime && $endTime > $now) {
756
                            $isActivedTime = true;
757
                        }
758
759
                        if (!$isActivedTime) {
760
                            continue;
761
                        }
762
                    }
763
                }
764
765
                $progress = learnpath::getProgress($lpId, $this->user->getId(), $this->course->getId(), $sessionId);
766
767
                $listData[] = [
768
                    'id' => $lpId,
769
                    'title' => Security::remove_XSS($lpDetails['lp_name']),
770
                    'progress' => intval($progress),
771
                    'url' => api_get_path(WEB_CODE_PATH).'webservices/api/v2.php?'.http_build_query([
772
                        'hash' => $this->encodeParams([
773
                            'action' => 'course_learnpath',
774
                            'lp_id' => $lpId,
775
                            'course' => $this->course->getId(),
776
                            'session' => $sessionId
777
                        ])
778
                    ])
779
                ];
780
            }
781
782
            if (empty($listData)) {
783
                continue;
784
            }
785
786
            $categoryData[] = [
787
                'id' => $category->getId(),
788
                'name' => $category->getName(),
789
                'learnpaths' => $listData
790
            ];
791
        }
792
793
        return $categoryData;
794
    }
795
796
    /**
797
     * @param array $additionalParams Optional
798
     * @return string
799
     */
800
    private function encodeParams(array $additionalParams = [])
801
    {
802
        $params = array_merge($additionalParams, [
803
            'api_key' => $this->apiKey,
804
            'username' => $this->user->getUsername(),
805
        ]);
806
807
        $strParams = serialize($params);
808
        $b64Encoded = base64_encode($strParams);
809
810
        return str_replace(['+', '/', '='], ['-', '_', '.'], $b64Encoded);
811
    }
812
813
    /**
814
     * @param string $encoded
815
     * @return array
816
     */
817
    public static function decodeParams($encoded)
818
    {
819
        $decoded = str_replace(['-', '_', '.'], ['+', '/', '='], $encoded);
820
        $mod4 = strlen($decoded) % 4;
821
822
        if ($mod4) {
823
            $decoded .= substr('====', $mod4);
824
        }
825
826
        $b64Decoded = base64_decode($decoded);
827
828
        return unserialize($b64Decoded);
829
    }
830
831
    /**
832
     * Start login for a user. Then make a redirect to show the learnpath
833
     * @param int $lpId
834
     */
835
    public function showLearningPath($lpId)
836
    {
837
        $loggedUser['user_id'] = $this->user->getId();
0 ignored issues
show
Comprehensibility Best Practice introduced by
$loggedUser was never initialized. Although not strictly required by PHP, it is generally a good practice to add $loggedUser = array(); before regardless.
Loading history...
838
        $loggedUser['status'] = $this->user->getStatus();
839
        $loggedUser['uidReset'] = true;
840
        $sessionId = $this->session ? $this->session->getId() : 0;
841
842
        ChamiloSession::write('_user', $loggedUser);
843
        Login::init_user($this->user->getId(), true);
844
845
        $url = api_get_path(WEB_CODE_PATH).'lp/lp_controller.php?'.http_build_query([
846
            'cidReq' => $this->course->getCode(),
847
            'id_session' => $sessionId,
848
            'gidReq' => 0,
849
            'gradebook' => 0,
850
            'origin' => '',
851
            'action' => 'view',
852
            'lp_id' => intval($lpId),
853
            'isStudentView' => 'true'
854
        ]);
855
856
        header("Location: $url");
857
        exit;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
858
    }
859
860
    /**
861
     * @param array $postValues
862
     * @param int $forumId
863
     * @return array
864
     */
865
    public function saveForumPost(array $postValues, $forumId)
866
    {
867
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
868
869
        $forum = get_forums($forumId, $this->course->getCode());
870
        store_reply($forum, $postValues, $this->course->getId(), $this->user->getId());
871
872
        return [
873
            'registered' => true
874
        ];
875
    }
876
877
    /**
878
     * Get the list of sessions for current user
879
     * @return array the sessions list
880
     */
881
    public function getUserSessions()
882
    {
883
        $data = [];
884
        $sessionsByCategory = UserManager::get_sessions_by_category($this->user->getId(), false);
885
886
        foreach ($sessionsByCategory as $category) {
887
            $categorySessions = [];
888
889
            foreach ($category['sessions'] as $sessions) {
890
                $sessionCourses = [];
891
892
                foreach ($sessions['courses'] as $course) {
893
                    $courseInfo = api_get_course_info_by_id($course['real_id']);
894
                    $teachers = SessionManager::getCoachesByCourseSessionToString(
895
                        $sessions['session_id'],
896
                        $course['real_id']
897
                    );
898
899
                    $sessionCourses[] = [
900
                        'id' => $courseInfo['real_id'],
901
                        'title' => $courseInfo['title'],
902
                        'code' => $courseInfo['code'],
903
                        'directory' => $courseInfo['directory'],
904
                        'pictureUrl' => $courseInfo['course_image_large'],
905
                        'teachers' => $teachers
906
                    ];
907
                }
908
909
                $sessionBox = Display::get_session_title_box($sessions['session_id']);
910
911
                $categorySessions[] = [
912
                    'name' => $sessionBox['title'],
913
                    'id' => $sessions['session_id'],
914
                    'date' => $sessionBox['dates'],
915
                    'duration' => isset($sessionBox['duration']) ? $sessionBox['duration'] : null,
916
                    'courses' => $sessionCourses
917
                ];
918
            }
919
920
            $data[] = [
921
                'id' => $category['session_category']['id'],
922
                'name' => $category['session_category']['name'],
923
                'sessions' => $categorySessions
924
            ];
925
        }
926
927
        return $data;
928
    }
929
930
    /**
931
     * @param string $subject
932
     * @param string $text
933
     * @param array $receivers
934
     * @return array
935
     */
936
    public function saveUserMessage($subject, $text, array $receivers)
937
    {
938
        foreach ($receivers as $userId) {
939
            MessageManager::send_message($userId, $subject, $text);
940
        }
941
942
        return [
943
            'sent' => true
944
        ];
945
    }
946
947
    /**
948
     * @param string $search
949
     * @return array
950
     */
951
    public function getMessageUsers($search)
952
    {
953
        /** @var UserRepository $repo */
954
        $repo = Database::getManager()->getRepository('ChamiloUserBundle:User');
955
956
        $users = $repo->findUsersToSendMessage($this->user->getId(), $search);
957
958
        $showEmail = api_get_setting('show_email_addresses') === 'true';
959
        $data = [];
960
961
        /** @var User $user */
962
        foreach ($users as $user) {
963
            $userName = $user->getCompleteName();
964
965
            if ($showEmail) {
966
                $userName .= " ({$user->getEmail()})";
967
            }
968
969
            $data[] = [
970
                'id' => $user->getId(),
971
                'name' => $userName,
972
            ];
973
        }
974
975
        return $data;
976
    }
977
978
    /**
979
     * @param string $title
980
     * @param string $text
981
     * @return array
982
     */
983
    public function saveCourseNotebook($title, $text)
984
    {
985
        $values = ['note_title' => $title, 'note_comment' => $text];
986
        $sessionId = $this->session ? $this->session->getId() : 0;
987
988
        $noteBookId = NotebookManager::save_note(
989
            $values,
990
            $this->user->getId(),
991
            $this->course->getId(),
992
            $sessionId
993
        );
994
995
        return [
996
            'registered' => $noteBookId
997
        ];
998
    }
999
1000
    /**
1001
     * @param array $values
1002
     * @param int $forumId
1003
     * @return array
1004
     */
1005
    public function saveForumThread(array $values, $forumId)
1006
    {
1007
        require_once api_get_path(SYS_CODE_PATH).'forum/forumfunction.inc.php';
1008
1009
        $sessionId = $this->session ? $this->session->getId() : 0;
1010
        $forum = get_forums($forumId, $this->course->getCode(), true, $sessionId);
1011
        $courseInfo = api_get_course_info($this->course->getCode());
1012
        $id = store_thread($forum, $values, $courseInfo, false, $this->user->getId(), $sessionId);
1013
1014
        return [
1015
            'registered' => $id
1016
        ];
1017
    }
1018
1019
    /**
1020
     * @param array $course_param
1021
     * @return array
1022
     */
1023
    public function addCourse($course_param)
1024
    {
1025
        $table_course = Database::get_main_table(TABLE_MAIN_COURSE);
1026
        $extra_list= [];
1027
1028
        $title = isset($course_param['title']) ? $course_param['title'] : '';
1029
        $category_code = isset($course_param['category_code']) ? $course_param['category_code'] : '';
1030
        $wanted_code = isset($course_param['wanted_code']) ? intval($course_param['wanted_code']) : 0;
1031
        $tutor_name = isset($course_param['tutor_name']) ? $course_param['tutor_name'] : '';
1032
        $admin_id = isset($course_param['admin_id']) ? $course_param['admin_id'] : null;
1033
        $language = isset($course_param['language']) ? $course_param['language'] : null;
1034
        $original_course_id = isset($course_param['original_course_id']) ? $course_param['original_course_id'] : null;
1035
        $diskQuota = isset($course_param['disk_quota']) ? $course_param['disk_quota'] : '100';
1036
        $visibility = isset($course_param['visibility']) ? (int) $course_param['visibility'] : null;
1037
1038
        if (isset($course_param['visibility'])) {
1039
            if ($course_param['visibility'] &&
1040
                $course_param['visibility'] >= 0 &&
1041
                $course_param['visibility'] <= 3
1042
            ) {
1043
                $visibility = (int) $course_param['visibility'];
1044
            }
1045
        }
1046
1047
        // Check whether exits $x_course_code into user_field_values table.
1048
        $courseInfo = CourseManager::getCourseInfoFromOriginalId(
1049
            'id',
1050
            $course_param['original_course_id_name']
1051
        );
1052
1053
        if (!empty($courseInfo)) {
1054
            if ($courseInfo['visibility'] != 0) {
1055
                $sql = "UPDATE $table_course SET
1056
                            course_language = '".Database::escape_string($course_language)."',
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $course_language seems to be never defined.
Loading history...
1057
                            title = '".Database::escape_string($title)."',
1058
                            category_code = '".Database::escape_string($category_code)."',
1059
                            tutor_name = '".Database::escape_string($tutor_name)."',
1060
                            visual_code = '".Database::escape_string($wanted_code)."'";
1061
                if ($visibility !== null) {
1062
                    $sql .= ", visibility = $visibility ";
1063
                }
1064
                $sql .= " WHERE id = ".$courseInfo['real_id'];
1065
                Database::query($sql);
1066
                if (is_array($extra_list) && count($extra_list) > 0) {
1067
                    foreach ($extra_list as $extra) {
1068
                        $extra_field_name = $extra['field_name'];
1069
                        $extra_field_value = $extra['field_value'];
1070
                        // Save the external system's id into course_field_value table.
1071
                        CourseManager::update_course_extra_field_value(
1072
                            $courseInfo['code'],
1073
                            $extra_field_name,
1074
                            $extra_field_value
1075
                        );
1076
                    }
1077
                }
1078
                $results[] = $courseInfo['code'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
$results was never initialized. Although not strictly required by PHP, it is generally a good practice to add $results = array(); before regardless.
Loading history...
1079
            } else {
1080
                $results[] = 0;
1081
            }
1082
        }
1083
1084
        if (!empty($course_param['course_language'])) {
1085
            $course_language = $course_param['course_language'];
1086
        }
1087
1088
        $params = [];
1089
        $params['title'] = $title;
1090
        $params['wanted_code'] = $wanted_code;
1091
        $params['category_code'] = $category_code;
1092
        $params['course_category'] = $category_code;
1093
        $params['tutor_name'] = $tutor_name;
1094
        $params['course_language'] = $course_language;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $course_language does not seem to be defined for all execution paths leading up to this point.
Loading history...
1095
        $params['user_id'] = $this->user->getId();
1096
        $params['visibility'] = $visibility;
1097
        $params['disk_quota'] = $diskQuota;
1098
1099
        if (isset($subscribe) && $subscribe != '') { // Valid values: 0, 1
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $subscribe seems to never exist and therefore isset should always be false.
Loading history...
1100
            $params['subscribe'] = $subscribe;
1101
        }
1102
        if (isset($unsubscribe) && $subscribe != '') { // Valid values: 0, 1
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $subscribe seems to be never defined.
Loading history...
Comprehensibility Best Practice introduced by
The variable $unsubscribe seems to never exist and therefore isset should always be false.
Loading history...
1103
            $params['unsubscribe'] = $unsubscribe;
1104
        }
1105
1106
        $course_info = CourseManager::create_course($params, $params['user_id']);
1107
1108
        if (!empty($course_info)) {
1109
            $course_code = $course_info['code'];
1110
1111
            // Save new field label into course_field table
1112
            CourseManager::create_course_extra_field(
1113
                $original_course_id_name,
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $original_course_id_name does not exist. Did you maybe mean $original_course_id?
Loading history...
1114
                1,
1115
                $original_course_id_name,
1116
                ''
1117
            );
1118
1119
            // Save the external system's id into user_field_value table.
1120
            CourseManager::update_course_extra_field_value(
1121
                $course_code,
1122
                $original_course_id_name,
1123
                $original_course_id_value
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $original_course_id_value does not exist. Did you maybe mean $original_course_id?
Loading history...
1124
            );
1125
1126
            if (is_array($extra_list) && count($extra_list) > 0) {
1127
                foreach ($extra_list as $extra) {
1128
                    $extra_field_name  = $extra['field_name'];
1129
                    $extra_field_value = $extra['field_value'];
1130
                    // Save new fieldlabel into course_field table.
1131
                    CourseManager::create_course_extra_field(
1132
                        $extra_field_name,
1133
                        1,
1134
                        $extra_field_name,
1135
                        ''
1136
                    );
1137
                    // Save the external system's id into course_field_value table.
1138
                    CourseManager::update_course_extra_field_value(
1139
                        $course_code,
1140
                        $extra_field_name,
1141
                        $extra_field_value
1142
                    );
1143
                }
1144
            }
1145
            $results[] = $course_code;
1146
        } else {
1147
            $results[] = 0;
1148
        }
1149
1150
        return $results;
1151
    }
1152
1153
    /**
1154
     * @param $user_param
1155
     * @return array
1156
     */
1157
    public function addUser($user_param)
1158
    {
1159
        $results = [];
1160
        $orig_user_id_value = [];
1161
        $userManager = UserManager::getManager();
1162
        $userRepository = UserManager::getRepository();
1163
1164
        $firstName = $user_param['firstname'];
1165
        $lastName = $user_param['lastname'];
1166
        $status = $user_param['status'];
1167
        $email = $user_param['email'];
1168
        $loginName = $user_param['loginname'];
1169
        $password = $user_param['password'];
1170
        $official_code = '';
1171
        $language = '';
1172
        $phone = '';
1173
        $picture_uri = '';
1174
        $auth_source = PLATFORM_AUTH_SOURCE;
1175
        $expiration_date = '';
1176
        $active = 1;
1177
        $hr_dept_id = 0;
1178
        $extra = null;
1179
        $original_user_id_name = $user_param['original_user_id_name'];
1180
        $original_user_id_value = $user_param['original_user_id_value'];
1181
        $orig_user_id_value[] = $user_param['original_user_id_value'];
1182
        $extra_list = $user_param['extra'];
1183
        if (!empty($user_param['language'])) {
1184
            $language = $user_param['language'];
1185
        }
1186
        if (!empty($user_param['phone'])) {
1187
            $phone = $user_param['phone'];
1188
        }
1189
        if (!empty($user_param['expiration_date'])) {
1190
            $expiration_date = $user_param['expiration_date'];
1191
        }
1192
1193
        // Default language.
1194
        if (empty($language)) {
1195
            $language = api_get_setting('platformLanguage');
1196
        }
1197
1198
        // First check wether the login already exists.
1199
        if (!UserManager::is_username_available($loginName)) {
1200
            $results[] = 0;
1201
        }
1202
1203
        $userId = UserManager::create_user(
1204
            $firstName,
1205
            $lastName,
1206
            $status,
1207
            $email,
1208
            $loginName,
1209
            $password,
1210
            $official_code,
1211
            $language,
1212
            $phone,
1213
            $picture_uri,
1214
            $auth_source,
1215
            $expiration_date,
1216
            $active,
1217
            $hr_dept_id
1218
        );
1219
1220
        if ($userId) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $userId of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
1221
            if (api_is_multiple_url_enabled()) {
1222
                if (api_get_current_access_url_id() != -1) {
1223
                    UrlManager::add_user_to_url(
1224
                        $userId,
1225
                        api_get_current_access_url_id()
1226
                    );
1227
                } else {
1228
                    UrlManager::add_user_to_url($userId, 1);
1229
                }
1230
            } else {
1231
                // We add by default the access_url_user table with access_url_id = 1
1232
                UrlManager::add_user_to_url($userId, 1);
1233
            }
1234
1235
            // Save new field label into user_field table.
1236
            UserManager::create_extra_field(
1237
                $original_user_id_name,
1238
                1,
1239
                $original_user_id_name,
1240
                ''
1241
            );
1242
            // Save the external system's id into user_field_value table.
1243
            UserManager::update_extra_field_value(
1244
                $userId,
1245
                $original_user_id_name,
1246
                $original_user_id_value
1247
            );
1248
1249
            if (is_array($extra_list) && count($extra_list) > 0) {
1250
                foreach ($extra_list as $extra) {
1251
                    $extra_field_name = $extra['field_name'];
1252
                    $extra_field_value = $extra['field_value'];
1253
                    // Save new field label into user_field table.
1254
                    UserManager::create_extra_field(
1255
                        $extra_field_name,
1256
                        1,
1257
                        $extra_field_name,
1258
                        ''
1259
                    );
1260
                    // Save the external system's id into user_field_value table.
1261
                    UserManager::update_extra_field_value(
1262
                        $userId,
1263
                        $extra_field_name,
1264
                        $extra_field_value
1265
                    );
1266
                }
1267
            }
1268
            $results[] = $userId;
1269
        } else {
1270
            $results[] = 0;
1271
        }
1272
1273
        return $results;
1274
    }
1275
1276
    /**
1277
     * Subscribe User to Course
1278
     * @param array $params
1279
     * @return array
1280
     */
1281
    public function subscribeUserToCourse($params)
1282
    {
1283
        $course_id = $params['course_id'];
1284
        $course_code = $params['course_code'];
1285
        $user_id = $params['user_id'];
1286
        if (!$course_id && !$course_code) {
1287
            return [false];
1288
        }
1289
        if (!$course_code) {
1290
            $course_code = CourseManager::get_course_code_from_course_id($course_id);
1291
        }
1292
        if (CourseManager::subscribe_user($user_id, $course_code)) {
1293
            return [true];
1294
        } else {
1295
            return [false];
1296
        }
1297
        return [true];
0 ignored issues
show
Unused Code introduced by
return array(true) is not reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
1298
    }
1299
}
1300