Passed
Push — master ( d274e1...1d53fe )
by Yannick
07:28
created

check_system_version()   F

Complexity

Conditions 15
Paths 736

Size

Total Lines 128
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 15
eloc 84
c 2
b 0
f 0
nc 736
nop 0
dl 0
loc 128
rs 2.0424

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/* For licensing terms, see /license.txt */
4
5
use Chamilo\CoreBundle\Entity\BranchSync;
6
use Chamilo\CoreBundle\Framework\Container;
7
use Chamilo\CoreBundle\Repository\BranchSyncRepository;
8
use GuzzleHttp\Client;
9
use League\Flysystem\Filesystem;
10
11
require_once __DIR__.'/../global.inc.php';
12
13
api_protect_admin_script();
14
15
$action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
16
17
switch ($action) {
18
    case 'update_changeable_setting':
19
        $url_id = api_get_current_access_url_id();
20
21
        if (api_is_global_platform_admin() && 1 == $url_id) {
22
            if (isset($_GET['id']) && !empty($_GET['id'])) {
23
                $params = ['variable = ? ' => [$_GET['id']]];
24
                $data = api_get_settings_params($params);
25
                if (!empty($data)) {
26
                    foreach ($data as $item) {
27
                        $params = ['id' => $item['id'], 'access_url_changeable' => $_GET['changeable']];
28
                        api_set_setting_simple($params);
29
                    }
30
                }
31
                echo '1';
32
            }
33
        }
34
        break;
35
    case 'version':
36
        // Fix session block when loading admin/index.php and changing page
37
        session_write_close();
38
        echo version_check();
39
        break;
40
    case 'get_extra_content':
41
        $blockName = isset($_POST['block']) ? Security::remove_XSS($_POST['block']) : null;
42
43
        if (empty($blockName)) {
44
            exit;
45
        }
46
47
        /** @var Filesystem $fileSystem */
48
        $fileSystem = Container::$container->get('home_filesystem');
49
        $dir = 'admin/';
50
51
        if (api_is_multiple_url_enabled()) {
52
            $accessUrlId = api_get_current_access_url_id();
53
54
            if (-1 != $accessUrlId) {
55
                $urlInfo = api_get_access_url($accessUrlId);
56
                $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $urlInfo['url']));
57
                $cleanUrl = str_replace('/', '-', $url);
58
                $dir = "$cleanUrl/admin/";
59
            }
60
        }
61
62
        $filePath = $dir.$blockName.'_extra.html';
63
64
        if ($fileSystem->has($filePath)) {
65
            echo $fileSystem->read($dir.$blockName.'_extra.html');
66
        }
67
68
        break;
69
    case 'get_latest_news':
70
        if ('true' === api_get_setting('announcement.admin_chamilo_announcements_disable')) {
71
            break;
72
        }
73
74
        try {
75
            $latestNews = getLatestNews();
76
            $latestNews = json_decode($latestNews, true);
77
78
            echo Security::remove_XSS($latestNews['text'], COURSEMANAGER);
79
            break;
80
        } catch (Exception $e) {
81
            break;
82
        }
83
}
84
85
/**
86
 * Displays either the text for the registration or the message that the installation is (not) up to date.
87
 *
88
 * @return string html code
89
 *
90
 * @author Patrick Cool <[email protected]>, Ghent University
91
 *
92
 * @version august 2006
93
 *
94
 * @todo have a 6 monthly re-registration
95
 */
96
function version_check()
97
{
98
    $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
99
    $sql = 'SELECT selected_value FROM '.$tbl_settings.' WHERE variable = "registered" ';
100
    $result = Database::query($sql);
101
    $row = Database::fetch_array($result, 'ASSOC');
102
103
    // The site has not been registered yet.
104
    $return = '';
105
    if ('false' == $row['selected_value']) {
106
        check_system_version();
107
    } else {
108
        // site not registered. Call anyway
109
        $return .= check_system_version();
110
    }
111
112
    return $return;
113
}
114
115
/**
116
 * Check if the current installation is up to date
117
 * The code is borrowed from phpBB and slighlty modified.
118
 *
119
 * @throws \Exception
120
 * @throws \InvalidArgumentException
121
 *
122
 * @return string language string with some layout (color)
123
 */
124
function check_system_version()
125
{
126
    // Check if curl is available.
127
    if (!in_array('curl', get_loaded_extensions())) {
128
        return '<span style="color:red">'.
129
            get_lang('Impossible to contact the version server right now. Please try again later.').'</span>';
130
    }
131
132
    $url = 'https://version.chamilo.org';
133
    $options = [
134
        'verify' => false,
135
    ];
136
137
    $urlValidated = false;
138
139
    try {
140
        $client = new GuzzleHttp\Client();
141
        $res = $client->request('GET', $url, $options);
142
        if ('200' == $res->getStatusCode() || '301' == $res->getStatusCode()) {
143
            $urlValidated = true;
144
        }
145
    } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
146
    }
147
148
    // the chamilo version of your installation
149
    $system_version = '';
150
    $versionStatus = '';
151
    $versionFile =__DIR__.'/../../install/version.php';
152
    if (is_file($versionFile)) {
153
        $versionDetails = include($versionFile);
154
        $system_version = trim($versionDetails['new_version']);
155
        if (!empty($versionDetails['new_version_status']) &&  $versionDetails['new_version_status'] != 'stable') {
156
            $versionStatus = ' ('.$versionDetails['new_version_status'].')';
157
        }
158
    }
159
160
    if ($urlValidated) {
161
        // The number of courses
162
        $number_of_courses = Statistics::countCourses();
163
164
        // The number of users
165
        $number_of_users = Statistics::countUsers();
166
        $number_of_active_users = Statistics::countUsers(
167
            null,
168
            null,
169
            true,
170
            true
171
        );
172
173
        // The number of sessions
174
        $number_of_sessions = SessionManager::count_sessions(api_get_current_access_url_id());
175
        $packager = api_get_setting('platform.packager');
176
        if (empty($packager)) {
177
            $packager = 'chamilo';
178
        }
179
180
        $uniqueId = '';
181
        $entityManager = Database::getManager();
182
        /** @var BranchSyncRepository $repository */
183
        $repository = $entityManager->getRepository(BranchSync::class);
184
        /** @var BranchSync $branch */
185
        $branch = $repository->getTopBranch();
186
        if (is_a($branch, BranchSync::class)) {
187
            $uniqueId = $branch->getUniqueId();
188
        }
189
190
        $data = [
191
            'url' => api_get_path(WEB_PATH),
192
            'campus' => api_get_setting('siteName'),
193
            'contact' => api_get_setting('emailAdministrator'), // the admin's e-mail, with the only purpose of being able to contact admins to inform about critical security issues
194
            'version' => $system_version,
195
            'numberofcourses' => $number_of_courses, // to sum up into non-personal statistics - see https://version.chamilo.org/stats/
196
            'numberofusers' => $number_of_users, // to sum up into non-personal statistics
197
            'numberofactiveusers' => $number_of_active_users, // to sum up into non-personal statistics
198
            'numberofsessions' => $number_of_sessions,
199
            //The donotlistcampus setting recovery should be improved to make
200
            // it true by default - this does not affect numbers counting
201
            'donotlistcampus' => api_get_setting('donotlistcampus'),
202
            'organisation' => api_get_setting('Institution'),
203
            'language' => api_get_setting('platformLanguage'), //helps us know the spread of language usage for campuses, by main language
204
            'adminname' => api_get_setting('administratorName').' '.api_get_setting('administratorSurname'), //not sure this is necessary...
0 ignored issues
show
Bug introduced by
Are you sure api_get_setting('administratorName') of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

204
            'adminname' => /** @scrutinizer ignore-type */ api_get_setting('administratorName').' '.api_get_setting('administratorSurname'), //not sure this is necessary...
Loading history...
Bug introduced by
Are you sure api_get_setting('administratorSurname') of type array|string can be used in concatenation? ( Ignorable by Annotation )

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

204
            'adminname' => api_get_setting('administratorName').' './** @scrutinizer ignore-type */ api_get_setting('administratorSurname'), //not sure this is necessary...
Loading history...
205
            'ip' => $_SERVER['REMOTE_ADDR'], //the admin's IP address, with the only purpose of trying to geolocate portals around the globe to draw a map
206
            // Reference to the packager system or provider through which
207
            // Chamilo is installed/downloaded. Packagers can change this in
208
            // the default config file (main/install/configuration.dist.php)
209
            // or in the installed config file. The default value is 'chamilo'
210
            'packager' => $packager,
211
            'unique_id' => $uniqueId,
212
        ];
213
214
        $version = null;
215
        $client = new GuzzleHttp\Client();
216
        $url .= '?';
217
        foreach ($data as $k => $v) {
218
            $url .= urlencode($k).'='.urlencode($v).'&';
219
        }
220
        $res = $client->request('GET', $url, $options);
221
        if ('200' == $res->getStatusCode()) {
222
            $versionData = $res->getHeader('X-Chamilo-Version');
223
            if (isset($versionData[0])) {
224
                $version = trim($versionData[0]);
225
            }
226
        }
227
228
        if (version_compare($system_version, $version, '<')) {
229
            $output = '<span style="color:red">'.
230
                get_lang('Your version is not up-to-date').'<br />'.
231
                get_lang('The latest version is').' <b>Chamilo '.$version.'</b>.  <br />'.
232
                get_lang('Your version is').' <b>Chamilo '.$system_version.$versionStatus.'</b>.  <br />'.
233
                str_replace(
234
                    'http://www.chamilo.org',
235
                    '<a href="https://chamilo.org/download">https://chamilo.org/download</a>',
236
                    get_lang('Please visit our website: http://www.chamilo.org')
237
                ).
238
                '</span>';
239
        } else {
240
            $output = '<span style="color:green">'.
241
                get_lang('Your version is up-to-date').'<br />'.
242
                get_lang('The latest version is').' <b>Chamilo '.$version.'</b>.  <br />'.
243
                get_lang('Your version is').' <b>Chamilo '.$system_version.$versionStatus.'</b>.  <br />'.
244
                '</span>';
245
        }
246
247
        return $output;
248
    }
249
250
    return '<span style="color:red">'.
251
        get_lang('Impossible to contact the version server right now. Please try again later.').'</span>';
252
}
253
254
/**
255
 * Display the latest news from the Chamilo Association for admins.
256
 *
257
 * @throws \GuzzleHttp\Exception\GuzzleException
258
 * @throws Exception
259
 *
260
 * @return string|void
261
 */
262
function getLatestNews()
263
{
264
    $url = 'https://version.chamilo.org/news/latest.php';
265
266
    $client = new Client();
267
    $response = $client->request(
268
        'GET',
269
        $url,
270
        [
271
            'query' => [
272
                'language' => api_get_language_isocode(),
273
            ],
274
        ]
275
    );
276
277
    if (200 !== $response->getStatusCode()) {
278
        throw new Exception(get_lang('Deny access'));
279
    }
280
281
    return $response->getBody()->getContents();
282
}
283