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