]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/classes.inc
bacula-web:Changed css classes for header and boxes
[bacula/bacula] / gui / bacula-web / classes.inc
1 <?php
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         var $dbs_name;
39
40
41
42         function Bweb() {
43                 
44                 $conf = new Config_File (CONFIG_DIR);
45                 $this->dbs = array();
46                 $i = 2;
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);
53                         $i++;
54                 }
55
56                 if ( $i < 4)
57                         $sec = "DATABASE";
58                 else {
59                         if ( !empty($_POST['sel_database']) ) {
60                                 $_SESSION['DATABASE'] = $_POST['sel_database'];
61                                 $sec = $_POST['sel_database'];
62                         } else {
63                                 if (isset($_SESSION['DATABASE']) )
64                                         $sec = $_SESSION['DATABASE'];
65                                 else
66                                         $sec = "DATABASE";
67                         }
68                 }
69
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");
77                         
78                 $this->link =& $this->connect($this->dsn);
79                 
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'];
85         }
86                 
87         function close() {
88
89                 $this->link->disconnect();
90         }      
91
92         
93          
94         function CalculateBytesPeriod($server,$StartDate,$EndPeriod) {   // Bytes transferred in a period.
95
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(); 
99                 return $return[0];
100         }//end function
101
102         
103          
104         function CalculateFilesPeriod($server,$StartDate,$EndPeriod) {    // Number of files transferred in a period.
105
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();
109                 return $return[0];
110         }//end function 
111
112                  
113
114         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) {  // Convert date for Smarty. Check if only works with Mysql.
115         
116                 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
117                 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59";  // last day full
118                 
119         }//end function
120  
121
122
123         function GetDataVolumes() {
124
125                 $volume = array();
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);
134                                 if ($pos != FALSE)
135                                         array_push($volume["$tmp[0]"],$tmp1);
136                                 else
137                                         $volume += array($tmp[0]=>array($tmp1));
138                         }
139                 }
140                 
141                 $res->free();
142                 $result->free();
143                 return $volume;
144         }
145         
146                 function human_file_size( $size, $decimal = 2 )
147                 {
148                         $unit_id = 0;
149                         $lisible = false;
150                         $units = array('B','KB','MB','GB','TB');
151                         $hsize = $size;
152                                 
153                         while( !$lisible ) {
154                                 if ( $hsize >= 1024 ) {
155                                         $hsize    = $hsize / 1024;
156                                         $unit_id += 1;
157                                 } 
158                                 else {
159                                         $lisible = true;
160                                 } 
161                         } 
162                         // Format human size
163                         $hsize = sprintf("%." . $decimal . "f", $hsize);
164                         return $hsize . ' ' . $units[$unit_id];
165                 } // end function
166
167                 
168                 function GetDbSize() 
169                 {
170                         $database_size = 0;
171                         if ( $this->driver == "mysql") {
172                                 $dbsize = $this->link->query("show table status") or die ("classes.inc: Error query: 3");
173                                 
174                                 if ( $dbsize->numRows() ) {
175                                         while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
176                                                 $database_size += $res["Data_length"];
177                 } else {
178                                         return 0;
179                                 } // end if else
180             } // end if
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");
183                                 
184                                 if (PEAR::isError($dbsize))
185                                         die($dbsize->getMessage());
186                     
187                                         if ( $dbsize->numRows() ) {
188                                                 while ( $res = $dbsize->fetchRow() )
189                                                         $database_size += $res[0];
190                     } else {
191                                                 return 0;
192                                         }
193             } // end if       
194                                 
195                         $dbsize->free();
196                 
197                         return $this->human_file_size( $database_size );  
198         } // end function GetDbSize()
199                 
200 } // end class Bweb
201
202 class BGraph {
203
204         var $type;
205         var $sizex;
206         var $sizey;
207         var $MarginBottom;
208         var $MarginLeft;
209         var $Leg;
210
211
212         
213         function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
214         
215                 global $type;
216         
217                 require_once ("external_packages/phplot/phplot.php");
218
219                 if ( empty($this->sizex) || empty($this->sizey) ) {    //Default size
220                         $this->sizex = "600";
221                         $this->sizey = "400";
222                 }
223                 if ( empty($this->MarginBottom) ) {
224                         $this->MarginBottom = 120;
225                 }
226                 
227                 $legend = $leyenda;
228 //              $bgcolor = array(222,206,215);      // Background color of graph
229                 $bgcolor = array(207,231,231);
230                 $fgcolor = array(110,41,57);
231                 
232
233                 
234                 $graph = new PHPlot($this->sizex,$this->sizey,"","");
235
236                 if ( !empty($type) )
237                         $graph->setDataType($type);
238
239                 $graph->SetDataValues($datos);
240                 $graph->SetPlotType($tipo);
241 //              $graph->SetUseTTF(1);
242                 $graph->SetBackgroundColor($bgcolor);
243
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("","","","");
250                 
251                 if ( count($datos) > 5 )
252                         $graph->SetXDataLabelAngle(90);
253                 else
254                         $graph->SetXDataLabelAngle(0);
255                 $graph->SetNumXTicks(1);
256 //              $graph->SetXDataLabelPos('none');
257 //              $graph->SetXTickLabelPos('plotdown');
258                 
259 //              $graph->SetXGridLabelType("time");
260 //              $graph->SetXTimeFormat("%b ") ;
261
262                 if ( $this->Leg == 1 ) {
263                         $this->MarginLeftWithLegend($legend);
264                         $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
265                         $graph->SetLegend($legend);
266                                 }
267                 else
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);
273
274 //              FIX ME -- to round y axis.
275                 $vtick = strlen (round ($graph->max_y));
276                 $res = 1;
277                 for ($i=1;$i < $vtick; $i++)
278                         $res = $res*10;
279                 if (strlen($graph->max_y-$res) != $vtick )
280                         $res = $res/10;
281                 $graph->SetVertTickIncrement($res);
282                 $graph->DrawGraph();
283
284         }//end Crear
285
286
287 //Estupidez que tengo que cambiar. !!!!!!!!!!!
288         function SetDataType($typ) {
289                 
290                 global $type;
291                 $type = $typ;
292         }
293
294         function MarginLeftWithLegend($clients) {
295                 
296                 $maxlen = 0;
297                 
298                 while (next($clients)) {
299                         $tmp = strlen(current($clients));
300                         if ( $tmp > $maxlen )
301                                 $maxlen = $tmp;
302                 }
303                 $this->MarginLeft = $maxlen * 9;
304         }       
305
306 }//end class
307
308
309
310
311
312 class BCreateGraph extends BGraph {
313
314         var $BD_bacula;
315         var $izquierda;
316         var $derecha;
317         var $StartDate;
318         var $EndDate;
319         var $elapsed;                        // Default elapsed time to show complex graphs
320         
321         
322         
323         function BCreateGraph() {
324         
325                 $this->StartDate = "1900-01-01";
326                 $this->EndDate = "4000-01-01";
327                 $this->elapsed = "86400";                   // 24 hours in seconds.
328                 
329          }              
330          
331          
332          
333         function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
334         
335                 global $DB_bacula;
336                 global $izquierda;
337                 global $derecha;
338                 global $clientes;
339         
340                 $this->clientes=array();
341                 $DB_bacula = new Bweb();
342                 $datos = $this->SQLPrepareData($server,$tipo_dato);
343         
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);
350                         ImagePng($img);
351                         ImageDestroy($img);
352                         return; 
353                 }
354         
355                 if ( empty ($xlabel) ) {                       // If no label, table names like leyends
356                         $xlabel=$derecha; $ylabel=$izquierda; 
357                 } 
358                         
359                 $this->SetDataType("text-data");
360                 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
361                 
362         }
363
364
365  
366         function SQLPrepareData($servidor,$tipo_dato=0) {         // Prepare bytes data from database.
367
368                 global $DB_bacula;
369                 global $izquierda;
370                 global $derecha;
371         
372                 if ( $tipo_dato<30 ) {               // Simple graph. Only 2 data 
373         
374                 switch ($tipo_dato)
375                                 {
376                                 case BACULA_TYPE_BYTES_FILES:
377                                         $izquierda="jobbytes";
378                                         $derecha="jobfiles";
379                                         break;
380                                 case BACULA_TYPE_FILES_JOBID:
381                                         $izquierda="jobfiles";
382                                         $derecha="jobid";
383                                         break;
384                                 default:
385                                         $izquierda="jobbytes";
386                                         $derecha="endtime";
387                                         break;
388                                 }
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]);
393                 }
394                 $result->free();
395         } else {                                                // Complex graph. 3 or more data.
396                 
397                         switch ( $tipo_dato )
398                                 {
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"]);
404                                         $result->free();
405                                         break;
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.
409                                         
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");
415                                         }
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");
421                                         }
422                                         
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]);
427                                                 
428 //                                      echo "<pre>";
429 //                                      print_r ($this->clientes);
430 //                                      echo "</pre>";
431                                         
432                                         
433                                         $spr = array();                        // Temporal array
434                                         $spr2 = array();                       // Temporal array
435                                         $whole_result = array();
436                                         
437                                         while ( $tmpdata = $resdata->fetchRow() ) {
438                                                 $count++;
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");
447                                                 }
448                                                 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
449                                                         $spr2 = array_merge($spr2,array($row["name"]=>$row["sum"]));
450                                                         $i = $result->numRows();
451                                                 }
452
453                                         
454 //                                              echo "<pre>";
455 //                                              print_r ($spr2);
456 //                                              echo "</pre>";
457                                                 
458                                                 reset ($this->clientes);        
459                                                 do {
460                                                         if ( $spr2[current($this->clientes)] != NULL)
461                                                                 array_push($spr,$spr2[current($this->clientes)]);
462                                                         else
463                                                                 array_push($spr,0);
464                                                 } while ( next($this->clientes) );
465                                                 
466                                                 if ( $i2 < $i )
467                                                         $i2 = $i;
468                                                 
469                                                 if ( $tmpdata[0] != $row["EndTime"] )   
470                                                         array_push($whole_result,$spr);
471                                                 
472                                                 $spr = array();
473                                                 $spr2 = array();
474                                         }
475
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...
479                                                         continue;
480                                                 $tmp = $i2 - $tmp;
481                                                 for ( $a = 0; $a <= $tmp; $a++ )
482                                                         array_push($whole_result[$i],"0");                                      // Fill the array
483                                         }
484                                         $resdata->free();       
485 //                                      echo "DEBUG:<br>";
486 //                                      echo "<pre>";
487 //                                      print_r ($whole_result);
488 //                                      echo "</pre>";  
489                                         break;
490                                 
491                                 default:
492                                         break;
493                         }
494                 }
495 //      $result->free();
496           return $whole_result;
497         }//end function
498
499
500
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){
503         
504                 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
505                 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
506                 
507         }//end function
508
509
510         function array_merge_php4($array1,$array2) {
511             $return=array();
512
513             foreach(func_get_args() as $arg) {
514                 if(!is_array($arg)){
515                 $arg=array($arg);
516                 }
517                     foreach($arg as $key=>$val){
518                             if(!is_int($key)){
519                                 $return[$key]=$val;
520                             }else{
521                                 $return[]=$val;
522                             }
523                     }
524             }
525         return $return;
526         }
527
528 }//end class
529
530 ?>