]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/classes.inc
Apply bacula-web 1.2 updates
[bacula/bacula] / gui / bacula-web / classes.inc
1 <?
2 /* 
3 +-------------------------------------------------------------------------+
4 | Copyright (C) 2004 Juan Luis Francés Jiménez                            |
5 |                                                                         |
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.                  |
10 |                                                                         |
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 +-------------------------------------------------------------------------+ 
16 */
17 // Last Err: 11
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);
23
24 require_once "paths.php";
25 require_once "DB.php";                                                                                                                  // Pear DB
26 require_once($smarty_path."Config_File.class.php");
27
28 if (!function_exists('array_fill')) {                                                                                   // For PHP < 4.2.0 users 
29     require_once('array_fill.func.php');
30 }
31
32 class Bweb extends DB {
33
34         var $StartDate;
35         var $EndDate;
36         var $driver;
37
38
39
40         function Bweb() {
41                 
42                 $conf = new Config_File (CONFIG_DIR);
43                 
44                 
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");
52                         
53                 $this->link =& $this->connect($this->dsn);
54                 
55                 if (DB::isError($this->link))
56                     die($this->link->getMessage());
57                 $this->driver = $this->dsn[phptype];                            
58                 register_shutdown_function(array(&$this,'close'));
59          }
60
61
62                 
63         function close() {
64
65                 $this->link->disconnect();
66          }      
67
68         
69          
70         function CalculateBytesPeriod($server,$StartDate,$EndPeriod) {                          // Bytes transferred in a period.
71
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(); 
75                 return $return[0];
76          }//end function
77
78         
79          
80         function CalculateFilesPeriod($server,$StartDate,$EndPeriod) {                          // Number of files transferred in a period.
81
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();
85                 return $return[0];
86          }//end function 
87
88                  
89
90         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) {  // Convert date for Smarty. Check if only works with Mysql.
91         
92                 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
93                 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59";  // last day full
94                 
95         }//end function
96  
97
98
99         function GetDataVolumes() {
100
101                 $volume = array();
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);
110                                 if ($pos != FALSE)
111                                         array_push($volume["$tmp[0]"],$tmp1);
112                                 else
113                                         $volume += array($tmp[0]=>array($tmp1));
114                         }
115                 }
116                 
117                 $res->free();
118                 $result->free();
119                 return $volume;
120         }
121         
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];
129                         }
130                         else
131                                 return 0;
132                 }
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];
139                         }
140                         else
141                                 return 0;
142                 }       
143         $dbsize->free();
144         return $database_size;  
145         }
146
147 }
148
149 class BGraph {
150
151         var $type;
152         var $sizex;
153         var $sizey;
154         var $MarginBottom;
155         var $MarginLeft;
156         var $Leg;
157
158
159         
160         function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
161         
162                 global $type;
163         
164                 require_once ("external_packages/phplot/phplot.php");
165
166                 if ( empty($this->sizex) || empty($this->sizey) ) {                                             //Default size
167                         $this->sizex = "600";
168                         $this->sizey = "400";
169                 }
170                 if ( empty($this->MarginBottom) ) {
171                         $this->MarginBottom = 120;
172                 }
173                 
174                 $legend = $leyenda;
175 //              $bgcolor = array(222,206,215);                                                                                  // Background color of graph
176                 $bgcolor = array(207,231,231);
177                 $fgcolor = array(110,41,57);
178                 
179
180                 
181                 $graph = new PHPlot($this->sizex,$this->sizey,"","");
182
183                 if ( !empty($type) )
184                         $graph->setDataType($type);
185
186                 $graph->SetDataValues($datos);
187                 $graph->SetPlotType($tipo);
188 //              $graph->SetUseTTF(1);
189                 $graph->SetBackgroundColor($bgcolor);
190
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("","","","");
197                 
198                 if ( count($datos) > 5 )
199                         $graph->SetXDataLabelAngle(90);
200                 else
201                         $graph->SetXDataLabelAngle(0);
202 //              $graph->SetNumXTicks(10);
203 //              $graph->SetXDataLabelPos('none');
204 //              $graph->SetXTickLabelPos('plotdown');
205                 
206 //              $graph->SetXGridLabelType("time");
207 //              $graph->SetXTimeFormat("%b ") ;
208
209                 if ( $this->Leg == 1 ) {
210                         $this->MarginLeftWithLegend($legend);
211                         $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
212                         $graph->SetLegend($legend);                     
213                 }
214                 else
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);
220
221 //              FIX ME -- to round y axis.
222                 $vtick = strlen (round ($graph->max_y));
223                 $res = 1;
224                 for ($i=1;$i < $vtick; $i++)
225                         $res = $res*10;
226                 if (strlen($graph->max_y-$res) != $vtick )
227                         $res = $res/10;
228                 $graph->SetVertTickIncrement($res);
229                 $graph->DrawGraph();
230
231         }//end Crear
232
233
234 //Estupidez que tengo que cambiar. !!!!!!!!!!!
235         function SetDataType($typ) {
236                 
237                 global $type;
238                 $type = $typ;
239         }
240
241         function MarginLeftWithLegend($clients) {
242                 
243                 $maxlen = 0;
244                 
245                 while (next($clients)) {
246                         $tmp = strlen (current($clients));
247                         if ( $tmp > $maxlen )
248                                 $maxlen = $tmp;
249                 }
250                 $this->MarginLeft = $maxlen * 11;
251         }       
252
253 }//end class
254
255
256
257
258
259 class BCreateGraph extends BGraph {
260
261         var $BD_bacula;
262         var $izquierda;
263         var $derecha;
264         var $StartDate;
265         var $EndDate;
266         var $elapsed;                                                                                                                           // Default elapsed time to show complex graphs
267         
268         
269         
270         function BCreateGraph() {
271         
272                 $this->StartDate = "1900-01-01";
273                 $this->EndDate = "4000-01-01";
274                 $this->elapsed = "86400";                                                                                               // 24 hours in seconds.
275                 
276          }              
277          
278          
279          
280         function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
281         
282                 global $DB_bacula;
283                 global $izquierda;
284                 global $derecha;
285                 global $clientes;
286         
287                 $this->clientes=array();
288                 $DB_bacula = new Bweb();
289                 $datos = $this->SQLPrepareData($server,$tipo_dato);
290         
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);
297                         ImagePng($img);
298                         ImageDestroy($img);
299                         return; 
300                 }
301         
302                 if ( empty ($xlabel) ) {                                                                                                // If no label, table names like leyends
303                         $xlabel=$derecha; $ylabel=$izquierda; 
304                 }                                                       
305                         
306                 $this->SetDataType("text-data");
307                 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
308                 
309         }
310
311
312  
313         function SQLPrepareData($servidor,$tipo_dato=0) {                                                       // Prepare bytes data from database.
314
315                 global $DB_bacula;
316                 global $izquierda;
317                 global $derecha;
318         
319                 if ( $tipo_dato<30 ) {                                                                                                  // Simple graph. Only 2 data 
320         
321                 switch ($tipo_dato)
322                                 {
323                                 case BACULA_TYPE_BYTES_FILES:
324                                         $izquierda="jobbytes";
325                                         $derecha="jobfiles";
326                                         break;
327                                 case BACULA_TYPE_FILES_JOBID:
328                                         $izquierda="jobfiles";
329                                         $derecha="jobid";
330                                         break;
331                                 default:
332                                         $izquierda="jobbytes";
333                                         $derecha="endtime";
334                                         break;
335                                 }
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]);
340                 }
341                 $result->free();
342         } else {                                                                                                                                // Complex graph. 3 or more data.
343                 
344                         switch ( $tipo_dato )
345                                 {
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"]);
351                                         $result->free();
352                                         break;
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 número de jobs totales de un cliente.
355                                         $i2 = 0;                                                                                                        // Counter of number of keys of array. SP: Contador del número de valores del array.
356                                         
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");
365                                         
366                                         while ( $tmpdata = $res->fetchRow() )
367                                                 array_push($this->clientes,$tmpdata[0]);
368                                                 
369 //                                      echo "<pre>";
370 //                                      print_r ($this->clientes);
371 //                                      echo "</pre>";
372                                         
373                                         
374                                         $spr = array();                                                                                         // Temporal array
375                                         $spr2 = array();                                                                                        // Temporal array
376                                         $whole_result = array();
377                                         
378                                         while ( $tmpdata = $resdata->fetchRow() ) {
379                                                 $count++;
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();
390                                                 }
391
392                                         
393 //                                              echo "<pre>";
394 //                                              print_r ($spr2);
395 //                                              echo "</pre>";
396                                                 
397                                                 reset ($this->clientes);                                                                
398                                                 do { 
399                                                         if ( $spr2[current($this->clientes)] != NULL)
400                                                                 array_push($spr,$spr2[current($this->clientes)]);
401                                                         else
402                                                                 array_push($spr,0);
403                                                 } while ( next($this->clientes) );
404                                                 
405                                                 if ( $i2 < $i )
406                                                         $i2 = $i;
407                                                 
408                                                 if ( $tmpdata[0] != $row["EndTime"] )   
409                                                         array_push($whole_result,$spr);
410                                                 
411                                                 $spr = array();
412                                                 $spr2 = array();
413                                         }
414                                 
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áfica no se descuadre
416                                                 $tmp = count($whole_result[$i]);
417                                                 if ( $i2 < $tmp )                                                                               // Estupidez?. Check this code later...
418                                                         continue;
419                                                 $tmp = $i2 - $tmp;
420                                                 for ( $a = 0; $a <= $tmp; $a++ )
421                                                         array_push($whole_result[$i],"0");                                      // Fill the array
422                                         }
423                                         $resdata->free();       
424 //                                      echo "DEBUG:<br>";
425 //                                      echo "<pre>";
426 //                                      print_r ($whole_result);
427 //                                      echo "</pre>";  
428                                         break;
429                                 
430                                 default:
431                                         break;
432                         }
433                 }
434 //      $result->free();
435           return $whole_result;
436         }//end function
437
438
439
440         //Conversión 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){
442         
443                 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
444                 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
445                 
446         }//end function
447
448
449         function array_merge_php4($array1,$array2) {
450             $return=array();
451
452             foreach(func_get_args() as $arg) {
453                 if(!is_array($arg)){
454                 $arg=array($arg);
455                 }
456                     foreach($arg as $key=>$val){
457                             if(!is_int($key)){
458                                 $return[$key]=$val;
459                             }else{
460                                 $return[]=$val;
461                             }
462                     }
463             }
464         return $return;
465         }
466
467 }//end class
468
469 ?>