Code coverage for /20080809/includes/database.mysqli.inc

Line #Times calledCode
1
<?php
2
// $Id: database.mysqli.inc,v 1.57 2008/04/14 17:48:33 dries Exp $
3
4
/**
5
 * @file
6
 * Database interface code for MySQL database servers using the mysqli
client libraries. mysqli is included in PHP 5 by default and allows
developers to use the advanced features of MySQL 4.1.x, 5.0.x and beyond.
7
 */
8
9
 // Maintainers of this file should consult:
10
 // http://www.php.net/manual/en/ref.mysqli.php
11
12
/**
13
 * @ingroup database
14
 * @{
15
 */
16
17
// Include functions shared between mysql and mysqli.
182027
require_once './includes/database.mysql-common.inc';
19
20
/**
21
 * Report database status.
22
 */
232027
function db_status_report($phase) {
243
  $t = get_t();
25
263
  $version = db_version();
27
283
  $form['mysql'] = array(
293
    'title' => $t('MySQL database'),
303
    'value' => ($phase == 'runtime') ? l($version,
'admin/reports/status/sql') : $version,
31
  );
32
333
  if (version_compare($version, DRUPAL_MINIMUM_MYSQL) < 0) {
340
    $form['mysql']['severity'] = REQUIREMENT_ERROR;
350
    $form['mysql']['description'] = $t('Your MySQL Server is too old.
Drupal requires at least MySQL %version.', array('%version' =>
DRUPAL_MINIMUM_MYSQL));
360
  }
37
383
  return $form;
390
}
40
41
/**
42
 * Returns the version of the database server currently in use.
43
 *
44
 * @return Database server version
45
 */
462027
function db_version() {
473
  global $active_db;
483
  list($version) = explode('-', mysqli_get_server_info($active_db));
493
  return $version;
500
}
51
52
/**
53
 * Initialise a database connection.
54
 *
55
 * Note that mysqli does not support persistent connections.
56
 */
572027
function db_connect($url) {
58
  // Check if MySQLi support is present in PHP
592027
  if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
600
    _db_error_page('Unable to use the MySQLi database because the MySQLi
extension for PHP is not installed. Check your <code>php.ini</code> to see
how you can enable it.');
610
  }
62
632027
  $url = parse_url($url);
64
65
  // Decode url-encoded information in the db connection string
662027
  $url['user'] = urldecode($url['user']);
67
  // Test if database url has a password.
682027
  $url['pass'] = isset($url['pass']) ? urldecode($url['pass']) : '';
692027
  $url['host'] = urldecode($url['host']);
702027
  $url['path'] = urldecode($url['path']);
712027
  if (!isset($url['port'])) {
722027
    $url['port'] = NULL;
732027
  }
74
752027
  $connection = mysqli_init();
762027
  @mysqli_real_connect($connection, $url['host'], $url['user'],
$url['pass'], substr($url['path'], 1), $url['port'], NULL,
MYSQLI_CLIENT_FOUND_ROWS);
77
782027
  if (mysqli_connect_errno() > 0) {
790
    _db_error_page(mysqli_connect_error());
800
  }
81
82
  // Force UTF-8.
832027
  mysqli_query($connection, 'SET NAMES "utf8"');
84
  // Require ANSI mode to improve SQL portability.
852027
  mysqli_query($connection, "SET SESSION sql_mode='ANSI'");
86
872027
  return $connection;
880
}
89
90
/**
91
 * Helper function for db_query().
92
 */
932027
function _db_query($query, $debug = 0) {
942087
  global $active_db, $queries, $user;
95
962087
  if (variable_get('dev_query', 0)) {
970
    list($usec, $sec) = explode(' ', microtime());
980
    $timer = (float)$usec + (float)$sec;
99
    // If devel.module query logging is enabled, prepend a comment with the
username and calling function
100
    // to the SQL string. This is useful when running mysql's SHOW
PROCESSLIST to learn what exact
101
    // code is issueing the slow query.
1020
    $bt = debug_backtrace();
103
    // t() may not be available yet so we don't wrap 'Anonymous'
1040
    $name = $user->uid ? $user->name : variable_get('anonymous',
'Anonymous');
105
    // str_replace() to prevent SQL injection via username or anonymous
name.
1060
    $name = str_replace(array('*', '/'), '', $name);
1070
    $query = '/* ' . $name . ' : ' . $bt[2]['function'] . ' */ ' . $query;
1080
  }
109
1102087
  $result = mysqli_query($active_db, $query);
111
1122087
  if (variable_get('dev_query', 0)) {
1130
    $query = $bt[2]['function'] . "\n" . $query;
1140
    list($usec, $sec) = explode(' ', microtime());
1150
    $stop = (float)$usec + (float)$sec;
1160
    $diff = $stop - $timer;
1170
    $queries[] = array($query, $diff);
1180
  }
119
1202087
  if ($debug) {
1210
    print '<p>query: ' . $query . '<br />error:' . mysqli_error($active_db)
. '</p>';
1220
  }
123
1242087
  if (!mysqli_errno($active_db)) {
1252087
    return $result;
1260
  }
127
  else {
128
    // Indicate to drupal_error_handler that this is a database error.
1290
    ${DB_ERROR} = TRUE;
1300
    trigger_error(check_plain(mysqli_error($active_db) . "\nquery: " .
$query), E_USER_WARNING);
1310
    return FALSE;
132
  }
1330
}
134
135
/**
136
 * Fetch one result row from the previous query as an object.
137
 *
138
 * @param $result
139
 *   A database query result resource, as returned from db_query().
140
 * @return
141
 *   An object representing the next row of the result, or FALSE. The
attributes
142
 *   of this object are the table fields selected by the query.
143
 */
1442027
function db_fetch_object($result) {
1452087
  if ($result) {
1462087
    $object = mysqli_fetch_object($result);
1472087
    return isset($object) ? $object : FALSE;
1480
  }
1490
}
150
151
/**
152
 * Fetch one result row from the previous query as an array.
153
 *
154
 * @param $result
155
 *   A database query result resource, as returned from db_query().
156
 * @return
157
 *   An associative array representing the next row of the result, or
FALSE.
158
 *   The keys of this object are the names of the table fields selected by
the
159
 *   query, and the values are the field values for this result row.
160
 */
1612027
function db_fetch_array($result) {
1622078
  if ($result) {
1632078
    $array = mysqli_fetch_array($result, MYSQLI_ASSOC);
1642078
    return isset($array) ? $array : FALSE;
1650
  }
1660
}
167
168
/**
169
 * Return an individual result field from the previous query.
170
 *
171
 * Only use this function if exactly one field is being selected;
otherwise,
172
 * use db_fetch_object() or db_fetch_array().
173
 *
174
 * @param $result
175
 *   A database query result resource, as returned from db_query().
176
 * @return
177
 *   The resulting field or FALSE.
178
 */
1792027
function db_result($result) {
1802087
  if ($result && mysqli_num_rows($result) > 0) {
181
    // The mysqli_fetch_row function has an optional second parameter $row
182
    // but that can't be used for compatibility with Oracle, DB2, etc.
1832087
    $array = mysqli_fetch_row($result);
1842087
    return $array[0];
1850
  }
1862087
  return FALSE;
1870
}
188
189
/**
190
 * Determine whether the previous query caused an error.
191
 */
1922027
function db_error() {
1930
  global $active_db;
1940
  return mysqli_errno($active_db);
1950
}
196
197
/**
198
 * Determine the number of rows changed by the preceding query.
199
 */
2002027
function db_affected_rows() {
2011700
  global $active_db; /* mysqli connection resource */
2021700
  return mysqli_affected_rows($active_db);
2030
}
204
205
/**
206
 * Runs a limited-range query in the active database.
207
 *
208
 * Use this as a substitute for db_query() when a subset of the query is to
be
209
 * returned.
210
 * User-supplied arguments to the query should be passed in as separate
parameters
211
 * so that they can be properly escaped to avoid SQL injection attacks.
212
 *
213
 * @param $query
214
 *   A string containing an SQL query.
215
 * @param ...
216
 *   A variable number of arguments which are substituted into the query
217
 *   using printf() syntax. The query arguments can be enclosed in one
218
 *   array instead.
219
 *   Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
220
 *   in '') and %%.
221
 *
222
 *   NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
223
 *   and TRUE values to decimal 1.
224
 *
225
 * @param $from
226
 *   The first result row to return.
227
 * @param $count
228
 *   The maximum number of result rows to return.
229
 * @return
230
 *   A database query result resource, or FALSE if the query was not
executed
231
 *   correctly.
232
 */
2332027
function db_query_range($query) {
2342071
  $args = func_get_args();
2352071
  $count = array_pop($args);
2362071
  $from = array_pop($args);
2372071
  array_shift($args);
238
2392071
  $query = db_prefix_tables($query);
2402071
  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one
array' syntax
2412070
    $args = $args[0];
2422070
  }
2432071
  _db_query_callback($args, TRUE);
2442071
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback',
$query);
2452071
  $query .= ' LIMIT ' . (int)$from . ', ' . (int)$count;
2462071
  return _db_query($query);
2470
}
248
249
/**
250
 * Runs a SELECT query and stores its results in a temporary table.
251
 *
252
 * Use this as a substitute for db_query() when the results need to stored
253
 * in a temporary table. Temporary tables exist for the duration of the
page
254
 * request.
255
 * User-supplied arguments to the query should be passed in as separate
parameters
256
 * so that they can be properly escaped to avoid SQL injection attacks.
257
 *
258
 * Note that if you need to know how many results were returned, you should
do
259
 * a SELECT COUNT(*) on the temporary table afterwards. db_affected_rows()
does
260
 * not give consistent result across different database types in this
case.
261
 *
262
 * @param $query
263
 *   A string containing a normal SELECT SQL query.
264
 * @param ...
265
 *   A variable number of arguments which are substituted into the query
266
 *   using printf() syntax. The query arguments can be enclosed in one
267
 *   array instead.
268
 *   Valid %-modifiers are: %s, %d, %f, %b (binary data, do not enclose
269
 *   in '') and %%.
270
 *
271
 *   NOTE: using this syntax will cast NULL and FALSE values to decimal 0,
272
 *   and TRUE values to decimal 1.
273
 *
274
 * @param $table
275
 *   The name of the temporary table to select into. This name will not be
276
 *   prefixed as there is no risk of collision.
277
 * @return
278
 *   A database query result resource, or FALSE if the query was not
executed
279
 *   correctly.
280
 */
2812027
function db_query_temporary($query) {
2820
  $args = func_get_args();
2830
  $tablename = array_pop($args);
2840
  array_shift($args);
285
2860
  $query = preg_replace('/^SELECT/i', 'CREATE TEMPORARY TABLE ' .
$tablename . ' Engine=HEAP SELECT', db_prefix_tables($query));
2870
  if (isset($args[0]) and is_array($args[0])) { // 'All arguments in one
array' syntax
2880
    $args = $args[0];
2890
  }
2900
  _db_query_callback($args, TRUE);
2910
  $query = preg_replace_callback(DB_QUERY_REGEXP, '_db_query_callback',
$query);
2920
  return _db_query($query);
2930
}
294
295
/**
296
 * Returns a properly formatted Binary Large Object value.
297
 *
298
 * @param $data
299
 *   Data to encode.
300
 * @return
301
 *  Encoded data.
302
 */
3032027
function db_encode_blob($data) {
3041295
  global $active_db;
3051295
  return "'" . mysqli_real_escape_string($active_db, $data) . "'";
3060
}
307
308
/**
309
 * Returns text from a Binary Large OBject value.
310
 *
311
 * @param $data
312
 *   Data to decode.
313
 * @return
314
 *  Decoded data.
315
 */
3162027
function db_decode_blob($data) {
3172087
  return $data;
3180
}
319
320
/**
321
 * Prepare user input for use in a database query, preventing SQL injection
attacks.
322
 */
3232027
function db_escape_string($text) {
3242087
  global $active_db;
3252087
  return mysqli_real_escape_string($active_db, $text);
3260
}
327
328
/**
329
 * Lock a table.
330
 */
3312027
function db_lock_table($table) {
3320
  db_query('LOCK TABLES {' . db_escape_table($table) . '} WRITE');
3330
}
334
335
/**
336
 * Unlock all locked tables.
337
 */
3382027
function db_unlock_tables() {
3390
  db_query('UNLOCK TABLES');
3400
}
341
342
/**
343
 * Check if a table exists.
344
 */
3452027
function db_table_exists($table) {
3461
  return (bool) db_fetch_object(db_query("SHOW TABLES LIKE '{" .
db_escape_table($table) . "}'"));
3470
}
348
349
/**
350
 * Check if a column exists in the given table.
351
 */
3522027
function db_column_exists($table, $column) {
3530
  return (bool) db_fetch_object(db_query("SHOW COLUMNS FROM {" .
db_escape_table($table) . "} LIKE '" . db_escape_table($column) . "'"));
3540
}
355
356
/**
357
 * Wraps the given table.field entry with a DISTINCT(). The wrapper is
added to
358
 * the SELECT list entry of the given query and the resulting query is
returned.
359
 * This function only applies the wrapper if a DISTINCT doesn't already
exist in
360
 * the query.
361
 *
362
 * @param $table Table containing the field to set as DISTINCT
363
 * @param $field Field to set as DISTINCT
364
 * @param $query Query to apply the wrapper to
365
 * @return SQL query with the DISTINCT wrapper surrounding the given
table.field.
366
 */
3672027
function db_distinct_field($table, $field, $query) {
3680
  $field_to_select = 'DISTINCT(' . $table . '.' . $field . ')';
369
  // (?<!text) is a negative look-behind (no need to rewrite queries that
already use DISTINCT).
3700
  return preg_replace('/(SELECT.*)(?:' . $table .
'\.|\s)(?<!DISTINCT\()(?<!DISTINCT\(' . $table . '\.)' . $field . '(.*FROM
)/AUsi', '\1 ' . $field_to_select . '\2', $query);
3710
}
372
373
/**
374
 * @} End of "ingroup database".
375
 */
376
3772027