Completed
Push — master ( 2ee5f7...8f1dcc )
by Daniel
02:10
created

Informator::getServerDetailsFromPhp()   B

Complexity

Conditions 4
Paths 4

Size

Total Lines 23
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
rs 8.7972
cc 4
eloc 19
nc 4
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'],
65
            'Server Info'              => ['getServerDetails'],
66
            'System Info'              => ['systemInfo'],
67
            'Tomcat Info'              => ['getTomcatDetails'],
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 callDynamicFunctionToGetResults(array $inLabelsArray)
76
    {
77
        $aReturn = [];
78
        switch (count($inLabelsArray)) {
79
            case 1:
80
                $aReturn = call_user_func([$this, $inLabelsArray[0]]);
81
                break;
82
            case 2:
83
                if (is_array($inLabelsArray[1])) {
84
                    $aReturn = call_user_func_array([$this, $inLabelsArray[0]], [$inLabelsArray[1]]);
85
                }
86
                if (!is_array($inLabelsArray[1])) {
87
                    $standardPhpFunctions = [
88
                        'get_loaded_extensions',
89
                        'stream_get_filters',
90
                        'stream_get_transports',
91
                        'stream_get_wrappers',
92
                    ];
93
                    $dynFnPrmtr           = $inLabelsArray[1];
94
                    if (in_array($inLabelsArray[1], $standardPhpFunctions)) {
95
                        $dynFnPrmtr = call_user_func($inLabelsArray[1]);
96
                    }
97
                    $aReturn = call_user_func([$this, $inLabelsArray[0]], $dynFnPrmtr);
98
                }
99
                break;
100
        }
101
        return $aReturn;
102
    }
103
104
    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...
105
    {
106
        $srvSignature     = $_SERVER['SERVER_SOFTWARE'];
107
        $srvSoftwareArray = explode(' ', $srvSignature);
108
        $sInfo            = [];
109
        $tmp              = explode('/', $srvSoftwareArray[0]);
110
        if (strpos($srvSoftwareArray[0], 'Apache') !== false) {
111
            $sInfo['Apache'] = [
112
                'Name'      => $tmp[0],
113
                'Signature' => $srvSignature,
114
                'Version'   => $tmp[1]
115
            ];
116
        }
117
        $modulesToDisregard         = [
118
            $srvSoftwareArray[0],
119
            '(Win64)',
120
        ];
121
        $sInfo['Apache']['Modules'] = $this->getApacheModules(array_diff($srvSoftwareArray, $modulesToDisregard));
122
        ksort($sInfo['Apache']);
123
        return $sInfo['Apache'];
124
    }
125
126
    private function getApacheModules(array $srvSoftwareArray)
127
    {
128
        $aReturn = [];
129
        foreach ($srvSoftwareArray as $value) {
130
            $tmp                  = explode('/', $value);
131
            $rootModule           = strtolower(str_replace(['mod_', 'OpenSSL'], ['', 'SSL'], $tmp[0]));
132
            $aReturn[$rootModule] = [
133
                'Name'    => $tmp[0],
134
                'Version' => $tmp[1]
135
            ];
136
        }
137
        ksort($aReturn);
138
        return $aReturn;
139
    }
140
141
    private function getClientBrowserDetailsForInformator()
142
    {
143
        $tmpFolder        = $this->getTemporaryFolder();
144
        $tmpDoctrineCache = null;
145
        clearstatcache();
146
        if (is_dir($tmpFolder) && is_writable($tmpFolder)) {
147
            $tmpDoctrineCache = $tmpFolder . DIRECTORY_SEPARATOR . 'DoctrineCache';
148
        }
149
        return $this->getClientBrowserDetails(['Browser', 'Device', 'OS'], $tmpDoctrineCache);
150
    }
151
152
    private function getMySQLinfo($returnType = ['Engines Active', 'General', 'Variables Global'])
153
    {
154
        if (is_null($this->mySQLconnection)) {
155
            $this->connectToMySql([
156
                'host'     => MYSQL_HOST,
157
                'port'     => MYSQL_PORT,
158
                'username' => MYSQL_USERNAME,
159
                'password' => MYSQL_PASSWORD,
160
                'database' => MYSQL_DATABASE,
161
            ]);
162
        }
163
        $sInfo           = [];
164
        $aMySQLinfoLabel = [
165
            'Databases All'    => ['getMySQLlistDatabases', false],
166
            'Databases Client' => ['getMySQLlistDatabases', true],
167
            'Engines Active'   => ['getMySQLlistEngines', true],
168
            'Engines All'      => ['getMySQLlistEngines', false],
169
            'General'          => ['getMySQLgenericInformations'],
170
            'Variables Global' => ['getMySQLglobalVariables'],
171
        ];
172
        foreach ($returnType as $value) {
173
            $sInfo['MySQL'][$value] = $this->callDynamicFunctionToGetResults($aMySQLinfoLabel[$value]);
174
        }
175
        ksort($sInfo['MySQL']);
176
        return $sInfo['MySQL'];
177
    }
178
179
    private function getPhpDetails($returnType = ['General', 'INI Settings', 'Extensions Loaded', 'Temporary Folder'])
180
    {
181
        $sInfo = [];
182
        foreach ($returnType as $value) {
183
            switch ($value) {
184
                case 'General':
185
                    $sInfo['PHP'][$value] = [
186
                        'Version'             => phpversion(),
187
                        'Zend Engine Version' => zend_version(),
188
                    ];
189
                    break;
190
                case 'INI Settings':
191
                    $sInfo['PHP'][$value] = ini_get_all(null, false);
192
                    break;
193
                default:
194
                    $stLabels             = [
195
                        'Extensions Loaded' => ['setArrayValuesAsKey', 'get_loaded_extensions'],
196
                        'Stream Filters'    => ['setArrayValuesAsKey', 'stream_get_filters'],
197
                        'Stream Transports' => ['setArrayValuesAsKey', 'stream_get_transports'],
198
                        'Stream Wrappers'   => ['setArrayValuesAsKey', 'stream_get_wrappers'],
199
                        'Temporary Folder'  => ['getTemporaryFolder'],
200
                    ];
201
                    $sInfo['PHP'][$value] = $this->callDynamicFunctionToGetResults($stLabels[$value]);
202
                    break;
203
            }
204
        }
205
        ksort($sInfo['PHP']);
206
        return $sInfo['PHP'];
207
    }
208
209
    private function getServerDetails()
210
    {
211
        $serverMachineType = 'unknown';
212
        $hst               = $this->informatorInternalArray['superGlobals']->getHttpHost();
213
        $serverInfo        = [
214
            'name'    => 'undisclosed',
215
            'host'    => $hst,
216
            'release' => 'undisclosed',
217
            'version' => 'undisclosed',
218
        ];
219
        if (function_exists('php_uname')) {
220
            $infServerFromPhp  = $this->getServerDetailsFromPhp();
221
            $serverMachineType = $infServerFromPhp['OS Architecture'];
222
            $serverInfo        = $infServerFromPhp['OS Name+Host+Release+Version'];
223
        }
224
        $srvIp = filter_var(gethostbyname($hst), FILTER_VALIDATE_IP);
225
        return [
226
            'OS'              => php_uname(),
227
            'OS Architecture' => $serverMachineType,
228
            'OS Date/time'    => date('Y-m-d H:i:s'),
229
            'OS Ip'           => $srvIp,
230
            'OS Ip type'      => $this->checkIpIsPrivate($srvIp),
231
            'OS Ip v4/v6'     => $this->checkIpIsV4OrV6($srvIp),
232
            'OS Name'         => $serverInfo['name'],
233
            'OS Host'         => $serverInfo['host'],
234
            'OS Release'      => $serverInfo['release'],
235
            'OS Version'      => $serverInfo['version'],
236
        ];
237
    }
238
239
    private function getServerDetailsFromPhp()
240
    {
241
        $aReturn = [];
242
        switch (php_uname('m')) {
243
            case 'AMD64':
244
                $aReturn['OS Architecture'] = 'x64 (64 bit)';
245
                break;
246
            case 'i386':
247
            case 'i586':
248
                $aReturn['OS Architecture'] = 'x86 (32 bit)';
249
                break;
250
            default:
251
                $aReturn['OS Architecture'] = php_uname('m');
252
                break;
253
        }
254
        $aReturn['OS Name+Host+Release+Version'] = [
255
            'name'    => php_uname('s'),
256
            'host'    => php_uname('n'),
257
            'release' => php_uname('r'),
258
            'version' => php_uname('v'),
259
        ];
260
        return $aReturn;
261
    }
262
263
    private function getTemporaryFolder()
264
    {
265
        return sys_get_temp_dir() . DIRECTORY_SEPARATOR;
266
    }
267
268
    private function getTomcatDetails()
269
    {
270
        $sReturn           = [];
271
        $sReturn['Tomcat'] = '---';
272
        $url               = 'http://' . $this->informatorInternalArray['superGlobals']->getHttpHost()
273
                . ':8080/informator.Tomcat/index.jsp';
274
        $urlFeedback       = $this->getContentFromUrlThroughCurlAsArrayIfJson($url);
275
        if (is_array($urlFeedback) && isset($urlFeedback['response'])) {
276
            $sReturn['Tomcat'] = $urlFeedback['response'];
277
        }
278
        return $sReturn;
279
    }
280
281
    private function setInterface()
282
    {
283
        $requestedLabel = $this->informatorInternalArray['superGlobals']->get('Label');
284
        $showLabels     = true;
285
        $feedback       = '<span style="background-color:red;color:white;">Label not set...</span>';
286
        $arToReturn     = [];
287
        if (isset($requestedLabel)) {
288
            $feedback = '<span style="background-color:red;color:white;">'
289
                    . 'Unknown label transmited...'
290
                    . '</span>';
291
            if (array_key_exists($requestedLabel, $this->informatorInternalArray['knownLabels'])) {
292
                $showLabels = false;
293
                $feedback   = '';
294
                $lblValue   = $this->informatorInternalArray['knownLabels'][$requestedLabel];
295
                if ($requestedLabel == '--- List of known labels') {
296
                    $arToReturn = array_keys($this->informatorInternalArray['knownLabels']);
297
                } elseif ($requestedLabel == 'Auto Dependencies File') {
298
                    $arToReturn = $lblValue;
299
                } elseif ($requestedLabel == 'System Info') {
300
                    $arToReturn = $this->systemInfo();
301
                }
302
                if ($arToReturn == []) {
303
                    $arToReturn = $this->callDynamicFunctionToGetResults($lblValue);
304
                }
305
            }
306
        }
307
        $outputArray = [
308
            'showLabels'    => $showLabels,
309
            'feedback'      => $feedback,
310
            'arrayToReturn' => $arToReturn,
311
        ];
312
        return $this->setOutputInterface($outputArray);
313
    }
314
315
    private function setOutputInterface($inArray)
316
    {
317
        if ($inArray['showLabels']) {
318
            $sReturn    = [];
319
            $sReturn[]  = $this->setHeaderCommon([
320
                'lang'  => 'en-US',
321
                'title' => 'Informator'
322
            ]);
323
            $sReturn[]  = $inArray['feedback'] . '<p style="background-color:green;color:white;">'
324
                    . 'So you might want to choose one from the list below:</p>'
325
                    . '<ul>';
326
            $arToReturn = array_keys($this->informatorInternalArray['knownLabels']);
327
            foreach ($arToReturn as $value) {
328
                $sReturn[] = '<li>'
329
                        . '<a href="?Label=' . urlencode($value) . '" target="_blank">' . $value . '</a>'
330
                        . '</li>';
331
            }
332
            $sReturn[] = '</ul>' . $this->setFooterCommon();
333
            return implode('', $sReturn);
334
        }
335
        $this->setHeaderGZiped();
336
        $this->setHeaderNoCache('application/json');
337
        echo $this->setArrayToJson($inArray['arrayToReturn']);
338
        $this->setFooterGZiped();
339
    }
340
341
    /**
342
     * Builds an array with most important key aspects of LAMP/WAMP
343
     * @return array
344
     */
345
    private function systemInfo()
346
    {
347
        $cFile = $this->informatorInternalArray['composerLockFile'];
348
        return [
349
            'Apache'            => $this->getApacheDetails(),
350
            'Auto Dependencies' => $this->getPackageDetailsFromGivenComposerLockFile($cFile),
351
            'Client'            => $this->getClientBrowserDetailsForInformator(),
352
            'InfoCompareFile'   => $this->getFileDetails(__FILE__),
353
            'MySQL'             => $this->getMySQLinfo(),
354
            'PHP'               => $this->getPhpDetails(),
355
            'Server'            => $this->getServerDetails(),
356
            'Tomcat'            => $this->getTomcatDetails()['Tomcat'],
357
        ];
358
    }
359
}
360