[ Index ]

PHP Cross Reference of Drupal 6 (yi-drupal)

title

Body

[close]

/includes/ -> database.inc (source)

   1  <?php
   2  
   3  /**
   4   * @file
   5   * Wrapper for database interface code.
   6   */
   7  
   8  /**
   9   * A hash value to check when outputting database errors, md5('DB_ERROR').
  10   *
  11   * @see drupal_error_handler()
  12   */
  13  define('DB_ERROR', 'a515ac9c2796ca0e23adbe92c68fc9fc');
  14  
  15  /**
  16   * @defgroup database Database abstraction layer
  17   * @{
  18   * Allow the use of different database servers using the same code base.
  19   *
  20   * Drupal provides a slim database abstraction layer to provide developers with
  21   * the ability to support multiple database servers easily. The intent of this
  22   * layer is to preserve the syntax and power of SQL as much as possible, while
  23   * letting Drupal control the pieces of queries that need to be written
  24   * differently for different servers and provide basic security checks.
  25   *
  26   * Most Drupal database queries are performed by a call to db_query() or
  27   * db_query_range(). Module authors should also consider using pager_query() for
  28   * queries that return results that need to be presented on multiple pages, and
  29   * tablesort_sql() for generating appropriate queries for sortable tables.
  30   *
  31   * For example, one might wish to return a list of the most recent 10 nodes
  32   * authored by a given user. Instead of directly issuing the SQL query
  33   * @code
  34   *   SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;
  35   * @endcode
  36   * one would instead call the Drupal functions:
  37   * @code
  38   *   $result = db_query_range('SELECT n.nid, n.title, n.created
  39   *     FROM {node} n WHERE n.uid = %d', $uid, 0, 10);
  40   *   while ($node = db_fetch_object($result)) {
  41   *     // Perform operations on $node->body, etc. here.
  42   *   }
  43   * @endcode
  44   * Curly braces are used around "node" to provide table prefixing via
  45   * db_prefix_tables(). The explicit use of a user ID is pulled out into an
  46   * argument passed to db_query() so that SQL injection attacks from user input
  47   * can be caught and nullified. The LIMIT syntax varies between database servers,
  48   * so that is abstracted into db_query_range() arguments. Finally, note the
  49   * common pattern of iterating over the result set using db_fetch_object().
  50   */
  51  
  52  /**
  53   * Perform an SQL query and return success or failure.
  54   *
  55   * @param $sql
  56   *   A string containing a complete SQL query.  %-substitution
  57   *   parameters are not supported.
  58   * @return
  59   *   An array containing the keys:
  60   *      success: a boolean indicating whether the query succeeded
  61   *      query: the SQL query executed, passed through check_plain()
  62   */
  63  function update_sql($sql) {
  64    $result = db_query($sql, true);
  65    return array('success' => $result !== FALSE, 'query' => check_plain($sql));
  66  }
  67  
  68  /**
  69   * Append a database prefix to all tables in a query.
  70   *
  71   * Queries sent to Drupal should wrap all table names in curly brackets. This
  72   * function searches for this syntax and adds Drupal's table prefix to all
  73   * tables, allowing Drupal to coexist with other systems in the same database if
  74   * necessary.
  75   *
  76   * @param $sql
  77   *   A string containing a partial or entire SQL query.
  78   * @return
  79   *   The properly-prefixed string.
  80   */
  81  function db_prefix_tables($sql) {
  82    global $db_prefix;
  83  
  84    if (is_array($db_prefix)) {
  85      if (array_key_exists('default', $db_prefix)) {
  86        $tmp = $db_prefix;
  87        unset($tmp['default']);
  88        foreach ($tmp as $key => $val) {
  89          $sql = strtr($sql, array('{'. $key .'}' => $val . $key));
  90        }
  91        return strtr($sql, array('{' => $db_prefix['default'], '}' => ''));
  92      }
  93      else {
  94        foreach ($db_prefix as $key => $val) {
  95          $sql = strtr($sql, array('{'. $key .'}' => $val . $key));
  96        }
  97        return strtr($sql, array('{' => '', '}' => ''));
  98      }
  99    }
 100    else {
 101      return strtr($sql, array('{' => $db_prefix, '}' => ''));
 102    }
 103  }
 104  
 105  /**
 106   * Activate a database for future queries.
 107   *
 108   * If it is necessary to use external databases in a project, this function can
 109   * be used to change where database queries are sent. If the database has not
 110   * yet been used, it is initialized using the URL specified for that name in
 111   * Drupal's configuration file. If this name is not defined, a duplicate of the
 112   * default connection is made instead.
 113   *
 114   * Be sure to change the connection back to the default when done with custom
 115   * code.
 116   *
 117   * @param $name
 118   *   The key in the $db_url global variable from settings.php. If omitted, the
 119   *   default connection will be made active.
 120   *
 121   * @return
 122   *   The name of the previously active database, or FALSE if none was found.
 123   */
 124  function db_set_active($name = 'default') {
 125    global $db_url, $db_type, $active_db;
 126    static $db_conns, $active_name = FALSE;
 127  
 128    if (empty($db_url)) {
 129      include_once  'includes/install.inc';
 130      install_goto('install.php');
 131    }
 132  
 133    if (!isset($db_conns[$name])) {
 134      // Initiate a new connection, using the named DB URL specified.
 135      if (is_array($db_url)) {
 136        $connect_url = array_key_exists($name, $db_url) ? $db_url[$name] : $db_url['default'];
 137      }
 138      else {
 139        $connect_url = $db_url;
 140      }
 141  
 142      $db_type = substr($connect_url, 0, strpos($connect_url, '://'));
 143      $handler = "./includes/database.$db_type.inc";
 144  
 145      if (is_file($handler)) {
 146        include_once $handler;
 147      }
 148      else {
 149        _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  
 152      $db_conns[$name] = db_connect($connect_url);
 153    }
 154  
 155    $previous_name = $active_name;
 156    // Set the active connection.
 157    $active_name = $name;
 158    $active_db = $db_conns[$name];
 159  
 160    return $previous_name;
 161  }
 162  
 163  /**
 164   * Helper function to show fatal database errors.
 165   *
 166   * Prints a themed maintenance page with the 'Site off-line' text,
 167   * adding the provided error message in the case of 'display_errors'
 168   * set to on. Ends the page request; no return.
 169   *
 170   * @param $error
 171   *   The error message to be appended if 'display_errors' is on.
 172   */
 173  function _db_error_page($error = '') {
 174    global $db_type;
 175    drupal_init_language();
 176    drupal_maintenance_theme();
 177    drupal_set_header($_SERVER['SERVER_PROTOCOL'] .' 503 Service Unavailable');
 178    drupal_set_title('Site off-line');
 179  
 180    $message = '<p>The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.</p>';
 181    $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>';
 182  
 183    if ($error && ini_get('display_errors')) {
 184      $message .= '<p><small>The '. theme('placeholder', $db_type) .' error was: '. theme('placeholder', $error) .'.</small></p>';
 185    }
 186  
 187    print theme('maintenance_page', $message);
 188    exit;
 189  }
 190  
 191  /**
 192   * Returns a boolean depending on the availability of the database.
 193   */
 194  function db_is_active() {
 195    global $active_db;
 196    return !empty($active_db);
 197  }
 198  
 199  /**
 200   * Helper function for db_query().
 201   */
 202  function _db_query_callback($match, $init = FALSE) {
 203    static $args = NULL;
 204    if ($init) {
 205      $args = $match;
 206      return;
 207    }
 208  
 209    switch ($match[1]) {
 210      case '%d': // We must use type casting to int to convert FALSE/NULL/(TRUE?)
 211        $value = array_shift($args);
 212        // Do we need special bigint handling?
 213        if ($value > PHP_INT_MAX) {
 214          $precision = ini_get('precision');
 215          @ini_set('precision', 16);
 216          $value = sprintf('%.0f', $value);
 217          @ini_set('precision', $precision);
 218        }
 219        else {
 220          $value = (int) $value;
 221        }
 222        // We don't need db_escape_string as numbers are db-safe.
 223        return $value;
 224      case '%s':
 225        return db_escape_string(array_shift($args));
 226      case '%n':
 227        // Numeric values have arbitrary precision, so can't be treated as float.
 228        // is_numeric() allows hex values (0xFF), but they are not valid.
 229        $value = trim(array_shift($args));
 230        return is_numeric($value) && !preg_match('/x/i', $value) ? $value : '0';
 231      case '%%':
 232        return '%';
 233      case '%f':
 234        return (float) array_shift($args);
 235      case '%b': // binary data
 236        return db_encode_blob(array_shift($args));
 237    }
 238  }
 239  
 240  /**
 241   * Generate placeholders for an array of query arguments of a single type.
 242   *
 243   * Given a Schema API field type, return correct %-placeholders to
 244   * embed in a query
 245   *
 246   * @param $arguments
 247   *  An array with at least one element.
 248   * @param $type
 249   *   The Schema API type of a field (e.g. 'int', 'text', or 'varchar').
 250   */
 251  function db_placeholders($arguments, $type = 'int') {
 252    $placeholder = db_type_placeholder($type);
 253    return implode(',', array_fill(0, count($arguments), $placeholder));
 254  }
 255  
 256  /**
 257   * Indicates the place holders that should be replaced in _db_query_callback().
 258   */
 259  define('DB_QUERY_REGEXP', '/(%d|%s|%%|%f|%b|%n)/');
 260  
 261  /**
 262   * Helper function for db_rewrite_sql.
 263   *
 264   * Collects JOIN and WHERE statements via hook_db_rewrite_sql()
 265   * Decides whether to select primary_key or DISTINCT(primary_key)
 266   *
 267   * @param $query
 268   *   Query to be rewritten.
 269   * @param $primary_table
 270   *   Name or alias of the table which has the primary key field for this query.
 271   *   Typical table names would be: {blocks}, {comments}, {forum}, {node},
 272   *   {menu}, {term_data} or {vocabulary}. However, in most cases the usual
 273   *   table alias (b, c, f, n, m, t or v) is used instead of the table name.
 274   * @param $primary_field
 275   *   Name of the primary field.
 276   * @param $args
 277   *   Array of additional arguments.
 278   * @return
 279   *   An array: join statements, where statements, field or DISTINCT(field).
 280   */
 281  function _db_rewrite_sql($query = '', $primary_table = 'n', $primary_field = 'nid', $args = array()) {
 282    $where = array();
 283    $join = array();
 284    $distinct = FALSE;
 285    foreach (module_implements('db_rewrite_sql') as $module) {
 286      $result = module_invoke($module, 'db_rewrite_sql', $query, $primary_table, $primary_field, $args);
 287      if (isset($result) && is_array($result)) {
 288        if (isset($result['where'])) {
 289          $where[] = $result['where'];
 290        }
 291        if (isset($result['join'])) {
 292          $join[] = $result['join'];
 293        }
 294        if (isset($result['distinct']) && $result['distinct']) {
 295          $distinct = TRUE;
 296        }
 297      }
 298      elseif (isset($result)) {
 299        $where[] = $result;
 300      }
 301    }
 302  
 303    $where = empty($where) ? '' : '('. implode(') AND (', $where) .')';
 304    $join = empty($join) ? '' : implode(' ', $join);
 305  
 306    return array($join, $where, $distinct);
 307  }
 308  
 309  /**
 310   * Rewrites node, taxonomy and comment queries. Use it for listing queries. Do not
 311   * use FROM table1, table2 syntax, use JOIN instead.
 312   *
 313   * @param $query
 314   *   Query to be rewritten.
 315   * @param $primary_table
 316   *   Name or alias of the table which has the primary key field for this query.
 317   *   Typical table names would be: {blocks}, {comments}, {forum}, {node},
 318   *   {menu}, {term_data} or {vocabulary}. However, it is more common to use the
 319   *   the usual table aliases: b, c, f, n, m, t or v.
 320   * @param $primary_field
 321   *   Name of the primary field.
 322   * @param $args
 323   *   An array of arguments, passed to the implementations of hook_db_rewrite_sql.
 324   * @return
 325   *   The original query with JOIN and WHERE statements inserted from
 326   *   hook_db_rewrite_sql implementations. nid is rewritten if needed.
 327   */
 328  function db_rewrite_sql($query, $primary_table = 'n', $primary_field = 'nid',  $args = array()) {
 329    list($join, $where, $distinct) = _db_rewrite_sql($query, $primary_table, $primary_field, $args);
 330  
 331    if ($distinct) {
 332      $query = db_distinct_field($primary_table, $primary_field, $query);
 333    }
 334  
 335    if (!empty($where) || !empty($join)) {
 336      $pattern = '{
 337        # Beginning of the string
 338        ^
 339        ((?P<anonymous_view>
 340          # Everything within this set of parentheses is named "anonymous view"
 341          (?:
 342            [^()]++                   # anything not parentheses
 343          |
 344            \( (?P>anonymous_view) \)          # an open parenthesis, more "anonymous view" and finally a close parenthesis.
 345          )*
 346        )[^()]+WHERE)
 347      }x';
 348      preg_match($pattern, $query, $matches);
 349      if (!$where) {
 350        $where = '1 = 1';
 351      }
 352      if ($matches) {
 353        $n = strlen($matches[1]);
 354        $second_part = substr($query, $n);
 355        $first_part = substr($matches[1], 0, $n - 5) ." $join WHERE $where AND ( ";
 356        // PHP 4 does not support strrpos for strings. We emulate it.
 357        $haystack_reverse = strrev($second_part);
 358      }
 359      else {
 360        $haystack_reverse = strrev($query);
 361      }
 362      // No need to use strrev on the needle, we supply GROUP, ORDER, LIMIT
 363      // reversed.
 364      foreach (array('PUORG', 'REDRO', 'TIMIL') as $needle_reverse) {
 365        $pos = strpos($haystack_reverse, $needle_reverse);
 366        if ($pos !== FALSE) {
 367          // All needles are five characters long.
 368          $pos += 5;
 369          break;
 370        }
 371      }
 372      if ($matches) {
 373        if ($pos === FALSE) {
 374          $query = $first_part . $second_part .')';
 375        }
 376        else {
 377          $query = $first_part . substr($second_part, 0, -$pos) .')'. substr($second_part, -$pos);
 378        }
 379      }
 380      elseif ($pos === FALSE) {
 381        $query .= " $join WHERE $where";
 382      }
 383      else {
 384        $query = substr($query, 0, -$pos) . " $join WHERE $where " . substr($query, -$pos);
 385      }
 386    }
 387  
 388    return $query;
 389  }
 390  
 391  /**
 392   * Adds the DISTINCT flag to the supplied query and returns the altered query.
 393   *
 394   * The supplied query should not contain a DISTINCT flag. This will not, and
 395   * never did guarantee that you will obtain distinct values of $table.$field.
 396   *
 397   * @param $table
 398   *   Unused. Kept to retain API compatibility.
 399   * @param $field
 400   *   Unused. Kept to retain API compatibility.
 401   * @param $query
 402   *   Query to which the DISTINCT flag should be applied.
 403   *
 404   * @return
 405   *   SQL query with the DISTINCT flag set.
 406   */
 407  function db_distinct_field($table, $field, $query) {
 408    $matches = array();
 409    if (!preg_match('/^SELECT\s*DISTINCT/i', $query, $matches)) {
 410      // Only add distinct to the outer SELECT to avoid messing up subqueries.
 411      $query = preg_replace('/^SELECT/i', 'SELECT DISTINCT', $query);
 412    }
 413  
 414    return $query;
 415  }
 416  
 417  /**
 418   * Restrict a dynamic table, column or constraint name to safe characters.
 419   *
 420   * Only keeps alphanumeric and underscores.
 421   */
 422  function db_escape_table($string) {
 423    return preg_replace('/[^A-Za-z0-9_]+/', '', $string);
 424  }
 425  
 426  /**
 427   * @} End of "defgroup database".
 428   */
 429  
 430  /**
 431   * @defgroup schemaapi Schema API
 432   * @{
 433   *
 434   * A Drupal schema definition is an array structure representing one or
 435   * more tables and their related keys and indexes. A schema is defined by
 436   * hook_schema(), which usually lives in a modulename.install file.
 437   *
 438   * By implementing hook_schema() and specifying the tables your module
 439   * declares, you can easily create and drop these tables on all
 440   * supported database engines. You don't have to deal with the
 441   * different SQL dialects for table creation and alteration of the
 442   * supported database engines.
 443   *
 444   * hook_schema() should return an array with a key for each table that
 445   * the module defines.
 446   *
 447   * The following keys are defined:
 448   *
 449   *   - 'description': A string describing this table and its purpose.
 450   *     References to other tables should be enclosed in
 451   *     curly-brackets.  For example, the node_revisions table
 452   *     description field might contain "Stores per-revision title and
 453   *     body data for each {node}."
 454   *   - 'fields': An associative array ('fieldname' => specification)
 455   *     that describes the table's database columns.  The specification
 456   *     is also an array.  The following specification parameters are defined:
 457   *     - 'description': A string describing this field and its purpose.
 458   *       References to other tables should be enclosed in
 459   *       curly-brackets.  For example, the node table vid field
 460   *       description might contain "Always holds the largest (most
 461   *       recent) {node_revisions}.vid value for this nid."
 462   *     - 'type': The generic datatype: 'varchar', 'int', 'serial'
 463   *       'float', 'numeric', 'text', 'blob' or 'datetime'.  Most types
 464   *       just map to the according database engine specific
 465   *       datatypes.  Use 'serial' for auto incrementing fields. This
 466   *       will expand to 'int auto_increment' on mysql.
 467   *     - 'serialize': A boolean indicating whether the field will be stored
 468           as a serialized string.
 469   *     - 'size': The data size: 'tiny', 'small', 'medium', 'normal',
 470   *       'big'.  This is a hint about the largest value the field will
 471   *       store and determines which of the database engine specific
 472   *       datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT).
 473   *       'normal', the default, selects the base type (e.g. on MySQL,
 474   *       INT, VARCHAR, BLOB, etc.).
 475   *       Not all sizes are available for all data types. See
 476   *       db_type_map() for possible combinations.
 477   *     - 'not null': If true, no NULL values will be allowed in this
 478   *       database column.  Defaults to false.
 479   *     - 'default': The field's default value.  The PHP type of the
 480   *       value matters: '', '0', and 0 are all different.  If you
 481   *       specify '0' as the default value for a type 'int' field it
 482   *       will not work because '0' is a string containing the
 483   *       character "zero", not an integer.
 484   *     - 'length': The maximal length of a type 'char', 'varchar' or 'text'
 485   *       field.  Ignored for other field types.
 486   *     - 'unsigned': A boolean indicating whether a type 'int', 'float'
 487   *       and 'numeric' only is signed or unsigned.  Defaults to
 488   *       FALSE.  Ignored for other field types.
 489   *     - 'precision', 'scale': For type 'numeric' fields, indicates
 490   *       the precision (total number of significant digits) and scale
 491   *       (decimal digits right of the decimal point).  Both values are
 492   *       mandatory.  Ignored for other field types.
 493   *     All parameters apart from 'type' are optional except that type
 494   *     'numeric' columns must specify 'precision' and 'scale'.
 495   *  - 'primary key': An array of one or more key column specifiers (see below)
 496   *    that form the primary key.
 497   *  - 'unique keys': An associative array of unique keys ('keyname' =>
 498   *    specification).  Each specification is an array of one or more
 499   *    key column specifiers (see below) that form a unique key on the table.
 500   *  - 'indexes':  An associative array of indexes ('indexame' =>
 501   *    specification).  Each specification is an array of one or more
 502   *    key column specifiers (see below) that form an index on the
 503   *    table.
 504   *
 505   * A key column specifier is either a string naming a column or an
 506   * array of two elements, column name and length, specifying a prefix
 507   * of the named column.
 508   *
 509   * As an example, here is a SUBSET of the schema definition for
 510   * Drupal's 'node' table.  It show four fields (nid, vid, type, and
 511   * title), the primary key on field 'nid', a unique key named 'vid' on
 512   * field 'vid', and two indexes, one named 'nid' on field 'nid' and
 513   * one named 'node_title_type' on the field 'title' and the first four
 514   * bytes of the field 'type':
 515   *
 516   * @code
 517   * $schema['node'] = array(
 518   *   'fields' => array(
 519   *     'nid'      => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
 520   *     'vid'      => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0),
 521   *     'type'     => array('type' => 'varchar', 'length' => 32, 'not null' => TRUE, 'default' => ''),
 522   *     'title'    => array('type' => 'varchar', 'length' => 128, 'not null' => TRUE, 'default' => ''),
 523   *   ),
 524   *   'primary key' => array('nid'),
 525   *   'unique keys' => array(
 526   *     'vid'     => array('vid')
 527   *   ),
 528   *   'indexes' => array(
 529   *     'nid'                 => array('nid'),
 530   *     'node_title_type'     => array('title', array('type', 4)),
 531   *   ),
 532   * );
 533   * @endcode
 534   *
 535   * @see drupal_install_schema()
 536   */
 537  
 538   /**
 539   * Create a new table from a Drupal table definition.
 540   *
 541   * @param $ret
 542   *   Array to which query results will be added.
 543   * @param $name
 544   *   The name of the table to create.
 545   * @param $table
 546   *   A Schema API table definition array.
 547   */
 548  function db_create_table(&$ret, $name, $table) {
 549    $statements = db_create_table_sql($name, $table);
 550    foreach ($statements as $statement) {
 551      $ret[] = update_sql($statement);
 552    }
 553  }
 554  
 555  /**
 556   * Return an array of field names from an array of key/index column specifiers.
 557   *
 558   * This is usually an identity function but if a key/index uses a column prefix
 559   * specification, this function extracts just the name.
 560   *
 561   * @param $fields
 562   *   An array of key/index column specifiers.
 563   * @return
 564   *   An array of field names.
 565   */
 566  function db_field_names($fields) {
 567    $ret = array();
 568    foreach ($fields as $field) {
 569      if (is_array($field)) {
 570        $ret[] = $field[0];
 571      }
 572      else {
 573        $ret[] = $field;
 574      }
 575    }
 576    return $ret;
 577  }
 578  
 579  /**
 580   * Given a Schema API field type, return the correct %-placeholder.
 581   *
 582   * Embed the placeholder in a query to be passed to db_query and and pass as an
 583   * argument to db_query a value of the specified type.
 584   *
 585   * @param $type
 586   *   The Schema API type of a field.
 587   * @return
 588   *   The placeholder string to embed in a query for that type.
 589   */
 590  function db_type_placeholder($type) {
 591    switch ($type) {
 592      case 'varchar':
 593      case 'char':
 594      case 'text':
 595      case 'datetime':
 596        return "'%s'";
 597  
 598      case 'numeric':
 599        // Numeric values are arbitrary precision numbers.  Syntacically, numerics
 600        // should be specified directly in SQL. However, without single quotes
 601        // the %s placeholder does not protect against non-numeric characters such
 602        // as spaces which would expose us to SQL injection.
 603        return '%n';
 604  
 605      case 'serial':
 606      case 'int':
 607        return '%d';
 608  
 609      case 'float':
 610        return '%f';
 611  
 612      case 'blob':
 613        return '%b';
 614    }
 615  
 616    // There is no safe value to return here, so return something that
 617    // will cause the query to fail.
 618    return 'unsupported type '. $type .'for db_type_placeholder';
 619  }
 620  
 621  /**
 622   * @} End of "defgroup schemaapi".
 623   */


Generated: Mon Jul 9 18:01:44 2012 Cross-referenced by PHPXref 0.7