From 19d46e48b4e15a489e2607f6fcea5a7ae149f192 Mon Sep 17 00:00:00 2001 From: Michael Clemens Date: Tue, 12 May 2009 00:30:45 +0000 Subject: [PATCH] first step of migration to object oriented version of TSM Monitor deleted functions.php, replaced with tsmmonitor.php which includes new class TSMMonitor --- admin.php | 38 +- includes/functions.php | 1739 --------------------------------------- includes/global.php | 14 +- includes/overview.php | 8 +- includes/pdf.php | 15 +- includes/polld.php | 1 + includes/topnav.php | 12 +- includes/tsmmonitor.php | 1620 ++++++++++++++++++++++++++++++++++++ index.php | 56 +- install.php | 26 +- 10 files changed, 1707 insertions(+), 1822 deletions(-) delete mode 100644 includes/functions.php create mode 100644 includes/tsmmonitor.php diff --git a/admin.php b/admin.php index 41ee697..8aa9cef 100644 --- a/admin.php +++ b/admin.php @@ -57,7 +57,7 @@ if ($_POST["css"] != "") {

@@ -68,14 +68,14 @@ if ($_POST["css"] != "") { GETVars['qq'] != "logout" && $_SESSION["logindata"]["loggedin"]) { + if ($tsmmonitor->GETVars['qq'] != "" && $tsmmonitor->GETVars['qq'] != "overview") { // show overview page - if ($GETVars['qq'] == "index") { + if ($tsmmonitor->GETVars['qq'] == "index") { // do nothing // show settings page - } else if ($GETVars['qq'] == "settings") { + } else if ($tsmmonitor->GETVars['qq'] == "settings") { $tmonpolld = new PollD(); $tmonpolld->setDBParams($db_host, $db_name, $db_user, $db_password); $tmonpolld->initialize(); @@ -98,7 +98,7 @@ if (isset($_SESSION["logindata"]["user"]) && isset($_SESSION["logindata"]["pass" } echo "PollD Control
"; - echo "
"; + echo ""; echo ""; echo ""; echo "\n"; - } - - return $out; - -} - - -/** - * generateTimetableHeader - returns HTML code for timetable header (display of hours) - * - * @param string $startpunkt I forgot that one - * @param string $FirstCol first field of result table - * @return string - */ - -function generateTimetableHeader($startpunkt = '', $FirstCol = '') { - - $header = $FirstCol["label"]; - $out= ""; - -return $out; - -} - - -/** - * generateTimetableNavigation - returns HTML code for timetable header (navigation buttons) - * - * @return string - */ - -function generateTimetableNavigation() { - - global $GETVars; - - $timesteps = array("1 hour" => "1", "6 hours" => "6", "12 hours" => "12", "24 hours" => "24"); - - $timetablestarttime = 24 + $_SESSION['timeshift']; - $out = ""; - // get value from combobox - if ($_POST["timestep"] != "") { - $_SESSION['selectedtimestep'] = $_POST["timestep"]; - } - $out .= ""; - $out .= ""; - - return $out; -} - - - -/** - * generateTimetable - generates HTML code for graphical timetables - * - * @param array $tablearray Array containing an SQL query result - * @param string $FirstCol first field of result table - * @return string - */ - -function generateTimetable($tablearray = '', $FirstCol = '') { - - global $timetablestarttime; - - $now = time(); - $out = ''; - $height = 8; - $faktor = 120; - $oneday = 86400; - $onehour = 3600; - $tolerance = 1200; - - $timetablestarttime = 24 + $_SESSION['timeshift']; - - $startpunkt = ((ceil($now/$onehour)*$onehour)-$onehour-$oneday)-(($timetablestarttime-24)*$onehour); - $endpunkt = $startpunkt + $oneday + $onehour; - $lastpoint = ($endpunkt - $startpunkt)/$faktor; - - $out .= "
Start/StopStatus
"; @@ -114,9 +114,9 @@ if (isset($_SESSION["logindata"]["user"]) && isset($_SESSION["logindata"]["pass" $i = 0; // show Add New Entry Form if ($_POST['Add'] == "Add") { - $sqlth = "SHOW COLUMNS from cfg_".$GETVars['qq']; - $sqlresth = fetchArrayDB($sqlth, $conn); - echo ""; + $sqlth = "SHOW COLUMNS from cfg_".$tsmmonitor->GETVars['qq']; + $sqlresth = $tsmmonitor->fetchArrayDB($sqlth, $conn); + echo ""; echo ""; echo ""; foreach ($sqlresth as $col) { @@ -144,8 +144,8 @@ echo "TEST: ".$col['Field']." -> $colval
\n"; // show Edit Existing Entry Form } else { - $tablearray = getAdminTables("edit"); - echo ""; + $tablearray = $tsmmonitor->getAdminTables("edit"); + echo ""; echo "
KeyValue
"; echo ""; foreach ($tablearray as $row) { @@ -182,12 +182,12 @@ echo "TEST: ".$col['Field']." -> $colval
\n"; if ($_GET['action'] == "delete") { echo $_POST['hidfield']; $sql = "DELETE from cfg_".$_GET['q']." where id='".$_GET['id']."' LIMIT 1"; - execDB($sql, $conn); + $tsmmonitor->execDB($sql, $conn); } // Process update of an existing item or insert of a new one } else if ($_POST['EditSave'] == "Save" || $_POST['AddSave'] == "Save") { $sqlth = "SHOW COLUMNS from cfg_".$_GET['q']; - $sqlresth = fetchArrayDB($sqlth, $conn); + $sqlresth = $tsmmonitor->fetchArrayDB($sqlth, $conn); $colarray = array(); $colarray['id'] = $_POST['id']; $set = ""; @@ -228,13 +228,13 @@ echo "TEST: ".$col['Field']." -> $colval
\n"; } else if ($_POST['EditSave'] == "Save") { $sql = "UPDATE cfg_".$_GET['q']." set ".$set." where id='".$_POST['id']."' LIMIT 1"; } - updateDB("cfg_".$_GET['q'], $colarray, 'id', $conn); + $tsmmonitor->updateDB("cfg_".$_GET['q'], $colarray, 'id', $conn); } - echo ""; + echo ""; echo "
KeyValue
"; - echo getTableheader(); - echo getAdminTables("list"); - $nav = showPageNavigation("40"); + echo $tsmmonitor->getTableheader(); + echo $tsmmonitor->getAdminTables("list"); + $nav = $tsmmonitor->showPageNavigation("40"); if ($nav!="") { echo ""; } @@ -256,7 +256,7 @@ echo "TEST: ".$col['Field']." -> $colval
\n"; include_once "includes/login.php"; } -$_SESSION['from'] = $GETVars['qq']; +$_SESSION['from'] = $tsmmonitor->GETVars['qq']; session_write_close(void); ?> diff --git a/includes/functions.php b/includes/functions.php deleted file mode 100644 index 7513e10..0000000 --- a/includes/functions.php +++ /dev/null @@ -1,1739 +0,0 @@ -. - -************************************************************************ -*/ - -/** - * - * functions.php, TSM Monitor - * - * This file includes all general functions for TSM Monitor - * - * @author Michael Clemens - * @package tsmmonitor - */ - -/** - * initialize - This function us called every time index.php is refreshed - * - */ - -function initialize() { - - global $configarray; - global $queryarray; - global $GETVars; - global $page; - - global $submenu; - global $adminmenu; - //global $query; - global $whereclause; - global $message; - global $db_type, $db_name, $db_user, $db_password, $db_host, $db_charset, $db_collate, $conn; - - session_name("tsmmonitordev"); - session_start(); - - - // Login if not logged in and credentials are ok - if ((isset($_POST) && isset($_POST["loginname"]) && isset($_POST["loginpasswort"]) && (!isset($_SESSION["logindata"])))) { - $_SESSION["logindata"]["user"] = $_POST["loginname"]; - $_SESSION["logindata"]["pass"] = $_POST["loginpasswort"]; - checkLogin(); - } - - if ($_GET['q'] == "logout") { - unset($_SESSION["logindata"]); - } - -// if (!isset($_SESSION) || !isset($_SESSION['configarray'])) { - $_SESSION['configarray'] = getConfigArray(); -// } - - // GET-variables - $GETVars["menu"] = $_GET['m']; - $GETVars["qq"] = $_GET['q']; - $GETVars['ob'] = $_GET['sort']; - $GETVars['orderdir'] = $_GET['so']; - - if ($_POST['s'] != '') { - $GETVars['server'] = $_POST['s']; - } else { - $GETVars['server'] = $_GET['s']; - } - - - // Session-variables - $configarray = $_SESSION['configarray']; - - // timeout - if( !ini_get('safe_mode') && ini_get('max_execution_time') != $configarray["settings"]["timeout"]) { - ini_set('max_execution_time', $configarray["settings"]["timeout"]); - } - - // set defaults if vars are empty - if ($GETVars["menu"] == "") { $GETVars["menu"]="main"; } - if ($GETVars["qq"] == "") { $GETVars["qq"]="index"; } - if ($GETVars['server'] == "") { $GETVars['server']=$configarray["defaultserver"]; } - if ($GETVars['orderdir'] == "") { $GETVars['orderdir'] = "asc"; } - - if ($_SESSION['timeshift'] == '' || !strstr($GETVars["qq"], 'dynamictimetable')) { - $_SESSION['timeshift'] = 0 ; - } - - $submenu = $configarray["menuarray"][$GETVars['menu']]; - $adminmenu = $configarray["adminmenuarray"]; - //$query = $configarray["queryarray"][$GETVars['qq']]["tsmquery"]; - $queryarray = $configarray["queryarray"]; - - $_SESSION["GETVars"] = $GETVars; - - - // BEGIN Timemachine - if ($_SESSION["from"] != $_GET['q']) { - $_SESSION['timemachine'] = ""; - } - - if ($_POST['dateinput'] != "") $_SESSION['timemachine']['date'] = strtotime($_POST['dateinput']); - if ($_POST['timestamps'] != "") $_SESSION['timemachine']['time'] = $_POST['timestamps']; - - - if ($_POST["Poll"] == "Poll Now!") { - $timestamp = time(); - $tmonpolld = new PollD(); - $tmonpolld->setDBParams($db_host, $db_name, $db_user, $db_password); - $tmonpolld->initialize(); - $tmonpolld->pollQuery($tmonpolld->queries[$GETVars['qq']], $tmonpolld->servers[$GETVars['server']], TRUE, $timestamp); - $_SESSION['timemachine']['date'] = $timestamp; - $_SESSION['timemachine']['time'] = $timestamp; - } - - - if (($_POST['Poll'] == "Poll Now!" || $_SESSION['timemachine']['date'] == "") && $queryarray[$GETVars['qq']]["polltype"]=="snapshot" || $_POST['s'] != "" && $GETVars['qq'] != "overview" && $GETVars['qq'] != "index") { - $qtable = $configarray["queryarray"][$GETVars['qq']]["name"]; - $sql = "SELECT MAX(TimeStamp) FROM res_".$qtable."_".$GETVars["server"]; - $res = fetchArrayDB($sql, $conn); - $resarr = (array)$res[0]; - $_SESSION['timemachine']['date'] = $resarr["MAX(TimeStamp)"]; - $_SESSION['timemachine']['time'] = $resarr["MAX(TimeStamp)"]; - } - - - // Custom Stylesheet - if ($_SESSION['stylesheet'] == "") { - if ($configarray['stylesheet'] != "") { - $_SESSION['stylesheet'] = $configarray['stylesheet']; - } else { - $_SESSION['stylesheet'] = "default.css"; - } - } - -} - - - - -/** - * showPageNavigation - generates a clickable navigation bar for sql results - * splitted by function fetchSplitArrayDB - * - * @param string links_per_page number of links that will be displayed per page - * @return string - */ - -function showPageNavigation($links_per_page = "1") { - - //$page = $_GET["page"]; - global $max_pages; - global $GETVars; - - $page = intval($_GET['page']); - if ($page == "") $page = 1; - $so = $_GET['so']; - $sortcol = $_GET['sort']; - - $getvars = 'q='.$_GET['q'].'&m='.$_GET['m'].'&s='.$GETVars['server'].'&sort='.$sortcol."&so=".$so; - $self = htmlspecialchars($_SERVER['PHP_SELF']); - $navelement = ''.$fp.''; - $fp = $navelement.'1">'.$fp.''; - } - - if($page != $max_pages) { - $lp = $navelement.($max_pages).'">'.$lp.''; - } - - if($page > 1) { - $pp = $navelement.($page-1).'">'.$pp.''; - } - - if($page < $max_pages) { - $np = $navelement.($page+1).'">'.$np.''; - } - - // Numbers - for($i=1;$i<=$max_pages;$i+=$links_per_page) { - if($page >= $i) { - $start = $i; - } - } - - if($max_pages > $links_per_page) { - $end = $start+$links_per_page; - if($end > $max_pages) $end = $max_pages+1; - } - else { - $end = $max_pages; - } - - $numbers = ''; - - for( $i=$start ; $i<=$end ; $i++) { - if($i == $page ) { - $numbers .= " $i "; - } - else { - $numbers .= ' '.$navelement.$i.'">'.$i.' '; - } - } - if ($end > 1) { - return $fp.' '.$pp.' '.$numbers.' '.$np.' '.$lp; - } else { - return ""; - } - -} - - - -/** - * GetBetween - little helper function that returns a string between two given strings - * - * @param string $content complete string - * @param string $start first string - * @param string $end second string - * @return string - */ - -function GetBetween($content,$start,$end) { - $r = explode($start, $content); - if (isset($r[1])) { - $r = explode($end, $r[1]); - return $r[0]; - } - return ''; -} - - - - -/** - * GetTimemachine - generates a date-/timechooser with which one can select a specific snapshot - * - * @return string - */ - -function GetTimemachine() { - - global $GETVars; - global $configarray; - $queryarray = $configarray["queryarray"]; - - $ret = ""; - - if ($queryarray[$GETVars['qq']]["polltype"]=="snapshot") { - $ret .= "
Time Machine

"; - $ret .= ""; - $ret .= ""; - $ret .= "
"; - $ret .= ""; - $ret .= "
"; - $ret .= "
"; - $ret .= ""; - $ret .= "

"; - - } else if ($queryarray[$GETVars['qq']]["polltype"]=="update" || $queryarray[$GETVars['qq']]["polltype"]=="append") { - $LastTimestamp = GetLastSnapshot(); - if ($LastTimestamp!="") { - $ret .= "
Time Machine

"; - $ret .= "
"; - $ret .= "Last updated: ".strftime('%H:%M:%S', $LastTimestamp); - $ret .= "
"; - $ret .= "
"; - $ret .= ""; - $ret .= "

"; - } - - } - - return $ret; - -} - - - - -/** - * getMenu - resturns HTML code for sidebar menu - * - * @param string $menu currently displayed menu - * @param string $activelink link that will be marked as selected - * @param string $type index or admin - * @return string - */ - -function getMenu($menu = '', $activelink = '', $type) { - - global $GETVars; - global $configarray; - - if (!isset($menu)) { return ""; }; - while(list($key, $val) = each($menu)) { - - $bCont = TRUE; - $q = GetBetween($key,"q=","&m="); - if ($configarray["queryarray"][$q]["notforlibclient"] == 1 && $configarray["serverlist"][$GETVars['server']]["libraryclient"] == 1) { - $bCont = FALSE; - - } - $key = $_SERVER['PHP_SELF']."?".$key; - - if ($type == "index") { - $key .= "&s=".$GETVars['server']; - } - - if ($val == "Admin") { - $key = "admin.php"; - }else if ($val == "TSM Monitor") { - $key = "index.php"; - } - - if ($val == "trennlinie") { - $links .= "
\n"; - } else if ($bCont) { - - if (!stristr($key,$activelink)) { - $links .= "$val\n"; - } else { - $links .= "
$val
\n"; - } - } - - } - return $links; -} - - - -/** - * getMessage - returns HTML code for global system message - * - * @return string - */ - - -function getMessage() { - - global $message; - - return "
System Message:

".$message."
"; -} - - - - -/** - * getInfo - returns HTML Code for Infoboxes with information about current query - * - * @return string - */ - -function getInfo() { - - global $configarray; - global $GETVars; - - $label = $configarray["queryarray"][$GETVars['qq']]["label"]; - $info = $configarray["queryarray"][$GETVars['qq']]["info"]; - - if ($info != "") { - $ret = "
".$label.":

".$info; - $ret .= "
"; - return $ret; - } -} - - - - - -/** - * getTableheader - generates and returns headers for query result HTML tables. - * - * @return string - */ - -function getTableheader() { - - global $GETVars; - global $configarray; - global $timetablestarttime; - global $conn; - - $tableheader=""; - $orderby = $configarray["queryarray"][$GETVars['qq']]["orderby"]; - $orderdir = $GETVars['orderdir']; - $page = $_GET['page']; - - if ($orderdir == "asc") { - $sonew="desc"; - } else if ($orderdir == "desc") { - $sonew="asc"; - } - - $isAdmin = strstr($_SERVER['PHP_SELF'], 'admin.php'); - - if ($isAdmin) { - $sql = "SHOW COLUMNS FROM cfg_".$_GET['q']; - } else { - $sql = "SHOW COLUMNS FROM res_".$configarray["queryarray"][$GETVars['qq']]["name"]."_".$GETVars['server']; - } - $fieldnames = fetchArrayDB($sql, $conn); - - // If table has more than one column - if (sizeof($fieldnames) > 1) { - foreach ($fieldnames as $col) { - if ($col['Field'] != "timestamp" && $col['Field'] != "id") { - $name = $col['Field']; - $arrow = ""; - if (($GETVars['ob'] == $name && $GETVars['ob']!="") || ($GETVars['ob']=="" && $orderby!="" && $orderby == $name)) { - $link = "href='".$_SERVER['PHP_SELF']."?q=".$GETVars['qq']."&m=".$GETVars['menu']."&sort=".$name."&page=".$page."&so=".$sonew."&s=".$GETVars['server']."'"; - if ($orderdir == "asc") { - $arrow = "⇑"; - } else if ($orderdir == "desc") { - $arrow = "⇓"; - } - } else { - $arrow = ""; - $link = "href='".$_SERVER['PHP_SELF']."?q=".$GETVars['qq']."&m=".$GETVars['menu']."&sort=".$name."&page=".$page."&s=".$GETVars['server']."'"; - } - $tableheader = $tableheader.""; - } - } - } else { - if ($orderdir == "asc") { - $arrow = "⇑"; - } else if ($orderdir == "desc") { - $arrow = "⇓"; - } - $link = "href='".$_SERVER['PHP_SELF']."?q=".$GETVars['qq']."&m=".$GETVars['menu']."&sort=".$name."&page=".$page."&so=".$sonew."'"; - $label = $fieldnames[0]['Field']; - $tableheader = $tableheader.""; - } - if ($isAdmin) { - $tableheader = $tableheader.""; - } - $tableheader=$tableheader.""; - return $tableheader; -} - - -/** - * checkLogin - processes login procedure and sets loggedin property in SESSION - * - */ - -function checkLogin() { - - global $configarray; - global $GETVars; - global $conn; - $user = $_SESSION["logindata"]["user"]; - $pass = $_SESSION["logindata"]["pass"]; - $wc = ""; - - $isAdmin = strstr($_SERVER['PHP_SELF'], 'admin.php'); - - if ($user != "" && $pass != "") { - $sql = "SELECT password, role from cfg_users where username='".$user."'"; - $ret = fetchArrayDB($sql, $conn); - - if ($ret[0] != "" && $ret[0]['password'] == md5($pass)) { - $_SESSION["logindata"]["role"] = $ret[0]['role']; - if (!$isAdmin || ($isAdmin && $ret[0]['role'] == "admin")) { - $_SESSION["logindata"]["loggedin"] = TRUE; - } - } else { - $_SESSION["logindata"]["loggedin"] = FALSE; - } - } else { - $_SESSION["logindata"]["loggedin"] = FALSE; - } - -} - - - -/** - * checkAlert - this function checks if a value is above, below or equal a alarm valu - * - * @param string $comperator - * @param string $alertval the value which will trigger an alert - * @param string $val the value that will be checked - * @return boolean - */ - -function checkAlert($comperator = '', $alertval = '', $val = '') { - - $error = false; - - if (substr($val, -1) == "*") { - $val = substr($val,0,-1); - } - if ($comperator == "equal") { - if ($val == $alertval ) { - $error=true; - } - } else if ($comperator == "notequal") { - if ($val != $alertval ) { - $error=true; - } - } else if ($comperator == "less") { - if ($val < $alertval ) { - $error=true; - } - } else if ($comperator == "more") { - if ($val > $alertval ) { - $error=true; - } - } - return $error; - -} - - - - -/** - * getTimestampsOfADay - returns a list of all timestamps of a day which are in the database for the current query - * - * @param string $timestamp a timestamp that s needed to get the current day - * @return string - */ - -function getTimestampsOfADay($timestamp = "") { - - global $GETVars; - global $configarray; - global $conn; - - $server = $GETVars['server']; - $ret = array(); - - $daystring = strftime("%Y-%m-%d", $timestamp); - $startofday = strtotime($daystring." 00:00:00"); - $endofday = strtotime($daystring." 23:59:59"); - - $qtable = $configarray["queryarray"][$GETVars['qq']]["name"]; - - $timestampquery = " WHERE timestamp between ".$startofday." and ".$endofday; - $sql = "SELECT distinct timestamp from res_".$qtable."_".$server.$timestampquery; - $ret = fetchArrayDB($sql, $conn); - - return $ret; - -} - - -/** - * getLastSnapshot - returns the last inserted timestamp of a query result - * - * @return string - */ - -function getLastSnapshot() { - - global $GETVars; - global $configarray; - global $conn; - - $server = $GETVars['server']; - $ret = array(); - - $qtable = $configarray["queryarray"][$GETVars['qq']]["name"]; - - $sql = "SELECT MAX(TimeStamp) from res_".$qtable."_".$server; - $ret = fetchArrayDB($sql, $conn); - $ret = (array)$ret[0]; - - return $ret["MAX(TimeStamp)"]; - -} - - -/** - * getTableFields - * - * @param string tablename - * @return string - */ - -function getTableFields($tablename="") { - - global $GETVars; - global $conn; - - $sqlth = "SELECT * from ".$tablename." LIMIT 1"; - - $sqlresth = fetchArrayDB($sqlth, $conn); - $columnnames = ""; - - echo $sql; - // get all table fields to be selected - foreach ($sqlresth as $row) { - foreach ($row as $colname => $colval) { - if ($colname != "timestamp") { - $columnnames .= "`".$colname."`"; - if ( $i < $numfields-1) $columnnames .= ", "; - } - } - } - $columnnames = ereg_replace(", $", "", $columnnames); - return $columnnames; -} - - -/** - * getAdminTables - gets data out of the DB and generates a HTML result table for admin backend - * - * @param string $type (list, edit, add) - * @return string - */ - -function getAdminTables($type="") { - - global $configarray; - global $conn; - global $GETVars; - - $columnnames = getTableFields("cfg_".$GETVars['qq']); - - if ($GETVars['ob'] != '' ) { - $sqlappend = " order by `".$GETVars['ob']."` ".$GETVars['orderdir']; - } elseif ($configarray["queryarray"][$GETVars['qq']]["orderby"] != '') { - $sqlappend = " order by `".$configarray["queryarray"][$GETVars['qq']]["orderby"]."` ".$GETVars['orderdir']; - } - - if ($type == "edit") { - $wc = " where `id`='".$_GET['id']."' "; - } - - $sql = "SELECT ".$columnnames." from cfg_".$GETVars["qq"].$wc.$sqlappend; - $_SESSION["lastsql"] = $sql; - if ($sqlres) $message = $sql; - - $i = 1; - $rs = fetchArrayDB($sql, $conn); - - foreach ($rs as $row) { - if ($type=="list") { - if ($i % 2 == 0) { - $outp .= ""; - }else{ - $outp .= ""; - } - $i++; - - while(list($keycell, $valcell) = each($row)) { - if ($keycell == "id") { - $id = $valcell; - } else { - $outp .= ""; - } - } - - $baseurl = $_SERVER['PHP_SELF']."?q=".$GETVars['qq']."&m=".$GETVars['menu']; - $outp .= ""; - $outp .= ""; - - $outp .= "\n"; - } else { - $outp = fetchArrayDB($sql, $conn); - var_dump($outp); - } - } - return $outp; -} - - -/** - * execute - gets data out of the DB and generates a HTML result table - * - * @param string $type sets the table type (vertical, standard and graphical time table) - * @return string - */ - -function execute($type = 'table') { - - global $configarray; - global $GETVars; - global $timetablestarttime; - global $whereclause; - global $message; - global $conn; - - $colorsarray = $configarray["colorsarray"]; - $queryarray = $configarray["queryarray"][$GETVars['qq']]; - - $now = time(); - $oneday = 86400; - $onehour = 3600; - $tolerance = 1200; - - $server = $GETVars['server']; - $outp = ''; - $outp_cache = ''; - $stop=FALSE; - $tablearray = array(); - $bContinue = TRUE; - - if ($GETVars['ob'] != '' ) { - $sqlappend = " order by `".$GETVars['ob']."` ".$GETVars['orderdir']; - } elseif ($configarray["queryarray"][$GETVars['qq']]["orderby"] != '') { - $sqlappend = " order by `".$configarray["queryarray"][$GETVars['qq']]["orderby"]."` ".$GETVars['orderdir']; - } - - $qtable = $configarray["queryarray"][$GETVars['qq']]["name"]; - $polltype = $configarray["queryarray"][$GETVars['qq']]["polltype"]; - - if ($polltype == "snapshot") { - if ($_SESSION['timemachine']['time'] == $_SESSION['timemachine']['date']) { - $timestampquery = " WHERE timestamp=(SELECT MAX(TimeStamp) FROM res_".$qtable."_".$server.")"; - } else { - $timestampquery = " WHERE timestamp = '".$_SESSION['timemachine']['time']."'"; - } - } else { - $timestampquery = ""; - } - - // get only latest entry - $searcharr = $_SESSION["search"][$GETVars['qq']]; - if (isset($searcharr) && $searcharr["field"] != "" && $searcharr["val"] != "") { - if ($polltype == "snapshot") { - $wc = " AND "; - } else { - $wc = " WHERE "; - } - $wc .= "`".$searcharr["field"]."`".$searcharr["op"]."'".$searcharr["val"]."' "; - } else if (isset($timetablestarttime)) { - $startunix = ((ceil($now/$onehour)*$onehour)-$onehour-$oneday)-(($timetablestarttime-24)*$onehour); - $endunix = $startunix + $oneday + $onehour; - $start = strftime("%Y-%m-%d %H:%M:%S.000000", $startunix); - $end = strftime("%Y-%m-%d %H:%M:%S.000000", $endunix); - $wc = " WHERE `End Time` >= '".$start."' AND `Start Time` <= '".$end."'"; - } else { - $wc= " "; - } - - $columnnames = getTableFields("res_".$qtable."_".$server); - - if ($columnnames == "") $bContinue = FALSE; - - //execute the constructed query - $sql = "SELECT ".$columnnames." from res_".$qtable."_".$server.$timestampquery.$wc.$sqlappend; - - $_SESSION["lastsql"] = $sql; - if ($sqlres) $message = $sql; - - if ($bContinue) { - if ($type == "table") { - $i = 1; - $rs = fetchSplitArrayDB($sql,$conn,20); - - foreach ($rs as $row) { - $color = ""; - $col = $queryarray["alert_field"]; - if ($col != '') { - $error = checkAlert($queryarray["alert_comp"], $queryarray["alert_val"], $row[$col]); - if($error) { - $color = $queryarray["alert_col"]; - } else { - $color = "ok"; - } - $colorzebra = $colorsarray[$color][$i]; - } - if ($i % 2 == 0) { - $outp = $outp.""; - }else{ - $outp = $outp.""; - } - $i++; - - while(list($keycell, $valcell) = each($row)) { - if($color!="" && $col==$keycell) { - - if ($i % 2 == 0) { - $cellcol = $colorsarray[$color."_light"]; - } else { - $cellcol = $colorsarray[$color."_dark"]; - } - $outp = $outp.""; - } else { - $outp = $outp.""; - } - - } - $outp = $outp."\n"; - } - } - else if ($type == "verticaltable") { - $outp = fetchArrayDB($sql, $conn); - } - else if ($type == "timetable") { - $sqlres = fetchArrayDB($sql, $conn); - $outp = array();; - foreach ($sqlres as $row) { - $rowarray2 = array(); - while(list($keycell, $valcell) = each($row)) { - if ($keycell == "Start Time" || $keycell == "End Time") { - $date = $row[$keycell]; - $rowarray2[] = mktime(substr($date,11,2),substr($date,14,2),substr($date,17,2),substr($date,5,2),substr($date,8,2),substr($date,0,4)); - } else { - $rowarray2[] = $valcell; - } - } - array_push($outp, $rowarray2); - } - } - } - - return $outp; -} - - - - - -/** - * getCustomQuery - executes a custom tsm query directly on the selected TSM server and returns a HTML table - * - * @return string - */ -/** -function getCustomQuery() { - - global $GETVars; - global $configarray; - - $serverarr = $configarray["serverlist"][$GETVars['server']]; - $server = $serverarr["servername"]; - $port = $serverarr["port"]; - $ip = $serverarr["ip"]; - $user = $serverarr["username"]; - $pass = $serverarr["password"]; - - $input = ""; - - $input .= ""; - $input .= ""; - $input .= ""; - $input .= "
"; - - $query = $_POST["querytxt"]; - - if ($query != "") { - - $handle = popen("dsmadmc -se=$server -id=$user -password=$pass -TCPServeraddress=$ip -COMMMethod=TCPIP -TCPPort=$port -dataonly=yes -TAB \"$query\" ", 'r'); - - $colcount = 0; - - if ($handle) { - while (!feof($handle)) { - $i=1; - while (!feof($handle) && !$stop) { - $read = fgets($handle, 4096); - $stop = strstr($read, 'ANR2034E'); - if ($read != ' ' && $read != '' && !$stop) { - $read=preg_replace('/[\n]+/', '', $read); - $cols = split("\t", $read); - if ($i % 2 == 0) { - $outp = $outp.""; - }else{ - $outp = $outp.""; - } - $i++; - $colcount = count($cols); - for ($co = 0; $co < count($cols); $co++) { - $outp = $outp.""; - } - $outp = $outp."\n"; - $outp_cache = $outp; - } - } - } - $outp .= "
".ucfirst($name)." ".$arrow."".$label." ".$arrow."
".$valcell."
".$valcell."".$valcell."
".$cols[$co]."
"; - } - - $header = ""; - for ($count = 0; $count < $colcount; $count++) { - $header .= ""; - } - $header .= ""; - } - - - return $input.$header.$outp; - -} -**/ - - -/** - * getSearchfield - returns the HTML code of the upper searchfield panel - * - * @return string - */ - -function getSearchfield() { - - global $GETVars; - global $configarray; - global $conn; - $ret = ""; - $arrfield = ""; - $arrval = ""; - $arrop = ""; - - $operators = array ("<", "=", "<>", ">"); - - $searcharr = $_SESSION["search"][$GETVars['qq']]; - if (isset($searcharr)) { - $arrfield = $searcharr["field"]; - $arrval = $searcharr["val"]; - $arrop = $searcharr["op"]; - } - $sql = "SHOW COLUMNS FROM res_".$configarray["queryarray"][$GETVars['qq']]["name"]."_".$GETVars['server']; - $fieldnames = fetchArrayDB($sql, $conn); - - // Build Field Name Combobox - $fieldbox = ""; - - // Build Operator Combobox - if ($arrop=="") $arrop="="; - $opbox = ""; - - $link = $_SERVER['PHP_SELF']."?q=".$GETVars['qq']."&m=".$GETVars['menu']."&s=".$GETVars['server']; - $ret .= ""; - $ret .= $fieldbox; - $ret .= $opbox; - $ret .= " "; - $ret .= ""; - $ret .= ""; - $ret .= ""; - - return $ret; - -} - - - -/** - * getServerlist - returns teh HTML code for the server combobox - * - * @return string - */ - -function getServerlist() { - - global $configarray; - global $GETVars; - $ret = ""; - $serverlist = $configarray["serverlist"]; - - $i = 0; - $ret = "
-
"; - $ret .= ""; - while(list($servername,$serveritems) = each($serverlist)) { - $listip = $serveritems["ip"]; - $listdescription = $serveritems["description"]; - $listport = $serveritems["port"]; - if ($i == 0) { - $ret .= ""; - $i = 1; - } else { - $ret .= ""; - $i = 0; - } - $listlink = $_SERVER['PHP_SELF']."?q=".$_SESSION["from"]."&m=".$GETVars['menu']."&s=".$servername; - $ret .= ""; - } - - return $ret."
ServernameDescriptionIP-AddressPort
".$servername."".$listdescription."".$listip."".$listport."
"; - -} - - -/** - * getPollDStat - returns the HTML code for the TSM Polling Daemon status/log table - * - * @return string - */ - -function getPollDStat() { - - global $GETVars; - global $configarray; - global $conn; - - $i=1; - $outp = ""; - $outp .= ""; - - $sql = "SELECT enabled, status, lastrun, nextrun from log_polldstat"; - $sqlres = fetchArrayDB($sql, $conn); - foreach ($sqlres as $row) { - if ($row['enabled'] == "1") { - if ($row['status'] == "running") { - $cellcolor = "green"; - } else if ($row['status'] == "sleeping") { - $cellcolor = "yellow"; - } else { - $cellcolor = "red"; - } - if ($row['nextrun'] != "") $nextrun = strftime("%Y/%m/%d %H:%M:%S", $row['nextrun']); - $status = $row['status']; - } else { - $status = "disabled"; - $cellcolor = "red"; - } - if ($row['lastrun'] != "") $lastrun = strftime("%Y/%m/%d %H:%M:%S", $row['lastrun']); - $outp .= ""; - } - $outp .= "
StatusLast RunNext Run
".$status."".$lastrun."".$nextrun."


"; - - $outp .= ""; - $outp .= ""; - - $sql = "SELECT * from log_polldlog where timestamp > '".(time()-86400)."' order by timestamp desc"; - $_SESSION["lastsql"] = $sql; - $rs = fetchSplitArrayDB($sql,$conn,20); - foreach ($rs as $row) { - if ($i % 2 == 0) { - $outp = $outp.""; - } else { - $outp = $outp.""; - } - $i++; - - while(list($keycell, $valcell) = each($row)) { - if ($keycell == "timestamp") { - $valcell = strftime("%Y/%m/%d %T", $valcell); - } - $outp = $outp.""; - } - $outp = $outp."\n"; - } - $nav = showPageNavigation("20"); - if ($nav!="") { - $outp = $outp.""; - } - - return $outp."
TimeServernameUpdatedUnchangedPollfreq not reachedTime needed (s)
".$valcell."
"; -} - - -/** - * getOverviewRows - returns HTML code for overview page - * - * @param array $subindexqueryarray array of query objects - * @return string - */ - -function getOverviewRows($subindexqueryarray = '') { - - global $GETVars; - global $configarray; - global $conn; - - $out=""; - $i=0; - - while(list($key, $val) = each($subindexqueryarray)) { - - $bgcol=""; - $comperator = ""; - $alertval = ""; - $alertcol = ""; - $cellcolors = $configarray["colorsarray"]; - - $cache = $subindexqueryarray[$key]["cache"]; - if ($configarray["serverlist"][$GETVars['server']]["libraryclient"] == 1 && $subindexqueryarray[$key]["notforlibclient"] == 1) { - $res = "-§§§-"; - } else { - $res = ''; - $sql = "SELECT name, result from res_overview_".$GETVars['server']." where name='".$subindexqueryarray[$key]["name"]."'"; - $sqlres = fetchArrayDB($sql, $conn); - foreach ($sqlres as $row) { - $res .= $row['name']."§§§".$row['result']; - } - } - - if ($i == 1) { - $out = $out."
"; - $i=0; - } else { - $out = $out."
"; - $i=1; - } - $res = split("§§§", $res); - //$out .= $subindexqueryarray[$key]["header"]; - $out .= $res[0]; - $comperator = $subindexqueryarray[$key]["alert_comp"]; - $alertval = $subindexqueryarray[$key]["alert_val"]; - $alertcol = $subindexqueryarray[$key]["alert_col"]; - $unit = $subindexqueryarray[$key]["unit"]; - $error = checkAlert($comperator, $alertval, $res[1]); - if ($i==1) { - $shade="light"; - } else { - $shade="dark"; - } - if ($error && $res != "" && $res[1] != "-") { - $bgcol="bgcolor='".$cellcolors[$alertcol."_".$shade]."'"; - } else { - $bgcol="bgcolor='".$cellcolors["ok_".$shade]."'"; - } - $out .= "".$res[1]." ".$unit."
".$header.""; - for ($count = 0; $count <= 24; $count++) { - $imagename = strftime("%H", $startpunkt+($count*3600)); - $out .= ""; - } - - $out .= "
"; - $out .= ""; - $out .= ""; - $out .= ""; - $out .= "
"; - $out .= generateTimetableNavigation(); - $out .= generateTimetableHeader($startpunkt, $FirstCol); - $out .= ""; - - $lasttimepoint=$now-($timetablestarttime*$onehour)-$tolerance; - - $repeatingcol = ""; - $ii=1; - - while(list($keyrow, $valrow) = each($tablearray)) { - if ($valrow[1] <= $endpunkt && $valrow[2] > $lasttimepoint) { - $name = $valrow[0]; - $status = $valrow[3]; - $statusmsg = ""; - $dur = strftime("%H:%M", ($valrow[2]-$valrow[1])-$onehour); - $shade=""; - if ($valrow[1] < $lasttimepoint) { - // cut the bar at the left side to fit into table - $start = 0; - } else { - $start = ($valrow[1]-$startpunkt)/$faktor; - } - $end = ($valrow[2]-$startpunkt)/$faktor; - $duration = $end - $start; - // fake a longer time for better visibility - if ($duration < 2) {$duration=2;} - // cut the bar at the right side to fit into table - if (($start+$duration)>$lastpoint) { - $duration = $lastpoint-$start; - $shade="light"; - } - if ($valrow[1] < $lasttimepoint) { - $shade="light"; - } - if (isset($status)) { - if ($status == "YES" || $status == "Completed") { - $barcol = $shade."green"; - $statusmsg = ", Status was OK"; - }else{ - $barcol = $shade."red"; - $statusmsg = ", Status was UNSUCCESSFUL"; - } - } else { - $barcol = $shade."grey"; - $statusmsg = ""; - } - - if($ii == 1) { - $out .= ""; - } else { - $out .= ""; - $ii = 0; - } - if ($repeatingcol != $valrow[0]) { - $out .= ""; - $repeatingcol = $valrow[0]; - } else { - $out .= ""; - } - if ($valrow[3] != 'Missed') { - $out .= "\n"; - $ii++; - } - } - $out .= generateTimetableHeader($startpunkt); - $out .= generateTimetableNavigation(); - $out .= "
".$valrow[0]."".$valrow[0].""; - $out .= ""; - $out .= ""; - } else { - $out .= ""; - } - $out .= "
"; - - return $out; - -} - - -/** - * getConfigArray - queries the DB and generates the global config array - * - * @return array - */ - -function getConfigArray() { - - global $conn; - $retArray = array(); - - // Navigation - $query = "SELECT * from cfg_mainmenu"; - $mainmenutablerows = fetchArrayDB($query, $conn); - - $ret = array(); - - $menuarray = array(); - $mainmenuarray = array(); - - while (list ($key, $val) = each ($mainmenutablerows)) { - $menuname = $val['name']; - $menulabel = $val['label']; - $url = "q=overview&m=".$menuname; - $mainmenuarray[$url] = $menulabel; - } - - $menuarrayxml = $queryconfigarray["navigation"]["mainmenuitem"]; - $mainmenuarrayxml = $menuarrayxml; - $mainmenuarray["trennlinie"] = "trennlinie"; - $mainmenuarray["q=polldstat&m=main"] = "Polling Daemon Log"; - $mainmenuarray["q=serverlist&m=main"] = "Change Server"; - if ($_SESSION["logindata"]["role"] == "admin") $mainmenuarray["admin"] = "Admin"; - $mainmenuarray["q=logout"] = "Logout"; - $menuarray["main"] = $mainmenuarray; - - $query = "SELECT * from cfg_mainmenu"; - $mainmenutablerows = fetchArrayDB($query, $conn); - $query = "SELECT * from cfg_queries"; - $querytablerows = fetchArrayDB($query, $conn); - - - while (list ($key, $val) = each ($mainmenutablerows)) { - $menuname = $val['name']; - $menulabel = $val['label']; - $submenuarray = array(); - $submenuarray[""] = "<---"; - $query = "SELECT * from cfg_queries where parent='".$menuname."'"; - $querytablerows = fetchArrayDB($query, $conn); - while (list ($subkey, $submenuitem) = each ($querytablerows)) { - $submenuitem_name = $submenuitem['name']; - $submenuitem_label = $submenuitem['label']; - $url = "q=".$submenuitem_name."&m=".$menuname; - $submenuarray[$url] = $submenuitem_label; - } - $submenuarray["trennlinie"] = "trennlinie"; - $submenuarray["q=polldstat&m=".$submenu['name']] = "Polling Daemon Log"; - $submenuarray["q=serverlist&m=".$submenu['name']] = "Change Server"; - if ($_SESSION["logindata"]["role"] == "admin") $submenuarray["admin"] = "Admin"; - $submenuarray["q=logout"] = "Logout"; - $menuarray[$menuname] = $submenuarray; - } - - $retArray["menuarray"] = $menuarray; - - // Admin Backend Menu - $adminmenuarray = array(); - $adminmenuarray["q=config&m=main"] = "General"; - $adminmenuarray["q=users&m=main"] = "Users"; - $adminmenuarray["q=groups&m=main"] = "Groups"; - $adminmenuarray["q=servers&m=main"] = "Servers"; - $adminmenuarray["q=mainmenu&m=main"] = "Mainmenu"; - $adminmenuarray["q=queries&m=main"] = "Queries"; - $adminmenuarray["trennlinie"] = "trennlinie"; - $adminmenuarray["q=settings&m=main"] = "Settings"; - $adminmenuarray["trennlinie2"] = "trennlinie"; - $adminmenuarray["tsmmonitor"] = "TSM Monitor"; - $adminmenuarray["q=logout"] = "Logout"; - $retArray["adminmenuarray"] = $adminmenuarray; - - // Overview Boxes - $ret = array(); - - $query = "SELECT * from cfg_overviewboxes order by sortorder asc"; - $queryoverviewboxes = fetchArrayDB($query, $conn); - while (list ($subkey, $box) = each ($queryoverviewboxes)) { - $query = "SELECT * from cfg_overviewqueries where parent='".$box['name']."' order by sortorder asc"; - $queryoverview = fetchArrayDB($query, $conn); - $temp = array (); - //print_r($queryoverview); - while (list ($subkey, $ovquery) = each ($queryoverview)) { - $ovquery['header'] = $queryoverview['name']; - $temp[] = (array)$ovquery; - } - $ret[$box['name']] = $temp; - } - $retArray["infoboxarray"] = $ret; - - // Queries - $dbret = array(); - $query = "SELECT * from cfg_queries"; - $querytablerows = fetchArrayDB($query, $conn); - while (list ($subkey, $queryrow) = each ($querytablerows)) { - $dbret[$queryrow['name']] = (array)$queryrow; - } - $retArray["queryarray"] = $dbret; - - // General settings - $query = "SELECT * from cfg_config"; - $rows = fetchArrayDB($query, $conn); - $ret = array(); - foreach ($rows as $key => $val) { - $ret[$val['confkey']] = $val['confval']; - } - $retArray["settings"] = $ret; - - // Set Stylesheet - $query = "SELECT stylesheet from cfg_users where username='".$_SESSION["logindata"]["user"]."'"; - $row = fetchArrayDB($query, $conn); - $retArray["stylesheet"] = $row[0]['stylesheet']; - - // Colors - $query = "SELECT * from cfg_colors"; - $rows = fetchArrayDB($query, $conn); - - $ret = array(); - while (list ($key, $val) = each ($rows)) { - $ret[$val['name']] = $val['value']; - } - $retArray["colorsarray"] = $ret; - - // Servers - $query = "SELECT * from cfg_servers"; - $rows = fetchArrayDB($query, $conn); - - $ret = array(); - while (list ($key, $val) = each ($rows)) { - $ret[$val['servername']] = (array)$val; - if ($val['default'] == 1) { - $retArray["defaultserver"] = $val['servername']; - } - } - - $retArray["serverlist"] = $ret; - return $retArray; -} - - -/** - * findPath - find a external program in the search path - * - * @param string $binary the external program to search for - * @param string $search_path the search path in which to look for the external program - * @return string the full path to the external program or empty string if not found - */ -function findPath($binary, $search_path) { - foreach ($search_path as $path) { - if ((file_exists($path . "/" . $binary)) && (is_readable($path . "/" . $binary))) { - return($path . "/" . $binary); - } - } -} - - -/** - * connectDB - establish a DB connection via ADODB - * - * @param string $host the hostname of the DB server - * @param string $port the portnumber for the DB connection - * @param string $user the username for the DB connection - * @param string $pass the password for the DB connection - * @param string $db_name the name of the DB - * @param string $db_type the type of the DB (currently only 'mysql') - * @param string $retr the number attempts for the DB connection before a failure is reported - * @return ADOConnection DB connection ID or error code if connection failed - */ -function connectDB($host, $port = "3306", $user, $pass, $db_name, $db_type, $retr = 20) { - $try = 0; - $hostport = $host . ":" . $port; - $conn = NewADOConnection($db_type); - - while ($try <= $retries) { - if ($conn->PConnect($hostport,$user,$pass,$db_name)) { - return($conn); - } - $try++; - usleep(50000); - } - - die("FATAL: Cannot connect to database server on '$host':'$port'. Please make sure you have specified a valid database name in 'includes/config.php'\n"); - return 0; -} - - -/** - * closeDB - close an open DB connection - * - * @param ADOConnection $DBconn DB connection ID to be closed - * @return string - */ -function closeDB($DBconn = FALSE) { - if ($DBconn) { - return $DBconn->Close(); - } -} - - -/** - * execDB - execute a SQL statement against the DB via ADODB - * - * @param string $sql SQL statement to execute - * @param ADOConnection $DBconn DB connection ID to run the SQL against - * @return ADORecordSet - */ -function execDB($sql, $DBconn = FALSE) { -// $DBconn->debug = true; - $sql = sanitizeSQL($sql); - - $recordSet = &$DBconn->Execute($sql); - if (($recordSet) || ($DBconn->ErrorNo() == 0)) { - return($recordSet); - } else { - echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; - exit; - } -} - - -/** - * fetchCellDB - execute a SQL query against the DB via ADODB and - * return only the first column of the fist row found - * or a specified column of the fist row found - * - * @param string $sql SQL statement to execute - * @param $column_name Column name to use instead of the first column - * @param ADOConnection $DBconn DB connection ID to run the SQL against - * @return string Content of the cell as a single variable - */ -function fetchCellDB($sql, $column_name, $DBconn = FALSE) { -// $DBconn->debug = true; - $sql = sanitizeSQL($sql); - - if ($column_name != '') { - $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); - } else { - $DBconn->SetFetchMode(ADODB_FETCH_NUM); - } - $recordSet = $DBconn->Execute($sql); - - if (($recordSet) || ($DBconn->ErrorNo() == 0)) { - if (!$recordSet->EOF) { - if ($column_name != '') { - $column = $recordSet->fields[$column_name]; - }else{ - $column = $recordSet->fields[0]; - } - $recordSet->close(); - - return($column); - } - } else { - echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; - exit; - } -} - - -/** - * fetchRowDB - execute a SQL query against the DB via ADODB - * and return only the first row found - * - * @param string $sql SQL statement to execute - * @param ADOConnection $DBconn DB connection ID to run the SQL against - * @return array First row of results as an associative array - */ -function fetchRowDB($sql, $DBconn = FALSE) { -// $DBconn->debug = true; - $sql = sanitizeSQL($sql); - - $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); - $recordSet = $DBconn->Execute($sql); - - if (($recordSet) || ($DBconn->ErrorNo() == 0)) { - if (!$recordSet->EOF) { - $recordFields = $recordSet->fields; - $recordSet->close(); - - return($recordFields); - } - } else { - echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; - exit; - } -} - - -/** - * fetchArrayDB - execute a SQL query against the DB via ADODB - * and return results in an associative array. - * - * @param string $sql SQL statement to execute - * @param ADOConnection $DBconn DB connection ID to run the SQL against - * @return array All results in an associative array - */ -function fetchArrayDB($sql, $DBconn = FALSE) { -// $DBconn->debug = true; - $sql = sanitizeSQL($sql); - - $recordArray = array(); - $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); - $recordSet = &$DBconn->Execute($sql); - - if (($recordSet) || ($DBconn->ErrorNo() == 0)) { - while ((!$recordSet->EOF) && ($recordSet)) { - $recordArray{sizeof($recordArray)} = $recordSet->fields; - $recordSet->MoveNext(); - } - $recordSet->close(); - return($recordArray); - } else { - echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; - exit; - } -} - - -/** - * fetchSplitArrayDB - execute a SQL query against the DB via ADODB - * and return results in an associative array. - * - * @param string $sql SQL statement to execute - * @param ADOConnection $DBconn DB connection ID to run the SQL against - * @param string $rows_per_page number of rows per page a result will have - * @return array All results in an associative array - */ -function fetchSplitArrayDB($sql, $DBconn = FALSE, $rows_per_page = '20') { -// $DBconn->debug = true; - global $max_pages; - $page = intval($_GET['page']); - - $sql = sanitizeSQL($sql); - - $recordArray = array(); - $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); - $recordSet = &$DBconn->Execute($sql); - - if (($recordSet) || ($DBconn->ErrorNo() == 0)) { - $total_rows = $recordSet->RecordCount($recordSet); - $max_pages = ceil($total_rows/$rows_per_page); - - if($page > $max_pages || $page <= 0) { - $page = 1; - } - $offset = $rows_per_page * ($page-1); - $endset = $offset + $rows_per_page; - $recordSet->Move($offset); - - while (($recordSet->CurrentRow() < $endset) && ($recordSet->CurrentRow() < $total_rows) && ($recordSet)) { - $recordArray{sizeof($recordArray)} = $recordSet->fields; - $recordSet->MoveNext(); - } - $recordSet->close(); - return($recordArray); - } else { - echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; - exit; - } -} - - -/** - * updateDB - execute a SQL update statement against the DB via ADODB - * to update a record. If the record is not found, an insert - * statement is generated and executed. - * - * @param string $table The name of the table containing the record to be updated - * @param array $cells An array of columnname/value pairs of the record to be updated - * @param string $keys Name of the primary key - * @param boolean $autoquote Use intelligent auto-quoting - * @param ADOConnection $DBconn DB connection ID to run the SQL against - * @return string Auto-increment ID if insert was performed - */ -function updateDB($table, $cells, $keys, $DBconn = FALSE, $autoquote = TRUE) { - //$DBconn->debug = true; - $DBconn->Replace($table, $cells, $keys, $autoquote); - - return $DBconn->Insert_ID(); -} - - -/** - * sanitizeSQL - removes unwanted chars in values passed for use in - * SQL statements - * - * @param string $sql SQL expression to sanitize - * @return string - */ -function sanitizeSQL($sql) { - $sql = str_replace(";", "\;", $sql); - $sql = str_replace("\n", "", $sql); - $sql = str_replace("\r", "", $sql); - $sql = str_replace("\t", " ", $sql); - return $sql; -} - -?> diff --git a/includes/global.php b/includes/global.php index f0aeca2..fa333c2 100644 --- a/includes/global.php +++ b/includes/global.php @@ -84,20 +84,26 @@ header("Pragma: no-cache"); // ** Include generic code and external libraries ** // include ($config["library_path"] . "/adodb5/adodb.inc.php"); -include_once($config["include_path"] . "/functions.php"); +//include_once($config["include_path"] . "/functions.php"); +include_once($config["include_path"] . "/tsmmonitor.php"); include_once($config["include_path"] . "/polld.php"); +// ** instantiate TSMMonitor Class ** // +$tsmmonitor = new TSMMonitor(); + // ** Connect to the database ** // -$conn = connectDB($db_host, $db_port, $db_user, $db_password, $db_name, $db_type); +//$conn = connectDB($db_host, $db_port, $db_user, $db_password, $db_name, $db_type); +$tsmmonitor->conn = $tsmmonitor->connectDB($db_host, $db_port, $db_user, $db_password, $db_name, $db_type); // check to see if this is a new installation -$version = fetchCellDB("select confval from cfg_config where confkey='version'", '', $conn); +$version = $tsmmonitor->fetchCellDB("select confval from cfg_config where confkey='version'", '', $tsmmonitor->conn); if ($version != $config["tsm_monitor_version"] && basename($_SERVER['REQUEST_URI']) != 'install.php') { header("Location: install.php"); exit; } // ** Initialize PHP session ** // -initialize(); +//initialize(); +$tsmmonitor->initialize(); // ** Include generic code and external libraries ** // // ... more includes here diff --git a/includes/overview.php b/includes/overview.php index 8004457..8d6d283 100644 --- a/includes/overview.php +++ b/includes/overview.php @@ -39,7 +39,7 @@ - +getOverviewRows($tsmmonitor->configarray["infoboxarray"]["healthdata"]); ?>
Health Status
@@ -48,7 +48,7 @@ - +getOverviewRows($tsmmonitor->configarray["infoboxarray"]["database"]); ?>
TSM Database
@@ -58,7 +58,7 @@ - +getOverviewRows($tsmmonitor->configarray["infoboxarray"]["totaldata"]); ?>
Total Data
@@ -67,7 +67,7 @@ - +getOverviewRows($tsmmonitor->configarray["infoboxarray"]["schedules"]); ?>
Schedule Status
diff --git a/includes/pdf.php b/includes/pdf.php index ffcb227..6953afb 100644 --- a/includes/pdf.php +++ b/includes/pdf.php @@ -160,16 +160,16 @@ function AddCol($field=-1,$width=-1,$caption='',$align='L') * @param array $prop */ -function Table($query,$prop=array(),$DBconn) +function Table($query,$prop=array(),$dbresult) { //Issue query - $res=fetchArrayDB($query, $DBconn); + //$res=fetchArrayDB($query, $DBconn); //Add all columns if none was specified if(count($this->aCols)==0) { - foreach($res[0] as $colname => $col) { + foreach($dbresult[0] as $colname => $col) { $this->AddCol(-1,-1,ucfirst($colname)); - } + } } //Handle properties @@ -199,7 +199,7 @@ function Table($query,$prop=array(),$DBconn) $this->SetFont('Arial','',6); $this->ColorIndex=0; $this->ProcessingTable=true; - foreach($res as $key => $row) { + foreach($dbresult as $key => $row) { $row_num = array_values($row); $row_comb = array_merge($row, $row_num); $this->Row($row_comb); @@ -247,7 +247,6 @@ class PDF extends PDF_MySQL_Table } } - $pdf=new PDF(); $pdf->Open(); $pdf->AddPage(); @@ -257,7 +256,9 @@ $prop=array('HeaderColor'=>array(180,180,180), 'color2'=>array(230,230,230), 'padding'=>2); //$pdf->Table('select * from res_'.$_SESSION["GETVars"]["qq"].'_'.$_SESSION["GETVars"]["server"],$prop); -$pdf->Table($_SESSION["lastsql"],$prop,$conn); +$res = $tsmmonitor->fetchArrayDB($_SESSION["lastsql"], $tsmmonitor->conn); +//var_dump($res); +$pdf->Table($_SESSION["lastsql"],$prop,$res); $pdf->Output(); ?> diff --git a/includes/polld.php b/includes/polld.php index 9e61173..09dec67 100644 --- a/includes/polld.php +++ b/includes/polld.php @@ -85,6 +85,7 @@ function setDBParams($db_host, $db_name, $db_user, $db_password){ function initialize() { + $this->setDBParams("localhost", "tsmmonitor", "tsmmonitor", "tsmmonitor"); $this->servers = $this->getServers(); $this->queries = $this->getQueries(); $this->overviewqueries = $this->getOverviewQueries(); diff --git a/includes/topnav.php b/includes/topnav.php index cf6050e..d74c1b4 100644 --- a/includes/topnav.php +++ b/includes/topnav.php @@ -31,19 +31,19 @@ ?> -
+ GETVars['qq'] != "admin" && !$_POST["edit"] == "edit") { +if ($tsmmonitor->GETVars['qq'] != "index" && $tsmmonitor->GETVars['qq'] != "overview" && $tsmmonitor->GETVars['qq'] != "serverlist") { echo ""; } -if ($GETVars['qq'] != "polldstat" && $GETVars['qq'] != "serverlist") { +if ($tsmmonitor->GETVars['qq'] != "polldstat" && $tsmmonitor->GETVars['qq'] != "serverlist") { echo ""; diff --git a/includes/tsmmonitor.php b/includes/tsmmonitor.php new file mode 100644 index 0000000..fa9f9fc --- /dev/null +++ b/includes/tsmmonitor.php @@ -0,0 +1,1620 @@ +. + +************************************************************************ +*/ + +/** + * + * tsmmonitor.php, TSM Monitor + * + * TSM Monitor main class + * + * @author Michael Clemens + * @package tsmmonitor + */ + + +/** + * + * Class + * + */ + +class TSMMonitor { + + + var $configarray; + var $queryarray; + var $GETVars; + var $page; + var $max_pages; + var $timetablestarttime; + + var $submenu; + var $adminmenu; + var $message; + var $conn; + + + + + /** + * initialize - This function us called every time index.php is refreshed + * + */ + + function initialize() { + + + session_name("tsmmonitordev"); + session_start(); + + + // Login if not logged in and credentials are ok + if ((isset($_POST) && isset($_POST["loginname"]) && isset($_POST["loginpasswort"]) && (!isset($_SESSION["logindata"])))) { + $_SESSION["logindata"]["user"] = $_POST["loginname"]; + $_SESSION["logindata"]["pass"] = $_POST["loginpasswort"]; + $this->checkLogin(); + } + + if ($_GET['q'] == "logout") { + unset($_SESSION["logindata"]); + } + + $_SESSION['configarray'] = $this->getConfigArray(); + + // GET-variables + $this->GETVars["menu"] = $_GET['m']; + $this->GETVars["qq"] = $_GET['q']; + $this->GETVars['ob'] = $_GET['sort']; + $this->GETVars['orderdir'] = $_GET['so']; + + if ($_POST['s'] != '') { + $this->GETVars['server'] = $_POST['s']; + } else { + $this->GETVars['server'] = $_GET['s']; + } + + + // Session-variables + $this->configarray = $_SESSION['configarray']; + + // timeout + if( !ini_get('safe_mode') && ini_get('max_execution_time') != $this->configarray["settings"]["timeout"]) { + ini_set('max_execution_time', $this->configarray["settings"]["timeout"]); + } + + // set defaults if vars are empty + if ($this->GETVars["menu"] == "") { $this->GETVars["menu"]="main"; } + if ($this->GETVars["qq"] == "") { $this->GETVars["qq"]="index"; } + if ($this->GETVars['server'] == "") { $this->GETVars['server']=$this->configarray["defaultserver"]; } + if ($this->GETVars['orderdir'] == "") { $this->GETVars['orderdir'] = "asc"; } + + if ($_SESSION['timeshift'] == '' || !strstr($this->GETVars["qq"], 'dynamictimetable')) { + $_SESSION['timeshift'] = 0 ; + } + + $this->submenu = $this->configarray["menuarray"][$this->GETVars['menu']]; + $this->adminmenu = $this->configarray["adminmenuarray"]; + //$query = $this->configarray["queryarray"][$this->GETVars['qq']]["tsmquery"]; + $this->queryarray = $this->configarray["queryarray"]; + + $_SESSION["GETVars"] = $this->GETVars; + + + // BEGIN Timemachine + if ($_SESSION["from"] != $_GET['q']) { + $_SESSION['timemachine'] = ""; + } + + if ($_POST['dateinput'] != "") $_SESSION['timemachine']['date'] = strtotime($_POST['dateinput']); + if ($_POST['timestamps'] != "") $_SESSION['timemachine']['time'] = $_POST['timestamps']; + + + if ($_POST["Poll"] == "Poll Now!") { + $timestamp = time(); + $tmonpolld = new PollD(); + //$tmonpolld->setDBParams($this->db_host, $this->db_name, $this->db_user, $this>db_password); + $tmonpolld->initialize(); + $tmonpolld->pollQuery($tmonpolld->queries[$this->GETVars['qq']], $tmonpolld->servers[$this->GETVars['server']], TRUE, $timestamp); + $_SESSION['timemachine']['date'] = $timestamp; + $_SESSION['timemachine']['time'] = $timestamp; + } + + + if (($_POST['Poll'] == "Poll Now!" || $_SESSION['timemachine']['date'] == "") && $this->queryarray[$this->GETVars['qq']]["polltype"]=="snapshot" || $_POST['s'] != "" && $this->GETVars['qq'] != "overview" && $this->GETVars['qq'] != "index") { + $qtable = $this->configarray["queryarray"][$this->GETVars['qq']]["name"]; + $sql = "SELECT MAX(TimeStamp) FROM res_".$qtable."_".$this->GETVars["server"]; + $res = $this->fetchArrayDB($sql, $this->conn); + $resarr = (array)$res[0]; + $_SESSION['timemachine']['date'] = $resarr["MAX(TimeStamp)"]; + $_SESSION['timemachine']['time'] = $resarr["MAX(TimeStamp)"]; + } + + + // Custom Stylesheet + if ($_SESSION['stylesheet'] == "") { + if ($this->configarray['stylesheet'] != "") { + $_SESSION['stylesheet'] = $this->configarray['stylesheet']; + } else { + $_SESSION['stylesheet'] = "default.css"; + } + } + + } + + + + + /** + * showPageNavigation - generates a clickable navigation bar for sql results + * splitted by function fetchSplitArrayDB + * + * @param string links_per_page number of links that will be displayed per page + * @return string + */ + + function showPageNavigation($links_per_page = "1") { + + $this->page = intval($_GET['page']); + if ($this->page == "") $this->page = 1; + $so = $_GET['so']; + $sortcol = $_GET['sort']; + + $getvars = 'q='.$_GET['q'].'&m='.$_GET['m'].'&s='.$this->GETVars['server'].'&sort='.$sortcol."&so=".$so; + $self = htmlspecialchars($_SERVER['PHP_SELF']); + $navelement = 'page != 1) { + //$fp = ''.$fp.''; + $fp = $navelement.'1">'.$fp.''; + } + + if($this->page != $this->max_pages) { + $lp = $navelement.($this->max_pages).'">'.$lp.''; + } + + if($this->page > 1) { + $pp = $navelement.($this->page-1).'">'.$pp.''; + } + + if($this->page < $this->max_pages) { + $np = $navelement.($this->page+1).'">'.$np.''; + } + + // Numbers + for($i=1;$i<=$this->max_pages;$i+=$links_per_page) { + if($this->page >= $i) { + $start = $i; + } + } + + if($this->max_pages > $links_per_page) { + $end = $start+$links_per_page; + if($end > $this->max_pages) $end = $this->max_pages+1; + } + else { + $end = $this->max_pages; + } + + $numbers = ''; + + for( $i=$start ; $i<=$end ; $i++) { + if($i == $this->page ) { + $numbers .= " $i "; + } + else { + $numbers .= ' '.$navelement.$i.'">'.$i.' '; + } + } + if ($end > 1) { + return $fp.' '.$pp.' '.$numbers.' '.$np.' '.$lp; + } else { + return ""; + } + + } + + + + /** + * GetBetween - little helper function that returns a string between two given strings + * + * @param string $content complete string + * @param string $start first string + * @param string $end second string + * @return string + */ + + function GetBetween($content,$start,$end) { + $r = explode($start, $content); + if (isset($r[1])) { + $r = explode($end, $r[1]); + return $r[0]; + } + return ''; + } + + + + + /** + * GetTimemachine - generates a date-/timechooser with which one can select a specific snapshot + * + * @return string + */ + + function GetTimemachine() { + + $this->queryarray = $this->configarray["queryarray"]; + + $ret = ""; + + if ($this->queryarray[$this->GETVars['qq']]["polltype"]=="snapshot") { + $ret .= "
Time Machine

"; + $ret .= ""; + $ret .= ""; + $ret .= "
"; + $ret .= ""; + $ret .= "
"; + $ret .= "
"; + $ret .= ""; + $ret .= "

"; + + } else if ($this->queryarray[$this->GETVars['qq']]["polltype"]=="update" || $this->queryarray[$this->GETVars['qq']]["polltype"]=="append") { + $LastTimestamp = $this->GetLastSnapshot(); + if ($LastTimestamp!="") { + $ret .= "
Time Machine

"; + $ret .= "
"; + $ret .= "Last updated: ".strftime('%H:%M:%S', $LastTimestamp); + $ret .= "
"; + $ret .= "
"; + $ret .= ""; + $ret .= "

"; + } + + } + + return $ret; + + } + + + + + /** + * getMenu - resturns HTML code for sidebar menu + * + * @param string $menu currently displayed menu + * @param string $activelink link that will be marked as selected + * @param string $type index or admin + * @return string + */ + + function getMenu($menu = '', $activelink = '', $type) { + + if (!isset($menu)) { return ""; }; + while(list($key, $val) = each($menu)) { + + $bCont = TRUE; + $q = $this->GetBetween($key,"q=","&m="); + if ($this->configarray["queryarray"][$q]["notforlibclient"] == 1 && $this->configarray["serverlist"][$this->GETVars['server']]["libraryclient"] == 1) { + $bCont = FALSE; + + } + $key = $_SERVER['PHP_SELF']."?".$key; + + if ($type == "index") { + $key .= "&s=".$this->GETVars['server']; + } + + if ($val == "Admin") { + $key = "admin.php"; + }else if ($val == "TSM Monitor") { + $key = "index.php"; + } + + if ($val == "trennlinie") { + $links .= "
\n"; + } else if ($bCont) { + + if (!stristr($key,$activelink)) { + $links .= "$val\n"; + } else { + $links .= "
$val
\n"; + } + } + } + return $links; + } + + + + /** + * getMessage - returns HTML code for global system message + * + * @return string + */ + + function getMessage() { + + return "
System Message:

".$this->message."
"; + } + + + + + /** + * getInfo - returns HTML Code for Infoboxes with information about current query + * + * @return string + */ + + function getInfo() { + + $label = $this->configarray["queryarray"][$this->GETVars['qq']]["label"]; + $info = $this->configarray["queryarray"][$this->GETVars['qq']]["info"]; + + if ($info != "") { + $ret = "
".$label.":

".$info; + $ret .= "
"; + return $ret; + } + } + + + + + + /** + * getTableheader - generates and returns headers for query result HTML tables. + * + * @return string + */ + + function getTableheader() { + + $tableheader=""; + $orderby = $this->configarray["queryarray"][$this->GETVars['qq']]["orderby"]; + $orderdir = $this->GETVars['orderdir']; + $this->page = $_GET['page']; + + if ($orderdir == "asc") { + $sonew="desc"; + } else if ($orderdir == "desc") { + $sonew="asc"; + } + + $isAdmin = strstr($_SERVER['PHP_SELF'], 'admin.php'); + + if ($isAdmin) { + $sql = "SHOW COLUMNS FROM cfg_".$_GET['q']; + } else { + $sql = "SHOW COLUMNS FROM res_".$this->configarray["queryarray"][$this->GETVars['qq']]["name"]."_".$this->GETVars['server']; + } + $fieldnames = $this->fetchArrayDB($sql, $this->conn); + + // If table has more than one column + if (sizeof($fieldnames) > 1) { + foreach ($fieldnames as $col) { + if ($col['Field'] != "timestamp" && $col['Field'] != "id") { + $name = $col['Field']; + $arrow = ""; + if (($this->GETVars['ob'] == $name && $this->GETVars['ob']!="") || ($this->GETVars['ob']=="" && $orderby!="" && $orderby == $name)) { + $link = "href='".$_SERVER['PHP_SELF']."?q=".$this->GETVars['qq']."&m=".$this->GETVars['menu']."&sort=".$name."&page=".$this->page."&so=".$sonew."&s=".$this->GETVars['server']."'"; + if ($orderdir == "asc") { + $arrow = "⇑"; + } else if ($orderdir == "desc") { + $arrow = "⇓"; + } + } else { + $arrow = ""; + $link = "href='".$_SERVER['PHP_SELF']."?q=".$this->GETVars['qq']."&m=".$this->GETVars['menu']."&sort=".$name."&page=".$this->page."&s=".$this->GETVars['server']."'"; + } + $tableheader = $tableheader."".ucfirst($name)." ".$arrow.""; + } + } + } else { + if ($orderdir == "asc") { + $arrow = "⇑"; + } else if ($orderdir == "desc") { + $arrow = "⇓"; + } + $link = "href='".$_SERVER['PHP_SELF']."?q=".$this->GETVars['qq']."&m=".$this->GETVars['menu']."&sort=".$name."&page=".$this->page."&so=".$sonew."'"; + $label = $fieldnames[0]['Field']; + $tableheader = $tableheader."".$label." ".$arrow.""; + } + if ($isAdmin) { + $tableheader = $tableheader.""; + } + $tableheader=$tableheader.""; + return $tableheader; + } + + + /** + * checkLogin - processes login procedure and sets loggedin property in SESSION + * + */ + + function checkLogin() { + + $user = $_SESSION["logindata"]["user"]; + $pass = $_SESSION["logindata"]["pass"]; + $wc = ""; + + $isAdmin = strstr($_SERVER['PHP_SELF'], 'admin.php'); + + if ($user != "" && $pass != "") { + $sql = "SELECT password, role from cfg_users where username='".$user."'"; + $ret = $this->fetchArrayDB($sql, $this->conn); + + if ($ret[0] != "" && $ret[0]['password'] == md5($pass)) { + $_SESSION["logindata"]["role"] = $ret[0]['role']; + if (!$isAdmin || ($isAdmin && $ret[0]['role'] == "admin")) { + $_SESSION["logindata"]["loggedin"] = TRUE; + } + } else { + $_SESSION["logindata"]["loggedin"] = FALSE; + } + } else { + $_SESSION["logindata"]["loggedin"] = FALSE; + } + + } + + + + /** + * checkAlert - this function checks if a value is above, below or equal a alarm valu + * + * @param string $comperator + * @param string $alertval the value which will trigger an alert + * @param string $val the value that will be checked + * @return boolean + */ + + function checkAlert($comperator = '', $alertval = '', $val = '') { + + $error = false; + + if (substr($val, -1) == "*") { + $val = substr($val,0,-1); + } + if ($comperator == "equal") { + if ($val == $alertval ) { + $error=true; + } + } else if ($comperator == "notequal") { + if ($val != $alertval ) { + $error=true; + } + } else if ($comperator == "less") { + if ($val < $alertval ) { + $error=true; + } + } else if ($comperator == "more") { + if ($val > $alertval ) { + $error=true; + } + } + return $error; + + } + + + + + /** + * getTimestampsOfADay - returns a list of all timestamps of a day which are in the database for the current query + * + * @param string $timestamp a timestamp that s needed to get the current day + * @return string + */ + + function getTimestampsOfADay($timestamp = "") { + + $server = $this->GETVars['server']; + $ret = array(); + + $daystring = strftime("%Y-%m-%d", $timestamp); + $startofday = strtotime($daystring." 00:00:00"); + $endofday = strtotime($daystring." 23:59:59"); + + $qtable = $this->configarray["queryarray"][$this->GETVars['qq']]["name"]; + + $timestampquery = " WHERE timestamp between ".$startofday." and ".$endofday; + $sql = "SELECT distinct timestamp from res_".$qtable."_".$server.$timestampquery; + $ret = $this->fetchArrayDB($sql, $this->conn); + + return $ret; + + } + + + /** + * getLastSnapshot - returns the last inserted timestamp of a query result + * + * @return string + */ + + function getLastSnapshot() { + + $server = $this->GETVars['server']; + $ret = array(); + + $qtable = $this->configarray["queryarray"][$this->GETVars['qq']]["name"]; + + $sql = "SELECT MAX(TimeStamp) from res_".$qtable."_".$server; + $ret = $this->fetchArrayDB($sql, $this->conn); + $ret = (array)$ret[0]; + + return $ret["MAX(TimeStamp)"]; + + } + + + /** + * $this->getTableFields + * + * @param string tablename + * @return string + */ + + function getTableFields($tablename="") { + + $sqlth = "SELECT * from ".$tablename." LIMIT 1"; + + $sqlresth = $this->fetchArrayDB($sqlth, $this->conn); + $columnnames = ""; + + // get all table fields to be selected + foreach ($sqlresth as $row) { + foreach ($row as $colname => $colval) { + if ($colname != "timestamp") { + $columnnames .= "`".$colname."`"; + if ( $i < $numfields-1) $columnnames .= ", "; + } + } + } + $columnnames = ereg_replace(", $", "", $columnnames); + return $columnnames; + } + + + /** + * getAdminTables - gets data out of the DB and generates a HTML result table for admin backend + * + * @param string $type (list, edit, add) + * @return string + */ + + function getAdminTables($type="") { + + $columnnames = $this->getTableFields("cfg_".$this->GETVars['qq']); + + if ($this->GETVars['ob'] != '' ) { + $sqlappend = " order by `".$this->GETVars['ob']."` ".$this->GETVars['orderdir']; + } elseif ($this->configarray["queryarray"][$this->GETVars['qq']]["orderby"] != '') { + $sqlappend = " order by `".$this->configarray["queryarray"][$this->GETVars['qq']]["orderby"]."` ".$this->GETVars['orderdir']; + } + + if ($type == "edit") { + $wc = " where `id`='".$_GET['id']."' "; + } + + $sql = "SELECT ".$columnnames." from cfg_".$this->GETVars["qq"].$wc.$sqlappend; + $_SESSION["lastsql"] = $sql; + if ($sqlres) $this->message = $sql; + + $i = 1; + $rs = $this->fetchArrayDB($sql, $this->conn); + + foreach ($rs as $row) { + if ($type=="list") { + if ($i % 2 == 0) { + $outp .= ""; + }else{ + $outp .= ""; + } + $i++; + + while(list($keycell, $valcell) = each($row)) { + if ($keycell == "id") { + $id = $valcell; + } else { + $outp .= "".$valcell.""; + } + } + + $baseurl = $_SERVER['PHP_SELF']."?q=".$this->GETVars['qq']."&m=".$this->GETVars['menu']; + $outp .= ""; + $outp .= ""; + + $outp .= "\n"; + } else { + $outp = $this->fetchArrayDB($sql, $this->conn); + var_dump($outp); + } + } + return $outp; + } + + + /** + * execute - gets data out of the DB and generates a HTML result table + * + * @param string $type sets the table type (vertical, standard and graphical time table) + * @return string + */ + + function execute($type = 'table') { + + $colorsarray = $this->configarray["colorsarray"]; + $this->queryarray = $this->configarray["queryarray"][$this->GETVars['qq']]; + + $now = time(); + $oneday = 86400; + $onehour = 3600; + $tolerance = 1200; + + $server = $this->GETVars['server']; + $outp = ''; + $outp_cache = ''; + $stop=FALSE; + $tablearray = array(); + $bContinue = TRUE; + + if ($this->GETVars['ob'] != '' ) { + $sqlappend = " order by `".$this->GETVars['ob']."` ".$this->GETVars['orderdir']; + } elseif ($this->configarray["queryarray"][$this->GETVars['qq']]["orderby"] != '') { + $sqlappend = " order by `".$this->configarray["queryarray"][$this->GETVars['qq']]["orderby"]."` ".$this->GETVars['orderdir']; + } + + $qtable = $this->configarray["queryarray"][$this->GETVars['qq']]["name"]; + $polltype = $this->configarray["queryarray"][$this->GETVars['qq']]["polltype"]; + + if ($polltype == "snapshot") { + if ($_SESSION['timemachine']['time'] == $_SESSION['timemachine']['date']) { + $timestampquery = " WHERE timestamp=(SELECT MAX(TimeStamp) FROM res_".$qtable."_".$server.")"; + } else { + $timestampquery = " WHERE timestamp = '".$_SESSION['timemachine']['time']."'"; + } + } else { + $timestampquery = ""; + } + + // get only latest entry + $searcharr = $_SESSION["search"][$this->GETVars['qq']]; + if (isset($searcharr) && $searcharr["field"] != "" && $searcharr["val"] != "") { + if ($polltype == "snapshot") { + $wc = " AND "; + } else { + $wc = " WHERE "; + } + $wc .= "`".$searcharr["field"]."`".$searcharr["op"]."'".$searcharr["val"]."' "; + } else if (isset($this->timetablestarttime)) { + $startunix = ((ceil($now/$onehour)*$onehour)-$onehour-$oneday)-(($this->timetablestarttime-24)*$onehour); + $endunix = $startunix + $oneday + $onehour; + $start = strftime("%Y-%m-%d %H:%M:%S.000000", $startunix); + $end = strftime("%Y-%m-%d %H:%M:%S.000000", $endunix); + $wc = " WHERE `End Time` >= '".$start."' AND `Start Time` <= '".$end."'"; + } else { + $wc= " "; + } + + $columnnames = $this->getTableFields("res_".$qtable."_".$server); + + if ($columnnames == "") $bContinue = FALSE; + + //execute the constructed query + $sql = "SELECT ".$columnnames." from res_".$qtable."_".$server.$timestampquery.$wc.$sqlappend; + + $_SESSION["lastsql"] = $sql; + if ($sqlres) $this->message = $sql; + + if ($bContinue) { + if ($type == "table") { + $i = 1; + $rs = $this->fetchSplitArrayDB($sql,$this->conn,20); + + foreach ($rs as $row) { + $color = ""; + $col = $this->queryarray["alert_field"]; + if ($col != '') { + $error = $this->checkAlert($this->queryarray["alert_comp"], $this->queryarray["alert_val"], $row[$col]); + if($error) { + $color = $this->queryarray["alert_col"]; + } else { + $color = "ok"; + } + $colorzebra = $colorsarray[$color][$i]; + } + if ($i % 2 == 0) { + $outp = $outp.""; + }else{ + $outp = $outp.""; + } + $i++; + + while(list($keycell, $valcell) = each($row)) { + if($color!="" && $col==$keycell) { + + if ($i % 2 == 0) { + $cellcol = $colorsarray[$color."_light"]; + } else { + $cellcol = $colorsarray[$color."_dark"]; + } + $outp = $outp."".$valcell.""; + } else { + $outp = $outp."".$valcell.""; + } + + } + $outp = $outp."\n"; + } + } + else if ($type == "verticaltable") { + $outp = $this->fetchArrayDB($sql, $this->conn); + } + else if ($type == "timetable") { + $sqlres = $this->fetchArrayDB($sql, $this->conn); + $outp = array();; + foreach ($sqlres as $row) { + $rowarray2 = array(); + while(list($keycell, $valcell) = each($row)) { + if ($keycell == "Start Time" || $keycell == "End Time") { + $date = $row[$keycell]; + $rowarray2[] = mktime(substr($date,11,2),substr($date,14,2),substr($date,17,2),substr($date,5,2),substr($date,8,2),substr($date,0,4)); + } else { + $rowarray2[] = $valcell; + } + } + array_push($outp, $rowarray2); + } + } + } + + return $outp; + } + + + + /** + * getSearchfield - returns the HTML code of the upper searchfield panel + * + * @return string + */ + + function getSearchfield() { + + $ret = ""; + $arrfield = ""; + $arrval = ""; + $arrop = ""; + + $operators = array ("<", "=", "<>", ">"); + + $searcharr = $_SESSION["search"][$this->GETVars['qq']]; + if (isset($searcharr)) { + $arrfield = $searcharr["field"]; + $arrval = $searcharr["val"]; + $arrop = $searcharr["op"]; + } + $sql = "SHOW COLUMNS FROM res_".$this->configarray["queryarray"][$this->GETVars['qq']]["name"]."_".$this->GETVars['server']; + $fieldnames = $this->fetchArrayDB($sql, $this->conn); + + // Build Field Name Combobox + $fieldbox = ""; + + // Build Operator Combobox + if ($arrop=="") $arrop="="; + $opbox = ""; + + $link = $_SERVER['PHP_SELF']."?q=".$this->GETVars['qq']."&m=".$this->GETVars['menu']."&s=".$this->GETVars['server']; + $ret .= "
"; + $ret .= $fieldbox; + $ret .= $opbox; + $ret .= " "; + $ret .= ""; + $ret .= ""; + $ret .= "
"; + + return $ret; + + } + + + + /** + * getServerlist - returns teh HTML code for the server combobox + * + * @return string + */ + + function getServerlist() { + + $ret = ""; + $serverlist = $this->configarray["serverlist"]; + + $i = 0; + $ret = ""; + $ret .= ""; + while(list($servername,$serveritems) = each($serverlist)) { + $listip = $serveritems["ip"]; + $listdescription = $serveritems["description"]; + $listport = $serveritems["port"]; + if ($i == 0) { + $ret .= ""; + $i = 1; + } else { + $ret .= ""; + $i = 0; + } + $listlink = $_SERVER['PHP_SELF']."?q=".$_SESSION["from"]."&m=".$this->GETVars['menu']."&s=".$servername; + $ret .= ""; + } + + return $ret."
ServernameDescriptionIP-AddressPort
".$servername."".$listdescription."".$listip."".$listport."
"; + + } + + + /** + * getPollDStat - returns the HTML code for the TSM Polling Daemon status/log table + * + * @return string + */ + + function getPollDStat() { + + $i=1; + $outp = ""; + $outp .= ""; + + $sql = "SELECT enabled, status, lastrun, nextrun from log_polldstat"; + $sqlres = $this->fetchArrayDB($sql, $this->conn); + foreach ($sqlres as $row) { + if ($row['enabled'] == "1") { + if ($row['status'] == "running") { + $cellcolor = "green"; + } else if ($row['status'] == "sleeping") { + $cellcolor = "yellow"; + } else { + $cellcolor = "red"; + } + if ($row['nextrun'] != "") $nextrun = strftime("%Y/%m/%d %H:%M:%S", $row['nextrun']); + $status = $row['status']; + } else { + $status = "disabled"; + $cellcolor = "red"; + } + if ($row['lastrun'] != "") $lastrun = strftime("%Y/%m/%d %H:%M:%S", $row['lastrun']); + $outp .= ""; + } + $outp .= "
StatusLast RunNext Run
".$status."".$lastrun."".$nextrun."


"; + + $outp .= ""; + $outp .= ""; + + $sql = "SELECT * from log_polldlog where timestamp > '".(time()-86400)."' order by timestamp desc"; + $_SESSION["lastsql"] = $sql; + $rs = $this->fetchSplitArrayDB($sql,$this->conn,20); + foreach ($rs as $row) { + if ($i % 2 == 0) { + $outp = $outp.""; + } else { + $outp = $outp.""; + } + $i++; + + while(list($keycell, $valcell) = each($row)) { + if ($keycell == "timestamp") { + $valcell = strftime("%Y/%m/%d %T", $valcell); + } + $outp = $outp.""; + } + $outp = $outp."\n"; + } + $nav = $this->showPageNavigation("20"); + if ($nav!="") { + $outp = $outp.""; + } + + return $outp."
TimeServernameUpdatedUnchangedPollfreq not reachedTime needed (s)
".$valcell."
"; + } + + + /** + * getOverviewRows - returns HTML code for overview page + * + * @param array $subindexqueryarray array of query objects + * @return string + */ + + function getOverviewRows($subindexqueryarray = '') { + + $out=""; + $i=0; + + while(list($key, $val) = each($subindexqueryarray)) { + + $bgcol=""; + $comperator = ""; + $alertval = ""; + $alertcol = ""; + $cellcolors = $this->configarray["colorsarray"]; + + $cache = $subindexqueryarray[$key]["cache"]; + if ($this->configarray["serverlist"][$this->GETVars['server']]["libraryclient"] == 1 && $subindexqueryarray[$key]["notforlibclient"] == 1) { + $res = "-§§§-"; + } else { + $res = ''; + $sql = "SELECT name, result from res_overview_".$this->GETVars['server']." where name='".$subindexqueryarray[$key]["name"]."'"; + $sqlres = $this->fetchArrayDB($sql, $this->conn); + foreach ($sqlres as $row) { + $res .= $row['name']."§§§".$row['result']; + } + } + + if ($i == 1) { + $out = $out.""; + $i=0; + } else { + $out = $out.""; + $i=1; + } + $res = split("§§§", $res); + //$out .= $subindexqueryarray[$key]["header"]; + $out .= $res[0]; + $comperator = $subindexqueryarray[$key]["alert_comp"]; + $alertval = $subindexqueryarray[$key]["alert_val"]; + $alertcol = $subindexqueryarray[$key]["alert_col"]; + $unit = $subindexqueryarray[$key]["unit"]; + $error = $this->checkAlert($comperator, $alertval, $res[1]); + if ($i==1) { + $shade="light"; + } else { + $shade="dark"; + } + if ($error && $res != "" && $res[1] != "-") { + $bgcol="bgcolor='".$cellcolors[$alertcol."_".$shade]."'"; + } else { + $bgcol="bgcolor='".$cellcolors["ok_".$shade]."'"; + } + $out .= "".$res[1]." ".$unit."\n"; + } + + return $out; + + } + + + + + /** + * generateTimetableHeader - returns HTML code for timetable header (display of hours) + * + * @param string $startpunkt I forgot that one + * @param string $FirstCol first field of result table + * @return string + */ + + function generateTimetableHeader($startpunkt = '', $FirstCol = '') { + + $header = $FirstCol["label"]; + $out= "".$header.""; + for ($count = 0; $count <= 24; $count++) { + $imagename = strftime("%H", $startpunkt+($count*3600)); + $out .= ""; + } + + $out .= ""; + + return $out; + + } + + + + + /** + * generateTimetableNavigation - returns HTML code for timetable header (navigation buttons) + * + * @return string + */ + + function generateTimetableNavigation() { + + + $timesteps = array("1 hour" => "1", "6 hours" => "6", "12 hours" => "12", "24 hours" => "24"); + + $this->timetablestarttime = 24 + $_SESSION['timeshift']; + $out = "
"; + // get value from combobox + if ($_POST["timestep"] != "") { + $_SESSION['selectedtimestep'] = $_POST["timestep"]; + } + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= ""; + $out .= "
"; + + return $out; + } + + + + + + /** + * generateTimetable - generates HTML code for graphical timetables + * + * @param array $tablearray Array containing an SQL query result + * @param string $FirstCol first field of result table + * @return string + */ + + function generateTimetable($tablearray = '', $FirstCol = '') { + + $now = time(); + $out = ''; + $height = 8; + $faktor = 120; + $oneday = 86400; + $onehour = 3600; + $tolerance = 1200; + + $this->timetablestarttime = 24 + $_SESSION['timeshift']; + + $startpunkt = ((ceil($now/$onehour)*$onehour)-$onehour-$oneday)-(($this->timetablestarttime-24)*$onehour); + $endpunkt = $startpunkt + $oneday + $onehour; + $lastpoint = ($endpunkt - $startpunkt)/$faktor; + + $out .= ""; + $out .= $this->generateTimetableNavigation(); + $out .= $this->generateTimetableHeader($startpunkt, $FirstCol); + $out .= ""; + + $lasttimepoint=$now-($this->timetablestarttime*$onehour)-$tolerance; + + $repeatingcol = ""; + $ii=1; + + while(list($keyrow, $valrow) = each($tablearray)) { + if ($valrow[1] <= $endpunkt && $valrow[2] > $lasttimepoint) { + $name = $valrow[0]; + $status = $valrow[3]; + $statusmsg = ""; + $dur = strftime("%H:%M", ($valrow[2]-$valrow[1])-$onehour); + $shade=""; + if ($valrow[1] < $lasttimepoint) { + // cut the bar at the left side to fit into table + $start = 0; + } else { + $start = ($valrow[1]-$startpunkt)/$faktor; + } + $end = ($valrow[2]-$startpunkt)/$faktor; + $duration = $end - $start; + // fake a longer time for better visibility + if ($duration < 2) {$duration=2;} + // cut the bar at the right side to fit into table + if (($start+$duration)>$lastpoint) { + $duration = $lastpoint-$start; + $shade="light"; + } + if ($valrow[1] < $lasttimepoint) { + $shade="light"; + } + if (isset($status)) { + if ($status == "YES" || $status == "Completed") { + $barcol = $shade."green"; + $statusmsg = ", Status was OK"; + }else{ + $barcol = $shade."red"; + $statusmsg = ", Status was UNSUCCESSFUL"; + } + } else { + $barcol = $shade."grey"; + $statusmsg = ""; + } + + if($ii == 1) { + $out .= ""; + } else { + $out .= ""; + $ii = 0; + } + if ($repeatingcol != $valrow[0]) { + $out .= ""; + $repeatingcol = $valrow[0]; + } else { + $out .= ""; + } + if ($valrow[3] != 'Missed') { + $out .= "\n"; + $ii++; + } + } + $out .= $this->generateTimetableHeader($startpunkt); + $out .= $this->generateTimetableNavigation(); + $out .= "
".$valrow[0]."".$valrow[0].""; + $out .= ""; + $out .= ""; + } else { + $out .= ""; + } + $out .= "
"; + + return $out; + + } + + + + + /** + * getConfigArray - queries the DB and generates the global config array + * + * @return array + */ + + function getConfigArray() { + + $retArray = array(); + + // Navigation + $query = "SELECT * from cfg_mainmenu"; + $mainmenutablerows = $this->fetchArrayDB($query, $this->conn); + + $ret = array(); + + $menuarray = array(); + $mainmenuarray = array(); + + while (list ($key, $val) = each ($mainmenutablerows)) { + $menuname = $val['name']; + $menulabel = $val['label']; + $url = "q=overview&m=".$menuname; + $mainmenuarray[$url] = $menulabel; + } + + $menuarrayxml = $queryconfigarray["navigation"]["mainmenuitem"]; + $mainmenuarrayxml = $menuarrayxml; + $mainmenuarray["trennlinie"] = "trennlinie"; + $mainmenuarray["q=polldstat&m=main"] = "Polling Daemon Log"; + $mainmenuarray["q=serverlist&m=main"] = "Change Server"; + if ($_SESSION["logindata"]["role"] == "admin") $mainmenuarray["admin"] = "Admin"; + $mainmenuarray["q=logout"] = "Logout"; + $menuarray["main"] = $mainmenuarray; + + $query = "SELECT * from cfg_mainmenu"; + $mainmenutablerows = $this->fetchArrayDB($query, $this->conn); + $query = "SELECT * from cfg_queries"; + $querytablerows = $this->fetchArrayDB($query, $this->conn); + + + while (list ($key, $val) = each ($mainmenutablerows)) { + $menuname = $val['name']; + $menulabel = $val['label']; + $submenuarray = array(); + $submenuarray[""] = "<---"; + $query = "SELECT * from cfg_queries where parent='".$menuname."'"; + $querytablerows = $this->fetchArrayDB($query, $this->conn); + while (list ($subkey, $submenuitem) = each ($querytablerows)) { + $submenuitem_name = $submenuitem['name']; + $submenuitem_label = $submenuitem['label']; + $url = "q=".$submenuitem_name."&m=".$menuname; + $submenuarray[$url] = $submenuitem_label; + } + $submenuarray["trennlinie"] = "trennlinie"; + $submenuarray["q=polldstat&m=".$submenu['name']] = "Polling Daemon Log"; + $submenuarray["q=serverlist&m=".$submenu['name']] = "Change Server"; + if ($_SESSION["logindata"]["role"] == "admin") $submenuarray["admin"] = "Admin"; + $submenuarray["q=logout"] = "Logout"; + $menuarray[$menuname] = $submenuarray; + } + + $retArray["menuarray"] = $menuarray; + + // Admin Backend Menu + $adminmenuarray = array(); + $adminmenuarray["q=config&m=main"] = "General"; + $adminmenuarray["q=users&m=main"] = "Users"; + $adminmenuarray["q=groups&m=main"] = "Groups"; + $adminmenuarray["q=servers&m=main"] = "Servers"; + $adminmenuarray["q=mainmenu&m=main"] = "Mainmenu"; + $adminmenuarray["q=queries&m=main"] = "Queries"; + $adminmenuarray["trennlinie"] = "trennlinie"; + $adminmenuarray["q=settings&m=main"] = "Settings"; + $adminmenuarray["trennlinie2"] = "trennlinie"; + $adminmenuarray["tsmmonitor"] = "TSM Monitor"; + $adminmenuarray["q=logout"] = "Logout"; + $retArray["adminmenuarray"] = $adminmenuarray; + + // Overview Boxes + $ret = array(); + + $query = "SELECT * from cfg_overviewboxes order by sortorder asc"; + $queryoverviewboxes = $this->fetchArrayDB($query, $this->conn); + while (list ($subkey, $box) = each ($queryoverviewboxes)) { + $query = "SELECT * from cfg_overviewqueries where parent='".$box['name']."' order by sortorder asc"; + $queryoverview = $this->fetchArrayDB($query, $this->conn); + $temp = array (); + //print_r($queryoverview); + while (list ($subkey, $ovquery) = each ($queryoverview)) { + $ovquery['header'] = $queryoverview['name']; + $temp[] = (array)$ovquery; + } + $ret[$box['name']] = $temp; + } + $retArray["infoboxarray"] = $ret; + + // Queries + $dbret = array(); + $query = "SELECT * from cfg_queries"; + $querytablerows = $this->fetchArrayDB($query, $this->conn); + while (list ($subkey, $queryrow) = each ($querytablerows)) { + $dbret[$queryrow['name']] = (array)$queryrow; + } + $retArray["queryarray"] = $dbret; + + // General settings + $query = "SELECT * from cfg_config"; + $rows = $this->fetchArrayDB($query, $this->conn); + $ret = array(); + foreach ($rows as $key => $val) { + $ret[$val['confkey']] = $val['confval']; + } + $retArray["settings"] = $ret; + + // Set Stylesheet + $query = "SELECT stylesheet from cfg_users where username='".$_SESSION["logindata"]["user"]."'"; + $row = $this->fetchArrayDB($query, $this->conn); + $retArray["stylesheet"] = $row[0]['stylesheet']; + + // Colors + $query = "SELECT * from cfg_colors"; + $rows = $this->fetchArrayDB($query, $this->conn); + + $ret = array(); + while (list ($key, $val) = each ($rows)) { + $ret[$val['name']] = $val['value']; + } + $retArray["colorsarray"] = $ret; + + // Servers + $query = "SELECT * from cfg_servers"; + $rows = $this->fetchArrayDB($query, $this->conn); + + $ret = array(); + while (list ($key, $val) = each ($rows)) { + $ret[$val['servername']] = (array)$val; + if ($val['default'] == 1) { + $retArray["defaultserver"] = $val['servername']; + } + } + + $retArray["serverlist"] = $ret; + return $retArray; + } + + + /** + * findPath - find a external program in the search path + * + * @param string $binary the external program to search for + * @param string $search_path the search path in which to look for the external program + * @return string the full path to the external program or empty string if not found + */ + function findPath($binary, $search_path) { + foreach ($search_path as $path) { + if ((file_exists($path . "/" . $binary)) && (is_readable($path . "/" . $binary))) { + return($path . "/" . $binary); + } + } + } + + + /** + * connectDB - establish a DB connection via ADODB + * + * @param string $host the hostname of the DB server + * @param string $port the portnumber for the DB connection + * @param string $user the username for the DB connection + * @param string $pass the password for the DB connection + * @param string $db_name the name of the DB + * @param string $db_type the type of the DB (currently only 'mysql') + * @param string $retr the number attempts for the DB connection before a failure is reported + * @return ADOConnection DB connection ID or error code if connection failed + */ + function connectDB($host, $port = "3306", $user, $pass, $db_name, $db_type, $retr = 20) { + $try = 0; + $hostport = $host . ":" . $port; + $this->conn = NewADOConnection($db_type); + + while ($try <= $retries) { + if ($this->conn->PConnect($hostport,$user,$pass,$db_name)) { + return($this->conn); + } + $try++; + usleep(50000); + } + + die("FATAL: Cannot connect to database server on '$host':'$port'. Please make sure you have specified a valid database name in 'includes/config.php'\n"); + return 0; + } + + + /** + * closeDB - close an open DB connection + * + * @param ADOConnection $DBconn DB connection ID to be closed + * @return string + */ + function closeDB($DBconn = FALSE) { + if ($DBconn) { + return $DBconn->Close(); + } + } + + + /** + * execDB - execute a SQL statement against the DB via ADODB + * + * @param string $sql SQL statement to execute + * @param ADOConnection $DBconn DB connection ID to run the SQL against + * @return ADORecordSet + */ + function execDB($sql, $DBconn = FALSE) { + // $DBconn->debug = true; + $sql = $this->sanitizeSQL($sql); + + $recordSet = &$DBconn->Execute($sql); + if (($recordSet) || ($DBconn->ErrorNo() == 0)) { + return($recordSet); + } else { + echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; + exit; + } + } + + + /** + * fetchCellDB - execute a SQL query against the DB via ADODB and + * return only the first column of the fist row found + * or a specified column of the fist row found + * + * @param string $sql SQL statement to execute + * @param $column_name Column name to use instead of the first column + * @param ADOConnection $DBconn DB connection ID to run the SQL against + * @return string Content of the cell as a single variable + */ + function fetchCellDB($sql, $column_name, $DBconn = FALSE) { + //$DBconn->debug = true; + $sql = $this->sanitizeSQL($sql); + + if ($column_name != '') { + $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); + } else { + $DBconn->SetFetchMode(ADODB_FETCH_NUM); + } + $recordSet = $DBconn->Execute($sql); + + if (($recordSet) || ($DBconn->ErrorNo() == 0)) { + if (!$recordSet->EOF) { + if ($column_name != '') { + $column = $recordSet->fields[$column_name]; + }else{ + $column = $recordSet->fields[0]; + } + $recordSet->close(); + + return($column); + } + } else { + echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; + exit; + } + } + + + /** + * fetchRowDB - execute a SQL query against the DB via ADODB + * and return only the first row found + * + * @param string $sql SQL statement to execute + * @param ADOConnection $DBconn DB connection ID to run the SQL against + * @return array First row of results as an associative array + */ + function fetchRowDB($sql, $DBconn = FALSE) { + //$DBconn->debug = true; + $sql = $this->sanitizeSQL($sql); + + $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); + $recordSet = $DBconn->Execute($sql); + + if (($recordSet) || ($DBconn->ErrorNo() == 0)) { + if (!$recordSet->EOF) { + $recordFields = $recordSet->fields; + $recordSet->close(); + + return($recordFields); + } + } else { + echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; + exit; + } + } + + + /** + * fetchArrayDB - execute a SQL query against the DB via ADODB + * and return results in an associative array. + * + * @param string $sql SQL statement to execute + * @param ADOConnection $DBconn DB connection ID to run the SQL against + * @return array All results in an associative array + */ + function fetchArrayDB($sql, $DBconn = FALSE) { + //$DBconn->debug = true; + $sql = $this->sanitizeSQL($sql); + + $recordArray = array(); + $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); + $recordSet = &$DBconn->Execute($sql); + + if (($recordSet) || ($DBconn->ErrorNo() == 0)) { + while ((!$recordSet->EOF) && ($recordSet)) { + $recordArray{sizeof($recordArray)} = $recordSet->fields; + $recordSet->MoveNext(); + } + $recordSet->close(); + return($recordArray); + } else { + echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; + exit; + } + } + + + /** + * $this->fetchSplitArrayDB - execute a SQL query against the DB via ADODB + * and return results in an associative array. + * + * @param string $sql SQL statement to execute + * @param ADOConnection $DBconn DB connection ID to run the SQL against + * @param string $rows_per_page number of rows per page a result will have + * @return array All results in an associative array + */ + function fetchSplitArrayDB($sql, $DBconn = FALSE, $rows_per_page = '20') { + // $DBconn->debug = true; + $this->page = intval($_GET['page']); + + $sql = $this->sanitizeSQL($sql); + + $recordArray = array(); + $DBconn->SetFetchMode(ADODB_FETCH_ASSOC); + $recordSet = &$DBconn->Execute($sql); + + if (($recordSet) || ($DBconn->ErrorNo() == 0)) { + $total_rows = $recordSet->RecordCount($recordSet); + $this->max_pages = ceil($total_rows/$rows_per_page); + + if($this->page > $this->max_pages || $this->page <= 0) { + $this->page = 1; + } + $offset = $rows_per_page * ($this->page-1); + $endset = $offset + $rows_per_page; + $recordSet->Move($offset); + + while (($recordSet->CurrentRow() < $endset) && ($recordSet->CurrentRow() < $total_rows) && ($recordSet)) { + $recordArray{sizeof($recordArray)} = $recordSet->fields; + $recordSet->MoveNext(); + } + $recordSet->close(); + return($recordArray); + } else { + echo "

Database Error (".$DBconn->ErrorNo().")

\n

".$DBconn->ErrorMsg()."

"; + exit; + } + } + + + /** + * updateDB - execute a SQL update statement against the DB via ADODB + * to update a record. If the record is not found, an insert + * statement is generated and executed. + * + * @param string $table The name of the table containing the record to be updated + * @param array $cells An array of columnname/value pairs of the record to be updated + * @param string $keys Name of the primary key + * @param boolean $autoquote Use intelligent auto-quoting + * @param ADOConnection $DBconn DB connection ID to run the SQL against + * @return string Auto-increment ID if insert was performed + */ + function updateDB($table, $cells, $keys, $DBconn = FALSE, $autoquote = TRUE) { + //$DBconn->debug = true; + $DBconn->Replace($table, $cells, $keys, $autoquote); + + return $DBconn->Insert_ID(); + } + + + /** + * sanitizeSQL - removes unwanted chars in values passed for use in + * SQL statements + * + * @param string $sql SQL expression to sanitize + * @return string + */ + function sanitizeSQL($sql) { + $sql = str_replace(";", "\;", $sql); + $sql = str_replace("\n", "", $sql); + $sql = str_replace("\r", "", $sql); + $sql = str_replace("\t", " ", $sql); + return $sql; + } + +} + +?> diff --git a/index.php b/index.php index 1de9438..27c6de3 100644 --- a/index.php +++ b/index.php @@ -49,8 +49,8 @@ if ($_POST["css"] != "") {
GETVars['qq'], array("admin", "serverlist", "custom", "polldstat", "index", "overview", "")) && !strstr($tsmmonitor->GETVars['qq'], 'table') ) { + echo $tsmmonitor->getSearchfield(); } ?> @@ -66,15 +66,15 @@ if ($_POST["css"] != "") {


@@ -84,27 +84,23 @@ if ($_POST["css"] != "") { GETVars['qq'] != "logout" && $_SESSION["logindata"]["loggedin"]){ + if ($tsmmonitor->GETVars['qq'] != "" && $tsmmonitor->GETVars['qq'] != "overview"){ // show overview page - if ($GETVars['qq'] == "index") { + if ($tsmmonitor->GETVars['qq'] == "index") { include_once "includes/overview.php" ; // show polld status - } else if ($GETVars['qq'] == "polldstat") { - echo getPollDStat(); + } else if ($tsmmonitor->GETVars['qq'] == "polldstat") { + echo $tsmmonitor->getPollDStat(); - // show custom query - } else if ($GETVars['qq'] == "custom") { - echo getCustomQuery(); - // show serverlist - } else if ( $GETVars['qq'] == "serverlist" ) { - echo getServerlist(); + } else if ( $tsmmonitor->GETVars['qq'] == "serverlist" ) { + echo $tsmmonitor->getServerlist(); // show graphical chart (timetable) - } else if ( strstr($GETVars['qq'], 'timetable')) { + } else if ( strstr($tsmmonitor->GETVars['qq'], 'timetable')) { if ($_POST["back"] != "") { $_SESSION['timeshift'] += $_SESSION['selectedtimestep']; @@ -116,16 +112,16 @@ if (isset($_SESSION["logindata"]["user"]) && isset($_SESSION["logindata"]["pass" $_SESSION['timeshift'] = 0; } - $tablearray = execute('timetable'); - $headerarray = $queryarray[$GETVars['qq']]["header"]["column"]; - echo generateTimetable($tablearray, $headerarray[0]); + $tablearray = $tsmmonitor->execute('timetable'); + $headerarray = $queryarray[$tsmmonitor->GETVars['qq']]["header"]["column"]; + echo $tsmmonitor->generateTimetable($tablearray, $headerarray[0]); // "vertical" table - } else if ( strstr($GETVars['qq'], 'vertical')) { + } else if ( strstr($tsmmonitor->GETVars['qq'], 'vertical')) { $i = 0; - $tablearray = execute('verticaltable'); + $tablearray = $tsmmonitor->execute('verticaltable'); echo ""; echo ""; foreach ($tablearray as $row) { @@ -156,22 +152,22 @@ if (isset($_SESSION["logindata"]["user"]) && isset($_SESSION["logindata"]["pass" //} if ($whereclause["field"]!="" && $whereclause["val"]!="") { if ($_POST["Clear"] == "Clear") { - $_SESSION["search"][$GETVars['qq']] = ""; + $_SESSION["search"][$tsmmonitor->GETVars['qq']] = ""; } else { if (!isset($_SESSION["search"])){ $temp = array(); - $temp[$GETVars['qq']] = $whereclause; + $temp[$tsmmonitor->GETVars['qq']] = $whereclause; $_SESSION["search"] = $temp; } else { - $_SESSION["search"][$GETVars['qq']] = $whereclause; + $_SESSION["search"][$tsmmonitor->GETVars['qq']] = $whereclause; } } } echo "
KeyValue
"; - //echo get_tableheader($queryarray[$GETVars['qq']]["header"]["column"]); - echo getTableheader(); - echo execute('table'); - $nav = showPageNavigation("40"); + //echo get_tableheader($queryarray[$tsmmonitor->GETVars['qq']]["header"]["column"]); + echo $tsmmonitor->getTableheader(); + echo $tsmmonitor->execute('table'); + $nav = $tsmmonitor->showPageNavigation("40"); if ($nav!="") { echo ""; } @@ -192,7 +188,7 @@ if (isset($_SESSION["logindata"]["user"]) && isset($_SESSION["logindata"]["pass" include_once "includes/login.php"; } -$_SESSION['from'] = $GETVars['qq']; +$_SESSION['from'] = $tsmmonitor->GETVars['qq']; session_write_close(void); ?> diff --git a/install.php b/install.php index 1c68afe..4a0d446 100644 --- a/install.php +++ b/install.php @@ -62,7 +62,7 @@ $ext_miss $tsm_monitor_versions = array("0.1.0", "0.1.1"); -$old_tsm_monitor_version = fetchCellDB("select confval from cfg_config where confkey='version'", '', $conn); +$old_tsm_monitor_version = $tsmmonitor->fetchCellDB("select confval from cfg_config where confkey='version'", '', $tsmmonitor->conn); // try to find current (old) version in the array $old_version_index = array_search($old_tsm_monitor_version, $tsm_monitor_versions); @@ -94,9 +94,9 @@ if ($old_tsm_monitor_version == $config["tsm_monitor_version"]) { // dsmadmc binary path $input["path_dsmadmc"]["name"] = "dsmadmc Binary Path"; $input["path_dsmadmc"]["desc"] = "The path to the TSM admin client binary."; -$which_dsmadmc = findPath("dsmadmc", $config["search_path"]); -if (isset($configarray["settings"]["path_dsmadmc"])) { - $input["path_dsmadmc"]["default"] = $configarray["settings"]["path_dsmadmc"]; +$which_dsmadmc = $tsmmonitor->findPath("dsmadmc", $config["search_path"]); +if (isset($tsmmonitor->configarray["settings"]["path_dsmadmc"])) { + $input["path_dsmadmc"]["default"] = $tsmmonitor->configarray["settings"]["path_dsmadmc"]; } else if (!empty($which_dsmadmc)) { $input["path_dsmadmc"]["default"] = $which_dsmadmc; } else { @@ -106,12 +106,12 @@ if (isset($configarray["settings"]["path_dsmadmc"])) { // php/php5 binary path $input["path_php"]["name"] = "PHP Binary Path"; $input["path_php"]["desc"] = "The path to the PHP binary."; -$which_php = findPath("php", $config["search_path"]); +$which_php = $tsmmonitor->findPath("php", $config["search_path"]); if(!isset($which_php)) { - $which_php = findPath("php5", $config["search_path"]); + $which_php = $tsmmonitor->findPath("php5", $config["search_path"]); } -if (isset($configarray["settings"]["path_php"])) { - $input["path_php"]["default"] = $configarray["settings"]["path_php"]; +if (isset($tsmmonitor->configarray["settings"]["path_php"])) { + $input["path_php"]["default"] = $tsmmonitor->configarray["settings"]["path_php"]; } else if (!empty($which_php)) { $input["path_php"]["default"] = $which_php; } else { @@ -121,8 +121,8 @@ if (isset($configarray["settings"]["path_php"])) { // logfile path $input["path_tmlog"]["name"] = "TSM Monitor Logfile Path"; $input["path_tmlog"]["desc"] = "The path to the TSM Monitor log file."; -if (isset($configarray["settings"]["path_tmlog"])) { - $input["path_tmlog"]["default"] = $configarray["settings"]["path_tmlog"]; +if (isset($tsmmonitor->configarray["settings"]["path_tmlog"])) { + $input["path_tmlog"]["default"] = $tsmmonitor->configarray["settings"]["path_tmlog"]; } else { $input["path_tmlog"]["default"] = $config["base_path"] . "tsmmonitor.log"; } @@ -173,11 +173,11 @@ if ($_REQUEST["step"] == "90") { // Flush updated data to DB foreach ($input as $name => $array) { if (isset($_POST[$name])) { - updateDB('cfg_config', array(confkey => "$name", confval => $_POST[$name], description => $array['name']), 'confkey', $conn); + $tsmmonitor->updateDB('cfg_config', array(confkey => "$name", confval => $_POST[$name], description => $array['name']), 'confkey', $tsmmonitor->conn); } } - updateDB('cfg_config', array(confkey => 'version', confval => $config['tsm_monitor_version']), 'confkey', $conn); - closeDB($conn); + $tsmmonitor->updateDB('cfg_config', array(confkey => 'version', confval => $config['tsm_monitor_version']), 'confkey', $tsmmonitor->conn); + $tsmmonitor->closeDB($tsmmonitor->conn); header("Location: index.php"); exit; } elseif (($_REQUEST["step"] == "40") && ($_REQUEST["install_type"] == "20")) {