home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2005 June / PCpro_2005_06.ISO / files / opensource / xamp / xampp-win32.exe / xampp / adodb-perf.inc.php < prev    next >
Encoding:
PHP Script  |  2005-01-24  |  27.0 KB  |  919 lines

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