PageRenderTime 45ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/tags/Doduo/WebKitSite/blog/wp-includes/wp-db.php

https://github.com/weissms/owb-mirror
PHP | 435 lines | 275 code | 63 blank | 97 comment | 55 complexity | b29c0fc120201edaf93d0fbe565a70ef MD5 | raw file
  1. <?php
  2. // WordPress DB Class
  3. // ORIGINAL CODE FROM:
  4. // Justin Vincent (justin@visunet.ie)
  5. // http://php.justinvincent.com
  6. define('EZSQL_VERSION', 'WP1.25');
  7. define('OBJECT', 'OBJECT', true);
  8. define('ARRAY_A', 'ARRAY_A', false);
  9. define('ARRAY_N', 'ARRAY_N', false);
  10. if (!defined('SAVEQUERIES'))
  11. define('SAVEQUERIES', false);
  12. class wpdb {
  13. var $show_errors = false;
  14. var $num_queries = 0;
  15. var $last_query;
  16. var $col_info;
  17. var $queries;
  18. var $ready = false;
  19. // Our tables
  20. var $posts;
  21. var $users;
  22. var $categories;
  23. var $post2cat;
  24. var $comments;
  25. var $links;
  26. var $options;
  27. var $optiontypes;
  28. var $optionvalues;
  29. var $optiongroups;
  30. var $optiongroup_options;
  31. var $postmeta;
  32. var $usermeta;
  33. var $terms;
  34. var $term_taxonomy;
  35. var $term_relationships;
  36. var $charset;
  37. var $collate;
  38. /**
  39. * Connects to the database server and selects a database
  40. * @param string $dbuser
  41. * @param string $dbpassword
  42. * @param string $dbname
  43. * @param string $dbhost
  44. */
  45. function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
  46. return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
  47. }
  48. function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
  49. register_shutdown_function(array(&$this, "__destruct"));
  50. if ( defined('WP_DEBUG') and WP_DEBUG == true )
  51. $this->show_errors();
  52. if ( defined('DB_CHARSET') )
  53. $this->charset = DB_CHARSET;
  54. if ( defined('DB_COLLATE') )
  55. $this->collate = DB_COLLATE;
  56. $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword);
  57. if (!$this->dbh) {
  58. $this->bail("
  59. <h1>Error establishing a database connection</h1>
  60. <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>$dbhost</code>. This could mean your host's database server is down.</p>
  61. <ul>
  62. <li>Are you sure you have the correct username and password?</li>
  63. <li>Are you sure that you have typed the correct hostname?</li>
  64. <li>Are you sure that the database server is running?</li>
  65. </ul>
  66. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>
  67. ");
  68. return;
  69. }
  70. $this->ready = true;
  71. if ( !empty($this->charset) && version_compare(mysql_get_server_info(), '4.1.0', '>=') )
  72. $this->query("SET NAMES '$this->charset'");
  73. $this->select($dbname);
  74. }
  75. function __destruct() {
  76. return true;
  77. }
  78. /**
  79. * Selects a database using the current class's $this->dbh
  80. * @param string $db name
  81. */
  82. function select($db) {
  83. if (!@mysql_select_db($db, $this->dbh)) {
  84. $this->ready = false;
  85. $this->bail("
  86. <h1>Can&#8217;t select database</h1>
  87. <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>$db</code> database.</p>
  88. <ul>
  89. <li>Are you sure it exists?</li>
  90. <li>Does the user <code>".DB_USER."</code> have permission to use the <code>$db</code> database?</li>
  91. <li>On some systems the name of your database is prefixed with your username, so it would be like username_wordpress. Could that be the problem?</li>
  92. </ul>
  93. <p>If you don't know how to setup a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>");
  94. return;
  95. }
  96. }
  97. /**
  98. * Escapes content for insertion into the database, for security
  99. *
  100. * @param string $string
  101. * @return string query safe string
  102. */
  103. function escape($string) {
  104. return addslashes( $string ); // Disable rest for now, causing problems
  105. if( !$this->dbh || version_compare( phpversion(), '4.3.0' ) == '-1' )
  106. return mysql_escape_string( $string );
  107. else
  108. return mysql_real_escape_string( $string, $this->dbh );
  109. }
  110. /**
  111. * Escapes content by reference for insertion into the database, for security
  112. * @param string $s
  113. */
  114. function escape_by_ref(&$s) {
  115. $s = $this->escape($s);
  116. }
  117. /**
  118. * Prepares a SQL query for safe use, using sprintf() syntax
  119. */
  120. function prepare($args=NULL) {
  121. if ( NULL === $args )
  122. return;
  123. $args = func_get_args();
  124. $query = array_shift($args);
  125. $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
  126. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  127. $query = str_replace('%s', "'%s'", $query); // quote the strings
  128. array_walk($args, array(&$this, 'escape_by_ref'));
  129. return @vsprintf($query, $args);
  130. }
  131. // ==================================================================
  132. // Print SQL/DB error.
  133. function print_error($str = '') {
  134. global $EZSQL_ERROR;
  135. if (!$str) $str = mysql_error($this->dbh);
  136. $EZSQL_ERROR[] =
  137. array ('query' => $this->last_query, 'error_str' => $str);
  138. $error_str = "WordPress database error $str for query $this->last_query";
  139. error_log($error_str, 0);
  140. // Is error output turned on or not..
  141. if ( !$this->show_errors )
  142. return false;
  143. $str = htmlspecialchars($str, ENT_QUOTES);
  144. $query = htmlspecialchars($this->last_query, ENT_QUOTES);
  145. // If there is an error then take note of it
  146. print "<div id='error'>
  147. <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
  148. <code>$query</code></p>
  149. </div>";
  150. }
  151. // ==================================================================
  152. // Turn error handling on or off..
  153. function show_errors( $show = true ) {
  154. $errors = $this->show_errors;
  155. $this->show_errors = $show;
  156. return $errors;
  157. }
  158. function hide_errors() {
  159. $show = $this->show_errors;
  160. $this->show_errors = false;
  161. return $show;
  162. }
  163. // ==================================================================
  164. // Kill cached query results
  165. function flush() {
  166. $this->last_result = array();
  167. $this->col_info = null;
  168. $this->last_query = null;
  169. }
  170. // ==================================================================
  171. // Basic Query - see docs for more detail
  172. function query($query) {
  173. if ( ! $this->ready )
  174. return false;
  175. // filter the query, if filters are available
  176. // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  177. if ( function_exists('apply_filters') )
  178. $query = apply_filters('query', $query);
  179. // initialise return
  180. $return_val = 0;
  181. $this->flush();
  182. // Log how the function was called
  183. $this->func_call = "\$db->query(\"$query\")";
  184. // Keep track of the last query for debug..
  185. $this->last_query = $query;
  186. // Perform the query via std mysql_query function..
  187. if (SAVEQUERIES)
  188. $this->timer_start();
  189. $this->result = @mysql_query($query, $this->dbh);
  190. ++$this->num_queries;
  191. if (SAVEQUERIES)
  192. $this->queries[] = array( $query, $this->timer_stop() );
  193. // If there is an error then take note of it..
  194. if ( mysql_error($this->dbh) ) {
  195. $this->print_error();
  196. return false;
  197. }
  198. if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
  199. $this->rows_affected = mysql_affected_rows($this->dbh);
  200. // Take note of the insert_id
  201. if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
  202. $this->insert_id = mysql_insert_id($this->dbh);
  203. }
  204. // Return number of rows affected
  205. $return_val = $this->rows_affected;
  206. } else {
  207. $i = 0;
  208. while ($i < @mysql_num_fields($this->result)) {
  209. $this->col_info[$i] = @mysql_fetch_field($this->result);
  210. $i++;
  211. }
  212. $num_rows = 0;
  213. while ( $row = @mysql_fetch_object($this->result) ) {
  214. $this->last_result[$num_rows] = $row;
  215. $num_rows++;
  216. }
  217. @mysql_free_result($this->result);
  218. // Log number of rows the query returned
  219. $this->num_rows = $num_rows;
  220. // Return number of rows selected
  221. $return_val = $this->num_rows;
  222. }
  223. return $return_val;
  224. }
  225. /**
  226. * Get one variable from the database
  227. * @param string $query (can be null as well, for caching, see codex)
  228. * @param int $x = 0 row num to return
  229. * @param int $y = 0 col num to return
  230. * @return mixed results
  231. */
  232. function get_var($query=null, $x = 0, $y = 0) {
  233. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  234. if ( $query )
  235. $this->query($query);
  236. // Extract var out of cached results based x,y vals
  237. if ( $this->last_result[$y] ) {
  238. $values = array_values(get_object_vars($this->last_result[$y]));
  239. }
  240. // If there is a value return it else return null
  241. return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
  242. }
  243. /**
  244. * Get one row from the database
  245. * @param string $query
  246. * @param string $output ARRAY_A | ARRAY_N | OBJECT
  247. * @param int $y row num to return
  248. * @return mixed results
  249. */
  250. function get_row($query = null, $output = OBJECT, $y = 0) {
  251. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  252. if ( $query )
  253. $this->query($query);
  254. else
  255. return null;
  256. if ( !isset($this->last_result[$y]) )
  257. return null;
  258. if ( $output == OBJECT ) {
  259. return $this->last_result[$y] ? $this->last_result[$y] : null;
  260. } elseif ( $output == ARRAY_A ) {
  261. return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
  262. } elseif ( $output == ARRAY_N ) {
  263. return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
  264. } else {
  265. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  266. }
  267. }
  268. /**
  269. * Gets one column from the database
  270. * @param string $query (can be null as well, for caching, see codex)
  271. * @param int $x col num to return
  272. * @return array results
  273. */
  274. function get_col($query = null , $x = 0) {
  275. if ( $query )
  276. $this->query($query);
  277. $new_array = array();
  278. // Extract the column values
  279. for ( $i=0; $i < count($this->last_result); $i++ ) {
  280. $new_array[$i] = $this->get_var(null, $x, $i);
  281. }
  282. return $new_array;
  283. }
  284. /**
  285. * Return an entire result set from the database
  286. * @param string $query (can also be null to pull from the cache)
  287. * @param string $output ARRAY_A | ARRAY_N | OBJECT
  288. * @return mixed results
  289. */
  290. function get_results($query = null, $output = OBJECT) {
  291. $this->func_call = "\$db->get_results(\"$query\", $output)";
  292. if ( $query )
  293. $this->query($query);
  294. else
  295. return null;
  296. // Send back array of objects. Each row is an object
  297. if ( $output == OBJECT ) {
  298. return $this->last_result;
  299. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  300. if ( $this->last_result ) {
  301. $i = 0;
  302. foreach( $this->last_result as $row ) {
  303. $new_array[$i] = (array) $row;
  304. if ( $output == ARRAY_N ) {
  305. $new_array[$i] = array_values($new_array[$i]);
  306. }
  307. $i++;
  308. }
  309. return $new_array;
  310. } else {
  311. return null;
  312. }
  313. }
  314. }
  315. /**
  316. * Grabs column metadata from the last query
  317. * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  318. * @param int $col_offset 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type
  319. * @return mixed results
  320. */
  321. function get_col_info($info_type = 'name', $col_offset = -1) {
  322. if ( $this->col_info ) {
  323. if ( $col_offset == -1 ) {
  324. $i = 0;
  325. foreach($this->col_info as $col ) {
  326. $new_array[$i] = $col->{$info_type};
  327. $i++;
  328. }
  329. return $new_array;
  330. } else {
  331. return $this->col_info[$col_offset]->{$info_type};
  332. }
  333. }
  334. }
  335. /**
  336. * Starts the timer, for debugging purposes
  337. */
  338. function timer_start() {
  339. $mtime = microtime();
  340. $mtime = explode(' ', $mtime);
  341. $this->time_start = $mtime[1] + $mtime[0];
  342. return true;
  343. }
  344. /**
  345. * Stops the debugging timer
  346. * @return int total time spent on the query, in milliseconds
  347. */
  348. function timer_stop() {
  349. $mtime = microtime();
  350. $mtime = explode(' ', $mtime);
  351. $time_end = $mtime[1] + $mtime[0];
  352. $time_total = $time_end - $this->time_start;
  353. return $time_total;
  354. }
  355. /**
  356. * Wraps fatal errors in a nice header and footer and dies.
  357. * @param string $message
  358. */
  359. function bail($message) { // Just wraps errors in a nice header and footer
  360. if ( !$this->show_errors ) {
  361. if ( class_exists('WP_Error') )
  362. $this->error = new WP_Error('500', $message);
  363. else
  364. $this->error = $message;
  365. return false;
  366. }
  367. wp_die($message);
  368. }
  369. }
  370. if ( ! isset($wpdb) )
  371. $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
  372. ?>