PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/system/database/DB_utility.php

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