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