Completed
Push — master ( 371d59...f8efc0 )
by Julito
28:47
created

PageController   D

Complexity

Total Complexity 234

Size/Duplication

Total Lines 1450
Duplicated Lines 25.03 %

Coupling/Cohesion

Components 2
Dependencies 8

Importance

Changes 0
Metric Value
dl 363
loc 1450
rs 4.4102
c 0
b 0
f 0
wmc 234
lcom 2
cbo 8

24 Methods

Rating   Name   Duplication   Size   Complexity  
B setSessionBlock() 0 23 5
A setProfileBlock() 0 10 3
A setCourseSessionMenu() 0 17 1
A returnHelp() 9 21 3
A returnSkillsLinks() 7 19 4
A returnNotice() 0 19 3
A show_right_block() 0 14 3
A return_search_block() 16 16 2
B setUserImageBlock() 0 27 6
C setCourseBlock() 15 70 14
D getAnnouncements() 40 40 9
D returnHomePage() 0 41 10
A return_reservation_block() 0 15 3
B return_classes_block() 31 31 6
B return_exercise_block() 14 35 5
C return_teacher_link() 16 58 15
F return_courses_in_categories() 90 274 65
B returnMyCourseCategories() 35 35 3
B returnSpecialCourses() 29 29 4
A returnCourses() 0 58 4
D returnSessionsCategories() 17 171 32
D returnSessions() 44 243 27
A return_welcome_to_course_block() 0 17 2
B returnNavigationLinks() 0 16 5

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like PageController 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. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

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 PageController, and based on these observations, apply Extract Interface, too.

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
namespace Chamilo\CoreBundle\Framework;
5
6
use Pagerfanta\Adapter\FixedAdapter;
7
use Pagerfanta\Pagerfanta;
8
use Pagerfanta\View\TwitterBootstrapView;
9
use SystemAnnouncementManager;
10
use UserManager;
11
use CourseManager;
12
use ChamiloSession as Session;
13
use Display;
14
use Chamilo\CoreBundle\Framework\Container;
15
16
/**
17
 * Class PageController
18
 * Controller for pages presentation in general
19
 * @package chamilo.page.controller
20
 * @author Julio Montoya <[email protected]>
21
 *
22
 * @todo move functions in the Template class, remove this class.
23
 */
24
class PageController
25
{
26
    public $maxPerPage = 5;
27
28
    /**
29
     * Returns an HTML block with the user picture (as a link in a <div>)
30
     * @param int User ID (if not provided, will use the user ID from session)
31
     * @return string HTML div with a link to the user's profile
32
     * @uses UserManager::get_user_pictur_path_by_id() to get the image path
33
     * @uses UserManager::get_picture_user() to get the details of the image in a specific format
34
     * @uses PageController::show_right_block() to include the image in a larger user block
35
     */
36
    public function setUserImageBlock($user_id = null)
37
    {
38
        if (empty($user_id)) {
39
            $user_id = api_get_user_id();
40
        }
41
42
        //Always show the user image
43
        $img_array = UserManager::get_user_picture_path_by_id($user_id, 'web', true, true);
44
        $no_image  = false;
45
        if ($img_array['file'] == 'unknown.jpg') {
46
            $no_image = true;
47
        }
48
        $img_array       = UserManager::get_picture_user($user_id, $img_array['file'], 100, USER_IMAGE_SIZE_ORIGINAL);
49
        $profile_content = null;
50
        if (api_get_setting('social.allow_social_tool') == 'true') {
51
            if (!$no_image) {
52
                $profile_content .= '<a style="text-align:center" href="'.api_get_path(WEB_CODE_PATH).'social/home.php">
53
                                    <img src="'.$img_array['file'].'"></a>';
54
            } else {
55
                $profile_content .= '<a style="text-align:center"  href="'.Container::getRouter()->generate('fos_user_profile_edit').'">
56
                                    <img title="'.get_lang('EditProfile').'" src="'.$img_array['file'].'"></a>';
57
            }
58
        }
59
        if (!empty($profile_content)) {
60
            $this->show_right_block(null, null, 'user_image_block', array('content' => $profile_content));
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
61
        }
62
    }
63
64
    /**
65
     * Return a block with course-related links. The resulting HTML block's
66
     * contents are only based on the user defined by the active session.
67
     *
68
     * @return string HTML <div> with links
69
     */
70
    public function setCourseBlock($filter = null)
71
    {
72
        $show_course_link = false;
73
        $display_add_course_link = false;
74
75
        if ((api_get_setting('course.allow_users_to_create_courses') == 'true'
76
            && api_is_allowed_to_create_course() ||
77
            api_is_platform_admin())
78
        ) {
79
            $display_add_course_link = true;
80
        }
81
82
        if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create_course()) {
83
            $show_course_link = true;
84
        } else {
85
            if (api_get_setting('display.allow_students_to_browse_courses') ==
86
                'true') {
87
                $show_course_link = true;
88
            }
89
        }
90
91
        // My account section.
92
        $my_account_content = array();
93
94 View Code Duplication
        if ($display_add_course_link) {
95
            $my_account_content[] = array(
96
                'href'  => api_get_path(WEB_CODE_PATH).'create_course/add_course.php',
97
                'title' => api_get_setting('course.course_validation') ==
98
                'true' ? get_lang('CreateCourseRequest') : get_lang(
99
                    'CourseCreate'
100
                )
101
            );
102
        }
103
104
        // Sort courses.
105
        $url = api_get_path(WEB_CODE_PATH).'auth/courses.php?action=sortmycourses';
106
        $my_account_content[] = array(
107
            'href'  => $url,
108
            'title' => get_lang('SortMyCourses')
109
        );
110
111
        // Course management.
112
        if ($show_course_link) {
113
            if (!api_is_drh()) {
114
                $my_account_content[] = array(
115
                    'href'  => api_get_path(WEB_CODE_PATH).'auth/courses.php',
116
                    'title' => get_lang('CourseCatalog')
117
                );
118
119
                if (isset($filter) && $filter == 'history') {
120
                    $my_account_content[] = array(
121
                        'href'  => api_get_path(WEB_PUBLIC_PATH).'userportal',
122
                        'title' => get_lang('DisplayTrainingList')
123
                    );
124
                } else {
125
                    $my_account_content[] = array(
126
                        'href'  => api_get_path(WEB_PUBLIC_PATH).'userportal/history',
127
                        'title' => get_lang('HistoryTrainingSessions')
128
                    );
129
                }
130 View Code Duplication
            } else {
131
                $my_account_content[] = array(
132
                    'href'  => api_get_path(WEB_CODE_PATH).'dashboard/index.php',
133
                    'title' => get_lang('Dashboard')
134
                );
135
            }
136
        }
137
138
        $this->show_right_block(get_lang('Courses'), $my_account_content, 'course_block');
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
139
    }
140
141
    /**
142
     *
143
     */
144
    public function setSessionBlock()
145
    {
146
        $showSessionBlock = false;
147
148
        if (api_is_platform_admin()) {
149
            $showSessionBlock = true;
150
        }
151
152
        if (api_get_setting('session.allow_teachers_to_create_sessions') ==
153
            'true' && api_is_allowed_to_create_course()) {
154
            $showSessionBlock = true;
155
        }
156
157
        if ($showSessionBlock) {
158
            $content = array(
159
                array(
160
                    'href'  => api_get_path(WEB_CODE_PATH).'session/session_add.php',
161
                    'title' => get_lang('AddSession')
162
                )
163
            );
164
            $this->show_right_block(get_lang('Sessions'), $content, 'session_block');
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
165
        }
166
    }
167
168
    /**
169
     * Returns the profile block, showing links to the messaging and social
170
     * network tools. The user ID is taken from the active session
171
     * @return string HTML <div> block
172
     */
173
    public function setProfileBlock()
174
    {
175
        if (api_get_setting('message.allow_message_tool') == 'true') {
176
            if (api_get_setting('social.allow_social_tool') == 'true') {
177
                $this->show_right_block(get_lang('Profile'), array(), 'profile_social_block');
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
178
            } else {
179
                $this->show_right_block(get_lang('Profile'), array(), 'profile_block');
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
180
            }
181
        }
182
    }
183
184
    /**
185
     * Get the course - session menu
186
     */
187
    public function setCourseSessionMenu()
188
    {
189
        $courseURL             = Session::$urlGenerator->generate('userportal', array('type' => 'courses'));
190
        $sessionURL            = Session::$urlGenerator->generate('userportal', array('type' => 'sessions'));
191
        $courseCategoriesURL   = Session::$urlGenerator->generate('userportal', array('type' => 'mycoursecategories'));
192
        $specialCoursesURL     = Session::$urlGenerator->generate('userportal', array('type' => 'specialcourses'));
193
        $sessionCategoriesURL  = Session::$urlGenerator->generate('userportal', array('type' => 'sessioncategories'));
194
195
        $params = array(
196
            array('href' => $courseURL, 'title' => get_lang('Courses')),
197
            array('href' => $specialCoursesURL, 'title' => get_lang('SpecialCourses')),
198
            array('href' => $courseCategoriesURL, 'title' => get_lang('MyCourseCategories')),
199
            array('href' => $sessionURL, 'title' => get_lang('Sessions')),
200
            array('href' => $sessionCategoriesURL, 'title' => get_lang('SessionsCategories')),
201
        );
202
        $this->show_right_block(get_lang('CourseSessionBlock'), $params, 'course_session_block');
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
203
    }
204
205
    /**
206
     * Returns an online help block read from the home/home_menu_[lang].html
207
     * file
208
     * @return string HTML block
209
     */
210
    public function returnHelp()
211
    {
212
        $home                   = api_get_home_path();
213
        $user_selected_language = api_get_language_isocode();
214
        $sys_path               = api_get_path(SYS_PATH);
215
        $platformLanguage = api_get_setting('language.platform_language');
216
217
        if (!isset($user_selected_language)) {
218
            $user_selected_language = $platformLanguage;
219
        }
220
        $home_menu = @(string)file_get_contents($sys_path.$home.'home_menu_'.$user_selected_language.'.html');
221 View Code Duplication
        if (!empty($home_menu)) {
222
            $home_menu_content = api_to_system_encoding($home_menu, api_detect_encoding(strip_tags($home_menu)));
223
            $this->show_right_block(
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
224
                get_lang('MenuGeneral'),
225
                null,
226
                'help_block',
227
                array('content' => $home_menu_content)
228
            );
229
        }
230
    }
231
232
    /**
233
     * Returns an HTML block with links to the skills tools
234
     * @return string HTML <div> block
235
     */
236
    public function returnSkillsLinks()
237
    {
238
        if (api_get_setting('skill.allow_skills_tool') == 'true') {
239
            $content   = array();
240
            $content[] = array(
241
                'title' => get_lang('MySkills'),
242
                'href'  => api_get_path(WEB_CODE_PATH).'social/skills_wheel.php'
243
            );
244
245 View Code Duplication
            if (api_get_setting('skill.allow_hr_skills_management') == 'true'
246
                || api_is_platform_admin()) {
247
                $content[] = array(
248
                    'title' => get_lang('ManageSkills'),
249
                    'href'  => api_get_path(WEB_CODE_PATH).'admin/skills_wheel.php'
250
                );
251
            }
252
            $this->show_right_block(get_lang("Skills"), $content, 'skill_block');
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
253
        }
254
    }
255
256
    /**
257
     * Returns an HTML block with the notice, as found in the
258
     * home/home_notice_[lang].html file
259
     * @return string HTML <div> block
260
     */
261
    public function returnNotice()
262
    {
263
        $sys_path               = api_get_path(SYS_PATH);
264
        $user_selected_language = api_get_language_isocode();
265
        $home                   = api_get_home_path();
266
267
        // Notice
268
        $home_notice = @(string)file_get_contents($sys_path.$home.'home_notice_'.$user_selected_language.'.html');
269
        if (empty($home_notice)) {
270
            $home_notice = @(string)file_get_contents($sys_path.$home.'home_notice.html');
271
        }
272
273
        if (!empty($home_notice)) {
274
            $home_notice = api_to_system_encoding($home_notice, api_detect_encoding(strip_tags($home_notice)));
275
            $home_notice = Display::div($home_notice, array('class' => 'homepage_notice'));
276
277
            $this->show_right_block(get_lang('Notice'), null, 'notice_block', array('content' => $home_notice));
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
278
        }
279
    }
280
281
    /**
282
     * Returns the received content packaged in <div> block, with the title as
283
     * <h4>
284
     * @param string Title to include as h4
285
     * @param string Longer content to show (usually a <ul> list)
286
     * @param string ID to be added to the HTML attributes for the block
287
     * @param array Array of attributes to add to the HTML block
288
     * @return string HTML <div> block
289
     * @todo use the menu builder
290
     */
291
    public function show_right_block($title, $content, $id, $params = null)
292
    {
293
        if (!empty($id)) {
294
            $params['id'] = $id;
295
        }
296
        $block_menu = array(
297
            'id'       => $params['id'],
298
            'title'    => $title,
299
            'elements' => $content,
300
            'content'  => isset($params['content']) ? $params['content'] : null
301
        );
302
303
        //$app['template']->assign($id, $block_menu);
304
    }
305
306
307
    /**
308
     * Returns a content search form in an HTML <div>, pointing at the
309
     * main/search/ directory. If search_enabled is not set, then it returns
310
     * an empty string
311
     * @return string HTML <div> block showing the search form, or an empty string if search not enabled
312
     */
313 View Code Duplication
    public function return_search_block()
314
    {
315
        $html = '';
316
        if (api_get_setting('search.search_enabled') == 'true') {
317
            $html .= '<div class="searchbox">';
318
            $search_btn     = get_lang('Search');
319
            $search_content = '<br />
320
                <form action="main/search/" method="post">
321
                <input type="text" id="query" class="span2" name="query" value="" />
322
                <button class="save" type="submit" name="submit" value="'.$search_btn.'" />'.$search_btn.' </button>
323
                </form></div>';
324
            $html .= $this->show_right_block(get_lang('Search'), $search_content, 'search_block');
325
        }
326
327
        return $html;
328
    }
329
330
    /**
331
     * Returns a list of announcements
332
     * @param int User ID
333
     * @param bool True: show the announcements as a slider. False: show them as a vertical list
334
     * @return string HTML list of announcements
335
     */
336 View Code Duplication
    public function getAnnouncements($user_id = null, $show_slide = true)
337
    {
338
        // Display System announcements
339
        $hideAnnouncements = api_get_setting('hide_global_announcements_when_not_connected');
340
        if ($hideAnnouncements == 'true' && empty($user_id)) {
341
            return null;
342
        }
343
344
        $announcement = isset($_GET['announcement']) ? $_GET['announcement'] : null;
345
        $announcement = intval($announcement);
346
347
        if (!api_is_anonymous() && $user_id) {
348
            $visibility = api_is_allowed_to_create_course() ? SystemAnnouncementManager::VISIBLE_TEACHER : SystemAnnouncementManager::VISIBLE_STUDENT;
349
            if ($show_slide) {
350
                $announcements = SystemAnnouncementManager:: display_announcements_slider(
351
                    $visibility,
352
                    $announcement
353
                );
354
            } else {
355
                $announcements = SystemAnnouncementManager:: display_all_announcements(
356
                    $visibility,
357
                    $announcement
358
                );
359
            }
360
        } else {
361
            if ($show_slide) {
362
                $announcements = SystemAnnouncementManager:: display_announcements_slider(
363
                    SystemAnnouncementManager::VISIBLE_GUEST,
364
                    $announcement
365
                );
366
            } else {
367
                $announcements = SystemAnnouncementManager:: display_all_announcements(
368
                    SystemAnnouncementManager::VISIBLE_GUEST,
369
                    $announcement
370
                );
371
            }
372
        }
373
374
        return $announcements;
375
    }
376
377
    /**
378
     * Return the homepage, including announcements
379
     * @return string The portal's homepage as an HTML string
380
     */
381
    public function returnHomePage()
382
    {
383
        // Including the page for the news
384
        $html          = null;
385
        $home          = api_get_path(SYS_DATA_PATH).api_get_home_path();
386
        $home_top_temp = null;
387
388
        if (!empty($_GET['include']) && preg_match('/^[a-zA-Z0-9_-]*\.html$/', $_GET['include'])) {
389
            $open = @(string)file_get_contents(api_get_path(SYS_PATH).$home.$_GET['include']);
390
            $html = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
391
        } else {
392
            $user_selected_language = api_get_user_language();
393
394
            if (!file_exists($home.'home_news_'.$user_selected_language.'.html')) {
395
                if (file_exists($home.'home_top.html')) {
396
                    $home_top_temp = file($home.'home_top.html');
397
                } else {
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
398
                    //$home_top_temp = file('home/'.'home_top.html');
399
                }
400
                if (!empty($home_top_temp)) {
401
                    $home_top_temp = implode('', $home_top_temp);
402
                }
403
            } else {
404
                if (file_exists($home.'home_top_'.$user_selected_language.'.html')) {
405
                    $home_top_temp = file_get_contents($home.'home_top_'.$user_selected_language.'.html');
406
                } else {
407
                    $home_top_temp = file_get_contents($home.'home_top.html');
408
                }
409
            }
410
411
            if (empty($home_top_temp) && api_is_platform_admin()) {
412
                $home_top_temp = get_lang('PortalHomepageDefaultIntroduction');
413
            }
414
            $open = str_replace('{rel_path}', api_get_path(REL_PATH), $home_top_temp);
415
            if (!empty($open)) {
416
                $html = api_to_system_encoding($open, api_detect_encoding(strip_tags($open)));
417
            }
418
        }
419
420
        return $html;
421
    }
422
423
    /**
424
     * Returns the reservation block (if the reservation tool is enabled)
425
     * @return string HTML block, or empty string if reservation tool is disabled
426
     */
427
    public function return_reservation_block()
428
    {
429
        $html            = '';
430
        $booking_content = null;
431
        if (api_get_setting('allow_reservation') == 'true' && api_is_allowed_to_create_course()) {
432
            $booking_content .= '<ul class="nav nav-list">';
433
            $booking_content .= '<a href="main/reservation/reservation.php">'.get_lang(
434
                'ManageReservations'
435
            ).'</a><br />';
436
            $booking_content .= '</ul>';
437
            $html .= $this->show_right_block(get_lang('Booking'), $booking_content, 'reservation_block');
438
        }
439
440
        return $html;
441
    }
442
443
    /**
444
     * Returns an HTML block with classes (if show_groups_to_users is true)
445
     * @return string A list of links to users classes tools, or an empty string if show_groups_to_users is disabled
446
     */
447 View Code Duplication
    public function return_classes_block()
448
    {
449
        $html = '';
450
        if (api_get_setting('show_groups_to_users') == 'true') {
451
            $usergroup      = new Usergroup();
452
            $usergroup_list = $usergroup->get_usergroup_by_user(api_get_user_id());
453
            $classes        = '';
454
            if (!empty($usergroup_list)) {
455
                foreach ($usergroup_list as $group_id) {
456
                    $data         = $usergroup->get($group_id);
457
                    $data['name'] = Display::url(
458
                        $data['name'],
459
                        api_get_path(WEB_CODE_PATH).'user/classes.php?id='.$data['id']
460
                    );
461
                    $classes .= Display::tag('li', $data['name']);
462
                }
463
            }
464
            if (api_is_platform_admin()) {
465
                $classes .= Display::tag(
466
                    'li',
467
                    Display::url(get_lang('AddClasses'), api_get_path(WEB_CODE_PATH).'admin/usergroups.php?action=add')
468
                );
469
            }
470
            if (!empty($classes)) {
471
                $classes = Display::tag('ul', $classes, array('class' => 'nav nav-list'));
472
                $html .= $this->show_right_block(get_lang('Classes'), $classes, 'classes_block');
473
            }
474
        }
475
476
        return $html;
477
    }
478
479
    /**
480
     * Prepares a block with all the pending exercises in all courses
481
     * @param array Array of courses (arrays) of the user
482
     * @return void Doesn't return anything but prepares and HTML block for use in templates
483
     */
484
    public function return_exercise_block($personal_course_list, $tpl)
485
    {
486
        $exercise_list = array();
487
        if (!empty($personal_course_list)) {
488 View Code Duplication
            foreach ($personal_course_list as $course_item) {
489
                $course_code = $course_item['c'];
490
                $session_id  = $course_item['id_session'];
491
492
                $exercises = ExerciseLib::get_exercises_to_be_taken($course_code, $session_id);
493
494
                foreach ($exercises as $exercise_item) {
495
                    $exercise_item['course_code'] = $course_code;
496
                    $exercise_item['session_id']  = $session_id;
497
                    $exercise_item['tms']         = api_strtotime($exercise_item['end_time'], 'UTC');
498
499
                    $exercise_list[] = $exercise_item;
500
                }
501
            }
502
            if (!empty($exercise_list)) {
503
                $exercise_list = ArrayClass::msort($exercise_list, 'tms');
504
                $my_exercise   = $exercise_list[0];
505
                $url           = Display::url(
506
                    $my_exercise['title'],
507
                    api_get_path(
508
                        WEB_CODE_PATH
509
                    ).'exercise/overview.php?exerciseId='.$my_exercise['id'].'&cidReq='.$my_exercise['course_code'].'&id_session='.$my_exercise['session_id']
510
                );
511
                $tpl->assign('exercise_url', $url);
512
                $tpl->assign(
513
                    'exercise_end_date',
514
                    api_convert_and_format_date($my_exercise['end_time'], DATE_FORMAT_SHORT)
515
                );
516
            }
517
        }
518
    }
519
520
    /**
521
     * Returns links to teachers tools (create course, etc) based on the user
522
     * in the active session
523
     * @return string HTML <div> block
524
     */
525
    public function return_teacher_link()
526
    {
527
        $user_id = api_get_user_id();
528
529
        if (!empty($user_id)) {
530
            // tabs that are deactivated are added here
531
532
            $show_menu        = false;
533
            $show_create_link = false;
534
            $show_course_link = false;
535
536
            if (api_is_platform_admin() || api_is_course_admin() || api_is_allowed_to_create_course()) {
537
                $show_menu        = true;
538
                $show_course_link = true;
539
            } else {
540
                if (api_get_setting('display.allow_students_to_browse_courses') == 'true') {
541
                    $show_menu        = true;
542
                    $show_course_link = true;
543
                }
544
            }
545
546
            if ($show_menu && ($show_create_link || $show_course_link)) {
547
                $show_menu = true;
548
            } else {
549
                $show_menu = false;
550
            }
551
        }
552
553
        // My Account section
554
        $elements = array();
555
        if ($show_menu) {
556 View Code Duplication
            if ($show_create_link) {
557
                $elements[] = array(
558
                    'href'  => api_get_path(WEB_CODE_PATH).'create_course/add_course.php',
559
                    'title' => (api_get_setting(
560
                        'course.course_validation'
561
                    ) == 'true' ? get_lang(
562
                        'CreateCourseRequest'
563
                    ) : get_lang('CourseCreate'))
564
                );
565
            }
566
567
            if ($show_course_link) {
568
                if (!api_is_drh() && !api_is_session_admin()) {
569
                    $elements[] = array(
570
                        'href'  => api_get_path(WEB_CODE_PATH).'auth/courses.php',
571
                        'title' => get_lang('CourseCatalog')
572
                    );
573 View Code Duplication
                } else {
574
                    $elements[] = array(
575
                        'href'  => api_get_path(WEB_CODE_PATH).'dashboard/index.php',
576
                        'title' => get_lang('Dashboard')
577
                    );
578
                }
579
            }
580
        }
581
        $this->show_right_block(get_lang('Courses'), $elements, 'teacher_block');
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
582
    }
583
584
    /**
585
     * Display list of courses in a category.
586
     * (for anonymous users)
587
     *
588
     * @version 1.1
589
     * @author Patrick Cool <[email protected]>, Ghent University - refactoring and code cleaning
590
     * @author Julio Montoya <[email protected]>, Beeznest template modifs
591
     */
592
    public function return_courses_in_categories()
593
    {
594
        $result = '';
595
        $stok   = Security::get_token();
596
597
        // Initialization.
598
        $user_identified                  = (api_get_user_id() > 0 && !api_is_anonymous());
599
        $web_course_path                  = api_get_path(WEB_COURSE_PATH);
600
        $category                         = Database::escape_string($_GET['category']);
601
        $setting_show_also_closed_courses = api_get_setting('show_closed_courses') == 'true';
602
603
        // Database table definitions.
604
        $main_course_table   = Database :: get_main_table(TABLE_MAIN_COURSE);
605
        $main_category_table = Database :: get_main_table(TABLE_MAIN_CATEGORY);
606
607
        // Get list of courses in category $category.
608
        $sql_get_course_list = "SELECT * FROM $main_course_table cours
609
                                    WHERE category_code = '".Database::escape_string($_GET['category'])."'
610
                                    ORDER BY title, UPPER(visual_code)";
611
612
        // Showing only the courses of the current access_url_id.
613
        if (api_is_multiple_url_enabled()) {
614
            $url_access_id = api_get_current_access_url_id();
615
            if ($url_access_id != -1) {
616
                $tbl_url_rel_course  = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
617
                $sql_get_course_list = "SELECT * FROM $main_course_table as course INNER JOIN $tbl_url_rel_course as url_rel_course
618
                        ON (url_rel_course.c_id = course.id)
619
                        WHERE access_url_id = $url_access_id AND category_code = '".Database::escape_string(
620
                    $_GET['category']
621
                )."' ORDER BY title, UPPER(visual_code)";
622
            }
623
        }
624
625
        // Removed: AND cours.visibility='".COURSE_VISIBILITY_OPEN_WORLD."'
626
        $sql_result_courses = Database::query($sql_get_course_list);
627
628
        while ($course_result = Database::fetch_array($sql_result_courses)) {
629
            $course_list[] = $course_result;
630
        }
631
632
        $platform_visible_courses = '';
633
        // $setting_show_also_closed_courses
634 View Code Duplication
        if ($user_identified) {
635
            if ($setting_show_also_closed_courses) {
636
                $platform_visible_courses = '';
637
            } else {
638
                $platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' OR t3.visibility='".COURSE_VISIBILITY_OPEN_PLATFORM."' )";
639
            }
640
        } else {
641
            if ($setting_show_also_closed_courses) {
642
                $platform_visible_courses = '';
643
            } else {
644
                $platform_visible_courses = "  AND (t3.visibility='".COURSE_VISIBILITY_OPEN_WORLD."' )";
645
            }
646
        }
647
        $sqlGetSubCatList = "
648
                    SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
649
                    FROM $main_category_table t1
650
                    LEFT JOIN $main_category_table t2 ON t1.code=t2.parent_id
651
                    LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
652
                    WHERE t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
653
                    GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
654
655
656
        // Showing only the category of courses of the current access_url_id
657
        if (api_is_multiple_url_enabled()) {
658
            $url_access_id = api_get_current_access_url_id();
659 View Code Duplication
            if ($url_access_id != -1) {
660
                $tbl_url_rel_course = Database::get_main_table(TABLE_MAIN_ACCESS_URL_REL_COURSE);
661
                $sqlGetSubCatList   = "
662
                    SELECT t1.name,t1.code,t1.parent_id,t1.children_count,COUNT(DISTINCT t3.code) AS nbCourse
663
                    FROM $main_category_table t1
664
                    LEFT JOIN $main_category_table t2 ON t1.code=t2.parent_id
665
                    LEFT JOIN $main_course_table t3 ON (t3.category_code=t1.code $platform_visible_courses)
666
                    INNER JOIN $tbl_url_rel_course as url_rel_course
667
                        ON (url_rel_course.c_id = t3.id)
668
                    WHERE access_url_id = $url_access_id AND t1.parent_id ".(empty($category) ? "IS NULL" : "='$category'")."
669
                    GROUP BY t1.name,t1.code,t1.parent_id,t1.children_count ORDER BY t1.tree_pos, t1.name";
670
            }
671
        }
672
673
        $resCats       = Database::query($sqlGetSubCatList);
674
        $thereIsSubCat = false;
675
        if (Database::num_rows($resCats) > 0) {
676
            $htmlListCat = Display::page_header(get_lang('CatList'));
677
            $htmlListCat .= '<ul>';
678
            while ($catLine = Database::fetch_array($resCats)) {
679
                if ($catLine['code'] != $category) {
680
                    $category_has_open_courses = $this->category_has_open_courses($catLine['code']);
681 View Code Duplication
                    if ($category_has_open_courses) {
682
                        // The category contains courses accessible to anonymous visitors.
683
                        $htmlListCat .= '<li>';
684
                        $htmlListCat .= '<a href="'.api_get_self(
685
                        ).'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
686
                        if (api_get_setting('show_number_of_courses') == 'true') {
687
                            $htmlListCat .= ' ('.$catLine['nbCourse'].' '.get_lang('Courses').')';
688
                        }
689
                        $htmlListCat .= "</li>";
690
                        $thereIsSubCat = true;
691
                    } elseif ($catLine['children_count'] > 0) {
692
                        // The category has children, subcategories.
693
                        $htmlListCat .= '<li>';
694
                        $htmlListCat .= '<a href="'.api_get_self(
695
                        ).'?category='.$catLine['code'].'">'.$catLine['name'].'</a>';
696
                        $htmlListCat .= "</li>";
697
                        $thereIsSubCat = true;
698
                    } elseif (api_get_setting('show_empty_course_categories') == 'true') {
699
                        /* End changed code to eliminate the (0 courses) after empty categories. */
700
                        $htmlListCat .= '<li>';
701
                        $htmlListCat .= $catLine['name'];
702
                        $htmlListCat .= "</li>";
703
                        $thereIsSubCat = true;
704
                    } // Else don't set thereIsSubCat to true to avoid printing things if not requested.
705
                } else {
706
                    $htmlTitre = '<p>';
707 View Code Duplication
                    if (api_get_setting('show_back_link_on_top_of_tree') == 'true') {
708
                        $htmlTitre .= '<a href="'.api_get_self().'">&lt;&lt; '.get_lang('BackToHomePage').'</a>';
709
                    }
710
                    if (!is_null($catLine['parent_id']) ||
711
                        (api_get_setting('show_back_link_on_top_of_tree') != 'true' &&
712
                        !is_null($catLine['code']))
713
                    ) {
714
                        $htmlTitre .= '<a href="'.api_get_self(
715
                        ).'?category='.$catLine['parent_id'].'">&lt;&lt; '.get_lang('Up').'</a>';
716
                    }
717
                    $htmlTitre .= "</p>";
718 View Code Duplication
                    if ($category != "" && !is_null($catLine['code'])) {
719
                        $htmlTitre .= '<h3>'.$catLine['name']."</h3>";
720
                    } else {
721
                        $htmlTitre .= '<h3>'.get_lang('Categories')."</h3>";
722
                    }
723
                }
724
            }
725
            $htmlListCat .= "</ul>";
726
        }
727
        $result .= $htmlTitre;
728
        if ($thereIsSubCat) {
729
            $result .= $htmlListCat;
730
        }
731
        while ($categoryName = Database::fetch_array($resCats)) {
732
            $result .= '<h3>'.$categoryName['name']."</h3>\n";
733
        }
734
        $numrows             = Database::num_rows($sql_result_courses);
735
        $courses_list_string = '';
736
        $courses_shown       = 0;
737
        if ($numrows > 0) {
738
739
            $courses_list_string .= Display::page_header(get_lang('CourseList'));
740
            $courses_list_string .= "<ul>";
741
742
            if (api_get_user_id()) {
743
                $courses_of_user = $this->get_courses_of_user(api_get_user_id());
744
            }
745
746
            foreach ($course_list as $course) {
747
                // $setting_show_also_closed_courses
748
                if (!$setting_show_also_closed_courses) {
749
                    // If we do not show the closed courses
750
                    // we only show the courses that are open to the world (to everybody)
751
                    // and the courses that are open to the platform (if the current user is a registered user.
752
                    if (($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM) || ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)) {
753
                        $courses_shown++;
754
                        $courses_list_string .= "<li>\n";
755
                        $courses_list_string .= '<a href="'.$web_course_path.$course['directory'].'/">'.$course['title'].'</a><br />';
756
                        $course_details = array();
757
                        if (api_get_setting('course.display_coursecode_in_courselist') ==
758
                            'true') {
759
                            $course_details[] = $course['visual_code'];
760
                        }
761
                        if (api_get_setting('course.display_teacher_in_courselist') ==
762
                            'true') {
763
                            $course_details[] = $course['tutor_name'];
764
                        }
765
                        if (api_get_setting('display.show_different_course_language') ==
766
                            'true' && $course['course_language'] != api_get_setting(
767
                                'language.platform_language'
768
                            )
769
                        ) {
770
                            $course_details[] = $course['course_language'];
771
                        }
772
                        $courses_list_string .= implode(' - ', $course_details);
773
                        $courses_list_string .= "</li>\n";
774
                    }
775
                } else {
776
                    // We DO show the closed courses.
777
                    // The course is accessible if (link to the course homepage):
778
                    // 1. the course is open to the world (doesn't matter if the user is logged in or not): $course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD);
779
                    // 2. the user is logged in and the course is open to the world or open to the platform: ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM);
780
                    // 3. the user is logged in and the user is subscribed to the course and the course visibility is not COURSE_VISIBILITY_CLOSED;
781
                    // 4. the user is logged in and the user is course admin of te course (regardless of the course visibility setting);
782
                    // 5. the user is the platform admin api_is_platform_admin().
783
                    //
784
                    $courses_shown++;
785
                    $courses_list_string .= "<li>\n";
786 View Code Duplication
                    if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
787
                        || ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
788
                        || ($user_identified && key_exists(
789
                            $course['code'],
790
                            $courses_of_user
791
                        ) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
792
                        || $courses_of_user[$course['code']]['status'] == '1'
793
                        || api_is_platform_admin()
794
                    ) {
795
                        $courses_list_string .= '<a href="'.$web_course_path.$course['directory'].'/">';
796
                    }
797
                    $courses_list_string .= $course['title'];
798 View Code Duplication
                    if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD
799
                        || ($user_identified && $course['visibility'] == COURSE_VISIBILITY_OPEN_PLATFORM)
800
                        || ($user_identified && key_exists(
801
                            $course['code'],
802
                            $courses_of_user
803
                        ) && $course['visibility'] != COURSE_VISIBILITY_CLOSED)
804
                        || $courses_of_user[$course['code']]['status'] == '1'
805
                        || api_is_platform_admin()
806
                    ) {
807
                        $courses_list_string .= '</a><br />';
808
                    }
809
                    $course_details = array();
810
                    if (api_get_setting('course.display_coursecode_in_courselist') == 'true') {
811
                        $course_details[] = $course['visual_code'];
812
                    }
813
                    if (api_get_setting('course.display_teacher_in_courselist') == 'true') {
814
                        $course_details[] = $course['tutor_name'];
815
                    }
816
                    if (api_get_setting(
817
                            'display.show_different_course_language'
818
                        ) == 'true' && $course['course_language'] != api_get_setting(
819
                            'language.platform_language'
820
                        )
821
                    ) {
822
                        $course_details[] = $course['course_language'];
823
                    }
824 View Code Duplication
                    if (api_get_setting(
825
                        'show_different_course_language'
826
                        ) == 'true' && $course['course_language'] != api_get_setting(
827
                            'language.platform_language'
828
                        )
829
                    ) {
830
                        $course_details[] = $course['course_language'];
831
                    }
832
833
                    $courses_list_string .= implode(' - ', $course_details);
834
                    // We display a subscription link if:
835
                    // 1. it is allowed to register for the course and if the course is not already in the courselist of the user and if the user is identiefied
836
                    // 2.
837
                    if ($user_identified && !array_key_exists($course['code'], $courses_of_user)) {
838
                        if ($course['subscribe'] == '1') {
839
                            $courses_list_string .= '<form action="main/auth/courses.php?action=subscribe&category='.Security::remove_XSS(
840
                                $_GET['category']
841
                            ).'" method="post">';
842
                            $courses_list_string .= '<input type="hidden" name="sec_token" value="'.$stok.'">';
843
                            $courses_list_string .= '<input type="hidden" name="subscribe" value="'.$course['code'].'" />';
844
                            $courses_list_string .= '<input type="image" name="unsub" src="'.api_get_path(WEB_IMG_PATH).'enroll.gif" alt="'.get_lang('Subscribe').'" />'.get_lang('Subscribe').'
845
                            </form>';
846
                        } else {
847
                            $courses_list_string .= '<br />'.get_lang('SubscribingNotAllowed');
848
                        }
849
                    }
850
                    $courses_list_string .= "</li>";
851
                } //end else
852
            } // end foreach
853
            $courses_list_string .= "</ul>";
854
        }
855
        if ($courses_shown > 0) {
856
            // Only display the list of courses and categories if there was more than
857
            // 0 courses visible to the world (we're in the anonymous list here).
858
            $result .= $courses_list_string;
859
        }
860 View Code Duplication
        if ($category != '') {
861
            $result .= '<p><a href="'.api_get_self().'"> '.Display :: return_icon('back.png', get_lang('BackToHomePage')).get_lang('BackToHomePage').'</a></p>';
862
        }
863
864
        return $result;
865
    }
866
867
    /**
868
     * @param int $user_id
869
     * @param string $filter
870
     * @param int $page
871
     *
872
     * @return bool
873
     */
874 View Code Duplication
    public function returnMyCourseCategories($user_id, $filter, $page)
875
    {
876
        if (empty($user_id)) {
877
            return false;
878
        }
879
        $loadDirs = api_get_setting('document.show_documents_preview') == 'true' ? true : false;
880
        $start    = ($page - 1) * $this->maxPerPage;
881
882
        $nbResults = (int)CourseManager::displayPersonalCourseCategories($user_id, $filter, $loadDirs, true);
883
884
        $html = CourseManager::displayPersonalCourseCategories(
885
            $user_id,
886
            $filter,
887
            $loadDirs,
888
            false,
889
            $start,
890
            $this->maxPerPage
891
        );
892
893
        $adapter    = new FixedAdapter($nbResults, array());
894
        $pagerfanta = new Pagerfanta($adapter);
895
        $pagerfanta->setMaxPerPage($this->maxPerPage); // 10 by default
896
        $pagerfanta->setCurrentPage($page); // 1 by default
897
898
        $this->app['pagerfanta.view.router.name']   = 'userportal';
899
        $this->app['pagerfanta.view.router.params'] = array(
900
            'filter' => $filter,
901
            'type'   => 'courses',
902
            'page'   => $page
903
        );
904
        $this->app['template']->assign('pagination', $pagerfanta);
905
906
        return $html;
907
908
    }
909
910 View Code Duplication
    function returnSpecialCourses($user_id, $filter, $page)
911
    {
912
        if (empty($user_id)) {
913
            return false;
914
        }
915
916
        $loadDirs = api_get_setting('document.show_documents_preview') == 'true' ? true : false;
917
        $start    = ($page - 1) * $this->maxPerPage;
918
919
        $nbResults = CourseManager::displaySpecialCourses($user_id, $filter, $loadDirs, true);
920
921
        $html = CourseManager::displaySpecialCourses($user_id, $filter, $loadDirs, false, $start, $this->maxPerPage);
922
        if (!empty($html)) {
923
924
            $adapter    = new FixedAdapter($nbResults, array());
925
            $pagerfanta = new Pagerfanta($adapter);
926
            $pagerfanta->setMaxPerPage($this->maxPerPage); // 10 by default
927
            $pagerfanta->setCurrentPage($page); // 1 by default
928
            $this->app['pagerfanta.view.router.name']   = 'userportal';
929
            $this->app['pagerfanta.view.router.params'] = array(
930
                'filter' => $filter,
931
                'type'   => 'courses',
932
                'page'   => $page
933
            );
934
            $this->app['template']->assign('pagination', $pagerfanta);
935
        }
936
937
        return $html;
938
    }
939
940
    /**
941
    * The most important function here, prints the session and course list (user_portal.php)
942
    *
943
    * @param int $user_id
944
    * @param string $filter
945
    * @param int $page
946
    * @return string HTML list of sessions and courses
947
    *
948
    */
949
    public function returnCourses($user_id, $filter, $page)
950
    {
951
        if (empty($user_id)) {
952
            return false;
953
        }
954
955
        $loadDirs = api_get_setting('document.show_documents_preview') == 'true' ? true : false;
956
        $start = ($page - 1) * $this->maxPerPage;
957
958
        $nbResults = CourseManager::displayCourses(
959
            $user_id,
960
            $filter,
961
            $loadDirs,
962
            true
963
        );
964
965
        $html = CourseManager::displayCourses(
966
            $user_id,
967
            $filter,
968
            $loadDirs,
969
            false,
970
            $start,
971
            $this->maxPerPage
972
        );
973
974
        if (!empty($html)) {
975
            $adapter    = new FixedAdapter($nbResults, array());
976
            $pagerfanta = new Pagerfanta($adapter);
977
            $pagerfanta->setMaxPerPage($this->maxPerPage); // 10 by default
978
            $pagerfanta->setCurrentPage($page); // 1 by default
979
980
            /*
981
            Original pagination construction
982
            $view = new TwitterBootstrapView();
983
            $routeGenerator = function($page) use ($app, $filter) {
984
                return $app['url_generator']->generate('userportal', array(
985
                    'filter' => $filter,
986
                    'type' => 'courses',
987
                    'page' => $page)
988
                );
989
            };
990
            $pagination = $view->render($pagerfanta, $routeGenerator, array(
991
                'proximity' => 3,
992
            ));
993
            */
994
            //Pagination using the pagerfanta silex service provider
995
            /*$this->app['pagerfanta.view.router.name']   = 'userportal';
996
            $this->app['pagerfanta.view.router.params'] = array(
997
                'filter' => $filter,
998
                'type'   => 'courses',
999
                'page'   => $page
1000
            );
1001
            $this->app['template']->assign('pagination', $pagerfanta);*/
1002
            // {{ pagerfanta(my_pager, 'twitter_bootstrap3') }}
1003
        }
1004
1005
        return $html;
1006
    }
1007
1008
    public function returnSessionsCategories($user_id, $filter, $page)
1009
    {
1010
        if (empty($user_id)) {
1011
            return false;
1012
        }
1013
1014
        $load_history = (isset($filter) && $filter == 'history') ? true : false;
1015
1016
        $start = ($page - 1) * $this->maxPerPage;
1017
1018
        $nbResults = UserManager::getCategories($user_id, false, true, true);
1019
        $session_categories = UserManager::getCategories(
1020
            $user_id,
1021
            false,
1022
            false,
1023
            true,
1024
            $start,
1025
            $this->maxPerPage
1026
        );
1027
1028
        $html = null;
1029
        //Showing history title
1030
        if ($load_history) {
1031
            $html .= Display::page_subheader(get_lang('HistoryTrainingSession'));
1032
            if (empty($session_categories)) {
1033
                $html .= get_lang('YouDoNotHaveAnySessionInItsHistory');
1034
            }
1035
        }
1036
1037
        $load_directories_preview = api_get_setting('document.show_documents_preview') == 'true' ? true : false;
1038
        $sessions_with_category   = $html;
1039
1040
        if (isset($session_categories) && !empty($session_categories)) {
1041
            foreach ($session_categories as $session_category) {
1042
                $session_category_id = $session_category['session_category']['id'];
1043
1044
                // All sessions included in
1045
                $count_courses_session = 0;
1046
                $html_sessions = '';
1047
                foreach ($session_category['sessions'] as $session) {
1048
                    $session_id = $session['session_id'];
1049
1050
                    // Don't show empty sessions.
1051
                    if (count($session['courses']) < 1) {
1052
                        continue;
1053
                    }
1054
1055
                    $html_courses_session = '';
1056
                    $count                = 0;
1057
                    foreach ($session['courses'] as $course) {
1058
                        if (api_get_setting('session.hide_courses_in_sessions') == 'false') {
1059
                            $html_courses_session .= CourseManager::get_logged_user_course_html($course, $session_id);
1060
                        }
1061
                        $count_courses_session++;
1062
                        $count++;
1063
                    }
1064
1065
                    $params = array();
1066
                    if ($count > 0) {
1067
                        $params['icon'] = Display::return_icon(
1068
                            'window_list.png',
1069
                            $session['session_name'],
1070
                            array('id' => 'session_img_'.$session_id),
1071
                            ICON_SIZE_LARGE
1072
                        );
1073
1074
                        //Default session name
1075
                        $session_link   = $session['session_name'];
1076
                        $params['link'] = null;
1077
1078 View Code Duplication
                        if (api_get_setting('session.session_page_enabled') == 'true' && !api_is_drh()) {
1079
                            //session name with link
1080
                            $session_link = Display::tag(
1081
                                'a',
1082
                                $session['session_name'],
1083
                                array('href' => api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session_id)
1084
                            );
1085
                            $params['link'] = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session_id;
1086
                        }
1087
1088
                        $params['title'] = $session_link;
1089
1090
                        $moved_status = \SessionManager::get_session_change_user_reason(
1091
                            $session['moved_status']
1092
                        );
1093
                        $moved_status = isset($moved_status) && !empty($moved_status) ? ' ('.$moved_status.')' : null;
1094
1095
                        $params['subtitle'] = isset($session['coach_info']) ? $session['coach_info']['complete_name'] : null.$moved_status;
1096
                        $params['dates']    = $session['date_message'];
1097
1098 View Code Duplication
                        if (api_is_platform_admin()) {
1099
                            $params['right_actions'] = '<a href="'.api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session_id.'">'.Display::return_icon(
1100
                                'edit.png',
1101
                                get_lang('Edit'),
1102
                                array('align' => 'absmiddle'),
1103
                                ICON_SIZE_SMALL
1104
                            ).'</a>';
1105
                        }
1106
                        $html_sessions .= CourseManager::course_item_html($params, true).$html_courses_session;
1107
                    }
1108
                }
1109
1110
                if ($count_courses_session > 0) {
1111
                    $params = array();
1112
                    $params['icon'] = Display::return_icon(
1113
                        'folder_blue.png',
1114
                        $session_category['session_category']['name'],
1115
                        array(),
1116
                        ICON_SIZE_LARGE
1117
                    );
1118
1119
                    if (api_is_platform_admin()) {
1120
                        $params['right_actions'] = '<a href="'.api_get_path(
1121
                            WEB_CODE_PATH
1122
                        ).'admin/session_category_edit.php?&id='.$session_category['session_category']['id'].'">'.Display::return_icon(
1123
                            'edit.png',
1124
                            get_lang('Edit'),
1125
                            array(),
1126
                            ICON_SIZE_SMALL
1127
                        ).'</a>';
1128
                    }
1129
1130
                    $params['title'] = $session_category['session_category']['name'];
1131
1132
                    if (api_is_platform_admin()) {
1133
                        $params['link'] = api_get_path(
1134
                            WEB_CODE_PATH
1135
                        ).'admin/session_category_edit.php?&id='.$session_category['session_category']['id'];
1136
                    }
1137
1138
                    $session_category_start_date = $session_category['session_category']['date_start'];
1139
                    $session_category_end_date   = $session_category['session_category']['date_end'];
1140
1141
                    if (!empty($session_category_start_date) && $session_category_start_date != '0000-00-00' && !empty($session_category_end_date) && $session_category_end_date != '0000-00-00') {
1142
                        $params['subtitle'] = sprintf(
1143
                            get_lang('FromDateXToDateY'),
1144
                            $session_category['session_category']['date_start'],
1145
                            $session_category['session_category']['date_end']
1146
                        );
1147
                    } else {
1148
                        if (!empty($session_category_start_date) && $session_category_start_date != '0000-00-00') {
1149
                            $params['subtitle'] = get_lang('From').' '.$session_category_start_date;
1150
                        }
1151
                        if (!empty($session_category_end_date) && $session_category_end_date != '0000-00-00') {
1152
                            $params['subtitle'] = get_lang('Until').' '.$session_category_end_date;
1153
                        }
1154
                    }
1155
                    $sessions_with_category .= CourseManager::course_item_parent(
1156
                        CourseManager::course_item_html($params, true),
1157
                        $html_sessions
1158
                    );
1159
                }
1160
            }
1161
1162
            //Pagination
1163
            $adapter    = new FixedAdapter($nbResults, array());
1164
            $pagerfanta = new Pagerfanta($adapter);
1165
            $pagerfanta->setMaxPerPage($this->maxPerPage); // 10 by default
1166
            $pagerfanta->setCurrentPage($page); // 1 by default
1167
1168
            $this->app['pagerfanta.view.router.name']   = 'userportal';
1169
            $this->app['pagerfanta.view.router.params'] = array(
1170
                'filter' => $filter,
1171
                'type'   => 'sessioncategories',
1172
                'page'   => $page
1173
            );
1174
            $this->app['template']->assign('pagination', $pagerfanta);
1175
        }
1176
1177
        return $sessions_with_category;
1178
    }
1179
1180
    /**
1181
     * @param int $user_id
1182
     * @param string $filter current|history
1183
     * @param int $page
1184
     * @return bool|null|string
1185
     */
1186
    public function returnSessions($user_id, $filter, $page)
1187
    {
1188
        if (empty($user_id)) {
1189
            return false;
1190
        }
1191
1192
        $loadHistory = (isset($filter) && $filter == 'history') ? true : false;
1193
1194
        /*$app['session_menu'] = function ($app) use ($loadHistory) {
1195
            $menu = $app['knp_menu.factory']->createItem(
1196
                'root',
1197
                array(
1198
                    'childrenAttributes' => array(
1199
                        'class'        => 'nav nav-tabs',
1200
                        'currentClass' => 'active'
1201
                    )
1202
                )
1203
            );
1204
1205
            $current = $menu->addChild(
1206
                get_lang('Current'),
1207
                array(
1208
                    'route'           => 'userportal',
1209
                    'routeParameters' => array(
1210
                        'filter' => 'current',
1211
                        'type'   => 'sessions'
1212
                    )
1213
                )
1214
            );
1215
            $history = $menu->addChild(
1216
                get_lang('HistoryTrainingSession'),
1217
                array(
1218
                    'route'           => 'userportal',
1219
                    'routeParameters' => array(
1220
                        'filter' => 'history',
1221
                        'type'   => 'sessions'
1222
                    )
1223
                )
1224
            );
1225
            //@todo use URIVoter
1226
            if ($loadHistory) {
1227
                $history->setCurrent(true);
1228
            } else {
1229
                $current->setCurrent(true);
1230
            }
1231
1232
            return $menu;
1233
        };*/
1234
1235
        //@todo move this in template
1236
        //$app['knp_menu.menus'] = array('actions_menu' => 'session_menu');
1237
1238
        $start = ($page - 1) * $this->maxPerPage;
1239
1240
        if ($loadHistory) {
1241
            // Load sessions in category in *history*.
1242
            $nbResults = (int)UserManager::get_sessions_by_category(
1243
                $user_id,
1244
                true,
1245
                true,
1246
                true,
1247
                null,
1248
                null,
1249
                'no_category'
1250
            );
1251
1252
            $session_categories = UserManager::get_sessions_by_category(
1253
                $user_id,
1254
                true,
1255
                false,
1256
                true,
1257
                $start,
1258
                $this->maxPerPage,
1259
                'no_category'
1260
            );
1261
        } else {
1262
            // Load sessions in category.
1263
            $nbResults = (int)UserManager::get_sessions_by_category(
1264
                $user_id,
1265
                false,
1266
                true,
1267
                false,
1268
                null,
1269
                null,
1270
                'no_category'
1271
            );
1272
1273
            $session_categories = UserManager::get_sessions_by_category(
1274
                $user_id,
1275
                false,
1276
                false,
1277
                false,
1278
                $start,
1279
                $this->maxPerPage,
1280
                'no_category'
1281
            );
1282
        }
1283
1284
        $html = null;
1285
1286
        // Showing history title
1287
        if ($loadHistory) {
1288
            // $html .= Display::page_subheader(get_lang('HistoryTrainingSession'));
1289
            if (empty($session_categories)) {
1290
                $html .= get_lang('YouDoNotHaveAnySessionInItsHistory');
1291
            }
1292
        }
1293
1294
        $load_directories_preview = api_get_setting('document.show_documents_preview') == 'true' ? true : false;
1295
        $sessions_with_no_category = $html;
1296
1297
        if (isset($session_categories) && !empty($session_categories)) {
1298
            foreach ($session_categories as $session_category) {
1299
                $session_category_id = $session_category['session_category']['id'];
1300
1301
                // Sessions does not belong to a session category
1302
                if ($session_category_id == 0) {
1303
1304
                    // Independent sessions
1305
                    if (isset($session_category['sessions'])) {
1306
                        foreach ($session_category['sessions'] as $session) {
1307
                            $session_id = $session['session_id'];
1308
1309
                            // Don't show empty sessions.
1310
                            if (count($session['courses']) < 1) {
1311
                                continue;
1312
                            }
1313
1314
                            // Courses inside the current session.
1315
                            $date_session_start = $session['access_start_date'];
1316
                            $date_session_end = $session['access_end_date'];
1317
                            $coachAccessStartDate = $session['coach_access_start_date'];
1318
                            $coachAccessEndDate = $session['coach_access_end_date'];
1319
1320
                            $session_now = time();
1321
                            $count_courses_session = 0;
1322
                            $count_courses_session = 0;
1323
1324
                            // Loop course content
1325
                            $html_courses_session = [];
1326
                            $atLeastOneCourseIsVisible = false;
1327
1328
                            foreach ($session['courses'] as $course) {
1329
                                $is_coach_course = api_is_coach($session_id, $course['real_id']);
1330
                                $allowed_time = 0;
1331
1332
                                // Read only and accessible
1333 View Code Duplication
                                if (api_get_setting('session.hide_courses_in_sessions') == 'false') {
1334
                                    $courseUserHtml = CourseManager::get_logged_user_course_html(
1335
                                        $course,
1336
                                        $session_id,
1337
                                        $load_directories_preview
1338
                                    );
1339
1340
                                    if (isset($courseUserHtml[1])) {
1341
                                        $course_session = $courseUserHtml[1];
1342
                                        $course_session['skill'] = isset($courseUserHtml['skill']) ? $courseUserHtml['skill'] : '';
1343
                                        $html_courses_session[] = $course_session;
1344
                                    }
1345
1346
                                }
1347
                                $count_courses_session++;
1348
                            }
1349
1350
                            if ($count_courses_session > 0) {
1351
                                $params = array();
1352
1353
                                $params['icon'] = Display::return_icon(
1354
                                    'window_list.png',
1355
                                    $session['session_name'],
1356
                                    array('id' => 'session_img_'.$session_id),
1357
                                    ICON_SIZE_LARGE
1358
                                );
1359
                                $params['is_session'] = true;
1360
                                //Default session name
1361
                                $session_link   = $session['session_name'];
1362
                                $params['link'] = null;
1363
1364 View Code Duplication
                                if (api_get_setting('session.session_page_enabled') == 'true' && !api_is_drh()) {
1365
                                    //session name with link
1366
                                    $session_link = Display::tag(
1367
                                        'a',
1368
                                        $session['session_name'],
1369
                                        array(
1370
                                            'href' => api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session_id
1371
                                        )
1372
                                    );
1373
                                    $params['link'] = api_get_path(WEB_CODE_PATH).'session/index.php?session_id='.$session_id;
1374
                                }
1375
1376
                                $params['title'] = $session_link;
1377
1378
                                $moved_status = \SessionManager::get_session_change_user_reason(
1379
                                    $session['moved_status']
1380
                                );
1381
                                $moved_status = isset($moved_status) && !empty($moved_status) ? ' ('.$moved_status.')' : null;
1382
1383
                                $params['subtitle'] = isset($session['coach_info']) ? $session['coach_info']['complete_name'] : null.$moved_status;
1384
                                $params['dates'] = $session['date_message'];
1385
                                $params['right_actions'] = '';
1386 View Code Duplication
                                if (api_is_platform_admin()) {
1387
                                    $params['right_actions'] .=
1388
                                        Display::url(
1389
                                            Display::return_icon(
1390
                                                'edit.png',
1391
                                                get_lang('Edit'),
1392
                                                array('align' => 'absmiddle'),
1393
                                                ICON_SIZE_SMALL
1394
                                            ),
1395
                                            api_get_path(WEB_CODE_PATH).'session/resume_session.php?id_session='.$session_id
1396
                                        );
1397
                                }
1398
1399
                                if (api_get_setting('session.hide_courses_in_sessions') == 'false') {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
1400
                                    //    $params['extra'] .=  $html_courses_session;
1401
                                }
1402
                                $courseDataToString = CourseManager::parseCourseListData($html_courses_session);
1403
                                $sessions_with_no_category .= CourseManager::course_item_parent(
1404
                                    CourseManager::course_item_html($params, true),
1405
                                    $courseDataToString
1406
                                );
1407
                            }
1408
                        }
1409
                    }
1410
                }
1411
            }
1412
1413
            /*$adapter = new FixedAdapter($nbResults, array());
1414
            $pagerfanta = new Pagerfanta($adapter);
1415
            $pagerfanta->setMaxPerPage($this->maxPerPage); // 10 by default
1416
            $pagerfanta->setCurrentPage($page); // 1 by default
1417
1418
            $this->app['pagerfanta.view.router.name']   = 'userportal';
1419
            $this->app['pagerfanta.view.router.params'] = array(
1420
                'filter' => $filter,
1421
                'type'   => 'sessions',
1422
                'page'   => $page
1423
            );
1424
            $this->app['template']->assign('pagination', $pagerfanta);*/
1425
        }
1426
1427
        return $sessions_with_no_category;
1428
    }
1429
1430
    /**
1431
     * Shows a welcome message when the user doesn't have any content in
1432
     * the course list
1433
     * @param object A Template object used to declare variables usable in the given template
1434
     * @return void
1435
     */
1436
    public function return_welcome_to_course_block($tpl)
1437
    {
1438
        if (empty($tpl)) {
1439
            return false;
1440
        }
1441
        $count_courses = CourseManager::count_courses();
1442
1443
        $course_catalog_url = api_get_path(WEB_CODE_PATH).'auth/courses.php';
1444
        $course_list_url    = api_get_path(WEB_PATH).'user_portal.php';
1445
1446
        $tpl->assign('course_catalog_url', $course_catalog_url);
1447
        $tpl->assign('course_list_url', $course_list_url);
1448
        $tpl->assign('course_catalog_link', Display::url(get_lang('here'), $course_catalog_url));
1449
        $tpl->assign('course_list_link', Display::url(get_lang('here'), $course_list_url));
1450
        $tpl->assign('count_courses', $count_courses);
1451
        $tpl->assign('welcome_to_course_block', 1);
1452
    }
1453
1454
     /**
1455
     * @param array
1456
     */
1457
    public function returnNavigationLinks($items)
1458
    {
1459
        // Main navigation section.
1460
        // Tabs that are deactivated are added here.
1461
        if (!empty($items)) {
1462
            $content = '<ul class="nav nav-list">';
1463
            foreach ($items as $section => $navigation_info) {
1464
                $current = isset($GLOBALS['this_section']) && $section == $GLOBALS['this_section'] ? ' id="current"' : '';
1465
                $content .= '<li '.$current.'>';
1466
                $content .= '<a href="'.$navigation_info['url'].'" target="_self">'.$navigation_info['title'].'</a>';
1467
                $content .= '</li>';
1468
            }
1469
            $content .= '</ul>';
1470
            $this->show_right_block(get_lang('MainNavigation'), null, 'navigation_block', array('content' => $content));
0 ignored issues
show
Unused Code introduced by
The call to the method Chamilo\CoreBundle\Frame...ler::show_right_block() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
1471
        }
1472
    }
1473
}
1474