PageRenderTime 52ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/adodb/adodb-perf.inc.php

https://bitbucket.org/yousef_fadila/vtiger
PHP | 1056 lines | 850 code | 90 blank | 116 comment | 121 complexity | 17882e06c2ed238cb05dcdb36e26ccb8 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0
  1. <?php
  2. /*
  3. V4.90 8 June 2006 (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
  4. Released under both BSD license and Lesser GPL library license.
  5. Whenever there is any discrepancy between the two licenses,
  6. the BSD license will take precedence. See License.txt.
  7. Set tabs to 4 for best viewing.
  8. Latest version is available at http://adodb.sourceforge.net
  9. Library for basic performance monitoring and tuning.
  10. My apologies if you see code mixed with presentation. The presentation suits
  11. my needs. If you want to separate code from presentation, be my guest. Patches
  12. are welcome.
  13. */
  14. if (!defined('ADODB_DIR')) include_once(dirname(__FILE__).'/adodb.inc.php');
  15. include_once(ADODB_DIR.'/tohtml.inc.php');
  16. define( 'ADODB_OPT_HIGH', 2);
  17. define( 'ADODB_OPT_LOW', 1);
  18. // returns in K the memory of current process, or 0 if not known
  19. function adodb_getmem()
  20. {
  21. if (function_exists('memory_get_usage'))
  22. return (integer) ((memory_get_usage()+512)/1024);
  23. $pid = getmypid();
  24. if ( strncmp(strtoupper(PHP_OS),'WIN',3)==0) {
  25. $output = array();
  26. exec('tasklist /FI "PID eq ' . $pid. '" /FO LIST', $output);
  27. return substr($output[5], strpos($output[5], ':') + 1);
  28. }
  29. /* Hopefully UNIX */
  30. exec("ps --pid $pid --no-headers -o%mem,size", $output);
  31. if (sizeof($output) == 0) return 0;
  32. $memarr = explode(' ',$output[0]);
  33. if (sizeof($memarr)>=2) return (integer) $memarr[1];
  34. return 0;
  35. }
  36. // avoids localization problems where , is used instead of .
  37. function adodb_round($n,$prec)
  38. {
  39. return number_format($n, $prec, '.', '');
  40. }
  41. /* return microtime value as a float */
  42. function adodb_microtime()
  43. {
  44. $t = microtime();
  45. $t = explode(' ',$t);
  46. return (float)$t[1]+ (float)$t[0];
  47. }
  48. /* sql code timing */
  49. function& adodb_log_sql(&$conn,$sql,$inputarr)
  50. {
  51. $perf_table = adodb_perf::table();
  52. $conn->fnExecute = false;
  53. $t0 = microtime();
  54. $rs =& $conn->Execute($sql,$inputarr);
  55. $t1 = microtime();
  56. if (!empty($conn->_logsql)) {
  57. $conn->_logsql = false; // disable logsql error simulation
  58. $dbT = $conn->databaseType;
  59. $a0 = split(' ',$t0);
  60. $a0 = (float)$a0[1]+(float)$a0[0];
  61. $a1 = split(' ',$t1);
  62. $a1 = (float)$a1[1]+(float)$a1[0];
  63. $time = $a1 - $a0;
  64. if (!$rs) {
  65. $errM = $conn->ErrorMsg();
  66. $errN = $conn->ErrorNo();
  67. $conn->lastInsID = 0;
  68. $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
  69. } else {
  70. $tracer = '';
  71. $errM = '';
  72. $errN = 0;
  73. $dbg = $conn->debug;
  74. $conn->debug = false;
  75. if (!is_object($rs) || $rs->dataProvider == 'empty')
  76. $conn->_affected = $conn->affected_rows(true);
  77. $conn->lastInsID = @$conn->Insert_ID();
  78. $conn->debug = $dbg;
  79. }
  80. if (isset($_SERVER['HTTP_HOST'])) {
  81. $tracer .= '<br>'.$_SERVER['HTTP_HOST'];
  82. if (isset($_SERVER['PHP_SELF'])) $tracer .= $_SERVER['PHP_SELF'];
  83. } else
  84. if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.$_SERVER['PHP_SELF'];
  85. //$tracer .= (string) adodb_backtrace(false);
  86. $tracer = (string) substr($tracer,0,500);
  87. if (is_array($inputarr)) {
  88. if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
  89. else {
  90. // Quote string parameters so we can see them in the
  91. // performance stats. This helps spot disabled indexes.
  92. $xar_params = $inputarr;
  93. foreach ($xar_params as $xar_param_key => $xar_param) {
  94. if (gettype($xar_param) == 'string')
  95. $xar_params[$xar_param_key] = '"' . $xar_param . '"';
  96. }
  97. $params = implode(', ', $xar_params);
  98. if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
  99. }
  100. } else {
  101. $params = '';
  102. }
  103. if (is_array($sql)) $sql = $sql[0];
  104. $arr = array('b'=>strlen($sql).'.'.crc32($sql),
  105. 'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
  106. //var_dump($arr);
  107. $saved = $conn->debug;
  108. $conn->debug = 0;
  109. $d = $conn->sysTimeStamp;
  110. if (empty($d)) $d = date("'Y-m-d H:i:s'");
  111. if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
  112. $isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
  113. } else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || $dbT == 'odbtp') {
  114. $timer = $arr['f'];
  115. if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
  116. $sql1 = $conn->qstr($arr['b']);
  117. $sql2 = $conn->qstr($arr['c']);
  118. $params = $conn->qstr($arr['d']);
  119. $tracer = $conn->qstr($arr['e']);
  120. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)";
  121. if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
  122. $arr = false;
  123. } else {
  124. $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
  125. }
  126. $ok = $conn->Execute($isql,$arr);
  127. $conn->debug = $saved;
  128. if ($ok) {
  129. $conn->_logsql = true;
  130. } else {
  131. $err2 = $conn->ErrorMsg();
  132. $conn->_logsql = true; // enable logsql error simulation
  133. $perf =& NewPerfMonitor($conn);
  134. if ($perf) {
  135. if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
  136. } else {
  137. $ok = $conn->Execute("create table $perf_table (
  138. created varchar(50),
  139. sql0 varchar(250),
  140. sql1 varchar(4000),
  141. params varchar(3000),
  142. tracer varchar(500),
  143. timer decimal(16,6))");
  144. }
  145. if (!$ok) {
  146. ADOConnection::outp( "<p><b>LOGSQL Insert Failed</b>: $isql<br>$err2</p>");
  147. $conn->_logsql = false;
  148. }
  149. }
  150. $conn->_errorMsg = $errM;
  151. $conn->_errorCode = $errN;
  152. }
  153. $conn->fnExecute = 'adodb_log_sql';
  154. return $rs;
  155. }
  156. /*
  157. The settings data structure is an associative array that database parameter per element.
  158. Each database parameter element in the array is itself an array consisting of:
  159. 0: category code, used to group related db parameters
  160. 1: either
  161. a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'",
  162. b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),
  163. c. a string prefixed by =, then a PHP method of the class is invoked,
  164. e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',
  165. 2: description of the database parameter
  166. */
  167. class adodb_perf {
  168. var $conn;
  169. var $color = '#F0F0F0';
  170. var $table = '<table border=1 bgcolor=white>';
  171. var $titles = '<tr><td><b>Parameter</b></td><td><b>Value</b></td><td><b>Description</b></td></tr>';
  172. var $warnRatio = 90;
  173. var $tablesSQL = false;
  174. var $cliFormat = "%32s => %s \r\n";
  175. var $sql1 = 'sql1'; // used for casting sql1 to text for mssql
  176. var $explain = true;
  177. var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";
  178. var $createTableSQL = false;
  179. var $maxLength = 2000;
  180. // Sets the tablename to be used
  181. function table($newtable = false)
  182. {
  183. static $_table;
  184. if (!empty($newtable)) $_table = $newtable;
  185. if (empty($_table)) $_table = 'adodb_logsql';
  186. return $_table;
  187. }
  188. // returns array with info to calculate CPU Load
  189. function _CPULoad()
  190. {
  191. /*
  192. cpu 524152 2662 2515228 336057010
  193. cpu0 264339 1408 1257951 168025827
  194. cpu1 259813 1254 1257277 168031181
  195. page 622307 25475680
  196. swap 24 1891
  197. intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  198. disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)
  199. ctxt 66155838
  200. btime 1062315585
  201. processes 69293
  202. */
  203. // Algorithm is taken from
  204. // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wmisdk/wmi/example__obtaining_raw_performance_data.asp
  205. if (strncmp(PHP_OS,'WIN',3)==0) {
  206. if (PHP_VERSION == '5.0.0') return false;
  207. if (PHP_VERSION == '5.0.1') return false;
  208. if (PHP_VERSION == '5.0.2') return false;
  209. if (PHP_VERSION == '5.0.3') return false;
  210. if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737
  211. @$c = new COM("WinMgmts:{impersonationLevel=impersonate}!Win32_PerfRawData_PerfOS_Processor.Name='_Total'");
  212. if (!$c) return false;
  213. $info[0] = $c->PercentProcessorTime;
  214. $info[1] = 0;
  215. $info[2] = 0;
  216. $info[3] = $c->TimeStamp_Sys100NS;
  217. //print_r($info);
  218. return $info;
  219. }
  220. // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
  221. $statfile = '/proc/stat';
  222. if (!file_exists($statfile)) return false;
  223. $fd = fopen($statfile,"r");
  224. if (!$fd) return false;
  225. $statinfo = explode("\n",fgets($fd, 1024));
  226. fclose($fd);
  227. foreach($statinfo as $line) {
  228. $info = explode(" ",$line);
  229. if($info[0]=="cpu") {
  230. array_shift($info); // pop off "cpu"
  231. if(!$info[0]) array_shift($info); // pop off blank space (if any)
  232. return $info;
  233. }
  234. }
  235. return false;
  236. }
  237. /* NOT IMPLEMENTED */
  238. function MemInfo()
  239. {
  240. /*
  241. total: used: free: shared: buffers: cached:
  242. Mem: 1055289344 917299200 137990144 0 165437440 599773184
  243. Swap: 2146775040 11055104 2135719936
  244. MemTotal: 1030556 kB
  245. MemFree: 134756 kB
  246. MemShared: 0 kB
  247. Buffers: 161560 kB
  248. Cached: 581384 kB
  249. SwapCached: 4332 kB
  250. Active: 494468 kB
  251. Inact_dirty: 322856 kB
  252. Inact_clean: 24256 kB
  253. Inact_target: 168316 kB
  254. HighTotal: 131064 kB
  255. HighFree: 1024 kB
  256. LowTotal: 899492 kB
  257. LowFree: 133732 kB
  258. SwapTotal: 2096460 kB
  259. SwapFree: 2085664 kB
  260. Committed_AS: 348732 kB
  261. */
  262. }
  263. /*
  264. Remember that this is client load, not db server load!
  265. */
  266. var $_lastLoad;
  267. function CPULoad()
  268. {
  269. $info = $this->_CPULoad();
  270. if (!$info) return false;
  271. if (empty($this->_lastLoad)) {
  272. sleep(1);
  273. $this->_lastLoad = $info;
  274. $info = $this->_CPULoad();
  275. }
  276. $last = $this->_lastLoad;
  277. $this->_lastLoad = $info;
  278. $d_user = $info[0] - $last[0];
  279. $d_nice = $info[1] - $last[1];
  280. $d_system = $info[2] - $last[2];
  281. $d_idle = $info[3] - $last[3];
  282. //printf("Delta - User: %f Nice: %f System: %f Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
  283. if (strncmp(PHP_OS,'WIN',3)==0) {
  284. if ($d_idle < 1) $d_idle = 1;
  285. return 100*(1-$d_user/$d_idle);
  286. }else {
  287. $total=$d_user+$d_nice+$d_system+$d_idle;
  288. if ($total<1) $total=1;
  289. return 100*($d_user+$d_nice+$d_system)/$total;
  290. }
  291. }
  292. function Tracer($sql)
  293. {
  294. $perf_table = adodb_perf::table();
  295. $saveE = $this->conn->fnExecute;
  296. $this->conn->fnExecute = false;
  297. global $ADODB_FETCH_MODE;
  298. $save = $ADODB_FETCH_MODE;
  299. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  300. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  301. $sqlq = $this->conn->qstr($sql);
  302. $arr = $this->conn->GetArray(
  303. "select count(*),tracer
  304. from $perf_table where sql1=$sqlq
  305. group by tracer
  306. order by 1 desc");
  307. $s = '';
  308. if ($arr) {
  309. $s .= '<h3>Scripts Affected</h3>';
  310. foreach($arr as $k) {
  311. $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
  312. }
  313. }
  314. if (isset($savem)) $this->conn->SetFetchMode($savem);
  315. $ADODB_CACHE_MODE = $save;
  316. $this->conn->fnExecute = $saveE;
  317. return $s;
  318. }
  319. /*
  320. Explain Plan for $sql.
  321. If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the
  322. actual sql.
  323. */
  324. function Explain($sql,$partial=false)
  325. {
  326. return false;
  327. }
  328. function InvalidSQL($numsql = 10)
  329. {
  330. if (isset($_GET['sql'])) return;
  331. $s = '<h3>Invalid SQL</h3>';
  332. $saveE = $this->conn->fnExecute;
  333. $this->conn->fnExecute = false;
  334. $perf_table = adodb_perf::table();
  335. $rs =& $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
  336. $this->conn->fnExecute = $saveE;
  337. if ($rs) {
  338. $s .= rs2html($rs,false,false,false,false);
  339. } else
  340. return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  341. return $s;
  342. }
  343. /*
  344. This script identifies the longest running SQL
  345. */
  346. function _SuspiciousSQL($numsql = 10)
  347. {
  348. global $ADODB_FETCH_MODE;
  349. $perf_table = adodb_perf::table();
  350. $saveE = $this->conn->fnExecute;
  351. $this->conn->fnExecute = false;
  352. if (isset($_GET['exps']) && isset($_GET['sql'])) {
  353. $partial = !empty($_GET['part']);
  354. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  355. }
  356. if (isset($_GET['sql'])) return;
  357. $sql1 = $this->sql1;
  358. $save = $ADODB_FETCH_MODE;
  359. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  360. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  361. //$this->conn->debug=1;
  362. $rs =& $this->conn->SelectLimit(
  363. "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  364. from $perf_table
  365. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  366. and (tracer is null or tracer not like 'ERROR:%')
  367. group by sql1
  368. order by 1 desc",$numsql);
  369. if (isset($savem)) $this->conn->SetFetchMode($savem);
  370. $ADODB_FETCH_MODE = $save;
  371. $this->conn->fnExecute = $saveE;
  372. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  373. $s = "<h3>Suspicious SQL</h3>
  374. <font size=1>The following SQL have high average execution times</font><br>
  375. <table border=1 bgcolor=white><tr><td><b>Avg Time</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
  376. $max = $this->maxLength;
  377. while (!$rs->EOF) {
  378. $sql = $rs->fields[1];
  379. $raw = urlencode($sql);
  380. if (strlen($raw)>$max-100) {
  381. $sql2 = substr($sql,0,$max-500);
  382. $raw = urlencode($sql2).'&part='.crc32($sql);
  383. }
  384. $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
  385. $suffix = "</a>";
  386. if ($this->explain == false || strlen($prefix)>$max) {
  387. $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
  388. $prefix = '';
  389. }
  390. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  391. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  392. $rs->MoveNext();
  393. }
  394. return $s."</table>";
  395. }
  396. function CheckMemory()
  397. {
  398. return '';
  399. }
  400. function SuspiciousSQL($numsql=10)
  401. {
  402. return adodb_perf::_SuspiciousSQL($numsql);
  403. }
  404. function ExpensiveSQL($numsql=10)
  405. {
  406. return adodb_perf::_ExpensiveSQL($numsql);
  407. }
  408. /*
  409. This reports the percentage of load on the instance due to the most
  410. expensive few SQL statements. Tuning these statements can often
  411. make huge improvements in overall system performance.
  412. */
  413. function _ExpensiveSQL($numsql = 10)
  414. {
  415. global $ADODB_FETCH_MODE;
  416. $perf_table = adodb_perf::table();
  417. $saveE = $this->conn->fnExecute;
  418. $this->conn->fnExecute = false;
  419. if (isset($_GET['expe']) && isset($_GET['sql'])) {
  420. $partial = !empty($_GET['part']);
  421. echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
  422. }
  423. if (isset($_GET['sql'])) return;
  424. $sql1 = $this->sql1;
  425. $save = $ADODB_FETCH_MODE;
  426. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  427. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  428. $rs =& $this->conn->SelectLimit(
  429. "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
  430. from $perf_table
  431. where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
  432. and (tracer is null or tracer not like 'ERROR:%')
  433. group by sql1
  434. having count(*)>1
  435. order by 1 desc",$numsql);
  436. if (isset($savem)) $this->conn->SetFetchMode($savem);
  437. $this->conn->fnExecute = $saveE;
  438. $ADODB_FETCH_MODE = $save;
  439. if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
  440. $s = "<h3>Expensive SQL</h3>
  441. <font size=1>Tuning the following SQL could reduce the server load substantially</font><br>
  442. <table border=1 bgcolor=white><tr><td><b>Load</b><td><b>Count</b><td><b>SQL</b><td><b>Max</b><td><b>Min</b></tr>\n";
  443. $max = $this->maxLength;
  444. while (!$rs->EOF) {
  445. $sql = $rs->fields[1];
  446. $raw = urlencode($sql);
  447. if (strlen($raw)>$max-100) {
  448. $sql2 = substr($sql,0,$max-500);
  449. $raw = urlencode($sql2).'&part='.crc32($sql);
  450. }
  451. $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
  452. $suffix = "</a>";
  453. if($this->explain == false || strlen($prefix>$max)) {
  454. $prefix = '';
  455. $suffix = '';
  456. }
  457. $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
  458. "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
  459. $rs->MoveNext();
  460. }
  461. return $s."</table>";
  462. }
  463. /*
  464. Raw function to return parameter value from $settings.
  465. */
  466. function DBParameter($param)
  467. {
  468. if (empty($this->settings[$param])) return false;
  469. $sql = $this->settings[$param][1];
  470. return $this->_DBParameter($sql);
  471. }
  472. /*
  473. Raw function returning array of poll paramters
  474. */
  475. function &PollParameters()
  476. {
  477. $arr[0] = (float)$this->DBParameter('data cache hit ratio');
  478. $arr[1] = (float)$this->DBParameter('data reads');
  479. $arr[2] = (float)$this->DBParameter('data writes');
  480. $arr[3] = (integer) $this->DBParameter('current connections');
  481. return $arr;
  482. }
  483. /*
  484. Low-level Get Database Parameter
  485. */
  486. function _DBParameter($sql)
  487. {
  488. $savelog = $this->conn->LogSQL(false);
  489. if (is_array($sql)) {
  490. global $ADODB_FETCH_MODE;
  491. $sql1 = $sql[0];
  492. $key = $sql[1];
  493. if (sizeof($sql)>2) $pos = $sql[2];
  494. else $pos = 1;
  495. if (sizeof($sql)>3) $coef = $sql[3];
  496. else $coef = false;
  497. $ret = false;
  498. $save = $ADODB_FETCH_MODE;
  499. $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  500. if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
  501. $rs = $this->conn->Execute($sql1);
  502. if (isset($savem)) $this->conn->SetFetchMode($savem);
  503. $ADODB_FETCH_MODE = $save;
  504. if ($rs) {
  505. while (!$rs->EOF) {
  506. $keyf = reset($rs->fields);
  507. if (trim($keyf) == $key) {
  508. $ret = $rs->fields[$pos];
  509. if ($coef) $ret *= $coef;
  510. break;
  511. }
  512. $rs->MoveNext();
  513. }
  514. $rs->Close();
  515. }
  516. $this->conn->LogSQL($savelog);
  517. return $ret;
  518. } else {
  519. if (strncmp($sql,'=',1) == 0) {
  520. $fn = substr($sql,1);
  521. return $this->$fn();
  522. }
  523. $sql = str_replace('$DATABASE',$this->conn->database,$sql);
  524. $ret = $this->conn->GetOne($sql);
  525. $this->conn->LogSQL($savelog);
  526. return $ret;
  527. }
  528. }
  529. /*
  530. Warn if cache ratio falls below threshold. Displayed in "Description" column.
  531. */
  532. function WarnCacheRatio($val)
  533. {
  534. if ($val < $this->warnRatio)
  535. return '<font color=red><b>Cache ratio should be at least '.$this->warnRatio.'%</b></font>';
  536. else return '';
  537. }
  538. /***********************************************************************************************/
  539. // HIGH LEVEL UI FUNCTIONS
  540. /***********************************************************************************************/
  541. function UI($pollsecs=5)
  542. {
  543. $perf_table = adodb_perf::table();
  544. $conn = $this->conn;
  545. $app = $conn->host;
  546. if ($conn->host && $conn->database) $app .= ', db=';
  547. $app .= $conn->database;
  548. if ($app) $app .= ', ';
  549. $savelog = $this->conn->LogSQL(false);
  550. $info = $conn->ServerInfo();
  551. if (isset($_GET['clearsql'])) {
  552. $this->conn->Execute("delete from $perf_table");
  553. }
  554. $this->conn->LogSQL($savelog);
  555. // magic quotes
  556. if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
  557. $_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
  558. }
  559. if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
  560. else $nsql = $_SESSION['ADODB_PERF_SQL'];
  561. $app .= $info['description'];
  562. if (isset($_GET['do'])) $do = $_GET['do'];
  563. else if (isset($_POST['do'])) $do = $_POST['do'];
  564. else if (isset($_GET['sql'])) $do = 'viewsql';
  565. else $do = 'stats';
  566. if (isset($_GET['nsql'])) {
  567. if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
  568. }
  569. echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
  570. if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
  571. else $form = "<td>&nbsp;</td>";
  572. $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
  573. if (empty($_GET['hidem']))
  574. echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
  575. <b><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</b> <font size=1>for $app</font></tr><tr><td>
  576. <a href=?do=stats><b>Performance Stats</b></a> &nbsp; <a href=?do=viewsql><b>View SQL</b></a>
  577. &nbsp; <a href=?do=tables><b>View Tables</b></a> &nbsp; <a href=?do=poll><b>Poll Stats</b></a>",
  578. $allowsql ? ' &nbsp; <a href=?do=dosql><b>Run SQL</b></a>' : '',
  579. "$form",
  580. "</tr></table>";
  581. switch ($do) {
  582. default:
  583. case 'stats':
  584. echo $this->HealthCheck();
  585. //$this->conn->debug=1;
  586. echo $this->CheckMemory();
  587. break;
  588. case 'poll':
  589. echo "<iframe width=720 height=80%
  590. src=\"{$_SERVER['PHP_SELF']}?do=poll2&hidem=1\"></iframe>";
  591. break;
  592. case 'poll2':
  593. echo "<pre>";
  594. $this->Poll($pollsecs);
  595. break;
  596. case 'dosql':
  597. if (!$allowsql) break;
  598. $this->DoSQLForm();
  599. break;
  600. case 'viewsql':
  601. if (empty($_GET['hidem']))
  602. echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
  603. echo($this->SuspiciousSQL($nsql));
  604. echo($this->ExpensiveSQL($nsql));
  605. echo($this->InvalidSQL($nsql));
  606. break;
  607. case 'tables':
  608. echo $this->Tables(); break;
  609. }
  610. global $ADODB_vers;
  611. echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
  612. }
  613. /*
  614. Runs in infinite loop, returning real-time statistics
  615. */
  616. function Poll($secs=5)
  617. {
  618. $this->conn->fnExecute = false;
  619. //$this->conn->debug=1;
  620. if ($secs <= 1) $secs = 1;
  621. echo "Accumulating statistics, every $secs seconds...\n";flush();
  622. $arro =& $this->PollParameters();
  623. $cnt = 0;
  624. set_time_limit(0);
  625. sleep($secs);
  626. while (1) {
  627. $arr =& $this->PollParameters();
  628. $hits = sprintf('%2.2f',$arr[0]);
  629. $reads = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
  630. $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
  631. $sess = sprintf('%5d',$arr[3]);
  632. $load = $this->CPULoad();
  633. if ($load !== false) {
  634. $oslabel = 'WS-CPU%';
  635. $osval = sprintf(" %2.1f ",(float) $load);
  636. }else {
  637. $oslabel = '';
  638. $osval = '';
  639. }
  640. if ($cnt % 10 == 0) echo " Time ".$oslabel." Hit% Sess Reads/s Writes/s\n";
  641. $cnt += 1;
  642. echo date('H:i:s').' '.$osval."$hits $sess $reads $writes\n";
  643. flush();
  644. if (connection_aborted()) return;
  645. sleep($secs);
  646. $arro = $arr;
  647. }
  648. }
  649. /*
  650. Returns basic health check in a command line interface
  651. */
  652. function HealthCheckCLI()
  653. {
  654. return $this->HealthCheck(true);
  655. }
  656. /*
  657. Returns basic health check as HTML
  658. */
  659. function HealthCheck($cli=false)
  660. {
  661. $saveE = $this->conn->fnExecute;
  662. $this->conn->fnExecute = false;
  663. if ($cli) $html = '';
  664. else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
  665. $oldc = false;
  666. $bgc = '';
  667. foreach($this->settings as $name => $arr) {
  668. if ($arr === false) break;
  669. if (!is_string($name)) {
  670. if ($cli) $html .= " -- $arr -- \n";
  671. else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
  672. continue;
  673. }
  674. if (!is_array($arr)) break;
  675. $category = $arr[0];
  676. $how = $arr[1];
  677. if (sizeof($arr)>2) $desc = $arr[2];
  678. else $desc = ' &nbsp; ';
  679. if ($category == 'HIDE') continue;
  680. $val = $this->_DBParameter($how);
  681. if ($desc && strncmp($desc,"=",1) === 0) {
  682. $fn = substr($desc,1);
  683. $desc = $this->$fn($val);
  684. }
  685. if ($val === false) {
  686. $m = $this->conn->ErrorMsg();
  687. $val = "Error: $m";
  688. } else {
  689. if (is_numeric($val) && $val >= 256*1024) {
  690. if ($val % (1024*1024) == 0) {
  691. $val /= (1024*1024);
  692. $val .= 'M';
  693. } else if ($val % 1024 == 0) {
  694. $val /= 1024;
  695. $val .= 'K';
  696. }
  697. //$val = htmlspecialchars($val);
  698. }
  699. }
  700. if ($category != $oldc) {
  701. $oldc = $category;
  702. //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
  703. }
  704. if (strlen($desc)==0) $desc = '&nbsp;';
  705. if (strlen($val)==0) $val = '&nbsp;';
  706. if ($cli) {
  707. $html .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
  708. }else {
  709. $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
  710. }
  711. }
  712. if (!$cli) $html .= "</table>\n";
  713. $this->conn->fnExecute = $saveE;
  714. return $html;
  715. }
  716. function Tables($orderby='1')
  717. {
  718. if (!$this->tablesSQL) return false;
  719. $savelog = $this->conn->LogSQL(false);
  720. $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
  721. $this->conn->LogSQL($savelog);
  722. $html = rs2html($rs,false,false,false,false);
  723. return $html;
  724. }
  725. function CreateLogTable()
  726. {
  727. if (!$this->createTableSQL) return false;
  728. $table = $this->table();
  729. $sql = str_replace('adodb_logsql',$table,$this->createTableSQL);
  730. $savelog = $this->conn->LogSQL(false);
  731. $ok = $this->conn->Execute($sql);
  732. $this->conn->LogSQL($savelog);
  733. return ($ok) ? true : false;
  734. }
  735. function DoSQLForm()
  736. {
  737. $PHP_SELF = $_SERVER['PHP_SELF'];
  738. $sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
  739. if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
  740. else $rows = 3;
  741. if (isset($_REQUEST['SMALLER'])) {
  742. $rows /= 2;
  743. if ($rows < 3) $rows = 3;
  744. $_SESSION['phplens_sqlrows'] = $rows;
  745. }
  746. if (isset($_REQUEST['BIGGER'])) {
  747. $rows *= 2;
  748. $_SESSION['phplens_sqlrows'] = $rows;
  749. }
  750. ?>
  751. <form method="POST" action="<?php echo $PHP_SELF ?>">
  752. <table><tr>
  753. <td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
  754. </td>
  755. <td align=right>
  756. <input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
  757. </td></tr>
  758. <tr>
  759. <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
  760. </td>
  761. </tr>
  762. </table>
  763. </form>
  764. <?php
  765. if (!isset($_REQUEST['sql'])) return;
  766. $sql = $this->undomq(trim($sql));
  767. if (substr($sql,strlen($sql)-1) === ';') {
  768. $print = true;
  769. $sqla = $this->SplitSQL($sql);
  770. } else {
  771. $print = false;
  772. $sqla = array($sql);
  773. }
  774. foreach($sqla as $sqls) {
  775. if (!$sqls) continue;
  776. if ($print) {
  777. print "<p>".htmlspecialchars($sqls)."</p>";
  778. flush();
  779. }
  780. $savelog = $this->conn->LogSQL(false);
  781. $rs = $this->conn->Execute($sqls);
  782. $this->conn->LogSQL($savelog);
  783. if ($rs && is_object($rs) && !$rs->EOF) {
  784. rs2html($rs);
  785. while ($rs->NextRecordSet()) {
  786. print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
  787. rs2html($rs);
  788. }
  789. } else {
  790. $e1 = (integer) $this->conn->ErrorNo();
  791. $e2 = $this->conn->ErrorMsg();
  792. if (($e1) || ($e2)) {
  793. if (empty($e1)) $e1 = '-1'; // postgresql fix
  794. print ' &nbsp; '.$e1.': '.$e2;
  795. } else {
  796. print "<p>No Recordset returned<br></p>";
  797. }
  798. }
  799. } // foreach
  800. }
  801. function SplitSQL($sql)
  802. {
  803. $arr = explode(';',$sql);
  804. return $arr;
  805. }
  806. function undomq($m)
  807. {
  808. if (get_magic_quotes_gpc()) {
  809. // undo the damage
  810. $m = str_replace('\\\\','\\',$m);
  811. $m = str_replace('\"','"',$m);
  812. $m = str_replace('\\\'','\'',$m);
  813. }
  814. return $m;
  815. }
  816. /************************************************************************/
  817. /**
  818. * Reorganise multiple table-indices/statistics/..
  819. * OptimizeMode could be given by last Parameter
  820. *
  821. * @example
  822. * <pre>
  823. * optimizeTables( 'tableA');
  824. * </pre>
  825. * <pre>
  826. * optimizeTables( 'tableA', 'tableB', 'tableC');
  827. * </pre>
  828. * <pre>
  829. * optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
  830. * </pre>
  831. *
  832. * @param string table name of the table to optimize
  833. * @param int mode optimization-mode
  834. * <code>ADODB_OPT_HIGH</code> for full optimization
  835. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  836. * Default is LOW <code>ADODB_OPT_LOW</code>
  837. * @author Markus Staab
  838. * @return Returns <code>true</code> on success and <code>false</code> on error
  839. */
  840. function OptimizeTables()
  841. {
  842. $args = func_get_args();
  843. $numArgs = func_num_args();
  844. if ( $numArgs == 0) return false;
  845. $mode = ADODB_OPT_LOW;
  846. $lastArg = $args[ $numArgs - 1];
  847. if ( !is_string($lastArg)) {
  848. $mode = $lastArg;
  849. unset( $args[ $numArgs - 1]);
  850. }
  851. foreach( $args as $table) {
  852. $this->optimizeTable( $table, $mode);
  853. }
  854. }
  855. /**
  856. * Reorganise the table-indices/statistics/.. depending on the given mode.
  857. * Default Implementation throws an error.
  858. *
  859. * @param string table name of the table to optimize
  860. * @param int mode optimization-mode
  861. * <code>ADODB_OPT_HIGH</code> for full optimization
  862. * <code>ADODB_OPT_LOW</code> for CPU-less optimization
  863. * Default is LOW <code>ADODB_OPT_LOW</code>
  864. * @author Markus Staab
  865. * @return Returns <code>true</code> on success and <code>false</code> on error
  866. */
  867. function OptimizeTable( $table, $mode = ADODB_OPT_LOW)
  868. {
  869. ADOConnection::outp( sprintf( "<p>%s: '%s' not implemented for driver '%s'</p>", __CLASS__, __FUNCTION__, $this->conn->databaseType));
  870. return false;
  871. }
  872. /**
  873. * Reorganise current database.
  874. * Default implementation loops over all <code>MetaTables()</code> and
  875. * optimize each using <code>optmizeTable()</code>
  876. *
  877. * @author Markus Staab
  878. * @return Returns <code>true</code> on success and <code>false</code> on error
  879. */
  880. function optimizeDatabase()
  881. {
  882. $conn = $this->conn;
  883. if ( !$conn) return false;
  884. $tables = $conn->MetaTables( 'TABLES');
  885. if ( !$tables ) return false;
  886. foreach( $tables as $table) {
  887. if ( !$this->optimizeTable( $table)) {
  888. return false;
  889. }
  890. }
  891. return true;
  892. }
  893. // end hack
  894. }
  895. ?>