]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/bgraph.inc.php
bacula-web: Implemented new BGraph PHP classe
[bacula/bacula] / gui / bacula-web / bgraph.inc.php
1 <?php
2 require_once ("external_packages/phplot/phplot.php");
3
4 class BGraph{
5         private $title;
6         
7         private $data;
8         private $data_type;
9         private $type;
10         
11         private $colors;
12         private $shading;
13         
14         private $width;
15         private $height;
16         private $output_file;
17         private $plot;
18         
19         function __construct( $filename = "graph.png" )
20         {
21                 if( !empty($filename) )
22                         $this->output_file = "graph.png";
23                 else
24                         $this->output_file = $filename;
25         }
26         
27         public function SetData( $data_in, $type, $data_type, $shading = 5 )
28         {
29                 $this->data             = $data_in;
30                 $this->type             = $type;
31                 $this->data_type        = $data_type;
32                 $this->shadding         = $shading;
33         }
34         
35         public function SetGraphSize( $width, $height )
36         {
37                 $this->width  = $width;
38                 $this->height = $height;
39         }
40         
41         public function SetTitle( $title )
42         {
43                 if( !empty($title) )
44                         $this->title = $title;
45                 else
46                         die( "Please provide a non empty title for the graph" );
47         }
48         
49         public function SetColors( $colors )
50         {
51                 if( is_array( $colors ) )
52                         $this->colors = $colors;
53                 else
54                         die( "Please provide a array in BGraph->SetColors()" );
55         }
56         
57         public function Get_Image_file()
58         {
59                 return $this->output_file;
60         }
61         
62         public function Render()
63         {
64                 // Setting the size
65                 $this->plot = new PHPlot( $this->width, $this->height );
66                 
67                 // Render to file instead of screen
68                 $this->plot->SetIsInline( true );
69                 $this->plot->SetOutputFile( $this->output_file );
70                 
71                 $this->plot->SetImageBorderType('plain');
72
73                 // Data, type and data type
74                 $this->plot->SetPlotType( $this->type );
75                 $this->plot->SetDataType( $this->data_type );
76                 $this->plot->SetDataValues( $this->data );
77                 
78                 // Plot colors
79                 $this->plot->SetDataColors( $this->colors );
80                 
81                 // Plot shading
82                 $this->plot->SetShading( $this->shading );
83                 
84                 // Image border
85                 $this->plot->SetImageBorderType( 'none' );
86
87
88                 // Labels position
89                 if( $this->type == 'pie' )
90                         $this->plot->SetLabelScalePosition( 0.2 );
91                 
92                 // Graph title
93                 $this->plot->SetTitle( $this->title );
94
95                 //$this->plot->SetLegend(array('Engineering', 'Manufacturing', 'Administration'));
96                 // Setting up legends
97                 $legends = array();
98                 foreach( $this->data as $key => $legend ) {
99                         $this->plot->SetLegend( implode(': ',$legend) );
100                         //array_push( $legends, $legend[0] );
101                 }
102                         
103                 //$this->plot->SetLegend( $legends );
104
105                 # Turn off X tick labels and ticks because they don't apply here:
106                 $this->plot->SetXTickLabelPos('none');
107                 $this->plot->SetXTickPos('none');
108
109                 $this->plot->DrawGraph();
110         } // end function Render()
111 }
112 /*
113 class BGraph {
114
115         var $type;
116         var $sizex;
117         var $sizey;
118         var $MarginBottom;
119         var $MarginLeft;
120         var $Leg;
121
122
123         
124         function BShowGraph($datos,$title,$xlabel,$ylabel,$leyenda,$tipo="lines") {
125         
126                 global $type;
127         
128                 require_once ("external_packages/phplot/phplot.php");
129
130                 if ( empty($this->sizex) || empty($this->sizey) ) {    //Default size
131                         $this->sizex = "600";
132                         $this->sizey = "400";
133                 }
134                 if ( empty($this->MarginBottom) ) {
135                         $this->MarginBottom = 120;
136                 }
137                 
138                 $legend = $leyenda;
139 //              $bgcolor = array(222,206,215);      // Background color of graph
140                 $bgcolor = array(207,231,231);
141                 $fgcolor = array(110,41,57);
142                 
143
144                 
145                 $graph = new PHPlot($this->sizex,$this->sizey,"","");
146
147                 if ( !empty($type) )
148                         $graph->setDataType($type);
149
150                 $graph->SetDataValues($datos);
151                 $graph->SetPlotType($tipo);
152 //              $graph->SetUseTTF(1);
153                 $graph->SetBackgroundColor($bgcolor);
154
155                 $graph->SetLegendPixels(1,20);
156                 $graph->SetDataColors(array('SkyBlue','purple','PeachPuff','aquamarine1','#2CB04B','beige','#9F865F','#135568','orchid','navy','red', 'black', 'blue', 'green', 'brown', 'yellow','cyan','orange','#B9F5A7','#AFAFAF'));
157                 $graph->SetTitle($title);
158                 $graph->SetXLabel($xlabel);
159                 $graph->SetYLabel($ylabel);
160                 $graph->SetPlotAreaWorld("","","","");
161                 
162                 if ( count($datos) > 5 )
163                         $graph->SetXDataLabelAngle(90);
164                 else
165                         $graph->SetXDataLabelAngle(0);
166                 $graph->SetNumXTicks(1);
167 //              $graph->SetXDataLabelPos('none');
168 //              $graph->SetXTickLabelPos('plotdown');
169                 
170 //              $graph->SetXGridLabelType("time");
171 //              $graph->SetXTimeFormat("%b ") ;
172
173                 if ( $this->Leg == 1 ) {
174                         $this->MarginLeftWithLegend($legend);
175                         $graph->SetMarginsPixels($this->MarginLeft,10,35,$this->MarginBottom);
176                         $graph->SetLegend($legend);
177                                 }
178                 else
179                         $graph->SetMarginsPixels(90,35,35,$this->MarginBottom);
180 //              $graph->SetDataColors(array($fgcolor),array( "black"));
181                 $graph->SetFileFormat( "png");
182 //              $graph->DoScaleData(1,1);
183 //              $graph->DoMovingAverage(1,1,1);
184
185 //              FIX ME -- to round y axis.
186                 $vtick = strlen (round ($graph->max_y));
187                 $res = 1;
188                 for ($i=1;$i < $vtick; $i++)
189                         $res = $res*10;
190                 if (strlen($graph->max_y-$res) != $vtick )
191                         $res = $res/10;
192                 $graph->SetVertTickIncrement($res);
193                 $graph->DrawGraph();
194
195         }//end Crear
196
197
198 //Estupidez que tengo que cambiar. !!!!!!!!!!!
199         function SetDataType($typ) {
200                 
201                 global $type;
202                 $type = $typ;
203         }
204
205         function MarginLeftWithLegend($clients) {
206                 
207                 $maxlen = 0;
208                 
209                 while (next($clients)) {
210                         $tmp = strlen(current($clients));
211                         if ( $tmp > $maxlen )
212                                 $maxlen = $tmp;
213                 }
214                 $this->MarginLeft = $maxlen * 9;
215         }       
216
217 }//end class
218
219
220
221
222
223 class BCreateGraph extends BGraph {
224
225         var $BD_bacula;
226         var $izquierda;
227         var $derecha;
228         var $StartDate;
229         var $EndDate;
230         var $elapsed;                        // Default elapsed time to show complex graphs
231         
232         
233         
234         function BCreateGraph() {
235         
236                 $this->StartDate = "1900-01-01";
237                 $this->EndDate = "4000-01-01";
238                 $this->elapsed = "86400";                   // 24 hours in seconds.
239                 
240          }              
241          
242          
243          
244         function BCreate($server,$tipo_dato,$title,$tipo="bars",$xlabel="",$ylabel="") {
245         
246                 global $DB_bacula;
247                 global $izquierda;
248                 global $derecha;
249                 global $clientes;
250         
251                 $this->clientes=array();
252                 $DB_bacula = new Bweb();
253                 $datos = $this->SQLPrepareData($server,$tipo_dato);
254         
255                 if ( empty($datos) ) {                       //No data = No stats = Empty graph
256                         header("Content-type: image/png");
257                         $img= @ImageCreate(200,100) or die ("Cannot intialize GD stream");
258                         $bgc= ImageColorAllocate($img, 0, 255,255);
259                         $txc= ImageColorAllocate($img, 0,0,0);
260                         ImageString($img, 5, 4, 4, "No data to process", $txc);
261                         ImagePng($img);
262                         ImageDestroy($img);
263                         return; 
264                 }
265         
266                 if ( empty ($xlabel) ) {                       // If no label, table names like leyends
267                         $xlabel=$derecha; $ylabel=$izquierda; 
268                 } 
269                         
270                 $this->SetDataType("text-data");
271                 $this->BShowGraph($datos,$title,$xlabel,$ylabel,$this->clientes,$tipo);
272                 
273         }
274
275
276  
277         function SQLPrepareData($servidor,$tipo_dato=0) {         // Prepare bytes data from database.
278
279                 global $DB_bacula;
280                 global $izquierda;
281                 global $derecha;
282         
283                 if ( $tipo_dato<30 ) {               // Simple graph. Only 2 data 
284         
285                 switch ($tipo_dato)
286                                 {
287                                 case BACULA_TYPE_BYTES_FILES:
288                                         $izquierda="jobbytes";
289                                         $derecha="jobfiles";
290                                         break;
291                                 case BACULA_TYPE_FILES_JOBID:
292                                         $izquierda="jobfiles";
293                                         $derecha="jobid";
294                                         break;
295                                 default:
296                                         $izquierda="jobbytes";
297                                         $derecha="endtime";
298                                         break;
299                                 }
300                         $result = $DB_bacula->db_link->query("select $derecha,$izquierda from Job where Name='$servidor' and EndTime < '$this->EndDate' and EndTime > '$this->StartDate' order by SchedTime asc")
301                                 or die ("classes.inc: Error at query: 5");
302                 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
303                         $whole_result[] = $this->array_merge_php4($row["$derecha"],$row[$izquierda]);
304                 }
305                 $result->free();
306         } else {                                                // Complex graph. 3 or more data.
307                 
308                         switch ( $tipo_dato )
309                                 {
310                                 case '30':                      // Unused, at this time.
311                                         $result = $DB_bacula->db_link->query("select JobBytes,JobFiles,Jobid from Job where Name='$servidor' order by EndTime asc")
312                                                 or die ("classes.inc: Error at query: 6");
313                                         while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) )
314                                                 $whole_result[] = array_merge($row["Jobid"],$row["JobFiles"],$row["JobBytes"]);
315                                         $result->free();
316                                         break;
317                                 case BACULA_TYPE_BYTES_ENDTIME_ALLJOBS:  // Special: Generic graph from all clientes.
318                                         $i = -1;                         // Counter of number of jobs of one client. SP: Contador del nmero de jobs totales de un cliente.
319                                         $i2 = 0;                         // Counter of number of keys of array. SP: Contador del nmero de valores del array.
320                                         
321                                         if ($DB_bacula->driver == "mysql") {
322                                         $res = $DB_bacula->db_link->query("select Name from Job where UNIX_TIMESTAMP(EndTime) > UNIX_TIMESTAMP(NOW())-$this->elapsed  group by Name order by Name desc")
323                                                 or die ("classes.inc: Error at query: 7");
324                                                 $resdata = $DB_bacula->db_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")
325                                                         or die ("classes.inc: Error at query: 8");
326                                         }
327                                         else if ($DB_bacula->driver == "pgsql") {
328                                                 $res = $DB_bacula->db_link->query("select Name from Job where EndTime > now() - 1*interval'$this->elapsed s'  group by Name order by Name desc")
329                                                         or die ("classes.inc: Error at query: 8");
330                                                 $resdata = $DB_bacula->db_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")
331                                                         or die ("classes.inc: Error at query: 9");
332                                         }
333                                         
334                                         if (PEAR::isError($resdata))
335                                                 die("classes.inc: Error at query: 9.1<br>".$resdata->getMessage());
336                                         while ( $tmpdata = $res->fetchRow() )
337                                                 array_push($this->clientes,$tmpdata[0]);
338                                                 
339 //                                      echo "<pre>";
340 //                                      print_r ($this->clientes);
341 //                                      echo "</pre>";
342                                         
343                                         
344                                         $spr                    = array();                        // Temporal array
345                                         $spr2                   = array();                       // Temporal array
346                                         $whole_result   = array();
347                                         $count                  = 0;
348                                                                                 
349                                         while ( $tmpdata = $resdata->fetchRow() ) {
350                                                 $count++;
351                                                 array_push($spr,$tmpdata[0]);
352                                                 if ($DB_bacula->driver == "mysql")
353                                                         $result = $DB_bacula->db_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")
354                                                                 or die ("classes.inc: Error at query: 10");
355                                                 else if ($DB_bacula->driver == "pgsql") {
356                                                         $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";
357                                                         $result = $DB_bacula->db_link->query($query)
358                                                                 or die ("classes.inc: Error at query: 11");
359                                                 }
360                                                 while ( $row = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
361                                                         $spr2 = array_merge($spr2,array($row["name"]=>$row["sum"]));
362                                                         $i = $result->numRows();
363                                                 }
364
365                                         
366 //                                              echo "<pre>";
367 //                                              print_r ($spr2);
368 //                                              echo "</pre>";
369                                                 
370                                                 reset ($this->clientes);        
371                                                 do {
372                                                         if ( $spr2[current($this->clientes)] != NULL)
373                                                                 array_push($spr,$spr2[current($this->clientes)]);
374                                                         else
375                                                                 array_push($spr,0);
376                                                 } while ( next($this->clientes) );
377                                                 
378                                                 if ( $i2 < $i )
379                                                         $i2 = $i;
380                                                 
381                                                 if ( $tmpdata[0] != $row["EndTime"] )   
382                                                         array_push($whole_result,$spr);
383                                                 
384                                                 $spr = array();
385                                                 $spr2 = array();
386                                         }
387
388                                         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
389                                                 $tmp = count($whole_result[$i]);
390                                                 if ( $i2 < $tmp )                // Estupidez?. Check this code later...
391                                                         continue;
392                                                 $tmp = $i2 - $tmp;
393                                                 for ( $a = 0; $a <= $tmp; $a++ )
394                                                         array_push($whole_result[$i],"0");                                      // Fill the array
395                                         }
396                                         $resdata->free();       
397 //                                      echo "DEBUG:<br>";
398 //                                      echo "<pre>";
399 //                                      print_r ($whole_result);
400 //                                      echo "</pre>";  
401                                         break;
402                                 
403                                 default:
404                                         break;
405                         }
406                 }
407 //      $result->free();
408           return $whole_result;
409         }//end function
410
411
412
413         //Convert date from mysql to smarty.           THE SAME FUNCTION AT 2 CLASSES. THIS WAY IS BUGGY. TO SOLVE LATER.
414         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear){
415         
416                 $this->StartDate = $StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
417                 $this->EndDate = $EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:00";
418                 
419         }//end function
420
421
422         function array_merge_php4($array1,$array2) {
423             $return=array();
424
425             foreach(func_get_args() as $arg) {
426                 if(!is_array($arg)){
427                 $arg=array($arg);
428                 }
429                     foreach($arg as $key=>$val){
430                             if(!is_int($key)){
431                                 $return[$key]=$val;
432                             }else{
433                                 $return[]=$val;
434                             }
435                     }
436             }
437         return $return;
438         }
439
440 }//end class
441 */
442 ?>