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 {
42 $conf = new Config_File (CONFIG_DIR);
45 $this->dsn[hostspec] = $conf->get(CONFIG_FILE,"DATABASE","host");
46 $this->dsn[username] = $conf->get(CONFIG_FILE,"DATABASE","login");
47 $this->dsn[password] = $conf->get(CONFIG_FILE,"DATABASE","pass");
48 $this->dsn[database] = $conf->get(CONFIG_FILE,"DATABASE","db_name");
49 $this->dsn[phptype] = $conf->get(CONFIG_FILE,"DATABASE","db_type"); // mysql, (sqlite, pgsql) -->> Yet not checked
50 if ( $conf->get(CONFIG_FILE,"DATABASE","db_port") )
51 $this->dsn[port] = $conf->get(CONFIG_FILE,"DATABASE","db_port");
53 $this->link =& $this->connect($this->dsn);
55 if (DB::isError($this->link))
56 die($this->link->getMessage());
57 $this->driver = $this->dsn[phptype];
58 register_shutdown_function(array(&$this,'close'));
65 $this->link->disconnect();
70 function CalculateBytesPeriod($server,$StartDate,$EndPeriod) { // Bytes transferred in a period.
72 $result =& $this->link->query("select SUM(JobBytes) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
73 or die("classes.inc: Error query: 1");
74 $return =& $result->fetchRow();
80 function CalculateFilesPeriod($server,$StartDate,$EndPeriod) { // Number of files transferred in a period.
82 $result =& $this->link->query("select SUM(JobFiles) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
83 or die("classes.inc: Error query: 2");
84 $return =& $result->fetchRow();
90 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) { // Convert date for Smarty. Check if only works with Mysql.
92 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
93 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59"; // last day full
99 function GetDataVolumes() {
102 $res = $this->link->query("SELECT Name FROM Pool");
103 while ( $tmp =& $res->fetchRow() ) {
104 if ($this->driver == "mysql" )
105 $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");
106 else if ($this->driver == "pgsql")
107 $result = $this->link->query("select Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten,FROM_UNIXTIME(Media.LastWritten::Timestamp without time zone + Media.VolRetention) as expire from Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId where Name='$tmp[0]' order by Media.VolumeName");
108 while ( $tmp1 = $result->fetchRow() ) {
109 $pos = array_key_exists($tmp[0],$volume);
111 array_push($volume["$tmp[0]"],$tmp1);
113 $volume += array($tmp[0]=>array($tmp1));
122 function GetDbSize() {
123 if ( $this->driver == "mysql") {
124 $dbsize = $this->link->query("show table status")
125 or die ("classes.inc: Error query: 3");
126 if ( $dbsize->numRows() ) {
127 while ( $res = $dbsize->fetchRow() )
128 $database_size += $res[5];
133 else if ( $this->driver == "pgsql") {
134 $dbsize = $this->link->query("select database_size('bacula')")
135 or die ("classes.inc: Error query: 4");
136 if ( $dbsize->numRows() ) {
137 while ( $res = $dbsize->fetchRow() )
138 $database_size += $res[0];
144 return $database_size;
160 function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
164 require_once ("external_packages/phplot/phplot.php");
166 if ( empty($this->sizex) || empty($this->sizey) ) { //Default size
167 $this->sizex = "600";
168 $this->sizey = "400";
170 if ( empty($this->MarginBottom) ) {
171 $this->MarginBottom = 120;
175 // $bgcolor = array(222,206,215); // Background color of graph
176 $bgcolor = array(207,231,231);
177 $fgcolor = array(110,41,57);
181 $graph = new PHPlot($this->sizex,$this->sizey,"","");
184 $graph->setDataType($type);
186 $graph->SetDataValues($datos);
187 $graph->SetPlotType($tipo);
188 // $graph->SetUseTTF(1);
189 $graph->SetBackgroundColor($bgcolor);
191 $graph->SetLegendPixels(1,20);
192 $graph->SetDataColors(array('SkyBlue','purple','PeachPuff','aquamarine1','#2CB04B','beige','#9F865F','#135568','orchid','navy','red', 'black', 'blue', 'green', 'brown', 'yellow','cyan','orange','#B9F5A7','#AFAFAF'));
193 $graph->SetTitle($title);
194 $graph->SetXLabel($xlabel);
195 $graph->SetYLabel($ylabel);
196 $graph->SetPlotAreaWorld("","","","");
198 if ( count($datos) > 5 )
199 $graph->SetXDataLabelAngle(90);
201 $graph->SetXDataLabelAngle(0);
202 // $graph->SetNumXTicks(10);
203 // $graph->SetXDataLabelPos('none');
204 // $graph->SetXTickLabelPos('plotdown');
206 // $graph->SetXGridLabelType("time");
207 // $graph->SetXTimeFormat("%b ") ;
209 if ( $this->Leg == 1 ) {
210 $this->MarginLeftWithLegend($legend);
211 $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
212 $graph->SetLegend($legend);
215 $graph->SetMarginsPixels(90,35,35,$this->MarginBottom);
216 // $graph->SetDataColors(array($fgcolor),array( "black"));
217 $graph->SetFileFormat( "png");
218 // $graph->DoScaleData(1,1);
219 // $graph->DoMovingAverage(1,1,1);
221 // FIX ME -- to round y axis.
222 $vtick = strlen (round ($graph->max_y));
224 for ($i=1;$i < $vtick; $i++)
226 if (strlen($graph->max_y-$res) != $vtick )
228 $graph->SetVertTickIncrement($res);
234 //Estupidez que tengo que cambiar. !!!!!!!!!!!
235 function SetDataType($typ) {
241 function MarginLeftWithLegend($clients) {
245 while (next($clients)) {
246 $tmp = strlen(current($clients));
247 if ( $tmp > $maxlen )
250 $this->MarginLeft = $maxlen * 11;
259 class BCreateGraph extends BGraph {
266 var $elapsed; // Default elapsed time to show complex graphs
270 function BCreateGraph() {
272 $this->StartDate = "1900-01-01";
273 $this->EndDate = "4000-01-01";
274 $this->elapsed = "86400"; // 24 hours in seconds.
280 function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
287 $this->clientes=array();
288 $DB_bacula = new Bweb();
289 $datos = $this->SQLPrepareData($server,$tipo_dato);
291 if ( empty($datos) ) { //No data = No stats = Empty graph
292 header("Content-type: image/png");
293 $img= @ImageCreate(200,100) or die ("Cannot intialize GD stream");
294 $bgc= ImageColorAllocate($img, 0, 255,255);
295 $txc= ImageColorAllocate($img, 0,0,0);
296 ImageString($img, 5, 4, 4, "None data to process", $txc);
302 if ( empty ($xlabel) ) { // If no label, table names like leyends
303 $xlabel=$derecha; $ylabel=$izquierda;
306 $this->SetDataType("text-data");
307 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
313 function SQLPrepareData($servidor,$tipo_dato=0) { // Prepare bytes data from database.
319 if ( $tipo_dato<30 ) { // Simple graph. Only 2 data
323 case BACULA_TYPE_BYTES_FILES:
324 $izquierda="jobbytes";
327 case BACULA_TYPE_FILES_JOBID:
328 $izquierda="jobfiles";
332 $izquierda="jobbytes";
336 $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")
337 or die ("classes.inc: Error at query: 5");
338 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
339 $whole_result[] = $this->array_merge_php4($row["$derecha"],$row[$izquierda]);
342 } else { // Complex graph. 3 or more data.
344 switch ( $tipo_dato )
346 case '30': // Unused, at this time.
347 $result = $DB_bacula->link->query("select JobBytes,JobFiles,Jobid from Job where Name='$servidor' order by EndTime asc")
348 or die ("classes.inc: Error at query: 6");
349 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) )
350 $whole_result[] = array_merge($row["Jobid"],$row["JobFiles"],$row["JobBytes"]);
353 case BACULA_TYPE_BYTES_ENDTIME_ALLJOBS: // Special: Generic graph from all clientes.
354 $i = -1; // Counter of number of jobs of one cliente. SP: Contador del nmero de jobs totales de un cliente.
355 $i2 = 0; // Counter of number of keys of array. SP: Contador del nmero de valores del array.
357 $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")
358 or die ("classes.inc: Error at query: 7");
359 if ($DB_bacula->driver == "mysql")
360 $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")
361 or die ("classes.inc: Error at query: 8");
362 else if ($DB_bacula->driver == "pgsql")
363 $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 EndTime order by EndTime")
364 or die ("classes.inc: Error at query: 9");
366 while ( $tmpdata = $res->fetchRow() )
367 array_push($this->clientes,$tmpdata[0]);
370 // print_r ($this->clientes);
374 $spr = array(); // Temporal array
375 $spr2 = array(); // Temporal array
376 $whole_result = array();
378 while ( $tmpdata = $resdata->fetchRow() ) {
380 array_push($spr,$tmpdata[0]);
381 if ($DB_bacula->driver == "mysql")
382 $result = $DB_bacula->link->query("select date_format(EndTime,\"%Y-%m-%d\"),SUM(JobBytes),Name,count(Name) as Nname from Job WHERE EndTime like '$tmpdata[0]%' group by Name order by Name desc")
383 or die ("classes.inc: Error at query: 10");
384 else if ($DB_bacula->driver == "pgsql")
385 $result = $DB_bacula->link->query("select date_format(EndTime,'%Y-%m-%d'),SUM(JobBytes),Name,count(Name) as Nname from Job WHERE EndTime like '$tmpdata[0]%' group by EndTime,Name order by Name desc")
386 or die ("classes.inc: Error at query: 11");
387 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
388 $spr2 = array_merge($spr2,array($row["Name"]=>$row["SUM(JobBytes)"]));
389 $i = $result->numRows();
397 reset ($this->clientes);
399 if ( $spr2[current($this->clientes)] != NULL)
400 array_push($spr,$spr2[current($this->clientes)]);
403 } while ( next($this->clientes) );
408 if ( $tmpdata[0] != $row["EndTime"] )
409 array_push($whole_result,$spr);
415 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
416 $tmp = count($whole_result[$i]);
417 if ( $i2 < $tmp ) // Estupidez?. Check this code later...
420 for ( $a = 0; $a <= $tmp; $a++ )
421 array_push($whole_result[$i],"0"); // Fill the array
424 // echo "DEBUG:<br>";
426 // print_r ($whole_result);
435 return $whole_result;
440 //Conversi� de la fecha a Mysql-format para Smarty. THE SAME FUNCTION AT 2 CLASSES. THIS WAY IS BUGGY. TO SOLVE LATER.
441 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear){
443 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
444 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
449 function array_merge_php4($array1,$array2) {
452 foreach(func_get_args() as $arg) {
456 foreach($arg as $key=>$val){