check_system_version()   C
last analyzed

Complexity

Conditions 12
Paths 246

Size

Total Lines 106
Code Lines 65

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 12
eloc 65
nc 246
nop 0
dl 0
loc 106
rs 5.2103
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* For licensing terms, see /license.txt */
3
4
use Chamilo\CoreBundle\Entity\BranchSync;
5
use Chamilo\CoreBundle\Entity\Repository\BranchSyncRepository;
6
use GuzzleHttp\Client;
7
8
/**
9
 * Responses to AJAX calls.
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() && $url_id == 1) {
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
        if (api_is_multiple_url_enabled()) {
48
            $accessUrlId = api_get_current_access_url_id();
49
50
            if ($accessUrlId == -1) {
51
                exit;
52
            }
53
54
            $urlInfo = api_get_access_url($accessUrlId);
55
            $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $urlInfo['url']));
56
            $cleanUrl = str_replace('/', '-', $url);
57
            $newUrlDir = api_get_path(SYS_APP_PATH)."home/$cleanUrl/admin/";
58
        } else {
59
            $newUrlDir = api_get_path(SYS_APP_PATH)."home/admin/";
60
        }
61
62
        if (!file_exists($newUrlDir)) {
63
            exit;
64
        }
65
66
        if (!Security::check_abs_path("{$newUrlDir}{$blockName}_extra.html", $newUrlDir)) {
67
            exit;
68
        }
69
70
        if (!file_exists("{$newUrlDir}{$blockName}_extra.html")) {
71
            exit;
72
        }
73
74
        echo file_get_contents("{$newUrlDir}{$blockName}_extra.html");
75
        break;
76
    case 'get_latest_news':
77
        if (api_get_configuration_value('admin_chamilo_announcements_disable') === true) {
78
            break;
79
        }
80
81
        try {
82
            $latestNews = getLatestNews();
83
            $latestNews = json_decode($latestNews, true);
84
85
            echo Security::remove_XSS($latestNews['text'], COURSEMANAGER);
86
            break;
87
        } catch (Exception $e) {
88
            break;
89
        }
90
}
91
92
/**
93
 * Displays either the text for the registration or the message that the installation is (not) up to date.
94
 *
95
 * @return string html code
96
 *
97
 * @author Patrick Cool <[email protected]>, Ghent University
98
 *
99
 * @version august 2006
100
 *
101
 * @todo have a 6 monthly re-registration
102
 */
103
function version_check()
104
{
105
    $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
106
    $sql = 'SELECT selected_value FROM '.$tbl_settings.' WHERE variable = "registered" ';
107
    $result = Database::query($sql);
108
    $row = Database::fetch_array($result, 'ASSOC');
109
110
    // The site has not been registered yet.
111
    $return = '';
112
    if ($row['selected_value'] == 'false') {
113
        $return .= get_lang('VersionCheckExplanation');
114
        $return .= '<form class="version-checking" action="'.api_get_path(WEB_CODE_PATH).'admin/index.php" id="VersionCheck" name="VersionCheck" method="post">';
115
        $return .= '<label class="checkbox"><input type="checkbox" name="donotlistcampus" value="1" id="checkbox" />'.get_lang('HideCampusFromPublicPlatformsList');
116
        $return .= '</label><button type="submit" class="btn btn-primary btn-block" name="Register" value="'.get_lang('EnableVersionCheck').'" id="register" >'.get_lang('EnableVersionCheck').'</button>';
117
        $return .= '</form>';
118
        check_system_version();
119
    } else {
120
        // site not registered. Call anyway
121
        $return .= check_system_version();
122
    }
123
124
    return $return;
125
}
126
127
/**
128
 * Check if the current installation is up to date
129
 * The code is borrowed from phpBB and slighlty modified.
130
 *
131
 * @throws \Exception
132
 * @throws \InvalidArgumentException
133
 *
134
 * @return string language string with some layout (color)
135
 */
136
function check_system_version()
137
{
138
    // Check if curl is available.
139
    if (!in_array('curl', get_loaded_extensions())) {
140
        return '<span style="color:red">'.get_lang('ImpossibleToContactVersionServerPleaseTryAgain').'</span>';
141
    }
142
143
    $url = 'https://version.chamilo.org';
144
    $options = [
145
        'verify' => false,
146
    ];
147
148
    $urlValidated = false;
149
150
    try {
151
        $client = new GuzzleHttp\Client();
152
        $res = $client->request('GET', $url, $options);
153
        if ($res->getStatusCode() == '200' || $res->getStatusCode() == '301') {
154
            $urlValidated = true;
155
        }
156
    } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
157
    }
158
159
    // the chamilo version of your installation
160
    $system_version = trim(api_get_configuration_value('system_version'));
161
162
    if ($urlValidated) {
163
        // The number of courses
164
        $number_of_courses = Statistics::countCourses();
165
166
        // The number of users
167
        $number_of_users = Statistics::countUsers();
168
        $number_of_active_users = Statistics::countUsers(
169
            null,
170
            null,
171
            null,
172
            true
173
        );
174
175
        // The number of sessions
176
        $number_of_sessions = SessionManager::count_sessions(api_get_current_access_url_id());
177
        $packager = api_get_configuration_value('packager');
178
        if (empty($packager)) {
179
            $packager = 'chamilo';
180
        }
181
182
        $uniqueId = '';
183
        $entityManager = Database::getManager();
184
        /** @var BranchSyncRepository $branch */
185
        $repository = $entityManager->getRepository('ChamiloCoreBundle:BranchSync');
186
        /** @var BranchSync $branch */
187
        $branch = $repository->getTopBranch();
188
        if (is_a($branch, '\Chamilo\CoreBundle\Entity\BranchSync')) {
189
            $uniqueId = $branch->getUniqueId();
190
        }
191
192
        $data = [
193
            'url' => api_get_path(WEB_PATH),
194
            'campus' => api_get_setting('siteName'),
195
            '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
196
            'version' => $system_version,
197
            'numberofcourses' => $number_of_courses, // to sum up into non-personal statistics - see https://version.chamilo.org/stats/
198
            'numberofusers' => $number_of_users, // to sum up into non-personal statistics
199
            'numberofactiveusers' => $number_of_active_users, // to sum up into non-personal statistics
200
            'numberofsessions' => $number_of_sessions,
201
            //The donotlistcampus setting recovery should be improved to make
202
            // it true by default - this does not affect numbers counting
203
            'donotlistcampus' => api_get_setting('donotlistcampus'),
204
            'organisation' => api_get_setting('Institution'),
205
            'language' => api_get_setting('platformLanguage'), //helps us know the spread of language usage for campuses, by main language
206
            'adminname' => api_get_setting('administratorName').' '.api_get_setting('administratorSurname'), //not sure this is necessary...
207
            '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
208
            // Reference to the packager system or provider through which
209
            // Chamilo is installed/downloaded. Packagers can change this in
210
            // the default config file (main/install/configuration.dist.php)
211
            // or in the installed config file. The default value is 'chamilo'
212
            'packager' => $packager,
213
            'unique_id' => $uniqueId,
214
        ];
215
216
        $version = null;
217
        $client = new GuzzleHttp\Client();
218
        $url .= '?';
219
        foreach ($data as $k => $v) {
220
            $url .= urlencode($k).'='.urlencode($v).'&';
221
        }
222
        $res = $client->request('GET', $url, $options);
223
        if ($res->getStatusCode() == '200') {
224
            $versionData = $res->getHeader('X-Chamilo-Version');
225
            if (isset($versionData[0])) {
226
                $version = trim($versionData[0]);
227
            }
228
        }
229
230
        if (version_compare($system_version, $version, '<')) {
231
            $output = '<span style="color:red">'.get_lang('YourVersionNotUpToDate').'<br />
232
                       '.get_lang('LatestVersionIs').' <b>Chamilo '.$version.'</b>.  <br />
233
                       '.get_lang('YourVersionIs').' <b>Chamilo '.$system_version.'</b>.  <br />'.str_replace('http://www.chamilo.org', '<a href="http://www.chamilo.org">http://www.chamilo.org</a>', get_lang('PleaseVisitOurWebsite')).'</span>';
234
        } else {
235
            $output = '<span style="color:green">'.get_lang('VersionUpToDate').': Chamilo '.$version.'</span>';
236
        }
237
238
        return $output;
239
    }
240
241
    return '<span style="color:red">'.get_lang('ImpossibleToContactVersionServerPleaseTryAgain').'</span>';
242
}
243
244
/**
245
 * Display the latest news from the Chamilo Association for admins.
246
 *
247
 * @throws \GuzzleHttp\Exception\GuzzleException
248
 * @throws Exception
249
 *
250
 * @return string|void
251
 */
252
function getLatestNews()
253
{
254
    $url = 'https://version.chamilo.org/news/latest.php';
255
256
    $client = new Client();
257
    $response = $client->request(
258
        'GET',
259
        $url,
260
        [
261
            'query' => [
262
                'language' => api_get_interface_language(),
263
            ],
264
        ]
265
    );
266
267
    if ($response->getStatusCode() !== 200) {
268
        throw new Exception(get_lang('DenyEntry'));
269
    }
270
271
    return $response->getBody()->getContents();
272
}
273