Teknik is a suite of services with attractive and functional interfaces. https://www.teknik.io/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

class.CommonFunctions.inc.php 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  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
  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
  23. * @version Release: 3.0
  24. * @link http://phpsysinfo.sourceforge.net
  25. */
  26. class CommonFunctions
  27. {
  28. private static function _parse_log_file($string)
  29. {
  30. if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
  31. $log_file = substr(PSI_LOG, 1);
  32. if (file_exists($log_file)) {
  33. $contents = @file_get_contents($log_file);
  34. if ($contents && preg_match("/^\-\-\-[^-\n]+\-\-\- ".preg_quote($string, '/')."\n/m", $contents, $matches, PREG_OFFSET_CAPTURE)) {
  35. $findIndex = $matches[0][1];
  36. if (preg_match("/\n/m", $contents, $matches, PREG_OFFSET_CAPTURE, $findIndex)) {
  37. $startIndex = $matches[0][1]+1;
  38. if (preg_match("/^\-\-\-[^-\n]+\-\-\- /m", $contents, $matches, PREG_OFFSET_CAPTURE, $startIndex)) {
  39. $stopIndex = $matches[0][1];
  40. return substr($contents, $startIndex, $stopIndex-$startIndex );
  41. } else {
  42. return substr($contents, $startIndex );
  43. }
  44. }
  45. }
  46. }
  47. }
  48. return false;
  49. }
  50. /**
  51. * Find a system program, do also path checking when not running on WINNT
  52. * on WINNT we simply return the name with the exe extension to the program name
  53. *
  54. * @param string $strProgram name of the program
  55. *
  56. * @return string complete path and name of the program
  57. */
  58. private static function _findProgram($strProgram)
  59. {
  60. $path_parts = pathinfo($strProgram);
  61. if (empty($path_parts['basename'])) {
  62. return;
  63. }
  64. $arrPath = array();
  65. if ((PSI_OS == 'WINNT') && empty($path_parts['extension'])) {
  66. $strProgram .= '.exe';
  67. $path_parts = pathinfo($strProgram);
  68. }
  69. if (empty($path_parts['dirname']) || ($path_parts['dirname'] == '.')) {
  70. if (PSI_OS == 'WINNT') {
  71. $arrPath = preg_split('/;/', getenv("Path"), -1, PREG_SPLIT_NO_EMPTY);
  72. } else {
  73. $arrPath = preg_split('/:/', getenv("PATH"), -1, PREG_SPLIT_NO_EMPTY);
  74. }
  75. } else {
  76. array_push($arrPath, $path_parts['dirname']);
  77. $strProgram = $path_parts['basename'];
  78. }
  79. if ( defined('PSI_ADD_PATHS') && is_string(PSI_ADD_PATHS) ) {
  80. if (preg_match(ARRAY_EXP, PSI_ADD_PATHS)) {
  81. $arrPath = array_merge(eval(PSI_ADD_PATHS), $arrPath); // In this order so $addpaths is before $arrPath when looking for a program
  82. } else {
  83. $arrPath = array_merge(array(PSI_ADD_PATHS), $arrPath); // In this order so $addpaths is before $arrPath when looking for a program
  84. }
  85. }
  86. //add some default paths if we still have no paths here
  87. if (empty($arrPath) && PSI_OS != 'WINNT') {
  88. if (PSI_OS == 'Android') {
  89. array_push($arrPath, '/system/bin');
  90. } else {
  91. array_push($arrPath, '/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin', '/usr/local/sbin');
  92. }
  93. }
  94. // If open_basedir defined, fill the $open_basedir array with authorized paths,. (Not tested when no open_basedir restriction)
  95. if ((bool) ini_get('open_basedir')) {
  96. if (PSI_OS == 'WINNT') {
  97. $open_basedir = preg_split('/;/', ini_get('open_basedir'), -1, PREG_SPLIT_NO_EMPTY);
  98. } else {
  99. $open_basedir = preg_split('/:/', ini_get('open_basedir'), -1, PREG_SPLIT_NO_EMPTY);
  100. }
  101. }
  102. foreach ($arrPath as $strPath) {
  103. // Path with trailing slash
  104. if (PSI_OS == 'WINNT') {
  105. $strPathS = rtrim($strPath,"\\")."\\";
  106. } else {
  107. $strPathS = rtrim($strPath,"/")."/";
  108. }
  109. if (!((PSI_OS == 'Android') && ($strPath=='/system/bin')) //is_dir('/system/bin') Android patch
  110. && !is_dir($strPath)) {
  111. continue;
  112. }
  113. // To avoid "open_basedir restriction in effect" error when testing paths if restriction is enabled
  114. if (isset($open_basedir)) {
  115. $inBaseDir = false;
  116. if (PSI_OS == 'WINNT') {
  117. foreach ($open_basedir as $openbasedir) {
  118. if (substr($openbasedir,-1)=="\\") {
  119. $str_Path = $strPathS;
  120. } else {
  121. $str_Path = $strPath;
  122. }
  123. if (stripos($str_Path, $openbasedir) === 0) {
  124. $inBaseDir = true;
  125. break;
  126. }
  127. }
  128. } else {
  129. foreach ($open_basedir as $openbasedir) {
  130. if (substr($openbasedir,-1)=="/") {
  131. $str_Path = $strPathS;
  132. } else {
  133. $str_Path = $strPath;
  134. }
  135. if (strpos($str_Path, $openbasedir) === 0) {
  136. $inBaseDir = true;
  137. break;
  138. }
  139. }
  140. }
  141. if ($inBaseDir == false) {
  142. continue;
  143. }
  144. }
  145. if (PSI_OS == 'WINNT') {
  146. $strProgrammpath = rtrim($strPath,"\\")."\\".$strProgram;
  147. } else {
  148. $strProgrammpath = rtrim($strPath,"/")."/".$strProgram;
  149. }
  150. if (is_executable($strProgrammpath)) {
  151. return $strProgrammpath;
  152. }
  153. }
  154. }
  155. /**
  156. * Execute a system program. return a trim()'d result.
  157. * does very crude pipe checking. you need ' | ' for it to work
  158. * ie $program = CommonFunctions::executeProgram('netstat', '-anp | grep LIST');
  159. * NOT $program = CommonFunctions::executeProgram('netstat', '-anp|grep LIST');
  160. *
  161. * @param string $strProgramname name of the program
  162. * @param string $strArgs arguments to the program
  163. * @param string &$strBuffer output of the command
  164. * @param boolean $booErrorRep en- or disables the reporting of errors which should be logged
  165. *
  166. * @return boolean command successfull or not
  167. */
  168. public static function executeProgram($strProgramname, $strArgs, &$strBuffer, $booErrorRep = true)
  169. {
  170. if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
  171. $out = self::_parse_log_file("Executing: ".trim($strProgramname.' '.$strArgs));
  172. if ($out == false) {
  173. if (substr(PSI_LOG, 0, 1)=="-") {
  174. $strBuffer = '';
  175. return false;
  176. }
  177. } else {
  178. $strBuffer = $out;
  179. return true;
  180. }
  181. }
  182. $strBuffer = '';
  183. $strError = '';
  184. $pipes = array();
  185. $strProgram = self::_findProgram($strProgramname);
  186. $error = Error::singleton();
  187. if (!$strProgram) {
  188. if ($booErrorRep) {
  189. $error->addError('find_program('.$strProgramname.')', 'program not found on the machine');
  190. }
  191. return false;
  192. }
  193. // see if we've gotten a |, if we have we need to do path checking on the cmd
  194. if ($strArgs) {
  195. $arrArgs = preg_split('/ /', $strArgs, -1, PREG_SPLIT_NO_EMPTY);
  196. for ($i = 0, $cnt_args = count($arrArgs); $i < $cnt_args; $i++) {
  197. if ($arrArgs[$i] == '|') {
  198. $strCmd = $arrArgs[$i + 1];
  199. $strNewcmd = self::_findProgram($strCmd);
  200. $strArgs = preg_replace("/\| ".$strCmd.'/', "| ".$strNewcmd, $strArgs);
  201. }
  202. }
  203. }
  204. $descriptorspec = array(0=>array("pipe", "r"), 1=>array("pipe", "w"), 2=>array("pipe", "w"));
  205. if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN === true) {
  206. $process = $pipes[1] = popen($strProgram." ".$strArgs." 2>/dev/null", "r");
  207. } else {
  208. $process = proc_open($strProgram." ".$strArgs, $descriptorspec, $pipes);
  209. }
  210. if (is_resource($process)) {
  211. self::_timeoutfgets($pipes, $strBuffer, $strError);
  212. if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN === true) {
  213. $return_value = pclose($pipes[1]);
  214. } else {
  215. fclose($pipes[0]);
  216. fclose($pipes[1]);
  217. fclose($pipes[2]);
  218. // It is important that you close any pipes before calling
  219. // proc_close in order to avoid a deadlock
  220. $return_value = proc_close($process);
  221. }
  222. } else {
  223. if ($booErrorRep) {
  224. $error->addError($strProgram, "\nOpen process error");
  225. }
  226. return false;
  227. }
  228. $strError = trim($strError);
  229. $strBuffer = trim($strBuffer);
  230. if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
  231. error_log("---".gmdate('r T')."--- Executing: ".trim($strProgramname.' '.$strArgs)."\n".$strBuffer."\n", 3, PSI_LOG);
  232. }
  233. if (! empty($strError)) {
  234. if ($booErrorRep) {
  235. $error->addError($strProgram, $strError."\nReturn value: ".$return_value);
  236. }
  237. return $return_value == 0;
  238. }
  239. return true;
  240. }
  241. /**
  242. * read a file and return the content as a string
  243. *
  244. * @param string $strFileName name of the file which should be read
  245. * @param string &$strRet content of the file (reference)
  246. * @param integer $intLines control how many lines should be read
  247. * @param integer $intBytes control how many bytes of each line should be read
  248. * @param boolean $booErrorRep en- or disables the reporting of errors which should be logged
  249. *
  250. * @return boolean command successfull or not
  251. */
  252. public static function rfts($strFileName, &$strRet, $intLines = 0, $intBytes = 4096, $booErrorRep = true)
  253. {
  254. if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
  255. $out = self::_parse_log_file("Reading: ".$strFileName);
  256. if ($out == false) {
  257. if (substr(PSI_LOG, 0, 1)=="-") {
  258. $strRet = '';
  259. return false;
  260. }
  261. } else {
  262. $strRet = $out;
  263. return true;
  264. }
  265. }
  266. $strFile = "";
  267. $intCurLine = 1;
  268. $error = Error::singleton();
  269. if (file_exists($strFileName)) {
  270. if (is_readable($strFileName)) {
  271. if ($fd = fopen($strFileName, 'r')) {
  272. while (!feof($fd)) {
  273. $strFile .= fgets($fd, $intBytes);
  274. if ($intLines <= $intCurLine && $intLines != 0) {
  275. break;
  276. } else {
  277. $intCurLine++;
  278. }
  279. }
  280. fclose($fd);
  281. $strRet = $strFile;
  282. if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && (substr(PSI_LOG, 0, 1)!="-") && (substr(PSI_LOG, 0, 1)!="+")) {
  283. error_log("---".gmdate('r T')."--- Reading: ".$strFileName."\n".$strRet, 3, PSI_LOG);
  284. }
  285. } else {
  286. if ($booErrorRep) {
  287. $error->addError('fopen('.$strFileName.')', 'file can not read by phpsysinfo');
  288. }
  289. return false;
  290. }
  291. } else {
  292. if ($booErrorRep) {
  293. $error->addError('fopen('.$strFileName.')', 'file permission error');
  294. }
  295. return false;
  296. }
  297. } else {
  298. if ($booErrorRep) {
  299. $error->addError('file_exists('.$strFileName.')', 'the file does not exist on your machine');
  300. }
  301. return false;
  302. }
  303. return true;
  304. }
  305. /**
  306. * file exists
  307. *
  308. * @param string $strFileName name of the file which should be check
  309. *
  310. * @return boolean command successfull or not
  311. */
  312. public static function fileexists($strFileName)
  313. {
  314. if (defined('PSI_LOG') && is_string(PSI_LOG) && (strlen(PSI_LOG)>0) && ((substr(PSI_LOG, 0, 1)=="-") || (substr(PSI_LOG, 0, 1)=="+"))) {
  315. $log_file = substr(PSI_LOG, 1);
  316. if (file_exists($log_file)
  317. && ($contents = @file_get_contents($log_file))
  318. && preg_match("/^\-\-\-[^-\n]+\-\-\- ".preg_quote("Reading: ".$strFileName, '/')."\n/m", $contents)) {
  319. return true;
  320. } else {
  321. if (substr(PSI_LOG, 0, 1)=="-") {
  322. return false;
  323. }
  324. }
  325. }
  326. return file_exists($strFileName);
  327. }
  328. /**
  329. * reads a directory and return the name of the files and directorys in it
  330. *
  331. * @param string $strPath path of the directory which should be read
  332. * @param boolean $booErrorRep en- or disables the reporting of errors which should be logged
  333. *
  334. * @return array content of the directory excluding . and ..
  335. */
  336. public static function gdc($strPath, $booErrorRep = true)
  337. {
  338. $arrDirectoryContent = array();
  339. $error = Error::singleton();
  340. if (is_dir($strPath)) {
  341. if ($handle = opendir($strPath)) {
  342. while (($strFile = readdir($handle)) !== false) {
  343. if ($strFile != "." && $strFile != "..") {
  344. $arrDirectoryContent[] = $strFile;
  345. }
  346. }
  347. closedir($handle);
  348. } else {
  349. if ($booErrorRep) {
  350. $error->addError('opendir('.$strPath.')', 'directory can not be read by phpsysinfo');
  351. }
  352. }
  353. } else {
  354. if ($booErrorRep) {
  355. $error->addError('is_dir('.$strPath.')', 'directory does not exist on your machine');
  356. }
  357. }
  358. return $arrDirectoryContent;
  359. }
  360. /**
  361. * Check for needed php extensions
  362. *
  363. * We need that extensions for almost everything
  364. * This function will return a hard coded
  365. * XML string (with headers) if the SimpleXML extension isn't loaded.
  366. * Then it will terminate the script.
  367. * See bug #1787137
  368. *
  369. * @param array $arrExt additional extensions for which a check should run
  370. *
  371. * @return void
  372. */
  373. public static function checkForExtensions($arrExt = array())
  374. {
  375. if ((strcasecmp(PSI_SYSTEM_CODEPAGE,"UTF-8") == 0) || (strcasecmp(PSI_SYSTEM_CODEPAGE,"CP437") == 0))
  376. $arrReq = array('simplexml', 'pcre', 'xml', 'dom');
  377. elseif (PSI_OS == "WINNT")
  378. $arrReq = array('simplexml', 'pcre', 'xml', 'mbstring', 'dom', 'com_dotnet');
  379. else
  380. $arrReq = array('simplexml', 'pcre', 'xml', 'mbstring', 'dom');
  381. $extensions = array_merge($arrExt, $arrReq);
  382. $text = "";
  383. $error = false;
  384. $text .= "<?xml version='1.0'?>\n";
  385. $text .= "<phpsysinfo>\n";
  386. $text .= " <Error>\n";
  387. foreach ($extensions as $extension) {
  388. if (!extension_loaded($extension)) {
  389. $text .= " <Function>checkForExtensions</Function>\n";
  390. $text .= " <Message>phpSysInfo requires the ".$extension." extension to php in order to work properly.</Message>\n";
  391. $error = true;
  392. }
  393. }
  394. $text .= " </Error>\n";
  395. $text .= "</phpsysinfo>";
  396. if ($error) {
  397. header("Content-Type: text/xml\n\n");
  398. echo $text;
  399. die();
  400. }
  401. }
  402. /**
  403. * get the content of stdout/stderr with the option to set a timeout for reading
  404. *
  405. * @param array $pipes array of file pointers for stdin, stdout, stderr (proc_open())
  406. * @param string &$out target string for the output message (reference)
  407. * @param string &$err target string for the error message (reference)
  408. * @param integer $timeout timeout value in seconds (default value is 30)
  409. *
  410. * @return void
  411. */
  412. private static function _timeoutfgets($pipes, &$out, &$err, $timeout = 30)
  413. {
  414. $w = NULL;
  415. $e = NULL;
  416. if (defined("PSI_MODE_POPEN") && PSI_MODE_POPEN === true) {
  417. $pipe2 = false;
  418. } else {
  419. $pipe2 = true;
  420. }
  421. while (!(feof($pipes[1]) || ($pipe2 && feof($pipes[2])))) {
  422. if ($pipe2) {
  423. $read = array($pipes[1], $pipes[2]);
  424. } else {
  425. $read = array($pipes[1]);
  426. }
  427. $n = stream_select($read, $w, $e, $timeout);
  428. if ($n === FALSE) {
  429. error_log('stream_select: failed !');
  430. break;
  431. } elseif ($n === 0) {
  432. error_log('stream_select: timeout expired !');
  433. break;
  434. }
  435. foreach ($read as $r) {
  436. if ($r == $pipes[1]) {
  437. $out .= fread($r, 4096);
  438. }
  439. if ($pipe2 && ($r == $pipes[2])) {
  440. $err .= fread($r, 4096);
  441. }
  442. }
  443. }
  444. }
  445. /**
  446. * function for getting a list of values in the specified context
  447. * optionally filter this list, based on the list from third parameter
  448. *
  449. * @param $wmi holds the COM object that we pull the WMI data from
  450. * @param string $strClass name of the class where the values are stored
  451. * @param array $strValue filter out only needed values, if not set all values of the class are returned
  452. *
  453. * @return array content of the class stored in an array
  454. */
  455. public static function getWMI($wmi, $strClass, $strValue = array())
  456. {
  457. $arrData = array();
  458. if ($wmi) {
  459. $value = "";
  460. try {
  461. $objWEBM = $wmi->Get($strClass);
  462. $arrProp = $objWEBM->Properties_;
  463. $arrWEBMCol = $objWEBM->Instances_();
  464. foreach ($arrWEBMCol as $objItem) {
  465. if (is_array($arrProp)) {
  466. reset($arrProp);
  467. }
  468. $arrInstance = array();
  469. foreach ($arrProp as $propItem) {
  470. eval("\$value = \$objItem->".$propItem->Name.";");
  471. if ( empty($strValue)) {
  472. if (is_string($value)) $arrInstance[$propItem->Name] = trim($value);
  473. else $arrInstance[$propItem->Name] = $value;
  474. } else {
  475. if (in_array($propItem->Name, $strValue)) {
  476. if (is_string($value)) $arrInstance[$propItem->Name] = trim($value);
  477. else $arrInstance[$propItem->Name] = $value;
  478. }
  479. }
  480. }
  481. $arrData[] = $arrInstance;
  482. }
  483. } catch (Exception $e) {
  484. if (PSI_DEBUG) {
  485. $this->error->addError($e->getCode(), $e->getMessage());
  486. }
  487. }
  488. }
  489. return $arrData;
  490. }
  491. /**
  492. * get all configured plugins from config.php (file must be included before calling this function)
  493. *
  494. * @return array
  495. */
  496. public static function getPlugins()
  497. {
  498. if ( defined('PSI_PLUGINS') && is_string(PSI_PLUGINS) ) {
  499. if (preg_match(ARRAY_EXP, PSI_PLUGINS)) {
  500. return eval(strtolower(PSI_PLUGINS));
  501. } else {
  502. return array(strtolower(PSI_PLUGINS));
  503. }
  504. } else {
  505. return array();
  506. }
  507. }
  508. }