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 {
43 $conf = new Config_File (CONFIG_DIR);
46 $sections = $conf->get(CONFIG_FILE,"DATABASE","host");
47 array_push($this->dbs, "DATABASE");
48 while ( !empty($sections) ) {
49 $sections = $conf->get(CONFIG_FILE,"DATABASE".$i,"host");
50 if ( !empty($sections) )
51 array_push($this->dbs,"DATABASE".$i);
58 if ( !empty($_POST['sel_database']) ) {
59 $_SESSION['DATABASE'] = $_POST['sel_database'];
60 $sec = $_POST['sel_database'];
62 if (isset($_SESSION['DATABASE']) )
63 $sec = $_SESSION['DATABASE'];
69 $this->dsn['hostspec'] = $conf->get(CONFIG_FILE,$sec,"host");
70 $this->dsn['username'] = $conf->get(CONFIG_FILE,$sec,"login");
71 $this->dsn['password'] = $conf->get(CONFIG_FILE,$sec,"pass");
72 $this->dsn['database'] = $conf->get(CONFIG_FILE,$sec,"db_name");
73 $this->dsn['phptype'] = $conf->get(CONFIG_FILE,$sec,"db_type"); // mysql, (sqlite, pgsql) -->> Yet not checked
74 if ( $conf->get(CONFIG_FILE,$sec,"db_port") )
75 $this->dsn[port] = $conf->get(CONFIG_FILE,$sec,"db_port");
77 $this->link =& $this->connect($this->dsn);
79 if (DB::isError($this->link))
80 die($this->link->getMessage());
81 $this->driver = $this->dsn[phptype];
82 register_shutdown_function(array(&$this,'close'));
87 $this->link->disconnect();
92 function CalculateBytesPeriod($server,$StartDate,$EndPeriod) { // Bytes transferred in a period.
94 $result =& $this->link->query("select SUM(JobBytes) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
95 or die("classes.inc: Error query: 1");
96 $return =& $result->fetchRow();
102 function CalculateFilesPeriod($server,$StartDate,$EndPeriod) { // Number of files transferred in a period.
104 $result =& $this->link->query("select SUM(JobFiles) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
105 or die("classes.inc: Error query: 2");
106 $return =& $result->fetchRow();
112 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) { // Convert date for Smarty. Check if only works with Mysql.
114 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
115 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59"; // last day full
121 function GetDataVolumes() {
124 $res = $this->link->query("SELECT Name FROM Pool");
125 while ( $tmp =& $res->fetchRow() ) {
126 if ($this->driver == "mysql" )
127 $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");
128 else if ($this->driver == "pgsql")
129 $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");
130 while ( $tmp1 = $result->fetchRow() ) {
131 $pos = array_key_exists($tmp[0],$volume);
133 array_push($volume["$tmp[0]"],$tmp1);
135 $volume += array($tmp[0]=>array($tmp1));
144 function GetDbSize() {
145 if ( $this->driver == "mysql") {
146 $dbsize = $this->link->query("show table status")
147 or die ("classes.inc: Error query: 3");
148 if ( $dbsize->numRows() ) {
149 while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
150 $database_size += $res["Data_length"];
155 else if ( $this->driver == "pgsql") {
156 $dbsize = $this->link->query("select database_size('bacula')")
157 or die ("classes.inc: Error query: 4");
158 if ( $dbsize->numRows() ) {
159 while ( $res = $dbsize->fetchRow() )
160 $database_size += $res[0];
166 return $database_size;
182 function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
186 require_once ("external_packages/phplot/phplot.php");
188 if ( empty($this->sizex) || empty($this->sizey) ) { //Default size
189 $this->sizex = "600";
190 $this->sizey = "400";
192 if ( empty($this->MarginBottom) ) {
193 $this->MarginBottom = 120;
197 // $bgcolor = array(222,206,215); // Background color of graph
198 $bgcolor = array(207,231,231);
199 $fgcolor = array(110,41,57);
203 $graph = new PHPlot($this->sizex,$this->sizey,"","");
206 $graph->setDataType($type);
208 $graph->SetDataValues($datos);
209 $graph->SetPlotType($tipo);
210 // $graph->SetUseTTF(1);
211 $graph->SetBackgroundColor($bgcolor);
213 $graph->SetLegendPixels(1,20);
214 $graph->SetDataColors(array('SkyBlue','purple','PeachPuff','aquamarine1','#2CB04B','beige','#9F865F','#135568','orchid','navy','red', 'black', 'blue', 'green', 'brown', 'yellow','cyan','orange','#B9F5A7','#AFAFAF'));
215 $graph->SetTitle($title);
216 $graph->SetXLabel($xlabel);
217 $graph->SetYLabel($ylabel);
218 $graph->SetPlotAreaWorld("","","","");
220 if ( count($datos) > 5 )
221 $graph->SetXDataLabelAngle(90);
223 $graph->SetXDataLabelAngle(0);
224 // $graph->SetNumXTicks(10);
225 // $graph->SetXDataLabelPos('none');
226 // $graph->SetXTickLabelPos('plotdown');
228 // $graph->SetXGridLabelType("time");
229 // $graph->SetXTimeFormat("%b ") ;
231 if ( $this->Leg == 1 ) {
232 $this->MarginLeftWithLegend($legend);
233 $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
234 $graph->SetLegend($legend);
237 $graph->SetMarginsPixels(90,35,35,$this->MarginBottom);
238 // $graph->SetDataColors(array($fgcolor),array( "black"));
239 $graph->SetFileFormat( "png");
240 // $graph->DoScaleData(1,1);
241 // $graph->DoMovingAverage(1,1,1);
243 // FIX ME -- to round y axis.
244 $vtick = strlen (round ($graph->max_y));
246 for ($i=1;$i < $vtick; $i++)
248 if (strlen($graph->max_y-$res) != $vtick )
250 $graph->SetVertTickIncrement($res);
256 //Estupidez que tengo que cambiar. !!!!!!!!!!!
257 function SetDataType($typ) {
263 function MarginLeftWithLegend($clients) {
267 while (next($clients)) {
268 $tmp = strlen(current($clients));
269 if ( $tmp > $maxlen )
272 $this->MarginLeft = $maxlen * 9;
281 class BCreateGraph extends BGraph {
288 var $elapsed; // Default elapsed time to show complex graphs
292 function BCreateGraph() {
294 $this->StartDate = "1900-01-01";
295 $this->EndDate = "4000-01-01";
296 $this->elapsed = "86400"; // 24 hours in seconds.
302 function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
309 $this->clientes=array();
310 $DB_bacula = new Bweb();
311 $datos = $this->SQLPrepareData($server,$tipo_dato);
313 if ( empty($datos) ) { //No data = No stats = Empty graph
314 header("Content-type: image/png");
315 $img= @ImageCreate(200,100) or die ("Cannot intialize GD stream");
316 $bgc= ImageColorAllocate($img, 0, 255,255);
317 $txc= ImageColorAllocate($img, 0,0,0);
318 ImageString($img, 5, 4, 4, "None data to process", $txc);
324 if ( empty ($xlabel) ) { // If no label, table names like leyends
325 $xlabel=$derecha; $ylabel=$izquierda;
328 $this->SetDataType("text-data");
329 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
335 function SQLPrepareData($servidor,$tipo_dato=0) { // Prepare bytes data from database.
341 if ( $tipo_dato<30 ) { // Simple graph. Only 2 data
345 case BACULA_TYPE_BYTES_FILES:
346 $izquierda="jobbytes";
349 case BACULA_TYPE_FILES_JOBID:
350 $izquierda="jobfiles";
354 $izquierda="jobbytes";
358 $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")
359 or die ("classes.inc: Error at query: 5");
360 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
361 $whole_result[] = $this->array_merge_php4($row["$derecha"],$row[$izquierda]);
364 } else { // Complex graph. 3 or more data.
366 switch ( $tipo_dato )
368 case '30': // Unused, at this time.
369 $result = $DB_bacula->link->query("select JobBytes,JobFiles,Jobid from Job where Name='$servidor' order by EndTime asc")
370 or die ("classes.inc: Error at query: 6");
371 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) )
372 $whole_result[] = array_merge($row["Jobid"],$row["JobFiles"],$row["JobBytes"]);
375 case BACULA_TYPE_BYTES_ENDTIME_ALLJOBS: // Special: Generic graph from all clientes.
376 $i = -1; // Counter of number of jobs of one cliente. SP: Contador del nmero de jobs totales de un cliente.
377 $i2 = 0; // Counter of number of keys of array. SP: Contador del nmero de valores del array.
379 if ($DB_bacula->driver == "mysql") {
380 $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")
381 or die ("classes.inc: Error at query: 7");
382 $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")
383 or die ("classes.inc: Error at query: 8");
385 else if ($DB_bacula->driver == "pgsql") {
386 $res = $DB_bacula->link->query("select Name from Job where EndTime > now() - interval '$this->elapsed seconds' group by Name order by Name desc")
387 or die ("classes.inc: Error at query: 8");
388 $resdata = $DB_bacula->link->query("select date(EndTime) from Job where EndTime > NOW() - interval '$this->elapsed seconds' group by EndTime order by EndTime")
389 or die ("classes.inc: Error at query: 9");
392 while ( $tmpdata = $res->fetchRow() )
393 array_push($this->clientes,$tmpdata[0]);
396 // print_r ($this->clientes);
400 $spr = array(); // Temporal array
401 $spr2 = array(); // Temporal array
402 $whole_result = array();
404 while ( $tmpdata = $resdata->fetchRow() ) {
406 array_push($spr,$tmpdata[0]);
407 if ($DB_bacula->driver == "mysql")
408 $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")
409 or die ("classes.inc: Error at query: 10");
410 else if ($DB_bacula->driver == "pgsql")
411 $result = $DB_bacula->link->query("select date(EndTime),SUM(JobBytes),Name,count(Name) as Nname from Job WHERE EndTime like '$tmpdata[0]%' group by EndTime,Name order by Name desc")
412 or die ("classes.inc: Error at query: 11");
413 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
414 $spr2 = array_merge($spr2,array($row["Name"]=>$row["SUM(JobBytes)"]));
415 $i = $result->numRows();
423 reset ($this->clientes);
425 if ( $spr2[current($this->clientes)] != NULL)
426 array_push($spr,$spr2[current($this->clientes)]);
429 } while ( next($this->clientes) );
434 if ( $tmpdata[0] != $row["EndTime"] )
435 array_push($whole_result,$spr);
441 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
442 $tmp = count($whole_result[$i]);
443 if ( $i2 < $tmp ) // Estupidez?. Check this code later...
446 for ( $a = 0; $a <= $tmp; $a++ )
447 array_push($whole_result[$i],"0"); // Fill the array
450 // echo "DEBUG:<br>";
452 // print_r ($whole_result);
461 return $whole_result;
466 //Conversi� de la fecha a Mysql-format para Smarty. THE SAME FUNCTION AT 2 CLASSES. THIS WAY IS BUGGY. TO SOLVE LATER.
467 function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear){
469 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
470 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
475 function array_merge_php4($array1,$array2) {
478 foreach(func_get_args() as $arg) {
482 foreach($arg as $key=>$val){