webmaster@1: body, etc. here. webmaster@1: * } webmaster@1: * @endcode webmaster@1: * Curly braces are used around "node" to provide table prefixing via webmaster@1: * db_prefix_tables(). The explicit use of a user ID is pulled out into an webmaster@1: * argument passed to db_query() so that SQL injection attacks from user input webmaster@1: * can be caught and nullified. The LIMIT syntax varies between database servers, webmaster@1: * so that is abstracted into db_query_range() arguments. Finally, note the webmaster@1: * common pattern of iterating over the result set using db_fetch_object(). webmaster@1: */ webmaster@1: webmaster@1: /** webmaster@1: * Perform an SQL query and return success or failure. webmaster@1: * webmaster@1: * @param $sql webmaster@1: * A string containing a complete SQL query. %-substitution webmaster@1: * parameters are not supported. webmaster@1: * @return webmaster@1: * An array containing the keys: webmaster@1: * success: a boolean indicating whether the query succeeded webmaster@1: * query: the SQL query executed, passed through check_plain() webmaster@1: */ webmaster@1: function update_sql($sql) { webmaster@1: $result = db_query($sql, true); webmaster@1: return array('success' => $result !== FALSE, 'query' => check_plain($sql)); webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Append a database prefix to all tables in a query. webmaster@1: * webmaster@1: * Queries sent to Drupal should wrap all table names in curly brackets. This webmaster@1: * function searches for this syntax and adds Drupal's table prefix to all webmaster@1: * tables, allowing Drupal to coexist with other systems in the same database if webmaster@1: * necessary. webmaster@1: * webmaster@1: * @param $sql webmaster@1: * A string containing a partial or entire SQL query. webmaster@1: * @return webmaster@1: * The properly-prefixed string. webmaster@1: */ webmaster@1: function db_prefix_tables($sql) { webmaster@1: global $db_prefix; webmaster@1: webmaster@1: if (is_array($db_prefix)) { webmaster@1: if (array_key_exists('default', $db_prefix)) { webmaster@1: $tmp = $db_prefix; webmaster@1: unset($tmp['default']); webmaster@1: foreach ($tmp as $key => $val) { webmaster@1: $sql = strtr($sql, array('{'. $key .'}' => $val . $key)); webmaster@1: } webmaster@1: return strtr($sql, array('{' => $db_prefix['default'], '}' => '')); webmaster@1: } webmaster@1: else { webmaster@1: foreach ($db_prefix as $key => $val) { webmaster@1: $sql = strtr($sql, array('{'. $key .'}' => $val . $key)); webmaster@1: } webmaster@1: return strtr($sql, array('{' => '', '}' => '')); webmaster@1: } webmaster@1: } webmaster@1: else { webmaster@1: return strtr($sql, array('{' => $db_prefix, '}' => '')); webmaster@1: } webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Activate a database for future queries. webmaster@1: * webmaster@1: * If it is necessary to use external databases in a project, this function can webmaster@1: * be used to change where database queries are sent. If the database has not webmaster@1: * yet been used, it is initialized using the URL specified for that name in webmaster@1: * Drupal's configuration file. If this name is not defined, a duplicate of the webmaster@1: * default connection is made instead. webmaster@1: * webmaster@1: * Be sure to change the connection back to the default when done with custom webmaster@1: * code. webmaster@1: * webmaster@1: * @param $name webmaster@1: * The name assigned to the newly active database connection. If omitted, the webmaster@1: * default connection will be made active. webmaster@1: * webmaster@1: * @return the name of the previously active database or FALSE if non was found. webmaster@1: */ webmaster@1: function db_set_active($name = 'default') { webmaster@1: global $db_url, $db_type, $active_db; webmaster@1: static $db_conns, $active_name = FALSE; webmaster@1: webmaster@1: if (empty($db_url)) { webmaster@1: include_once 'includes/install.inc'; webmaster@1: install_goto('install.php'); webmaster@1: } webmaster@1: webmaster@1: if (!isset($db_conns[$name])) { webmaster@1: // Initiate a new connection, using the named DB URL specified. webmaster@1: if (is_array($db_url)) { webmaster@1: $connect_url = array_key_exists($name, $db_url) ? $db_url[$name] : $db_url['default']; webmaster@1: } webmaster@1: else { webmaster@1: $connect_url = $db_url; webmaster@1: } webmaster@1: webmaster@1: $db_type = substr($connect_url, 0, strpos($connect_url, '://')); webmaster@1: $handler = "./includes/database.$db_type.inc"; webmaster@1: webmaster@1: if (is_file($handler)) { webmaster@1: include_once $handler; webmaster@1: } webmaster@1: else { webmaster@1: _db_error_page("The database type '". $db_type ."' is unsupported. Please use either 'mysql' or 'mysqli' for MySQL, or 'pgsql' for PostgreSQL databases."); webmaster@1: } webmaster@1: webmaster@1: $db_conns[$name] = db_connect($connect_url); webmaster@1: } webmaster@1: webmaster@1: $previous_name = $active_name; webmaster@1: // Set the active connection. webmaster@1: $active_name = $name; webmaster@1: $active_db = $db_conns[$name]; webmaster@1: webmaster@1: return $previous_name; webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Helper function to show fatal database errors. webmaster@1: * webmaster@1: * Prints a themed maintenance page with the 'Site off-line' text, webmaster@1: * adding the provided error message in the case of 'display_errors' webmaster@1: * set to on. Ends the page request; no return. webmaster@1: * webmaster@1: * @param $error webmaster@1: * The error message to be appended if 'display_errors' is on. webmaster@1: */ webmaster@1: function _db_error_page($error = '') { webmaster@1: global $db_type; webmaster@13: drupal_init_language(); webmaster@1: drupal_maintenance_theme(); webmaster@1: drupal_set_header('HTTP/1.1 503 Service Unavailable'); webmaster@1: drupal_set_title('Site off-line'); webmaster@1: webmaster@1: $message = '

The site is currently not available due to technical problems. Please try again later. Thank you for your understanding.

'; webmaster@1: $message .= '

If you are the maintainer of this site, please check your database settings in the settings.php file and ensure that your hosting provider\'s database server is running. For more help, see the handbook, or contact your hosting provider.

'; webmaster@1: webmaster@1: if ($error && ini_get('display_errors')) { webmaster@1: $message .= '

The '. theme('placeholder', $db_type) .' error was: '. theme('placeholder', $error) .'.

'; webmaster@1: } webmaster@1: webmaster@1: print theme('maintenance_page', $message); webmaster@1: exit; webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Returns a boolean depending on the availability of the database. webmaster@1: */ webmaster@1: function db_is_active() { webmaster@1: global $active_db; webmaster@1: return !empty($active_db); webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Helper function for db_query(). webmaster@1: */ webmaster@1: function _db_query_callback($match, $init = FALSE) { webmaster@1: static $args = NULL; webmaster@1: if ($init) { webmaster@1: $args = $match; webmaster@1: return; webmaster@1: } webmaster@1: webmaster@1: switch ($match[1]) { webmaster@1: case '%d': // We must use type casting to int to convert FALSE/NULL/(TRUE?) webmaster@1: return (int) array_shift($args); // We don't need db_escape_string as numbers are db-safe webmaster@1: case '%s': webmaster@1: return db_escape_string(array_shift($args)); webmaster@7: case '%n': webmaster@7: // Numeric values have arbitrary precision, so can't be treated as float. webmaster@7: // is_numeric() allows hex values (0xFF), but they are not valid. webmaster@7: $value = trim(array_shift($args)); webmaster@7: return is_numeric($value) && !preg_match('/x/i', $value) ? $value : '0'; webmaster@1: case '%%': webmaster@1: return '%'; webmaster@1: case '%f': webmaster@1: return (float) array_shift($args); webmaster@1: case '%b': // binary data webmaster@1: return db_encode_blob(array_shift($args)); webmaster@1: } webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Generate placeholders for an array of query arguments of a single type. webmaster@1: * webmaster@1: * Given a Schema API field type, return correct %-placeholders to webmaster@1: * embed in a query webmaster@1: * webmaster@1: * @param $arguments webmaster@1: * An array with at least one element. webmaster@1: * @param $type webmaster@1: * The Schema API type of a field (e.g. 'int', 'text', or 'varchar'). webmaster@1: */ webmaster@1: function db_placeholders($arguments, $type = 'int') { webmaster@1: $placeholder = db_type_placeholder($type); webmaster@1: return implode(',', array_fill(0, count($arguments), $placeholder)); webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Indicates the place holders that should be replaced in _db_query_callback(). webmaster@1: */ webmaster@7: define('DB_QUERY_REGEXP', '/(%d|%s|%%|%f|%b|%n)/'); webmaster@1: webmaster@1: /** webmaster@1: * Helper function for db_rewrite_sql. webmaster@1: * webmaster@1: * Collects JOIN and WHERE statements via hook_db_rewrite_sql() webmaster@1: * Decides whether to select primary_key or DISTINCT(primary_key) webmaster@1: * webmaster@1: * @param $query webmaster@1: * Query to be rewritten. webmaster@1: * @param $primary_table webmaster@1: * Name or alias of the table which has the primary key field for this query. webmaster@1: * Typical table names would be: {blocks}, {comments}, {forum}, {node}, webmaster@1: * {menu}, {term_data} or {vocabulary}. However, in most cases the usual webmaster@1: * table alias (b, c, f, n, m, t or v) is used instead of the table name. webmaster@1: * @param $primary_field webmaster@1: * Name of the primary field. webmaster@1: * @param $args webmaster@1: * Array of additional arguments. webmaster@1: * @return webmaster@1: * An array: join statements, where statements, field or DISTINCT(field). webmaster@1: */ webmaster@1: function _db_rewrite_sql($query = '', $primary_table = 'n', $primary_field = 'nid', $args = array()) { webmaster@1: $where = array(); webmaster@1: $join = array(); webmaster@1: $distinct = FALSE; webmaster@1: foreach (module_implements('db_rewrite_sql') as $module) { webmaster@1: $result = module_invoke($module, 'db_rewrite_sql', $query, $primary_table, $primary_field, $args); webmaster@1: if (isset($result) && is_array($result)) { webmaster@1: if (isset($result['where'])) { webmaster@1: $where[] = $result['where']; webmaster@1: } webmaster@1: if (isset($result['join'])) { webmaster@1: $join[] = $result['join']; webmaster@1: } webmaster@1: if (isset($result['distinct']) && $result['distinct']) { webmaster@1: $distinct = TRUE; webmaster@1: } webmaster@1: } webmaster@1: elseif (isset($result)) { webmaster@1: $where[] = $result; webmaster@1: } webmaster@1: } webmaster@1: webmaster@1: $where = empty($where) ? '' : '('. implode(') AND (', $where) .')'; webmaster@1: $join = empty($join) ? '' : implode(' ', $join); webmaster@1: webmaster@1: return array($join, $where, $distinct); webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Rewrites node, taxonomy and comment queries. Use it for listing queries. Do not webmaster@1: * use FROM table1, table2 syntax, use JOIN instead. webmaster@1: * webmaster@1: * @param $query webmaster@1: * Query to be rewritten. webmaster@1: * @param $primary_table webmaster@1: * Name or alias of the table which has the primary key field for this query. webmaster@1: * Typical table names would be: {blocks}, {comments}, {forum}, {node}, webmaster@1: * {menu}, {term_data} or {vocabulary}. However, it is more common to use the webmaster@1: * the usual table aliases: b, c, f, n, m, t or v. webmaster@1: * @param $primary_field webmaster@1: * Name of the primary field. webmaster@1: * @param $args webmaster@1: * An array of arguments, passed to the implementations of hook_db_rewrite_sql. webmaster@1: * @return webmaster@1: * The original query with JOIN and WHERE statements inserted from webmaster@1: * hook_db_rewrite_sql implementations. nid is rewritten if needed. webmaster@1: */ webmaster@1: function db_rewrite_sql($query, $primary_table = 'n', $primary_field = 'nid', $args = array()) { webmaster@1: list($join, $where, $distinct) = _db_rewrite_sql($query, $primary_table, $primary_field, $args); webmaster@1: webmaster@1: if ($distinct) { webmaster@1: $query = db_distinct_field($primary_table, $primary_field, $query); webmaster@1: } webmaster@1: webmaster@1: if (!empty($where) || !empty($join)) { webmaster@1: $pattern = '{ webmaster@1: # Beginning of the string webmaster@1: ^ webmaster@1: ((?P webmaster@1: # Everything within this set of parentheses is named "anonymous view" webmaster@1: (?: webmaster@1: [^()]++ # anything not parentheses webmaster@1: | webmaster@1: \( (?P>anonymous_view) \) # an open parenthesis, more "anonymous view" and finally a close parenthesis. webmaster@1: )* webmaster@1: )[^()]+WHERE) webmaster@1: }x'; webmaster@1: preg_match($pattern, $query, $matches); webmaster@1: if (!$where) { webmaster@1: $where = '1 = 1'; webmaster@1: } webmaster@1: if ($matches) { webmaster@1: $n = strlen($matches[1]); webmaster@1: $second_part = substr($query, $n); webmaster@1: $first_part = substr($matches[1], 0, $n - 5) ." $join WHERE $where AND ( "; webmaster@1: // PHP 4 does not support strrpos for strings. We emulate it. webmaster@1: $haystack_reverse = strrev($second_part); webmaster@1: } webmaster@1: else { webmaster@1: $haystack_reverse = strrev($query); webmaster@1: } webmaster@1: // No need to use strrev on the needle, we supply GROUP, ORDER, LIMIT webmaster@1: // reversed. webmaster@1: foreach (array('PUORG', 'REDRO', 'TIMIL') as $needle_reverse) { webmaster@1: $pos = strpos($haystack_reverse, $needle_reverse); webmaster@1: if ($pos !== FALSE) { webmaster@1: // All needles are five characters long. webmaster@1: $pos += 5; webmaster@1: break; webmaster@1: } webmaster@1: } webmaster@1: if ($matches) { webmaster@1: if ($pos === FALSE) { webmaster@1: $query = $first_part . $second_part .')'; webmaster@1: } webmaster@1: else { webmaster@1: $query = $first_part . substr($second_part, 0, -$pos) .')'. substr($second_part, -$pos); webmaster@1: } webmaster@1: } webmaster@1: elseif ($pos === FALSE) { webmaster@1: $query .= " $join WHERE $where"; webmaster@1: } webmaster@1: else { webmaster@1: $query = substr($query, 0, -$pos) . " $join WHERE $where " . substr($query, -$pos); webmaster@1: } webmaster@1: } webmaster@1: webmaster@1: return $query; webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Restrict a dynamic table, column or constraint name to safe characters. webmaster@1: * webmaster@1: * Only keeps alphanumeric and underscores. webmaster@1: */ webmaster@1: function db_escape_table($string) { webmaster@1: return preg_replace('/[^A-Za-z0-9_]+/', '', $string); webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * @} End of "defgroup database". webmaster@1: */ webmaster@1: webmaster@1: /** webmaster@1: * @defgroup schemaapi Schema API webmaster@1: * @{ webmaster@1: * webmaster@1: * A Drupal schema definition is an array structure representing one or webmaster@1: * more tables and their related keys and indexes. A schema is defined by webmaster@1: * hook_schema(), which usually lives in a modulename.install file. webmaster@1: * webmaster@1: * By implementing hook_schema() and specifying the tables your module webmaster@1: * declares, you can easily create and drop these tables on all webmaster@1: * supported database engines. You don't have to deal with the webmaster@1: * different SQL dialects for table creation and alteration of the webmaster@1: * supported database engines. webmaster@1: * webmaster@1: * hook_schema() should return an array with a key for each table that webmaster@1: * the module defines. webmaster@1: * webmaster@1: * The following keys are defined: webmaster@1: * webmaster@1: * - 'description': A string describing this table and its purpose. webmaster@1: * References to other tables should be enclosed in webmaster@1: * curly-brackets. For example, the node_revisions table webmaster@1: * description field might contain "Stores per-revision title and webmaster@1: * body data for each {node}." webmaster@1: * - 'fields': An associative array ('fieldname' => specification) webmaster@1: * that describes the table's database columns. The specification webmaster@1: * is also an array. The following specification parameters are defined: webmaster@1: * webmaster@1: * - 'description': A string describing this field and its purpose. webmaster@1: * References to other tables should be enclosed in webmaster@1: * curly-brackets. For example, the node table vid field webmaster@1: * description might contain "Always holds the largest (most webmaster@1: * recent) {node_revisions}.vid value for this nid." webmaster@1: * - 'type': The generic datatype: 'varchar', 'int', 'serial' webmaster@1: * 'float', 'numeric', 'text', 'blob' or 'datetime'. Most types webmaster@1: * just map to the according database engine specific webmaster@1: * datatypes. Use 'serial' for auto incrementing fields. This webmaster@1: * will expand to 'int auto_increment' on mysql. webmaster@1: * - 'size': The data size: 'tiny', 'small', 'medium', 'normal', webmaster@1: * 'big'. This is a hint about the largest value the field will webmaster@1: * store and determines which of the database engine specific webmaster@1: * datatypes will be used (e.g. on MySQL, TINYINT vs. INT vs. BIGINT). webmaster@1: * 'normal', the default, selects the base type (e.g. on MySQL, webmaster@1: * INT, VARCHAR, BLOB, etc.). webmaster@1: * webmaster@1: * Not all sizes are available for all data types. See webmaster@1: * db_type_map() for possible combinations. webmaster@1: * - 'not null': If true, no NULL values will be allowed in this webmaster@1: * database column. Defaults to false. webmaster@1: * - 'default': The field's default value. The PHP type of the webmaster@1: * value matters: '', '0', and 0 are all different. If you webmaster@1: * specify '0' as the default value for a type 'int' field it webmaster@1: * will not work because '0' is a string containing the webmaster@1: * character "zero", not an integer. webmaster@1: * - 'length': The maximal length of a type 'varchar' or 'text' webmaster@1: * field. Ignored for other field types. webmaster@1: * - 'unsigned': A boolean indicating whether a type 'int', 'float' webmaster@1: * and 'numeric' only is signed or unsigned. Defaults to webmaster@1: * FALSE. Ignored for other field types. webmaster@1: * - 'precision', 'scale': For type 'numeric' fields, indicates webmaster@1: * the precision (total number of significant digits) and scale webmaster@1: * (decimal digits right of the decimal point). Both values are webmaster@1: * mandatory. Ignored for other field types. webmaster@1: * webmaster@1: * All parameters apart from 'type' are optional except that type webmaster@1: * 'numeric' columns must specify 'precision' and 'scale'. webmaster@1: * webmaster@1: * - 'primary key': An array of one or more key column specifiers (see below) webmaster@1: * that form the primary key. webmaster@1: * - 'unique key': An associative array of unique keys ('keyname' => webmaster@1: * specification). Each specification is an array of one or more webmaster@1: * key column specifiers (see below) that form a unique key on the table. webmaster@1: * - 'indexes': An associative array of indexes ('indexame' => webmaster@1: * specification). Each specification is an array of one or more webmaster@1: * key column specifiers (see below) that form an index on the webmaster@1: * table. webmaster@1: * webmaster@1: * A key column specifier is either a string naming a column or an webmaster@1: * array of two elements, column name and length, specifying a prefix webmaster@1: * of the named column. webmaster@1: * webmaster@1: * As an example, here is a SUBSET of the schema definition for webmaster@1: * Drupal's 'node' table. It show four fields (nid, vid, type, and webmaster@1: * title), the primary key on field 'nid', a unique key named 'vid' on webmaster@1: * field 'vid', and two indexes, one named 'nid' on field 'nid' and webmaster@1: * one named 'node_title_type' on the field 'title' and the first four webmaster@1: * bytes of the field 'type': webmaster@1: * webmaster@1: * @code webmaster@1: * $schema['node'] = array( webmaster@1: * 'fields' => array( webmaster@1: * 'nid' => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE), webmaster@1: * 'vid' => array('type' => 'int', 'unsigned' => TRUE, 'not null' => TRUE, 'default' => 0), webmaster@1: * 'type' => array('type' => 'varchar', 'length' => 32, 'not null' => TRUE, 'default' => ''), webmaster@1: * 'title' => array('type' => 'varchar', 'length' => 128, 'not null' => TRUE, 'default' => ''), webmaster@1: * ), webmaster@1: * 'primary key' => array('nid'), webmaster@1: * 'unique keys' => array( webmaster@1: * 'vid' => array('vid') webmaster@1: * ), webmaster@1: * 'indexes' => array( webmaster@1: * 'nid' => array('nid'), webmaster@1: * 'node_title_type' => array('title', array('type', 4)), webmaster@1: * ), webmaster@1: * ); webmaster@1: * @endcode webmaster@1: * webmaster@1: * @see drupal_install_schema() webmaster@1: */ webmaster@1: webmaster@1: /** webmaster@1: * Create a new table from a Drupal table definition. webmaster@1: * webmaster@1: * @param $ret webmaster@1: * Array to which query results will be added. webmaster@1: * @param $name webmaster@1: * The name of the table to create. webmaster@1: * @param $table webmaster@1: * A Schema API table definition array. webmaster@1: */ webmaster@1: function db_create_table(&$ret, $name, $table) { webmaster@1: $statements = db_create_table_sql($name, $table); webmaster@1: foreach ($statements as $statement) { webmaster@1: $ret[] = update_sql($statement); webmaster@1: } webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Return an array of field names from an array of key/index column specifiers. webmaster@1: * webmaster@1: * This is usually an identity function but if a key/index uses a column prefix webmaster@1: * specification, this function extracts just the name. webmaster@1: * webmaster@1: * @param $fields webmaster@1: * An array of key/index column specifiers. webmaster@1: * @return webmaster@1: * An array of field names. webmaster@1: */ webmaster@1: function db_field_names($fields) { webmaster@1: $ret = array(); webmaster@1: foreach ($fields as $field) { webmaster@1: if (is_array($field)) { webmaster@1: $ret[] = $field[0]; webmaster@1: } webmaster@1: else { webmaster@1: $ret[] = $field; webmaster@1: } webmaster@1: } webmaster@1: return $ret; webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * Given a Schema API field type, return the correct %-placeholder. webmaster@1: * webmaster@1: * Embed the placeholder in a query to be passed to db_query and and pass as an webmaster@1: * argument to db_query a value of the specified type. webmaster@1: * webmaster@1: * @param $type webmaster@1: * The Schema API type of a field. webmaster@1: * @return webmaster@1: * The placeholder string to embed in a query for that type. webmaster@1: */ webmaster@1: function db_type_placeholder($type) { webmaster@1: switch ($type) { webmaster@1: case 'varchar': webmaster@1: case 'char': webmaster@1: case 'text': webmaster@1: case 'datetime': webmaster@7: return "'%s'"; webmaster@1: webmaster@1: case 'numeric': webmaster@7: // Numeric values are arbitrary precision numbers. Syntacically, numerics webmaster@7: // should be specified directly in SQL. However, without single quotes webmaster@7: // the %s placeholder does not protect against non-numeric characters such webmaster@7: // as spaces which would expose us to SQL injection. webmaster@7: return '%n'; webmaster@1: webmaster@1: case 'serial': webmaster@1: case 'int': webmaster@1: return '%d'; webmaster@1: webmaster@1: case 'float': webmaster@1: return '%f'; webmaster@1: webmaster@1: case 'blob': webmaster@1: return '%b'; webmaster@1: } webmaster@1: webmaster@1: // There is no safe value to return here, so return something that webmaster@1: // will cause the query to fail. webmaster@1: return 'unsupported type '. $type .'for db_type_placeholder'; webmaster@1: } webmaster@1: webmaster@1: /** webmaster@1: * @} End of "defgroup schemaapi". webmaster@1: */