Code coverage for /20080809/includes/database.inc

Line #Times calledCode
1
<?php
2
// $Id: database.inc,v 1.96 2008/07/19 12:31:14 dries Exp $
3
4
/**
5
 * @file
6
 * Wrapper for database interface code.
7
 */
8
9
/**
10
 * A hash value to check when outputting database errors, md5('DB_ERROR').
11
 *
12
 * @see drupal_error_handler()
13
 */
142027
define('DB_ERROR', 'a515ac9c2796ca0e23adbe92c68fc9fc');
15
16
/**
17
 * @defgroup database Database abstraction layer
18
 * @{
19
 * Allow the use of different database servers using the same code base.
20
 *
21
 * Drupal provides a slim database abstraction layer to provide developers
with
22
 * the ability to support multiple database servers easily. The intent of
this
23
 * layer is to preserve the syntax and power of SQL as much as possible,
while
24
 * letting Drupal control the pieces of queries that need to be written
25
 * differently for different servers and provide basic security checks.
26
 *
27
 * Most Drupal database queries are performed by a call to db_query() or
28
 * db_query_range(). Module authors should also consider using
pager_query() for
29
 * queries that return results that need to be presented on multiple pages,
and
30
 * tablesort_sql() for generating appropriate queries for sortable tables.
31
 *
32
 * For example, one might wish to return a list of the most recent 10
nodes
33
 * authored by a given user. Instead of directly issuing the SQL query
34
 * @code
35
 *   SELECT n.title, n.body, n.created FROM node n WHERE n.uid = $uid LIMIT
0, 10;
36
 * @endcode
37
 * one would instead call the Drupal functions:
38
 * @code
39
 *   $result = db_query_range('SELECT n.title, n.body, n.created
40
 *     FROM {node} n WHERE n.uid = %d', $uid, 0, 10);
41
 *   while ($node = db_fetch_object($result)) {
42
 *     // Perform operations on $node->body, etc. here.
43
 *   }
44
 * @endcode
45
 * Curly braces are used around "node" to provide table prefixing via
46
 * db_prefix_tables(). The explicit use of a user ID is pulled out into an
47
 * argument passed to db_query() so that SQL injection attacks from user
input
48
 * can be caught and nullified. The LIMIT syntax varies between database
servers,
49
 * so that is abstracted into db_query_range() arguments. Finally, note
the
50
 * common pattern of iterating over the result set using
db_fetch_object().
51
 */
52
53
/**
54
 * Perform an SQL query and return success or failure.
55
 *
56
 * @param $sql
57
 *   A string containing a complete SQL query.  %-substitution
58
 *   parameters are not supported.
59
 * @return
60
 *   An array containing the keys:
61
 *      success: a boolean indicating whether the query succeeded
62
 *      query: the SQL query executed, passed through check_plain()
63
 */
642027
function update_sql($sql) {
6565
  $result = db_query($sql, true);
6665
  return array('success' => $result !== FALSE, 'query' =>
check_plain($sql));
670
}
68
69
/**
70
 * Append a database prefix to all tables in a query.
71
 *
72
 * Queries sent to Drupal should wrap all table names in curly brackets.
This
73
 * function searches for this syntax and adds Drupal's table prefix to all
74
 * tables, allowing Drupal to coexist with other systems in the same
database if
75
 * necessary.
76
 *
77
 * @param $sql
78
 *   A string containing a partial or entire SQL query.
79
 * @return
80
 *   The properly-prefixed string.
81
 */
822027
function db_prefix_tables($sql) {
832087
  global $db_prefix;
84
852087
  if (is_array($db_prefix)) {
860
    if (array_key_exists('default', $db_prefix)) {
870
      $tmp = $db_prefix;
880
      unset($tmp['default']);
890
      foreach ($tmp as $key => $val) {
900
        $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
910
      }
920
      return strtr($sql, array('{' => $db_prefix['default'], '}' => ''));
930
    }
94
    else {
950
      foreach ($db_prefix as $key => $val) {
960
        $sql = strtr($sql, array('{' . $key . '}' => $val . $key));
970
      }
980
      return strtr($sql, array('{' => '', '}' => ''));
99
    }
1000
  }
101
  else {
1022087
    return strtr($sql, array('{' => $db_prefix, '}' => ''));
103
  }
1040
}
105
106
/**
107
 * Activate a database for future queries.
108
 *
109
 * If it is necessary to use external databases in a project, this function
can
110
 * be used to change where database queries are sent. If the database has
not
111
 * yet been used, it is initialized using the URL specified for that name
in
112
 * Drupal's configuration file. If this name is not defined, a duplicate of
the
113
 * default connection is made instead.
114
 *
115
 * Be sure to change the connection back to the default when done with
custom
116
 * code.
117
 *
118
 * @param $name
119
 *   The name assigned to the newly active database connection. If omitted,
the
120
 *   default connection will be made active.
121
 *
122
 * @return the name of the previously active database or FALSE if non was
found.
123
 */
1242027
function db_set_active($name = 'default') {
1252087
  global $db_url, $db_type, $active_db, $db_prefix;
1262087
  static $db_conns, $active_name = FALSE;
127
1282087
  if (empty($db_url)) {
1290
    include_once 'includes/install.inc';
1300
    install_goto('install.php');
1310
  }
132
1332087
  if (!isset($db_conns[$name])) {
134
    // Initiate a new connection, using the named DB URL specified.
1352027
    if (is_array($db_url)) {
1360
      $connect_url = array_key_exists($name, $db_url) ? $db_url[$name] :
$db_url['default'];
1370
    }
138
    else {
1392027
      $connect_url = $db_url;
140
    }
141
1422027
    $db_type = substr($connect_url, 0, strpos($connect_url, '://'));
1432027
    $handler = "./includes/database.$db_type.inc";
144
1452027
    if (is_file($handler)) {
1462027
      include_once $handler;
1472027
    }
148
    else {
1490
      _db_error_page("The database type '" . $db_type . "' is unsupported.
Please use either 'mysql' or 'mysqli' for MySQL, or 'pgsql' for PostgreSQL
databases.");
150
    }
151
1522027
    $db_conns[$name] = db_connect($connect_url);
153
    // We need to pass around the simpletest database prefix in the
request
154
    // and we put that in the user_agent header.
1552027
    if (preg_match("/^simpletest\d+$/", $_SERVER['HTTP_USER_AGENT'])) {
1562027
      $db_prefix = $_SERVER['HTTP_USER_AGENT'];
1572027
    }
158
1592027
  }
160
1612087
  $previous_name = $active_name;
162
  // Set the active connection.
1632087
  $active_name = $name;
1642087
  $active_db = $db_conns[$name];
165
1662087
  return $previous_name;
1670
}
168
169
/**
170
 * Helper function to show fatal database errors.
171
 *
172
 * Prints a themed maintenance page with the 'Site offline' text,
173
 * adding the provided error message in the case of 'display_errors'
174
 * set to on. Ends the page request; no return.
175
 *
176
 * @param $error
177
 *   The error message to be appended if 'display_errors' is on.
178
 */
1792027
function _db_error_page($error = '') {
1800
  global $db_type;
1810
  drupal_maintenance_theme();
1820
  drupal_set_header('HTTP/1.1 503 Service Unavailable');
1830
  drupal_set_title('Site offline');
184
1850
  $message = '<p>The site is currently not available due to technical
problems. Please try again later. Thank you for your understanding.</p>';
1860
  $message .= '<hr /><p><small>If you are the maintainer of this site,
please check your database settings in the <code>settings.php</code> file
and ensure that your hosting provider\'s database server is running. For
more help, see the <a href="http://drupal.org/node/258">handbook</a>, or
contact your hosting provider.</small></p>';
187
1880
  if ($error && ini_get('display_errors')) {
1890
    $message .= '<p><small>The ' . theme('placeholder', $db_type) . ' error
was: ' . theme('placeholder', $error) . '.</small></p>';
1900
  }
191
1920
  print theme('maintenance_page', $message);
1930
  exit;
1940
}
195
196
/**
197
 * Returns a boolean depending on the availability of the database.
198
 */
1992027
function db_is_active() {
2002027
  global $active_db;
2012027
  return !empty($active_db);
2020
}
203
204
/**
205
 * Helper function for db_query().
206
 */
2072027
function _db_query_callback($match, $init = FALSE) {
2082087
  static $args = NULL;
2092087
  if ($init) {
2102087
    $args = $match;
2112087
    return;
2120
  }
213
2142087
  switch ($match[1]) {
2152087
    case '%d': // We must use type casting to int to convert
FALSE/NULL/(TRUE?)
2162087
      return (int) array_shift($args); // We don't need db_escape_string as
numbers are db-safe
2172087
    case '%s':
2182087
      return db_escape_string(array_shift($args));
2191369
    case '%n':
220
      // Numeric values have arbitrary precision, so can't be treated as
float.
221
      // is_numeric() allows hex values (0xFF), but they are not valid.
2220
      $value = trim(array_shift($args));
2230
      return (is_numeric($value) && !stripos($value, 'x')) ? $value : '0';
2241369
    case '%%':
225261
      return '%';
2261295
    case '%f':
2272
      return (float) array_shift($args);
2281295
    case '%b': // binary data
2291295
      return db_encode_blob(array_shift($args));
2300
  }
2310
}
232
233
/**
234
 * Generate placeholders for an array of query arguments of a single type.
235
 *
236
 * Given a Schema API field type, return correct %-placeholders to
237
 * embed in a query
238
 *
239
 * @param $arguments
240
 *  An array with at least one element.
241
 * @param $type
242
 *   The Schema API type of a field (e.g. 'int', 'text', or 'varchar').
243
 */
2442027
function db_placeholders($arguments, $type = 'int') {
2451844
  $placeholder = db_type_placeholder($type);
2461844
  return implode(',', array_fill(0, count($arguments), $placeholder));
2470
}
248
249
/**
250
 * Indicates the place holders that should be replaced in
_db_query_callback().
251
 */
2522027
define('DB_QUERY_REGEXP', '/(%d|%s|%%|%f|%b|%n)/');
253
254
/**
255
 * Helper function for db_rewrite_sql.
256
 *
257
 * Collects JOIN and WHERE statements via hook_db_rewrite_sql()
258
 * Decides whether to select primary_key or DISTINCT(primary_key)
259
 *
260
 * @param $query
261
 *   Query to be rewritten.
262
 * @param $primary_table
263
 *   Name or alias of the table which has the primary key field for this
query.
264
 *   Typical table names would be: {blocks}, {comments}, {forum}, {node},
265
 *   {menu}, {term_data} or {vocabulary}. However, in most cases the usual
266
 *   table alias (b, c, f, n, m, t or v) is used instead of the table
name.
267
 * @param $primary_field
268
 *   Name of the primary field.
269
 * @param $args
270
 *   Array of additional arguments.
271
 * @return
272
 *   An array: join statements, where statements, field or
DISTINCT(field).
273
 */
2742027
function _db_rewrite_sql($query = '', $primary_table = 'n', $primary_field
= 'nid', $args = array()) {
2751724
  $where = array();
2761724
  $join = array();
2771724
  $distinct = FALSE;
2781724
  foreach (module_implements('db_rewrite_sql') as $module) {
2791724
    $result = module_invoke($module, 'db_rewrite_sql', $query,
$primary_table, $primary_field, $args);
2801724
    if (isset($result) && is_array($result)) {
2810
      if (isset($result['where'])) {
2820
        $where[] = $result['where'];
2830
      }
2840
      if (isset($result['join'])) {
2850
        $join[] = $result['join'];
2860
      }
2870
      if (isset($result['distinct']) && $result['distinct']) {
2880
        $distinct = TRUE;
2890
      }
2900
    }
2911724
    elseif (isset($result)) {
2920
      $where[] = $result;
2930
    }
2941724
  }
295
2961724
  $where = empty($where) ? '' : '(' . implode(') AND (', $where) . ')';
2971724
  $join = empty($join) ? '' : implode(' ', $join);
298
2991724
  return array($join, $where, $distinct);
3000
}
301
302
/**
303
 * Rewrites node, taxonomy and comment queries. Use it for listing queries.
Do not
304
 * use FROM table1, table2 syntax, use JOIN instead.
305
 *
306
 * @param $query
307
 *   Query to be rewritten.
308
 * @param $primary_table
309
 *   Name or alias of the table which has the primary key field for this
query.
310
 *   Typical table names would be: {blocks}, {comments}, {forum}, {node},
311
 *   {menu}, {term_data} or {vocabulary}. However, it is more common to use
the
312
 *   the usual table aliases: b, c, f, n, m, t or v.
313
 * @param $primary_field
314
 *   Name of the primary field.
315
 * @param $args
316
 *   An array of arguments, passed to the implementations of
hook_db_rewrite_sql.
317
 * @return
318
 *   The original query with JOIN and WHERE statements inserted from
319
 *   hook_db_rewrite_sql implementations. nid is rewritten if needed.
320
 */
3212027
function db_rewrite_sql($query, $primary_table = 'n', $primary_field =
'nid',  $args = array()) {
3221724
  list($join, $where, $distinct) = _db_rewrite_sql($query, $primary_table,
$primary_field, $args);
323
3241724
  if ($distinct) {
3250
    $query = db_distinct_field($primary_table, $primary_field, $query);
3260
  }
327
3281724
  if (!empty($where) || !empty($join)) {
329
    $pattern = '{
330
      # Beginning of the string
331
      ^
332
      ((?P<anonymous_view>
333
        # Everything within this set of parentheses is named "anonymous
view"
334
        (?:
335
          [^()]++                   # anything not parentheses
336
        |
337
          \( (?P>anonymous_view) \)          # an open parenthesis, more
"anonymous view" and finally a close parenthesis.
338
        )*
339
      )[^()]+WHERE)
3400
    }x';
3410
    preg_match($pattern, $query, $matches);
3420
    if ($where) {
3430
      $n = strlen($matches[1]);
3440
      $second_part = substr($query, $n);
3450
      $first_part = substr($matches[1], 0, $n - 5) . " $join WHERE $where
AND ( ";
346
      // PHP 4 does not support strrpos for strings. We emulate it.
3470
      $haystack_reverse = strrev($second_part);
348
      // No need to use strrev on the needle, we supply GROUP, ORDER,
LIMIT
349
      // reversed.
3500
      foreach (array('PUORG', 'REDRO', 'TIMIL') as $needle_reverse) {
3510
        $pos = strpos($haystack_reverse, $needle_reverse);
3520
        if ($pos !== FALSE) {
353
          // All needles are five characters long.
3540
          $pos += 5;
3550
          break;
3560
        }
3570
      }
3580
      if ($pos === FALSE) {
3590
        $query = $first_part . $second_part . ')';
3600
      }
361
      else {
3620
        $query = $first_part . substr($second_part, 0, -$pos) . ')' .
substr($second_part, -$pos);
363
      }
3640
    }
365
    else {
3660
      $query = $matches[1] . " $join " . substr($query,
strlen($matches[1]));
367
    }
3680
  }
369
3701724
  return $query;
3710
}
372
373
/**
374
 * Restrict a dynamic table, column or constraint name to safe characters.
375
 *
376
 * Only keeps alphanumeric and underscores.
377
 */
3782027
function db_escape_table($string) {
37913
  return preg_replace('/[^A-Za-z0-9_]+/', '', $string);
3800
}
381
382
/**
383
 * @} End of "defgroup database".
384
 */
385
386
/**
387
 * @defgroup schemaapi Schema API
388
 * @{
389
 *
390
 * A Drupal schema definition is an array structure representing one or
391
 * more tables and their related keys and indexes. A schema is defined by
392
 * hook_schema(), which usually lives in a modulename.install file.
393
 *
394
 * By implementing hook_schema() and specifying the tables your module
395
 * declares, you can easily create and drop these tables on all
396
 * supported database engines. You don't have to deal with the
397
 * different SQL dialects for table creation and alteration of the
398
 * supported database engines.
399
 *
400
 * hook_schema() should return an array with a key for each table that
401
 * the module defines.
402
 *
403
 * The following keys are defined:
404
 *
405
 *   - 'description': A string describing this table and its purpose.
406
 *     References to other tables should be enclosed in
407
 *     curly-brackets.  For example, the node_revisions table
408
 *     description field might contain "Stores per-revision title and
409
 *     body data for each {node}."
410
 *   - 'fields': An associative array ('fieldname' => specification)
411
 *     that describes the table's database columns.  The specification
412
 *     is also an array.  The following specification parameters are
defined:
413
 *
414
 *     - 'description': A string describing this field and its purpose.
415
 *       References to other tables should be enclosed in
416
 *       curly-brackets.  For example, the node table vid field
417
 *       description might contain "Always holds the largest (most
418
 *       recent) {node_revisions}.vid value for this nid."
419
 *     - 'type': The generic datatype: 'varchar', 'int', 'serial'
420
 *       'float', 'numeric', 'text', 'blob' or 'datetime'.  Most types
421
 *       just map to the according database engine specific
422
 *       datatypes.  Use 'serial' for auto incrementing fields. This
423
 *       will expand to 'int auto_increment' on mysql.
424
 *     - 'size': The data size: 'tiny', 'small', 'medium', 'normal',
425
 *       'big'.  This is a hint about the largest value the field will
426
 *       store and determines which of the database engine specific
427
 *       datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs.
BIGINT).
428
 *       'normal', the default, selects the base type (e.g. on MySQL,
429
 *       INT, VARCHAR, BLOB, etc.).
430
 *
431
 *       Not all sizes are available for all data types. See
432
 *       db_type_map() for possible combinations.
433
 *     - 'not null': If true, no NULL values will be allowed in this
434
 *       database column.  Defaults to false.
435
 *     - 'default': The field's default value.  The PHP type of the
436
 *       value matters: '', '0', and 0 are all different.  If you
437
 *       specify '0' as the default value for a type 'int' field it
438
 *       will not work because '0' is a string containing the
439
 *       character "zero", not an integer.
440
 *     - 'length': The maximal length of a type 'varchar' or 'text'
441
 *       field.  Ignored for other field types.
442
 *     - 'unsigned': A boolean indicating whether a type 'int', 'float'
443
 *       and 'numeric' only is signed or unsigned.  Defaults to
444
 *       FALSE.  Ignored for other field types.
445
 *     - 'precision', 'scale': For type 'numeric' fields, indicates
446
 *       the precision (total number of significant digits) and scale
447
 *       (decimal digits right of the decimal point).  Both values are
448
 *       mandatory.  Ignored for other field types.
449
 *
450
 *     All parameters apart from 'type' are optional except that type
451
 *     'numeric' columns must specify 'precision' and 'scale'.
452
 *
453
 *  - 'primary key': An array of one or more key column specifiers (see
below)
454
 *    that form the primary key.
455
 *  - 'unique key': An associative array of unique keys ('keyname' =>
456
 *    specification).  Each specification is an array of one or more
457
 *    key column specifiers (see below) that form a unique key on the
table.
458
 *  - 'indexes':  An associative array of indexes ('indexame' =>
459
 *    specification).  Each specification is an array of one or more
460
 *    key column specifiers (see below) that form an index on the
461
 *    table.
462
 *
463
 * A key column specifier is either a string naming a column or an
464
 * array of two elements, column name and length, specifying a prefix
465
 * of the named column.
466
 *
467
 * As an example, here is a SUBSET of the schema definition for
468
 * Drupal's 'node' table.  It show four fields (nid, vid, type, and
469
 * title), the primary key on field 'nid', a unique key named 'vid' on
470
 * field 'vid', and two indexes, one named 'nid' on field 'nid' and
471
 * one named 'node_title_type' on the field 'title' and the first four
472
 * bytes of the field 'type':
473
 *
474
 * @code
475
 * $schema['node'] = array(
476
 *   'fields' => array(
477
 *     'nid'      => array('type' => 'serial', 'unsigned' => TRUE, 'not
null' => TRUE),
478
 *     'vid'      => array('type' => 'int', 'unsigned' => TRUE, 'not null'
=> TRUE, 'default' => 0),
479
 *     'type'     => array('type' => 'varchar', 'length' => 32, 'not null'
=> TRUE, 'default' => ''),
480
 *     'title'    => array('type' => 'varchar', 'length' => 128, 'not null'
=> TRUE, 'default' => ''),
481
 *   ),
482
 *   'primary key' => array('nid'),
483
 *   'unique keys' => array(
484
 *     'vid'     => array('vid')
485
 *   ),
486
 *   'indexes' => array(
487
 *     'nid'                 => array('nid'),
488
 *     'node_title_type'     => array('title', array('type', 4)),
489
 *   ),
490
 * );
491
 * @endcode
492
 *
493
 * @see drupal_install_schema()
494
 */
495
496
 /**
497
 * Create a new table from a Drupal table definition.
498
 *
499
 * @param $ret
500
 *   Array to which query results will be added.
501
 * @param $name
502
 *   The name of the table to create.
503
 * @param $table
504
 *   A Schema API table definition array.
505
 */
5062027
function db_create_table(&$ret, $name, $table) {
50764
  $statements = db_create_table_sql($name, $table);
50864
  foreach ($statements as $statement) {
50964
    $ret[] = update_sql($statement);
51064
  }
51164
}
512
513
/**
514
 * Return an array of field names from an array of key/index column
specifiers.
515
 *
516
 * This is usually an identity function but if a key/index uses a column
prefix
517
 * specification, this function extracts just the name.
518
 *
519
 * @param $fields
520
 *   An array of key/index column specifiers.
521
 * @return
522
 *   An array of field names.
523
 */
5242027
function db_field_names($fields) {
5250
  $ret = array();
5260
  foreach ($fields as $field) {
5270
    if (is_array($field)) {
5280
      $ret[] = $field[0];
5290
    }
530
    else {
5310
      $ret[] = $field;
532
    }
5330
  }
5340
  return $ret;
5350
}
536
537
/**
538
 * Given a Schema API field type, return the correct %-placeholder.
539
 *
540
 * Embed the placeholder in a query to be passed to db_query and and pass
as an
541
 * argument to db_query a value of the specified type.
542
 *
543
 * @param $type
544
 *   The Schema API type of a field.
545
 * @return
546
 *   The placeholder string to embed in a query for that type.
547
 */
5482027
function db_type_placeholder($type) {
549
  switch ($type) {
5501844
    case 'varchar':
5511844
    case 'char':
5521844
    case 'text':
5531844
    case 'datetime':
5541676
      return "'%s'";
555
5561837
    case 'numeric':
557
      // Numeric values are arbitrary precision numbers.  Syntacically,
numerics
558
      // should be specified directly in SQL. However, without single
quotes
559
      // the %s placeholder does not protect against non-numeric characters
such
560
      // as spaces which would expose us to SQL injection.
5610
      return '%n';
562
5631837
    case 'serial':
5641837
    case 'int':
5651837
      return '%d';
566
5670
    case 'float':
5680
      return '%f';
569
5700
    case 'blob':
5710
      return '%b';
5720
  }
573
574
  // There is no safe value to return here, so return something that
575
  // will cause the query to fail.
5760
  return 'unsupported type ' . $type . 'for db_type_placeholder';
5770
}
578
579
/**
580
 * @} End of "defgroup schemaapi".
581
 */
5822027