Passed
Push — master ( e80e7a...4357b6 )
by Julito
11:11 queued 02:04
created

Diagnoser::get_database_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 55
Code Lines 44

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 44
nc 1
nop 0
dl 0
loc 55
rs 9.216
c 0
b 0
f 0

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
3
/* For licensing terms, see /license.txt */
4
5
/**
6
 * Class Diagnoser
7
 * Class that is responsible for generating diagnostic information about the system.
8
 *
9
 * @author Ivan Tcholakov, 2008, initial proposal and sample code.
10
 * @author spou595, 2009, implementation for Chamilo 2.x
11
 * @author Julio Montoya <[email protected]>, 2010, port to chamilo 1.8.7, Some fixes
12
 */
13
class Diagnoser
14
{
15
    public const STATUS_OK = 1;
16
    public const STATUS_WARNING = 2;
17
    public const STATUS_ERROR = 3;
18
    public const STATUS_INFORMATION = 4;
19
20
    /**
21
     * Contructor.
22
     */
23
    public function __construct()
24
    {
25
    }
26
27
    /**
28
     * Show html table.
29
     */
30
    public function show_html()
31
    {
32
        $sections = [
33
            'chamilo' => [
34
                'lang' => 'Chamilo',
35
                'info' => 'State of Chamilo requirements',
36
            ],
37
            'php' => [
38
                'lang' => 'PHP',
39
                'info' => 'State of PHP settings on the server',
40
            ],
41
            'database' => [
42
                'lang' => 'Database',
43
                'info' => 'Configuration settings of the database server. To check the database consistency after an upgrade, if you have access to the command line, you can use "php bin/doctrine.php orm:schema-tool:update --dump-sql". This will print a list of database changes that should be applied to your system in order to get the right structure. Index name changes can be ignored. Use "--force" instead of "--dump" to try and execute them in order.',
44
            ],
45
            'webserver' => [
46
                'lang' => get_lang('Web server'),
47
                'info' => 'Information about your webserver\'s configuration ',
48
            ],
49
            'paths' => [
50
                'lang' => 'Paths',
51
                'info' => 'The following paths are called by their constant throughout Chamilo\'s code using the api_get_path() function. Here is a list of these paths and what they would be translated to on this portal.',
52
            ],
53
            'courses_space' => [
54
                'lang' => 'Courses space',
55
                'info' => 'Information about space used by courses on disk. The space used on disk represents the total space used, whereas the quota only limits files in the documents tool. Only 1000 courses are shown, by order of last access and alphabetical code order. For more, please go to the courses folder and use "du -sh *" to get the size of the courses.',
56
            ],
57
        ];
58
        $currentSection = isset($_GET['section']) ? $_GET['section'] : '';
59
        if (!in_array(trim($currentSection), array_keys($sections))) {
60
            $currentSection = 'chamilo';
61
        }
62
63
        $html = '<div class="tabbable"><ul class="nav nav-tabs">';
64
65
        foreach ($sections as $section => $details) {
66
            if ($currentSection === $section) {
67
                $html .= '<li class="active">';
68
            } else {
69
                $html .= '<li>';
70
            }
71
            $params['section'] = $section;
72
            $html .= '<a href="system_status.php?section='.$section.'">'.$details['lang'].'</a></li>';
73
        }
74
75
        $html .= '</ul><div class="tab-pane">';
76
77
        $data = call_user_func([$this, 'get_'.$currentSection.'_data']);
78
        echo $html;
79
80
        if ($currentSection === 'paths') {
81
            echo '<br />';
82
            echo Display::return_message($sections[$currentSection]['info'], 'normal');
83
84
            $headers = $data['headers'];
85
            $results = $data['data'];
86
            $table = new HTML_Table(['class' => 'table table-hover table-striped data_table']);
87
88
            $column = 0;
89
            foreach ($headers as $header) {
90
                $table->setHeaderContents(0, $column, $header);
91
                $column++;
92
            }
93
            $row = 1;
94
            foreach ($results as $index => $rowData) {
95
                $table->setCellContents(
96
                    $row,
97
                    0,
98
                    $rowData
99
                );
100
                $table->setCellContents(
101
                    $row,
102
                    1,
103
                    $index
104
                );
105
                $row++;
106
            }
107
            $table->display();
108
        } elseif ($currentSection == 'courses_space') {
109
            echo '<br />';
110
            echo Display::return_message($sections[$currentSection]['info'], 'normal');
111
112
            $table = new SortableTableFromArray($data, 1, 1000);
113
            $table->set_additional_parameters(['section' => 'courses_space']);
114
            $table->set_header(0, '', false);
115
            $table->set_header(1, get_lang('CourseCode'), true);
116
            $table->set_header(2, 'Space used on disk (MB)', true);
117
            $table->set_header(3, 'Set max course space (MB)', false);
118
            $table->set_header(4, get_lang('Edit'), false);
119
            $table->set_header(5, get_lang('LastVisit'), true);
120
            $table->set_header(6, get_lang('CurrentDirectory'), false);
121
122
            $table->display();
123
        } else {
124
            echo '<br />';
125
            echo Display::return_message($sections[$currentSection]['info'], 'normal');
126
127
            $table = new SortableTableFromArray($data, 1, 100);
128
            $table->set_header(0, '', false);
129
            $table->set_header(1, get_lang('Section'), false);
130
            $table->set_header(2, get_lang('Setting'), false);
131
            $table->set_header(3, get_lang('Current'), false);
132
            $table->set_header(4, get_lang('Expected'), false);
133
            $table->set_header(5, get_lang('Comment'), false);
134
135
            $table->display();
136
        }
137
        echo '</div></div>';
138
    }
139
140
    /**
141
     * @return array
142
     */
143
    public function get_paths_data()
144
    {
145
        global $paths;
146
        $list = $paths[api_get_path(WEB_PATH)];
147
        //$list['url_append'] = api_get_configuration_value('url_append');
148
        asort($list);
149
150
        return [
151
            'headers' => ['Path', 'constant'],
152
            'data' => $list,
153
        ];
154
    }
155
156
    /**
157
     * Functions to get the data for the chamilo diagnostics.
158
     *
159
     * @return array of data
160
     */
161
    public function get_chamilo_data()
162
    {
163
        $array = [];
164
        $writable_folders = [
165
            api_get_path(SYS_ARCHIVE_PATH).'cache',
166
            api_get_path(SYS_PATH).'upload/users/',
167
        ];
168
        foreach ($writable_folders as $index => $folder) {
169
            $writable = is_writable($folder);
170
            $status = $writable ? self::STATUS_OK : self::STATUS_ERROR;
171
            $array[] = $this->build_setting(
172
                $status,
173
                '[FILES]',
174
                get_lang('Is writable').': '.$folder,
175
                'http://be2.php.net/manual/en/function.is-writable.php',
176
                $writable,
177
                1,
178
                'yes_no',
179
                get_lang('The directory must be writable by the web server')
180
            );
181
        }
182
183
        $exists = file_exists(api_get_path(SYS_CODE_PATH).'install');
184
        $status = $exists ? self::STATUS_WARNING : self::STATUS_OK;
185
        $array[] = $this->build_setting(
186
            $status,
187
            '[FILES]',
188
            get_lang('The directory exists').': /install',
189
            'http://be2.php.net/file_exists',
190
            $exists,
191
            0,
192
            'yes_no',
193
            get_lang('The directory should be removed (it is no longer necessary)')
194
        );
195
196
        $app_version = api_get_setting('platform.chamilo_database_version');
197
        $array[] = $this->build_setting(
198
            self::STATUS_INFORMATION,
199
            '[DB]',
200
            'chamilo_database_version',
201
            '#',
202
            $app_version,
203
            0,
204
            null,
205
            'Chamilo DB version'
206
        );
207
208
        $access_url_id = api_get_current_access_url_id();
209
210
        if (1 === $access_url_id) {
211
            $size = '-';
212
            global $_configuration;
213
            $message2 = '';
214
            if (1 === $access_url_id) {
215
                if (api_is_windows_os()) {
216
                    $message2 .= get_lang('The space used on disk cannot be measured properly on Windows-based systems.');
217
                } else {
218
                    $dir = api_get_path(SYS_PATH);
219
                    $du = exec('du -sh '.$dir, $err);
220
                    list($size, $none) = explode("\t", $du);
221
                    unset($none);
222
                    $limit = 0;
223
                    if (isset($_configuration[$access_url_id])) {
224
                        if (isset($_configuration[$access_url_id]['hosting_limit_disk_space'])) {
225
                            $limit = $_configuration[$access_url_id]['hosting_limit_disk_space'];
226
                        }
227
                    }
228
                    $message2 .= sprintf(get_lang('Total space used by portal %s limit is %s MB'), $size, $limit);
229
                }
230
            }
231
232
            $array[] = $this->build_setting(
233
                self::STATUS_OK,
234
                '[FILES]',
235
                'hosting_limit_disk_space',
236
                '#',
237
                $size,
238
                0,
239
                null,
240
                $message2
241
            );
242
        }
243
        $new_version = '-';
244
        $new_version_status = '';
245
        $file = api_get_path(SYS_CODE_PATH).'install/version.php';
246
        if (is_file($file)) {
247
            @include $file;
248
        }
249
        $array[] = $this->build_setting(
250
            self::STATUS_INFORMATION,
251
            '[CONFIG]',
252
            get_lang('Version from the version file'),
253
            '#',
254
            $new_version.' '.$new_version_status,
255
            '-',
256
            null,
257
            get_lang('The version from the version.php file is updated with each version but only available if the main/install/ directory is present.')
258
        );
259
        $array[] = $this->build_setting(
260
            self::STATUS_INFORMATION,
261
            '[CONFIG]',
262
            get_lang('Version from the config file'),
263
            '#',
264
            api_get_configuration_value('system_version'),
265
            $new_version,
266
            null,
267
            get_lang('The version from the main configuration file shows on the main administration page, but has to be changed manually on upgrade.')
268
        );
269
270
        return $array;
271
    }
272
273
    /**
274
     * Functions to get the data for the php diagnostics.
275
     *
276
     * @return array of data
277
     */
278
    public function get_php_data()
279
    {
280
        $array = [];
281
282
        // General Functions
283
284
        $version = phpversion();
285
        $status = $version > REQUIRED_PHP_VERSION ? self::STATUS_OK : self::STATUS_ERROR;
286
        $array[] = $this->build_setting(
287
            $status,
288
            '[PHP]',
289
            'phpversion()',
290
            'https://php.net/manual/en/function.phpversion.php',
291
            phpversion(),
292
            '>= '.REQUIRED_PHP_VERSION,
293
            null,
294
            get_lang('PHP version')
295
        );
296
297
        $setting = ini_get('output_buffering');
298
        $req_setting = 1;
299
        $status = $setting >= $req_setting ? self::STATUS_OK : self::STATUS_ERROR;
300
        $array[] = $this->build_setting(
301
            $status,
302
            '[INI]',
303
            'output_buffering',
304
            'https://php.net/manual/en/outcontrol.configuration.php#ini.output-buffering',
305
            $setting,
306
            $req_setting,
307
            'on_off',
308
            get_lang('Output buffering setting is "On" for being enabled or "Off" for being disabled. This setting also may be enabled through an integer value (4096 for example) which is the output buffer size.')
309
        );
310
311
        $setting = ini_get('file_uploads');
312
        $req_setting = 1;
313
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_ERROR;
314
        $array[] = $this->build_setting(
315
            $status,
316
            '[INI]',
317
            'file_uploads',
318
            'https://php.net/manual/en/ini.core.php#ini.file-uploads',
319
            $setting,
320
            $req_setting,
321
            'on_off',
322
            get_lang('File uploads indicate whether file uploads are authorized at all')
323
        );
324
325
        $setting = ini_get('magic_quotes_runtime');
326
        $req_setting = 0;
327
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_ERROR;
328
        $array[] = $this->build_setting(
329
            $status,
330
            '[INI]',
331
            'magic_quotes_runtime',
332
            'https://php.net/manual/en/ini.core.php#ini.magic-quotes-runtime',
333
            $setting,
334
            $req_setting,
335
            'on_off',
336
            get_lang('This is a highly unrecommended feature which converts values returned by all functions that returned external values to slash-escaped values. This feature should *not* be enabled.')
337
        );
338
339
        $setting = ini_get('safe_mode');
340
        $req_setting = 0;
341
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_WARNING;
342
        $array[] = $this->build_setting(
343
            $status,
344
            '[INI]',
345
            'safe_mode',
346
            'https://php.net/manual/en/ini.core.php#ini.safe-mode',
347
            $setting,
348
            $req_setting,
349
            'on_off',
350
            get_lang('Safe mode is a deprecated PHP feature which (badly) limits the access of PHP scripts to other resources. It is recommended to leave it off.')
351
        );
352
353
        $setting = ini_get('register_globals');
354
        $req_setting = 0;
355
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_ERROR;
356
        $array[] = $this->build_setting(
357
            $status,
358
            '[INI]',
359
            'register_globals',
360
            'https://php.net/manual/en/ini.core.php#ini.register-globals',
361
            $setting,
362
            $req_setting,
363
            'on_off',
364
            get_lang('Whether to use the register globals feature or not. Using it represents potential security risks with this software.')
365
        );
366
367
        $setting = ini_get('short_open_tag');
368
        $req_setting = 0;
369
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_WARNING;
370
        $array[] = $this->build_setting(
371
            $status,
372
            '[INI]',
373
            'short_open_tag',
374
            'https://php.net/manual/en/ini.core.php#ini.short-open-tag',
375
            $setting,
376
            $req_setting,
377
            'on_off',
378
            get_lang('Whether to allow for short open tags to be used or not. This feature should not be used.')
379
        );
380
381
        $setting = ini_get('magic_quotes_gpc');
382
        $req_setting = 0;
383
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_ERROR;
384
        $array[] = $this->build_setting(
385
            $status,
386
            '[INI]',
387
            'magic_quotes_gpc',
388
            'https://php.net/manual/en/ini.core.php#ini.magic_quotes_gpc',
389
            $setting,
390
            $req_setting,
391
            'on_off',
392
            get_lang('Whether to automatically escape values from GET, POST and COOKIES arrays. A similar feature is provided for the required data inside this software, so using it provokes double slash-escaping of values.')
393
        );
394
395
        $setting = ini_get('display_errors');
396
        $req_setting = 0;
397
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_WARNING;
398
        $array[] = $this->build_setting(
399
            $status,
400
            '[INI]',
401
            'display_errors',
402
            'https://php.net/manual/en/ini.core.php#ini.display_errors',
403
            $setting,
404
            $req_setting,
405
            'on_off',
406
            get_lang('Show errors on screen. Turn this on on development servers, off on production servers.')
407
        );
408
409
        $setting = ini_get('default_charset');
410
        if ('' == $setting) {
411
            $setting = null;
412
        }
413
        $req_setting = 'UTF-8';
414
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_ERROR;
415
        $array[] = $this->build_setting(
416
            $status,
417
            '[INI]',
418
            'default_charset',
419
            'https://php.net/manual/en/ini.core.php#ini.default-charset',
420
            $setting,
421
            $req_setting,
422
            null,
423
            get_lang('The default character set to be sent when returning pages')
424
        );
425
426
        $setting = ini_get('max_execution_time');
427
        $req_setting = '300 ('.get_lang('minimum').')';
428
        $status = $setting >= 300 ? self::STATUS_OK : self::STATUS_WARNING;
429
        $array[] = $this->build_setting(
430
            $status,
431
            '[INI]',
432
            'max_execution_time',
433
            'https://php.net/manual/en/ini.core.php#ini.max-execution-time',
434
            $setting,
435
            $req_setting,
436
            null,
437
            get_lang('Maximum time a script can take to execute. If using more than that, the script is abandoned to avoid slowing down other users.')
438
        );
439
440
        $setting = ini_get('max_input_time');
441
        $req_setting = '300 ('.get_lang('minimum').')';
442
        $status = $setting >= 300 ? self::STATUS_OK : self::STATUS_WARNING;
443
        $array[] = $this->build_setting(
444
            $status,
445
            '[INI]',
446
            'max_input_time',
447
            'https://php.net/manual/en/ini.core.php#ini.max-input-time',
448
            $setting,
449
            $req_setting,
450
            null,
451
            get_lang('The maximum time allowed for a form to be processed by the server. If it takes longer, the process is abandonned and a blank page is returned.')
452
        );
453
454
        $setting = ini_get('memory_limit');
455
        $req_setting = '>= '.REQUIRED_MIN_MEMORY_LIMIT.'M';
456
        $status = self::STATUS_ERROR;
457
        if ((float) $setting >= REQUIRED_MIN_MEMORY_LIMIT) {
458
            $status = self::STATUS_OK;
459
        }
460
        $array[] = $this->build_setting(
461
            $status,
462
            '[INI]',
463
            'memory_limit',
464
            'https://php.net/manual/en/ini.core.php#ini.memory-limit',
465
            $setting,
466
            $req_setting,
467
            null,
468
            get_lang('Maximum memory limit for one single script run. If the memory needed is higher, the process will stop to avoid consuming all the server\'s available memory and thus slowing down other users.')
469
        );
470
471
        $setting = ini_get('post_max_size');
472
        $req_setting = '>= '.REQUIRED_MIN_POST_MAX_SIZE.'M';
473
        $status = self::STATUS_ERROR;
474
        if ((float) $setting >= REQUIRED_MIN_POST_MAX_SIZE) {
475
            $status = self::STATUS_OK;
476
        }
477
        $array[] = $this->build_setting(
478
            $status,
479
            '[INI]',
480
            'post_max_size',
481
            'https://php.net/manual/en/ini.core.php#ini.post-max-size',
482
            $setting,
483
            $req_setting,
484
            null,
485
            get_lang('This is the maximum size of uploads through forms using the POST method (i.e. classical file upload forms)')
486
        );
487
488
        $setting = ini_get('upload_max_filesize');
489
        $req_setting = '>= '.REQUIRED_MIN_UPLOAD_MAX_FILESIZE.'M';
490
        $status = self::STATUS_ERROR;
491
        if ((float) $setting >= REQUIRED_MIN_UPLOAD_MAX_FILESIZE) {
492
            $status = self::STATUS_OK;
493
        }
494
        $array[] = $this->build_setting(
495
            $status,
496
            '[INI]',
497
            'upload_max_filesize',
498
            'https://php.net/manual/en/ini.core.php#ini.upload_max_filesize',
499
            $setting,
500
            $req_setting,
501
            null,
502
            get_lang('Maximum volume of an uploaded file. This setting should, most of the time, be matched with the post_max_size variable.')
503
        );
504
505
        $setting = ini_get('upload_tmp_dir');
506
        $status = self::STATUS_OK;
507
        $array[] = $this->build_setting(
508
            $status,
509
            '[INI]',
510
            'upload_tmp_dir',
511
            'https://php.net/manual/en/ini.core.php#ini.upload_tmp_dir',
512
            $setting,
513
            '',
514
            null,
515
            get_lang('The temporary upload directory is a space on the server where files are uploaded before being filtered and treated by PHP.')
516
        );
517
518
        $setting = ini_get('variables_order');
519
        $req_setting = 'GPCS';
520
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_ERROR;
521
        $array[] = $this->build_setting(
522
            $status,
523
            '[INI]',
524
            'variables_order',
525
            'https://php.net/manual/en/ini.core.php#ini.variables-order',
526
            $setting,
527
            $req_setting,
528
            null,
529
            get_lang('The order of precedence of Environment, GET, POST, COOKIES and SESSION variables')
530
        );
531
532
        $setting = ini_get('session.gc_maxlifetime');
533
        $req_setting = '4320';
534
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_WARNING;
535
        $array[] = $this->build_setting(
536
            $status,
537
            '[SESSION]',
538
            'session.gc_maxlifetime',
539
            'https://php.net/manual/en/ini.core.php#session.gc-maxlifetime',
540
            $setting,
541
            $req_setting,
542
            null,
543
            get_lang('The session garbage collector maximum lifetime indicates which maximum time is given between two runs of the garbage collector.')
544
        );
545
546
        if (api_check_browscap()) {
547
            $setting = true;
548
        } else {
549
            $setting = false;
550
        }
551
        $req_setting = true;
552
        $status = $setting == $req_setting ? self::STATUS_OK : self::STATUS_WARNING;
553
        $array[] = $this->build_setting(
554
            $status,
555
            '[INI]',
556
            'browscap',
557
            'https://php.net/manual/en/misc.configuration.php#ini.browscap',
558
            $setting,
559
            $req_setting,
560
            'on_off',
561
            get_lang('Browscap loading browscap.ini file that contains a large amount of data on the browser and its capabilities, so it can be used by the function get_browser () PHP')
562
        );
563
564
        // Extensions
565
        $extensions = [
566
            'gd' => [
567
                'link' => 'https://php.net/gd',
568
                'expected' => 1,
569
                'comment' => get_lang('This extension must be loaded.'),
570
            ],
571
            'pdo_mysql' => [
572
                'link' => 'https://php.net/manual/en/ref.pdo-mysql.php',
573
                'expected' => 1,
574
                'comment' => get_lang('This extension must be loaded.'),
575
            ],
576
            'pcre' => [
577
                'link' => 'https://php.net/pcre',
578
                'expected' => 1,
579
                'comment' => get_lang('This extension must be loaded.'),
580
            ],
581
            'session' => [
582
                'link' => 'https://php.net/session',
583
                'expected' => 1,
584
                'comment' => get_lang('This extension must be loaded.'),
585
            ],
586
            'standard' => [
587
                'link' => 'https://php.net/spl',
588
                'expected' => 1,
589
                'comment' => get_lang('This extension must be loaded.'),
590
            ],
591
            'zlib' => [
592
                'link' => 'https://php.net/zlib',
593
                'expected' => 1,
594
                'comment' => get_lang('ExtensionMustBeLoaded'),
595
            ],
596
            'curl' => [
597
                'link' => 'https://php.net/curl',
598
                'expected' => 1,
599
                'comment' => get_lang('ExtensionMustBeLoaded'),
600
            ],
601
            'fileinfo' => [
602
                'link' => 'https://php.net/fileinfo',
603
                'expected' => 1,
604
                'comment' => get_lang('ExtensionMustBeLoaded'),
605
            ],
606
            'xsl' => [
607
                'link' => 'https://php.net/xsl',
608
                'expected' => 2,
609
                'comment' => get_lang('ExtensionShouldBeLoaded'),
610
            ],
611
            'Zend OPcache' => [
612
                'link' => 'https://php.net/opcache',
613
                'expected' => 2,
614
                'comment' => get_lang('This extension should be loaded.'),
615
            ],
616
            'apcu' => [
617
                'link' => 'https://php.net/apcu',
618
                'expected' => 2,
619
                'comment' => get_lang('This extension should be loaded.'),
620
            ],
621
            'exif' => [
622
                'link' => 'https://www.php.net/exif',
623
                'expected' => 1,
624
                'comment' => get_lang('This extension should be loaded.'),
625
            ],
626
            'mbstring' => [
627
                'link' => 'https://www.php.net/mbstring',
628
                'expected' => 1,
629
                'comment' => get_lang('This extension should be loaded.'),
630
            ],
631
            'openssl' => [ //required only for DKIM e-mail signatures
632
                'link' => 'https://php.net/openssl',
633
                'expected' => 2,
634
                'comment' => get_lang('ExtensionShouldBeLoaded'),
635
            ],
636
            'bcmath' => [
637
                'link' => 'https://php.net/bcmath',
638
                'expected' => 2,
639
                'comment' => get_lang('ExtensionShouldBeLoaded'),
640
            ],
641
        ];
642
643
        foreach ($extensions as $extension => $data) {
644
            $url = $data['link'];
645
            $expected_value = $data['expected'];
646
            $comment = $data['comment'];
647
648
            $loaded = extension_loaded($extension);
649
            $status = $loaded ? self::STATUS_OK : self::STATUS_ERROR;
650
            $array[] = $this->build_setting(
651
                $status,
652
                '[EXTENSION]',
653
                get_lang('Extension loaded').': '.$extension,
654
                $url,
655
                $loaded,
656
                $expected_value,
657
                'yes_no_optional',
658
                $comment
659
            );
660
        }
661
662
        return $array;
663
    }
664
665
    /**
666
     * Functions to get the data for the mysql diagnostics.
667
     *
668
     * @return array of data
669
     */
670
    public function get_database_data()
671
    {
672
        $array = [];
673
        $em = Database::getManager();
674
        $connection = $em->getConnection();
675
        $host = $connection->getHost();
676
        $db = $connection->getDatabase();
677
        $port = $connection->getPort();
678
        $driver = $connection->getDriver()->getName();
679
680
        $array[] = $this->build_setting(
681
            self::STATUS_INFORMATION,
682
            '[Database]',
683
            'driver',
684
            '',
685
            $driver,
686
            null,
687
            null,
688
            get_lang('Driver')
689
        );
690
691
        $array[] = $this->build_setting(
692
            self::STATUS_INFORMATION,
693
            '[Database]',
694
            'host',
695
            '',
696
            $host,
697
            null,
698
            null,
699
            get_lang('MySQL server host')
700
        );
701
702
        $array[] = $this->build_setting(
703
            self::STATUS_INFORMATION,
704
            '[Database]',
705
            'port',
706
            '',
707
            $port,
708
            null,
709
            null,
710
            get_lang('Port')
711
        );
712
713
        $array[] = $this->build_setting(
714
            self::STATUS_INFORMATION,
715
            '[Database]',
716
            'Database name',
717
            '',
718
            $db,
719
            null,
720
            null,
721
            get_lang('Name')
722
        );
723
724
        return $array;
725
    }
726
727
    /**
728
     * Functions to get the data for the webserver diagnostics.
729
     *
730
     * @return array of data
731
     */
732
    public function get_webserver_data()
733
    {
734
        $array = [];
735
736
        $array[] = $this->build_setting(
737
            self::STATUS_INFORMATION,
738
            '[SERVER]',
739
            '$_SERVER["SERVER_NAME"]',
740
            'http://be.php.net/reserved.variables.server',
741
            $_SERVER["SERVER_NAME"],
742
            null,
743
            null,
744
            get_lang('Server name (as used in your request)')
745
        );
746
        $array[] = $this->build_setting(
747
            self::STATUS_INFORMATION,
748
            '[SERVER]',
749
            '$_SERVER["SERVER_ADDR"]',
750
            'http://be.php.net/reserved.variables.server',
751
            $_SERVER["SERVER_ADDR"],
752
            null,
753
            null,
754
            get_lang('Server address')
755
        );
756
        $array[] = $this->build_setting(
757
            self::STATUS_INFORMATION,
758
            '[SERVER]',
759
            '$_SERVER["SERVER_PORT"]',
760
            'http://be.php.net/reserved.variables.server',
761
            $_SERVER["SERVER_PORT"],
762
            null,
763
            null,
764
            get_lang('Server port')
765
        );
766
        $array[] = $this->build_setting(
767
            self::STATUS_INFORMATION,
768
            '[SERVER]',
769
            '$_SERVER["SERVER_SOFTWARE"]',
770
            'http://be.php.net/reserved.variables.server',
771
            $_SERVER["SERVER_SOFTWARE"],
772
            null,
773
            null,
774
            get_lang('Software running as a web server')
775
        );
776
        $array[] = $this->build_setting(
777
            self::STATUS_INFORMATION,
778
            '[SERVER]',
779
            '$_SERVER["REMOTE_ADDR"]',
780
            'http://be.php.net/reserved.variables.server',
781
            $_SERVER["REMOTE_ADDR"],
782
            null,
783
            null,
784
            get_lang('Remote address (your address as received by the server)')
785
        );
786
        $array[] = $this->build_setting(
787
            self::STATUS_INFORMATION,
788
            '[SERVER]',
789
            '$_SERVER["HTTP_USER_AGENT"]',
790
            'http://be.php.net/reserved.variables.server',
791
            $_SERVER["HTTP_USER_AGENT"],
792
            null,
793
            null,
794
            get_lang('Your user agent as received by the server')
795
        );
796
        $array[] = $this->build_setting(
797
            self::STATUS_INFORMATION,
798
            '[SERVER]',
799
            '$_SERVER["SERVER_PROTOCOL"]',
800
            'http://be.php.net/reserved.variables.server',
801
            $_SERVER["SERVER_PROTOCOL"],
802
            null,
803
            null,
804
            get_lang('Protocol used by this server')
805
        );
806
        $array[] = $this->build_setting(
807
            self::STATUS_INFORMATION,
808
            '[SERVER]',
809
            'php_uname()',
810
            'http://be2.php.net/php_uname',
811
            php_uname(),
812
            null,
813
            null,
814
            get_lang('Information on the system the current server is running on')
815
        );
816
        $array[] = $this->build_setting(
817
            self::STATUS_INFORMATION,
818
            '[SERVER]',
819
            '$_SERVER["HTTP_X_FORWARDED_FOR"]',
820
            'http://be.php.net/reserved.variables.server',
821
            (!empty($_SERVER["HTTP_X_FORWARDED_FOR"]) ? $_SERVER["HTTP_X_FORWARDED_FOR"] : ''),
822
            null,
823
            null,
824
            get_lang('If the server is behind a proxy or firewall (and only in those cases), it might be using the X_FORWARDED_FOR HTTP header to show the remote user IP (yours, in this case).')
825
        );
826
827
        return $array;
828
    }
829
830
    /**
831
     * Functions to get the data for the courses space usage.
832
     *
833
     * @throws Exception
834
     *
835
     * @return array of data
836
     */
837
    public function get_courses_space_data()
838
    {
839
        $array = [];
840
841
        $em = Database::getManager();
842
        $connection = $em->getConnection();
843
        $res = $connection->query('SELECT id, code, directory, disk_quota, last_visit FROM course ORDER BY last_visit DESC, code LIMIT 500');
844
        $systemPath = api_get_path(SYS_COURSE_PATH);
0 ignored issues
show
Bug introduced by
The constant SYS_COURSE_PATH was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
845
        $webPath = api_get_path(WEB_COURSE_PATH);
846
        $courseHomeIcon = Display::return_icon('home.png', get_lang('CourseHome'));
847
        $courseEditIcon = Display::return_icon('edit.png', get_lang('Edit'));
848
        $windows = api_is_windows_os();
849
        $courseEditPath = api_get_path(WEB_CODE_PATH).'admin/course_edit.php?id=';
850
        while ($row = $res->fetch()) {
851
            $quota = $row['disk_quota'] / (1024 * 1024);
852
            $dir = $systemPath.$row['directory'].'/';
853
            $path = '<a href="'.$webPath.$row['code'].'/index.php?id_session=0">'.$courseHomeIcon.'</a>';
854
            $size = '-';
855
            $courseEditLink = '<a href="'.$courseEditPath.$row['id'].'">'.$courseEditIcon.'</a>';
856
857
            if (!$windows) {
858
                $err = [];
859
                $du = exec('du -s '.$dir, $err);
860
                list($size, $none) = explode("\t", $du);
861
                unset($none);
862
                $size = intval($size);
863
                if ($size < 1024) {
864
                    $size = 1;
865
                } else {
866
                    $size = round($size / 1024);
867
                }
868
            }
869
            $array[] = [
870
                $path,
871
                $row['code'],
872
                $size,
873
                round($quota),
874
                $courseEditLink,
875
                $row['last_visit'],
876
                $dir,
877
            ];
878
        }
879
880
        return $array;
881
    }
882
883
    /**
884
     * Functions to get the number of courses in the database.
885
     *
886
     * @throws Exception
887
     *
888
     * @return array of data
889
     */
890
    public function get_courses_space_count()
891
    {
892
        $em = Database::getManager();
893
        $connection = $em->getConnection();
894
        $res = $connection->query('SELECT count(id) FROM course');
895
        while ($row = $res->fetch()) {
896
            $count = $row[0];
897
        }
898
899
        return $count;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $count does not seem to be defined for all execution paths leading up to this point.
Loading history...
900
    }
901
902
    /**
903
     * Additional functions needed for fast integration.
904
     *
905
     * @param int    $status         Status constant defining which icon to use to illustrate the info
906
     * @param string $section        The name of the section this setting is included in
907
     * @param string $title          The name of the setting (usually a translated string)
908
     * @param string $url            A URL to point the user to regarding this setting, or '#' otherwise
909
     * @param mixed  $current_value  The current value for this setting
910
     * @param mixed  $expected_value The expected value for this setting
911
     * @param string $formatter      If this setting is expressed in some kind of format, which format to use
912
     * @param string $comment        A translated string explaining what this setting represents
913
     *
914
     * @return array A list of elements to show in an array's row
915
     */
916
    public function build_setting(
917
        $status,
918
        $section,
919
        $title,
920
        $url,
921
        $current_value,
922
        $expected_value,
923
        $formatter,
924
        $comment
925
    ) {
926
        switch ($status) {
927
            case self::STATUS_OK:
928
                $img = 'bullet_green.png';
929
                break;
930
            case self::STATUS_WARNING:
931
                $img = 'bullet_orange.png';
932
                break;
933
            case self::STATUS_ERROR:
934
                $img = 'bullet_red.png';
935
                break;
936
            case self::STATUS_INFORMATION:
937
            default:
938
                $img = 'bullet_blue.png';
939
                break;
940
        }
941
942
        $image = Display::return_icon($img, $status);
943
        $url = $this->get_link($title, $url);
944
945
        $formatted_current_value = $current_value;
946
        $formatted_expected_value = $expected_value;
947
948
        if ($formatter) {
949
            if (method_exists($this, 'format_'.$formatter)) {
950
                $formatted_current_value = call_user_func([$this, 'format_'.$formatter], $current_value);
951
                $formatted_expected_value = call_user_func([$this, 'format_'.$formatter], $expected_value);
952
            }
953
        }
954
955
        return [$image, $section, $url, $formatted_current_value, $formatted_expected_value, $comment];
956
    }
957
958
    /**
959
     * Create a link with a url and a title.
960
     *
961
     * @param $title
962
     * @param $url
963
     *
964
     * @return string the url
965
     */
966
    public function get_link($title, $url)
967
    {
968
        return '<a href="'.$url.'" target="about:bank">'.$title.'</a>';
969
    }
970
971
    /**
972
     * @param int $value
973
     *
974
     * @return string
975
     */
976
    public function format_yes_no_optional($value)
977
    {
978
        $return = '';
979
        switch ($value) {
980
            case 0:
981
                $return = get_lang('No');
982
                break;
983
            case 1:
984
                $return = get_lang('Yes');
985
                break;
986
            case 2:
987
                $return = get_lang('Optional');
988
                break;
989
        }
990
991
        return $return;
992
    }
993
994
    /**
995
     * @param $value
996
     *
997
     * @return string
998
     */
999
    public function format_yes_no($value)
1000
    {
1001
        return $value ? get_lang('Yes') : get_lang('No');
1002
    }
1003
1004
    /**
1005
     * @param int $value
1006
     *
1007
     * @return string
1008
     */
1009
    public function format_on_off($value)
1010
    {
1011
        $value = intval($value);
1012
        if ($value > 1) {
1013
            // Greater than 1 values are shown "as-is", they may be interpreted as "On" later.
1014
            return $value;
1015
        }
1016
        // These are the values 'On' and 'Off' used in the php-ini file. Translation (get_lang()) is not needed here.
1017
        return $value ? 'On' : 'Off';
1018
    }
1019
}
1020