]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/classes.inc
- (0000019,0000021) Fixed psql querys.
[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         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 GetDbSize() {
147                 if ( $this->driver == "mysql") {
148                         $dbsize = $this->link->query("show table status")
149                                 or die ("classes.inc: Error query: 3");
150                         if ( $dbsize->numRows() ) {
151                                 while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
152                                         $database_size += $res["Data_length"];
153                         }
154                         else
155                                 return 0;
156                 }
157                 else if ( $this->driver == "pgsql") {
158                         $dbsize = $this->link->query("select pg_database_size('$this->dbs_name')")
159                                 or die ("classes.inc: Error query: 4");
160                         if (PEAR::isError($dbsize))
161                             die($dbsize->getMessage());
162                         if ( $dbsize->numRows() ) {
163                                 while ( $res = $dbsize->fetchRow() )
164                                         $database_size += $res[0];
165                         }
166                         else
167                                 return 0;
168                 }       
169         $dbsize->free();
170         return $database_size;  
171         }
172
173 }
174
175 class BGraph {
176
177         var $type;
178         var $sizex;
179         var $sizey;
180         var $MarginBottom;
181         var $MarginLeft;
182         var $Leg;
183
184
185         
186         function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
187         
188                 global $type;
189         
190                 require_once ("external_packages/phplot/phplot.php");
191
192                 if ( empty($this->sizex) || empty($this->sizey) ) {    //Default size
193                         $this->sizex = "600";
194                         $this->sizey = "400";
195                 }
196                 if ( empty($this->MarginBottom) ) {
197                         $this->MarginBottom = 120;
198                 }
199                 
200                 $legend = $leyenda;
201 //              $bgcolor = array(222,206,215);      // Background color of graph
202                 $bgcolor = array(207,231,231);
203                 $fgcolor = array(110,41,57);
204                 
205
206                 
207                 $graph = new PHPlot($this->sizex,$this->sizey,"","");
208
209                 if ( !empty($type) )
210                         $graph->setDataType($type);
211
212                 $graph->SetDataValues($datos);
213                 $graph->SetPlotType($tipo);
214 //              $graph->SetUseTTF(1);
215                 $graph->SetBackgroundColor($bgcolor);
216
217                 $graph->SetLegendPixels(1,20);
218                 $graph->SetDataColors(array('SkyBlue','purple','PeachPuff','aquamarine1','#2CB04B','beige','#9F865F','#135568','orchid','navy','red', 'black', 'blue', 'green', 'brown', 'yellow','cyan','orange','#B9F5A7','#AFAFAF'));
219                 $graph->SetTitle($title);
220                 $graph->SetXLabel($xlabel);
221                 $graph->SetYLabel($ylabel);
222                 $graph->SetPlotAreaWorld("","","","");
223                 
224                 if ( count($datos) > 5 )
225                         $graph->SetXDataLabelAngle(90);
226                 else
227                         $graph->SetXDataLabelAngle(0);
228                 $graph->SetNumXTicks(1);
229 //              $graph->SetXDataLabelPos('none');
230 //              $graph->SetXTickLabelPos('plotdown');
231                 
232 //              $graph->SetXGridLabelType("time");
233 //              $graph->SetXTimeFormat("%b ") ;
234
235                 if ( $this->Leg == 1 ) {
236                         $this->MarginLeftWithLegend($legend);
237                         $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
238                         $graph->SetLegend($legend);
239                                 }
240                 else
241                         $graph->SetMarginsPixels(90,35,35,$this->MarginBottom);
242 //              $graph->SetDataColors(array($fgcolor),array( "black"));
243                 $graph->SetFileFormat( "png");
244 //              $graph->DoScaleData(1,1);
245 //              $graph->DoMovingAverage(1,1,1);
246
247 //              FIX ME -- to round y axis.
248                 $vtick = strlen (round ($graph->max_y));
249                 $res = 1;
250                 for ($i=1;$i < $vtick; $i++)
251                         $res = $res*10;
252                 if (strlen($graph->max_y-$res) != $vtick )
253                         $res = $res/10;
254                 $graph->SetVertTickIncrement($res);
255                 $graph->DrawGraph();
256
257         }//end Crear
258
259
260 //Estupidez que tengo que cambiar. !!!!!!!!!!!
261         function SetDataType($typ) {
262                 
263                 global $type;
264                 $type = $typ;
265         }
266
267         function MarginLeftWithLegend($clients) {
268                 
269                 $maxlen = 0;
270                 
271                 while (next($clients)) {
272                         $tmp = strlen(current($clients));
273                         if ( $tmp > $maxlen )
274                                 $maxlen = $tmp;
275                 }
276                 $this->MarginLeft = $maxlen * 9;
277         }       
278
279 }//end class
280
281
282
283
284
285 class BCreateGraph extends BGraph {
286
287         var $BD_bacula;
288         var $izquierda;
289         var $derecha;
290         var $StartDate;
291         var $EndDate;
292         var $elapsed;                        // Default elapsed time to show complex graphs
293         
294         
295         
296         function BCreateGraph() {
297         
298                 $this->StartDate = "1900-01-01";
299                 $this->EndDate = "4000-01-01";
300                 $this->elapsed = "86400";                   // 24 hours in seconds.
301                 
302          }              
303          
304          
305          
306         function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
307         
308                 global $DB_bacula;
309                 global $izquierda;
310                 global $derecha;
311                 global $clientes;
312         
313                 $this->clientes=array();
314                 $DB_bacula = new Bweb();
315                 $datos = $this->SQLPrepareData($server,$tipo_dato);
316         
317                 if ( empty($datos) ) {                       //No data = No stats = Empty graph
318                         header("Content-type: image/png");
319                         $img= @ImageCreate(200,100) or die ("Cannot intialize GD stream");
320                         $bgc= ImageColorAllocate($img, 0, 255,255);
321                         $txc= ImageColorAllocate($img, 0,0,0);
322                         ImageString($img, 5, 4, 4, "None data to process", $txc);
323                         ImagePng($img);
324                         ImageDestroy($img);
325                         return; 
326                 }
327         
328                 if ( empty ($xlabel) ) {                       // If no label, table names like leyends
329                         $xlabel=$derecha; $ylabel=$izquierda; 
330                 } 
331                         
332                 $this->SetDataType("text-data");
333                 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
334                 
335         }
336
337
338  
339         function SQLPrepareData($servidor,$tipo_dato=0) {         // Prepare bytes data from database.
340
341                 global $DB_bacula;
342                 global $izquierda;
343                 global $derecha;
344         
345                 if ( $tipo_dato<30 ) {               // Simple graph. Only 2 data 
346         
347                 switch ($tipo_dato)
348                                 {
349                                 case BACULA_TYPE_BYTES_FILES:
350                                         $izquierda="jobbytes";
351                                         $derecha="jobfiles";
352                                         break;
353                                 case BACULA_TYPE_FILES_JOBID:
354                                         $izquierda="jobfiles";
355                                         $derecha="jobid";
356                                         break;
357                                 default:
358                                         $izquierda="jobbytes";
359                                         $derecha="endtime";
360                                         break;
361                                 }
362                         $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")
363                                 or die ("classes.inc: Error at query: 5");
364                 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
365                         $whole_result[] = $this->array_merge_php4($row["$derecha"],$row[$izquierda]);
366                 }
367                 $result->free();
368         } else {                                                // Complex graph. 3 or more data.
369                 
370                         switch ( $tipo_dato )
371                                 {
372                                 case '30':                      // Unused, at this time.
373                                         $result = $DB_bacula->link->query("select JobBytes,JobFiles,Jobid from Job where Name='$servidor' order by EndTime asc")
374                                                 or die ("classes.inc: Error at query: 6");
375                                         while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) )
376                                                 $whole_result[] = array_merge($row["Jobid"],$row["JobFiles"],$row["JobBytes"]);
377                                         $result->free();
378                                         break;
379                                 case BACULA_TYPE_BYTES_ENDTIME_ALLJOBS:  // Special: Generic graph from all clientes.
380                                         $i = -1;                         // Counter of number of jobs of one client. SP: Contador del nmero de jobs totales de un cliente.
381                                         $i2 = 0;                         // Counter of number of keys of array. SP: Contador del nmero de valores del array.
382                                         
383                                         if ($DB_bacula->driver == "mysql") {
384                                         $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")
385                                                 or die ("classes.inc: Error at query: 7");
386                                                 $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")
387                                                         or die ("classes.inc: Error at query: 8");
388                                         }
389                                         else if ($DB_bacula->driver == "pgsql") {
390                                                 $res = $DB_bacula->link->query("select Name from Job where EndTime > now() - 1*interval'$this->elapsed s'  group by Name order by Name desc")
391                                                         or die ("classes.inc: Error at query: 8");
392                                                 $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")
393                                                         or die ("classes.inc: Error at query: 9");
394                                         }
395                                         
396                                         if (PEAR::isError($resdata))
397                                                 die("classes.inc: Error at query: 9.1<br>".$resdata->getMessage());
398                                         while ( $tmpdata = $res->fetchRow() )
399                                                 array_push($this->clientes,$tmpdata[0]);
400                                                 
401 //                                      echo "<pre>";
402 //                                      print_r ($this->clientes);
403 //                                      echo "</pre>";
404                                         
405                                         
406                                         $spr = array();                        // Temporal array
407                                         $spr2 = array();                       // Temporal array
408                                         $whole_result = array();
409                                         
410                                         while ( $tmpdata = $resdata->fetchRow() ) {
411                                                 $count++;
412                                                 array_push($spr,$tmpdata[0]);
413                                                 if ($DB_bacula->driver == "mysql")
414                                                         $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")
415                                                                 or die ("classes.inc: Error at query: 10");
416                                                 else if ($DB_bacula->driver == "pgsql") {
417                                                         $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";
418                                                         $result = $DB_bacula->link->query($query)
419                                                                 or die ("classes.inc: Error at query: 11");
420                                                 }
421                                                 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
422                                                         $spr2 = array_merge($spr2,array($row["name"]=>$row["sum"]));
423                                                         $i = $result->numRows();
424                                                 }
425
426                                         
427 //                                              echo "<pre>";
428 //                                              print_r ($spr2);
429 //                                              echo "</pre>";
430                                                 
431                                                 reset ($this->clientes);        
432                                                 do {
433                                                         if ( $spr2[current($this->clientes)] != NULL)
434                                                                 array_push($spr,$spr2[current($this->clientes)]);
435                                                         else
436                                                                 array_push($spr,0);
437                                                 } while ( next($this->clientes) );
438                                                 
439                                                 if ( $i2 < $i )
440                                                         $i2 = $i;
441                                                 
442                                                 if ( $tmpdata[0] != $row["EndTime"] )   
443                                                         array_push($whole_result,$spr);
444                                                 
445                                                 $spr = array();
446                                                 $spr2 = array();
447                                         }
448
449                                         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
450                                                 $tmp = count($whole_result[$i]);
451                                                 if ( $i2 < $tmp )                // Estupidez?. Check this code later...
452                                                         continue;
453                                                 $tmp = $i2 - $tmp;
454                                                 for ( $a = 0; $a <= $tmp; $a++ )
455                                                         array_push($whole_result[$i],"0");                                      // Fill the array
456                                         }
457                                         $resdata->free();       
458 //                                      echo "DEBUG:<br>";
459 //                                      echo "<pre>";
460 //                                      print_r ($whole_result);
461 //                                      echo "</pre>";  
462                                         break;
463                                 
464                                 default:
465                                         break;
466                         }
467                 }
468 //      $result->free();
469           return $whole_result;
470         }//end function
471
472
473
474         //Convert date from mysql to smarty.           THE SAME FUNCTION AT 2 CLASSES. THIS WAY IS BUGGY. TO SOLVE LATER.
475         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear){
476         
477                 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
478                 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
479                 
480         }//end function
481
482
483         function array_merge_php4($array1,$array2) {
484             $return=array();
485
486             foreach(func_get_args() as $arg) {
487                 if(!is_array($arg)){
488                 $arg=array($arg);
489                 }
490                     foreach($arg as $key=>$val){
491                             if(!is_int($key)){
492                                 $return[$key]=$val;
493                             }else{
494                                 $return[]=$val;
495                             }
496                     }
497             }
498         return $return;
499         }
500
501 }//end class
502
503 ?>