Completed
Push — 1.10.x ( 1418a6...949d46 )
by Yannick
179:54 queued 131:47
created

admin.ajax.php ➔ check_system_version()   C

Complexity

Conditions 8
Paths 11

Size

Total Lines 75
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 8
eloc 46
c 1
b 0
f 1
nc 11
nop 0
dl 0
loc 75
rs 6.2413

How to fix   Long Method   

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
 * Responses to AJAX calls
5
 */
6
require_once '../global.inc.php';
7
8
api_protect_admin_script();
9
10
$action = isset($_REQUEST['a']) ? $_REQUEST['a'] : null;
11
12
switch ($action) {
13
    case 'update_changeable_setting':
14
        $url_id = api_get_current_access_url_id();
15
16
        if (api_is_global_platform_admin() && $url_id == 1) {
17
            if (isset($_GET['id']) && !empty($_GET['id'])) {
18
                $params = array('variable = ? ' =>  array($_GET['id']));
19
                $data = api_get_settings_params($params);
20 View Code Duplication
                if (!empty($data)) {
21
                    foreach ($data as $item) {
22
                        $params = array('id' =>$item['id'], 'access_url_changeable' => $_GET['changeable']);
23
                        api_set_setting_simple($params);
24
                    }
25
                }
26
                echo '1';
27
            }
28
        }
29
        break;
30
31
    case 'version':
32
        echo version_check();
33
        break;
34
35
    case 'get_extra_content':
36
        $blockName = isset($_POST['block']) ? Security::remove_XSS($_POST['block']) : null;
37
38
        if (empty($blockName)) {
39
            die;
40
        }
41
42
        if (api_is_multiple_url_enabled()) {
43
            $accessUrlId = api_get_current_access_url_id();
44
45
            if ($accessUrlId == -1) {
46
                die;
47
            }
48
49
            $urlInfo = api_get_access_url($accessUrlId);
50
            $url = api_remove_trailing_slash(preg_replace('/https?:\/\//i', '', $urlInfo['url']));
51
            $cleanUrl = str_replace('/', '-', $url);
52
53
            $newUrlDir = api_get_path(SYS_APP_PATH) . "home/$cleanUrl/admin/";
54
        } else {
55
            $newUrlDir = api_get_path(SYS_APP_PATH) . "home/admin/";
56
        }
57
58
        if (!file_exists($newUrlDir)) {
59
            die;
60
        }
61
62
        if (!Security::check_abs_path("{$newUrlDir}{$blockName}_extra.html", $newUrlDir)) {
63
            die;
64
        }
65
66
        if (!file_exists("{$newUrlDir}{$blockName}_extra.html")) {
67
            die;
68
        }
69
70
        echo file_get_contents("{$newUrlDir}{$blockName}_extra.html");
71
        break;
72
}
73
74
75
/**
76
 * Displays either the text for the registration or the message that the installation is (not) up to date
77
 *
78
 * @return string html code
79
 * @author Patrick Cool <[email protected]>, Ghent University
80
 * @version august 2006
81
 * @todo have a 6 monthly re-registration
82
 */
83
function version_check()
84
{
85
    $tbl_settings = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
86
    $sql = 'SELECT selected_value FROM '.$tbl_settings.' WHERE variable = "registered" ';
87
    $result = Database::query($sql);
88
    $row = Database::fetch_array($result, 'ASSOC');
89
90
    // The site has not been registered yet.
91
    $return = '';
92
    if ($row['selected_value'] == 'false') {
93
        $return .= get_lang('VersionCheckExplanation');
94
        $return .= '<form class="version-checking" action="'.api_get_path(WEB_CODE_PATH).'admin/index.php" id="VersionCheck" name="VersionCheck" method="post">';
95
        $return .= '<label class="checkbox"><input type="checkbox" name="donotlistcampus" value="1" id="checkbox" />'.get_lang('HideCampusFromPublicPlatformsList');
96
        $return .= '</label><button type="submit" class="btn btn-primary btn-block" name="Register" value="'.get_lang('EnableVersionCheck').'" id="register" >'.get_lang('EnableVersionCheck').'</button>';
97
        $return .= '</form>';
98
        check_system_version();
99
    } else {
100
        // site not registered. Call anyway
101
        $return .= check_system_version();
102
    }
103
    return $return;
104
}
105
106
/**
107
 * Check if the current installation is up to date
108
 * The code is borrowed from phpBB and slighlty modified
109
 * @author The phpBB Group <[email protected]> (the code)
110
 * @author Patrick Cool <[email protected]>, Ghent University (the modifications)
111
 * @author Yannick Warnier <[email protected]> for the move to HTTP request
112
 * @copyright (C) 2001 The phpBB Group
113
 * @return string language string with some layout (color)
114
 */
115
function check_system_version()
116
{
117
    // the chamilo version of your installation
118
    $system_version = trim(api_get_configuration_value('system_version'));
119
120
    if (ini_get('allow_url_fopen') == 1) {
121
        // The number of courses
122
        $number_of_courses = Statistics::countCourses();
123
124
        // The number of users
125
        $number_of_users = Statistics::countUsers();
126
        $number_of_active_users = Statistics::countUsers(null, null, null, true);
127
128
        // The number of sessions
129
        $number_of_sessions = Statistics::countSessions();
130
        $packager = api_get_configuration_value('packager');
131
        if (empty($packager)) {
132
            $packager = 'chamilo';
133
        }
134
135
        $data = array(
136
            'url' => api_get_path(WEB_PATH),
137
            'campus' => api_get_setting('siteName'),
138
            '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
139
            'version' => $system_version,
140
            'numberofcourses' => $number_of_courses, // to sum up into non-personal statistics - see https://version.chamilo.org/stats/
141
            'numberofusers' => $number_of_users, // to sum up into non-personal statistics
142
            'numberofactiveusers' => $number_of_active_users, // to sum up into non-personal statistics
143
            'numberofsessions' => $number_of_sessions,
144
            //The donotlistcampus setting recovery should be improved to make
145
            // it true by default - this does not affect numbers counting
146
            'donotlistcampus' => api_get_setting('donotlistcampus'),
147
            'organisation' => api_get_setting('Institution'),
148
            'language' => api_get_setting('platformLanguage'), //helps us know the spread of language usage for campuses, by main language
149
            'adminname' => api_get_setting('administratorName').' '.api_get_setting('administratorSurname'), //not sure this is necessary...
150
            '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
151
            // Reference to the packager system or provider through which
152
            // Chamilo is installed/downloaded. Packagers can change this in
153
            // the default config file (main/install/configuration.dist.php)
154
            // or in the installed config file. The default value is 'chamilo'
155
            'packager' => $packager,
156
        );
157
        $version = null;
158
        // version.php has been updated to include the version in an HTTP header
159
        // called "X-Chamilo-Version", so that we don't have to worry about
160
        // issues with the content not being returned by fread for some reason
161
        $res = _http_request('version.chamilo.org', 80, '/version.php', $data, 5, null, true);
162
        $lines = preg_split('/\r\n/', $res);
163
        foreach ($lines as $line) {
164
            $elements = preg_split('/:/', $line);
165
            // extract the X-Chamilo-Version header from the version.php response
166
            if (strcmp(trim($elements[0]), 'X-Chamilo-Version') === 0) {
167
                $version = trim($elements[1]);
168
            }
169
        }
170
        if (substr($res, 0, 5) != 'Error') {
171
            if (empty($version)) {
172
                $version_info = $res;
173
            } else {
174
                $version_info = $version;
175
            }
176
177
            if ($system_version != $version_info) {
178
                $output = '<br /><span style="color:red">' . get_lang('YourVersionNotUpToDate') . '. '.get_lang('LatestVersionIs').' <b>Chamilo '.$version_info.'</b>. '.get_lang('YourVersionIs').' <b>Chamilo '.$system_version. '</b>. '.str_replace('http://www.chamilo.org', '<a href="http://www.chamilo.org">http://www.chamilo.org</a>', get_lang('PleaseVisitOurWebsite')).'</span>';
179
            } else {
180
                $output = '<br /><span style="color:green">'.get_lang('VersionUpToDate').': Chamilo '.$version_info.'</span>';
181
            }
182
        } else {
183
            $output = '<span style="color:red">' . get_lang('ImpossibleToContactVersionServerPleaseTryAgain') . '</span>';
184
        }
185
    } else {
186
        $output = '<span style="color:red">' . get_lang('AllowurlfopenIsSetToOff') . '</span>';
187
    }
188
    return $output;
189
}
190
191
/**
192
 * Function to make an HTTP request through fsockopen (specialised for GET)
193
 * Derived from Jeremy Saintot: http://www.php.net/manual/en/function.fsockopen.php#101872
194
 * @param string $ip IP or hostname
195
 * @param int    $port Target port
196
 * @param string $uri URI (defaults to '/')
197
 * @param array  $getdata GET data
198
 * @param int    $timeout Timeout
199
 * @param bool   $req_hdr Include HTTP Request headers?
200
 * @param bool   $res_hdr Include HTTP Response headers?
201
 * @return string
202
 */
203
function _http_request($ip, $port = 80, $uri = '/', $getdata = array(), $timeout = 5, $req_hdr = false, $res_hdr = false)
204
{
205
    $verb = 'GET';
206
    $ret = '';
207
    $getdata_str = count($getdata) ? '?' : '';
208
209
    foreach ($getdata as $k => $v) {
210
                $getdata_str .= urlencode($k) .'='. urlencode($v) . '&';
211
    }
212
213
    $crlf = "\r\n";
214
    $req = $verb .' '. $uri . $getdata_str .' HTTP/1.1' . $crlf;
215
    $req .= 'Host: '. $ip . $crlf;
216
    $req .= 'User-Agent: Mozilla/5.0 Firefox/3.6.12' . $crlf;
217
    $req .= 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' . $crlf;
218
    $req .= 'Accept-Language: en-us,en;q=0.5' . $crlf;
219
    $req .= 'Accept-Encoding: deflate' . $crlf;
220
    $req .= 'Accept-Charset: utf-8;q=0.7,*;q=0.7' . $crlf;
221
222
    $req .= $crlf;
223
224
    if ($req_hdr) {
225
        $ret .= $req;
226
    }
227
    if (($fp = @fsockopen($ip, $port, $errno, $errstr, $timeout)) == false) {
228
        return "Error $errno: $errstr\n";
229
    }
230
231
    stream_set_timeout($fp, $timeout);
232
    $r = fwrite($fp, $req);
233
    $line = @fread($fp, 512);
234
    $ret .= $line;
235
    fclose($fp);
236
237
    if (!$res_hdr) {
238
        $ret = substr($ret, strpos($ret, "\r\n\r\n") + 4);
239
    }
240
    return trim($ret);
241
}
242