]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/classes.inc
Update
[bacula/bacula] / gui / bacula-web / classes.inc
1 <?
2 /* 
3 +-------------------------------------------------------------------------+
4 | Copyright (C) 2004-2005 Juan Luis Frances Jiminez                       |
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         var $dbs;
38
39
40
41         function Bweb() {
42                 
43                 $conf = new Config_File (CONFIG_DIR);
44                 $this->dbs = array();
45                 $i = 2;
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);
52                         $i++;
53                 }
54
55                 if ( $i < 4)
56                         $sec = "DATABASE";
57                 else {
58                         if ( !empty($_POST['sel_database']) ) {
59                                 $_SESSION['DATABASE'] = $_POST['sel_database'];
60                                 $sec = $_POST['sel_database'];
61                         } else {
62                                 if (isset($_SESSION['DATABASE']) )
63                                         $sec = $_SESSION['DATABASE'];
64                                 else
65                                         $sec = "DATABASE";
66                         }
67                 }
68
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");
76                         
77                 $this->link =& $this->connect($this->dsn);
78                 
79                 if (DB::isError($this->link))
80                     die($this->link->getMessage());
81                 $this->driver = $this->dsn[phptype];                            
82                 register_shutdown_function(array(&$this,'close'));
83         }
84                 
85         function close() {
86
87                 $this->link->disconnect();
88         }      
89
90         
91          
92         function CalculateBytesPeriod($server,$StartDate,$EndPeriod) {   // Bytes transferred in a period.
93
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(); 
97                 return $return[0];
98         }//end function
99
100         
101          
102         function CalculateFilesPeriod($server,$StartDate,$EndPeriod) {    // Number of files transferred in a period.
103
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();
107                 return $return[0];
108         }//end function 
109
110                  
111
112         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) {  // Convert date for Smarty. Check if only works with Mysql.
113         
114                 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
115                 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59";  // last day full
116                 
117         }//end function
118  
119
120
121         function GetDataVolumes() {
122
123                 $volume = array();
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);
132                                 if ($pos != FALSE)
133                                         array_push($volume["$tmp[0]"],$tmp1);
134                                 else
135                                         $volume += array($tmp[0]=>array($tmp1));
136                         }
137                 }
138                 
139                 $res->free();
140                 $result->free();
141                 return $volume;
142         }
143         
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"];
151                         }
152                         else
153                                 return 0;
154                 }
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];
161                         }
162                         else
163                                 return 0;
164                 }       
165         $dbsize->free();
166         return $database_size;  
167         }
168
169 }
170
171 class BGraph {
172
173         var $type;
174         var $sizex;
175         var $sizey;
176         var $MarginBottom;
177         var $MarginLeft;
178         var $Leg;
179
180
181         
182         function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
183         
184                 global $type;
185         
186                 require_once ("external_packages/phplot/phplot.php");
187
188                 if ( empty($this->sizex) || empty($this->sizey) ) {    //Default size
189                         $this->sizex = "600";
190                         $this->sizey = "400";
191                 }
192                 if ( empty($this->MarginBottom) ) {
193                         $this->MarginBottom = 120;
194                 }
195                 
196                 $legend = $leyenda;
197 //              $bgcolor = array(222,206,215);      // Background color of graph
198                 $bgcolor = array(207,231,231);
199                 $fgcolor = array(110,41,57);
200                 
201
202                 
203                 $graph = new PHPlot($this->sizex,$this->sizey,"","");
204
205                 if ( !empty($type) )
206                         $graph->setDataType($type);
207
208                 $graph->SetDataValues($datos);
209                 $graph->SetPlotType($tipo);
210 //              $graph->SetUseTTF(1);
211                 $graph->SetBackgroundColor($bgcolor);
212
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("","","","");
219                 
220                 if ( count($datos) > 5 )
221                         $graph->SetXDataLabelAngle(90);
222                 else
223                         $graph->SetXDataLabelAngle(0);
224 //              $graph->SetNumXTicks(10);
225 //              $graph->SetXDataLabelPos('none');
226 //              $graph->SetXTickLabelPos('plotdown');
227                 
228 //              $graph->SetXGridLabelType("time");
229 //              $graph->SetXTimeFormat("%b ") ;
230
231                 if ( $this->Leg == 1 ) {
232                         $this->MarginLeftWithLegend($legend);
233                         $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
234                         $graph->SetLegend($legend);
235                                 }
236                 else
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);
242
243 //              FIX ME -- to round y axis.
244                 $vtick = strlen (round ($graph->max_y));
245                 $res = 1;
246                 for ($i=1;$i < $vtick; $i++)
247                         $res = $res*10;
248                 if (strlen($graph->max_y-$res) != $vtick )
249                         $res = $res/10;
250                 $graph->SetVertTickIncrement($res);
251                 $graph->DrawGraph();
252
253         }//end Crear
254
255
256 //Estupidez que tengo que cambiar. !!!!!!!!!!!
257         function SetDataType($typ) {
258                 
259                 global $type;
260                 $type = $typ;
261         }
262
263         function MarginLeftWithLegend($clients) {
264                 
265                 $maxlen = 0;
266                 
267                 while (next($clients)) {
268                         $tmp = strlen(current($clients));
269                         if ( $tmp > $maxlen )
270                                 $maxlen = $tmp;
271                 }
272                 $this->MarginLeft = $maxlen * 9;
273         }       
274
275 }//end class
276
277
278
279
280
281 class BCreateGraph extends BGraph {
282
283         var $BD_bacula;
284         var $izquierda;
285         var $derecha;
286         var $StartDate;
287         var $EndDate;
288         var $elapsed;                        // Default elapsed time to show complex graphs
289         
290         
291         
292         function BCreateGraph() {
293         
294                 $this->StartDate = "1900-01-01";
295                 $this->EndDate = "4000-01-01";
296                 $this->elapsed = "86400";                   // 24 hours in seconds.
297                 
298          }              
299          
300          
301          
302         function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
303         
304                 global $DB_bacula;
305                 global $izquierda;
306                 global $derecha;
307                 global $clientes;
308         
309                 $this->clientes=array();
310                 $DB_bacula = new Bweb();
311                 $datos = $this->SQLPrepareData($server,$tipo_dato);
312         
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);
319                         ImagePng($img);
320                         ImageDestroy($img);
321                         return; 
322                 }
323         
324                 if ( empty ($xlabel) ) {                       // If no label, table names like leyends
325                         $xlabel=$derecha; $ylabel=$izquierda; 
326                 } 
327                         
328                 $this->SetDataType("text-data");
329                 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
330                 
331         }
332
333
334  
335         function SQLPrepareData($servidor,$tipo_dato=0) {         // Prepare bytes data from database.
336
337                 global $DB_bacula;
338                 global $izquierda;
339                 global $derecha;
340         
341                 if ( $tipo_dato<30 ) {               // Simple graph. Only 2 data 
342         
343                 switch ($tipo_dato)
344                                 {
345                                 case BACULA_TYPE_BYTES_FILES:
346                                         $izquierda="jobbytes";
347                                         $derecha="jobfiles";
348                                         break;
349                                 case BACULA_TYPE_FILES_JOBID:
350                                         $izquierda="jobfiles";
351                                         $derecha="jobid";
352                                         break;
353                                 default:
354                                         $izquierda="jobbytes";
355                                         $derecha="endtime";
356                                         break;
357                                 }
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]);
362                 }
363                 $result->free();
364         } else {                                                // Complex graph. 3 or more data.
365                 
366                         switch ( $tipo_dato )
367                                 {
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"]);
373                                         $result->free();
374                                         break;
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.
378                                         
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");
384                                         }
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");
390                                         }
391                                         
392                                         while ( $tmpdata = $res->fetchRow() )
393                                                 array_push($this->clientes,$tmpdata[0]);
394                                                 
395 //                                      echo "<pre>";
396 //                                      print_r ($this->clientes);
397 //                                      echo "</pre>";
398                                         
399                                         
400                                         $spr = array();                        // Temporal array
401                                         $spr2 = array();                       // Temporal array
402                                         $whole_result = array();
403                                         
404                                         while ( $tmpdata = $resdata->fetchRow() ) {
405                                                 $count++;
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();
416                                                 }
417
418                                         
419 //                                              echo "<pre>";
420 //                                              print_r ($spr2);
421 //                                              echo "</pre>";
422                                                 
423                                                 reset ($this->clientes);        
424                                                                                                 do { 
425                                                         if ( $spr2[current($this->clientes)] != NULL)
426                                                                 array_push($spr,$spr2[current($this->clientes)]);
427                                                         else
428                                                                 array_push($spr,0);
429                                                 } while ( next($this->clientes) );
430                                                 
431                                                 if ( $i2 < $i )
432                                                         $i2 = $i;
433                                                 
434                                                 if ( $tmpdata[0] != $row["EndTime"] )   
435                                                         array_push($whole_result,$spr);
436                                                 
437                                                 $spr = array();
438                                                 $spr2 = array();
439                                         }
440                                 
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...
444                                                         continue;
445                                                 $tmp = $i2 - $tmp;
446                                                 for ( $a = 0; $a <= $tmp; $a++ )
447                                                         array_push($whole_result[$i],"0");                                      // Fill the array
448                                         }
449                                         $resdata->free();       
450 //                                      echo "DEBUG:<br>";
451 //                                      echo "<pre>";
452 //                                      print_r ($whole_result);
453 //                                      echo "</pre>";  
454                                         break;
455                                 
456                                 default:
457                                         break;
458                         }
459                 }
460 //      $result->free();
461           return $whole_result;
462         }//end function
463
464
465
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){
468         
469                 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
470                 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
471                 
472         }//end function
473
474
475         function array_merge_php4($array1,$array2) {
476             $return=array();
477
478             foreach(func_get_args() as $arg) {
479                 if(!is_array($arg)){
480                 $arg=array($arg);
481                 }
482                     foreach($arg as $key=>$val){
483                             if(!is_int($key)){
484                                 $return[$key]=$val;
485                             }else{
486                                 $return[]=$val;
487                             }
488                     }
489             }
490         return $return;
491         }
492
493 }//end class
494
495 ?>