DB_utility.php

Go to the documentation of this file.
00001 <?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
00002 /**
00003  * Code Igniter
00004  *
00005  * An open source application development framework for PHP 4.3.2 or newer
00006  *
00007  * @package             CodeIgniter
00008  * @author              ExpressionEngine Dev Team
00009  * @copyright   Copyright (c) 2006, EllisLab, Inc.
00010  * @license             http://codeigniter.com/user_guide/license.html
00011  * @link                http://codeigniter.com
00012  * @since               Version 1.0
00013  * @filesource
00014  */
00015 
00016 // ------------------------------------------------------------------------
00017 
00018 /**
00019  * Database Utility Class
00020  *
00021  * @category    Database
00022  * @author              ExpressionEngine Dev Team
00023  * @link                http://codeigniter.com/user_guide/database/
00024  */
00025 class CI_DB_utility extends CI_DB_forge {
00026 
00027         var $db;
00028         var $data_cache         = array();
00029 
00030         /**
00031          * Constructor
00032          *
00033          * Grabs the CI super object instance so we can access it.
00034          *
00035          */     
00036         function CI_DB_utility()
00037         {
00038                 // Assign the main database object to $this->db
00039                 $CI =& get_instance();
00040                 $this->db =& $CI->db;
00041                 
00042                 log_message('debug', "Database Utility Class Initialized");
00043         }
00044 
00045         // --------------------------------------------------------------------
00046 
00047         /**
00048          * List databases
00049          *
00050          * @access      public
00051          * @return      bool
00052          */
00053         function list_databases()
00054         {       
00055                 // Is there a cached result?
00056                 if (isset($this->data_cache['db_names']))
00057                 {
00058                         return $this->data_cache['db_names'];
00059                 }
00060         
00061                 $query = $this->db->query($this->_list_databases());
00062                 $dbs = array();
00063                 if ($query->num_rows() > 0)
00064                 {
00065                         foreach ($query->result_array() as $row)
00066                         {
00067                                 $dbs[] = current($row);
00068                         }
00069                 }
00070                         
00071                 $this->data_cache['db_names'] = $dbs;
00072                 return $this->data_cache['db_names'];
00073         }
00074 
00075         // --------------------------------------------------------------------
00076 
00077         /**
00078          * Optimize Table
00079          *
00080          * @access      public
00081          * @param       string  the table name
00082          * @return      bool
00083          */
00084         function optimize_table($table_name)
00085         {
00086                 $sql = $this->_optimize_table($table_name);
00087                 
00088                 if (is_bool($sql))
00089                 {
00090                                 show_error('db_must_use_set');
00091                 }
00092         
00093                 $query = $this->db->query($sql);
00094                 $res = $query->result_array();
00095                 
00096                 // Note: Due to a bug in current() that affects some versions
00097                 // of PHP we can not pass function call directly into it
00098                 return current($res);
00099         }
00100 
00101         // --------------------------------------------------------------------
00102 
00103         /**
00104          * Optimize Database
00105          *
00106          * @access      public
00107          * @return      array
00108          */
00109         function optimize_database()
00110         {
00111                 $result = array();
00112                 foreach ($this->db->list_tables() as $table_name)
00113                 {
00114                         $sql = $this->_optimize_table($table_name);
00115                         
00116                         if (is_bool($sql))
00117                         {
00118                                 return $sql;
00119                         }
00120                         
00121                         $query = $this->db->query($sql);
00122                         
00123                         // Build the result array...
00124                         // Note: Due to a bug in current() that affects some versions
00125                         // of PHP we can not pass function call directly into it
00126                         $res = $query->result_array();
00127                         $res = current($res);
00128                         $key = str_replace($this->db->database.'.', '', current($res));
00129                         $keys = array_keys($res);
00130                         unset($res[$keys[0]]);
00131                         
00132                         $result[$key] = $res;
00133                 }
00134 
00135                 return $result;
00136         }
00137 
00138         // --------------------------------------------------------------------
00139 
00140         /**
00141          * Repair Table
00142          *
00143          * @access      public
00144          * @param       string  the table name
00145          * @return      bool
00146          */
00147         function repair_table($table_name)
00148         {
00149                 $sql = $this->_repair_table($table_name);
00150                 
00151                 if (is_bool($sql))
00152                 {
00153                         return $sql;
00154                 }
00155         
00156                 $query = $this->db->query($sql);
00157                 
00158                 // Note: Due to a bug in current() that affects some versions
00159                 // of PHP we can not pass function call directly into it
00160                 $res = $query->result_array();
00161                 return current($res);
00162         }
00163         
00164         // --------------------------------------------------------------------
00165 
00166         /**
00167          * Generate CSV from a query result object
00168          *
00169          * @access      public
00170          * @param       object  The query result object
00171          * @param       string  The delimiter - comma by default
00172          * @param       string  The newline character - \n by default
00173          * @param       string  The enclosure - double quote by default
00174          * @return      string
00175          */
00176         function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"')
00177         {
00178                 if ( ! is_object($query) OR ! method_exists($query, 'field_names'))
00179                 {
00180                         show_error('You must submit a valid result object');
00181                 }       
00182         
00183                 $out = '';
00184                 
00185                 // First generate the headings from the table column names
00186                 foreach ($query->list_fields() as $name)
00187                 {
00188                         $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
00189                 }
00190                 
00191                 $out = rtrim($out);
00192                 $out .= $newline;
00193                 
00194                 // Next blast through the result array and build out the rows
00195                 foreach ($query->result_array() as $row)
00196                 {
00197                         foreach ($row as $item)
00198                         {
00199                                 $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;                     
00200                         }
00201                         $out = rtrim($out);
00202                         $out .= $newline;
00203                 }
00204 
00205                 return $out;
00206         }
00207         
00208         // --------------------------------------------------------------------
00209 
00210         /**
00211          * Generate XML data from a query result object
00212          *
00213          * @access      public
00214          * @param       object  The query result object
00215          * @param       array   Any preferences
00216          * @return      string
00217          */
00218         function xml_from_result($query, $params = array())
00219         {
00220                 if ( ! is_object($query) OR ! method_exists($query, 'field_names'))
00221                 {
00222                         show_error('You must submit a valid result object');
00223                 }
00224                 
00225                 // Set our default values
00226                 foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val)
00227                 {
00228                         if ( ! isset($params[$key]))
00229                         {
00230                                 $params[$key] = $val;
00231                         }
00232                 }
00233                 
00234                 // Create variables for convenience
00235                 extract($params);
00236                         
00237                 // Load the xml helper
00238                 $CI =& get_instance();
00239                 $CI->load->helper('xml');
00240 
00241                 // Generate the result
00242                 $xml = "<{$root}>".$newline;
00243                 foreach ($query->result_array() as $row)
00244                 {
00245                         $xml .= $tab."<{$element}>".$newline;
00246                         
00247                         foreach ($row as $key => $val)
00248                         {
00249                                 $xml .= $tab.$tab."<{$key}>".xml_convert($val)."</{$key}>".$newline;
00250                         }
00251                         $xml .= $tab."</{$element}>".$newline;
00252                 }
00253                 $xml .= "</$root>".$newline;
00254                 
00255                 return $xml;
00256         }
00257 
00258         // --------------------------------------------------------------------
00259 
00260         /**
00261          * Database Backup
00262          *
00263          * @access      public
00264          * @return      void
00265          */
00266         function backup($params = array())
00267         {
00268                 // If the parameters have not been submitted as an
00269                 // array then we know that it is simply the table
00270                 // name, which is a valid short cut.
00271                 if (is_string($params))
00272                 {
00273                         $params = array('tables' => $params);
00274                 }
00275                 
00276                 // ------------------------------------------------------
00277         
00278                 // Set up our default preferences
00279                 $prefs = array(
00280                                                         'tables'                => array(),
00281                                                         'ignore'                => array(),
00282                                                         'filename'              => '',
00283                                                         'format'                => 'gzip', // gzip, zip, txt
00284                                                         'add_drop'              => TRUE,
00285                                                         'add_insert'    => TRUE,
00286                                                         'newline'               => "\n"
00287                                                 );
00288 
00289                 // Did the user submit any preferences? If so set them....
00290                 if (count($params) > 0)
00291                 {
00292                         foreach ($prefs as $key => $val)
00293                         {
00294                                 if (isset($params[$key]))
00295                                 {
00296                                         $prefs[$key] = $params[$key];
00297                                 }
00298                         }
00299                 }
00300 
00301                 // ------------------------------------------------------
00302 
00303                 // Are we backing up a complete database or individual tables?  
00304                 // If no table names were submitted we'll fetch the entire table list
00305                 if (count($prefs['tables']) == 0)
00306                 {
00307                         $prefs['tables'] = $this->db->list_tables();
00308                 }
00309                 
00310                 // ------------------------------------------------------
00311 
00312                 // Validate the format
00313                 if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE))
00314                 {
00315                         $prefs['format'] = 'txt';
00316                 }
00317 
00318                 // ------------------------------------------------------
00319 
00320                 // Is the encoder supported?  If not, we'll either issue an
00321                 // error or use plain text depending on the debug settings
00322                 if (($prefs['format'] == 'gzip' AND ! @function_exists('gzencode'))
00323                  OR ($prefs['format'] == 'zip'  AND ! @function_exists('gzcompress')))
00324                 {
00325                         if ($this->db->db_debug)
00326                         {
00327                                 return $this->db->display_error('db_unsuported_compression');
00328                         }
00329                 
00330                         $prefs['format'] = 'txt';
00331                 }
00332 
00333                 // ------------------------------------------------------
00334 
00335                 // Set the filename if not provided - Only needed with Zip files
00336                 if ($prefs['filename'] == '' AND $prefs['format'] == 'zip')
00337                 {
00338                         $prefs['filename'] = (count($prefs['tables']) == 1) ? $prefs['tables'] : $this->db->database;
00339                         $prefs['filename'] .= '_'.date('Y-m-d_H-i', time());
00340                 }
00341 
00342                 // ------------------------------------------------------
00343                                 
00344                 // Was a Gzip file requested?
00345                 if ($prefs['format'] == 'gzip')
00346                 {
00347                         return gzencode($this->_backup($prefs));
00348                 }
00349 
00350                 // ------------------------------------------------------
00351                 
00352                 // Was a text file requested?
00353                 if ($prefs['format'] == 'txt')
00354                 {
00355                         return $this->_backup($prefs);
00356                 }
00357 
00358                 // ------------------------------------------------------
00359 
00360                 // Was a Zip file requested?            
00361                 if ($prefs['format'] == 'zip')
00362                 {
00363                         // If they included the .zip file extension we'll remove it
00364                         if (preg_match("|.+?\.zip$|", $prefs['filename']))
00365                         {
00366                                 $prefs['filename'] = str_replace('.zip', '', $prefs['filename']);
00367                         }
00368                         
00369                         // Tack on the ".sql" file extension if needed
00370                         if ( ! preg_match("|.+?\.sql$|", $prefs['filename']))
00371                         {
00372                                 $prefs['filename'] .= '.sql';
00373                         }
00374 
00375                         // Load the Zip class and output it
00376                         
00377                         $CI =& get_instance();
00378                         $CI->load->library('zip');
00379                         $CI->zip->add_data($prefs['filename'], $this->_backup($prefs));                                                 
00380                         return $CI->zip->get_zip();
00381                 }
00382                 
00383         }
00384 
00385 }
00386 
00387 
00388 /* End of file DB_utility.php */
00389 /* Location: ./system/database/DB_utility.php */