PageRenderTime 49ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/phpmyadmin/libraries/Advisor.class.php

https://github.com/drbowen/openemr
PHP | 509 lines | 325 code | 42 blank | 142 comment | 42 complexity | f2397690b0229a519b10bdbd51aa7c56 MD5 | raw file
  1. <?php
  2. /* vim: set expandtab sw=4 ts=4 sts=4: */
  3. /**
  4. * A simple rules engine, that parses and executes the rules in advisory_rules.txt.
  5. * Adjusted to phpMyAdmin.
  6. *
  7. * @package PhpMyAdmin
  8. */
  9. if (! defined('PHPMYADMIN')) {
  10. exit;
  11. }
  12. /**
  13. * Advisor class
  14. *
  15. * @package PhpMyAdmin
  16. */
  17. class Advisor
  18. {
  19. var $variables;
  20. var $parseResult;
  21. var $runResult;
  22. /**
  23. * Parses and executes advisor rules
  24. *
  25. * @return array with run and parse results
  26. */
  27. function run()
  28. {
  29. // HowTo: A simple Advisory system in 3 easy steps.
  30. // Step 1: Get some variables to evaluate on
  31. $this->variables = array_merge(
  32. PMA_DBI_fetch_result('SHOW GLOBAL STATUS', 0, 1),
  33. PMA_DBI_fetch_result('SHOW GLOBAL VARIABLES', 0, 1)
  34. );
  35. if (PMA_DRIZZLE) {
  36. $this->variables = array_merge(
  37. $this->variables,
  38. PMA_DBI_fetch_result(
  39. "SELECT concat('Com_', variable_name), variable_value
  40. FROM data_dictionary.GLOBAL_STATEMENTS", 0, 1
  41. )
  42. );
  43. }
  44. // Add total memory to variables as well
  45. include_once 'libraries/sysinfo.lib.php';
  46. $sysinfo = PMA_getSysInfo();
  47. $memory = $sysinfo->memory();
  48. $this->variables['system_memory'] = $memory['MemTotal'];
  49. // Step 2: Read and parse the list of rules
  50. $this->parseResult = $this->parseRulesFile();
  51. // Step 3: Feed the variables to the rules and let them fire. Sets
  52. // $runResult
  53. $this->runRules();
  54. return array(
  55. 'parse' => array('errors' => $this->parseResult['errors']),
  56. 'run' => $this->runResult
  57. );
  58. }
  59. /**
  60. * Stores current error in run results.
  61. *
  62. * @param string $description description of an error.
  63. * @param object $exception exception raised
  64. *
  65. * @return void
  66. */
  67. function storeError($description, $exception)
  68. {
  69. $this->runResult['errors'][] = $description
  70. . ' '
  71. . sprintf(__('PHP threw following error: %s'), $exception->getMessage());
  72. }
  73. /**
  74. * Executes advisor rules
  75. *
  76. * @return void
  77. */
  78. function runRules()
  79. {
  80. $this->runResult = array(
  81. 'fired' => array(),
  82. 'notfired' => array(),
  83. 'unchecked'=> array(),
  84. 'errors' => array()
  85. );
  86. foreach ($this->parseResult['rules'] as $rule) {
  87. $this->variables['value'] = 0;
  88. $precond = true;
  89. if (isset($rule['precondition'])) {
  90. try {
  91. $precond = $this->ruleExprEvaluate($rule['precondition']);
  92. } catch (Exception $e) {
  93. $this->storeError(
  94. sprintf(
  95. __('Failed evaluating precondition for rule \'%s\''),
  96. $rule['name']
  97. ),
  98. $e
  99. );
  100. continue;
  101. }
  102. }
  103. if (! $precond) {
  104. $this->addRule('unchecked', $rule);
  105. } else {
  106. try {
  107. $value = $this->ruleExprEvaluate($rule['formula']);
  108. } catch(Exception $e) {
  109. $this->storeError(
  110. sprintf(
  111. __('Failed calculating value for rule \'%s\''),
  112. $rule['name']
  113. ),
  114. $e
  115. );
  116. continue;
  117. }
  118. $this->variables['value'] = $value;
  119. try {
  120. if ($this->ruleExprEvaluate($rule['test'])) {
  121. $this->addRule('fired', $rule);
  122. } else {
  123. $this->addRule('notfired', $rule);
  124. }
  125. } catch(Exception $e) {
  126. $this->storeError(
  127. sprintf(
  128. __('Failed running test for rule \'%s\''),
  129. $rule['name']
  130. ),
  131. $e
  132. );
  133. }
  134. }
  135. }
  136. return true;
  137. }
  138. /**
  139. * Escapes percent string to be used in format string.
  140. *
  141. * @param string $str string to escape
  142. *
  143. * @return string
  144. */
  145. static function escapePercent($str)
  146. {
  147. return preg_replace('/%( |,|\.|$|\(|\)|<|>)/', '%%\1', $str);
  148. }
  149. /**
  150. * Wrapper function for translating.
  151. *
  152. * @param string $str the string
  153. * @param mixed $param the parameters
  154. *
  155. * @return string
  156. */
  157. function translate($str, $param = null)
  158. {
  159. if (is_null($param)) {
  160. return sprintf(_gettext(Advisor::escapePercent($str)));
  161. } else {
  162. $printf = 'sprintf("' . _gettext(Advisor::escapePercent($str)) . '",';
  163. return $this->ruleExprEvaluate(
  164. $printf . $param . ')',
  165. strlen($printf)
  166. );
  167. }
  168. }
  169. /**
  170. * Splits justification to text and formula.
  171. *
  172. * @param string $rule the rule
  173. *
  174. * @return array
  175. */
  176. static function splitJustification($rule)
  177. {
  178. $jst = preg_split('/\s*\|\s*/', $rule['justification'], 2);
  179. if (count($jst) > 1) {
  180. return array($jst[0], $jst[1]);
  181. }
  182. return array($rule['justification']);
  183. }
  184. /**
  185. * Adds a rule to the result list
  186. *
  187. * @param string $type type of rule
  188. * @param array $rule rule itslef
  189. *
  190. * @return void
  191. */
  192. function addRule($type, $rule)
  193. {
  194. switch($type) {
  195. case 'notfired':
  196. case 'fired':
  197. $jst = Advisor::splitJustification($rule);
  198. if (count($jst) > 1) {
  199. try {
  200. /* Translate */
  201. $str = $this->translate($jst[0], $jst[1]);
  202. } catch (Exception $e) {
  203. $this->storeError(
  204. sprintf(
  205. __('Failed formatting string for rule \'%s\'.'),
  206. $rule['name']
  207. ),
  208. $e
  209. );
  210. return;
  211. }
  212. $rule['justification'] = $str;
  213. } else {
  214. $rule['justification'] = $this->translate($rule['justification']);
  215. }
  216. $rule['id'] = $rule['name'];
  217. $rule['name'] = $this->translate($rule['name']);
  218. $rule['issue'] = $this->translate($rule['issue']);
  219. // Replaces {server_variable} with 'server_variable'
  220. // linking to server_variables.php
  221. $rule['recommendation'] = preg_replace(
  222. '/\{([a-z_0-9]+)\}/Ui',
  223. '<a href="server_variables.php?' . PMA_generate_common_url() . '&filter=\1">\1</a>',
  224. $this->translate($rule['recommendation'])
  225. );
  226. // Replaces external Links with PMA_linkURL() generated links
  227. $rule['recommendation'] = preg_replace_callback(
  228. '#href=("|\')(https?://[^\1]+)\1#i',
  229. array($this, '_replaceLinkURL'),
  230. $rule['recommendation']
  231. );
  232. break;
  233. }
  234. $this->runResult[$type][] = $rule;
  235. }
  236. /**
  237. * Callback for wrapping links with PMA_linkURL
  238. *
  239. * @param array $matches List of matched elements form preg_replace_callback
  240. *
  241. * @return Replacement value
  242. */
  243. private function _replaceLinkURL($matches)
  244. {
  245. return 'href="' . PMA_linkURL($matches[2]) . '"';
  246. }
  247. /**
  248. * Callback for evaluating fired() condition.
  249. *
  250. * @param array $matches List of matched elements form preg_replace_callback
  251. *
  252. * @return Replacement value
  253. */
  254. private function _ruleExprEvaluateFired($matches)
  255. {
  256. // No list of fired rules
  257. if (!isset($this->runResult['fired'])) {
  258. return '0';
  259. }
  260. // Did matching rule fire?
  261. foreach ($this->runResult['fired'] as $rule) {
  262. if ($rule['id'] == $matches[2]) {
  263. return '1';
  264. }
  265. }
  266. return '0';
  267. }
  268. /**
  269. * Callback for evaluating variables in expression.
  270. *
  271. * @param array $matches List of matched elements form preg_replace_callback
  272. *
  273. * @return Replacement value
  274. */
  275. private function _ruleExprEvaluateVariable($matches)
  276. {
  277. return isset($this->variables[$matches[1]])
  278. ? (is_numeric($this->variables[$matches[1]])
  279. ? $this->variables[$matches[1]]
  280. : '"'.$this->variables[$matches[1]].'"')
  281. : $matches[1];
  282. }
  283. /**
  284. * Runs a code expression, replacing variable names with their respective
  285. * values
  286. *
  287. * @param string $expr expression to evaluate
  288. * @param int $ignoreUntil if > 0, it doesn't replace any variables until
  289. * that string position, but still evaluates the
  290. * whole expr
  291. *
  292. * @return result of evaluated expression
  293. */
  294. function ruleExprEvaluate($expr, $ignoreUntil = 0)
  295. {
  296. if ($ignoreUntil > 0) {
  297. $exprIgnore = substr($expr, 0, $ignoreUntil);
  298. $expr = substr($expr, $ignoreUntil);
  299. }
  300. // Evaluate fired() conditions
  301. $expr = preg_replace_callback(
  302. '/fired\s*\(\s*(\'|")(.*)\1\s*\)/Ui',
  303. array($this, '_ruleExprEvaluateFired'),
  304. $expr
  305. );
  306. // Evaluate variables
  307. $expr = preg_replace_callback(
  308. '/\b(\w+)\b/',
  309. array($this, '_ruleExprEvaluateVariable'),
  310. $expr
  311. );
  312. if ($ignoreUntil > 0) {
  313. $expr = $exprIgnore . $expr;
  314. }
  315. $value = 0;
  316. $err = 0;
  317. // Actually evaluate the code
  318. ob_start();
  319. eval('$value = ' . $expr . ';');
  320. $err = ob_get_contents();
  321. ob_end_clean();
  322. // Error handling
  323. if ($err) {
  324. throw new Exception(
  325. strip_tags($err) . '<br />Executed code: $value = ' . htmlspecialchars($expr) . ';'
  326. );
  327. }
  328. return $value;
  329. }
  330. /**
  331. * Reads the rule file into an array, throwing errors messages on syntax
  332. * errors.
  333. *
  334. * @return array with parsed data
  335. */
  336. static function parseRulesFile()
  337. {
  338. $file = file('libraries/advisory_rules.txt', FILE_IGNORE_NEW_LINES);
  339. $errors = array();
  340. $rules = array();
  341. $lines = array();
  342. $ruleSyntax = array(
  343. 'name', 'formula', 'test', 'issue', 'recommendation', 'justification'
  344. );
  345. $numRules = count($ruleSyntax);
  346. $numLines = count($file);
  347. $ruleNo = -1;
  348. $ruleLine = -1;
  349. for ($i = 0; $i < $numLines; $i++) {
  350. $line = $file[$i];
  351. if ($line == "" || $line[0] == '#') {
  352. continue;
  353. }
  354. // Reading new rule
  355. if (substr($line, 0, 4) == 'rule') {
  356. if ($ruleLine > 0) {
  357. $errors[] = sprintf(
  358. __('Invalid rule declaration on line %1$s, expected line %2$s of previous rule'),
  359. $i + 1,
  360. $ruleSyntax[$ruleLine++]
  361. );
  362. continue;
  363. }
  364. if (preg_match("/rule\s'(.*)'( \[(.*)\])?$/", $line, $match)) {
  365. $ruleLine = 1;
  366. $ruleNo++;
  367. $rules[$ruleNo] = array('name' => $match[1]);
  368. $lines[$ruleNo] = array('name' => $i + 1);
  369. if (isset($match[3])) {
  370. $rules[$ruleNo]['precondition'] = $match[3];
  371. $lines[$ruleNo]['precondition'] = $i + 1;
  372. }
  373. } else {
  374. $errors[] = sprintf(
  375. __('Invalid rule declaration on line %s'),
  376. $i + 1
  377. );
  378. }
  379. continue;
  380. } else {
  381. if ($ruleLine == -1) {
  382. $errors[] = sprintf(
  383. __('Unexpected characters on line %s'),
  384. $i + 1
  385. );
  386. }
  387. }
  388. // Reading rule lines
  389. if ($ruleLine > 0) {
  390. if (!isset($line[0])) {
  391. continue; // Empty lines are ok
  392. }
  393. // Non tabbed lines are not
  394. if ($line[0] != "\t") {
  395. $errors[] = sprintf(
  396. __('Unexpected character on line %1$s. Expected tab, but found "%2$s"'),
  397. $i + 1,
  398. $line[0]
  399. );
  400. continue;
  401. }
  402. $rules[$ruleNo][$ruleSyntax[$ruleLine]] = chop(substr($line, 1));
  403. $lines[$ruleNo][$ruleSyntax[$ruleLine]] = $i + 1;
  404. $ruleLine += 1;
  405. }
  406. // Rule complete
  407. if ($ruleLine == $numRules) {
  408. $ruleLine = -1;
  409. }
  410. }
  411. return array('rules' => $rules, 'lines' => $lines, 'errors' => $errors);
  412. }
  413. }
  414. /**
  415. * Formats interval like 10 per hour
  416. *
  417. * @param integer $num number to format
  418. * @param intefer $precision required precision
  419. *
  420. * @return formatted string
  421. */
  422. function ADVISOR_bytime($num, $precision)
  423. {
  424. $per = '';
  425. if ($num >= 1) { // per second
  426. $per = __('per second');
  427. } elseif ($num * 60 >= 1) { // per minute
  428. $num = $num * 60;
  429. $per = __('per minute');
  430. } elseif ($num * 60 * 60 >= 1 ) { // per hour
  431. $num = $num * 60 * 60;
  432. $per = __('per hour');
  433. } else {
  434. $num = $num * 60 * 60 * 24;
  435. $per = __('per day');
  436. }
  437. $num = round($num, $precision);
  438. if ($num == 0) {
  439. $num = '<' . PMA_Util::pow(10, -$precision);
  440. }
  441. return "$num $per";
  442. }
  443. /**
  444. * Wrapper for PMA_Util::timespanFormat
  445. *
  446. * @param int $seconds the timespan
  447. *
  448. * @return string the formatted value
  449. */
  450. function ADVISOR_timespanFormat($seconds)
  451. {
  452. return PMA_Util::timespanFormat($seconds);
  453. }
  454. /**
  455. * Wrapper around PMA_Util::formatByteDown
  456. *
  457. * @param double $value the value to format
  458. * @param int $limes the sensitiveness
  459. * @param int $comma the number of decimals to retain
  460. *
  461. * @return array the formatted value and its unit
  462. */
  463. function ADVISOR_formatByteDown($value, $limes = 6, $comma = 0)
  464. {
  465. return PMA_Util::formatByteDown($value, $limes, $comma);
  466. }
  467. ?>