Completed
Push — master ( cd768d...07a487 )
by Daniel
02:29
created

source/Informator.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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