]> git.sur5r.net Git - bacula/bacula/blob - gui/bacula-web/bweb.inc.php
bacula-web: Moved constants declaration
[bacula/bacula] / gui / bacula-web / bweb.inc.php
1 <?php
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 require_once "paths.php";
18 require_once "DB.php";                                                                                                                  // Pear DB
19 require_once "config.inc.php";
20 require_once "bgraph.inc.php";
21 require_once($smarty_path."Config_File.class.php");
22
23 if (!function_exists('array_fill')) {                                                                                   // For PHP < 4.2.0 users 
24     require_once('array_fill.func.php');
25 }
26
27 class Bweb extends DB {
28
29     var $StartDate;
30     var $EndDate;
31     var $driver;
32         var $dbs;
33         var $dbs_name;
34         
35         public $db_link;                                                // Database link
36         private $db_dsn;                                                // Data Source Name
37         
38         private $config_file;                                   // Config filename
39         private $config;                                                // Loaded config from bacula.conf
40         private $catalogs = array();                    // Catalog array
41
42     function __construct()
43         {             
44                 $this->catalogs = array();
45                 
46                 // Loading configuration
47                 $this->config_file = getcwd() . '/configs/bacula.conf';
48                 if( !$this->load_config() )
49                         die( "Unable to load configuration");
50                         
51                 //echo "Number of catalog defined " . count($this->catalogs) . "<br />";
52                 
53                 /*
54                 $conf = new Config_File (CONFIG_DIR);
55                 $this->dbs = array();
56
57                 $i = 2;
58                 $sections = $conf->get(CONFIG_FILE,"DATABASE","host");
59                 array_push($this->dbs, "DATABASE");
60
61                 while ( !empty($sections) ) {                
62                         $sections = $conf->get(CONFIG_FILE,"DATABASE".$i,"host");
63                         if ( !empty($sections) )
64                                 array_push($this->dbs,"DATABASE".$i);
65                         $i++;
66                 }
67
68                 if ( $i < 4)
69                         $sec = "DATABASE";
70                 else {
71                         if ( !empty($_POST['sel_database']) ) {
72                                 $_SESSION['DATABASE'] = $_POST['sel_database'];
73                                 $sec = $_POST['sel_database'];
74                         } else {
75                                 if (isset($_SESSION['DATABASE']) )
76                                         $sec = $_SESSION['DATABASE'];
77                                 else
78                                         $sec = "DATABASE";
79                         }
80                 }
81
82         $this->dsn['hostspec'] = $conf->get(CONFIG_FILE,$sec,"host");
83         $this->dsn['username'] = $conf->get(CONFIG_FILE,$sec,"login");
84         $this->dsn['password'] = $conf->get(CONFIG_FILE,$sec,"pass");
85         $this->dsn['database'] = $conf->get(CONFIG_FILE,$sec,"db_name");
86         $this->dsn['phptype']  = $conf->get(CONFIG_FILE,$sec,"db_type");   // mysql, pgsql
87         
88                 if (  $conf->get(CONFIG_FILE,$sec,"db_port") )
89                         $this->dsn[port] = $conf->get(CONFIG_FILE,$sec,"db_port");
90                 */
91                 
92                 // Construct a valid dsn
93         $this->db_dsn['hostspec'] = $this->catalogs[0]["host"];
94         $this->db_dsn['username'] = $this->catalogs[0]["login"];
95                 $this->db_dsn['password'] = $this->catalogs[0]["pass"];
96                 $this->db_dsn['database'] = $this->catalogs[0]["db_name"];
97                 $this->db_dsn['phptype']  = $this->catalogs[0]["db_type"];
98                 
99                                         
100         $this->db_link = $this->connect($this->db_dsn);
101         
102                 if (DB::isError($this->db_link)) {
103                         die($this->db_link->getMessage());
104                 }else {
105                         $this->driver = $this->db_dsn['phptype'];                            
106             register_shutdown_function(array(&$this,'close'));
107                         $this->dbs_name = $this->db_dsn['database'];
108                 }
109         }
110                 
111     function load_config()
112         {
113                 $this->config = parse_ini_file( $this->config_file, true );
114                 
115                 if( !$this->config == false ) {
116                         // Loading database connection information
117                         foreach( $this->config as $parameter => $value )
118                         {
119                                 //echo "Param $parameter = $value <br />";
120                                 if( is_array($value) ){         // Parsing database section
121                                         array_push( $this->catalogs, $value );
122                                 }
123                         }
124                         return true;
125                 }else
126                         return false;
127         }
128         
129         public function get_config_param( $param )
130         {
131                 if( isset( $this->config[$param] ) )
132                         return $this->config[$param];
133                 else
134                         return false;
135         }
136         
137         public function Get_Nb_Catalogs() 
138         {
139                 return count( $this->catalogs );
140         }
141         
142         
143         function close() 
144         {
145                 $this->db_link->disconnect();
146     }      
147
148         
149          
150         function CalculateBytesPeriod($server,$StartDate,$EndPeriod) {   // Bytes transferred in a period.
151
152                 $result =& $this->db_link->query("select SUM(JobBytes) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
153                         or die("classes.inc: Error query: 1");
154                 $return =& $result->fetchRow(); 
155                 return $return[0];
156         }//end function
157
158         
159          
160         function CalculateFilesPeriod($server,$StartDate,$EndPeriod) {    // Number of files transferred in a period.
161
162                 $result =& $this->db_link->query("select SUM(JobFiles) from Job WHERE EndTime < '$EndPeriod' and EndTime > '$StartDate' and Name='$server'")
163                         or die("classes.inc: Error query: 2");
164                 $return =& $result->fetchRow();
165                 return $return[0];
166         }//end function 
167
168                  
169
170         function PrepareDate($StartDateMonth,$StartDateDay,$StartDateYear,$EndDateMonth,$EndDateDay,$EndDateYear) {  // Convert date for Smarty. Check if only works with Mysql.
171         
172                 $this->StartDate=$StartDateYear."-".$StartDateMonth."-".$StartDateDay." 00:00:00";
173                 $this->EndDate=$EndDateYear."-".$EndDateMonth."-".$EndDateDay." 23:59:59";  // last day full
174                 
175         }//end function
176                 
177                 // Return humanized size with default unit of GB
178                 // if auto provide for unit argument, automaticaly decide which unit
179                 function human_file_size( $size, $decimal = 2, $unit = 'auto' )
180                 {
181                         $unit_id = 0;
182                         $lisible = false;
183                         $units = array('B','KB','MB','GB','TB');
184                         $hsize = $size;
185
186                         switch( $unit )
187                         {
188                                 case 'auto';
189                                         while( !$lisible ) {
190                                                 if ( $hsize >= 1024 ) {
191                                                         $hsize    = $hsize / 1024;
192                                                         $unit_id += 1;
193                                                 }        
194                                                 else {
195                                                         $lisible = true;
196                                                 } 
197                                         }
198                                 break;
199                                 
200                                 default:
201                                         $p = array_search( $unit, $units);
202                                         $hsize = $hsize / pow(1024,$p);
203                                 break;
204                         } // end switch
205                         
206                         $hsize = sprintf("%." . $decimal . "f", $hsize);
207                         $hsize = $hsize . ' ' . $units[$unit_id];
208                         return $hsize;
209                 } // end function
210
211                 
212                 function GetDbSize() 
213                 {
214                         $database_size = 0;
215                         if ( $this->driver == "mysql") {
216                                 $dbsize = $this->db_link->query("show table status") or die ("classes.inc: Error query: 3");
217                                 
218                                 if ( $dbsize->numRows() ) {
219                                         while ( $res = $dbsize->fetchRow(DB_FETCHMODE_ASSOC) )
220                                                 $database_size += $res["Data_length"];
221                 } else {
222                                         return 0;
223                                 } // end if else
224             } // end if
225             else if ( $this->driver == "pgsql") {
226                                 $dbsize = $this->db_link->query("select pg_database_size('$this->dbs_name')") or die ("classes.inc: Error query: 4");
227                                 
228                                 if (PEAR::isError($dbsize))
229                                         die($dbsize->getMessage());
230                     
231                                 if ( $dbsize->numRows() ) {
232                                         while ( $res = $dbsize->fetchRow() )
233                                                 $database_size += $res[0];
234                 } else {
235                                         return 0;
236                                 }
237             } // end if       
238                                 
239                         $dbsize->free();
240                 
241                         return $this->human_file_size( $database_size );  
242         } // end function GetDbSize()
243                 
244                 public function Get_Nb_Clients()
245                 {
246                         $clients = $this->db_link->query("SELECT COUNT(*) AS nb_client FROM Client");
247                         if( PEAR::isError($clients) )
248                                 die( "Unable to get client number" );
249                         else
250                                 return $clients->fetchRow( DB_FETCHMODE_ASSOC );
251                 }
252
253                 // Return an array of volumes ordered by poolid and volume name
254                 function GetVolumeList() {
255
256                 $volumes   = array();
257                 $query     = "";
258                                 $debug     = false;
259                                 
260                                 // Get the list of pools id
261                                 $query = "SELECT Pool.poolid, Pool.name FROM Pool ORDER BY Pool.poolid";
262                                 
263                                 //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
264                                 $pools = $this->db_link->query( $query );
265                                 
266                                 if( PEAR::isError( $pools ) )
267                                         die("Error: Failed to get pool list <br />SQL Query: $query<br />" . $pools->getMessage() );
268                                 
269                                 while( $pool = $pools->fetchRow( DB_FETCHMODE_ASSOC ) ) {
270                                         switch( $this->driver )
271                                         {
272                                                 case 'mysql':
273 /*
274                                                         $query  = "SELECT Media.VolumeName, Media.VolBytes, Media.VolStatus, Pool.Name, Media.MediaType,Media.LastWritten, FROM_UNIXTIME(UNIX_TIMESTAMP(Media.LastWritten)+Media.VolRetention ) AS expire 
275                                                                            FROM Pool LEFT JOIN Media ON Media.PoolId=Pool.PoolId WHERE poolid='$pool[0]' 
276                                                                            ORDER BY Media.VolumeName";
277 */
278                                                         $query  = "SELECT Media.volumename, Media.volbytes, Media.volstatus, Media.mediatype, Media.lastwritten, Media.volretention
279                                                                            FROM Media LEFT JOIN Pool ON Media.poolid = Pool.poolid
280                                                                        WHERE Media.poolid = '". $pool['poolid'] . "' ORDER BY Media.volumename";
281                                                 break;
282                                                 case 'pgsql':
283                                                         $query  = "SELECT media.volumename, media.volbytes, media.volstatus, media.mediatype, media.lastwritten, media.volretention
284                                                                            FROM media LEFT JOIN pool ON media.poolid = pool.poolid
285                                                                        WHERE media.poolid = '". $pool['poolid'] . "' ORDER BY media.volumename";
286                                                         /*
287                                                         $query  = "SELECT Media.VolumeName, Media.VolBytes,Media.VolStatus,Pool.Name,Media.MediaType,Media.LastWritten, Media.LastWritten + Media.VolRetention * interval '1 second' AS expire 
288                                                                            FROM Pool LEFT JOIN Media ON media.poolid=pool.poolid WHERE poolid='$pool[0]' 
289                                                                            ORDER BY Media.VolumeName";
290                                                         */
291                                                 break;
292                                                 case 'sqlite':
293                                                         $query  = "";           // not yet implemented
294                                                 break;
295                                                 default:
296                                                 break;
297                                         } // end switch
298                                         
299                                         //$this->db_link->setFetchMode(DB_FETCHMODE_ASSOC);
300                                         $medias = $this->db_link->query( $query );
301
302                                         if( PEAR::isError( $medias ) ) {
303                                                 die( "Failed to get media list for pool $volume[0] <br /> " . $medias->getMessage() );
304                                         }else {
305                                                 if( $debug ) echo "Found " . $medias->numRows() . " medias for pool " . $pool['name'] . " <br />";
306                                         
307                                                 // Create array key for each pool
308                                                 if( !array_key_exists( $pool['name'], $volumes) )
309                                                 {
310                                                         $volumes[ $pool['name'] ] = array();
311                                                 }
312                                                 while( $media = $medias->fetchRow( DB_FETCHMODE_ASSOC ) ) {
313                                                         if( $debug ) {
314                                                                 var_dump( $media );
315                                                         }
316                                                         // If the pool is empty (no volumes in this pool)
317                                                         if( $medias->numRows() == 0 ) {
318                                                                 if( $debug ) echo "No media in pool " . $pool['name'] . "<br />";
319                                                         } else {
320                                                                         if( $media['lastwritten'] != "0000-00-00 00:00:00" ) {
321                                                                                 // Calculate expiration date if the volume is Full
322                                                                                 if( $media['volstatus'] == 'Full' ) {
323                                                                                         $expire_date     = strtotime($media['lastwritten']) + $media['volretention'];
324                                                                                         $media['expire'] = strftime("%Y-%m-%d", $expire_date);
325                                                                                 }else {
326                                                                                         $media['expire'] = 'N/A';
327                                                                                 }
328                                                                                 // Media used bytes in a human format
329                                                                                 $media['volbytes'] = $this->human_file_size( $media['volbytes'] );
330                                                                                 //echo "volume " . $media['volumename'] . 'vol bytes' .$media['volbytes'] . '<br />';
331                                                                         } else {
332                                                                                 $media['lastwritten'] = "N/A";
333                                                                                 $media['expire']      = "N/A";
334                                                                                 $media['volbytes']        = "0 KB";
335                                                                         }                                                               
336                                                                 // Add the media in pool array
337                                                                 array_push( $volumes[ $pool['name']], $media);
338                                                         }
339                                                 } // end while
340                                         } // end if else
341                                 } // end while
342                                 return $volumes;
343         } // end function GetVolumeList()
344                 
345                 public function CountJobs( $delay = LAST_DAY, $status )
346                 {
347                         $query = "SELECT COUNT(JobId) AS job_nb FROM Job ";
348                         
349                         // Interval condition for SQL query
350                         $end_date    = mktime();
351                         $start_date  = $end_date - $delay;
352                         
353                         $start_date  = date( "Y-m-d H:i:s", $start_date );
354                         $end_date    = date( "Y-m-d H:i:s", $end_date );
355                         
356                         $query      .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
357                         
358                         // Job Status for SQL query
359                         switch( $status )
360                         {
361                                 case 'completed':
362                                         $query .= "AND JobStatus = 'T' ";
363                                 break;
364                                 case 'failed':
365                                         $query .= "AND JobStatus = 'f' ";
366                                 break;
367                         } // end switch
368                         
369                         $jobs = $this->db_link->query( $query );
370                 
371                         if (PEAR::isError( $jobs ) ) {
372                                 die( "Unable to get last $status jobs number from catalog <br />" . $status->getMessage() );
373                         }else {
374                                 return $jobs->fetchRow( DB_FETCHMODE_ASSOC );
375                         }
376                 }
377                 
378                 // Return the list of Pools in a array
379                 public function Get_Pools_List()
380                 {
381                         $pool_list = array();
382                         $result    = "";
383                         
384                         $query = "SELECT Name, PoolId FROM Pool";
385                         
386                         $result = $this->db_link->query ( $query );
387         
388                         if( PEAR::isError( $result ) ) {
389                                 die( "Unable to get the pool list from catalog" );                              
390                         }else {
391                                 while( $pool = $result->fetchRow(DB_FETCHMODE_ASSOC) ) {
392                                         array_push( $pool_list, array( $pool['Name'] => $pool['PoolId'] ) );
393                                 }
394                                 return $pool_list;
395                         }
396                 }
397                 
398                 public function Get_BackupJob_Names()
399                 {
400                         $query          = "SELECT Name FROM Job GROUP BY Name";
401                         $backupjobs = array();
402                         
403                         $result = $this->db_link->query( $query );
404                         
405                         if (PEAR::isError( $result ) ) {
406                                 die("Unable to get BackupJobs list from catalog" );
407                         }else{
408                                 while( $backupjob = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
409                                         array_push( $backupjobs, $backupjob["Name"] );
410                                 }
411                                 return $backupjobs;
412                         }
413                 }
414                 
415                 public function Get_ElapsedTime_Job( $delay = LAST_DAY )
416                 {
417                         $query                  = "";
418                         $total_elapsed  = 0;
419                         
420                         // Interval calculation
421                         $end_date   = mktime();
422                         $start_date = $end_date - $delay;
423                         
424                         $start_date = date( "Y-m-d H:i:s", $start_date );
425                         $end_date   = date( "Y-m-d H:i:s", $end_date );
426                         
427                         switch( $this->driver )
428                         {
429                                 case 'mysql':
430                                         $query  = "SELECT UNIX_TIMESTAMP(EndTime) - UNIX_TIMESTAMP(StartTime) AS elapsed from Job ";
431                                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
432                                 break;
433                         }
434                         $result = $this->db_link->query( $query );
435                         
436                         if( PEAR::isError($result) ){
437                                 die( "Unable to get elapsed time for jobs from catalog<br />query = $query <br />" . $result->getMessage() );
438                         }else {
439                                 while( $time = $result->fetchRow( DB_FETCHMODE_ASSOC ) ) {
440                                         //echo 'elapsed = ' . $time['elapsed'] . '<br />';
441                                         $total_elapsed += $time['elapsed'];
442                                 }
443                                 // Verify if elapsed time is more than 1 day
444                                 if ( $total_elapsed > 86400 ) {
445                                         return date("%d days H:i:s", $total_elapsed );
446                                 }else {
447                                         return date("H:i:s", $total_elapsed );
448                                 }
449                         }
450                 }
451                 
452                 // Return Jobs statistics for a specific interval such as
453                 // - Completed jobs number
454                 // - Failed jobs number
455                 // - Waiting jobs number
456                 // The returned values will be used by a Bgraph classe
457                 public function GetJobsStatistics( $type = 'completed', $delay = LAST_DAY )
458                 {
459                         $query  = "";
460                         $where  = "";
461                         $jobs   = "";
462                         $label  = "";
463                         $res    = "";
464                         
465                         // Interval calculation
466                         $end_date   = mktime();
467                         $start_date = $end_date - $delay;
468                         
469                         $start_date = date( "Y-m-d H:i:s", $start_date );
470                         $end_date   = date( "Y-m-d H:i:s", $end_date );
471                         
472                         // Job status
473                         switch( $type )
474                         {
475                                 case 'completed':
476                                         $where = "AND JobStatus = 'T' ";
477                                         $label = "Completed";
478                                 break;
479                                 case 'completed_errors':
480                                         $where = "AND JobStatus = 'E' ";
481                                         $label = "Completed with errors";
482                                 break;
483                                 case 'failed':
484                                         $where = "AND JobStatus = 'f' ";
485                                         $label = "Failed";
486                                 break;
487                                 case 'waiting':
488                                         $where = "AND JobStatus IN ('F','S','M','m','s','j','c','d','t') ";
489                                         $label = "Waiting";
490                                 break;
491                                 case 'created':
492                                         $where = "AND JobStatus = 'C' ";
493                                         $label = "Created but not running";
494                                 break;
495                                 case 'running':
496                                         $where = "AND JobStatus = 'R' ";
497                                         $label = "Running";
498                                 break;
499                                 case 'error':
500                                         $where = "AND JobStatus IN ('e','f') ";
501                                         $label = "Errors";
502                                 break;
503                         }
504                         
505                         $query  = 'SELECT COUNT(JobId) AS ' . $type . ' ';
506                         $query .= 'FROM Job ';
507                         $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date' ";
508                         $query .= $where;
509                 
510                         $jobs = $this->db_link->query( $query );
511                 
512                         if (PEAR::isError( $jobs ) ) {
513                                 die( "Unable to get last $type jobs status from catalog<br />" . $status->getMessage() );
514                         }else {
515                                 $res = $jobs->fetchRow();
516                                 return array( $label , current($res) );
517                         }
518                 } // end function GetJobsStatistics()
519                 
520                 public function GetPoolsStatistics( $pools )
521                 {
522                         foreach( $pools as $pool_name => $pool ) {
523                                 //var_dump( $pool );
524                                 $query = "SELECT COUNT(*) AS nb_vol FROM Media WHERE PoolId = '$pool'";
525                                 //echo $query . '<br />';
526                                 //echo 'Pool name ' . $pool_name . '<br />';
527                                 $result = $this->db_link->query( $query );
528                                 
529                                 if( PEAR::isError( $result ) ) {
530                                         die("Unable to get volume number from catalog");
531                                 }else{
532                                         $nb_vol = $result->fetchRow(DB_FETCHMODE_ASSOC);
533                                         return array( $pool_name, $nb_vol['nb_vol'] );
534                                 }
535                         }
536                 }
537                 
538                 public function GetStoredFiles()
539                 {
540                         $nbfiles = 0;
541                         $query = "SELECT COUNT(FilenameId) AS nbfiles FROM Filename";
542                         $result = $this->db_link->query( $query );
543                         
544                         if( !PEAR::isError($result) ) {
545                                 $nbfiles = $result->fetchRow(DB_FETCHMODE_ASSOC);
546                                 $nbfiles = $nbfiles['nbfiles'];
547                         }else{
548                                 die("Unable to get protected files from catalog");
549                         }
550                         return $nbfiles;
551                 }
552                 
553                 public function GetStoredBytes( $delay = LAST_DAY )
554                 {
555                         $query = "SELECT SUM(JobBytes) as stored_bytes FROM Job ";
556                         
557                         // Interval calculation
558                         $end_date   = mktime();
559                         $start_date = $end_date - $delay;
560                         
561                         $start_date = date( "Y-m-d H:i:s", $start_date );
562                         $end_date   = date( "Y-m-d H:i:s", $end_date );
563                         
564                         if( $delay != ALL ) {
565                                 $query .= "WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
566                         }
567                         
568                         $result = $this->db_link->query( $query );
569                         
570                         if( PEAR::isError( $result ) ) {
571                                 die( "Unable to get Job Bytes from catalog" );
572                         }else{
573                                 return $result->fetchRow( DB_FETCHMODE_ASSOC );
574                         }
575                 }
576                 
577                 public function GetStoredBytesByInterval( $start_date, $end_date )
578                 {
579                         $query = "SELECT SUM(JobBytes) as stored_bytes, EndTime FROM Job WHERE EndTime BETWEEN '$start_date' AND '$end_date'";
580                         
581                         $result = $this->db_link->query( $query );
582                         
583                         if( PEAR::isError( $result ) ) {
584                                 die( "Unable to get Job Bytes from catalog" );
585                         }else{
586                                 $stored_bytes = 0;
587                                 $tmp = $result->fetchRow( DB_FETCHMODE_ASSOC );
588                                 
589                                 $day = date( "D d", strtotime($end_date) );
590                                 
591                                 if( isset( $tmp['stored_bytes'] ) ) {
592                                         $hbytes = $this->human_file_size( $tmp['stored_bytes'], 3, 'GB');
593                                         $hbytes = explode( " ", $hbytes );
594                                         $stored_bytes = $hbytes[0];
595                                 }
596                                 
597                                 return array( $day, $stored_bytes );
598                         }
599                 }
600 } // end class Bweb
601 ?>