Passed
Push — master ( 3da7f5...514a9d )
by Yannick
08:22
created

getProSupport()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
cc 2
eloc 10
c 1
b 0
f 1
nc 2
nop 0
dl 0
loc 20
rs 9.9332
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
        try {
71
            $latestNews = getLatestNews();
72
            $latestNews = json_decode($latestNews, true);
73
74
            echo Security::remove_XSS($latestNews['text'], COURSEMANAGER);
75
            break;
76
        } catch (Exception $e) {
77
            break;
78
        }
79
    case 'get_support':
80
        try {
81
            $latestNews = getProSupport();
82
            $latestNews = json_decode($latestNews, true);
83
84
            echo Security::remove_XSS($latestNews['text'], COURSEMANAGER);
85
            break;
86
        } catch (Exception $e) {
87
            break;
88
        }
89
}
90
91
/**
92
 * Displays either the text for the registration or the message that the installation is (not) up to date.
93
 *
94
 * @return string html code
95
 *
96
 * @author Patrick Cool <[email protected]>, Ghent University
97
 *
98
 * @version august 2006
99
 *
100
 * @todo have a 6 monthly re-registration
101
 */
102
function version_check()
103
{
104
    $tbl_settings = Database::get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
105
    $sql = 'SELECT selected_value FROM '.$tbl_settings.' WHERE variable = "registered" ';
106
    $result = Database::query($sql);
107
    $row = Database::fetch_assoc($result);
108
109
    // The site has not been registered yet.
110
    $return = '';
111
    if ('false' == $row['selected_value']) {
112
        check_system_version();
113
    } else {
114
        // site not registered. Call anyway
115
        $return .= check_system_version();
116
    }
117
118
    return $return;
119
}
120
121
/**
122
 * Check if the current installation is up to date
123
 * The code is borrowed from phpBB and slighlty modified.
124
 *
125
 * @throws \Exception
126
 * @throws \InvalidArgumentException
127
 *
128
 * @return string language string with some layout (color)
129
 */
130
function check_system_version()
131
{
132
    // Check if curl is available.
133
    if (!in_array('curl', get_loaded_extensions())) {
134
        return '<span style="color:red">'.
135
            get_lang('Impossible to contact the version server right now. Please try again later.').'</span>';
136
    }
137
138
    $url = 'https://version.chamilo.org';
139
    $options = [
140
        'verify' => false,
141
    ];
142
143
    $urlValidated = false;
144
145
    try {
146
        $client = new GuzzleHttp\Client();
147
        $res = $client->request('GET', $url, $options);
148
        if ('200' == $res->getStatusCode() || '301' == $res->getStatusCode()) {
149
            $urlValidated = true;
150
        }
151
    } catch (Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
152
    }
153
154
    // the chamilo version of your installation
155
    $system_version = '';
156
    $versionStatus = '';
157
    $versionFile =__DIR__.'/../../install/version.php';
158
    if (is_file($versionFile)) {
159
        $versionDetails = include($versionFile);
160
        $system_version = trim($versionDetails['new_version']);
161
        if (!empty($versionDetails['new_version_status']) &&  $versionDetails['new_version_status'] != 'stable') {
162
            $versionStatus = ' ('.$versionDetails['new_version_status'].')';
163
        }
164
    }
165
166
    if ($urlValidated) {
167
        // The number of courses
168
        $number_of_courses = Statistics::countCourses();
169
170
        // The number of users
171
        $number_of_users = Statistics::countUsers();
172
        $number_of_active_users = Statistics::countUsers(
173
            null,
174
            null,
175
            true,
176
            true
177
        );
178
179
        // The number of sessions
180
        $number_of_sessions = SessionManager::count_sessions(api_get_current_access_url_id());
181
        $packager = api_get_setting('platform.packager');
182
        if (empty($packager)) {
183
            $packager = 'chamilo';
184
        }
185
186
        $uniqueId = '';
187
        $entityManager = Database::getManager();
188
        /** @var BranchSyncRepository $repository */
189
        $repository = $entityManager->getRepository(BranchSync::class);
190
        /** @var BranchSync $branch */
191
        $branch = $repository->getTopBranch();
192
        if (is_a($branch, BranchSync::class)) {
193
            $uniqueId = $branch->getUniqueId();
194
        }
195
196
        $data = [
197
            'url' => api_get_path(WEB_PATH),
198
            'campus' => api_get_setting('siteName'),
199
            '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
200
            'version' => $system_version,
201
            'numberofcourses' => $number_of_courses, // to sum up into non-personal statistics - see https://version.chamilo.org/stats/
202
            'numberofusers' => $number_of_users, // to sum up into non-personal statistics
203
            'numberofactiveusers' => $number_of_active_users, // to sum up into non-personal statistics
204
            'numberofsessions' => $number_of_sessions,
205
            //The donotlistcampus setting recovery should be improved to make
206
            // it true by default - this does not affect numbers counting
207
            'donotlistcampus' => api_get_setting('donotlistcampus'),
208
            'organisation' => api_get_setting('Institution'),
209
            'language' => api_get_setting('platformLanguage'), //helps us know the spread of language usage for campuses, by main language
210
            '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

210
            '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

210
            'adminname' => api_get_setting('administratorName').' './** @scrutinizer ignore-type */ api_get_setting('administratorSurname'), //not sure this is necessary...
Loading history...
211
            '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
212
            // Reference to the packager system or provider through which
213
            // Chamilo is installed/downloaded. Packagers can change this in
214
            // the default config file (main/install/configuration.dist.php)
215
            // or in the installed config file. The default value is 'chamilo'
216
            'packager' => $packager,
217
            'unique_id' => $uniqueId,
218
        ];
219
220
        $version = null;
221
        $client = new GuzzleHttp\Client();
222
        $url .= '?';
223
        foreach ($data as $k => $v) {
224
            $url .= urlencode($k).'='.urlencode($v).'&';
225
        }
226
        $res = $client->request('GET', $url, $options);
227
        if ('200' == $res->getStatusCode()) {
228
            $versionData = $res->getHeader('X-Chamilo-Version');
229
            if (isset($versionData[0])) {
230
                $version = trim($versionData[0]);
231
            }
232
        }
233
234
        if (version_compare($system_version, $version, '<')) {
235
            $output = '<span style="color:red">'.
236
                get_lang('Your version is not up-to-date').'<br />'.
237
                get_lang('The latest version is').' <b>Chamilo '.$version.'</b>.  <br />'.
238
                get_lang('Your version is').' <b>Chamilo '.$system_version.$versionStatus.'</b>.  <br />'.
239
                str_replace(
240
                    'https://chamilo.org/download',
241
                    '<a href="https://chamilo.org/download">https://chamilo.org/download</a>',
242
                    get_lang('Please visit our website: https://chamilo.org/download')
243
                ).
244
                '</span>';
245
        } else {
246
            $output = '<span style="color:green">'.
247
                get_lang('Your version is up-to-date').'<br />'.
248
                get_lang('The latest version is').' <b>Chamilo '.$version.'</b>.  <br />'.
249
                get_lang('Your version is').' <b>Chamilo '.$system_version.$versionStatus.'</b>.  <br />'.
250
                '</span>';
251
        }
252
253
        return $output;
254
    }
255
256
    return '<span style="color:red">'.
257
        get_lang('Impossible to contact the version server right now. Please try again later.').'</span>';
258
}
259
260
/**
261
 * Display the latest news from the Chamilo Association for admins.
262
 *
263
 * @throws \GuzzleHttp\Exception\GuzzleException
264
 * @throws Exception
265
 *
266
 * @return string|void
267
 */
268
function getLatestNews()
269
{
270
    $url = 'https://version.chamilo.org/news/latest.php';
271
272
    $client = new Client();
273
    $response = $client->request(
274
        'GET',
275
        $url,
276
        [
277
            'query' => [
278
                'language' => api_get_language_isocode(),
279
            ],
280
        ]
281
    );
282
283
    if (200 !== $response->getStatusCode()) {
284
        throw new Exception(get_lang('Deny access'));
285
    }
286
287
    return $response->getBody()->getContents();
288
}
289
290
/**
291
 * Display the latest support services block.
292
 *
293
 * @throws \GuzzleHttp\Exception\GuzzleException
294
 * @throws Exception
295
 *
296
 * @return string|void
297
 */
298
function getProSupport()
299
{
300
    $url = 'https://version.chamilo.org/support/latest.php';
301
302
    $client = new Client();
303
    $response = $client->request(
304
        'GET',
305
        $url,
306
        [
307
            'query' => [
308
                'language' => api_get_language_isocode(),
309
            ],
310
        ]
311
    );
312
313
    if (200 !== $response->getStatusCode()) {
314
        throw new Exception(get_lang('Deny access'));
315
    }
316
317
    return $response->getBody()->getContents();
318
}
319