]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/classes.inc
Initial revision
[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
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
37
38
39         function Bweb() {
40                 
41                 $conf = new Config_File (CONFIG_DIR);
42                 
43                 
44                 $this->dsn[hostspec] = $conf->get(CONFIG_FILE,"DATABASE","host");
45                 $this->dsn[username] = $conf->get(CONFIG_FILE,"DATABASE","login");
46                 $this->dsn[password] = $conf->get(CONFIG_FILE,"DATABASE","pass");
47                 $this->dsn[database] = $conf->get(CONFIG_FILE,"DATABASE","db_name");
48                 $this->dsn[phptype] = $conf->get(CONFIG_FILE,"DATABASE","db_type");                     // mysql, (sqlite, pgsql) -->> Yet not checked
49                 if (  $conf->get(CONFIG_FILE,"DATABASE","db_port") )
50                         $this->dsn[port] = $conf->get(CONFIG_FILE,"DATABASE","db_port");
51                         
52                 $this->link =& $this->connect($this->dsn);
53                 
54                 if (DB::isError($this->link))
55                     die($this->link->getMessage());
56                                 
57                 register_shutdown_function(array(&$this,'close'));
58          }
59
60
61                 
62         function close() {
63
64                 $this->link->disconnect();
65          }      
66
67         
68          
69         function CalculateBytesPeriod($server,$StartDate,$EndPeriod) {                          // Bytes transferred in a period.
70
71                 $result =& $this->link->query("select SUM(JobBytes) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
72                         or die("Error query row 68");
73                 $return =& $result->fetchRow(); 
74                 return $return[0];
75          }//end function
76
77         
78          
79         function CalculateFilesPeriod($server,$StartDate,$EndPeriod) {                          // Number of files transferred in a period.
80
81                 $result =& $this->link->query("select SUM(JobFiles) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
82                         or die("Error query row 78");
83                 $return =& $result->fetchRow();
84                 return $return[0];
85          }//end function 
86
87                  
88
89         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) {  // Convert date for Smarty. Check if only works with Mysql.
90         
91                 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
92                 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59";  // last day full
93                 
94         }//end function
95  
96
97
98         function GetDataVolumes() {
99
100                 $volume = array();
101                 $res = $this->link->query("SELECT Name FROM Pool");
102                 while ( $tmp =& $res->fetchRow() ) {
103                         $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");
104                         while ( $tmp1 = $result->fetchRow() ) {
105                                 $pos = array_key_exists($tmp[0],$volume);
106                                 if ($pos != FALSE)
107                                         array_push($volume["$tmp[0]"],$tmp1);
108                                 else
109                                         $volume += array($tmp[0]=>array($tmp1));
110                         }
111                 }
112                 
113                 $res->free();
114                 $result->free();
115                 return $volume;
116         }
117         
118 }
119
120 class BGraph {
121
122         var $type;
123         var $sizex;
124         var $sizey;
125         var $MarginBottom;
126         var $MarginLeft;
127         var $Leg;
128
129
130         
131         function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
132         
133                 global $type;
134         
135                 require_once ("external_packages/phplot/phplot.php");
136
137                 if ( empty($this->sizex) || empty($this->sizey) ) {                                             //Default size
138                         $this->sizex = "600";
139                         $this->sizey = "400";
140                 }
141                 if ( empty($this->MarginBottom) ) {
142                         $this->MarginBottom = 120;
143                 }
144                 
145                 $legend = $leyenda;
146 //              $bgcolor = array(222,206,215);                                                                                  // Background color of graph
147                 $bgcolor = array(207,231,231);
148                 $fgcolor = array(110,41,57);
149                 
150
151                 
152                 $graph = new PHPlot($this->sizex,$this->sizey,"","");
153
154                 if ( !empty($type) )
155                         $graph->setDataType($type);
156
157                 $graph->SetDataValues($datos);
158                 $graph->SetPlotType($tipo);
159 //              $graph->SetUseTTF(1);
160                 $graph->SetBackgroundColor($bgcolor);
161
162                 $graph->SetLegendPixels(1,20);
163                 $graph->SetDataColors(array('SkyBlue','purple','PeachPuff','aquamarine1','#2CB04B','beige','#9F865F','#135568','orchid','navy','red', 'black', 'blue', 'green', 'brown', 'yellow','cyan','orange','#B9F5A7','#AFAFAF'));
164                 $graph->SetTitle($title);
165                 $graph->SetXLabel($xlabel);
166                 $graph->SetYLabel($ylabel);
167                 $graph->SetPlotAreaWorld("","","","");
168                 
169                 if ( count($datos) > 5 )
170                         $graph->SetXDataLabelAngle(90);
171                 else
172                         $graph->SetXDataLabelAngle(0);
173 //              $graph->SetNumXTicks(10);
174 //              $graph->SetXDataLabelPos('none');
175 //              $graph->SetXTickLabelPos('plotdown');
176                 
177 //              $graph->SetXGridLabelType("time");
178 //              $graph->SetXTimeFormat("%b ") ;
179
180                 if ( $this->Leg == 1 ) {
181                         $this->MarginLeftWithLegend($legend);
182                         $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
183                         $graph->SetLegend($legend);                     
184                 }
185                 else
186                         $graph->SetMarginsPixels(90,35,35,$this->MarginBottom);
187 //              $graph->SetDataColors(array($fgcolor),array( "black"));
188                 $graph->SetFileFormat( "png");
189 //              $graph->DoScaleData(1,1);
190 //              $graph->DoMovingAverage(1,1,1);
191                 $graph->DrawGraph();
192
193         }//end Crear
194
195
196 //Estupidez que tengo que cambiar. !!!!!!!!!!!
197         function SetDataType($typ) {
198                 
199                 global $type;
200                 $type = $typ;
201         }
202
203         function MarginLeftWithLegend($clients) {
204                 
205                 $maxlen = 0;
206                 
207                 while (next($clients)) {
208                         $tmp = strlen (current($clients));
209                         if ( $tmp > $maxlen )
210                                 $maxlen = $tmp;
211                 }
212                 $this->MarginLeft = $maxlen * 11;
213         }       
214
215 }//end class
216
217
218
219
220
221 class BCreateGraph extends BGraph {
222
223         var $BD_bacula;
224         var $izquierda;
225         var $derecha;
226         var $StartDate;
227         var $EndDate;
228         var $elapsed;                                                                                                                           // Default elapsed time to show complex graphs
229         
230         
231         
232         function BCreateGraph() {
233         
234                 $this->StartDate = "1900-01-01";
235                 $this->EndDate = "4000-01-01";
236                 $this->elapsed = "86400";                                                                                               // 24 hours in seconds.
237                 
238          }              
239          
240          
241          
242         function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
243         
244                 global $DB_bacula;
245                 global $izquierda;
246                 global $derecha;
247                 global $clientes;
248         
249                 $this->clientes=array();
250                 $DB_bacula = new Bweb();
251                 $datos = $this->SQLPrepareData($server,$tipo_dato);
252         
253                 if ( empty($datos) ) {                                                                                                  //No data = No stats = Empty graph
254                         header("Content-type: image/png");
255                         $img= @ImageCreate(200,100) or die ("Cannot intialize GD stream");
256                         $bgc= ImageColorAllocate($img, 0, 255,255);
257                         $txc= ImageColorAllocate($img, 0,0,0);
258                         ImageString($img, 5, 4, 4, "None data to process", $txc);
259                         ImagePng($img);
260                         ImageDestroy($img);
261                         return; 
262                 }
263         
264                 if ( empty ($xlabel) ) {                                                                                                // If no label, table names like leyends
265                         $xlabel=$derecha; $ylabel=$izquierda; 
266                 }                                                       
267                         
268                 $this->SetDataType("text-data");
269                 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
270                 
271         }
272
273
274  
275         function SQLPrepareData($servidor,$tipo_dato=0) {                                                       // Prepare bytes data from database.
276
277                 global $DB_bacula;
278                 global $izquierda;
279                 global $derecha;
280         
281                 if ( $tipo_dato<30 ) {                                                                                                  // Simple graph. Only 2 data 
282         
283                 switch ($tipo_dato)
284                                 {
285                                 case BACULA_TYPE_BYTES_FILES:
286                                         $izquierda="JobBytes";
287                                         $derecha="JobFiles";
288                                         break;
289                                 case BACULA_TYPE_FILES_JOBID:
290                                         $izquierda="JobFiles";
291                                         $derecha="Jobid";
292                                         break;
293                                 default:
294                                         $izquierda="JobBytes";
295                                         $derecha="EndTime";
296                                         break;
297                                 }
298                         $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")
299                                 or die ("Ivalid query row 295");
300                 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
301                         $whole_result[] = array_merge($row["$derecha"],$row[$izquierda]);
302                 }
303                 $result->free();
304         } else {                                                                                                                                // Complex graph. 3 or more data.
305                 
306                         switch ( $tipo_dato )
307                                 {
308                                 case '30':                                                                                                              // Unused, at this time.
309                                         $result = $DB_bacula->link->query("select JobBytes,JobFiles,Jobid from Job where Name='$servidor' order by EndTime asc")
310                                                 or die ("Invalid query row 306");
311                                         while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) )
312                                                 $whole_result[] = array_merge($row["Jobid"],$row["JobFiles"],$row["JobBytes"]);
313                                         $result->free();
314                                         break;
315                                 case BACULA_TYPE_BYTES_ENDTIME_ALLJOBS:                                                 // Special: Generic graph from all clientes.
316                                         $i = -1;                                                                                                        // Counter of number of jobs of one cliente. SP: Contador del número de jobs totales de un cliente.
317                                         $i2 = 0;                                                                                                        // Counter of number of keys of array. SP: Contador del número de valores del array.
318                                         
319                                         $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")
320                                                 or die ("Invalid query row 316");
321                                         $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")
322                                                 or die ("Invalid query row 318");
323                                         
324                                         while ( $tmpdata = $res->fetchRow() )
325                                                 array_push($this->clientes,$tmpdata[0]);
326                                                 
327 //                                      echo "<pre>";
328 //                                      print_r ($this->clientes);
329 //                                      echo "</pre>";
330                                         
331                                         
332                                         $spr = array();                                                                                         // Temporal array
333                                         $spr2 = array();                                                                                        // Temporal array
334                                         $whole_result = array();
335                                         
336                                         while ( $tmpdata = $resdata->fetchRow() ) {
337                                                 $count++;
338                                                 array_push($spr,$tmpdata[0]);
339                                                 $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")
340                                                         or die ("invalid query row 336");
341                                                 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
342                                                         $spr2 = array_merge($spr2,array($row["Name"]=>$row["SUM(JobBytes)"]));
343                                                         $i = $result->numRows();
344                                                 }
345
346                                         
347 //                                              echo "<pre>";
348 //                                              print_r ($spr2);
349 //                                              echo "</pre>";
350                                                 
351                                                 reset ($this->clientes);                                                                
352                                                 do { 
353                                                         if ( $spr2[current($this->clientes)] != NULL)
354                                                                 array_push($spr,$spr2[current($this->clientes)]);
355                                                         else
356                                                                 array_push($spr,0);
357                                                 } while ( next($this->clientes) );
358                                                 
359                                                 if ( $i2 < $i )
360                                                         $i2 = $i;
361                                                 
362                                                 if ( $tmpdata[0] != $row["EndTime"] )   
363                                                         array_push($whole_result,$spr);
364                                                 
365                                                 $spr = array();
366                                                 $spr2 = array();
367                                         }
368                                 
369                                         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
370                                                 $tmp = count($whole_result[$i]);
371                                                 if ( $i2 < $tmp )                                                                               // Estupidez?. Check this code later...
372                                                         continue;
373                                                 $tmp = $i2 - $tmp;
374                                                 for ( $a = 0; $a <= $tmp; $a++ )
375                                                         array_push($whole_result[$i],"0");                                      // Fill the array
376                                         }
377                                         $resdata->free();       
378 //                                      echo "DEBUG:<br>";
379 //                                      echo "<pre>";
380 //                                      print_r ($whole_result);
381 //                                      echo "</pre>";  
382                                         break;
383                                 
384                                 default:
385                                         break;
386                         }
387                 }
388 //      $result->free();
389           return $whole_result;
390         }//end function
391
392
393
394         //Conversión de la fecha a Mysql-format para Smarty.            THE SAME FUNCTION AT 2 CLASSES. THIS WAY IS BUGGY. TO SOLVE LATER.
395         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear){
396         
397                 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
398                 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
399                 
400         }//end function
401
402
403 }//end class
404
405 ?>