3 +-------------------------------------------------------------------------+
4 | Copyright (C) 2004-2005 Juan Luis Frances Jiminez |
6 | This program is free software; you can redistribute it and/or |
7 | modify it under the terms of the GNU General Public License |
8 | as published by the Free Software Foundation; either version 2 |
9 | of the License, or (at your option) any later version. |
11 | This program is distributed in the hope that it will be useful, |
12 | but WITHOUT ANY WARRANTY; without even the implied warranty of |
13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
14 | GNU General Public License for more details. |
15 +-------------------------------------------------------------------------+
18 define('CONFIG_DIR', "configs");
19 define('CONFIG_FILE', "bacula.conf");
20 define('BACULA_TYPE_BYTES_FILES', 1);
21 define('BACULA_TYPE_FILES_JOBID', 2);
22 define('BACULA_TYPE_BYTES_ENDTIME_ALLJOBS', 69);
24 require_once "paths.php";
25 require_once "DB.php"; // Pear DB
26 require_once($smarty_path."Config_File.class.php");
28 if (!function_exists('array_fill')) { // For PHP < 4.2.0 users
29 require_once('array_fill.func.php');
32 class Bweb extends DB {
44 $conf = new Config_File (CONFIG_DIR);
47 $sections = $conf->get(CONFIG_FILE,"DATABASE","host");
48 array_push($this->dbs, "DATABASE");
49 while ( !empty($sections) ) {
50 $sections = $conf->get(CONFIG_FILE,"DATABASE".$i,"host");
51 if ( !empty($sections) )
52 array_push($this->dbs,"DATABASE".$i);
59 if ( !empty($_POST['sel_database']) ) {
60 $_SESSION['DATABASE'] = $_POST['sel_database'];
61 $sec = $_POST['sel_database'];
63 if (isset($_SESSION['DATABASE']) )
64 $sec = $_SESSION['DATABASE'];
70 $this->dsn['hostspec'] = $conf->get(CONFIG_FILE,$sec,"host");
71 $this->dsn['username'] = $conf->get(CONFIG_FILE,$sec,"login");
72 $this->dsn['password'] = $conf->get(CONFIG_FILE,$sec,"pass");
73 $this->dsn['database'] = $conf->get(CONFIG_FILE,$sec,"db_name");
74 $this->dsn['phptype'] = $conf->get(CONFIG_FILE,$sec,"db_type"); // mysql, pgsql
75 if ( $conf->get(CONFIG_FILE,$sec,"db_port") )
76 $this->dsn[port] = $conf->get(CONFIG_FILE,$sec,"db_port");
78 $this->link =& $this->connect($this->dsn);
80 if (DB::isError($this->link))
81 die($this->link->getMessage());
82 $this->driver = $this->dsn[phptype];
83 register_shutdown_function(array(&$this,'close'));
84 $this->dbs_name = $this->dsn['database'];
89 $this->link->disconnect();
94 function CalculateBytesPeriod($server,$StartDate,$EndPeriod) { // Bytes transferred in a period.
96 $result =& $this->link->query("select SUM(JobBytes) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
97 or die("classes.inc: Error query: 1");
98 $return =& $result->fetchRow();
104 function CalculateFilesPeriod($server,$StartDate,$EndPeriod) { // Number of files transferred in a period.
106 $result =& $this->link->query("select SUM(JobFiles) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
107 or die("classes.inc: Error query: 2");
108 $return =& $result->fetchRow();
114 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) { // Convert date for Smarty. Check if only works with Mysql.
116 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
117 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59"; // last day full
123 function GetDataVolumes() {
126 $res = $this->link->query("SELECT Name FROM Pool");
127 while ( $tmp =& $res->fetchRow() ) {
128 if ($this->driver == "mysql" )
129 $result = $this->link->query("select Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten,FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) as expire from Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId where Name='$tmp[0]' order by Media.VolumeName");
130 else if ($this->driver == "pgsql")
131 $result = $this->link->query("select Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' as expire from Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId where Name='$tmp[0]' order by Media.VolumeName");
132 while ( $tmp1 = $result->fetchRow() ) {
133 $pos = array_key_exists($tmp[0],$volume);
135 array_push($volume["$tmp[0]"],$tmp1);
137 $volume += array($tmp[0]=>array($tmp1));
146 function GetDbSize() {
147 if ( $this->driver == "mysql") {
148 $dbsize = $this->link->query("show table status")
149 or die ("classes.inc: Error query: 3");
150 if ( $dbsize->numRows() ) {
151 while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
152 $database_size += $res["Data_length"];
157 else if ( $this->driver == "pgsql") {
158 $dbsize = $this->link->query("select pg_database_size('$this->dbs_name')")
159 or die ("classes.inc: Error query: 4");
160 if (PEAR::isError($dbsize))
161 die($dbsize->getMessage());
162 if ( $dbsize->numRows() ) {
163 while ( $res = $dbsize->fetchRow() )
164 $database_size += $res[0];
170 return $database_size;
186 function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
190 require_once ("external_packages/phplot/phplot.php");
192 if ( empty($this->sizex) || empty($this->sizey) ) { //Default size
193 $this->sizex = "600";
194 $this->sizey = "400";
196 if ( empty($this->MarginBottom) ) {
197 $this->MarginBottom = 120;
201 // $bgcolor = array(222,206,215); // Background color of graph
202 $bgcolor = array(207,231,231);
203 $fgcolor = array(110,41,57);
207 $graph = new PHPlot($this->sizex,$this->sizey,"","");
210 $graph->setDataType($type);
212 $graph->SetDataValues($datos);
213 $graph->SetPlotType($tipo);
214 // $graph->SetUseTTF(1);
215 $graph->SetBackgroundColor($bgcolor);
217 $graph->SetLegendPixels(1,20);
218 $graph->SetDataColors(array('SkyBlue','purple','PeachPuff','aquamarine1','#2CB04B','beige','#9F865F','#135568','orchid','navy','red', 'black', 'blue', 'green', 'brown', 'yellow','cyan','orange','#B9F5A7','#AFAFAF'));
219 $graph->SetTitle($title);
220 $graph->SetXLabel($xlabel);
221 $graph->SetYLabel($ylabel);
222 $graph->SetPlotAreaWorld("","","","");
224 if ( count($datos) > 5 )
225 $graph->SetXDataLabelAngle(90);
227 $graph->SetXDataLabelAngle(0);
228 $graph->SetNumXTicks(1);
229 // $graph->SetXDataLabelPos('none');
230 // $graph->SetXTickLabelPos('plotdown');
232 // $graph->SetXGridLabelType("time");
233 // $graph->SetXTimeFormat("%b ") ;
235 if ( $this->Leg == 1 ) {
236 $this->MarginLeftWithLegend($legend);
237 $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
238 $graph->SetLegend($legend);
241 $graph->SetMarginsPixels(90,35,35,$this->MarginBottom);
242 // $graph->SetDataColors(array($fgcolor),array( "black"));
243 $graph->SetFileFormat( "png");
244 // $graph->DoScaleData(1,1);
245 // $graph->DoMovingAverage(1,1,1);
247 // FIX ME -- to round y axis.
248 $vtick = strlen (round ($graph->max_y));
250 for ($i=1;$i < $vtick; $i++)
252 if (strlen($graph->max_y-$res) != $vtick )
254 $graph->SetVertTickIncrement($res);
260 //Estupidez que tengo que cambiar. !!!!!!!!!!!
261 function SetDataType($typ) {
267 function MarginLeftWithLegend($clients) {
271 while (next($clients)) {
272 $tmp = strlen(current($clients));
273 if ( $tmp > $maxlen )
276 $this->MarginLeft = $maxlen * 9;
285 class BCreateGraph extends BGraph {
292 var $elapsed; // Default elapsed time to show complex graphs
296 function BCreateGraph() {
298 $this->StartDate = "1900-01-01";
299 $this->EndDate = "4000-01-01";
300 $this->elapsed = "86400"; // 24 hours in seconds.
306 function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
313 $this->clientes=array();
314 $DB_bacula = new Bweb();
315 $datos = $this->SQLPrepareData($server,$tipo_dato);
317 if ( empty($datos) ) { //No data = No stats = Empty graph
318 header("Content-type: image/png");
319 $img= @ImageCreate(200,100) or die ("Cannot intialize GD stream");
320 $bgc= ImageColorAllocate($img, 0, 255,255);
321 $txc= ImageColorAllocate($img, 0,0,0);
322 ImageString($img, 5, 4, 4, "None data to process", $txc);
328 if ( empty ($xlabel) ) { // If no label, table names like leyends
329 $xlabel=$derecha; $ylabel=$izquierda;
332 $this->SetDataType("text-data");
333 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
339 function SQLPrepareData($servidor,$tipo_dato=0) { // Prepare bytes data from database.
345 if ( $tipo_dato<30 ) { // Simple graph. Only 2 data
349 case BACULA_TYPE_BYTES_FILES:
350 $izquierda="jobbytes";
353 case BACULA_TYPE_FILES_JOBID:
354 $izquierda="jobfiles";
358 $izquierda="jobbytes";
362 $result = $DB_bacula->link->query("select $derecha,$izquierda from Job where Name='$servidor' and EndTime < '$this->EndDate' and EndTime > '$this->StartDate' order by SchedTime asc")
363 or die ("classes.inc: Error at query: 5");
364 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
365 $whole_result[] = $this->array_merge_php4($row["$derecha"],$row[$izquierda]);
368 } else { // Complex graph. 3 or more data.
370 switch ( $tipo_dato )
372 case '30': // Unused, at this time.
373 $result = $DB_bacula->link->query("select JobBytes,JobFiles,Jobid from Job where Name='$servidor' order by EndTime asc")
374 or die ("classes.inc: Error at query: 6");
375 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) )
376 $whole_result[] = array_merge($row["Jobid"],$row["JobFiles"],$row["JobBytes"]);
379 case BACULA_TYPE_BYTES_ENDTIME_ALLJOBS: // Special: Generic graph from all clientes.
380 $i = -1; // Counter of number of jobs of one client. SP: Contador del nmero de jobs totales de un cliente.
381 $i2 = 0; // Counter of number of keys of array. SP: Contador del nmero de valores del array.
383 if ($DB_bacula->driver == "mysql") {
384 $res = $DB_bacula->link->query("select Name from Job where UNIX_TIMESTAMP(EndTime) > UNIX_TIMESTAMP(NOW())-$this->elapsed group by Name order by Name desc")
385 or die ("classes.inc: Error at query: 7");
386 $resdata = $DB_bacula->link->query("select date_format(EndTime,\"%Y-%m-%d\") from Job where UNIX_TIMESTAMP(EndTime) > UNIX_TIMESTAMP(NOW())-$this->elapsed group by date_format(EndTime, \"%Y-%m-%d\") order by EndTime")
387 or die ("classes.inc: Error at query: 8");
389 else if ($DB_bacula->driver == "pgsql") {
390 $res = $DB_bacula->link->query("select Name from Job where EndTime > now() - 1*interval'$this->elapsed s' group by Name order by Name desc")
391 or die ("classes.inc: Error at query: 8");
392 $resdata = $DB_bacula->link->query("select to_char(EndTime,'YY-MM-DD') from Job where EndTime > NOW() - 1*interval'$this->elapsed s' group by EndTime order by EndTime")
393 or die ("classes.inc: Error at query: 9");
396 if (PEAR::isError($resdata))
397 die("classes.inc: Error at query: 9.1<br>".$resdata->getMessage());
398 while ( $tmpdata = $res->fetchRow() )
399 array_push($this->clientes,$tmpdata[0]);
402 // print_r ($this->clientes);
406 $spr = array(); // Temporal array
407 $spr2 = array(); // Temporal array
408 $whole_result = array();
410 while ( $tmpdata = $resdata->fetchRow() ) {
412 array_push($spr,$tmpdata[0]);
413 if ($DB_bacula->driver == "mysql")
414 $result = $DB_bacula->link->query("select date_format(EndTime,\"%Y-%m-%d\"),SUM(JobBytes) as sum,Name as name,count(Name) as Nname from Job WHERE EndTime like '$tmpdata[0]%' group by Name order by Name desc")
415 or die ("classes.inc: Error at query: 10");
416 else if ($DB_bacula->driver == "pgsql") {
417 $query = "select to_char(EndTime,'YY-MM-DD'),SUM(JobBytes) as sum,Name,count(Name) as Nname from Job WHERE EndTime like '%$tmpdata[0]%' group by EndTime,Name order by Name desc";
418 $result = $DB_bacula->link->query($query)
419 or die ("classes.inc: Error at query: 11");
421 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
422 $spr2 = array_merge($spr2,array($row["name"]=>$row["sum"]));
423 $i = $result->numRows();
431 reset ($this->clientes);
433 if ( $spr2[current($this->clientes)] != NULL)
434 array_push($spr,$spr2[current($this->clientes)]);
437 } while ( next($this->clientes) );
442 if ( $tmpdata[0] != $row["EndTime"] )
443 array_push($whole_result,$spr);
449 for ( $i = 0; $i < count($whole_result); $i++ ) { // To equal the arrays so that the graph is not unsquared. SP:Igualamos las matrices para que la gr�ica no se descuadre
450 $tmp = count($whole_result[$i]);
451 if ( $i2 < $tmp ) // Estupidez?. Check this code later...
454 for ( $a = 0; $a <= $tmp; $a++ )
455 array_push($whole_result[$i],"0"); // Fill the array
458 // echo "DEBUG:<br>";
460 // print_r ($whole_result);
469 return $whole_result;
474 //Convert date from mysql to smarty. THE SAME FUNCTION AT 2 CLASSES. THIS WAY IS BUGGY. TO SOLVE LATER.
475 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear){
477 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
478 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
483 function array_merge_php4($array1,$array2) {
486 foreach(func_get_args() as $arg) {
490 foreach($arg as $key=>$val){