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 human_file_size( $size, $decimal = 2 )
150 $units = array('B','KB','MB','GB','TB');
154 if ( $hsize >= 1024 ) {
155 $hsize = $hsize / 1024;
163 $hsize = sprintf("%." . $decimal . "f", $hsize);
164 return $hsize . ' ' . $units[$unit_id];
171 if ( $this->driver == "mysql") {
172 $dbsize = $this->link->query("show table status") or die ("classes.inc: Error query: 3");
174 if ( $dbsize->numRows() ) {
175 while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
176 $database_size += $res["Data_length"];
181 else if ( $this->driver == "pgsql") {
182 $dbsize = $this->link->query("select pg_database_size('$this->dbs_name')") or die ("classes.inc: Error query: 4");
184 if (PEAR::isError($dbsize))
185 die($dbsize->getMessage());
187 if ( $dbsize->numRows() ) {
188 while ( $res = $dbsize->fetchRow() )
189 $database_size += $res[0];
197 return $this->human_file_size( $database_size );
198 } // end function GetDbSize()
213 function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
217 require_once ("external_packages/phplot/phplot.php");
219 if ( empty($this->sizex) || empty($this->sizey) ) { //Default size
220 $this->sizex = "600";
221 $this->sizey = "400";
223 if ( empty($this->MarginBottom) ) {
224 $this->MarginBottom = 120;
228 // $bgcolor = array(222,206,215); // Background color of graph
229 $bgcolor = array(207,231,231);
230 $fgcolor = array(110,41,57);
234 $graph = new PHPlot($this->sizex,$this->sizey,"","");
237 $graph->setDataType($type);
239 $graph->SetDataValues($datos);
240 $graph->SetPlotType($tipo);
241 // $graph->SetUseTTF(1);
242 $graph->SetBackgroundColor($bgcolor);
244 $graph->SetLegendPixels(1,20);
245 $graph->SetDataColors(array('SkyBlue','purple','PeachPuff','aquamarine1','#2CB04B','beige','#9F865F','#135568','orchid','navy','red', 'black', 'blue', 'green', 'brown', 'yellow','cyan','orange','#B9F5A7','#AFAFAF'));
246 $graph->SetTitle($title);
247 $graph->SetXLabel($xlabel);
248 $graph->SetYLabel($ylabel);
249 $graph->SetPlotAreaWorld("","","","");
251 if ( count($datos) > 5 )
252 $graph->SetXDataLabelAngle(90);
254 $graph->SetXDataLabelAngle(0);
255 $graph->SetNumXTicks(1);
256 // $graph->SetXDataLabelPos('none');
257 // $graph->SetXTickLabelPos('plotdown');
259 // $graph->SetXGridLabelType("time");
260 // $graph->SetXTimeFormat("%b ") ;
262 if ( $this->Leg == 1 ) {
263 $this->MarginLeftWithLegend($legend);
264 $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
265 $graph->SetLegend($legend);
268 $graph->SetMarginsPixels(90,35,35,$this->MarginBottom);
269 // $graph->SetDataColors(array($fgcolor),array( "black"));
270 $graph->SetFileFormat( "png");
271 // $graph->DoScaleData(1,1);
272 // $graph->DoMovingAverage(1,1,1);
274 // FIX ME -- to round y axis.
275 $vtick = strlen (round ($graph->max_y));
277 for ($i=1;$i < $vtick; $i++)
279 if (strlen($graph->max_y-$res) != $vtick )
281 $graph->SetVertTickIncrement($res);
287 //Estupidez que tengo que cambiar. !!!!!!!!!!!
288 function SetDataType($typ) {
294 function MarginLeftWithLegend($clients) {
298 while (next($clients)) {
299 $tmp = strlen(current($clients));
300 if ( $tmp > $maxlen )
303 $this->MarginLeft = $maxlen * 9;
312 class BCreateGraph extends BGraph {
319 var $elapsed; // Default elapsed time to show complex graphs
323 function BCreateGraph() {
325 $this->StartDate = "1900-01-01";
326 $this->EndDate = "4000-01-01";
327 $this->elapsed = "86400"; // 24 hours in seconds.
333 function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
340 $this->clientes=array();
341 $DB_bacula = new Bweb();
342 $datos = $this->SQLPrepareData($server,$tipo_dato);
344 if ( empty($datos) ) { //No data = No stats = Empty graph
345 header("Content-type: image/png");
346 $img= @ImageCreate(200,100) or die ("Cannot intialize GD stream");
347 $bgc= ImageColorAllocate($img, 0, 255,255);
348 $txc= ImageColorAllocate($img, 0,0,0);
349 ImageString($img, 5, 4, 4, "No data to process", $txc);
355 if ( empty ($xlabel) ) { // If no label, table names like leyends
356 $xlabel=$derecha; $ylabel=$izquierda;
359 $this->SetDataType("text-data");
360 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
366 function SQLPrepareData($servidor,$tipo_dato=0) { // Prepare bytes data from database.
372 if ( $tipo_dato<30 ) { // Simple graph. Only 2 data
376 case BACULA_TYPE_BYTES_FILES:
377 $izquierda="jobbytes";
380 case BACULA_TYPE_FILES_JOBID:
381 $izquierda="jobfiles";
385 $izquierda="jobbytes";
389 $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")
390 or die ("classes.inc: Error at query: 5");
391 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
392 $whole_result[] = $this->array_merge_php4($row["$derecha"],$row[$izquierda]);
395 } else { // Complex graph. 3 or more data.
397 switch ( $tipo_dato )
399 case '30': // Unused, at this time.
400 $result = $DB_bacula->link->query("select JobBytes,JobFiles,Jobid from Job where Name='$servidor' order by EndTime asc")
401 or die ("classes.inc: Error at query: 6");
402 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) )
403 $whole_result[] = array_merge($row["Jobid"],$row["JobFiles"],$row["JobBytes"]);
406 case BACULA_TYPE_BYTES_ENDTIME_ALLJOBS: // Special: Generic graph from all clientes.
407 $i = -1; // Counter of number of jobs of one client. SP: Contador del nmero de jobs totales de un cliente.
408 $i2 = 0; // Counter of number of keys of array. SP: Contador del nmero de valores del array.
410 if ($DB_bacula->driver == "mysql") {
411 $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")
412 or die ("classes.inc: Error at query: 7");
413 $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")
414 or die ("classes.inc: Error at query: 8");
416 else if ($DB_bacula->driver == "pgsql") {
417 $res = $DB_bacula->link->query("select Name from Job where EndTime > now() - 1*interval'$this->elapsed s' group by Name order by Name desc")
418 or die ("classes.inc: Error at query: 8");
419 $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")
420 or die ("classes.inc: Error at query: 9");
423 if (PEAR::isError($resdata))
424 die("classes.inc: Error at query: 9.1<br>".$resdata->getMessage());
425 while ( $tmpdata = $res->fetchRow() )
426 array_push($this->clientes,$tmpdata[0]);
429 // print_r ($this->clientes);
433 $spr = array(); // Temporal array
434 $spr2 = array(); // Temporal array
435 $whole_result = array();
437 while ( $tmpdata = $resdata->fetchRow() ) {
439 array_push($spr,$tmpdata[0]);
440 if ($DB_bacula->driver == "mysql")
441 $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")
442 or die ("classes.inc: Error at query: 10");
443 else if ($DB_bacula->driver == "pgsql") {
444 $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";
445 $result = $DB_bacula->link->query($query)
446 or die ("classes.inc: Error at query: 11");
448 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
449 $spr2 = array_merge($spr2,array($row["name"]=>$row["sum"]));
450 $i = $result->numRows();
458 reset ($this->clientes);
460 if ( $spr2[current($this->clientes)] != NULL)
461 array_push($spr,$spr2[current($this->clientes)]);
464 } while ( next($this->clientes) );
469 if ( $tmpdata[0] != $row["EndTime"] )
470 array_push($whole_result,$spr);
476 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
477 $tmp = count($whole_result[$i]);
478 if ( $i2 < $tmp ) // Estupidez?. Check this code later...
481 for ( $a = 0; $a <= $tmp; $a++ )
482 array_push($whole_result[$i],"0"); // Fill the array
485 // echo "DEBUG:<br>";
487 // print_r ($whole_result);
496 return $whole_result;
501 //Convert date from mysql to smarty. THE SAME FUNCTION AT 2 CLASSES. THIS WAY IS BUGGY. TO SOLVE LATER.
502 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear){
504 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
505 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
510 function array_merge_php4($array1,$array2) {
513 foreach(func_get_args() as $arg) {
517 foreach($arg as $key=>$val){