Subversion Repositories ALCASAR

Rev

Rev 2770 | Rev 3037 | Go to most recent revision | 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
    /**
29
     * holds codepage for chcp
30
     *
31
     * @var integer
32
     */
33
    private static $_cp = null;
34
 
2976 rexy 35
    /**
36
     * value of checking run as administrator
37
     *
38
     * @var boolean
39
     */
40
    private static $_asadmin = null;
41
 
2770 rexy 42
    public static function setcp($cp)
43
    {
2976 rexy 44
        self::$_cp = $cp;
2770 rexy 45
    }
46
 
2976 rexy 47
    public static function getcp()
48
    {
49
        return self::$_cp;
50
    }
51
 
52
    public static function isAdmin()
53
    {
54
        if (self::$_asadmin == null) {
55
            if (PSI_OS == 'WINNT') {
56
                $strBuf = '';
57
                self::executeProgram('sfc', '2>&1', $strBuf, false); // 'net session' for detection does not work if "Server" (LanmanServer) service is stopped
58
                if (preg_match('/^\/SCANNOW\s/m', preg_replace('/(\x00)/', '', $strBuf))) { // SCANNOW checking - also if Unicode
59
                    self::$_asadmin = true;
60
                } else {
61
                    self::$_asadmin = false;
62
                }
63
            } else {
64
                self::$_asadmin = false;
65
            }
66
        }
67
 
68
        return self::$_asadmin;
69
    }
70
 
2770 rexy 71
    private static function _parse_log_file($string)
72
    {
73
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
74
            $log_file = substr(PSI_LOG, 1);
75
            if (file_exists($log_file)) {
76
                $contents = @file_get_contents($log_file);
77
                if ($contents && preg_match("/^\-\-\-[^-\r\n]+\-\-\- ".preg_quote($string, '/')."\r?\n/m", $contents, $matches, PREG_OFFSET_CAPTURE)) {
78
                    $findIndex = $matches[0][1];
79
                    if (preg_match("/\r?\n/m", $contents, $matches, PREG_OFFSET_CAPTURE, $findIndex)) {
80
                        $startIndex = $matches[0][1]+1;
81
                        if (preg_match("/^\-\-\-[^-\r\n]+\-\-\- /m", $contents, $matches, PREG_OFFSET_CAPTURE, $startIndex)) {
82
                            $stopIndex = $matches[0][1];
83
 
84
                            return substr($contents, $startIndex, $stopIndex-$startIndex);
85
                        } else {
86
                            return substr($contents, $startIndex);
87
                        }
88
                    }
89
                }
90
            }
91
        }
92
 
93
        return false;
94
    }
95
 
96
    /**
97
     * Find a system program, do also path checking when not running on WINNT
98
     * on WINNT we simply return the name with the exe extension to the program name
99
     *
100
     * @param string $strProgram name of the program
101
     *
102
     * @return string|null complete path and name of the program
103
     */
2976 rexy 104
    public static function _findProgram($strProgram)
2770 rexy 105
    {
106
        $path_parts = pathinfo($strProgram);
107
        if (empty($path_parts['basename'])) {
108
            return null;
109
        }
110
        $arrPath = array();
111
 
112
        if (empty($path_parts['dirname']) || ($path_parts['dirname'] == '.')) {
113
            if ((PSI_OS == 'WINNT') && empty($path_parts['extension'])) {
114
                $strProgram .= '.exe';
115
                $path_parts = pathinfo($strProgram);
116
            }
117
            if (PSI_OS == 'WINNT') {
2976 rexy 118
                if (self::readenv('Path', $serverpath)) {
2770 rexy 119
                    $arrPath = preg_split('/;/', $serverpath, -1, PREG_SPLIT_NO_EMPTY);
120
                }
121
            } else {
2976 rexy 122
                if (self::readenv('PATH', $serverpath)) {
2770 rexy 123
                    $arrPath = preg_split('/:/', $serverpath, -1, PREG_SPLIT_NO_EMPTY);
124
                }
125
            }
126
            if (defined('PSI_UNAMEO') && (PSI_UNAMEO === 'Android') && !empty($arrPath)) {
127
                array_push($arrPath, '/system/bin'); // Termux patch
128
            }
129
            if (defined('PSI_ADD_PATHS') && is_string(PSI_ADD_PATHS)) {
130
                if (preg_match(ARRAY_EXP, PSI_ADD_PATHS)) {
131
                    $arrPath = array_merge(eval(PSI_ADD_PATHS), $arrPath); // In this order so $addpaths is before $arrPath when looking for a program
132
                } else {
133
                    $arrPath = array_merge(array(PSI_ADD_PATHS), $arrPath); // In this order so $addpaths is before $arrPath when looking for a program
134
                }
135
            }
136
        } else { //directory defined
137
            array_push($arrPath, $path_parts['dirname']);
138
            $strProgram = $path_parts['basename'];
139
        }
140
 
141
        //add some default paths if we still have no paths here
2976 rexy 142
        if (empty($arrPath) && (PSI_OS != 'WINNT')) {
2770 rexy 143
            if (PSI_OS == 'Android') {
144
                array_push($arrPath, '/system/bin');
145
            } else {
146
                array_push($arrPath, '/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin');
147
            }
148
        }
149
 
150
        $exceptPath = "";
2976 rexy 151
        if ((PSI_OS == 'WINNT') && self::readenv('WinDir', $windir)) {
2770 rexy 152
            foreach ($arrPath as $strPath) {
2976 rexy 153
                if ((strtolower($strPath) == strtolower($windir)."\\system32") && is_dir($windir."\\SysWOW64")) {
154
                    if (is_dir($windir."\\sysnative\\drivers")) { // or strlen(decbin(~0)) == 32; is_dir($windir."\\sysnative") sometimes does not work
2770 rexy 155
                        $exceptPath = $windir."\\sysnative"; //32-bit PHP on 64-bit Windows
156
                    } else {
157
                        $exceptPath = $windir."\\SysWOW64"; //64-bit PHP on 64-bit Windows
158
                    }
159
                    array_push($arrPath, $exceptPath);
160
                    break;
161
                }
162
            }
163
        } elseif (PSI_OS == 'Android') {
164
            $exceptPath = '/system/bin';
165
        }
166
 
167
        foreach ($arrPath as $strPath) {
168
            // Path with and without trailing slash
169
            if (PSI_OS == 'WINNT') {
170
                $strPath = rtrim($strPath, "\\");
171
                $strPathS = $strPath."\\";
172
            } else {
173
                $strPath = rtrim($strPath, "/");
174
                $strPathS = $strPath."/";
175
            }
176
            if (($strPath !== $exceptPath) && !is_dir($strPath)) {
177
                continue;
178
            }
2976 rexy 179
            $strProgrammpath = $strPathS.$strProgram;
180
            if (is_executable($strProgrammpath) || ((PSI_OS == 'WINNT') && (strtolower($path_parts['extension']) == 'py'))) {
2770 rexy 181
                return $strProgrammpath;
182
            }
183
        }
184
 
185
        return null;
186
    }
187
 
188
    /**
189
     * Execute a system program. return a trim()'d result.
2976 rexy 190
     * does very crude pipe and multiple commands (on WinNT) checking.  you need ' | ' or ' & ' for it to work
2770 rexy 191
     * ie $program = CommonFunctions::executeProgram('netstat', '-anp | grep LIST');
192
     * NOT $program = CommonFunctions::executeProgram('netstat', '-anp|grep LIST');
193
     *
194
     * @param string  $strProgramname name of the program
195
     * @param string  $strArgs        arguments to the program
196
     * @param string  &$strBuffer     output of the command
197
     * @param boolean $booErrorRep    en- or disables the reporting of errors which should be logged
198
     * @param integer $timeout        timeout value in seconds (default value is PSI_EXEC_TIMEOUT_INT)
199
     *
200
     * @return boolean command successfull or not
201
     */
202
    public static function executeProgram($strProgramname, $strArgs, &$strBuffer, $booErrorRep = true, $timeout = PSI_EXEC_TIMEOUT_INT)
203
    {
204
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
205
            $out = self::_parse_log_file("Executing: ".trim($strProgramname.' '.$strArgs));
206
            if ($out == false) {
207
                if (substr(PSI_LOG, 0, 1)=="-") {
208
                    $strBuffer = '';
209
 
210
                    return false;
211
                }
212
            } else {
213
                $strBuffer = $out;
214
 
215
                return true;
216
            }
217
        }
218
 
2976 rexy 219
        if ((PSI_OS != 'WINNT') && preg_match('/^([^=]+=[^ \t]+)[ \t]+(.*)$/', $strProgramname, $strmatch)) {
2770 rexy 220
            $strSet = $strmatch[1].' ';
221
            $strProgramname = $strmatch[2];
222
        } else {
223
            $strSet = '';
224
        }
225
        $strProgram = self::_findProgram($strProgramname);
226
        $error = PSI_Error::singleton();
227
        if (!$strProgram) {
228
            if ($booErrorRep) {
229
                $error->addError('find_program("'.$strProgramname.'")', 'program not found on the machine');
230
            }
231
 
232
            return false;
233
        } else {
234
            if (preg_match('/\s/', $strProgram)) {
235
                $strProgram = '"'.$strProgram.'"';
236
            }
237
        }
238
 
2976 rexy 239
        if ((PSI_OS != 'WINNT') && defined('PSI_SUDO_COMMANDS') && is_string(PSI_SUDO_COMMANDS)) {
2770 rexy 240
            if (preg_match(ARRAY_EXP, PSI_SUDO_COMMANDS)) {
241
                $sudocommands = eval(PSI_SUDO_COMMANDS);
242
            } else {
243
                $sudocommands = array(PSI_SUDO_COMMANDS);
244
            }
245
            if (in_array($strProgramname, $sudocommands)) {
246
                $sudoProgram = self::_findProgram("sudo");
247
                if (!$sudoProgram) {
248
                    if ($booErrorRep) {
249
                        $error->addError('find_program("sudo")', 'program not found on the machine');
250
                    }
251
 
252
                    return false;
253
                } else {
254
                    if (preg_match('/\s/', $sudoProgram)) {
255
                        $strProgram = '"'.$sudoProgram.'" '.$strProgram;
256
                    } else {
257
                        $strProgram = $sudoProgram.' '.$strProgram;
258
                    }
259
                }
260
            }
261
        }
262
 
2976 rexy 263
        // see if we've gotten a | or &, if we have we need to do path checking on the cmd
2770 rexy 264
        if ($strArgs) {
265
            $arrArgs = preg_split('/ /', $strArgs, -1, PREG_SPLIT_NO_EMPTY);
266
            for ($i = 0, $cnt_args = count($arrArgs); $i < $cnt_args; $i++) {
2976 rexy 267
                if (($arrArgs[$i] == '|') || ($arrArgs[$i] == '&')) {
2770 rexy 268
                    $strCmd = $arrArgs[$i + 1];
269
                    $strNewcmd = self::_findProgram($strCmd);
2976 rexy 270
                    if ($arrArgs[$i] == '|') {
271
                        $strArgs = preg_replace('/\| '.$strCmd.'/', '| "'.$strNewcmd.'"', $strArgs);
272
                    } else {
273
                        $strArgs = preg_replace('/& '.$strCmd.'/', '& "'.$strNewcmd.'"', $strArgs);
274
                    }
2770 rexy 275
                }
276
            }
277
            $strArgs = ' '.$strArgs;
278
        }
279
 
280
        $strBuffer = '';
281
        $strError = '';
282
        $pipes = array();
283
        $descriptorspec = array(0=>array("pipe", "r"), 1=>array("pipe", "w"), 2=>array("pipe", "w"));
284
        if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN === true) {
285
            if (PSI_OS == 'WINNT') {
286
                $process = $pipes[1] = popen($strSet.$strProgram.$strArgs." 2>nul", "r");
287
            } else {
288
                $process = $pipes[1] = popen($strSet.$strProgram.$strArgs." 2>/dev/null", "r");
289
            }
290
        } else {
291
            $process = proc_open($strSet.$strProgram.$strArgs, $descriptorspec, $pipes);
292
        }
293
        if (is_resource($process)) {
294
            $te = self::_timeoutfgets($pipes, $strBuffer, $strError, $timeout);
295
            if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN === true) {
296
                $return_value = pclose($pipes[1]);
297
            } else {
298
                fclose($pipes[0]);
299
                fclose($pipes[1]);
300
                fclose($pipes[2]);
301
                // It is important that you close any pipes before calling
302
                // proc_close in order to avoid a deadlock
303
                if ($te) {
304
                    proc_terminate($process); // proc_close tends to hang if the process is timing out
305
                    $return_value = 0;
306
                } else {
307
                    $return_value = proc_close($process);
308
                }
309
            }
310
        } else {
311
            if ($booErrorRep) {
312
                $error->addError($strProgram, "\nOpen process error");
313
            }
314
 
315
            return false;
316
        }
317
        $strError = trim($strError);
318
        $strBuffer = trim($strBuffer);
319
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
320
            error_log("---".gmdate('r T')."--- Executing: ".trim($strProgramname.$strArgs)."\n".$strBuffer."\n", 3, PSI_LOG);
321
        }
322
        if (! empty($strError)) {
323
            if ($booErrorRep) {
324
                $error->addError($strProgram, $strError."\nReturn value: ".$return_value);
325
            }
326
 
327
            return $return_value == 0;
328
        }
329
 
330
        return true;
331
    }
332
 
333
    /**
334
     * read a one-line value from a file with a similar name
335
     *
336
     * @return value if successfull or null if not
337
     */
338
    public static function rolv($similarFileName, $match = "//", $replace = "")
339
    {
340
        $filename = preg_replace($match, $replace, $similarFileName);
2976 rexy 341
        if (self::fileexists($filename) && self::rfts($filename, $buf, 1, 4096, false) && (($buf=trim($buf)) != "")) {
2770 rexy 342
            return $buf;
343
        } else {
344
            return null;
345
        }
346
    }
347
 
348
    /**
349
     * read data from array $_SERVER
350
     *
351
     * @param string $strElem    element of array
352
     * @param string &$strBuffer output of the command
353
     *
354
     * @return string
355
     */
356
    public static function readenv($strElem, &$strBuffer)
357
    {
358
        $strBuffer = '';
359
        if (PSI_OS == 'WINNT') { //case insensitive
360
            if (isset($_SERVER)) {
361
                foreach ($_SERVER as $index=>$value) {
362
                    if (is_string($value) && (trim($value) !== '') && (strtolower($index) === strtolower($strElem))) {
363
                        $strBuffer = $value;
364
 
365
                        return true;
366
                    }
367
                }
368
            }
369
        } else {
370
            if (isset($_SERVER[$strElem]) && is_string($value = $_SERVER[$strElem]) && (trim($value) !== '')) {
371
                $strBuffer = $value;
372
 
373
                return true;
374
            }
375
        }
376
 
377
        return false;
378
    }
379
 
380
    /**
381
     * read a file and return the content as a string
382
     *
383
     * @param string  $strFileName name of the file which should be read
384
     * @param string  &$strRet     content of the file (reference)
385
     * @param integer $intLines    control how many lines should be read
386
     * @param integer $intBytes    control how many bytes of each line should be read
387
     * @param boolean $booErrorRep en- or disables the reporting of errors which should be logged
388
     *
389
     * @return boolean command successfull or not
390
     */
391
    public static function rfts($strFileName, &$strRet, $intLines = 0, $intBytes = 4096, $booErrorRep = true)
392
    {
393
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
394
            $out = self::_parse_log_file("Reading: ".$strFileName);
395
            if ($out == false) {
396
                if (substr(PSI_LOG, 0, 1)=="-") {
397
                    $strRet = '';
398
 
399
                    return false;
400
                }
401
            } else {
402
                $strRet = $out;
403
 
404
                return true;
405
            }
406
        }
407
 
408
        $strFile = "";
409
        $intCurLine = 1;
410
        $error = PSI_Error::singleton();
411
        if (file_exists($strFileName)) {
412
            if (is_readable($strFileName)) {
413
                if ($fd = fopen($strFileName, 'r')) {
414
                    while (!feof($fd)) {
415
                        $strFile .= fgets($fd, $intBytes);
416
                        if ($intLines <= $intCurLine && $intLines != 0) {
417
                            break;
418
                        } else {
419
                            $intCurLine++;
420
                        }
421
                    }
422
                    fclose($fd);
423
                    $strRet = $strFile;
424
                    if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
425
                        if ((strlen($strRet)>0)&&(substr($strRet, -1)!="\n")) {
426
                            error_log("---".gmdate('r T')."--- Reading: ".$strFileName."\n".$strRet."\n", 3, PSI_LOG);
427
                        } else {
428
                            error_log("---".gmdate('r T')."--- Reading: ".$strFileName."\n".$strRet, 3, PSI_LOG);
429
                        }
430
                    }
431
                } else {
432
                    if ($booErrorRep) {
433
                        $error->addError('fopen('.$strFileName.')', 'file can not read by phpsysinfo');
434
                    }
435
 
436
                    return false;
437
                }
438
            } else {
439
                if ($booErrorRep) {
440
                    $error->addError('fopen('.$strFileName.')', 'file permission error');
441
                }
442
 
443
                return false;
444
            }
445
        } else {
446
            if ($booErrorRep) {
447
                $error->addError('file_exists('.$strFileName.')', 'the file does not exist on your machine');
448
            }
449
 
450
            return false;
451
        }
452
 
453
        return true;
454
    }
455
 
456
    /**
457
     * file exists
458
     *
459
     * @param string $strFileName name of the file which should be check
460
     *
461
     * @return boolean command successfull or not
462
     */
463
    public static function fileexists($strFileName)
464
    {
465
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
466
            $log_file = substr(PSI_LOG, 1);
467
            if (file_exists($log_file)
468
                && ($contents = @file_get_contents($log_file))
469
                && preg_match("/^\-\-\-[^-\n]+\-\-\- ".preg_quote("Reading: ".$strFileName, '/')."\n/m", $contents)) {
470
                return true;
471
            } else {
472
                if (substr(PSI_LOG, 0, 1)=="-") {
473
                    return false;
474
                }
475
            }
476
        }
477
 
478
        $exists =  file_exists($strFileName);
479
        if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
480
            if ((substr($strFileName, 0, 5) === "/dev/") && $exists) {
481
                error_log("---".gmdate('r T')."--- Reading: ".$strFileName."\ndevice exists\n", 3, PSI_LOG);
482
            }
483
        }
484
 
485
        return $exists;
486
    }
487
 
488
    /**
489
     * reads a directory and return the name of the files and directorys in it
490
     *
491
     * @param string  $strPath     path of the directory which should be read
492
     * @param boolean $booErrorRep en- or disables the reporting of errors which should be logged
493
     *
494
     * @return array content of the directory excluding . and ..
495
     */
496
    public static function gdc($strPath, $booErrorRep = true)
497
    {
498
        $arrDirectoryContent = array();
499
        $error = PSI_Error::singleton();
500
        if (is_dir($strPath)) {
501
            if ($handle = opendir($strPath)) {
502
                while (($strFile = readdir($handle)) !== false) {
503
                    if ($strFile != "." && $strFile != "..") {
504
                        $arrDirectoryContent[] = $strFile;
505
                    }
506
                }
507
                closedir($handle);
508
            } else {
509
                if ($booErrorRep) {
510
                    $error->addError('opendir('.$strPath.')', 'directory can not be read by phpsysinfo');
511
                }
512
            }
513
        } else {
514
            if ($booErrorRep) {
515
                $error->addError('is_dir('.$strPath.')', 'directory does not exist on your machine');
516
            }
517
        }
518
 
519
        return $arrDirectoryContent;
520
    }
521
 
522
    /**
523
     * Check for needed php extensions
524
     *
525
     * We need that extensions for almost everything
526
     * This function will return a hard coded
527
     * XML string (with headers) if the SimpleXML extension isn't loaded.
528
     * Then it will terminate the script.
529
     * See bug #1787137
530
     *
531
     * @param array $arrExt additional extensions for which a check should run
532
     *
533
     * @return void
534
     */
535
    public static function checkForExtensions($arrExt = array())
536
    {
2976 rexy 537
        if (defined('PSI_SYSTEM_CODEPAGE') && ((strcasecmp(PSI_SYSTEM_CODEPAGE, "UTF-8") == 0) || (strcasecmp(PSI_SYSTEM_CODEPAGE, "CP437") == 0)))
2770 rexy 538
            $arrReq = array('simplexml', 'pcre', 'xml', 'dom');
2976 rexy 539
        elseif (PSI_OS == 'WINNT')
2770 rexy 540
            $arrReq = array('simplexml', 'pcre', 'xml', 'dom', 'mbstring', 'com_dotnet');
541
        else
542
            $arrReq = array('simplexml', 'pcre', 'xml', 'dom', 'mbstring');
543
        $extensions = array_merge($arrExt, $arrReq);
544
        $text = "";
545
        $error = false;
546
        $text .= "<?xml version='1.0'?>\n";
547
        $text .= "<phpsysinfo>\n";
548
        $text .= "  <Error>\n";
549
        foreach ($extensions as $extension) {
550
            if (!extension_loaded($extension)) {
551
                $text .= "    <Function>checkForExtensions</Function>\n";
552
                $text .= "    <Message>phpSysInfo requires the ".$extension." extension to php in order to work properly.</Message>\n";
553
                $error = true;
554
            }
555
        }
556
        $text .= "  </Error>\n";
557
        $text .= "</phpsysinfo>";
558
        if ($error) {
559
            header("Content-Type: text/xml\n\n");
560
            echo $text;
561
            die();
562
        }
563
    }
564
 
565
    /**
566
     * get the content of stdout/stderr with the option to set a timeout for reading
567
     *
568
     * @param array   $pipes   array of file pointers for stdin, stdout, stderr (proc_open())
569
     * @param string  &$out    target string for the output message (reference)
570
     * @param string  &$err    target string for the error message (reference)
571
     * @param integer $timeout timeout value in seconds
572
     *
573
     * @return boolean timeout expired or not
574
     */
575
    private static function _timeoutfgets($pipes, &$out, &$err, $timeout)
576
    {
577
        $w = null;
578
        $e = null;
579
        $te = false;
580
 
581
        if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN === true) {
582
            $pipe2 = false;
583
        } else {
584
            $pipe2 = true;
585
        }
586
        while (!(feof($pipes[1]) && (!$pipe2 || feof($pipes[2])))) {
587
            if ($pipe2) {
588
                $read = array($pipes[1], $pipes[2]);
589
            } else {
590
                $read = array($pipes[1]);
591
            }
592
 
593
            $n = stream_select($read, $w, $e, $timeout);
594
 
595
            if ($n === false) {
596
                error_log('stream_select: failed !');
597
                break;
598
            } elseif ($n === 0) {
599
                error_log('stream_select: timeout expired !');
600
                $te = true;
601
                break;
602
            }
603
 
604
            foreach ($read as $r) {
605
                if ($r == $pipes[1]) {
606
                    $out .= fread($r, 4096);
607
                } elseif (feof($pipes[1]) && $pipe2 && ($r == $pipes[2])) {//read STDERR after STDOUT
608
                    $err .= fread($r, 4096);
609
                }
610
            }
611
        }
612
 
613
        return $te;
614
    }
615
 
616
    /**
617
     * function for getting a list of values in the specified context
618
     * optionally filter this list, based on the list from third parameter
619
     *
620
     * @param $wmi object holds the COM object that we pull the WMI data from
621
     * @param string $strClass name of the class where the values are stored
622
     * @param array  $strValue filter out only needed values, if not set all values of the class are returned
623
     *
624
     * @return array content of the class stored in an array
625
     */
626
    public static function getWMI($wmi, $strClass, $strValue = array())
627
    {
628
        $arrData = array();
629
        if (gettype($wmi) === "object") {
630
            $value = "";
631
            try {
632
                $objWEBM = $wmi->Get($strClass);
633
                $arrProp = $objWEBM->Properties_;
634
                $arrWEBMCol = $objWEBM->Instances_();
635
                foreach ($arrWEBMCol as $objItem) {
636
                    if (is_array($arrProp)) {
637
                        reset($arrProp);
638
                    }
639
                    $arrInstance = array();
640
                    foreach ($arrProp as $propItem) {
641
                        $value = $objItem->{$propItem->Name}; //instead exploitable eval("\$value = \$objItem->".$propItem->Name.";");
642
                        if (empty($strValue)) {
643
                            if (is_string($value)) $arrInstance[$propItem->Name] = trim($value);
644
                            else $arrInstance[$propItem->Name] = $value;
645
                        } else {
646
                            if (in_array($propItem->Name, $strValue)) {
647
                                if (is_string($value)) $arrInstance[$propItem->Name] = trim($value);
648
                                else $arrInstance[$propItem->Name] = $value;
649
                            }
650
                        }
651
                    }
652
                    $arrData[] = $arrInstance;
653
                }
654
            } catch (Exception $e) {
655
                if (PSI_DEBUG) {
656
                    $error = PSI_Error::singleton();
657
                    $error->addError("getWMI()", preg_replace('/<br\/>/', "\n", preg_replace('/<b>|<\/b>/', '', $e->getMessage())));
658
                }
659
            }
2976 rexy 660
        } elseif ((gettype($wmi) === "string") && (PSI_OS == 'Linux')) {
661
            $delimeter = '@@@DELIM@@@';
662
            if (self::executeProgram('wmic', '--delimiter="'.$delimeter.'" '.$wmi.' '.$strClass.'" 2>/dev/null', $strBuf, true) && preg_match("/^CLASS:\s/", $strBuf)) {
663
                if (self::$_cp) {
664
                    if (self::$_cp == 932) {
665
                        $codename = ' (SJIS)';
666
                    } elseif (self::$_cp == 949) {
667
                        $codename = ' (EUC-KR)';
668
                    } elseif (self::$_cp == 950) {
669
                        $codename = ' (BIG-5)';
670
                    } else {
671
                        $codename = '';
672
                    }
673
                    self::convertCP($strBuf, 'windows-'.self::$_cp.$codename);
674
                }
675
                $lines = preg_split('/\n/', $strBuf, -1, PREG_SPLIT_NO_EMPTY);
676
                if (count($lines) >=3) {
677
                    unset($lines[0]);
678
                    $names = preg_split('/'.$delimeter.'/', $lines[1], -1, PREG_SPLIT_NO_EMPTY);
679
                    $namesc = count($names);
680
                    unset($lines[1]);
681
                    foreach ($lines as $line) {
682
                        $arrInstance = array();
683
                        $values = preg_split('/'.$delimeter.'/', $line, -1);
684
                        if (count($values) == $namesc) {
685
                            foreach ($values as $id=>$value) {
686
                                if (empty($strValue)) {
687
                                    if ($value !== "(null)") $arrInstance[$names[$id]] = trim($value);
688
                                    else $arrInstance[$names[$id]] = null;
689
                                } else {
690
                                    if (in_array($names[$id], $strValue)) {
691
                                        if ($value !== "(null)") $arrInstance[$names[$id]] = trim($value);
692
                                        else $arrInstance[$names[$id]] = null;
693
                                    }
694
                                }
695
                            }
696
                            $arrData[] = $arrInstance;
697
                        }
698
                    }
699
                }
700
            }
2770 rexy 701
        }
702
 
703
        return $arrData;
704
    }
705
 
706
    /**
707
     * get all configured plugins from phpsysinfo.ini (file must be included and processed before calling this function)
708
     *
709
     * @return array
710
     */
711
    public static function getPlugins()
712
    {
713
        if (defined('PSI_PLUGINS') && is_string(PSI_PLUGINS)) {
714
            if (preg_match(ARRAY_EXP, PSI_PLUGINS)) {
715
                return eval(strtolower(PSI_PLUGINS));
716
            } else {
717
                return array(strtolower(PSI_PLUGINS));
718
            }
719
        } else {
720
            return array();
721
        }
722
    }
723
 
724
    /**
725
     * name natural compare function
726
     *
727
     * @return comprasion result
728
     */
729
    public static function name_natural_compare($a, $b)
730
    {
731
        return strnatcmp($a->getName(), $b->getName());
732
    }
733
 
734
    /**
735
     * readReg function
736
     *
737
     * @return boolean command successfull or not
738
     */
739
    public static function readReg($reg, $strName, &$strBuffer, $booErrorRep = true)
740
    {
2976 rexy 741
        $arrBuffer = array();
742
        $_hkey = array('HKEY_CLASSES_ROOT'=>0x80000000, 'HKEY_CURRENT_USER'=>0x80000001, 'HKEY_LOCAL_MACHINE'=>0x80000002, 'HKEY_USERS'=>0x80000003, 'HKEY_PERFORMANCE_DATA'=>0x80000004, 'HKEY_PERFORMANCE_TEXT'=>0x80000050, 'HKEY_PERFORMANCE_NLSTEXT'=>0x80000060, 'HKEY_CURRENT_CONFIG'=>0x80000005, 'HKEY_DYN_DATA'=>0x80000006);
743
 
2770 rexy 744
        if ($reg === false) {
2976 rexy 745
            if (defined('PSI_EMU_HOSTNAME')) {
746
                return false;
747
            }
2770 rexy 748
            $last = strrpos($strName, "\\");
749
            $keyname = substr($strName, $last + 1);
2976 rexy 750
            if (self::$_cp) {
751
                if (self::executeProgram('cmd', '/c chcp '.self::$_cp.' >nul & reg query "'.substr($strName, 0, $last).'" /v '.$keyname.' 2>&1', $strBuf, $booErrorRep) && (strlen($strBuf) > 0) && preg_match("/^\s*".$keyname."\s+REG_\S+\s+(.+)\s*$/mi", $strBuf, $buffer2)) {
2770 rexy 752
                    $strBuffer = $buffer2[1];
753
                } else {
754
                    return false;
755
                }
756
            } else {
2976 rexy 757
                if (self::executeProgram('reg', 'query "'.substr($strName, 0, $last).'" /v '.$keyname.' 2>&1', $strBuf, $booErrorRep) && (strlen($strBuf) > 0) && preg_match("/^\s*".$keyname."\s+REG_\S+\s+(.+)\s*$/mi", $strBuf, $buffer2)) {
2770 rexy 758
                    $strBuffer = $buffer2[1];
759
                } else {
760
                    return false;
761
                }
762
            }
763
        } elseif (gettype($reg) === "object") {
2976 rexy 764
            $first = strpos($strName, "\\");
765
            $last = strrpos($strName, "\\");
766
            $hkey = substr($strName, 0, $first);
767
            if (isset($_hkey[$hkey])) {
768
                $sub_keys = new VARIANT();
769
                try {
770
                    $reg->Get("StdRegProv")->GetStringValue(strval($_hkey[$hkey]), substr($strName, $first+1, $last-$first-1), substr($strName, $last+1), $sub_keys);
771
                } catch (Exception $e) {
772
                    if ($booErrorRep) {
773
                        $error = PSI_Error::singleton();
774
                        $error->addError("GetStringValue()", preg_replace('/<br\/>/', "\n", preg_replace('/<b>|<\/b>/', '', $e->getMessage())));
775
                    }
776
 
777
                    return false;
2770 rexy 778
                }
2976 rexy 779
                if (variant_get_type($sub_keys) !== VT_NULL) {
780
                    $strBuffer = strval($sub_keys);
781
                } else {
782
                    return false;
783
                }
784
            } else {
785
               return false;
2770 rexy 786
            }
787
        }
788
 
789
        return true;
790
    }
791
 
792
    /**
793
     * enumKey function
794
     *
795
     * @return boolean command successfull or not
796
     */
2976 rexy 797
    public static function enumKey($reg, $strName, &$arrBuffer, $booErrorRep = true)
2770 rexy 798
    {
2976 rexy 799
        $arrBuffer = array();
2770 rexy 800
        $_hkey = array('HKEY_CLASSES_ROOT'=>0x80000000, 'HKEY_CURRENT_USER'=>0x80000001, 'HKEY_LOCAL_MACHINE'=>0x80000002, 'HKEY_USERS'=>0x80000003, 'HKEY_PERFORMANCE_DATA'=>0x80000004, 'HKEY_PERFORMANCE_TEXT'=>0x80000050, 'HKEY_PERFORMANCE_NLSTEXT'=>0x80000060, 'HKEY_CURRENT_CONFIG'=>0x80000005, 'HKEY_DYN_DATA'=>0x80000006);
801
 
2976 rexy 802
        if ($reg === false) {
803
            if (defined('PSI_EMU_HOSTNAME')) {
804
                return false;
805
            }
806
            if (self::$_cp) {
807
                if (self::executeProgram('cmd', '/c chcp '.self::$_cp.' >nul & reg query "'.$strName.'" 2>&1', $strBuf, $booErrorRep) && (strlen($strBuf) > 0) && preg_match_all("/^".preg_replace("/\\\\/", "\\\\\\\\", $strName)."\\\\(.*)/mi", $strBuf, $buffer2)) {
2770 rexy 808
                    foreach ($buffer2[1] as $sub_key) {
809
                        $arrBuffer[] = trim($sub_key);
810
                    }
811
                } else {
812
                    return false;
813
                }
814
            } else {
2976 rexy 815
                if (self::executeProgram('reg', 'query "'.$strName.'" 2>&1', $strBuf, $booErrorRep) && (strlen($strBuf) > 0) && preg_match_all("/^".preg_replace("/\\\\/", "\\\\\\\\", $strName)."\\\\(.*)/mi", $strBuf, $buffer2)) {
2770 rexy 816
                    foreach ($buffer2[1] as $sub_key) {
817
                        $arrBuffer[] = trim($sub_key);
818
                    }
819
                } else {
820
                    return false;
821
                }
822
            }
2976 rexy 823
        } elseif (gettype($reg) === "object") {
2770 rexy 824
            $first = strpos($strName, "\\");
825
            $hkey = substr($strName, 0, $first);
826
            if (isset($_hkey[$hkey])) {
827
                $sub_keys = new VARIANT();
828
                try {
2976 rexy 829
                   $reg->Get("StdRegProv")->EnumKey(strval($_hkey[$hkey]), substr($strName, $first+1), $sub_keys);
2770 rexy 830
                } catch (Exception $e) {
831
                    if ($booErrorRep) {
832
                        $error = PSI_Error::singleton();
833
                        $error->addError("enumKey()", preg_replace('/<br\/>/', "\n", preg_replace('/<b>|<\/b>/', '', $e->getMessage())));;
834
                    }
835
 
836
                    return false;
837
                }
2976 rexy 838
                if (variant_get_type($sub_keys) !== VT_NULL) foreach ($sub_keys as $sub_key) {
2770 rexy 839
                    $arrBuffer[] = $sub_key;
2976 rexy 840
                } else {
841
                    return false;
2770 rexy 842
                }
843
            } else {
844
               return false;
845
            }
846
        }
847
 
848
        return true;
849
    }
2976 rexy 850
 
851
 
852
    /**
853
     * initWMI function
854
     *
855
     * @return string, object or false
856
     */
857
    public static function initWMI($namespace, $booErrorRep = false)
858
    {
859
        $wmi = false;
860
        try {
861
            if (PSI_OS == 'Linux') {
862
                if (defined('PSI_EMU_HOSTNAME'))
863
                    $wmi = '--namespace="'.$namespace.'" -U '.PSI_EMU_USER.'%'.PSI_EMU_PASSWORD.' //'.PSI_EMU_HOSTNAME.' "select * from';
864
            } elseif (PSI_OS == 'WINNT') {
865
                $objLocator = new COM('WbemScripting.SWbemLocator');
866
                if (defined('PSI_EMU_HOSTNAME'))
867
                    $wmi = $objLocator->ConnectServer(PSI_EMU_HOSTNAME, $namespace, PSI_EMU_USER, PSI_EMU_PASSWORD);
868
                else
869
                    $wmi = $objLocator->ConnectServer('', $namespace);
870
            }
871
        } catch (Exception $e) {
872
            if ($booErrorRep) {
873
                $error = PSI_Error::singleton();
874
                $error->addError("WMI connect ".$namespace." error", "PhpSysInfo can not connect to the WMI interface for security reasons.\nCheck an authentication mechanism for the directory where phpSysInfo is installed or credentials.");
875
            }
876
        }
877
 
878
        return $wmi;
879
    }
880
 
881
    /**
882
     * convertCP function
883
     *
884
     * @return void
885
     */
886
    public static function convertCP(&$strBuf, $encoding)
887
    {
888
        if (defined('PSI_SYSTEM_CODEPAGE') && ($encoding != null) && ($encoding != PSI_SYSTEM_CODEPAGE)) {
889
            $systemcp = PSI_SYSTEM_CODEPAGE;
890
            if (preg_match("/^windows-\d+ \((.+)\)$/", $systemcp, $buf)) {
891
                $systemcp = $buf[1];
892
            }
893
            if (preg_match("/^windows-\d+ \((.+)\)$/", $encoding, $buf)) {
894
                $encoding = $buf[1];
895
            }
896
            $enclist = mb_list_encodings();
897
            if (in_array($encoding, $enclist) && in_array($systemcp, $enclist)) {
898
                $strBuf = mb_convert_encoding($strBuf, $encoding, $systemcp);
899
            } elseif (function_exists("iconv")) {
900
                if (($iconvout=iconv($systemcp, $encoding.'//IGNORE', $strBuf))!==false) {
901
                    $strBuf = $iconvout;
902
                }
903
            } elseif (function_exists("libiconv") && (($iconvout=libiconv($systemcp, $encoding, $strBuf))!==false)) {
904
                $strBuf = $iconvout;
905
            }
906
        }
907
    }
2770 rexy 908
}