Subversion Repositories ALCASAR

Rev

Rev 3100 | Details | Compare with Previous | Last modification | View Log

Rev Author Line No. Line
2770 rexy 1
<?php
2
/**
3
 * common Functions class
4
 *
5
 * PHP version 5
6
 *
7
 * @category  PHP
8
 * @package   PSI
9
 * @author    Michael Cramer <BigMichi1@users.sourceforge.net>
10
 * @copyright 2009 phpSysInfo
11
 * @license   http://opensource.org/licenses/gpl-2.0.php GNU General Public License version 2, or (at your option) any later version
12
 * @version   SVN: $Id: class.CommonFunctions.inc.php 699 2012-09-15 11:57:13Z namiltd $
13
 * @link      http://phpsysinfo.sourceforge.net
14
 */
15
 /**
16
 * class with common functions used in all places
17
 *
18
 * @category  PHP
19
 * @package   PSI
20
 * @author    Michael Cramer <BigMichi1@users.sourceforge.net>
21
 * @copyright 2009 phpSysInfo
22
 * @license   http://opensource.org/licenses/gpl-2.0.php GNU General Public License version 2, or (at your option) any later version
23
 * @version   Release: 3.0
24
 * @link      http://phpsysinfo.sourceforge.net
25
 */
26
class CommonFunctions
27
{
28
    /**
3037 rexy 29
     * holds dmi memory data
2770 rexy 30
     *
3037 rexy 31
     * @var array
2770 rexy 32
     */
3037 rexy 33
    private static $_dmimd = null;
2770 rexy 34
 
35
    private static function _parse_log_file($string)
36
    {
37
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
38
            $log_file = substr(PSI_LOG, 1);
39
            if (file_exists($log_file)) {
40
                $contents = @file_get_contents($log_file);
41
                if ($contents && preg_match("/^\-\-\-[^-\r\n]+\-\-\- ".preg_quote($string, '/')."\r?\n/m", $contents, $matches, PREG_OFFSET_CAPTURE)) {
42
                    $findIndex = $matches[0][1];
43
                    if (preg_match("/\r?\n/m", $contents, $matches, PREG_OFFSET_CAPTURE, $findIndex)) {
44
                        $startIndex = $matches[0][1]+1;
45
                        if (preg_match("/^\-\-\-[^-\r\n]+\-\-\- /m", $contents, $matches, PREG_OFFSET_CAPTURE, $startIndex)) {
46
                            $stopIndex = $matches[0][1];
47
 
48
                            return substr($contents, $startIndex, $stopIndex-$startIndex);
49
                        } else {
50
                            return substr($contents, $startIndex);
51
                        }
52
                    }
53
                }
54
            }
55
        }
56
 
57
        return false;
58
    }
59
 
60
    /**
61
     * Find a system program, do also path checking when not running on WINNT
62
     * on WINNT we simply return the name with the exe extension to the program name
63
     *
64
     * @param string $strProgram name of the program
65
     *
66
     * @return string|null complete path and name of the program
67
     */
2976 rexy 68
    public static function _findProgram($strProgram)
2770 rexy 69
    {
70
        $path_parts = pathinfo($strProgram);
71
        if (empty($path_parts['basename'])) {
72
            return null;
73
        }
74
        $arrPath = array();
75
 
76
        if (empty($path_parts['dirname']) || ($path_parts['dirname'] == '.')) {
77
            if ((PSI_OS == 'WINNT') && empty($path_parts['extension'])) {
78
                $strProgram .= '.exe';
79
                $path_parts = pathinfo($strProgram);
80
            }
81
            if (PSI_OS == 'WINNT') {
2976 rexy 82
                if (self::readenv('Path', $serverpath)) {
2770 rexy 83
                    $arrPath = preg_split('/;/', $serverpath, -1, PREG_SPLIT_NO_EMPTY);
84
                }
85
            } else {
2976 rexy 86
                if (self::readenv('PATH', $serverpath)) {
2770 rexy 87
                    $arrPath = preg_split('/:/', $serverpath, -1, PREG_SPLIT_NO_EMPTY);
88
                }
89
            }
90
            if (defined('PSI_UNAMEO') && (PSI_UNAMEO === 'Android') && !empty($arrPath)) {
91
                array_push($arrPath, '/system/bin'); // Termux patch
92
            }
93
            if (defined('PSI_ADD_PATHS') && is_string(PSI_ADD_PATHS)) {
94
                if (preg_match(ARRAY_EXP, PSI_ADD_PATHS)) {
95
                    $arrPath = array_merge(eval(PSI_ADD_PATHS), $arrPath); // In this order so $addpaths is before $arrPath when looking for a program
96
                } else {
97
                    $arrPath = array_merge(array(PSI_ADD_PATHS), $arrPath); // In this order so $addpaths is before $arrPath when looking for a program
98
                }
99
            }
100
        } else { //directory defined
101
            array_push($arrPath, $path_parts['dirname']);
102
            $strProgram = $path_parts['basename'];
103
        }
104
 
105
        //add some default paths if we still have no paths here
2976 rexy 106
        if (empty($arrPath) && (PSI_OS != 'WINNT')) {
2770 rexy 107
            if (PSI_OS == 'Android') {
108
                array_push($arrPath, '/system/bin');
109
            } else {
110
                array_push($arrPath, '/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin');
111
            }
112
        }
113
 
114
        $exceptPath = "";
2976 rexy 115
        if ((PSI_OS == 'WINNT') && self::readenv('WinDir', $windir)) {
2770 rexy 116
            foreach ($arrPath as $strPath) {
2976 rexy 117
                if ((strtolower($strPath) == strtolower($windir)."\\system32") && is_dir($windir."\\SysWOW64")) {
118
                    if (is_dir($windir."\\sysnative\\drivers")) { // or strlen(decbin(~0)) == 32; is_dir($windir."\\sysnative") sometimes does not work
2770 rexy 119
                        $exceptPath = $windir."\\sysnative"; //32-bit PHP on 64-bit Windows
120
                    } else {
121
                        $exceptPath = $windir."\\SysWOW64"; //64-bit PHP on 64-bit Windows
122
                    }
123
                    array_push($arrPath, $exceptPath);
124
                    break;
125
                }
126
            }
127
        } elseif (PSI_OS == 'Android') {
128
            $exceptPath = '/system/bin';
129
        }
130
 
131
        foreach ($arrPath as $strPath) {
132
            // Path with and without trailing slash
133
            if (PSI_OS == 'WINNT') {
134
                $strPath = rtrim($strPath, "\\");
135
                $strPathS = $strPath."\\";
136
            } else {
137
                $strPath = rtrim($strPath, "/");
138
                $strPathS = $strPath."/";
139
            }
140
            if (($strPath !== $exceptPath) && !is_dir($strPath)) {
141
                continue;
142
            }
2976 rexy 143
            $strProgrammpath = $strPathS.$strProgram;
3037 rexy 144
            if (is_executable($strProgrammpath) || ((PSI_OS == 'WINNT') && (strtolower($path_parts['extension']) == 'py') && is_file($strProgrammpath))) {
2770 rexy 145
                return $strProgrammpath;
146
            }
147
        }
148
 
149
        return null;
150
    }
151
 
152
    /**
153
     * Execute a system program. return a trim()'d result.
2976 rexy 154
     * does very crude pipe and multiple commands (on WinNT) checking.  you need ' | ' or ' & ' for it to work
2770 rexy 155
     * ie $program = CommonFunctions::executeProgram('netstat', '-anp | grep LIST');
156
     * NOT $program = CommonFunctions::executeProgram('netstat', '-anp|grep LIST');
157
     *
158
     * @param string  $strProgramname name of the program
3100 rexy 159
     * @param string  $strArguments   arguments to the program
2770 rexy 160
     * @param string  &$strBuffer     output of the command
161
     * @param boolean $booErrorRep    en- or disables the reporting of errors which should be logged
3037 rexy 162
     * @param int     $timeout        timeout value in seconds (default value is PSI_EXEC_TIMEOUT_INT)
2770 rexy 163
     *
164
     * @return boolean command successfull or not
165
     */
3100 rexy 166
    public static function executeProgram($strProgramname, $strArguments, &$strBuffer, $booErrorRep = true, $timeout = PSI_EXEC_TIMEOUT_INT, $separator = '')
2770 rexy 167
    {
3100 rexy 168
        if (PSI_ROOT_FILESYSTEM !== '') { // disabled if ROOTFS defined
169
 
170
            return false;
171
        }
172
 
173
        if ((PSI_OS != 'WINNT') && preg_match('/^([^=]+=[^ \t]+)[ \t]+(.*)$/', $strProgramname, $strmatch)) {
174
            $strSet = $strmatch[1].' ';
175
            $strProgramname = $strmatch[2];
176
        } else {
177
            $strSet = '';
178
        }
179
        $strAll = trim($strSet.$strProgramname.' '.$strArguments);
180
 
2770 rexy 181
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
3100 rexy 182
            $out = self::_parse_log_file("Executing: ".$strAll);
2770 rexy 183
            if ($out == false) {
184
                if (substr(PSI_LOG, 0, 1)=="-") {
185
                    $strBuffer = '';
186
 
187
                    return false;
188
                }
189
            } else {
190
                $strBuffer = $out;
191
 
192
                return true;
193
            }
194
        }
195
 
3100 rexy 196
        $PathStr = '';
197
        if (defined('PSI_EMU_PORT') && !in_array($strProgramname, array('ping', 'snmpwalk'))) {
198
            if (defined('PSI_SUDO_COMMANDS') && is_string(PSI_SUDO_COMMANDS)) {
199
                if (preg_match(ARRAY_EXP, PSI_SUDO_COMMANDS)) {
200
                    $sudocommands = eval(PSI_SUDO_COMMANDS);
201
                } else {
202
                    $sudocommands = array(PSI_SUDO_COMMANDS);
203
                }
204
                if (in_array($strProgramname, $sudocommands)) {
205
                    $strAll = 'sudo '.$strAll;
206
                }
207
            }
208
            $strSet = '';
209
            $strProgramname = 'sshpass';
210
            $strOptions = '';
211
            if (defined('PSI_EMU_ADD_OPTIONS') && is_string(PSI_EMU_ADD_OPTIONS)) {
212
                if (preg_match(ARRAY_EXP, PSI_EMU_ADD_OPTIONS)) {
213
                    $arrParams = eval(PSI_EMU_ADD_OPTIONS);
214
                } else {
215
                    $arrParams = array(PSI_EMU_ADD_OPTIONS);
216
                }
217
                foreach ($arrParams as $Params) if (preg_match('/(\S+)\s*\=\s*(\S+)/', $Params, $obuf)) {
218
                    $strOptions = $strOptions.'-o '.$obuf[1].'='.$obuf[2].' ';
219
                }
220
            }
221
            if (defined('PSI_EMU_ADD_PATHS') && is_string(PSI_EMU_ADD_PATHS)) {
222
                if (preg_match(ARRAY_EXP, PSI_EMU_ADD_PATHS)) {
223
                    $arrPath = eval(PSI_EMU_ADD_PATHS);
224
                } else {
225
                    $arrPath = array(PSI_EMU_ADD_PATHS);
226
                }
227
                foreach ($arrPath as $Path) {
228
                    if ($PathStr === '') {
229
                        $PathStr = $Path;
230
                    } else {
231
                        $PathStr = $PathStr.':'.$Path;
232
                    }
233
                }
234
                if ($separator === '') {
235
                    $strArguments = '-e ssh -Tq '.$strOptions.'-o ConnectTimeout='.$timeout.' -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '.PSI_EMU_USER.'@'.PSI_EMU_HOSTNAME.' -p '.PSI_EMU_PORT.' "PATH=\''.$PathStr.':$PATH\' '.$strAll.'"' ;
236
                } else {
237
                    $strArguments = '-e ssh -Tq '.$strOptions.'-o ConnectTimeout='.$timeout.' -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '.PSI_EMU_USER.'@'.PSI_EMU_HOSTNAME.' -p '.PSI_EMU_PORT;
238
                }
239
            } else {
240
                if ($separator === '') {
241
                    $strArguments = '-e ssh -Tq '.$strOptions.'-o ConnectTimeout='.$timeout.' -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '.PSI_EMU_USER.'@'.PSI_EMU_HOSTNAME.' -p '.PSI_EMU_PORT.' "'.$strAll.'"' ;
242
                } else {
243
                    $strArguments = '-e ssh -Tq '.$strOptions.'-o ConnectTimeout='.$timeout.' -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null '.PSI_EMU_USER.'@'.PSI_EMU_HOSTNAME.' -p '.PSI_EMU_PORT;
244
                }
245
            }
246
            $externally = true;
247
        } else {
248
            $externally = false;
3037 rexy 249
        }
250
 
2770 rexy 251
        $strProgram = self::_findProgram($strProgramname);
252
        $error = PSI_Error::singleton();
253
        if (!$strProgram) {
3100 rexy 254
            if ($booErrorRep || $externally) {
2770 rexy 255
                $error->addError('find_program("'.$strProgramname.'")', 'program not found on the machine');
256
            }
257
 
258
            return false;
259
        } else {
260
            if (preg_match('/\s/', $strProgram)) {
261
                $strProgram = '"'.$strProgram.'"';
262
            }
263
        }
264
 
3100 rexy 265
        if ((PSI_OS != 'WINNT') && !defined('PSI_EMU_HOSTNAME') && defined('PSI_SUDO_COMMANDS') && is_string(PSI_SUDO_COMMANDS)) {
2770 rexy 266
            if (preg_match(ARRAY_EXP, PSI_SUDO_COMMANDS)) {
267
                $sudocommands = eval(PSI_SUDO_COMMANDS);
268
            } else {
269
                $sudocommands = array(PSI_SUDO_COMMANDS);
270
            }
271
            if (in_array($strProgramname, $sudocommands)) {
272
                $sudoProgram = self::_findProgram("sudo");
273
                if (!$sudoProgram) {
3100 rexy 274
                    $error->addError('find_program("sudo")', 'program not found on the machine');
2770 rexy 275
 
276
                    return false;
277
                } else {
278
                    if (preg_match('/\s/', $sudoProgram)) {
279
                        $strProgram = '"'.$sudoProgram.'" '.$strProgram;
280
                    } else {
281
                        $strProgram = $sudoProgram.' '.$strProgram;
282
                    }
283
                }
284
            }
285
        }
286
 
3100 rexy 287
        $strArgs = $strArguments;
2976 rexy 288
        // see if we've gotten a | or &, if we have we need to do path checking on the cmd
2770 rexy 289
        if ($strArgs) {
290
            $arrArgs = preg_split('/ /', $strArgs, -1, PREG_SPLIT_NO_EMPTY);
291
            for ($i = 0, $cnt_args = count($arrArgs); $i < $cnt_args; $i++) {
2976 rexy 292
                if (($arrArgs[$i] == '|') || ($arrArgs[$i] == '&')) {
2770 rexy 293
                    $strCmd = $arrArgs[$i + 1];
294
                    $strNewcmd = self::_findProgram($strCmd);
3100 rexy 295
                    if (!$strNewcmd) {
296
                        if ($booErrorRep || $externally) {
297
                            $error->addError('find_program("'.$strCmd.'")', 'program not found on the machine');
298
                        }
299
 
300
                        return false;
301
                    }
302
                    if (preg_match('/\s/', $strNewcmd)) {
303
                        if ($arrArgs[$i] == '|') {
304
                            $strArgs = preg_replace('/\| '.$strCmd.'/', '| "'.$strNewcmd.'"', $strArgs);
305
                        } else {
306
                            $strArgs = preg_replace('/& '.$strCmd.'/', '& "'.$strNewcmd.'"', $strArgs);
307
                        }
2976 rexy 308
                    } else {
3100 rexy 309
                        if ($arrArgs[$i] == '|') {
310
                            $strArgs = preg_replace('/\| '.$strCmd.'/', '| '.$strNewcmd, $strArgs);
311
                        } else {
312
                            $strArgs = preg_replace('/& '.$strCmd.'/', '& '.$strNewcmd, $strArgs);
313
                        }
2976 rexy 314
                    }
2770 rexy 315
                }
316
            }
317
            $strArgs = ' '.$strArgs;
318
        }
319
 
320
        $strBuffer = '';
321
        $strError = '';
322
        $pipes = array();
323
        $descriptorspec = array(0=>array("pipe", "r"), 1=>array("pipe", "w"), 2=>array("pipe", "w"));
3100 rexy 324
        if ($externally) {
325
            putenv('SSHPASS='.PSI_EMU_PASSWORD);
326
        }
3037 rexy 327
        if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN) {
3100 rexy 328
            if ($separator !== '') {
329
                $error->addError('executeProgram', 'wrong execution mode');
330
 
331
                return false;
332
            }
2770 rexy 333
            if (PSI_OS == 'WINNT') {
334
                $process = $pipes[1] = popen($strSet.$strProgram.$strArgs." 2>nul", "r");
335
            } else {
336
                $process = $pipes[1] = popen($strSet.$strProgram.$strArgs." 2>/dev/null", "r");
337
            }
338
        } else {
339
            $process = proc_open($strSet.$strProgram.$strArgs, $descriptorspec, $pipes);
3100 rexy 340
            if ($separator !== '') {
341
                if ($PathStr === '') {
342
                    fwrite($pipes[0], $strAll."\n  "); // spaces at end for handling 'more'
343
                } else {
344
                    fwrite($pipes[0], 'PATH=\''.$PathStr.':$PATH\' '.$strAll."\n");
345
                }
346
            }
2770 rexy 347
        }
3100 rexy 348
        if ($externally) {
349
            putenv('SSHPASS');
350
        }
2770 rexy 351
        if (is_resource($process)) {
3100 rexy 352
            $te = self::_timeoutfgets($pipes, $strBuffer, $strError, $timeout, $separator);
3037 rexy 353
            if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN) {
2770 rexy 354
                $return_value = pclose($pipes[1]);
355
            } else {
356
                fclose($pipes[0]);
357
                fclose($pipes[1]);
358
                fclose($pipes[2]);
359
                // It is important that you close any pipes before calling
360
                // proc_close in order to avoid a deadlock
361
                if ($te) {
362
                    proc_terminate($process); // proc_close tends to hang if the process is timing out
363
                    $return_value = 0;
364
                } else {
365
                    $return_value = proc_close($process);
366
                }
367
            }
368
        } else {
369
            if ($booErrorRep) {
370
                $error->addError($strProgram, "\nOpen process error");
371
            }
372
 
373
            return false;
374
        }
375
        $strError = trim($strError);
376
        $strBuffer = trim($strBuffer);
377
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
3100 rexy 378
            error_log("---".gmdate('r T')."--- Executing: ".$strAll."\n".$strBuffer."\n", 3, PSI_LOG);
2770 rexy 379
        }
380
        if (! empty($strError)) {
381
            if ($booErrorRep) {
382
                $error->addError($strProgram, $strError."\nReturn value: ".$return_value);
383
            }
384
 
385
            return $return_value == 0;
386
        }
387
 
388
        return true;
389
    }
390
 
391
    /**
392
     * read a one-line value from a file with a similar name
393
     *
394
     * @return value if successfull or null if not
395
     */
396
    public static function rolv($similarFileName, $match = "//", $replace = "")
397
    {
3100 rexy 398
        if (defined('PSI_EMU_PORT')) {
399
            return null;
400
        }
401
 
2770 rexy 402
        $filename = preg_replace($match, $replace, $similarFileName);
2976 rexy 403
        if (self::fileexists($filename) && self::rfts($filename, $buf, 1, 4096, false) && (($buf=trim($buf)) != "")) {
2770 rexy 404
            return $buf;
405
        } else {
406
            return null;
407
        }
408
    }
409
 
410
    /**
411
     * read data from array $_SERVER
412
     *
413
     * @param string $strElem    element of array
414
     * @param string &$strBuffer output of the command
415
     *
416
     * @return string
417
     */
418
    public static function readenv($strElem, &$strBuffer)
419
    {
420
        $strBuffer = '';
421
        if (PSI_OS == 'WINNT') { //case insensitive
422
            if (isset($_SERVER)) {
423
                foreach ($_SERVER as $index=>$value) {
424
                    if (is_string($value) && (trim($value) !== '') && (strtolower($index) === strtolower($strElem))) {
425
                        $strBuffer = $value;
426
 
427
                        return true;
428
                    }
429
                }
430
            }
431
        } else {
432
            if (isset($_SERVER[$strElem]) && is_string($value = $_SERVER[$strElem]) && (trim($value) !== '')) {
433
                $strBuffer = $value;
434
 
435
                return true;
436
            }
437
        }
438
 
439
        return false;
440
    }
441
 
442
    /**
443
     * read a file and return the content as a string
444
     *
445
     * @param string  $strFileName name of the file which should be read
446
     * @param string  &$strRet     content of the file (reference)
3037 rexy 447
     * @param int     $intLines    control how many lines should be read
448
     * @param int     $intBytes    control how many bytes of each line should be read
2770 rexy 449
     * @param boolean $booErrorRep en- or disables the reporting of errors which should be logged
450
     *
451
     * @return boolean command successfull or not
452
     */
453
    public static function rfts($strFileName, &$strRet, $intLines = 0, $intBytes = 4096, $booErrorRep = true)
454
    {
3100 rexy 455
        if (defined('PSI_EMU_PORT')) {
456
            return false;
457
        }
458
 
2770 rexy 459
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
460
            $out = self::_parse_log_file("Reading: ".$strFileName);
461
            if ($out == false) {
462
                if (substr(PSI_LOG, 0, 1)=="-") {
463
                    $strRet = '';
464
 
465
                    return false;
466
                }
467
            } else {
468
                $strRet = $out;
469
 
470
                return true;
471
            }
472
        }
473
 
3037 rexy 474
        if (PSI_ROOT_FILESYSTEM !== '') {
475
            $rfsinfo = "[".PSI_ROOT_FILESYSTEM."]";
476
        } else {
477
            $rfsinfo = '';
478
        }
479
 
2770 rexy 480
        $strFile = "";
481
        $intCurLine = 1;
482
        $error = PSI_Error::singleton();
3037 rexy 483
        if (file_exists(PSI_ROOT_FILESYSTEM.$strFileName)) {
484
            if (is_readable(PSI_ROOT_FILESYSTEM.$strFileName)) {
485
                if ($fd = fopen(PSI_ROOT_FILESYSTEM.$strFileName, 'r')) {
2770 rexy 486
                    while (!feof($fd)) {
487
                        $strFile .= fgets($fd, $intBytes);
488
                        if ($intLines <= $intCurLine && $intLines != 0) {
489
                            break;
490
                        } else {
491
                            $intCurLine++;
492
                        }
493
                    }
494
                    fclose($fd);
495
                    $strRet = $strFile;
496
                    if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
497
                        if ((strlen($strRet)>0)&&(substr($strRet, -1)!="\n")) {
498
                            error_log("---".gmdate('r T')."--- Reading: ".$strFileName."\n".$strRet."\n", 3, PSI_LOG);
499
                        } else {
500
                            error_log("---".gmdate('r T')."--- Reading: ".$strFileName."\n".$strRet, 3, PSI_LOG);
501
                        }
502
                    }
503
                } else {
504
                    if ($booErrorRep) {
3037 rexy 505
                        $error->addError('fopen('.$rfsinfo.$strFileName.')', 'file can not read by phpsysinfo');
2770 rexy 506
                    }
507
 
508
                    return false;
509
                }
510
            } else {
511
                if ($booErrorRep) {
3037 rexy 512
                    $error->addError('fopen('.$rfsinfo.$strFileName.')', 'file permission error');
2770 rexy 513
                }
514
 
515
                return false;
516
            }
517
        } else {
518
            if ($booErrorRep) {
3037 rexy 519
                $error->addError('file_exists('.$rfsinfo.$strFileName.')', 'the file does not exist on your machine');
2770 rexy 520
            }
521
 
522
            return false;
523
        }
524
 
525
        return true;
526
    }
527
 
528
    /**
3037 rexy 529
     * read a data file and return the content as a string
530
     *
531
     * @param string $strDataFileName name of the data file which should be read
532
     * @param string &$strRet         content of the data file (reference)
533
     *
534
     * @return boolean command successfull or not
535
     */
536
    public static function rftsdata($strDataFileName, &$strRet)
537
    {
538
        $strFile = "";
539
        $strFileName = PSI_APP_ROOT."/data/".$strDataFileName;
540
        $error = PSI_Error::singleton();
541
        if (file_exists($strFileName)) {
542
            if (is_readable($strFileName)) {
543
                if ($fd = fopen($strFileName, 'r')) {
544
                    while (!feof($fd)) {
545
                        $strFile .= fgets($fd, 4096);
546
                    }
547
                    fclose($fd);
548
                    $strRet = $strFile;
549
                } else {
550
                    $error->addError('fopen('.$strFileName.')', 'file can not read by phpsysinfo');
551
 
552
                    return false;
553
                }
554
            } else {
555
                $error->addError('fopen('.$strFileName.')', 'file permission error');
556
 
557
                return false;
558
            }
559
        } else {
560
            $error->addError('file_exists('.$strFileName.')', 'the file does not exist on your machine');
561
 
562
            return false;
563
        }
564
 
565
        return true;
566
    }
567
 
568
    /**
569
     * Find pathnames matching a pattern
570
     *
571
     * @param string $pattern the pattern. No tilde expansion or parameter substitution is done.
572
     * @param int    $flags
573
     *
574
     * @return an array containing the matched files/directories, an empty array if no file matched or false on error
575
     */
576
    public static function findglob($pattern, $flags = 0)
577
    {
3100 rexy 578
        if (defined('PSI_EMU_PORT')) {
579
            return false;
580
        }
581
 
3037 rexy 582
        $outarr = glob(PSI_ROOT_FILESYSTEM.$pattern, $flags);
583
        if (PSI_ROOT_FILESYSTEM == '') {
584
            return $outarr;
585
        } elseif ($outarr === false) {
586
            return false;
587
        } else {
588
            $len = strlen(PSI_ROOT_FILESYSTEM);
589
            $newoutarr = array();
590
            foreach ($outarr as $out) {
591
                $newoutarr[] = substr($out, $len); // path without ROOTFS
592
            }
593
 
594
            return $newoutarr;
595
        }
596
    }
597
 
598
    /**
2770 rexy 599
     * file exists
600
     *
601
     * @param string $strFileName name of the file which should be check
602
     *
603
     * @return boolean command successfull or not
604
     */
605
    public static function fileexists($strFileName)
606
    {
3100 rexy 607
        if (defined('PSI_EMU_PORT')) {
608
            return false;
609
        }
610
 
2770 rexy 611
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
612
            $log_file = substr(PSI_LOG, 1);
613
            if (file_exists($log_file)
614
                && ($contents = @file_get_contents($log_file))
615
                && preg_match("/^\-\-\-[^-\n]+\-\-\- ".preg_quote("Reading: ".$strFileName, '/')."\n/m", $contents)) {
616
                return true;
617
            } else {
618
                if (substr(PSI_LOG, 0, 1)=="-") {
619
                    return false;
620
                }
621
            }
622
        }
623
 
3037 rexy 624
        $exists =  file_exists(PSI_ROOT_FILESYSTEM.$strFileName);
2770 rexy 625
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
626
            if ((substr($strFileName, 0, 5) === "/dev/") && $exists) {
627
                error_log("---".gmdate('r T')."--- Reading: ".$strFileName."\ndevice exists\n", 3, PSI_LOG);
628
            }
629
        }
630
 
631
        return $exists;
632
    }
633
 
634
    /**
635
     * reads a directory and return the name of the files and directorys in it
636
     *
637
     * @param string  $strPath     path of the directory which should be read
638
     * @param boolean $booErrorRep en- or disables the reporting of errors which should be logged
639
     *
640
     * @return array content of the directory excluding . and ..
641
     */
642
    public static function gdc($strPath, $booErrorRep = true)
643
    {
644
        $arrDirectoryContent = array();
645
        $error = PSI_Error::singleton();
646
        if (is_dir($strPath)) {
647
            if ($handle = opendir($strPath)) {
648
                while (($strFile = readdir($handle)) !== false) {
649
                    if ($strFile != "." && $strFile != "..") {
650
                        $arrDirectoryContent[] = $strFile;
651
                    }
652
                }
653
                closedir($handle);
654
            } else {
655
                if ($booErrorRep) {
656
                    $error->addError('opendir('.$strPath.')', 'directory can not be read by phpsysinfo');
657
                }
658
            }
659
        } else {
660
            if ($booErrorRep) {
661
                $error->addError('is_dir('.$strPath.')', 'directory does not exist on your machine');
662
            }
663
        }
664
 
665
        return $arrDirectoryContent;
666
    }
667
 
668
    /**
669
     * Check for needed php extensions
670
     *
671
     * We need that extensions for almost everything
672
     * This function will return a hard coded
673
     * XML string (with headers) if the SimpleXML extension isn't loaded.
674
     * Then it will terminate the script.
675
     * See bug #1787137
676
     *
677
     * @param array $arrExt additional extensions for which a check should run
678
     *
679
     * @return void
680
     */
681
    public static function checkForExtensions($arrExt = array())
682
    {
3037 rexy 683
        if (defined('PSI_SYSTEM_CODEPAGE') && (PSI_SYSTEM_CODEPAGE !== null) && ((strcasecmp(PSI_SYSTEM_CODEPAGE, "UTF-8") == 0) || (strcasecmp(PSI_SYSTEM_CODEPAGE, "CP437") == 0)))
2770 rexy 684
            $arrReq = array('simplexml', 'pcre', 'xml', 'dom');
2976 rexy 685
        elseif (PSI_OS == 'WINNT')
2770 rexy 686
            $arrReq = array('simplexml', 'pcre', 'xml', 'dom', 'mbstring', 'com_dotnet');
687
        else
688
            $arrReq = array('simplexml', 'pcre', 'xml', 'dom', 'mbstring');
689
        $extensions = array_merge($arrExt, $arrReq);
690
        $text = "";
691
        $error = false;
692
        $text .= "<?xml version='1.0'?>\n";
693
        $text .= "<phpsysinfo>\n";
694
        $text .= "  <Error>\n";
695
        foreach ($extensions as $extension) {
696
            if (!extension_loaded($extension)) {
697
                $text .= "    <Function>checkForExtensions</Function>\n";
698
                $text .= "    <Message>phpSysInfo requires the ".$extension." extension to php in order to work properly.</Message>\n";
699
                $error = true;
700
            }
701
        }
702
        $text .= "  </Error>\n";
703
        $text .= "</phpsysinfo>";
704
        if ($error) {
3037 rexy 705
            header('Content-Type: text/xml');
2770 rexy 706
            echo $text;
707
            die();
708
        }
709
    }
710
 
711
    /**
712
     * get the content of stdout/stderr with the option to set a timeout for reading
713
     *
3037 rexy 714
     * @param array  $pipes   array of file pointers for stdin, stdout, stderr (proc_open())
715
     * @param string &$out    target string for the output message (reference)
716
     * @param string &$err    target string for the error message (reference)
717
     * @param int    $timeout timeout value in seconds
2770 rexy 718
     *
719
     * @return boolean timeout expired or not
720
     */
3100 rexy 721
    private static function _timeoutfgets($pipes, &$out, &$err, $timeout, $separator = '')
2770 rexy 722
    {
723
        $w = null;
724
        $e = null;
725
        $te = false;
726
 
3037 rexy 727
        if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN) {
2770 rexy 728
            $pipe2 = false;
729
        } else {
730
            $pipe2 = true;
731
        }
732
        while (!(feof($pipes[1]) && (!$pipe2 || feof($pipes[2])))) {
733
            if ($pipe2) {
734
                $read = array($pipes[1], $pipes[2]);
735
            } else {
736
                $read = array($pipes[1]);
737
            }
738
 
739
            $n = stream_select($read, $w, $e, $timeout);
740
 
741
            if ($n === false) {
742
                error_log('stream_select: failed !');
743
                break;
744
            } elseif ($n === 0) {
745
                error_log('stream_select: timeout expired !');
3100 rexy 746
//                if ($separator !== '') {
747
//                    fwrite($pipes[0], "q");
748
//                }
2770 rexy 749
                $te = true;
750
                break;
751
            }
752
 
753
            foreach ($read as $r) {
754
                if ($r == $pipes[1]) {
755
                    $out .= fread($r, 4096);
756
                } elseif (feof($pipes[1]) && $pipe2 && ($r == $pipes[2])) {//read STDERR after STDOUT
757
                    $err .= fread($r, 4096);
758
                }
759
            }
3100 rexy 760
//            if (($separator !== '') && preg_match('/'.$separator.'[^'.$separator.']+'.$separator.'/', $out)) {
761
            if (($separator !== '') && preg_match('/'.$separator.'[\s\S]+'.$separator.'/', $out)) {
762
                fwrite($pipes[0], "quit\n");
763
                $separator = ''; //only one time
764
              //  $te = true;
765
              //  break;
766
            }
2770 rexy 767
        }
768
 
769
        return $te;
770
    }
771
 
772
    /**
773
     * get all configured plugins from phpsysinfo.ini (file must be included and processed before calling this function)
774
     *
775
     * @return array
776
     */
777
    public static function getPlugins()
778
    {
779
        if (defined('PSI_PLUGINS') && is_string(PSI_PLUGINS)) {
780
            if (preg_match(ARRAY_EXP, PSI_PLUGINS)) {
781
                return eval(strtolower(PSI_PLUGINS));
782
            } else {
783
                return array(strtolower(PSI_PLUGINS));
784
            }
785
        } else {
786
            return array();
787
        }
788
    }
789
 
790
    /**
791
     * name natural compare function
792
     *
793
     * @return comprasion result
794
     */
795
    public static function name_natural_compare($a, $b)
796
    {
797
        return strnatcmp($a->getName(), $b->getName());
798
    }
799
 
800
    /**
3037 rexy 801
     * get virtualizer from dmi data
2770 rexy 802
     *
3037 rexy 803
     * @return string|null
2770 rexy 804
     */
3037 rexy 805
    public static function decodevirtualizer($vendor_data)
2770 rexy 806
    {
3037 rexy 807
        if (gettype($vendor_data) === "array") {
808
            $vendarray = array(
809
                'KVM' => 'kvm', // KVM
3100 rexy 810
                'OpenStack' => 'kvm', // Detect OpenStack instance as KVM in non x86 architecture
811
                'KubeVirt' => 'kvm', // Detect KubeVirt instance as KVM in non x86 architecture
3037 rexy 812
                'Amazon EC2' => 'amazon', // Amazon EC2 Nitro using Linux KVM
813
                'QEMU' => 'qemu', // QEMU
814
                'VMware' => 'vmware', // VMware https://kb.vmware.com/s/article/1009458
815
                'VMW' => 'vmware',
816
                'innotek GmbH' => 'oracle', // Oracle VM VirtualBox
817
                'VirtualBox' => 'oracle',
818
                'Xen' => 'xen', // Xen hypervisor
819
                'Bochs' => 'bochs', // Bochs
820
                'Parallels' => 'parallels', // Parallels
821
                // https://wiki.freebsd.org/bhyve
822
                'BHYVE' => 'bhyve', // bhyve
823
                'Hyper-V' => 'microsoft', // Hyper-V
3100 rexy 824
                'Apple Virtualization' => 'apple', // Apple Virtualization.framework guests
3037 rexy 825
                'Microsoft Corporation Virtual Machine' => 'microsoft' // Hyper-V
826
            );
827
            for ($i = 0; $i < count($vendor_data); $i++) {
828
                foreach ($vendarray as $vend=>$virt) {
829
                    if (preg_match('/^'.$vend.'/', $vendor_data[$i])) {
830
                        return $virt;
2976 rexy 831
                    }
2770 rexy 832
                }
833
            }
3037 rexy 834
        } elseif (gettype($vendor_data) === "string") {
835
            $vidarray = array(
836
                'bhyvebhyve' => 'bhyve', // bhyve
837
                'KVMKVMKVM' => 'kvm', // KVM
3100 rexy 838
                'LinuxKVMHv' => 'hv-kvm', // KVM (KVM + HyperV Enlightenments)
3037 rexy 839
                'MicrosoftHv' => 'microsoft', // Hyper-V
840
                'lrpepyhvr' => 'parallels', // Parallels
841
                'UnisysSpar64' => 'spar', // Unisys sPar
842
                'VMwareVMware' => 'vmware', // VMware
843
                'XenVMMXenVMM' => 'xen', // Xen hypervisor
844
                'ACRNACRNACRN' => 'acrn', // ACRN hypervisor
845
                'TCGTCGTCGTCG' => 'qemu', // QEMU
846
                'QNXQVMBSQG' => 'qnx', // QNX hypervisor
3179 rexy 847
                'VBoxVBoxVBox' => 'oracle', // Oracle VM VirtualBox
848
                'SRESRESRESRE' => 'sre' // LMHS SRE hypervisor
3037 rexy 849
            );
850
            $shortvendorid = trim(preg_replace('/[\s!\.]/', '', $vendor_data));
851
            if (($shortvendorid !== "") && isset($vidarray[$shortvendorid])) {
852
                return $vidarray[$shortvendorid];
853
            }
2770 rexy 854
        }
855
 
3037 rexy 856
        return null;
2770 rexy 857
    }
858
 
3037 rexy 859
 
2770 rexy 860
    /**
3037 rexy 861
     * readdmimemdata function
2770 rexy 862
     *
3037 rexy 863
     * @return array
2770 rexy 864
     */
3037 rexy 865
    public static function readdmimemdata()
2770 rexy 866
    {
3100 rexy 867
        if ((PSI_OS != 'WINNT') && (!defined('PSI_EMU_HOSTNAME') || defined('PSI_EMU_PORT')) && (self::$_dmimd === null)) {
3037 rexy 868
            self::$_dmimd = array();
869
            $buffer = '';
870
            if (defined('PSI_DMIDECODE_ACCESS') && (strtolower(PSI_DMIDECODE_ACCESS)==='data')) {
871
                self::rftsdata('dmidecode.tmp', $buffer);
872
            } elseif (self::_findProgram('dmidecode')) {
873
                self::executeProgram('dmidecode', '-t 17', $buffer, PSI_DEBUG);
2976 rexy 874
            }
3037 rexy 875
            if (!empty($buffer)) {
876
                $banks = preg_split('/^(?=Handle\s)/m', $buffer, -1, PREG_SPLIT_NO_EMPTY);
877
                foreach ($banks as $bank) if (preg_match('/^Handle\s/', $bank)) {
878
                    $lines = preg_split("/\n/", $bank, -1, PREG_SPLIT_NO_EMPTY);
879
                    $mem = array();
880
                    foreach ($lines as $line) if (preg_match('/^\s+([^:]+):(.+)/', $line, $params)) {
881
                        if (preg_match('/^0x([A-F\d]+)/', $params2 = trim($params[2]), $buff)) {
882
                            $mem[trim($params[1])] = trim($buff[1]);
883
                        } elseif ($params2 != '') {
884
                            $mem[trim($params[1])] = $params2;
885
                        }
2770 rexy 886
                    }
3037 rexy 887
                    if (!empty($mem)) {
888
                        self::$_dmimd[] = $mem;
2770 rexy 889
                    }
890
                }
891
            }
892
        }
893
 
3037 rexy 894
        return self::$_dmimd;
2770 rexy 895
    }
896
}