Completed
Branch master (bfab80)
by Daniel
02:10
created

Informator::getApacheDetails()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 21
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 13
Bugs 0 Features 5
Metric Value
c 13
b 0
f 5
dl 0
loc 21
rs 9.3143
cc 2
eloc 16
nc 2
nop 0
1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\informator;
30
31
class Informator
32
{
33
34
    use \danielgp\common_lib\CommonCode;
35
36
    private $informatorInternalArray;
37
38
    public function __construct()
39
    {
40
        $this->informatorInternalArray['composerLockFile'] = realpath('../') . DIRECTORY_SEPARATOR . 'composer.lock';
41
        $this->informatorInternalArray['knownLabels']      = [
42
            '--- List of known labels' => '',
43
            'Apache Info'              => ['getApacheDetails', null],
44
            'Auto Dependencies'        => [
45
                'getPackageDetailsFromGivenComposerLockFile',
46
                $this->informatorInternalArray['composerLockFile'],
47
            ],
48
            'Auto Dependencies File'   => [$this->informatorInternalArray['composerLockFile']],
49
            'Client Info'              => ['getClientBrowserDetailsForInformator', null],
50
            'Informator File Details'  => ['getFileDetails', __FILE__],
51
            'MySQL Databases All'      => ['getMySQLinfo', ['Databases All']],
52
            'MySQL Databases Client'   => ['getMySQLinfo', ['Databases Client']],
53
            'MySQL Engines Active'     => ['getMySQLinfo', ['Engines Active']],
54
            'MySQL Engines All'        => ['getMySQLinfo', ['Engines All']],
55
            'MySQL General'            => ['getMySQLinfo', ['General']],
56
            'MySQL Variables Global'   => ['getMySQLinfo', ['Variables Global']],
57
            'MySQL Info'               => ['getMySQLinfo', ['Engines Active', 'General', 'Variables Global']],
58
            'Php Extensions Loaded'    => ['getPhpDetails', ['Extensions Loaded']],
59
            'Php General'              => ['getPhpDetails', ['General']],
60
            'Php INI Settings'         => ['getPhpDetails', ['INI Settings']],
61
            'Php Stream Filters'       => ['getPhpDetails', ['Stream Filters']],
62
            'Php Stream Transports'    => ['getPhpDetails', ['Stream Transports']],
63
            'Php Stream Wrappers'      => ['getPhpDetails', ['Stream Wrappers']],
64
            'Php Info'                 => ['getPhpDetails', null],
65
            'Server Info'              => ['getServerDetails', null],
66
            'System Info'              => ['systemInfo', null],
67
            'Tomcat Info'              => ['getTomcatDetails', null],
68
        ];
69
        ksort($this->informatorInternalArray['knownLabels']);
70
        $rqst                                              = new \Symfony\Component\HttpFoundation\Request;
71
        $this->informatorInternalArray['superGlobals']     = $rqst->createFromGlobals();
72
        echo $this->setInterface();
73
    }
74
75
    private function getApacheDetails()
0 ignored issues
show
Coding Style introduced by
getApacheDetails uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
76
    {
77
        $srvSignature     = $_SERVER['SERVER_SOFTWARE'];
78
        $srvSoftwareArray = explode(' ', $srvSignature);
79
        $sInfo            = [];
80
        $tmp              = explode('/', $srvSoftwareArray[0]);
81
        if (strpos($srvSoftwareArray[0], 'Apache') !== false) {
82
            $sInfo['Apache'] = [
83
                'Name'      => $tmp[0],
84
                'Signature' => $srvSignature,
85
                'Version'   => $tmp[1]
86
            ];
87
        }
88
        $modulesToDisregard         = [
89
            $srvSoftwareArray[0],
90
            '(Win64)',
91
        ];
92
        $sInfo['Apache']['Modules'] = $this->getApacheModules(array_diff($srvSoftwareArray, $modulesToDisregard));
93
        ksort($sInfo['Apache']);
94
        return $sInfo['Apache'];
95
    }
96
97
    private function getApacheModules(array $srvSoftwareArray)
98
    {
99
        $aReturn = [];
100
        foreach ($srvSoftwareArray as $value) {
101
            $tmp                  = explode('/', $value);
102
            $rootModule           = strtolower(str_replace(['mod_', 'OpenSSL'], ['', 'SSL'], $tmp[0]));
103
            $aReturn[$rootModule] = [
104
                'Name'    => $tmp[0],
105
                'Version' => $tmp[1]
106
            ];
107
        }
108
        ksort($aReturn);
109
        return $aReturn;
110
    }
111
112
    private function getClientBrowserDetailsForInformator()
113
    {
114
        $tmpFolder        = $this->getTemporaryFolder();
115
        $tmpDoctrineCache = null;
116
        clearstatcache();
117
        if (is_dir($tmpFolder) && is_writable($tmpFolder)) {
118
            $tmpDoctrineCache = $tmpFolder . DIRECTORY_SEPARATOR . 'DoctrineCache';
119
        }
120
        return $this->getClientBrowserDetails(['Browser', 'Device', 'OS'], $tmpDoctrineCache);
121
    }
122
123
    private function getMySQLinfo($returnType = ['Engines Active', 'General', 'Variables Global'])
124
    {
125
        if (is_null($this->mySQLconnection)) {
126
            $mySQLconfig = [
127
                'host'     => MYSQL_HOST,
128
                'port'     => MYSQL_PORT,
129
                'username' => MYSQL_USERNAME,
130
                'password' => MYSQL_PASSWORD,
131
                'database' => MYSQL_DATABASE,
132
            ];
133
            $this->connectToMySql($mySQLconfig);
134
        }
135
        $sInfo           = [];
136
        $aMySQLinfoLabel = [
137
            'Databases All'    => ['getMySQLlistDatabases', false],
138
            'Databases Client' => ['getMySQLlistDatabases', true],
139
            'Engines Active'   => ['getMySQLlistEngines', true],
140
            'Engines All'      => ['getMySQLlistEngines', false],
141
            'General'          => ['getMySQLgenericInformations'],
142
            'Variables Global' => ['getMySQLglobalVariables'],
143
        ];
144
        foreach ($returnType as $value) {
145
            $aVal = $aMySQLinfoLabel[$value];
146
            switch (count($aVal)) {
147 View Code Duplication
                case 1:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
148
                    $sInfo['MySQL'][$value] = call_user_func([$this, $aVal[0]]);
149
                    break;
150 View Code Duplication
                case 2:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
151
                    $sInfo['MySQL'][$value] = call_user_func([this, $aVal[0]], $aVal[1]);
152
                    break;
153
            }
154
        }
155
        ksort($sInfo['MySQL']);
156
        return $sInfo['MySQL'];
157
    }
158
159
    private function getPhpDetails($returnType = ['General', 'INI Settings', 'Extensions Loaded', 'Temporary Folder'])
160
    {
161
        $sInfo = [];
162
        foreach ($returnType as $value) {
163
            switch ($value) {
164
                case 'Extensions Loaded':
165
                    $sInfo['PHP'][$value] = $this->setArrayValuesAsKey(get_loaded_extensions());
0 ignored issues
show
Documentation introduced by
get_loaded_extensions() is of type array, but the function expects a object<danielgp\common_lib\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
166
                    break;
167
                case 'General':
168
                    $sInfo['PHP'][$value] = [
169
                        'Version'             => phpversion(),
170
                        'Zend Engine Version' => zend_version(),
171
                    ];
172
                    break;
173
                case 'INI Settings':
174
                    $sInfo['PHP'][$value] = ini_get_all(null, false);
175
                    break;
176 View Code Duplication
                case 'Stream Filters':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
                    $sArray               = (array) stream_get_filters();
178
                    $sInfo['PHP'][$value] = $this->setArrayValuesAsKey($sArray);
0 ignored issues
show
Documentation introduced by
$sArray is of type array, but the function expects a object<danielgp\common_lib\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
179
                    break;
180 View Code Duplication
                case 'Stream Transports':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
181
                    $sArray               = (array) stream_get_transports();
182
                    $sInfo['PHP'][$value] = $this->setArrayValuesAsKey($sArray);
0 ignored issues
show
Documentation introduced by
$sArray is of type array, but the function expects a object<danielgp\common_lib\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
183
                    break;
184 View Code Duplication
                case 'Stream Wrappers':
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
185
                    $sArray               = (array) stream_get_wrappers();
186
                    $sInfo['PHP'][$value] = $this->setArrayValuesAsKey($sArray);
0 ignored issues
show
Documentation introduced by
$sArray is of type array, but the function expects a object<danielgp\common_lib\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
187
                    break;
188
                case 'Temporary Folder':
189
                    $sInfo['PHP'][$value] = $this->getTemporaryFolder();
190
                    break;
191
            }
192
        }
193
        ksort($sInfo['PHP']);
194
        return $sInfo['PHP'];
195
    }
196
197
    private function getServerDetails()
198
    {
199
        $serverMachineType = 'unknown';
200
        $serverInfo        = [
201
            'name'    => 'undisclosed',
202
            'host'    => $this->informatorInternalArray['superGlobals']->getHttpHost(),
203
            'release' => 'undisclosed',
204
            'version' => 'undisclosed',
205
        ];
206
        if (function_exists('php_uname')) {
207
            switch (php_uname('m')) {
208
                case 'AMD64':
209
                    $serverMachineType = 'x64 (64 bit)';
210
                    break;
211
                case 'i386':
212
                case 'i586':
213
                    $serverMachineType = 'x86 (32 bit)';
214
                    break;
215
                default:
216
                    $serverMachineType = php_uname('m');
217
                    break;
218
            }
219
            $serverInfo = [
220
                'name'    => php_uname('s'),
221
                'host'    => php_uname('n'),
222
                'release' => php_uname('r'),
223
                'version' => php_uname('v'),
224
            ];
225
        }
226
        $srvIp = gethostbyname($this->informatorInternalArray['superGlobals']->getHttpHost());
227
        return [
228
            'OS'              => php_uname(),
229
            'OS Architecture' => $serverMachineType,
230
            'OS Date/time'    => date('Y-m-d H:i:s'),
231
            'OS Ip'           => $srvIp,
232
            'OS Ip type'      => $this->checkIpIsPrivate($srvIp),
0 ignored issues
show
Documentation introduced by
$srvIp is of type string, but the function expects a object<danielgp\network_components\ipv4>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
233
            'OS Ip v4/v6'     => $this->checkIpIsV4OrV6($srvIp),
0 ignored issues
show
Documentation introduced by
$srvIp is of type string, but the function expects a object<danielgp\network_components\ipv4>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
234
            'OS Name'         => $serverInfo['name'],
235
            'OS Host'         => $serverInfo['host'],
236
            'OS Release'      => $serverInfo['release'],
237
            'OS Version'      => $serverInfo['version'],
238
        ];
239
    }
240
241
    private function getTemporaryFolder()
242
    {
243
        return sys_get_temp_dir() . DIRECTORY_SEPARATOR;
244
    }
245
246
    private function getTomcatDetails()
247
    {
248
        $sReturn           = [];
249
        $sReturn['Tomcat'] = '---';
250
        $url               = 'http://' . $this->informatorInternalArray['superGlobals']->getHttpHost()
251
                . ':8080/informator.Tomcat/index.jsp';
252
        $urlFeedback       = $this->getContentFromUrlThroughCurlAsArrayIfJson($url);
253
        if (is_array($urlFeedback) && isset($urlFeedback['response'])) {
254
            $sReturn['Tomcat'] = $urlFeedback['response'];
255
        }
256
        return $sReturn;
257
    }
258
259
    private function setInterface()
260
    {
261
        $requestedLabel = $this->informatorInternalArray['superGlobals']->get('Label');
262
        $showLabels     = true;
263
        $feedback       = '<span style="background-color:red;color:white;">Label not set...</span>';
264
        $arToReturn     = [];
265
        if (isset($requestedLabel)) {
266
            $feedback = '<span style="background-color:red;color:white;">'
267
                    . 'Unknown label transmited...'
268
                    . '</span>';
269
            if (array_key_exists($requestedLabel, $this->informatorInternalArray['knownLabels'])) {
270
                $showLabels = false;
271
                $feedback   = '';
272
                $lblValue   = $this->informatorInternalArray['knownLabels'][$requestedLabel];
273
                if ($requestedLabel == '--- List of known labels') {
274
                    $arToReturn = array_keys($this->informatorInternalArray['knownLabels']);
275
                } elseif ($requestedLabel == 'Auto Dependencies File') {
276
                    $arToReturn = $lblValue;
277
                } elseif ($requestedLabel == 'System Info') {
278
                    $arToReturn = $this->systemInfo();
279
                } elseif (is_null($lblValue[1])) {
280
                    $arToReturn = call_user_func([$this, $lblValue[0]]);
281
                } elseif (is_array($lblValue[1])) {
282
                    $arToReturn = call_user_func_array([$this, $lblValue[0]], [$lblValue[1]]);
283
                } elseif (is_string($lblValue[1])) {
284
                    $arToReturn = call_user_func([$this, $lblValue[0]], $lblValue[1]);
285
                }
286
            }
287
        }
288
        $outputArray = [
289
            'showLabels'    => $showLabels,
290
            'feedback'      => $feedback,
291
            'arrayToReturn' => $arToReturn,
292
        ];
293
        return $this->setOutputInterface($outputArray);
294
    }
295
296
    private function setOutputInterface($inArray)
297
    {
298
        if ($inArray['showLabels']) {
299
            $sReturn    = [];
300
            $sReturn[]  = $this->setHeaderCommon([
301
                'lang'  => 'en-US',
302
                'title' => 'Informator'
303
            ]);
304
            $sReturn[]  = $inArray['feedback'] . '<p style="background-color:green;color:white;">'
305
                    . 'So you might want to choose one from the list below:</p>'
306
                    . '<ul>';
307
            $arToReturn = array_keys($this->informatorInternalArray['knownLabels']);
308
            foreach ($arToReturn as $value) {
309
                $sReturn[] = '<li>'
310
                        . '<a href="?Label=' . urlencode($value) . '" target="_blank">' . $value . '</a>'
311
                        . '</li>';
312
            }
313
            $sReturn[] = '</ul>' . $this->setFooterCommon();
314
            return implode('', $sReturn);
315
        }
316
        $this->setHeaderGZiped();
317
        $this->setHeaderNoCache('application/json');
318
        echo $this->setArrayToJson($inArray['arrayToReturn']);
319
        $this->setFooterGZiped();
320
    }
321
322
    /**
323
     * Builds an array with most important key aspects of LAMP/WAMP
324
     * @return array
325
     */
326
    private function systemInfo()
327
    {
328
        $cFile = $this->informatorInternalArray['composerLockFile'];
329
        return [
330
            'Apache'            => $this->getApacheDetails(),
331
            'Auto Dependencies' => $this->getPackageDetailsFromGivenComposerLockFile($cFile),
332
            'Client'            => $this->getClientBrowserDetailsForInformator(),
333
            'InfoCompareFile'   => $this->getFileDetails(__FILE__),
334
            'MySQL'             => $this->getMySQLinfo(),
335
            'PHP'               => $this->getPhpDetails(),
336
            'Server'            => $this->getServerDetails(),
337
            'Tomcat'            => $this->getTomcatDetails()['Tomcat'],
338
        ];
339
    }
340
}
341