PageRenderTime 53ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

/system/database/DB_utility.php

https://bitbucket.org/hlevine/myclientbase-south-african-version
PHP | 414 lines | 206 code | 71 blank | 137 comment | 32 complexity | 49c7d13150d2f407a584485476230cc8 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, GPL-2.0
  1. <?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
  2. /**
  3. * Code Igniter
  4. *
  5. * An open source application development framework for PHP 5.1.6 or newer
  6. *
  7. * @package CodeIgniter
  8. * @author ExpressionEngine Dev Team
  9. * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc.
  10. * @license http://codeigniter.com/user_guide/license.html
  11. * @link http://codeigniter.com
  12. * @since Version 1.0
  13. * @filesource
  14. */
  15. // ------------------------------------------------------------------------
  16. /**
  17. * Database Utility Class
  18. *
  19. * @category Database
  20. * @author ExpressionEngine Dev Team
  21. * @link http://codeigniter.com/user_guide/database/
  22. */
  23. class CI_DB_utility extends CI_DB_forge {
  24. var $db;
  25. var $data_cache = array();
  26. /**
  27. * Constructor
  28. *
  29. * Grabs the CI super object instance so we can access it.
  30. *
  31. */
  32. function __construct()
  33. {
  34. // Assign the main database object to $this->db
  35. $CI =& get_instance();
  36. $this->db =& $CI->db;
  37. log_message('debug', "Database Utility Class Initialized");
  38. }
  39. // --------------------------------------------------------------------
  40. /**
  41. * List databases
  42. *
  43. * @access public
  44. * @return bool
  45. */
  46. function list_databases()
  47. {
  48. // Is there a cached result?
  49. if (isset($this->data_cache['db_names']))
  50. {
  51. return $this->data_cache['db_names'];
  52. }
  53. $query = $this->db->query($this->_list_databases());
  54. $dbs = array();
  55. if ($query->num_rows() > 0)
  56. {
  57. foreach ($query->result_array() as $row)
  58. {
  59. $dbs[] = current($row);
  60. }
  61. }
  62. $this->data_cache['db_names'] = $dbs;
  63. return $this->data_cache['db_names'];
  64. }
  65. // --------------------------------------------------------------------
  66. /**
  67. * Determine if a particular database exists
  68. *
  69. * @access public
  70. * @param string
  71. * @return boolean
  72. */
  73. function database_exists($database_name)
  74. {
  75. // Some databases won't have access to the list_databases() function, so
  76. // this is intended to allow them to override with their own functions as
  77. // defined in $driver_utility.php
  78. if (method_exists($this, '_database_exists'))
  79. {
  80. return $this->_database_exists($database_name);
  81. }
  82. else
  83. {
  84. return ( ! in_array($database_name, $this->list_databases())) ? FALSE : TRUE;
  85. }
  86. }
  87. // --------------------------------------------------------------------
  88. /**
  89. * Optimize Table
  90. *
  91. * @access public
  92. * @param string the table name
  93. * @return bool
  94. */
  95. function optimize_table($table_name)
  96. {
  97. $sql = $this->_optimize_table($table_name);
  98. if (is_bool($sql))
  99. {
  100. show_error('db_must_use_set');
  101. }
  102. $query = $this->db->query($sql);
  103. $res = $query->result_array();
  104. // Note: Due to a bug in current() that affects some versions
  105. // of PHP we can not pass function call directly into it
  106. return current($res);
  107. }
  108. // --------------------------------------------------------------------
  109. /**
  110. * Optimize Database
  111. *
  112. * @access public
  113. * @return array
  114. */
  115. function optimize_database()
  116. {
  117. $result = array();
  118. foreach ($this->db->list_tables() as $table_name)
  119. {
  120. $sql = $this->_optimize_table($table_name);
  121. if (is_bool($sql))
  122. {
  123. return $sql;
  124. }
  125. $query = $this->db->query($sql);
  126. // Build the result array...
  127. // Note: Due to a bug in current() that affects some versions
  128. // of PHP we can not pass function call directly into it
  129. $res = $query->result_array();
  130. $res = current($res);
  131. $key = str_replace($this->db->database.'.', '', current($res));
  132. $keys = array_keys($res);
  133. unset($res[$keys[0]]);
  134. $result[$key] = $res;
  135. }
  136. return $result;
  137. }
  138. // --------------------------------------------------------------------
  139. /**
  140. * Repair Table
  141. *
  142. * @access public
  143. * @param string the table name
  144. * @return bool
  145. */
  146. function repair_table($table_name)
  147. {
  148. $sql = $this->_repair_table($table_name);
  149. if (is_bool($sql))
  150. {
  151. return $sql;
  152. }
  153. $query = $this->db->query($sql);
  154. // Note: Due to a bug in current() that affects some versions
  155. // of PHP we can not pass function call directly into it
  156. $res = $query->result_array();
  157. return current($res);
  158. }
  159. // --------------------------------------------------------------------
  160. /**
  161. * Generate CSV from a query result object
  162. *
  163. * @access public
  164. * @param object The query result object
  165. * @param string The delimiter - comma by default
  166. * @param string The newline character - \n by default
  167. * @param string The enclosure - double quote by default
  168. * @return string
  169. */
  170. function csv_from_result($query, $delim = ",", $newline = "\n", $enclosure = '"')
  171. {
  172. if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
  173. {
  174. show_error('You must submit a valid result object');
  175. }
  176. $out = '';
  177. // First generate the headings from the table column names
  178. foreach ($query->list_fields() as $name)
  179. {
  180. $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $name).$enclosure.$delim;
  181. }
  182. $out = rtrim($out);
  183. $out .= $newline;
  184. // Next blast through the result array and build out the rows
  185. foreach ($query->result_array() as $row)
  186. {
  187. foreach ($row as $item)
  188. {
  189. $out .= $enclosure.str_replace($enclosure, $enclosure.$enclosure, $item).$enclosure.$delim;
  190. }
  191. $out = rtrim($out);
  192. $out .= $newline;
  193. }
  194. return $out;
  195. }
  196. // --------------------------------------------------------------------
  197. /**
  198. * Generate XML data from a query result object
  199. *
  200. * @access public
  201. * @param object The query result object
  202. * @param array Any preferences
  203. * @return string
  204. */
  205. function xml_from_result($query, $params = array())
  206. {
  207. if ( ! is_object($query) OR ! method_exists($query, 'list_fields'))
  208. {
  209. show_error('You must submit a valid result object');
  210. }
  211. // Set our default values
  212. foreach (array('root' => 'root', 'element' => 'element', 'newline' => "\n", 'tab' => "\t") as $key => $val)
  213. {
  214. if ( ! isset($params[$key]))
  215. {
  216. $params[$key] = $val;
  217. }
  218. }
  219. // Create variables for convenience
  220. extract($params);
  221. // Load the xml helper
  222. $CI =& get_instance();
  223. $CI->load->helper('xml');
  224. // Generate the result
  225. $xml = "<{$root}>".$newline;
  226. foreach ($query->result_array() as $row)
  227. {
  228. $xml .= $tab."<{$element}>".$newline;
  229. foreach ($row as $key => $val)
  230. {
  231. $xml .= $tab.$tab."<{$key}>".xml_convert($val)."</{$key}>".$newline;
  232. }
  233. $xml .= $tab."</{$element}>".$newline;
  234. }
  235. $xml .= "</$root>".$newline;
  236. return $xml;
  237. }
  238. // --------------------------------------------------------------------
  239. /**
  240. * Database Backup
  241. *
  242. * @access public
  243. * @return void
  244. */
  245. function backup($params = array())
  246. {
  247. // If the parameters have not been submitted as an
  248. // array then we know that it is simply the table
  249. // name, which is a valid short cut.
  250. if (is_string($params))
  251. {
  252. $params = array('tables' => $params);
  253. }
  254. // ------------------------------------------------------
  255. // Set up our default preferences
  256. $prefs = array(
  257. 'tables' => array(),
  258. 'ignore' => array(),
  259. 'filename' => '',
  260. 'format' => 'gzip', // gzip, zip, txt
  261. 'add_drop' => TRUE,
  262. 'add_insert' => TRUE,
  263. 'newline' => "\n"
  264. );
  265. // Did the user submit any preferences? If so set them....
  266. if (count($params) > 0)
  267. {
  268. foreach ($prefs as $key => $val)
  269. {
  270. if (isset($params[$key]))
  271. {
  272. $prefs[$key] = $params[$key];
  273. }
  274. }
  275. }
  276. // ------------------------------------------------------
  277. // Are we backing up a complete database or individual tables?
  278. // If no table names were submitted we'll fetch the entire table list
  279. if (count($prefs['tables']) == 0)
  280. {
  281. $prefs['tables'] = $this->db->list_tables();
  282. }
  283. // ------------------------------------------------------
  284. // Validate the format
  285. if ( ! in_array($prefs['format'], array('gzip', 'zip', 'txt'), TRUE))
  286. {
  287. $prefs['format'] = 'txt';
  288. }
  289. // ------------------------------------------------------
  290. // Is the encoder supported? If not, we'll either issue an
  291. // error or use plain text depending on the debug settings
  292. if (($prefs['format'] == 'gzip' AND ! @function_exists('gzencode'))
  293. OR ($prefs['format'] == 'zip' AND ! @function_exists('gzcompress')))
  294. {
  295. if ($this->db->db_debug)
  296. {
  297. return $this->db->display_error('db_unsuported_compression');
  298. }
  299. $prefs['format'] = 'txt';
  300. }
  301. // ------------------------------------------------------
  302. // Set the filename if not provided - Only needed with Zip files
  303. if ($prefs['filename'] == '' AND $prefs['format'] == 'zip')
  304. {
  305. $prefs['filename'] = (count($prefs['tables']) == 1) ? $prefs['tables'] : $this->db->database;
  306. $prefs['filename'] .= '_'.date('Y-m-d_H-i', time());
  307. }
  308. // ------------------------------------------------------
  309. // Was a Gzip file requested?
  310. if ($prefs['format'] == 'gzip')
  311. {
  312. return gzencode($this->_backup($prefs));
  313. }
  314. // ------------------------------------------------------
  315. // Was a text file requested?
  316. if ($prefs['format'] == 'txt')
  317. {
  318. return $this->_backup($prefs);
  319. }
  320. // ------------------------------------------------------
  321. // Was a Zip file requested?
  322. if ($prefs['format'] == 'zip')
  323. {
  324. // If they included the .zip file extension we'll remove it
  325. if (preg_match("|.+?\.zip$|", $prefs['filename']))
  326. {
  327. $prefs['filename'] = str_replace('.zip', '', $prefs['filename']);
  328. }
  329. // Tack on the ".sql" file extension if needed
  330. if ( ! preg_match("|.+?\.sql$|", $prefs['filename']))
  331. {
  332. $prefs['filename'] .= '.sql';
  333. }
  334. // Load the Zip class and output it
  335. $CI =& get_instance();
  336. $CI->load->library('zip');
  337. $CI->zip->add_data($prefs['filename'], $this->_backup($prefs));
  338. return $CI->zip->get_zip();
  339. }
  340. }
  341. }
  342. /* End of file DB_utility.php */
  343. /* Location: ./system/database/DB_utility.php */