summaryrefslogtreecommitdiff
path: root/kolab.org/www/drupal-7.26/includes
diff options
context:
space:
mode:
Diffstat (limited to 'kolab.org/www/drupal-7.26/includes')
-rw-r--r--kolab.org/www/drupal-7.26/includes/actions.inc388
-rw-r--r--kolab.org/www/drupal-7.26/includes/ajax.inc1212
-rw-r--r--kolab.org/www/drupal-7.26/includes/archiver.inc68
-rw-r--r--kolab.org/www/drupal-7.26/includes/authorize.inc334
-rw-r--r--kolab.org/www/drupal-7.26/includes/batch.inc539
-rw-r--r--kolab.org/www/drupal-7.26/includes/batch.queue.inc84
-rw-r--r--kolab.org/www/drupal-7.26/includes/bootstrap.inc3487
-rw-r--r--kolab.org/www/drupal-7.26/includes/cache-install.inc74
-rw-r--r--kolab.org/www/drupal-7.26/includes/cache.inc575
-rw-r--r--kolab.org/www/drupal-7.26/includes/common.inc8224
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/database.inc3039
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/log.inc161
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/mysql/database.inc203
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/mysql/install.inc33
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/mysql/query.inc94
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/mysql/schema.inc536
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/pgsql/database.inc223
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/pgsql/install.inc197
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/pgsql/query.inc210
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/pgsql/schema.inc617
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/pgsql/select.inc108
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/prefetch.inc507
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/query.inc1963
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/schema.inc727
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/select.inc1613
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/sqlite/database.inc519
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/sqlite/install.inc51
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/sqlite/query.inc140
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/sqlite/schema.inc683
-rw-r--r--kolab.org/www/drupal-7.26/includes/database/sqlite/select.inc27
-rw-r--r--kolab.org/www/drupal-7.26/includes/date.inc196
-rw-r--r--kolab.org/www/drupal-7.26/includes/entity.inc1360
-rw-r--r--kolab.org/www/drupal-7.26/includes/errors.inc286
-rw-r--r--kolab.org/www/drupal-7.26/includes/file.inc2518
-rw-r--r--kolab.org/www/drupal-7.26/includes/file.mimetypes.inc859
-rw-r--r--kolab.org/www/drupal-7.26/includes/filetransfer/filetransfer.inc427
-rw-r--r--kolab.org/www/drupal-7.26/includes/filetransfer/ftp.inc144
-rw-r--r--kolab.org/www/drupal-7.26/includes/filetransfer/local.inc76
-rw-r--r--kolab.org/www/drupal-7.26/includes/filetransfer/ssh.inc108
-rw-r--r--kolab.org/www/drupal-7.26/includes/form.inc4617
-rw-r--r--kolab.org/www/drupal-7.26/includes/graph.inc145
-rw-r--r--kolab.org/www/drupal-7.26/includes/image.inc435
-rw-r--r--kolab.org/www/drupal-7.26/includes/install.core.inc1909
-rw-r--r--kolab.org/www/drupal-7.26/includes/install.inc1332
-rw-r--r--kolab.org/www/drupal-7.26/includes/iso.inc483
-rw-r--r--kolab.org/www/drupal-7.26/includes/json-encode.inc102
-rw-r--r--kolab.org/www/drupal-7.26/includes/language.inc580
-rw-r--r--kolab.org/www/drupal-7.26/includes/locale.inc2442
-rw-r--r--kolab.org/www/drupal-7.26/includes/lock.inc274
-rw-r--r--kolab.org/www/drupal-7.26/includes/mail.inc623
-rw-r--r--kolab.org/www/drupal-7.26/includes/menu.inc3891
-rw-r--r--kolab.org/www/drupal-7.26/includes/module.inc1103
-rw-r--r--kolab.org/www/drupal-7.26/includes/pager.inc664
-rw-r--r--kolab.org/www/drupal-7.26/includes/password.inc287
-rw-r--r--kolab.org/www/drupal-7.26/includes/path.inc587
-rw-r--r--kolab.org/www/drupal-7.26/includes/registry.inc189
-rw-r--r--kolab.org/www/drupal-7.26/includes/session.inc533
-rw-r--r--kolab.org/www/drupal-7.26/includes/stream_wrappers.inc834
-rw-r--r--kolab.org/www/drupal-7.26/includes/tablesort.inc256
-rw-r--r--kolab.org/www/drupal-7.26/includes/theme.inc2918
-rw-r--r--kolab.org/www/drupal-7.26/includes/theme.maintenance.inc211
-rw-r--r--kolab.org/www/drupal-7.26/includes/token.inc264
-rw-r--r--kolab.org/www/drupal-7.26/includes/unicode.entities.inc265
-rw-r--r--kolab.org/www/drupal-7.26/includes/unicode.inc672
-rw-r--r--kolab.org/www/drupal-7.26/includes/update.inc1477
-rw-r--r--kolab.org/www/drupal-7.26/includes/updater.inc427
-rw-r--r--kolab.org/www/drupal-7.26/includes/utility.inc66
-rw-r--r--kolab.org/www/drupal-7.26/includes/xmlrpc.inc624
-rw-r--r--kolab.org/www/drupal-7.26/includes/xmlrpcs.inc384
69 files changed, 61204 insertions, 0 deletions
diff --git a/kolab.org/www/drupal-7.26/includes/actions.inc b/kolab.org/www/drupal-7.26/includes/actions.inc
new file mode 100644
index 0000000..ed43af4
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/actions.inc
@@ -0,0 +1,388 @@
+<?php
+
+/**
+ * @file
+ * This is the actions engine for executing stored actions.
+ */
+
+/**
+ * @defgroup actions Actions
+ * @{
+ * Functions that perform an action on a certain system object.
+ *
+ * Action functions are declared by modules by implementing hook_action_info().
+ * Modules can cause action functions to run by calling actions_do(), and
+ * trigger.module provides a user interface that lets administrators define
+ * events that cause action functions to run.
+ *
+ * Each action function takes two to four arguments:
+ * - $entity: The object that the action acts on, such as a node, comment, or
+ * user.
+ * - $context: Array of additional information about what triggered the action.
+ * - $a1, $a2: Optional additional information, which can be passed into
+ * actions_do() and will be passed along to the action function.
+ *
+ * @}
+ */
+
+/**
+ * Performs a given list of actions by executing their callback functions.
+ *
+ * Given the IDs of actions to perform, this function finds out what the
+ * callback functions for the actions are by querying the database. Then
+ * it calls each callback using the function call $function($object, $context,
+ * $a1, $a2), passing the input arguments of this function (see below) to the
+ * action function.
+ *
+ * @param $action_ids
+ * The IDs of the actions to perform. Can be a single action ID or an array
+ * of IDs. IDs of configurable actions must be given as numeric action IDs;
+ * IDs of non-configurable actions may be given as action function names.
+ * @param $object
+ * The object that the action will act on: a node, user, or comment object.
+ * @param $context
+ * Associative array containing extra information about what triggered
+ * the action call, with $context['hook'] giving the name of the hook
+ * that resulted in this call to actions_do().
+ * @param $a1
+ * Passed along to the callback.
+ * @param $a2
+ * Passed along to the callback.
+ *
+ * @return
+ * An associative array containing the results of the functions that
+ * perform the actions, keyed on action ID.
+ *
+ * @ingroup actions
+ */
+function actions_do($action_ids, $object = NULL, $context = NULL, $a1 = NULL, $a2 = NULL) {
+ // $stack tracks the number of recursive calls.
+ static $stack;
+ $stack++;
+ if ($stack > variable_get('actions_max_stack', 35)) {
+ watchdog('actions', 'Stack overflow: too many calls to actions_do(). Aborting to prevent infinite recursion.', array(), WATCHDOG_ERROR);
+ return;
+ }
+ $actions = array();
+ $available_actions = actions_list();
+ $actions_result = array();
+ if (is_array($action_ids)) {
+ $conditions = array();
+ foreach ($action_ids as $action_id) {
+ if (is_numeric($action_id)) {
+ $conditions[] = $action_id;
+ }
+ elseif (isset($available_actions[$action_id])) {
+ $actions[$action_id] = $available_actions[$action_id];
+ }
+ }
+
+ // When we have action instances we must go to the database to retrieve
+ // instance data.
+ if (!empty($conditions)) {
+ $query = db_select('actions');
+ $query->addField('actions', 'aid');
+ $query->addField('actions', 'type');
+ $query->addField('actions', 'callback');
+ $query->addField('actions', 'parameters');
+ $query->condition('aid', $conditions, 'IN');
+ $result = $query->execute();
+ foreach ($result as $action) {
+ $actions[$action->aid] = $action->parameters ? unserialize($action->parameters) : array();
+ $actions[$action->aid]['callback'] = $action->callback;
+ $actions[$action->aid]['type'] = $action->type;
+ }
+ }
+
+ // Fire actions, in no particular order.
+ foreach ($actions as $action_id => $params) {
+ // Configurable actions need parameters.
+ if (is_numeric($action_id)) {
+ $function = $params['callback'];
+ if (function_exists($function)) {
+ $context = array_merge($context, $params);
+ $actions_result[$action_id] = $function($object, $context, $a1, $a2);
+ }
+ else {
+ $actions_result[$action_id] = FALSE;
+ }
+ }
+ // Singleton action; $action_id is the function name.
+ else {
+ $actions_result[$action_id] = $action_id($object, $context, $a1, $a2);
+ }
+ }
+ }
+ // Optimized execution of a single action.
+ else {
+ // If it's a configurable action, retrieve stored parameters.
+ if (is_numeric($action_ids)) {
+ $action = db_query("SELECT callback, parameters FROM {actions} WHERE aid = :aid", array(':aid' => $action_ids))->fetchObject();
+ $function = $action->callback;
+ if (function_exists($function)) {
+ $context = array_merge($context, unserialize($action->parameters));
+ $actions_result[$action_ids] = $function($object, $context, $a1, $a2);
+ }
+ else {
+ $actions_result[$action_ids] = FALSE;
+ }
+ }
+ // Singleton action; $action_ids is the function name.
+ else {
+ if (function_exists($action_ids)) {
+ $actions_result[$action_ids] = $action_ids($object, $context, $a1, $a2);
+ }
+ else {
+ // Set to avoid undefined index error messages later.
+ $actions_result[$action_ids] = FALSE;
+ }
+ }
+ }
+ $stack--;
+ return $actions_result;
+}
+
+/**
+ * Discovers all available actions by invoking hook_action_info().
+ *
+ * This function contrasts with actions_get_all_actions(); see the
+ * documentation of actions_get_all_actions() for an explanation.
+ *
+ * @param $reset
+ * Reset the action info static cache.
+ *
+ * @return
+ * An associative array keyed on action function name, with the same format
+ * as the return value of hook_action_info(), containing all
+ * modules' hook_action_info() return values as modified by any
+ * hook_action_info_alter() implementations.
+ *
+ * @see hook_action_info()
+ */
+function actions_list($reset = FALSE) {
+ $actions = &drupal_static(__FUNCTION__);
+ if (!isset($actions) || $reset) {
+ $actions = module_invoke_all('action_info');
+ drupal_alter('action_info', $actions);
+ }
+
+ // See module_implements() for an explanation of this cast.
+ return (array) $actions;
+}
+
+/**
+ * Retrieves all action instances from the database.
+ *
+ * This function differs from the actions_list() function, which gathers
+ * actions by invoking hook_action_info(). The actions returned by this
+ * function and the actions returned by actions_list() are partially
+ * synchronized. Non-configurable actions from hook_action_info()
+ * implementations are put into the database when actions_synchronize() is
+ * called, which happens when admin/config/system/actions is visited.
+ * Configurable actions are not added to the database until they are configured
+ * in the user interface, in which case a database row is created for each
+ * configuration of each action.
+ *
+ * @return
+ * Associative array keyed by numeric action ID. Each value is an associative
+ * array with keys 'callback', 'label', 'type' and 'configurable'.
+ */
+function actions_get_all_actions() {
+ $actions = db_query("SELECT aid, type, callback, parameters, label FROM {actions}")->fetchAllAssoc('aid', PDO::FETCH_ASSOC);
+ foreach ($actions as &$action) {
+ $action['configurable'] = (bool) $action['parameters'];
+ unset($action['parameters']);
+ unset($action['aid']);
+ }
+ return $actions;
+}
+
+/**
+ * Creates an associative array keyed by hashes of function names or IDs.
+ *
+ * Hashes are used to prevent actual function names from going out into HTML
+ * forms and coming back.
+ *
+ * @param $actions
+ * An associative array with function names or action IDs as keys
+ * and associative arrays with keys 'label', 'type', etc. as values.
+ * This is usually the output of actions_list() or actions_get_all_actions().
+ *
+ * @return
+ * An associative array whose keys are hashes of the input array keys, and
+ * whose corresponding values are associative arrays with components
+ * 'callback', 'label', 'type', and 'configurable' from the input array.
+ */
+function actions_actions_map($actions) {
+ $actions_map = array();
+ foreach ($actions as $callback => $array) {
+ $key = drupal_hash_base64($callback);
+ $actions_map[$key]['callback'] = isset($array['callback']) ? $array['callback'] : $callback;
+ $actions_map[$key]['label'] = $array['label'];
+ $actions_map[$key]['type'] = $array['type'];
+ $actions_map[$key]['configurable'] = $array['configurable'];
+ }
+ return $actions_map;
+}
+
+/**
+ * Returns an action array key (function or ID), given its hash.
+ *
+ * Faster than actions_actions_map() when you only need the function name or ID.
+ *
+ * @param $hash
+ * Hash of a function name or action ID array key. The array key
+ * is a key into the return value of actions_list() (array key is the action
+ * function name) or actions_get_all_actions() (array key is the action ID).
+ *
+ * @return
+ * The corresponding array key, or FALSE if no match is found.
+ */
+function actions_function_lookup($hash) {
+ // Check for a function name match.
+ $actions_list = actions_list();
+ foreach ($actions_list as $function => $array) {
+ if (drupal_hash_base64($function) == $hash) {
+ return $function;
+ }
+ }
+ $aid = FALSE;
+ // Must be a configurable action; check database.
+ $result = db_query("SELECT aid FROM {actions} WHERE parameters <> ''")->fetchAll(PDO::FETCH_ASSOC);
+ foreach ($result as $row) {
+ if (drupal_hash_base64($row['aid']) == $hash) {
+ $aid = $row['aid'];
+ break;
+ }
+ }
+ return $aid;
+}
+
+/**
+ * Synchronizes actions that are provided by modules in hook_action_info().
+ *
+ * Actions provided by modules in hook_action_info() implementations are
+ * synchronized with actions that are stored in the actions database table.
+ * This is necessary so that actions that do not require configuration can
+ * receive action IDs.
+ *
+ * @param $delete_orphans
+ * If TRUE, any actions that exist in the database but are no longer
+ * found in the code (for example, because the module that provides them has
+ * been disabled) will be deleted.
+ */
+function actions_synchronize($delete_orphans = FALSE) {
+ $actions_in_code = actions_list(TRUE);
+ $actions_in_db = db_query("SELECT aid, callback, label FROM {actions} WHERE parameters = ''")->fetchAllAssoc('callback', PDO::FETCH_ASSOC);
+
+ // Go through all the actions provided by modules.
+ foreach ($actions_in_code as $callback => $array) {
+ // Ignore configurable actions since their instances get put in when the
+ // user adds the action.
+ if (!$array['configurable']) {
+ // If we already have an action ID for this action, no need to assign aid.
+ if (isset($actions_in_db[$callback])) {
+ unset($actions_in_db[$callback]);
+ }
+ else {
+ // This is a new singleton that we don't have an aid for; assign one.
+ db_insert('actions')
+ ->fields(array(
+ 'aid' => $callback,
+ 'type' => $array['type'],
+ 'callback' => $callback,
+ 'parameters' => '',
+ 'label' => $array['label'],
+ ))
+ ->execute();
+ watchdog('actions', "Action '%action' added.", array('%action' => $array['label']));
+ }
+ }
+ }
+
+ // Any actions that we have left in $actions_in_db are orphaned.
+ if ($actions_in_db) {
+ $orphaned = array_keys($actions_in_db);
+
+ if ($delete_orphans) {
+ $actions = db_query('SELECT aid, label FROM {actions} WHERE callback IN (:orphaned)', array(':orphaned' => $orphaned))->fetchAll();
+ foreach ($actions as $action) {
+ actions_delete($action->aid);
+ watchdog('actions', "Removed orphaned action '%action' from database.", array('%action' => $action->label));
+ }
+ }
+ else {
+ $link = l(t('Remove orphaned actions'), 'admin/config/system/actions/orphan');
+ $count = count($actions_in_db);
+ $orphans = implode(', ', $orphaned);
+ watchdog('actions', '@count orphaned actions (%orphans) exist in the actions table. !link', array('@count' => $count, '%orphans' => $orphans, '!link' => $link), WATCHDOG_INFO);
+ }
+ }
+}
+
+/**
+ * Saves an action and its user-supplied parameter values to the database.
+ *
+ * @param $function
+ * The name of the function to be called when this action is performed.
+ * @param $type
+ * The type of action, to describe grouping and/or context, e.g., 'node',
+ * 'user', 'comment', or 'system'.
+ * @param $params
+ * An associative array with parameter names as keys and parameter values as
+ * values.
+ * @param $label
+ * A user-supplied label of this particular action, e.g., 'Send e-mail
+ * to Jim'.
+ * @param $aid
+ * The ID of this action. If omitted, a new action is created.
+ *
+ * @return
+ * The ID of the action.
+ */
+function actions_save($function, $type, $params, $label, $aid = NULL) {
+ // aid is the callback for singleton actions so we need to keep a separate
+ // table for numeric aids.
+ if (!$aid) {
+ $aid = db_next_id();
+ }
+
+ db_merge('actions')
+ ->key(array('aid' => $aid))
+ ->fields(array(
+ 'callback' => $function,
+ 'type' => $type,
+ 'parameters' => serialize($params),
+ 'label' => $label,
+ ))
+ ->execute();
+
+ watchdog('actions', 'Action %action saved.', array('%action' => $label));
+ return $aid;
+}
+
+/**
+ * Retrieves a single action from the database.
+ *
+ * @param $aid
+ * The ID of the action to retrieve.
+ *
+ * @return
+ * The appropriate action row from the database as an object.
+ */
+function actions_load($aid) {
+ return db_query("SELECT aid, type, callback, parameters, label FROM {actions} WHERE aid = :aid", array(':aid' => $aid))->fetchObject();
+}
+
+/**
+ * Deletes a single action from the database.
+ *
+ * @param $aid
+ * The ID of the action to delete.
+ */
+function actions_delete($aid) {
+ db_delete('actions')
+ ->condition('aid', $aid)
+ ->execute();
+ module_invoke_all('actions_delete', $aid);
+}
diff --git a/kolab.org/www/drupal-7.26/includes/ajax.inc b/kolab.org/www/drupal-7.26/includes/ajax.inc
new file mode 100644
index 0000000..ab0111c
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/ajax.inc
@@ -0,0 +1,1212 @@
+<?php
+
+/**
+ * @file
+ * Functions for use with Drupal's Ajax framework.
+ */
+
+/**
+ * @defgroup ajax Ajax framework
+ * @{
+ * Functions for Drupal's Ajax framework.
+ *
+ * Drupal's Ajax framework is used to dynamically update parts of a page's HTML
+ * based on data from the server. Upon a specified event, such as a button
+ * click, a callback function is triggered which performs server-side logic and
+ * may return updated markup, which is then replaced on-the-fly with no page
+ * refresh necessary.
+ *
+ * This framework creates a PHP macro language that allows the server to
+ * instruct JavaScript to perform actions on the client browser. When using
+ * forms, it can be used with the #ajax property.
+ * The #ajax property can be used to bind events to the Ajax framework. By
+ * default, #ajax uses 'system/ajax' as its path for submission and thus calls
+ * ajax_form_callback() and a defined #ajax['callback'] function.
+ * However, you may optionally specify a different path to request or a
+ * different callback function to invoke, which can return updated HTML or can
+ * also return a richer set of
+ * @link ajax_commands Ajax framework commands @endlink.
+ *
+ * Standard form handling is as follows:
+ * - A form element has a #ajax property that includes #ajax['callback'] and
+ * omits #ajax['path']. See below about using #ajax['path'] to implement
+ * advanced use-cases that require something other than standard form
+ * handling.
+ * - On the specified element, Ajax processing is triggered by a change to
+ * that element.
+ * - The browser submits an HTTP POST request to the 'system/ajax' Drupal
+ * path.
+ * - The menu page callback for 'system/ajax', ajax_form_callback(), calls
+ * drupal_process_form() to process the form submission and rebuild the
+ * form if necessary. The form is processed in much the same way as if it
+ * were submitted without Ajax, with the same #process functions and
+ * validation and submission handlers called in either case, making it easy
+ * to create Ajax-enabled forms that degrade gracefully when JavaScript is
+ * disabled.
+ * - After form processing is complete, ajax_form_callback() calls the
+ * function named by #ajax['callback'], which returns the form element that
+ * has been updated and needs to be returned to the browser, or
+ * alternatively, an array of custom Ajax commands.
+ * - The page delivery callback for 'system/ajax', ajax_deliver(), renders the
+ * element returned by #ajax['callback'], and returns the JSON string
+ * created by ajax_render() to the browser.
+ * - The browser unserializes the returned JSON string into an array of
+ * command objects and executes each command, resulting in the old page
+ * content within and including the HTML element specified by
+ * #ajax['wrapper'] being replaced by the new content returned by
+ * #ajax['callback'], using a JavaScript animation effect specified by
+ * #ajax['effect'].
+ *
+ * A simple example of basic Ajax use from the
+ * @link http://drupal.org/project/examples Examples module @endlink follows:
+ * @code
+ * function main_page() {
+ * return drupal_get_form('ajax_example_simplest');
+ * }
+ *
+ * function ajax_example_simplest($form, &$form_state) {
+ * $form = array();
+ * $form['changethis'] = array(
+ * '#type' => 'select',
+ * '#options' => array(
+ * 'one' => 'one',
+ * 'two' => 'two',
+ * 'three' => 'three',
+ * ),
+ * '#ajax' => array(
+ * 'callback' => 'ajax_example_simplest_callback',
+ * 'wrapper' => 'replace_textfield_div',
+ * ),
+ * );
+
+ * // This entire form element will be replaced with an updated value.
+ * $form['replace_textfield'] = array(
+ * '#type' => 'textfield',
+ * '#title' => t("The default value will be changed"),
+ * '#description' => t("Say something about why you chose") . "'" .
+ * (!empty($form_state['values']['changethis'])
+ * ? $form_state['values']['changethis'] : t("Not changed yet")) . "'",
+ * '#prefix' => '<div id="replace_textfield_div">',
+ * '#suffix' => '</div>',
+ * );
+ * return $form;
+ * }
+ *
+ * function ajax_example_simplest_callback($form, $form_state) {
+ * // The form has already been submitted and updated. We can return the replaced
+ * // item as it is.
+ * return $form['replace_textfield'];
+ * }
+ * @endcode
+ *
+ * In the above example, the 'changethis' element is Ajax-enabled. The default
+ * #ajax['event'] is 'change', so when the 'changethis' element changes,
+ * an Ajax call is made. The form is submitted and reprocessed, and then the
+ * callback is called. In this case, the form has been automatically
+ * built changing $form['replace_textfield']['#description'], so the callback
+ * just returns that part of the form.
+ *
+ * To implement Ajax handling in a form, add '#ajax' to the form
+ * definition of a field. That field will trigger an Ajax event when it is
+ * clicked (or changed, depending on the kind of field). #ajax supports
+ * the following parameters (either 'path' or 'callback' is required at least):
+ * - #ajax['callback']: The callback to invoke to handle the server side of the
+ * Ajax event, which will receive a $form and $form_state as arguments, and
+ * returns a renderable array (most often a form or form fragment), an HTML
+ * string, or an array of Ajax commands. If returning a renderable array or
+ * a string, the value will replace the original element named in
+ * #ajax['wrapper'], and
+ * theme_status_messages()
+ * will be prepended to that
+ * element. (If the status messages are not wanted, return an array
+ * of Ajax commands instead.)
+ * #ajax['wrapper']. If an array of Ajax commands is returned, it will be
+ * executed by the calling code.
+ * - #ajax['path']: The menu path to use for the request. This is often omitted
+ * and the default is used. This path should map
+ * to a menu page callback that returns data using ajax_render(). Defaults to
+ * 'system/ajax', which invokes ajax_form_callback(), eventually calling
+ * the function named in #ajax['callback']. If you use a custom
+ * path, you must set up the menu entry and handle the entire callback in your
+ * own code.
+ * - #ajax['wrapper']: The CSS ID of the area to be replaced by the content
+ * returned by the #ajax['callback'] function. The content returned from
+ * the callback will replace the entire element named by #ajax['wrapper'].
+ * The wrapper is usually created using #prefix and #suffix properties in the
+ * form. Note that this is the wrapper ID, not a CSS selector. So to replace
+ * the element referred to by the CSS selector #some-selector on the page,
+ * use #ajax['wrapper'] = 'some-selector', not '#some-selector'.
+ * - #ajax['effect']: The jQuery effect to use when placing the new HTML.
+ * Defaults to no effect. Valid options are 'none', 'slide', or 'fade'.
+ * - #ajax['speed']: The effect speed to use. Defaults to 'slow'. May be
+ * 'slow', 'fast' or a number in milliseconds which represents the length
+ * of time the effect should run.
+ * - #ajax['event']: The JavaScript event to respond to. This is normally
+ * selected automatically for the type of form widget being used, and
+ * is only needed if you need to override the default behavior.
+ * - #ajax['prevent']: A JavaScript event to prevent when 'event' is triggered.
+ * Defaults to 'click' for #ajax on #type 'submit', 'button', and
+ * 'image_button'. Multiple events may be specified separated by spaces.
+ * For example, when binding #ajax behaviors to form buttons, pressing the
+ * ENTER key within a textfield triggers the 'click' event of the form's first
+ * submit button. Triggering Ajax in this situation leads to problems, like
+ * breaking autocomplete textfields. Because of that, Ajax behaviors are bound
+ * to the 'mousedown' event on form buttons by default. However, binding to
+ * 'mousedown' rather than 'click' means that it is possible to trigger a
+ * click by pressing the mouse, holding the mouse button down until the Ajax
+ * request is complete and the button is re-enabled, and then releasing the
+ * mouse button. For this case, 'prevent' can be set to 'click', so an
+ * additional event handler is bound to prevent such a click from triggering a
+ * non-Ajax form submission. This also prevents a textfield's ENTER press
+ * triggering a button's non-Ajax form submission behavior.
+ * - #ajax['method']: The jQuery method to use to place the new HTML.
+ * Defaults to 'replaceWith'. May be: 'replaceWith', 'append', 'prepend',
+ * 'before', 'after', or 'html'. See the
+ * @link http://api.jquery.com/category/manipulation/ jQuery manipulators documentation @endlink
+ * for more information on these methods.
+ * - #ajax['progress']: Choose either a throbber or progress bar that is
+ * displayed while awaiting a response from the callback, and add an optional
+ * message. Possible keys: 'type', 'message', 'url', 'interval'.
+ * More information is available in the
+ * @link forms_api_reference.html Form API Reference @endlink
+ *
+ * In addition to using Form API for doing in-form modification, Ajax may be
+ * enabled by adding classes to buttons and links. By adding the 'use-ajax'
+ * class to a link, the link will be loaded via an Ajax call. When using this
+ * method, the href of the link can contain '/nojs/' as part of the path. When
+ * the Ajax framework makes the request, it will convert this to '/ajax/'.
+ * The server is then able to easily tell if this request was made through an
+ * actual Ajax request or in a degraded state, and respond appropriately.
+ *
+ * Similarly, submit buttons can be given the class 'use-ajax-submit'. The
+ * form will then be submitted via Ajax to the path specified in the #action.
+ * Like the ajax-submit class above, this path will have '/nojs/' replaced with
+ * '/ajax/' so that the submit handler can tell if the form was submitted
+ * in a degraded state or not.
+ *
+ * When responding to Ajax requests, the server should do what it needs to do
+ * for that request, then create a commands array. This commands array will
+ * be converted to a JSON object and returned to the client, which will then
+ * iterate over the array and process it like a macro language.
+ *
+ * Each command item is an associative array which will be converted to a
+ * command object on the JavaScript side. $command_item['command'] is the type
+ * of command, e.g. 'alert' or 'replace', and will correspond to a method in the
+ * Drupal.ajax[command] space. The command array may contain any other data that
+ * the command needs to process, e.g. 'method', 'selector', 'settings', etc.
+ *
+ * Commands are usually created with a couple of helper functions, so they
+ * look like this:
+ * @code
+ * $commands = array();
+ * // Replace the content of '#object-1' on the page with 'some html here'.
+ * $commands[] = ajax_command_replace('#object-1', 'some html here');
+ * // Add a visual "changed" marker to the '#object-1' element.
+ * $commands[] = ajax_command_changed('#object-1');
+ * // Menu 'page callback' and #ajax['callback'] functions are supposed to
+ * // return render arrays. If returning an Ajax commands array, it must be
+ * // encapsulated in a render array structure.
+ * return array('#type' => 'ajax', '#commands' => $commands);
+ * @endcode
+ *
+ * When returning an Ajax command array, it is often useful to have
+ * status messages rendered along with other tasks in the command array.
+ * In that case the the Ajax commands array may be constructed like this:
+ * @code
+ * $commands = array();
+ * $commands[] = ajax_command_replace(NULL, $output);
+ * $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
+ * return array('#type' => 'ajax', '#commands' => $commands);
+ * @endcode
+ *
+ * See @link ajax_commands Ajax framework commands @endlink
+ */
+
+/**
+ * Renders a commands array into JSON.
+ *
+ * @param $commands
+ * A list of macro commands generated by the use of ajax_command_*()
+ * functions.
+ */
+function ajax_render($commands = array()) {
+ // Ajax responses aren't rendered with html.tpl.php, so we have to call
+ // drupal_get_css() and drupal_get_js() here, in order to have new files added
+ // during this request to be loaded by the page. We only want to send back
+ // files that the page hasn't already loaded, so we implement simple diffing
+ // logic using array_diff_key().
+ foreach (array('css', 'js') as $type) {
+ // It is highly suspicious if $_POST['ajax_page_state'][$type] is empty,
+ // since the base page ought to have at least one JS file and one CSS file
+ // loaded. It probably indicates an error, and rather than making the page
+ // reload all of the files, instead we return no new files.
+ if (empty($_POST['ajax_page_state'][$type])) {
+ $items[$type] = array();
+ }
+ else {
+ $function = 'drupal_add_' . $type;
+ $items[$type] = $function();
+ drupal_alter($type, $items[$type]);
+ // @todo Inline CSS and JS items are indexed numerically. These can't be
+ // reliably diffed with array_diff_key(), since the number can change
+ // due to factors unrelated to the inline content, so for now, we strip
+ // the inline items from Ajax responses, and can add support for them
+ // when drupal_add_css() and drupal_add_js() are changed to use a hash
+ // of the inline content as the array key.
+ foreach ($items[$type] as $key => $item) {
+ if (is_numeric($key)) {
+ unset($items[$type][$key]);
+ }
+ }
+ // Ensure that the page doesn't reload what it already has.
+ $items[$type] = array_diff_key($items[$type], $_POST['ajax_page_state'][$type]);
+ }
+ }
+
+ // Render the HTML to load these files, and add AJAX commands to insert this
+ // HTML in the page. We pass TRUE as the $skip_alter argument to prevent the
+ // data from being altered again, as we already altered it above. Settings are
+ // handled separately, afterwards.
+ if (isset($items['js']['settings'])) {
+ unset($items['js']['settings']);
+ }
+ $styles = drupal_get_css($items['css'], TRUE);
+ $scripts_footer = drupal_get_js('footer', $items['js'], TRUE);
+ $scripts_header = drupal_get_js('header', $items['js'], TRUE);
+
+ $extra_commands = array();
+ if (!empty($styles)) {
+ $extra_commands[] = ajax_command_prepend('head', $styles);
+ }
+ if (!empty($scripts_header)) {
+ $extra_commands[] = ajax_command_prepend('head', $scripts_header);
+ }
+ if (!empty($scripts_footer)) {
+ $extra_commands[] = ajax_command_append('body', $scripts_footer);
+ }
+ if (!empty($extra_commands)) {
+ $commands = array_merge($extra_commands, $commands);
+ }
+
+ // Now add a command to merge changes and additions to Drupal.settings.
+ $scripts = drupal_add_js();
+ if (!empty($scripts['settings'])) {
+ $settings = $scripts['settings'];
+ array_unshift($commands, ajax_command_settings(call_user_func_array('array_merge_recursive', $settings['data']), TRUE));
+ }
+
+ // Allow modules to alter any Ajax response.
+ drupal_alter('ajax_render', $commands);
+
+ return drupal_json_encode($commands);
+}
+
+/**
+ * Gets a form submitted via #ajax during an Ajax callback.
+ *
+ * This will load a form from the form cache used during Ajax operations. It
+ * pulls the form info from $_POST.
+ *
+ * @return
+ * An array containing the $form and $form_state. Use the list() function
+ * to break these apart:
+ * @code
+ * list($form, $form_state, $form_id, $form_build_id) = ajax_get_form();
+ * @endcode
+ */
+function ajax_get_form() {
+ $form_state = form_state_defaults();
+
+ $form_build_id = $_POST['form_build_id'];
+
+ // Get the form from the cache.
+ $form = form_get_cache($form_build_id, $form_state);
+ if (!$form) {
+ // If $form cannot be loaded from the cache, the form_build_id in $_POST
+ // must be invalid, which means that someone performed a POST request onto
+ // system/ajax without actually viewing the concerned form in the browser.
+ // This is likely a hacking attempt as it never happens under normal
+ // circumstances, so we just do nothing.
+ watchdog('ajax', 'Invalid form POST data.', array(), WATCHDOG_WARNING);
+ drupal_exit();
+ }
+
+ // Since some of the submit handlers are run, redirects need to be disabled.
+ $form_state['no_redirect'] = TRUE;
+
+ // When a form is rebuilt after Ajax processing, its #build_id and #action
+ // should not change.
+ // @see drupal_rebuild_form()
+ $form_state['rebuild_info']['copy']['#build_id'] = TRUE;
+ $form_state['rebuild_info']['copy']['#action'] = TRUE;
+
+ // The form needs to be processed; prepare for that by setting a few internal
+ // variables.
+ $form_state['input'] = $_POST;
+ $form_id = $form['#form_id'];
+
+ return array($form, $form_state, $form_id, $form_build_id);
+}
+
+/**
+ * Menu callback; handles Ajax requests for the #ajax Form API property.
+ *
+ * This rebuilds the form from cache and invokes the defined #ajax['callback']
+ * to return an Ajax command structure for JavaScript. In case no 'callback' has
+ * been defined, nothing will happen.
+ *
+ * The Form API #ajax property can be set both for buttons and other input
+ * elements.
+ *
+ * This function is also the canonical example of how to implement
+ * #ajax['path']. If processing is required that cannot be accomplished with
+ * a callback, re-implement this function and set #ajax['path'] to the
+ * enhanced function.
+ *
+ * @see system_menu()
+ */
+function ajax_form_callback() {
+ list($form, $form_state) = ajax_get_form();
+ drupal_process_form($form['#form_id'], $form, $form_state);
+
+ // We need to return the part of the form (or some other content) that needs
+ // to be re-rendered so the browser can update the page with changed content.
+ // Since this is the generic menu callback used by many Ajax elements, it is
+ // up to the #ajax['callback'] function of the element (may or may not be a
+ // button) that triggered the Ajax request to determine what needs to be
+ // rendered.
+ if (!empty($form_state['triggering_element'])) {
+ $callback = $form_state['triggering_element']['#ajax']['callback'];
+ }
+ if (!empty($callback) && function_exists($callback)) {
+ return $callback($form, $form_state);
+ }
+}
+
+/**
+ * Theme callback for Ajax requests.
+ *
+ * Many different pages can invoke an Ajax request to system/ajax or another
+ * generic Ajax path. It is almost always desired for an Ajax response to be
+ * rendered using the same theme as the base page, because most themes are built
+ * with the assumption that they control the entire page, so if the CSS for two
+ * themes are both loaded for a given page, they may conflict with each other.
+ * For example, Bartik is Drupal's default theme, and Seven is Drupal's default
+ * administration theme. Depending on whether the "Use the administration theme
+ * when editing or creating content" checkbox is checked, the node edit form may
+ * be displayed in either theme, but the Ajax response to the Field module's
+ * "Add another item" button should be rendered using the same theme as the rest
+ * of the page. Therefore, system_menu() sets the 'theme callback' for
+ * 'system/ajax' to this function, and it is recommended that modules
+ * implementing other generic Ajax paths do the same.
+ *
+ * @see system_menu()
+ * @see file_menu()
+ */
+function ajax_base_page_theme() {
+ if (!empty($_POST['ajax_page_state']['theme']) && !empty($_POST['ajax_page_state']['theme_token'])) {
+ $theme = $_POST['ajax_page_state']['theme'];
+ $token = $_POST['ajax_page_state']['theme_token'];
+
+ // Prevent a request forgery from giving a person access to a theme they
+ // shouldn't be otherwise allowed to see. However, since everyone is allowed
+ // to see the default theme, token validation isn't required for that, and
+ // bypassing it allows most use-cases to work even when accessed from the
+ // page cache.
+ if ($theme === variable_get('theme_default', 'bartik') || drupal_valid_token($token, $theme)) {
+ return $theme;
+ }
+ }
+}
+
+/**
+ * Packages and sends the result of a page callback as an Ajax response.
+ *
+ * This function is the equivalent of drupal_deliver_html_page(), but for Ajax
+ * requests. Like that function, it:
+ * - Adds needed HTTP headers.
+ * - Prints rendered output.
+ * - Performs end-of-request tasks.
+ *
+ * @param $page_callback_result
+ * The result of a page callback. Can be one of:
+ * - NULL: to indicate no content.
+ * - An integer menu status constant: to indicate an error condition.
+ * - A string of HTML content.
+ * - A renderable array of content.
+ *
+ * @see drupal_deliver_html_page()
+ */
+function ajax_deliver($page_callback_result) {
+ // Browsers do not allow JavaScript to read the contents of a user's local
+ // files. To work around that, the jQuery Form plugin submits forms containing
+ // a file input element to an IFRAME, instead of using XHR. Browsers do not
+ // normally expect JSON strings as content within an IFRAME, so the response
+ // must be customized accordingly.
+ // @see http://malsup.com/jquery/form/#file-upload
+ // @see Drupal.ajax.prototype.beforeSend()
+ $iframe_upload = !empty($_POST['ajax_iframe_upload']);
+
+ // Emit a Content-Type HTTP header if none has been added by the page callback
+ // or by a wrapping delivery callback.
+ if (is_null(drupal_get_http_header('Content-Type'))) {
+ if (!$iframe_upload) {
+ // Standard JSON can be returned to a browser's XHR object, and to
+ // non-browser user agents.
+ // @see http://www.ietf.org/rfc/rfc4627.txt?number=4627
+ drupal_add_http_header('Content-Type', 'application/json; charset=utf-8');
+ }
+ else {
+ // Browser IFRAMEs expect HTML. With most other content types, Internet
+ // Explorer presents the user with a download prompt.
+ drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
+ }
+ }
+
+ // Print the response.
+ $commands = ajax_prepare_response($page_callback_result);
+ $json = ajax_render($commands);
+ if (!$iframe_upload) {
+ // Standard JSON can be returned to a browser's XHR object, and to
+ // non-browser user agents.
+ print $json;
+ }
+ else {
+ // Browser IFRAMEs expect HTML. Browser extensions, such as Linkification
+ // and Skype's Browser Highlighter, convert URLs, phone numbers, etc. into
+ // links. This corrupts the JSON response. Protect the integrity of the
+ // JSON data by making it the value of a textarea.
+ // @see http://malsup.com/jquery/form/#file-upload
+ // @see http://drupal.org/node/1009382
+ print '<textarea>' . $json . '</textarea>';
+ }
+
+ // Perform end-of-request tasks.
+ ajax_footer();
+}
+
+/**
+ * Converts the return value of a page callback into an Ajax commands array.
+ *
+ * @param $page_callback_result
+ * The result of a page callback. Can be one of:
+ * - NULL: to indicate no content.
+ * - An integer menu status constant: to indicate an error condition.
+ * - A string of HTML content.
+ * - A renderable array of content.
+ *
+ * @return
+ * An Ajax commands array that can be passed to ajax_render().
+ */
+function ajax_prepare_response($page_callback_result) {
+ $commands = array();
+ if (!isset($page_callback_result)) {
+ // Simply delivering an empty commands array is sufficient. This results
+ // in the Ajax request being completed, but nothing being done to the page.
+ }
+ elseif (is_int($page_callback_result)) {
+ switch ($page_callback_result) {
+ case MENU_NOT_FOUND:
+ $commands[] = ajax_command_alert(t('The requested page could not be found.'));
+ break;
+
+ case MENU_ACCESS_DENIED:
+ $commands[] = ajax_command_alert(t('You are not authorized to access this page.'));
+ break;
+
+ case MENU_SITE_OFFLINE:
+ $commands[] = ajax_command_alert(filter_xss_admin(variable_get('maintenance_mode_message',
+ t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
+ break;
+ }
+ }
+ elseif (is_array($page_callback_result) && isset($page_callback_result['#type']) && ($page_callback_result['#type'] == 'ajax')) {
+ // Complex Ajax callbacks can return a result that contains an error message
+ // or a specific set of commands to send to the browser.
+ $page_callback_result += element_info('ajax');
+ $error = $page_callback_result['#error'];
+ if (isset($error) && $error !== FALSE) {
+ if ((empty($error) || $error === TRUE)) {
+ $error = t('An error occurred while handling the request: The server received invalid input.');
+ }
+ $commands[] = ajax_command_alert($error);
+ }
+ else {
+ $commands = $page_callback_result['#commands'];
+ }
+ }
+ else {
+ // Like normal page callbacks, simple Ajax callbacks can return HTML
+ // content, as a string or render array. This HTML is inserted in some
+ // relationship to #ajax['wrapper'], as determined by which jQuery DOM
+ // manipulation method is used. The method used is specified by
+ // #ajax['method']. The default method is 'replaceWith', which completely
+ // replaces the old wrapper element and its content with the new HTML.
+ $html = is_string($page_callback_result) ? $page_callback_result : drupal_render($page_callback_result);
+ $commands[] = ajax_command_insert(NULL, $html);
+ // Add the status messages inside the new content's wrapper element, so that
+ // on subsequent Ajax requests, it is treated as old content.
+ $commands[] = ajax_command_prepend(NULL, theme('status_messages'));
+ }
+
+ return $commands;
+}
+
+/**
+ * Performs end-of-Ajax-request tasks.
+ *
+ * This function is the equivalent of drupal_page_footer(), but for Ajax
+ * requests.
+ *
+ * @see drupal_page_footer()
+ */
+function ajax_footer() {
+ // Even for Ajax requests, invoke hook_exit() implementations. There may be
+ // modules that need very fast Ajax responses, and therefore, run Ajax
+ // requests with an early bootstrap.
+ if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update')) {
+ module_invoke_all('exit');
+ }
+
+ // Commit the user session. See above comment about the possibility of this
+ // function running without session.inc loaded.
+ if (function_exists('drupal_session_commit')) {
+ drupal_session_commit();
+ }
+}
+
+/**
+ * Form element processing handler for the #ajax form property.
+ *
+ * @param $element
+ * An associative array containing the properties of the element.
+ *
+ * @return
+ * The processed element.
+ *
+ * @see ajax_pre_render_element()
+ */
+function ajax_process_form($element, &$form_state) {
+ $element = ajax_pre_render_element($element);
+ if (!empty($element['#ajax_processed'])) {
+ $form_state['cache'] = TRUE;
+ }
+ return $element;
+}
+
+/**
+ * Adds Ajax information about an element to communicate with JavaScript.
+ *
+ * If #ajax['path'] is set on an element, this additional JavaScript is added
+ * to the page header to attach the Ajax behaviors. See ajax.js for more
+ * information.
+ *
+ * @param $element
+ * An associative array containing the properties of the element.
+ * Properties used:
+ * - #ajax['event']
+ * - #ajax['prevent']
+ * - #ajax['path']
+ * - #ajax['options']
+ * - #ajax['wrapper']
+ * - #ajax['parameters']
+ * - #ajax['effect']
+ *
+ * @return
+ * The processed element with the necessary JavaScript attached to it.
+ */
+function ajax_pre_render_element($element) {
+ // Skip already processed elements.
+ if (isset($element['#ajax_processed'])) {
+ return $element;
+ }
+ // Initialize #ajax_processed, so we do not process this element again.
+ $element['#ajax_processed'] = FALSE;
+
+ // Nothing to do if there is neither a callback nor a path.
+ if (!(isset($element['#ajax']['callback']) || isset($element['#ajax']['path']))) {
+ return $element;
+ }
+
+ // Add a reasonable default event handler if none was specified.
+ if (isset($element['#ajax']) && !isset($element['#ajax']['event'])) {
+ switch ($element['#type']) {
+ case 'submit':
+ case 'button':
+ case 'image_button':
+ // Pressing the ENTER key within a textfield triggers the click event of
+ // the form's first submit button. Triggering Ajax in this situation
+ // leads to problems, like breaking autocomplete textfields, so we bind
+ // to mousedown instead of click.
+ // @see http://drupal.org/node/216059
+ $element['#ajax']['event'] = 'mousedown';
+ // Retain keyboard accessibility by setting 'keypress'. This causes
+ // ajax.js to trigger 'event' when SPACE or ENTER are pressed while the
+ // button has focus.
+ $element['#ajax']['keypress'] = TRUE;
+ // Binding to mousedown rather than click means that it is possible to
+ // trigger a click by pressing the mouse, holding the mouse button down
+ // until the Ajax request is complete and the button is re-enabled, and
+ // then releasing the mouse button. Set 'prevent' so that ajax.js binds
+ // an additional handler to prevent such a click from triggering a
+ // non-Ajax form submission. This also prevents a textfield's ENTER
+ // press triggering this button's non-Ajax form submission behavior.
+ if (!isset($element['#ajax']['prevent'])) {
+ $element['#ajax']['prevent'] = 'click';
+ }
+ break;
+
+ case 'password':
+ case 'textfield':
+ case 'textarea':
+ $element['#ajax']['event'] = 'blur';
+ break;
+
+ case 'radio':
+ case 'checkbox':
+ case 'select':
+ $element['#ajax']['event'] = 'change';
+ break;
+
+ case 'link':
+ $element['#ajax']['event'] = 'click';
+ break;
+
+ default:
+ return $element;
+ }
+ }
+
+ // Attach JavaScript settings to the element.
+ if (isset($element['#ajax']['event'])) {
+ $element['#attached']['library'][] = array('system', 'jquery.form');
+ $element['#attached']['library'][] = array('system', 'drupal.ajax');
+
+ $settings = $element['#ajax'];
+
+ // Assign default settings.
+ $settings += array(
+ 'path' => 'system/ajax',
+ 'options' => array(),
+ );
+
+ // @todo Legacy support. Remove in Drupal 8.
+ if (isset($settings['method']) && $settings['method'] == 'replace') {
+ $settings['method'] = 'replaceWith';
+ }
+
+ // Change path to URL.
+ $settings['url'] = url($settings['path'], $settings['options']);
+ unset($settings['path'], $settings['options']);
+
+ // Add special data to $settings['submit'] so that when this element
+ // triggers an Ajax submission, Drupal's form processing can determine which
+ // element triggered it.
+ // @see _form_element_triggered_scripted_submission()
+ if (isset($settings['trigger_as'])) {
+ // An element can add a 'trigger_as' key within #ajax to make the element
+ // submit as though another one (for example, a non-button can use this
+ // to submit the form as though a button were clicked). When using this,
+ // the 'name' key is always required to identify the element to trigger
+ // as. The 'value' key is optional, and only needed when multiple elements
+ // share the same name, which is commonly the case for buttons.
+ $settings['submit']['_triggering_element_name'] = $settings['trigger_as']['name'];
+ if (isset($settings['trigger_as']['value'])) {
+ $settings['submit']['_triggering_element_value'] = $settings['trigger_as']['value'];
+ }
+ unset($settings['trigger_as']);
+ }
+ elseif (isset($element['#name'])) {
+ // Most of the time, elements can submit as themselves, in which case the
+ // 'trigger_as' key isn't needed, and the element's name is used.
+ $settings['submit']['_triggering_element_name'] = $element['#name'];
+ // If the element is a (non-image) button, its name may not identify it
+ // uniquely, in which case a match on value is also needed.
+ // @see _form_button_was_clicked()
+ if (isset($element['#button_type']) && empty($element['#has_garbage_value'])) {
+ $settings['submit']['_triggering_element_value'] = $element['#value'];
+ }
+ }
+
+ // Convert a simple #ajax['progress'] string into an array.
+ if (isset($settings['progress']) && is_string($settings['progress'])) {
+ $settings['progress'] = array('type' => $settings['progress']);
+ }
+ // Change progress path to a full URL.
+ if (isset($settings['progress']['path'])) {
+ $settings['progress']['url'] = url($settings['progress']['path']);
+ unset($settings['progress']['path']);
+ }
+
+ $element['#attached']['js'][] = array(
+ 'type' => 'setting',
+ 'data' => array('ajax' => array($element['#id'] => $settings)),
+ );
+
+ // Indicate that Ajax processing was successful.
+ $element['#ajax_processed'] = TRUE;
+ }
+ return $element;
+}
+
+/**
+ * @} End of "defgroup ajax".
+ */
+
+/**
+ * @defgroup ajax_commands Ajax framework commands
+ * @{
+ * Functions to create various Ajax commands.
+ *
+ * These functions can be used to create arrays for use with the
+ * ajax_render() function.
+ */
+
+/**
+ * Creates a Drupal Ajax 'alert' command.
+ *
+ * The 'alert' command instructs the client to display a JavaScript alert
+ * dialog box.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.alert()
+ * defined in misc/ajax.js.
+ *
+ * @param $text
+ * The message string to display to the user.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ */
+function ajax_command_alert($text) {
+ return array(
+ 'command' => 'alert',
+ 'text' => $text,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'insert' command using the method in #ajax['method'].
+ *
+ * This command instructs the client to insert the given HTML using whichever
+ * jQuery DOM manipulation method has been specified in the #ajax['method']
+ * variable of the element that triggered the request.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.insert()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $html
+ * The data to use with the jQuery method.
+ * @param $settings
+ * An optional array of settings that will be used for this command only.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ */
+function ajax_command_insert($selector, $html, $settings = NULL) {
+ return array(
+ 'command' => 'insert',
+ 'method' => NULL,
+ 'selector' => $selector,
+ 'data' => $html,
+ 'settings' => $settings,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'insert/replaceWith' command.
+ *
+ * The 'insert/replaceWith' command instructs the client to use jQuery's
+ * replaceWith() method to replace each element matched matched by the given
+ * selector with the given HTML.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.insert()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $html
+ * The data to use with the jQuery replaceWith() method.
+ * @param $settings
+ * An optional array of settings that will be used for this command only.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * See
+ * @link http://docs.jquery.com/Manipulation/replaceWith#content jQuery replaceWith command @endlink
+ */
+function ajax_command_replace($selector, $html, $settings = NULL) {
+ return array(
+ 'command' => 'insert',
+ 'method' => 'replaceWith',
+ 'selector' => $selector,
+ 'data' => $html,
+ 'settings' => $settings,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'insert/html' command.
+ *
+ * The 'insert/html' command instructs the client to use jQuery's html()
+ * method to set the HTML content of each element matched by the given
+ * selector while leaving the outer tags intact.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.insert()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $html
+ * The data to use with the jQuery html() method.
+ * @param $settings
+ * An optional array of settings that will be used for this command only.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/Attributes/html#val
+ */
+function ajax_command_html($selector, $html, $settings = NULL) {
+ return array(
+ 'command' => 'insert',
+ 'method' => 'html',
+ 'selector' => $selector,
+ 'data' => $html,
+ 'settings' => $settings,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'insert/prepend' command.
+ *
+ * The 'insert/prepend' command instructs the client to use jQuery's prepend()
+ * method to prepend the given HTML content to the inside each element matched
+ * by the given selector.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.insert()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $html
+ * The data to use with the jQuery prepend() method.
+ * @param $settings
+ * An optional array of settings that will be used for this command only.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/Manipulation/prepend#content
+ */
+function ajax_command_prepend($selector, $html, $settings = NULL) {
+ return array(
+ 'command' => 'insert',
+ 'method' => 'prepend',
+ 'selector' => $selector,
+ 'data' => $html,
+ 'settings' => $settings,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'insert/append' command.
+ *
+ * The 'insert/append' command instructs the client to use jQuery's append()
+ * method to append the given HTML content to the inside of each element matched
+ * by the given selector.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.insert()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $html
+ * The data to use with the jQuery append() method.
+ * @param $settings
+ * An optional array of settings that will be used for this command only.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/Manipulation/append#content
+ */
+function ajax_command_append($selector, $html, $settings = NULL) {
+ return array(
+ 'command' => 'insert',
+ 'method' => 'append',
+ 'selector' => $selector,
+ 'data' => $html,
+ 'settings' => $settings,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'insert/after' command.
+ *
+ * The 'insert/after' command instructs the client to use jQuery's after()
+ * method to insert the given HTML content after each element matched by
+ * the given selector.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.insert()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $html
+ * The data to use with the jQuery after() method.
+ * @param $settings
+ * An optional array of settings that will be used for this command only.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/Manipulation/after#content
+ */
+function ajax_command_after($selector, $html, $settings = NULL) {
+ return array(
+ 'command' => 'insert',
+ 'method' => 'after',
+ 'selector' => $selector,
+ 'data' => $html,
+ 'settings' => $settings,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'insert/before' command.
+ *
+ * The 'insert/before' command instructs the client to use jQuery's before()
+ * method to insert the given HTML content before each of elements matched by
+ * the given selector.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.insert()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $html
+ * The data to use with the jQuery before() method.
+ * @param $settings
+ * An optional array of settings that will be used for this command only.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/Manipulation/before#content
+ */
+function ajax_command_before($selector, $html, $settings = NULL) {
+ return array(
+ 'command' => 'insert',
+ 'method' => 'before',
+ 'selector' => $selector,
+ 'data' => $html,
+ 'settings' => $settings,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'remove' command.
+ *
+ * The 'remove' command instructs the client to use jQuery's remove() method
+ * to remove each of elements matched by the given selector, and everything
+ * within them.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.remove()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/Manipulation/remove#expr
+ */
+function ajax_command_remove($selector) {
+ return array(
+ 'command' => 'remove',
+ 'selector' => $selector,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'changed' command.
+ *
+ * This command instructs the client to mark each of the elements matched by the
+ * given selector as 'ajax-changed'.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.changed()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $asterisk
+ * An optional CSS selector which must be inside $selector. If specified,
+ * an asterisk will be appended to the HTML inside the $asterisk selector.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ */
+function ajax_command_changed($selector, $asterisk = '') {
+ return array(
+ 'command' => 'changed',
+ 'selector' => $selector,
+ 'asterisk' => $asterisk,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'css' command.
+ *
+ * The 'css' command will instruct the client to use the jQuery css() method
+ * to apply the CSS arguments to elements matched by the given selector.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.css()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $argument
+ * An array of key/value pairs to set in the CSS for the selector.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/CSS/css#properties
+ */
+function ajax_command_css($selector, $argument) {
+ return array(
+ 'command' => 'css',
+ 'selector' => $selector,
+ 'argument' => $argument,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'settings' command.
+ *
+ * The 'settings' command instructs the client either to use the given array as
+ * the settings for ajax-loaded content or to extend Drupal.settings with the
+ * given array, depending on the value of the $merge parameter.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.settings()
+ * defined in misc/ajax.js.
+ *
+ * @param $argument
+ * An array of key/value pairs to add to the settings. This will be utilized
+ * for all commands after this if they do not include their own settings
+ * array.
+ * @param $merge
+ * Whether or not the passed settings in $argument should be merged into the
+ * global Drupal.settings on the page. By default (FALSE), the settings that
+ * are passed to Drupal.attachBehaviors will not include the global
+ * Drupal.settings.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ */
+function ajax_command_settings($argument, $merge = FALSE) {
+ return array(
+ 'command' => 'settings',
+ 'settings' => $argument,
+ 'merge' => $merge,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'data' command.
+ *
+ * The 'data' command instructs the client to attach the name=value pair of
+ * data to the selector via jQuery's data cache.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.data()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $name
+ * The name or key (in the key value pair) of the data attached to this
+ * selector.
+ * @param $value
+ * The value of the data. Not just limited to strings can be any format.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ *
+ * @see http://docs.jquery.com/Core/data#namevalue
+ */
+function ajax_command_data($selector, $name, $value) {
+ return array(
+ 'command' => 'data',
+ 'selector' => $selector,
+ 'name' => $name,
+ 'value' => $value,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'invoke' command.
+ *
+ * The 'invoke' command will instruct the client to invoke the given jQuery
+ * method with the supplied arguments on the elements matched by the given
+ * selector. Intended for simple jQuery commands, such as attr(), addClass(),
+ * removeClass(), toggleClass(), etc.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.invoke()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string. If the command is a response to a request from
+ * an #ajax form element then this value can be NULL.
+ * @param $method
+ * The jQuery method to invoke.
+ * @param $arguments
+ * (optional) A list of arguments to the jQuery $method, if any.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ */
+function ajax_command_invoke($selector, $method, array $arguments = array()) {
+ return array(
+ 'command' => 'invoke',
+ 'selector' => $selector,
+ 'method' => $method,
+ 'arguments' => $arguments,
+ );
+}
+
+/**
+ * Creates a Drupal Ajax 'restripe' command.
+ *
+ * The 'restripe' command instructs the client to restripe a table. This is
+ * usually used after a table has been modified by a replace or append command.
+ *
+ * This command is implemented by Drupal.ajax.prototype.commands.restripe()
+ * defined in misc/ajax.js.
+ *
+ * @param $selector
+ * A jQuery selector string.
+ *
+ * @return
+ * An array suitable for use with the ajax_render() function.
+ */
+function ajax_command_restripe($selector) {
+ return array(
+ 'command' => 'restripe',
+ 'selector' => $selector,
+ );
+}
diff --git a/kolab.org/www/drupal-7.26/includes/archiver.inc b/kolab.org/www/drupal-7.26/includes/archiver.inc
new file mode 100644
index 0000000..3ce1173
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/archiver.inc
@@ -0,0 +1,68 @@
+<?php
+
+/**
+ * @file
+ * Shared classes and interfaces for the archiver system.
+ */
+
+/**
+ * Defines the common interface for all Archiver classes.
+ */
+interface ArchiverInterface {
+
+ /**
+ * Constructs a new archiver instance.
+ *
+ * @param $file_path
+ * The full system path of the archive to manipulate. Only local files
+ * are supported. If the file does not yet exist, it will be created if
+ * appropriate.
+ */
+ public function __construct($file_path);
+
+ /**
+ * Adds the specified file or directory to the archive.
+ *
+ * @param $file_path
+ * The full system path of the file or directory to add. Only local files
+ * and directories are supported.
+ *
+ * @return ArchiverInterface
+ * The called object.
+ */
+ public function add($file_path);
+
+ /**
+ * Removes the specified file from the archive.
+ *
+ * @param $path
+ * The file name relative to the root of the archive to remove.
+ *
+ * @return ArchiverInterface
+ * The called object.
+ */
+ public function remove($path);
+
+ /**
+ * Extracts multiple files in the archive to the specified path.
+ *
+ * @param $path
+ * A full system path of the directory to which to extract files.
+ * @param $files
+ * Optionally specify a list of files to be extracted. Files are
+ * relative to the root of the archive. If not specified, all files
+ * in the archive will be extracted.
+ *
+ * @return ArchiverInterface
+ * The called object.
+ */
+ public function extract($path, array $files = array());
+
+ /**
+ * Lists all files in the archive.
+ *
+ * @return
+ * An array of file names relative to the root of the archive.
+ */
+ public function listContents();
+}
diff --git a/kolab.org/www/drupal-7.26/includes/authorize.inc b/kolab.org/www/drupal-7.26/includes/authorize.inc
new file mode 100644
index 0000000..8360e13
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/authorize.inc
@@ -0,0 +1,334 @@
+<?php
+
+/**
+ * @file
+ * Helper functions and form handlers used for the authorize.php script.
+ */
+
+/**
+ * Form constructor for the file transfer authorization form.
+ *
+ * Allows the user to choose a FileTransfer type and supply credentials.
+ *
+ * @see authorize_filetransfer_form_validate()
+ * @see authorize_filetransfer_form_submit()
+ * @ingroup forms
+ */
+function authorize_filetransfer_form($form, &$form_state) {
+ global $base_url, $is_https;
+ $form = array();
+
+ // If possible, we want to post this form securely via HTTPS.
+ $form['#https'] = TRUE;
+
+ // CSS we depend on lives in modules/system/maintenance.css, which is loaded
+ // via the default maintenance theme.
+ $form['#attached']['js'][] = $base_url . '/misc/authorize.js';
+
+ // Get all the available ways to transfer files.
+ if (empty($_SESSION['authorize_filetransfer_info'])) {
+ drupal_set_message(t('Unable to continue, no available methods of file transfer'), 'error');
+ return array();
+ }
+ $available_backends = $_SESSION['authorize_filetransfer_info'];
+
+ if (!$is_https) {
+ $form['information']['https_warning'] = array(
+ '#prefix' => '<div class="messages error">',
+ '#markup' => t('WARNING: You are not using an encrypted connection, so your password will be sent in plain text. <a href="@https-link">Learn more</a>.', array('@https-link' => 'http://drupal.org/https-information')),
+ '#suffix' => '</div>',
+ );
+ }
+
+ // Decide on a default backend.
+ if (isset($form_state['values']['connection_settings']['authorize_filetransfer_default'])) {
+ $authorize_filetransfer_default = $form_state['values']['connection_settings']['authorize_filetransfer_default'];
+ }
+ elseif ($authorize_filetransfer_default = variable_get('authorize_filetransfer_default', NULL));
+ else {
+ $authorize_filetransfer_default = key($available_backends);
+ }
+
+ $form['information']['main_header'] = array(
+ '#prefix' => '<h3>',
+ '#markup' => t('To continue, provide your server connection details'),
+ '#suffix' => '</h3>',
+ );
+
+ $form['connection_settings']['#tree'] = TRUE;
+ $form['connection_settings']['authorize_filetransfer_default'] = array(
+ '#type' => 'select',
+ '#title' => t('Connection method'),
+ '#default_value' => $authorize_filetransfer_default,
+ '#weight' => -10,
+ );
+
+ /*
+ * Here we create two submit buttons. For a JS enabled client, they will
+ * only ever see submit_process. However, if a client doesn't have JS
+ * enabled, they will see submit_connection on the first form (when picking
+ * what filetransfer type to use, and submit_process on the second one (which
+ * leads to the actual operation).
+ */
+ $form['submit_connection'] = array(
+ '#prefix' => "<br style='clear:both'/>",
+ '#name' => 'enter_connection_settings',
+ '#type' => 'submit',
+ '#value' => t('Enter connection settings'),
+ '#weight' => 100,
+ );
+
+ $form['submit_process'] = array(
+ '#name' => 'process_updates',
+ '#type' => 'submit',
+ '#value' => t('Continue'),
+ '#weight' => 100,
+ '#attributes' => array('style' => 'display:none'),
+ );
+
+ // Build a container for each connection type.
+ foreach ($available_backends as $name => $backend) {
+ $form['connection_settings']['authorize_filetransfer_default']['#options'][$name] = $backend['title'];
+ $form['connection_settings'][$name] = array(
+ '#type' => 'container',
+ '#attributes' => array('class' => array("filetransfer-$name", 'filetransfer')),
+ );
+ // We can't use #prefix on the container itself since then the header won't
+ // be hidden and shown when the containers are being manipulated via JS.
+ $form['connection_settings'][$name]['header'] = array(
+ '#markup' => '<h4>' . t('@backend connection settings', array('@backend' => $backend['title'])) . '</h4>',
+ );
+
+ $form['connection_settings'][$name] += _authorize_filetransfer_connection_settings($name);
+
+ // Start non-JS code.
+ if (isset($form_state['values']['connection_settings']['authorize_filetransfer_default']) && $form_state['values']['connection_settings']['authorize_filetransfer_default'] == $name) {
+
+ // If the user switches from JS to non-JS, Drupal (and Batch API) will
+ // barf. This is a known bug: http://drupal.org/node/229825.
+ setcookie('has_js', '', time() - 3600, '/');
+ unset($_COOKIE['has_js']);
+
+ // Change the submit button to the submit_process one.
+ $form['submit_process']['#attributes'] = array();
+ unset($form['submit_connection']);
+
+ // Activate the proper filetransfer settings form.
+ $form['connection_settings'][$name]['#attributes']['style'] = 'display:block';
+ // Disable the select box.
+ $form['connection_settings']['authorize_filetransfer_default']['#disabled'] = TRUE;
+
+ // Create a button for changing the type of connection.
+ $form['connection_settings']['change_connection_type'] = array(
+ '#name' => 'change_connection_type',
+ '#type' => 'submit',
+ '#value' => t('Change connection type'),
+ '#weight' => -5,
+ '#attributes' => array('class' => array('filetransfer-change-connection-type')),
+ );
+ }
+ // End non-JS code.
+ }
+ return $form;
+}
+
+/**
+ * Generates the Form API array for a given connection backend's settings.
+ *
+ * @param $backend
+ * The name of the backend (e.g. 'ftp', 'ssh', etc).
+ *
+ * @return
+ * Form API array of connection settings for the given backend.
+ *
+ * @see hook_filetransfer_backends()
+ */
+function _authorize_filetransfer_connection_settings($backend) {
+ $defaults = variable_get('authorize_filetransfer_connection_settings_' . $backend, array());
+ $form = array();
+
+ // Create an instance of the file transfer class to get its settings form.
+ $filetransfer = authorize_get_filetransfer($backend);
+ if ($filetransfer) {
+ $form = $filetransfer->getSettingsForm();
+ }
+ // Fill in the defaults based on the saved settings, if any.
+ _authorize_filetransfer_connection_settings_set_defaults($form, NULL, $defaults);
+ return $form;
+}
+
+/**
+ * Sets the default settings on a file transfer connection form recursively.
+ *
+ * The default settings for the file transfer connection forms are saved in
+ * the database. The settings are stored as a nested array in the case of a
+ * settings form that has fieldsets or otherwise uses a nested structure.
+ * Therefore, to properly add defaults, we need to walk through all the
+ * children form elements and process those defaults recursively.
+ *
+ * @param $element
+ * Reference to the Form API form element we're operating on.
+ * @param $key
+ * The key for our current form element, if any.
+ * @param array $defaults
+ * The default settings for the file transfer backend we're operating on.
+ */
+function _authorize_filetransfer_connection_settings_set_defaults(&$element, $key, array $defaults) {
+ // If we're operating on a form element which isn't a fieldset, and we have
+ // a default setting saved, stash it in #default_value.
+ if (!empty($key) && isset($defaults[$key]) && isset($element['#type']) && $element['#type'] != 'fieldset') {
+ $element['#default_value'] = $defaults[$key];
+ }
+ // Now, we walk through all the child elements, and recursively invoke
+ // ourself on each one. Since the $defaults settings array can be nested
+ // (because of #tree, any values inside fieldsets will be nested), if
+ // there's a subarray of settings for the form key we're currently
+ // processing, pass in that subarray to the recursive call. Otherwise, just
+ // pass on the whole $defaults array.
+ foreach (element_children($element) as $child_key) {
+ _authorize_filetransfer_connection_settings_set_defaults($element[$child_key], $child_key, ((isset($defaults[$key]) && is_array($defaults[$key])) ? $defaults[$key] : $defaults));
+ }
+}
+
+/**
+ * Form validation handler for authorize_filetransfer_form().
+ *
+ * @see authorize_filetransfer_form()
+ * @see authorize_filetransfer_submit()
+ */
+function authorize_filetransfer_form_validate($form, &$form_state) {
+ // Only validate the form if we have collected all of the user input and are
+ // ready to proceed with updating or installing.
+ if ($form_state['triggering_element']['#name'] != 'process_updates') {
+ return;
+ }
+
+ if (isset($form_state['values']['connection_settings'])) {
+ $backend = $form_state['values']['connection_settings']['authorize_filetransfer_default'];
+ $filetransfer = authorize_get_filetransfer($backend, $form_state['values']['connection_settings'][$backend]);
+ try {
+ if (!$filetransfer) {
+ throw new Exception(t('Error, this type of connection protocol (%backend) does not exist.', array('%backend' => $backend)));
+ }
+ $filetransfer->connect();
+ }
+ catch (Exception $e) {
+ // The format of this error message is similar to that used on the
+ // database connection form in the installer.
+ form_set_error('connection_settings', t('Failed to connect to the server. The server reports the following message: !message For more help installing or updating code on your server, see the <a href="@handbook_url">handbook</a>.', array(
+ '!message' => '<p class="error">' . $e->getMessage() . '</p>',
+ '@handbook_url' => 'http://drupal.org/documentation/install/modules-themes',
+ )));
+ }
+ }
+}
+
+/**
+ * Form submission handler for authorize_filetransfer_form().
+ *
+ * @see authorize_filetransfer_form()
+ * @see authorize_filetransfer_validate()
+ */
+function authorize_filetransfer_form_submit($form, &$form_state) {
+ global $base_url;
+ switch ($form_state['triggering_element']['#name']) {
+ case 'process_updates':
+
+ // Save the connection settings to the DB.
+ $filetransfer_backend = $form_state['values']['connection_settings']['authorize_filetransfer_default'];
+
+ // If the database is available then try to save our settings. We have
+ // to make sure it is available since this code could potentially (will
+ // likely) be called during the installation process, before the
+ // database is set up.
+ try {
+ $connection_settings = array();
+ foreach ($form_state['values']['connection_settings'][$filetransfer_backend] as $key => $value) {
+ // We do *not* want to store passwords in the database, unless the
+ // backend explicitly says so via the magic #filetransfer_save form
+ // property. Otherwise, we store everything that's not explicitly
+ // marked with #filetransfer_save set to FALSE.
+ if (!isset($form['connection_settings'][$filetransfer_backend][$key]['#filetransfer_save'])) {
+ if ($form['connection_settings'][$filetransfer_backend][$key]['#type'] != 'password') {
+ $connection_settings[$key] = $value;
+ }
+ }
+ // The attribute is defined, so only save if set to TRUE.
+ elseif ($form['connection_settings'][$filetransfer_backend][$key]['#filetransfer_save']) {
+ $connection_settings[$key] = $value;
+ }
+ }
+ // Set this one as the default authorize method.
+ variable_set('authorize_filetransfer_default', $filetransfer_backend);
+ // Save the connection settings minus the password.
+ variable_set('authorize_filetransfer_connection_settings_' . $filetransfer_backend, $connection_settings);
+
+ $filetransfer = authorize_get_filetransfer($filetransfer_backend, $form_state['values']['connection_settings'][$filetransfer_backend]);
+
+ // Now run the operation.
+ authorize_run_operation($filetransfer);
+ }
+ catch (Exception $e) {
+ // If there is no database available, we don't care and just skip
+ // this part entirely.
+ }
+
+ break;
+
+ case 'enter_connection_settings':
+ $form_state['rebuild'] = TRUE;
+ break;
+
+ case 'change_connection_type':
+ $form_state['rebuild'] = TRUE;
+ unset($form_state['values']['connection_settings']['authorize_filetransfer_default']);
+ break;
+ }
+}
+
+/**
+ * Runs the operation specified in $_SESSION['authorize_operation'].
+ *
+ * @param $filetransfer
+ * The FileTransfer object to use for running the operation.
+ */
+function authorize_run_operation($filetransfer) {
+ $operation = $_SESSION['authorize_operation'];
+ unset($_SESSION['authorize_operation']);
+
+ if (!empty($operation['page_title'])) {
+ drupal_set_title($operation['page_title']);
+ }
+
+ require_once DRUPAL_ROOT . '/' . $operation['file'];
+ call_user_func_array($operation['callback'], array_merge(array($filetransfer), $operation['arguments']));
+}
+
+/**
+ * Gets a FileTransfer class for a specific transfer method and settings.
+ *
+ * @param $backend
+ * The FileTransfer backend to get the class for.
+ * @param $settings
+ * Array of settings for the FileTransfer.
+ *
+ * @return
+ * An instantiated FileTransfer object for the requested method and settings,
+ * or FALSE if there was an error finding or instantiating it.
+ */
+function authorize_get_filetransfer($backend, $settings = array()) {
+ $filetransfer = FALSE;
+ if (!empty($_SESSION['authorize_filetransfer_info'][$backend])) {
+ $backend_info = $_SESSION['authorize_filetransfer_info'][$backend];
+ if (!empty($backend_info['file'])) {
+ $file = $backend_info['file path'] . '/' . $backend_info['file'];
+ require_once $file;
+ }
+ if (class_exists($backend_info['class'])) {
+ // PHP 5.2 doesn't support $class::factory() syntax, so we have to
+ // use call_user_func_array() until we can require PHP 5.3.
+ $filetransfer = call_user_func_array(array($backend_info['class'], 'factory'), array(DRUPAL_ROOT, $settings));
+ }
+ }
+ return $filetransfer;
+}
diff --git a/kolab.org/www/drupal-7.26/includes/batch.inc b/kolab.org/www/drupal-7.26/includes/batch.inc
new file mode 100644
index 0000000..061acd4
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/batch.inc
@@ -0,0 +1,539 @@
+<?php
+
+/**
+ * @file
+ * Batch processing API for processes to run in multiple HTTP requests.
+ *
+ * Note that batches are usually invoked by form submissions, which is
+ * why the core interaction functions of the batch processing API live in
+ * form.inc.
+ *
+ * @see form.inc
+ * @see batch_set()
+ * @see batch_process()
+ * @see batch_get()
+ */
+
+/**
+ * Loads a batch from the database.
+ *
+ * @param $id
+ * The ID of the batch to load. When a progressive batch is being processed,
+ * the relevant ID is found in $_REQUEST['id'].
+ *
+ * @return
+ * An array representing the batch, or FALSE if no batch was found.
+ */
+function batch_load($id) {
+ $batch = db_query("SELECT batch FROM {batch} WHERE bid = :bid AND token = :token", array(
+ ':bid' => $id,
+ ':token' => drupal_get_token($id),
+ ))->fetchField();
+ if ($batch) {
+ return unserialize($batch);
+ }
+ return FALSE;
+}
+
+/**
+ * Renders the batch processing page based on the current state of the batch.
+ *
+ * @see _batch_shutdown()
+ */
+function _batch_page() {
+ $batch = &batch_get();
+
+ if (!isset($_REQUEST['id'])) {
+ return FALSE;
+ }
+
+ // Retrieve the current state of the batch.
+ if (!$batch) {
+ $batch = batch_load($_REQUEST['id']);
+ if (!$batch) {
+ drupal_set_message(t('No active batch.'), 'error');
+ drupal_goto();
+ }
+ }
+
+ // Register database update for the end of processing.
+ drupal_register_shutdown_function('_batch_shutdown');
+
+ // Add batch-specific CSS.
+ foreach ($batch['sets'] as $batch_set) {
+ if (isset($batch_set['css'])) {
+ foreach ($batch_set['css'] as $css) {
+ drupal_add_css($css);
+ }
+ }
+ }
+
+ $op = isset($_REQUEST['op']) ? $_REQUEST['op'] : '';
+ $output = NULL;
+ switch ($op) {
+ case 'start':
+ $output = _batch_start();
+ break;
+
+ case 'do':
+ // JavaScript-based progress page callback.
+ _batch_do();
+ break;
+
+ case 'do_nojs':
+ // Non-JavaScript-based progress page.
+ $output = _batch_progress_page_nojs();
+ break;
+
+ case 'finished':
+ $output = _batch_finished();
+ break;
+ }
+
+ return $output;
+}
+
+/**
+ * Initializes the batch processing.
+ *
+ * JavaScript-enabled clients are identified by the 'has_js' cookie set in
+ * drupal.js. If no JavaScript-enabled page has been visited during the current
+ * user's browser session, the non-JavaScript version is returned.
+ */
+function _batch_start() {
+ if (isset($_COOKIE['has_js']) && $_COOKIE['has_js']) {
+ return _batch_progress_page_js();
+ }
+ else {
+ return _batch_progress_page_nojs();
+ }
+}
+
+/**
+ * Outputs a batch processing page with JavaScript support.
+ *
+ * This initializes the batch and error messages. Note that in JavaScript-based
+ * processing, the batch processing page is displayed only once and updated via
+ * AHAH requests, so only the first batch set gets to define the page title.
+ * Titles specified by subsequent batch sets are not displayed.
+ *
+ * @see batch_set()
+ * @see _batch_do()
+ */
+function _batch_progress_page_js() {
+ $batch = batch_get();
+
+ $current_set = _batch_current_set();
+ drupal_set_title($current_set['title'], PASS_THROUGH);
+
+ // Merge required query parameters for batch processing into those provided by
+ // batch_set() or hook_batch_alter().
+ $batch['url_options']['query']['id'] = $batch['id'];
+
+ $js_setting = array(
+ 'batch' => array(
+ 'errorMessage' => $current_set['error_message'] . '<br />' . $batch['error_message'],
+ 'initMessage' => $current_set['init_message'],
+ 'uri' => url($batch['url'], $batch['url_options']),
+ ),
+ );
+ drupal_add_js($js_setting, 'setting');
+ drupal_add_library('system', 'drupal.batch');
+
+ return '<div id="progress"></div>';
+}
+
+/**
+ * Does one execution pass with JavaScript and returns progress to the browser.
+ *
+ * @see _batch_progress_page_js()
+ * @see _batch_process()
+ */
+function _batch_do() {
+ // HTTP POST required.
+ if ($_SERVER['REQUEST_METHOD'] != 'POST') {
+ drupal_set_message(t('HTTP POST is required.'), 'error');
+ drupal_set_title(t('Error'));
+ return '';
+ }
+
+ // Perform actual processing.
+ list($percentage, $message) = _batch_process();
+
+ drupal_json_output(array('status' => TRUE, 'percentage' => $percentage, 'message' => $message));
+}
+
+/**
+ * Outputs a batch processing page without JavaScript support.
+ *
+ * @see _batch_process()
+ */
+function _batch_progress_page_nojs() {
+ $batch = &batch_get();
+
+ $current_set = _batch_current_set();
+ drupal_set_title($current_set['title'], PASS_THROUGH);
+
+ $new_op = 'do_nojs';
+
+ if (!isset($batch['running'])) {
+ // This is the first page so we return some output immediately.
+ $percentage = 0;
+ $message = $current_set['init_message'];
+ $batch['running'] = TRUE;
+ }
+ else {
+ // This is one of the later requests; do some processing first.
+
+ // Error handling: if PHP dies due to a fatal error (e.g. a nonexistent
+ // function), it will output whatever is in the output buffer, followed by
+ // the error message.
+ ob_start();
+ $fallback = $current_set['error_message'] . '<br />' . $batch['error_message'];
+ $fallback = theme('maintenance_page', array('content' => $fallback, 'show_messages' => FALSE));
+
+ // We strip the end of the page using a marker in the template, so any
+ // additional HTML output by PHP shows up inside the page rather than below
+ // it. While this causes invalid HTML, the same would be true if we didn't,
+ // as content is not allowed to appear after </html> anyway.
+ list($fallback) = explode('<!--partial-->', $fallback);
+ print $fallback;
+
+ // Perform actual processing.
+ list($percentage, $message) = _batch_process($batch);
+ if ($percentage == 100) {
+ $new_op = 'finished';
+ }
+
+ // PHP did not die; remove the fallback output.
+ ob_end_clean();
+ }
+
+ // Merge required query parameters for batch processing into those provided by
+ // batch_set() or hook_batch_alter().
+ $batch['url_options']['query']['id'] = $batch['id'];
+ $batch['url_options']['query']['op'] = $new_op;
+
+ $url = url($batch['url'], $batch['url_options']);
+ $element = array(
+ '#tag' => 'meta',
+ '#attributes' => array(
+ 'http-equiv' => 'Refresh',
+ 'content' => '0; URL=' . $url,
+ ),
+ );
+ drupal_add_html_head($element, 'batch_progress_meta_refresh');
+
+ return theme('progress_bar', array('percent' => $percentage, 'message' => $message));
+}
+
+/**
+ * Processes sets in a batch.
+ *
+ * If the batch was marked for progressive execution (default), this executes as
+ * many operations in batch sets until an execution time of 1 second has been
+ * exceeded. It will continue with the next operation of the same batch set in
+ * the next request.
+ *
+ * @return
+ * An array containing a completion value (in percent) and a status message.
+ */
+function _batch_process() {
+ $batch = &batch_get();
+ $current_set = &_batch_current_set();
+ // Indicate that this batch set needs to be initialized.
+ $set_changed = TRUE;
+
+ // If this batch was marked for progressive execution (e.g. forms submitted by
+ // drupal_form_submit()), initialize a timer to determine whether we need to
+ // proceed with the same batch phase when a processing time of 1 second has
+ // been exceeded.
+ if ($batch['progressive']) {
+ timer_start('batch_processing');
+ }
+
+ if (empty($current_set['start'])) {
+ $current_set['start'] = microtime(TRUE);
+ }
+
+ $queue = _batch_queue($current_set);
+
+ while (!$current_set['success']) {
+ // If this is the first time we iterate this batch set in the current
+ // request, we check if it requires an additional file for functions
+ // definitions.
+ if ($set_changed && isset($current_set['file']) && is_file($current_set['file'])) {
+ include_once DRUPAL_ROOT . '/' . $current_set['file'];
+ }
+
+ $task_message = '';
+ // Assume a single pass operation and set the completion level to 1 by
+ // default.
+ $finished = 1;
+
+ if ($item = $queue->claimItem()) {
+ list($function, $args) = $item->data;
+
+ // Build the 'context' array and execute the function call.
+ $batch_context = array(
+ 'sandbox' => &$current_set['sandbox'],
+ 'results' => &$current_set['results'],
+ 'finished' => &$finished,
+ 'message' => &$task_message,
+ );
+ call_user_func_array($function, array_merge($args, array(&$batch_context)));
+
+ if ($finished >= 1) {
+ // Make sure this step is not counted twice when computing $current.
+ $finished = 0;
+ // Remove the processed operation and clear the sandbox.
+ $queue->deleteItem($item);
+ $current_set['count']--;
+ $current_set['sandbox'] = array();
+ }
+ }
+
+ // When all operations in the current batch set are completed, browse
+ // through the remaining sets, marking them 'successfully processed'
+ // along the way, until we find a set that contains operations.
+ // _batch_next_set() executes form submit handlers stored in 'control'
+ // sets (see form_execute_handlers()), which can in turn add new sets to
+ // the batch.
+ $set_changed = FALSE;
+ $old_set = $current_set;
+ while (empty($current_set['count']) && ($current_set['success'] = TRUE) && _batch_next_set()) {
+ $current_set = &_batch_current_set();
+ $current_set['start'] = microtime(TRUE);
+ $set_changed = TRUE;
+ }
+
+ // At this point, either $current_set contains operations that need to be
+ // processed or all sets have been completed.
+ $queue = _batch_queue($current_set);
+
+ // If we are in progressive mode, break processing after 1 second.
+ if ($batch['progressive'] && timer_read('batch_processing') > 1000) {
+ // Record elapsed wall clock time.
+ $current_set['elapsed'] = round((microtime(TRUE) - $current_set['start']) * 1000, 2);
+ break;
+ }
+ }
+
+ if ($batch['progressive']) {
+ // Gather progress information.
+
+ // Reporting 100% progress will cause the whole batch to be considered
+ // processed. If processing was paused right after moving to a new set,
+ // we have to use the info from the new (unprocessed) set.
+ if ($set_changed && isset($current_set['queue'])) {
+ // Processing will continue with a fresh batch set.
+ $remaining = $current_set['count'];
+ $total = $current_set['total'];
+ $progress_message = $current_set['init_message'];
+ $task_message = '';
+ }
+ else {
+ // Processing will continue with the current batch set.
+ $remaining = $old_set['count'];
+ $total = $old_set['total'];
+ $progress_message = $old_set['progress_message'];
+ }
+
+ // Total progress is the number of operations that have fully run plus the
+ // completion level of the current operation.
+ $current = $total - $remaining + $finished;
+ $percentage = _batch_api_percentage($total, $current);
+ $elapsed = isset($current_set['elapsed']) ? $current_set['elapsed'] : 0;
+ $values = array(
+ '@remaining' => $remaining,
+ '@total' => $total,
+ '@current' => floor($current),
+ '@percentage' => $percentage,
+ '@elapsed' => format_interval($elapsed / 1000),
+ // If possible, estimate remaining processing time.
+ '@estimate' => ($current > 0) ? format_interval(($elapsed * ($total - $current) / $current) / 1000) : '-',
+ );
+ $message = strtr($progress_message, $values);
+ if (!empty($message)) {
+ $message .= '<br />';
+ }
+ if (!empty($task_message)) {
+ $message .= $task_message;
+ }
+
+ return array($percentage, $message);
+ }
+ else {
+ // If we are not in progressive mode, the entire batch has been processed.
+ return _batch_finished();
+ }
+}
+
+/**
+ * Formats the percent completion for a batch set.
+ *
+ * @param $total
+ * The total number of operations.
+ * @param $current
+ * The number of the current operation. This may be a floating point number
+ * rather than an integer in the case of a multi-step operation that is not
+ * yet complete; in that case, the fractional part of $current represents the
+ * fraction of the operation that has been completed.
+ *
+ * @return
+ * The properly formatted percentage, as a string. We output percentages
+ * using the correct number of decimal places so that we never print "100%"
+ * until we are finished, but we also never print more decimal places than
+ * are meaningful.
+ *
+ * @see _batch_process()
+ */
+function _batch_api_percentage($total, $current) {
+ if (!$total || $total == $current) {
+ // If $total doesn't evaluate as true or is equal to the current set, then
+ // we're finished, and we can return "100".
+ $percentage = "100";
+ }
+ else {
+ // We add a new digit at 200, 2000, etc. (since, for example, 199/200
+ // would round up to 100% if we didn't).
+ $decimal_places = max(0, floor(log10($total / 2.0)) - 1);
+ do {
+ // Calculate the percentage to the specified number of decimal places.
+ $percentage = sprintf('%01.' . $decimal_places . 'f', round($current / $total * 100, $decimal_places));
+ // When $current is an integer, the above calculation will always be
+ // correct. However, if $current is a floating point number (in the case
+ // of a multi-step batch operation that is not yet complete), $percentage
+ // may be erroneously rounded up to 100%. To prevent that, we add one
+ // more decimal place and try again.
+ $decimal_places++;
+ } while ($percentage == '100');
+ }
+ return $percentage;
+}
+
+/**
+ * Returns the batch set being currently processed.
+ */
+function &_batch_current_set() {
+ $batch = &batch_get();
+ return $batch['sets'][$batch['current_set']];
+}
+
+/**
+ * Retrieves the next set in a batch.
+ *
+ * If there is a subsequent set in this batch, assign it as the new set to
+ * process and execute its form submit handler (if defined), which may add
+ * further sets to this batch.
+ *
+ * @return
+ * TRUE if a subsequent set was found in the batch.
+ */
+function _batch_next_set() {
+ $batch = &batch_get();
+ if (isset($batch['sets'][$batch['current_set'] + 1])) {
+ $batch['current_set']++;
+ $current_set = &_batch_current_set();
+ if (isset($current_set['form_submit']) && ($function = $current_set['form_submit']) && function_exists($function)) {
+ // We use our stored copies of $form and $form_state to account for
+ // possible alterations by previous form submit handlers.
+ $function($batch['form_state']['complete form'], $batch['form_state']);
+ }
+ return TRUE;
+ }
+}
+
+/**
+ * Ends the batch processing.
+ *
+ * Call the 'finished' callback of each batch set to allow custom handling of
+ * the results and resolve page redirection.
+ */
+function _batch_finished() {
+ $batch = &batch_get();
+
+ // Execute the 'finished' callbacks for each batch set, if defined.
+ foreach ($batch['sets'] as $batch_set) {
+ if (isset($batch_set['finished'])) {
+ // Check if the set requires an additional file for function definitions.
+ if (isset($batch_set['file']) && is_file($batch_set['file'])) {
+ include_once DRUPAL_ROOT . '/' . $batch_set['file'];
+ }
+ if (function_exists($batch_set['finished'])) {
+ $queue = _batch_queue($batch_set);
+ $operations = $queue->getAllItems();
+ $batch_set['finished']($batch_set['success'], $batch_set['results'], $operations, format_interval($batch_set['elapsed'] / 1000));
+ }
+ }
+ }
+
+ // Clean up the batch table and unset the static $batch variable.
+ if ($batch['progressive']) {
+ db_delete('batch')
+ ->condition('bid', $batch['id'])
+ ->execute();
+ foreach ($batch['sets'] as $batch_set) {
+ if ($queue = _batch_queue($batch_set)) {
+ $queue->deleteQueue();
+ }
+ }
+ }
+ $_batch = $batch;
+ $batch = NULL;
+
+ // Clean-up the session. Not needed for CLI updates.
+ if (isset($_SESSION)) {
+ unset($_SESSION['batches'][$batch['id']]);
+ if (empty($_SESSION['batches'])) {
+ unset($_SESSION['batches']);
+ }
+ }
+
+ // Redirect if needed.
+ if ($_batch['progressive']) {
+ // Revert the 'destination' that was saved in batch_process().
+ if (isset($_batch['destination'])) {
+ $_GET['destination'] = $_batch['destination'];
+ }
+
+ // Determine the target path to redirect to.
+ if (!isset($_batch['form_state']['redirect'])) {
+ if (isset($_batch['redirect'])) {
+ $_batch['form_state']['redirect'] = $_batch['redirect'];
+ }
+ else {
+ $_batch['form_state']['redirect'] = $_batch['source_url'];
+ }
+ }
+
+ // Use drupal_redirect_form() to handle the redirection logic.
+ drupal_redirect_form($_batch['form_state']);
+
+ // If no redirection happened, redirect to the originating page. In case the
+ // form needs to be rebuilt, save the final $form_state for
+ // drupal_build_form().
+ if (!empty($_batch['form_state']['rebuild'])) {
+ $_SESSION['batch_form_state'] = $_batch['form_state'];
+ }
+ $function = $_batch['redirect_callback'];
+ if (function_exists($function)) {
+ $function($_batch['source_url'], array('query' => array('op' => 'finish', 'id' => $_batch['id'])));
+ }
+ }
+}
+
+/**
+ * Shutdown function: Stores the current batch data for the next request.
+ *
+ * @see _batch_page()
+ * @see drupal_register_shutdown_function()
+ */
+function _batch_shutdown() {
+ if ($batch = batch_get()) {
+ db_update('batch')
+ ->fields(array('batch' => serialize($batch)))
+ ->condition('bid', $batch['id'])
+ ->execute();
+ }
+}
diff --git a/kolab.org/www/drupal-7.26/includes/batch.queue.inc b/kolab.org/www/drupal-7.26/includes/batch.queue.inc
new file mode 100644
index 0000000..ed290ee
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/batch.queue.inc
@@ -0,0 +1,84 @@
+<?php
+
+/**
+ * @file
+ * Queue handlers used by the Batch API.
+ *
+ * These implementations:
+ * - Ensure FIFO ordering.
+ * - Allow an item to be repeatedly claimed until it is actually deleted (no
+ * notion of lease time or 'expire' date), to allow multipass operations.
+ */
+
+/**
+ * Defines a batch queue.
+ *
+ * Stale items from failed batches are cleaned from the {queue} table on cron
+ * using the 'created' date.
+ */
+class BatchQueue extends SystemQueue {
+
+ /**
+ * Overrides SystemQueue::claimItem().
+ *
+ * Unlike SystemQueue::claimItem(), this method provides a default lease
+ * time of 0 (no expiration) instead of 30. This allows the item to be
+ * claimed repeatedly until it is deleted.
+ */
+ public function claimItem($lease_time = 0) {
+ $item = db_query_range('SELECT data, item_id FROM {queue} q WHERE name = :name ORDER BY item_id ASC', 0, 1, array(':name' => $this->name))->fetchObject();
+ if ($item) {
+ $item->data = unserialize($item->data);
+ return $item;
+ }
+ return FALSE;
+ }
+
+ /**
+ * Retrieves all remaining items in the queue.
+ *
+ * This is specific to Batch API and is not part of the DrupalQueueInterface.
+ */
+ public function getAllItems() {
+ $result = array();
+ $items = db_query('SELECT data FROM {queue} q WHERE name = :name ORDER BY item_id ASC', array(':name' => $this->name))->fetchAll();
+ foreach ($items as $item) {
+ $result[] = unserialize($item->data);
+ }
+ return $result;
+ }
+}
+
+/**
+ * Defines a batch queue for non-progressive batches.
+ */
+class BatchMemoryQueue extends MemoryQueue {
+
+ /**
+ * Overrides MemoryQueue::claimItem().
+ *
+ * Unlike MemoryQueue::claimItem(), this method provides a default lease
+ * time of 0 (no expiration) instead of 30. This allows the item to be
+ * claimed repeatedly until it is deleted.
+ */
+ public function claimItem($lease_time = 0) {
+ if (!empty($this->queue)) {
+ reset($this->queue);
+ return current($this->queue);
+ }
+ return FALSE;
+ }
+
+ /**
+ * Retrieves all remaining items in the queue.
+ *
+ * This is specific to Batch API and is not part of the DrupalQueueInterface.
+ */
+ public function getAllItems() {
+ $result = array();
+ foreach ($this->queue as $item) {
+ $result[] = $item->data;
+ }
+ return $result;
+ }
+}
diff --git a/kolab.org/www/drupal-7.26/includes/bootstrap.inc b/kolab.org/www/drupal-7.26/includes/bootstrap.inc
new file mode 100644
index 0000000..e5de2d1
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/bootstrap.inc
@@ -0,0 +1,3487 @@
+<?php
+
+/**
+ * @file
+ * Functions that need to be loaded on every Drupal request.
+ */
+
+/**
+ * The current system version.
+ */
+define('VERSION', '7.26');
+
+/**
+ * Core API compatibility.
+ */
+define('DRUPAL_CORE_COMPATIBILITY', '7.x');
+
+/**
+ * Minimum supported version of PHP.
+ */
+define('DRUPAL_MINIMUM_PHP', '5.2.4');
+
+/**
+ * Minimum recommended value of PHP memory_limit.
+ */
+define('DRUPAL_MINIMUM_PHP_MEMORY_LIMIT', '32M');
+
+/**
+ * Error reporting level: display no errors.
+ */
+define('ERROR_REPORTING_HIDE', 0);
+
+/**
+ * Error reporting level: display errors and warnings.
+ */
+define('ERROR_REPORTING_DISPLAY_SOME', 1);
+
+/**
+ * Error reporting level: display all messages.
+ */
+define('ERROR_REPORTING_DISPLAY_ALL', 2);
+
+/**
+ * Indicates that the item should never be removed unless explicitly selected.
+ *
+ * The item may be removed using cache_clear_all() with a cache ID.
+ */
+define('CACHE_PERMANENT', 0);
+
+/**
+ * Indicates that the item should be removed at the next general cache wipe.
+ */
+define('CACHE_TEMPORARY', -1);
+
+/**
+ * @defgroup logging_severity_levels Logging severity levels
+ * @{
+ * Logging severity levels as defined in RFC 3164.
+ *
+ * The WATCHDOG_* constant definitions correspond to the logging severity levels
+ * defined in RFC 3164, section 4.1.1. PHP supplies predefined LOG_* constants
+ * for use in the syslog() function, but their values on Windows builds do not
+ * correspond to RFC 3164. The associated PHP bug report was closed with the
+ * comment, "And it's also not a bug, as Windows just have less log levels,"
+ * and "So the behavior you're seeing is perfectly normal."
+ *
+ * @see http://www.faqs.org/rfcs/rfc3164.html
+ * @see http://bugs.php.net/bug.php?id=18090
+ * @see http://php.net/manual/function.syslog.php
+ * @see http://php.net/manual/network.constants.php
+ * @see watchdog()
+ * @see watchdog_severity_levels()
+ */
+
+/**
+ * Log message severity -- Emergency: system is unusable.
+ */
+define('WATCHDOG_EMERGENCY', 0);
+
+/**
+ * Log message severity -- Alert: action must be taken immediately.
+ */
+define('WATCHDOG_ALERT', 1);
+
+/**
+ * Log message severity -- Critical conditions.
+ */
+define('WATCHDOG_CRITICAL', 2);
+
+/**
+ * Log message severity -- Error conditions.
+ */
+define('WATCHDOG_ERROR', 3);
+
+/**
+ * Log message severity -- Warning conditions.
+ */
+define('WATCHDOG_WARNING', 4);
+
+/**
+ * Log message severity -- Normal but significant conditions.
+ */
+define('WATCHDOG_NOTICE', 5);
+
+/**
+ * Log message severity -- Informational messages.
+ */
+define('WATCHDOG_INFO', 6);
+
+/**
+ * Log message severity -- Debug-level messages.
+ */
+define('WATCHDOG_DEBUG', 7);
+
+/**
+ * @} End of "defgroup logging_severity_levels".
+ */
+
+/**
+ * First bootstrap phase: initialize configuration.
+ */
+define('DRUPAL_BOOTSTRAP_CONFIGURATION', 0);
+
+/**
+ * Second bootstrap phase: try to serve a cached page.
+ */
+define('DRUPAL_BOOTSTRAP_PAGE_CACHE', 1);
+
+/**
+ * Third bootstrap phase: initialize database layer.
+ */
+define('DRUPAL_BOOTSTRAP_DATABASE', 2);
+
+/**
+ * Fourth bootstrap phase: initialize the variable system.
+ */
+define('DRUPAL_BOOTSTRAP_VARIABLES', 3);
+
+/**
+ * Fifth bootstrap phase: initialize session handling.
+ */
+define('DRUPAL_BOOTSTRAP_SESSION', 4);
+
+/**
+ * Sixth bootstrap phase: set up the page header.
+ */
+define('DRUPAL_BOOTSTRAP_PAGE_HEADER', 5);
+
+/**
+ * Seventh bootstrap phase: find out language of the page.
+ */
+define('DRUPAL_BOOTSTRAP_LANGUAGE', 6);
+
+/**
+ * Final bootstrap phase: Drupal is fully loaded; validate and fix input data.
+ */
+define('DRUPAL_BOOTSTRAP_FULL', 7);
+
+/**
+ * Role ID for anonymous users; should match what's in the "role" table.
+ */
+define('DRUPAL_ANONYMOUS_RID', 1);
+
+/**
+ * Role ID for authenticated users; should match what's in the "role" table.
+ */
+define('DRUPAL_AUTHENTICATED_RID', 2);
+
+/**
+ * The number of bytes in a kilobyte.
+ *
+ * For more information, visit http://en.wikipedia.org/wiki/Kilobyte.
+ */
+define('DRUPAL_KILOBYTE', 1024);
+
+/**
+ * The language code used when no language is explicitly assigned.
+ *
+ * Defined by ISO639-2 for "Undetermined".
+ */
+define('LANGUAGE_NONE', 'und');
+
+/**
+ * The type of language used to define the content language.
+ */
+define('LANGUAGE_TYPE_CONTENT', 'language_content');
+
+/**
+ * The type of language used to select the user interface.
+ */
+define('LANGUAGE_TYPE_INTERFACE', 'language');
+
+/**
+ * The type of language used for URLs.
+ */
+define('LANGUAGE_TYPE_URL', 'language_url');
+
+/**
+ * Language written left to right. Possible value of $language->direction.
+ */
+define('LANGUAGE_LTR', 0);
+
+/**
+ * Language written right to left. Possible value of $language->direction.
+ */
+define('LANGUAGE_RTL', 1);
+
+/**
+ * Time of the current request in seconds elapsed since the Unix Epoch.
+ *
+ * This differs from $_SERVER['REQUEST_TIME'], which is stored as a float
+ * since PHP 5.4.0. Float timestamps confuse most PHP functions
+ * (including date_create()).
+ *
+ * @see http://php.net/manual/reserved.variables.server.php
+ * @see http://php.net/manual/function.time.php
+ */
+define('REQUEST_TIME', (int) $_SERVER['REQUEST_TIME']);
+
+/**
+ * Flag used to indicate that text is not sanitized, so run check_plain().
+ *
+ * @see drupal_set_title()
+ */
+define('CHECK_PLAIN', 0);
+
+/**
+ * Flag used to indicate that text has already been sanitized.
+ *
+ * @see drupal_set_title()
+ */
+define('PASS_THROUGH', -1);
+
+/**
+ * Signals that the registry lookup cache should be reset.
+ */
+define('REGISTRY_RESET_LOOKUP_CACHE', 1);
+
+/**
+ * Signals that the registry lookup cache should be written to storage.
+ */
+define('REGISTRY_WRITE_LOOKUP_CACHE', 2);
+
+/**
+ * Regular expression to match PHP function names.
+ *
+ * @see http://php.net/manual/language.functions.php
+ */
+define('DRUPAL_PHP_FUNCTION_PATTERN', '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*');
+
+/**
+ * Provides a caching wrapper to be used in place of large array structures.
+ *
+ * This class should be extended by systems that need to cache large amounts
+ * of data and have it represented as an array to calling functions. These
+ * arrays can become very large, so ArrayAccess is used to allow different
+ * strategies to be used for caching internally (lazy loading, building caches
+ * over time etc.). This can dramatically reduce the amount of data that needs
+ * to be loaded from cache backends on each request, and memory usage from
+ * static caches of that same data.
+ *
+ * Note that array_* functions do not work with ArrayAccess. Systems using
+ * DrupalCacheArray should use this only internally. If providing API functions
+ * that return the full array, this can be cached separately or returned
+ * directly. However since DrupalCacheArray holds partial content by design, it
+ * should be a normal PHP array or otherwise contain the full structure.
+ *
+ * Note also that due to limitations in PHP prior to 5.3.4, it is impossible to
+ * write directly to the contents of nested arrays contained in this object.
+ * Only writes to the top-level array elements are possible. So if you
+ * previously had set $object['foo'] = array(1, 2, 'bar' => 'baz'), but later
+ * want to change the value of 'bar' from 'baz' to 'foobar', you cannot do so
+ * a targeted write like $object['foo']['bar'] = 'foobar'. Instead, you must
+ * overwrite the entire top-level 'foo' array with the entire set of new
+ * values: $object['foo'] = array(1, 2, 'bar' => 'foobar'). Due to this same
+ * limitation, attempts to create references to any contained data, nested or
+ * otherwise, will fail silently. So $var = &$object['foo'] will not throw an
+ * error, and $var will be populated with the contents of $object['foo'], but
+ * that data will be passed by value, not reference. For more information on
+ * the PHP limitation, see the note in the official PHP documentation at·
+ * http://php.net/manual/arrayaccess.offsetget.php on
+ * ArrayAccess::offsetGet().
+ *
+ * By default, the class accounts for caches where calling functions might
+ * request keys in the array that won't exist even after a cache rebuild. This
+ * prevents situations where a cache rebuild would be triggered over and over
+ * due to a 'missing' item. These cases are stored internally as a value of
+ * NULL. This means that the offsetGet() and offsetExists() methods
+ * must be overridden if caching an array where the top level values can
+ * legitimately be NULL, and where $object->offsetExists() needs to correctly
+ * return (equivalent to array_key_exists() vs. isset()). This should not
+ * be necessary in the majority of cases.
+ *
+ * Classes extending this class must override at least the
+ * resolveCacheMiss() method to have a working implementation.
+ *
+ * offsetSet() is not overridden by this class by default. In practice this
+ * means that assigning an offset via arrayAccess will only apply while the
+ * object is in scope and will not be written back to the persistent cache.
+ * This follows a similar pattern to static vs. persistent caching in
+ * procedural code. Extending classes may wish to alter this behavior, for
+ * example by overriding offsetSet() and adding an automatic call to persist().
+ *
+ * @see SchemaCache
+ */
+abstract class DrupalCacheArray implements ArrayAccess {
+
+ /**
+ * A cid to pass to cache_set() and cache_get().
+ */
+ protected $cid;
+
+ /**
+ * A bin to pass to cache_set() and cache_get().
+ */
+ protected $bin;
+
+ /**
+ * An array of keys to add to the cache at the end of the request.
+ */
+ protected $keysToPersist = array();
+
+ /**
+ * Storage for the data itself.
+ */
+ protected $storage = array();
+
+ /**
+ * Constructs a DrupalCacheArray object.
+ *
+ * @param $cid
+ * The cid for the array being cached.
+ * @param $bin
+ * The bin to cache the array.
+ */
+ public function __construct($cid, $bin) {
+ $this->cid = $cid;
+ $this->bin = $bin;
+
+ if ($cached = cache_get($this->cid, $this->bin)) {
+ $this->storage = $cached->data;
+ }
+ }
+
+ /**
+ * Implements ArrayAccess::offsetExists().
+ */
+ public function offsetExists($offset) {
+ return $this->offsetGet($offset) !== NULL;
+ }
+
+ /**
+ * Implements ArrayAccess::offsetGet().
+ */
+ public function offsetGet($offset) {
+ if (isset($this->storage[$offset]) || array_key_exists($offset, $this->storage)) {
+ return $this->storage[$offset];
+ }
+ else {
+ return $this->resolveCacheMiss($offset);
+ }
+ }
+
+ /**
+ * Implements ArrayAccess::offsetSet().
+ */
+ public function offsetSet($offset, $value) {
+ $this->storage[$offset] = $value;
+ }
+
+ /**
+ * Implements ArrayAccess::offsetUnset().
+ */
+ public function offsetUnset($offset) {
+ unset($this->storage[$offset]);
+ }
+
+ /**
+ * Flags an offset value to be written to the persistent cache.
+ *
+ * If a value is assigned to a cache object with offsetSet(), by default it
+ * will not be written to the persistent cache unless it is flagged with this
+ * method. This allows items to be cached for the duration of a request,
+ * without necessarily writing back to the persistent cache at the end.
+ *
+ * @param $offset
+ * The array offset that was requested.
+ * @param $persist
+ * Optional boolean to specify whether the offset should be persisted or
+ * not, defaults to TRUE. When called with $persist = FALSE the offset will
+ * be unflagged so that it will not be written at the end of the request.
+ */
+ protected function persist($offset, $persist = TRUE) {
+ $this->keysToPersist[$offset] = $persist;
+ }
+
+ /**
+ * Resolves a cache miss.
+ *
+ * When an offset is not found in the object, this is treated as a cache
+ * miss. This method allows classes implementing the interface to look up
+ * the actual value and allow it to be cached.
+ *
+ * @param $offset
+ * The offset that was requested.
+ *
+ * @return
+ * The value of the offset, or NULL if no value was found.
+ */
+ abstract protected function resolveCacheMiss($offset);
+
+ /**
+ * Writes a value to the persistent cache immediately.
+ *
+ * @param $data
+ * The data to write to the persistent cache.
+ * @param $lock
+ * Whether to acquire a lock before writing to cache.
+ */
+ protected function set($data, $lock = TRUE) {
+ // Lock cache writes to help avoid stampedes.
+ // To implement locking for cache misses, override __construct().
+ $lock_name = $this->cid . ':' . $this->bin;
+ if (!$lock || lock_acquire($lock_name)) {
+ if ($cached = cache_get($this->cid, $this->bin)) {
+ $data = $cached->data + $data;
+ }
+ cache_set($this->cid, $data, $this->bin);
+ if ($lock) {
+ lock_release($lock_name);
+ }
+ }
+ }
+
+ /**
+ * Destructs the DrupalCacheArray object.
+ */
+ public function __destruct() {
+ $data = array();
+ foreach ($this->keysToPersist as $offset => $persist) {
+ if ($persist) {
+ $data[$offset] = $this->storage[$offset];
+ }
+ }
+ if (!empty($data)) {
+ $this->set($data);
+ }
+ }
+}
+
+/**
+ * Starts the timer with the specified name.
+ *
+ * If you start and stop the same timer multiple times, the measured intervals
+ * will be accumulated.
+ *
+ * @param $name
+ * The name of the timer.
+ */
+function timer_start($name) {
+ global $timers;
+
+ $timers[$name]['start'] = microtime(TRUE);
+ $timers[$name]['count'] = isset($timers[$name]['count']) ? ++$timers[$name]['count'] : 1;
+}
+
+/**
+ * Reads the current timer value without stopping the timer.
+ *
+ * @param $name
+ * The name of the timer.
+ *
+ * @return
+ * The current timer value in ms.
+ */
+function timer_read($name) {
+ global $timers;
+
+ if (isset($timers[$name]['start'])) {
+ $stop = microtime(TRUE);
+ $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
+
+ if (isset($timers[$name]['time'])) {
+ $diff += $timers[$name]['time'];
+ }
+ return $diff;
+ }
+ return $timers[$name]['time'];
+}
+
+/**
+ * Stops the timer with the specified name.
+ *
+ * @param $name
+ * The name of the timer.
+ *
+ * @return
+ * A timer array. The array contains the number of times the timer has been
+ * started and stopped (count) and the accumulated timer value in ms (time).
+ */
+function timer_stop($name) {
+ global $timers;
+
+ if (isset($timers[$name]['start'])) {
+ $stop = microtime(TRUE);
+ $diff = round(($stop - $timers[$name]['start']) * 1000, 2);
+ if (isset($timers[$name]['time'])) {
+ $timers[$name]['time'] += $diff;
+ }
+ else {
+ $timers[$name]['time'] = $diff;
+ }
+ unset($timers[$name]['start']);
+ }
+
+ return $timers[$name];
+}
+
+/**
+ * Returns the appropriate configuration directory.
+ *
+ * Returns the configuration path based on the site's hostname, port, and
+ * pathname. Uses find_conf_path() to find the current configuration directory.
+ * See default.settings.php for examples on how the URL is converted to a
+ * directory.
+ *
+ * @param bool $require_settings
+ * Only configuration directories with an existing settings.php file
+ * will be recognized. Defaults to TRUE. During initial installation,
+ * this is set to FALSE so that Drupal can detect a matching directory,
+ * then create a new settings.php file in it.
+ * @param bool $reset
+ * Force a full search for matching directories even if one had been
+ * found previously. Defaults to FALSE.
+ *
+ * @return
+ * The path of the matching directory.
+ *
+ * @see default.settings.php
+ */
+function conf_path($require_settings = TRUE, $reset = FALSE) {
+ $conf = &drupal_static(__FUNCTION__, '');
+
+ if ($conf && !$reset) {
+ return $conf;
+ }
+
+ $confdir = 'sites';
+
+ $sites = array();
+ if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/sites.php')) {
+ // This will overwrite $sites with the desired mappings.
+ include(DRUPAL_ROOT . '/' . $confdir . '/sites.php');
+ }
+
+ $uri = explode('/', $_SERVER['SCRIPT_NAME'] ? $_SERVER['SCRIPT_NAME'] : $_SERVER['SCRIPT_FILENAME']);
+ $server = explode('.', implode('.', array_reverse(explode(':', rtrim($_SERVER['HTTP_HOST'], '.')))));
+ for ($i = count($uri) - 1; $i > 0; $i--) {
+ for ($j = count($server); $j > 0; $j--) {
+ $dir = implode('.', array_slice($server, -$j)) . implode('.', array_slice($uri, 0, $i));
+ if (isset($sites[$dir]) && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $sites[$dir])) {
+ $dir = $sites[$dir];
+ }
+ if (file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir . '/settings.php') || (!$require_settings && file_exists(DRUPAL_ROOT . '/' . $confdir . '/' . $dir))) {
+ $conf = "$confdir/$dir";
+ return $conf;
+ }
+ }
+ }
+ $conf = "$confdir/default";
+ return $conf;
+}
+
+/**
+ * Sets appropriate server variables needed for command line scripts to work.
+ *
+ * This function can be called by command line scripts before bootstrapping
+ * Drupal, to ensure that the page loads with the desired server parameters.
+ * This is because many parts of Drupal assume that they are running in a web
+ * browser and therefore use information from the global PHP $_SERVER variable
+ * that does not get set when Drupal is run from the command line.
+ *
+ * In many cases, the default way in which this function populates the $_SERVER
+ * variable is sufficient, and it can therefore be called without passing in
+ * any input. However, command line scripts running on a multisite installation
+ * (or on any installation that has settings.php stored somewhere other than
+ * the sites/default folder) need to pass in the URL of the site to allow
+ * Drupal to detect the correct location of the settings.php file. Passing in
+ * the 'url' parameter is also required for functions like request_uri() to
+ * return the expected values.
+ *
+ * Most other parameters do not need to be passed in, but may be necessary in
+ * some cases; for example, if Drupal's ip_address() function needs to return
+ * anything but the standard localhost value ('127.0.0.1'), the command line
+ * script should pass in the desired value via the 'REMOTE_ADDR' key.
+ *
+ * @param $variables
+ * (optional) An associative array of variables within $_SERVER that should
+ * be replaced. If the special element 'url' is provided in this array, it
+ * will be used to populate some of the server defaults; it should be set to
+ * the URL of the current page request, excluding any $_GET request but
+ * including the script name (e.g., http://www.example.com/mysite/index.php).
+ *
+ * @see conf_path()
+ * @see request_uri()
+ * @see ip_address()
+ */
+function drupal_override_server_variables($variables = array()) {
+ // Allow the provided URL to override any existing values in $_SERVER.
+ if (isset($variables['url'])) {
+ $url = parse_url($variables['url']);
+ if (isset($url['host'])) {
+ $_SERVER['HTTP_HOST'] = $url['host'];
+ }
+ if (isset($url['path'])) {
+ $_SERVER['SCRIPT_NAME'] = $url['path'];
+ }
+ unset($variables['url']);
+ }
+ // Define default values for $_SERVER keys. These will be used if $_SERVER
+ // does not already define them and no other values are passed in to this
+ // function.
+ $defaults = array(
+ 'HTTP_HOST' => 'localhost',
+ 'SCRIPT_NAME' => NULL,
+ 'REMOTE_ADDR' => '127.0.0.1',
+ 'REQUEST_METHOD' => 'GET',
+ 'SERVER_NAME' => NULL,
+ 'SERVER_SOFTWARE' => NULL,
+ 'HTTP_USER_AGENT' => NULL,
+ );
+ // Replace elements of the $_SERVER array, as appropriate.
+ $_SERVER = $variables + $_SERVER + $defaults;
+}
+
+/**
+ * Initializes the PHP environment.
+ */
+function drupal_environment_initialize() {
+ if (!isset($_SERVER['HTTP_REFERER'])) {
+ $_SERVER['HTTP_REFERER'] = '';
+ }
+ if (!isset($_SERVER['SERVER_PROTOCOL']) || ($_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.0' && $_SERVER['SERVER_PROTOCOL'] != 'HTTP/1.1')) {
+ $_SERVER['SERVER_PROTOCOL'] = 'HTTP/1.0';
+ }
+
+ if (isset($_SERVER['HTTP_HOST'])) {
+ // As HTTP_HOST is user input, ensure it only contains characters allowed
+ // in hostnames. See RFC 952 (and RFC 2181).
+ // $_SERVER['HTTP_HOST'] is lowercased here per specifications.
+ $_SERVER['HTTP_HOST'] = strtolower($_SERVER['HTTP_HOST']);
+ if (!drupal_valid_http_host($_SERVER['HTTP_HOST'])) {
+ // HTTP_HOST is invalid, e.g. if containing slashes it may be an attack.
+ header($_SERVER['SERVER_PROTOCOL'] . ' 400 Bad Request');
+ exit;
+ }
+ }
+ else {
+ // Some pre-HTTP/1.1 clients will not send a Host header. Ensure the key is
+ // defined for E_ALL compliance.
+ $_SERVER['HTTP_HOST'] = '';
+ }
+
+ // When clean URLs are enabled, emulate ?q=foo/bar using REQUEST_URI. It is
+ // not possible to append the query string using mod_rewrite without the B
+ // flag (this was added in Apache 2.2.8), because mod_rewrite unescapes the
+ // path before passing it on to PHP. This is a problem when the path contains
+ // e.g. "&" or "%" that have special meanings in URLs and must be encoded.
+ $_GET['q'] = request_path();
+
+ // Enforce E_ALL, but allow users to set levels not part of E_ALL.
+ error_reporting(E_ALL | error_reporting());
+
+ // Override PHP settings required for Drupal to work properly.
+ // sites/default/default.settings.php contains more runtime settings.
+ // The .htaccess file contains settings that cannot be changed at runtime.
+
+ // Don't escape quotes when reading files from the database, disk, etc.
+ ini_set('magic_quotes_runtime', '0');
+ // Use session cookies, not transparent sessions that puts the session id in
+ // the query string.
+ ini_set('session.use_cookies', '1');
+ ini_set('session.use_only_cookies', '1');
+ ini_set('session.use_trans_sid', '0');
+ // Don't send HTTP headers using PHP's session handler.
+ // An empty string is used here to disable the cache limiter.
+ ini_set('session.cache_limiter', '');
+ // Use httponly session cookies.
+ ini_set('session.cookie_httponly', '1');
+
+ // Set sane locale settings, to ensure consistent string, dates, times and
+ // numbers handling.
+ setlocale(LC_ALL, 'C');
+}
+
+/**
+ * Validates that a hostname (for example $_SERVER['HTTP_HOST']) is safe.
+ *
+ * @return
+ * TRUE if only containing valid characters, or FALSE otherwise.
+ */
+function drupal_valid_http_host($host) {
+ return preg_match('/^\[?(?:[a-zA-Z0-9-:\]_]+\.?)+$/', $host);
+}
+
+/**
+ * Sets the base URL, cookie domain, and session name from configuration.
+ */
+function drupal_settings_initialize() {
+ global $base_url, $base_path, $base_root;
+
+ // Export these settings.php variables to the global namespace.
+ global $databases, $cookie_domain, $conf, $installed_profile, $update_free_access, $db_url, $db_prefix, $drupal_hash_salt, $is_https, $base_secure_url, $base_insecure_url;
+ $conf = array();
+
+ if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.php')) {
+ include_once DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
+ }
+ $is_https = isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on';
+
+ if (isset($base_url)) {
+ // Parse fixed base URL from settings.php.
+ $parts = parse_url($base_url);
+ if (!isset($parts['path'])) {
+ $parts['path'] = '';
+ }
+ $base_path = $parts['path'] . '/';
+ // Build $base_root (everything until first slash after "scheme://").
+ $base_root = substr($base_url, 0, strlen($base_url) - strlen($parts['path']));
+ }
+ else {
+ // Create base URL.
+ $http_protocol = $is_https ? 'https' : 'http';
+ $base_root = $http_protocol . '://' . $_SERVER['HTTP_HOST'];
+
+ $base_url = $base_root;
+
+ // $_SERVER['SCRIPT_NAME'] can, in contrast to $_SERVER['PHP_SELF'], not
+ // be modified by a visitor.
+ if ($dir = rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/')) {
+ $base_path = $dir;
+ $base_url .= $base_path;
+ $base_path .= '/';
+ }
+ else {
+ $base_path = '/';
+ }
+ }
+ $base_secure_url = str_replace('http://', 'https://', $base_url);
+ $base_insecure_url = str_replace('https://', 'http://', $base_url);
+
+ if ($cookie_domain) {
+ // If the user specifies the cookie domain, also use it for session name.
+ $session_name = $cookie_domain;
+ }
+ else {
+ // Otherwise use $base_url as session name, without the protocol
+ // to use the same session identifiers across HTTP and HTTPS.
+ list( , $session_name) = explode('://', $base_url, 2);
+ // HTTP_HOST can be modified by a visitor, but we already sanitized it
+ // in drupal_settings_initialize().
+ if (!empty($_SERVER['HTTP_HOST'])) {
+ $cookie_domain = $_SERVER['HTTP_HOST'];
+ // Strip leading periods, www., and port numbers from cookie domain.
+ $cookie_domain = ltrim($cookie_domain, '.');
+ if (strpos($cookie_domain, 'www.') === 0) {
+ $cookie_domain = substr($cookie_domain, 4);
+ }
+ $cookie_domain = explode(':', $cookie_domain);
+ $cookie_domain = '.' . $cookie_domain[0];
+ }
+ }
+ // Per RFC 2109, cookie domains must contain at least one dot other than the
+ // first. For hosts such as 'localhost' or IP Addresses we don't set a cookie domain.
+ if (count(explode('.', $cookie_domain)) > 2 && !is_numeric(str_replace('.', '', $cookie_domain))) {
+ ini_set('session.cookie_domain', $cookie_domain);
+ }
+ // To prevent session cookies from being hijacked, a user can configure the
+ // SSL version of their website to only transfer session cookies via SSL by
+ // using PHP's session.cookie_secure setting. The browser will then use two
+ // separate session cookies for the HTTPS and HTTP versions of the site. So we
+ // must use different session identifiers for HTTPS and HTTP to prevent a
+ // cookie collision.
+ if ($is_https) {
+ ini_set('session.cookie_secure', TRUE);
+ }
+ $prefix = ini_get('session.cookie_secure') ? 'SSESS' : 'SESS';
+ session_name($prefix . substr(hash('sha256', $session_name), 0, 32));
+}
+
+/**
+ * Returns and optionally sets the filename for a system resource.
+ *
+ * The filename, whether provided, cached, or retrieved from the database, is
+ * only returned if the file exists.
+ *
+ * This function plays a key role in allowing Drupal's resources (modules
+ * and themes) to be located in different places depending on a site's
+ * configuration. For example, a module 'foo' may legally be located
+ * in any of these three places:
+ *
+ * modules/foo/foo.module
+ * sites/all/modules/foo/foo.module
+ * sites/example.com/modules/foo/foo.module
+ *
+ * Calling drupal_get_filename('module', 'foo') will give you one of
+ * the above, depending on where the module is located.
+ *
+ * @param $type
+ * The type of the item (theme, theme_engine, module, profile).
+ * @param $name
+ * The name of the item for which the filename is requested.
+ * @param $filename
+ * The filename of the item if it is to be set explicitly rather
+ * than by consulting the database.
+ *
+ * @return
+ * The filename of the requested item or NULL if the item is not found.
+ */
+function drupal_get_filename($type, $name, $filename = NULL) {
+ // The location of files will not change during the request, so do not use
+ // drupal_static().
+ static $files = array(), $dirs = array();
+
+ // Profiles are a special case: they have a fixed location and naming.
+ if ($type == 'profile') {
+ $profile_filename = "profiles/$name/$name.profile";
+ $files[$type][$name] = file_exists($profile_filename) ? $profile_filename : FALSE;
+ }
+ if (!isset($files[$type])) {
+ $files[$type] = array();
+ }
+
+ if (!empty($filename) && file_exists($filename)) {
+ $files[$type][$name] = $filename;
+ }
+ elseif (isset($files[$type][$name])) {
+ // nothing
+ }
+ // Verify that we have an active database connection, before querying
+ // the database. This is required because this function is called both
+ // before we have a database connection (i.e. during installation) and
+ // when a database connection fails.
+ else {
+ try {
+ if (function_exists('db_query')) {
+ $file = db_query("SELECT filename FROM {system} WHERE name = :name AND type = :type", array(':name' => $name, ':type' => $type))->fetchField();
+ if (file_exists(DRUPAL_ROOT . '/' . $file)) {
+ $files[$type][$name] = $file;
+ }
+ }
+ }
+ catch (Exception $e) {
+ // The database table may not exist because Drupal is not yet installed,
+ // or the database might be down. We have a fallback for this case so we
+ // hide the error completely.
+ }
+ // Fallback to searching the filesystem if the database could not find the
+ // file or the file returned by the database is not found.
+ if (!isset($files[$type][$name])) {
+ // We have a consistent directory naming: modules, themes...
+ $dir = $type . 's';
+ if ($type == 'theme_engine') {
+ $dir = 'themes/engines';
+ $extension = 'engine';
+ }
+ elseif ($type == 'theme') {
+ $extension = 'info';
+ }
+ else {
+ $extension = $type;
+ }
+
+ if (!isset($dirs[$dir][$extension])) {
+ $dirs[$dir][$extension] = TRUE;
+ if (!function_exists('drupal_system_listing')) {
+ require_once DRUPAL_ROOT . '/includes/common.inc';
+ }
+ // Scan the appropriate directories for all files with the requested
+ // extension, not just the file we are currently looking for. This
+ // prevents unnecessary scans from being repeated when this function is
+ // called more than once in the same page request.
+ $matches = drupal_system_listing("/^" . DRUPAL_PHP_FUNCTION_PATTERN . "\.$extension$/", $dir, 'name', 0);
+ foreach ($matches as $matched_name => $file) {
+ $files[$type][$matched_name] = $file->uri;
+ }
+ }
+ }
+ }
+
+ if (isset($files[$type][$name])) {
+ return $files[$type][$name];
+ }
+}
+
+/**
+ * Loads the persistent variable table.
+ *
+ * The variable table is composed of values that have been saved in the table
+ * with variable_set() as well as those explicitly specified in the
+ * configuration file.
+ */
+function variable_initialize($conf = array()) {
+ // NOTE: caching the variables improves performance by 20% when serving
+ // cached pages.
+ if ($cached = cache_get('variables', 'cache_bootstrap')) {
+ $variables = $cached->data;
+ }
+ else {
+ // Cache miss. Avoid a stampede.
+ $name = 'variable_init';
+ if (!lock_acquire($name, 1)) {
+ // Another request is building the variable cache.
+ // Wait, then re-run this function.
+ lock_wait($name);
+ return variable_initialize($conf);
+ }
+ else {
+ // Proceed with variable rebuild.
+ $variables = array_map('unserialize', db_query('SELECT name, value FROM {variable}')->fetchAllKeyed());
+ cache_set('variables', $variables, 'cache_bootstrap');
+ lock_release($name);
+ }
+ }
+
+ foreach ($conf as $name => $value) {
+ $variables[$name] = $value;
+ }
+
+ return $variables;
+}
+
+/**
+ * Returns a persistent variable.
+ *
+ * Case-sensitivity of the variable_* functions depends on the database
+ * collation used. To avoid problems, always use lower case for persistent
+ * variable names.
+ *
+ * @param $name
+ * The name of the variable to return.
+ * @param $default
+ * The default value to use if this variable has never been set.
+ *
+ * @return
+ * The value of the variable. Unserialization is taken care of as necessary.
+ *
+ * @see variable_del()
+ * @see variable_set()
+ */
+function variable_get($name, $default = NULL) {
+ global $conf;
+
+ return isset($conf[$name]) ? $conf[$name] : $default;
+}
+
+/**
+ * Sets a persistent variable.
+ *
+ * Case-sensitivity of the variable_* functions depends on the database
+ * collation used. To avoid problems, always use lower case for persistent
+ * variable names.
+ *
+ * @param $name
+ * The name of the variable to set.
+ * @param $value
+ * The value to set. This can be any PHP data type; these functions take care
+ * of serialization as necessary.
+ *
+ * @see variable_del()
+ * @see variable_get()
+ */
+function variable_set($name, $value) {
+ global $conf;
+
+ db_merge('variable')->key(array('name' => $name))->fields(array('value' => serialize($value)))->execute();
+
+ cache_clear_all('variables', 'cache_bootstrap');
+
+ $conf[$name] = $value;
+}
+
+/**
+ * Unsets a persistent variable.
+ *
+ * Case-sensitivity of the variable_* functions depends on the database
+ * collation used. To avoid problems, always use lower case for persistent
+ * variable names.
+ *
+ * @param $name
+ * The name of the variable to undefine.
+ *
+ * @see variable_get()
+ * @see variable_set()
+ */
+function variable_del($name) {
+ global $conf;
+
+ db_delete('variable')
+ ->condition('name', $name)
+ ->execute();
+ cache_clear_all('variables', 'cache_bootstrap');
+
+ unset($conf[$name]);
+}
+
+/**
+ * Retrieves the current page from the cache.
+ *
+ * Note: we do not serve cached pages to authenticated users, or to anonymous
+ * users when $_SESSION is non-empty. $_SESSION may contain status messages
+ * from a form submission, the contents of a shopping cart, or other user-
+ * specific content that should not be cached and displayed to other users.
+ *
+ * @param $check_only
+ * (optional) Set to TRUE to only return whether a previous call found a
+ * cache entry.
+ *
+ * @return
+ * The cache object, if the page was found in the cache, NULL otherwise.
+ */
+function drupal_page_get_cache($check_only = FALSE) {
+ global $base_root;
+ static $cache_hit = FALSE;
+
+ if ($check_only) {
+ return $cache_hit;
+ }
+
+ if (drupal_page_is_cacheable()) {
+ $cache = cache_get($base_root . request_uri(), 'cache_page');
+ if ($cache !== FALSE) {
+ $cache_hit = TRUE;
+ }
+ return $cache;
+ }
+}
+
+/**
+ * Determines the cacheability of the current page.
+ *
+ * @param $allow_caching
+ * Set to FALSE if you want to prevent this page to get cached.
+ *
+ * @return
+ * TRUE if the current page can be cached, FALSE otherwise.
+ */
+function drupal_page_is_cacheable($allow_caching = NULL) {
+ $allow_caching_static = &drupal_static(__FUNCTION__, TRUE);
+ if (isset($allow_caching)) {
+ $allow_caching_static = $allow_caching;
+ }
+
+ return $allow_caching_static && ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD')
+ && !drupal_is_cli();
+}
+
+/**
+ * Invokes a bootstrap hook in all bootstrap modules that implement it.
+ *
+ * @param $hook
+ * The name of the bootstrap hook to invoke.
+ *
+ * @see bootstrap_hooks()
+ */
+function bootstrap_invoke_all($hook) {
+ // Bootstrap modules should have been loaded when this function is called, so
+ // we don't need to tell module_list() to reset its internal list (and we
+ // therefore leave the first parameter at its default value of FALSE). We
+ // still pass in TRUE for the second parameter, though; in case this is the
+ // first time during the bootstrap that module_list() is called, we want to
+ // make sure that its internal cache is primed with the bootstrap modules
+ // only.
+ foreach (module_list(FALSE, TRUE) as $module) {
+ drupal_load('module', $module);
+ module_invoke($module, $hook);
+ }
+}
+
+/**
+ * Includes a file with the provided type and name.
+ *
+ * This prevents including a theme, engine, module, etc., more than once.
+ *
+ * @param $type
+ * The type of item to load (i.e. theme, theme_engine, module).
+ * @param $name
+ * The name of the item to load.
+ *
+ * @return
+ * TRUE if the item is loaded or has already been loaded.
+ */
+function drupal_load($type, $name) {
+ // Once a file is included this can't be reversed during a request so do not
+ // use drupal_static() here.
+ static $files = array();
+
+ if (isset($files[$type][$name])) {
+ return TRUE;
+ }
+
+ $filename = drupal_get_filename($type, $name);
+
+ if ($filename) {
+ include_once DRUPAL_ROOT . '/' . $filename;
+ $files[$type][$name] = TRUE;
+
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+/**
+ * Sets an HTTP response header for the current page.
+ *
+ * Note: When sending a Content-Type header, always include a 'charset' type,
+ * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
+ *
+ * @param $name
+ * The HTTP header name, or the special 'Status' header name.
+ * @param $value
+ * The HTTP header value; if equal to FALSE, the specified header is unset.
+ * If $name is 'Status', this is expected to be a status code followed by a
+ * reason phrase, e.g. "404 Not Found".
+ * @param $append
+ * Whether to append the value to an existing header or to replace it.
+ */
+function drupal_add_http_header($name, $value, $append = FALSE) {
+ // The headers as name/value pairs.
+ $headers = &drupal_static('drupal_http_headers', array());
+
+ $name_lower = strtolower($name);
+ _drupal_set_preferred_header_name($name);
+
+ if ($value === FALSE) {
+ $headers[$name_lower] = FALSE;
+ }
+ elseif (isset($headers[$name_lower]) && $append) {
+ // Multiple headers with identical names may be combined using comma (RFC
+ // 2616, section 4.2).
+ $headers[$name_lower] .= ',' . $value;
+ }
+ else {
+ $headers[$name_lower] = $value;
+ }
+ drupal_send_headers(array($name => $headers[$name_lower]), TRUE);
+}
+
+/**
+ * Gets the HTTP response headers for the current page.
+ *
+ * @param $name
+ * An HTTP header name. If omitted, all headers are returned as name/value
+ * pairs. If an array value is FALSE, the header has been unset.
+ *
+ * @return
+ * A string containing the header value, or FALSE if the header has been set,
+ * or NULL if the header has not been set.
+ */
+function drupal_get_http_header($name = NULL) {
+ $headers = &drupal_static('drupal_http_headers', array());
+ if (isset($name)) {
+ $name = strtolower($name);
+ return isset($headers[$name]) ? $headers[$name] : NULL;
+ }
+ else {
+ return $headers;
+ }
+}
+
+/**
+ * Sets the preferred name for the HTTP header.
+ *
+ * Header names are case-insensitive, but for maximum compatibility they should
+ * follow "common form" (see RFC 2617, section 4.2).
+ */
+function _drupal_set_preferred_header_name($name = NULL) {
+ static $header_names = array();
+
+ if (!isset($name)) {
+ return $header_names;
+ }
+ $header_names[strtolower($name)] = $name;
+}
+
+/**
+ * Sends the HTTP response headers that were previously set, adding defaults.
+ *
+ * Headers are set in drupal_add_http_header(). Default headers are not set
+ * if they have been replaced or unset using drupal_add_http_header().
+ *
+ * @param array $default_headers
+ * (optional) An array of headers as name/value pairs.
+ * @param bool $only_default
+ * (optional) If TRUE and headers have already been sent, send only the
+ * specified headers.
+ */
+function drupal_send_headers($default_headers = array(), $only_default = FALSE) {
+ $headers_sent = &drupal_static(__FUNCTION__, FALSE);
+ $headers = drupal_get_http_header();
+ if ($only_default && $headers_sent) {
+ $headers = array();
+ }
+ $headers_sent = TRUE;
+
+ $header_names = _drupal_set_preferred_header_name();
+ foreach ($default_headers as $name => $value) {
+ $name_lower = strtolower($name);
+ if (!isset($headers[$name_lower])) {
+ $headers[$name_lower] = $value;
+ $header_names[$name_lower] = $name;
+ }
+ }
+ foreach ($headers as $name_lower => $value) {
+ if ($name_lower == 'status') {
+ header($_SERVER['SERVER_PROTOCOL'] . ' ' . $value);
+ }
+ // Skip headers that have been unset.
+ elseif ($value !== FALSE) {
+ header($header_names[$name_lower] . ': ' . $value);
+ }
+ }
+}
+
+/**
+ * Sets HTTP headers in preparation for a page response.
+ *
+ * Authenticated users are always given a 'no-cache' header, and will fetch a
+ * fresh page on every request. This prevents authenticated users from seeing
+ * locally cached pages.
+ *
+ * Also give each page a unique ETag. This will force clients to include both
+ * an If-Modified-Since header and an If-None-Match header when doing
+ * conditional requests for the page (required by RFC 2616, section 13.3.4),
+ * making the validation more robust. This is a workaround for a bug in Mozilla
+ * Firefox that is triggered when Drupal's caching is enabled and the user
+ * accesses Drupal via an HTTP proxy (see
+ * https://bugzilla.mozilla.org/show_bug.cgi?id=269303): When an authenticated
+ * user requests a page, and then logs out and requests the same page again,
+ * Firefox may send a conditional request based on the page that was cached
+ * locally when the user was logged in. If this page did not have an ETag
+ * header, the request only contains an If-Modified-Since header. The date will
+ * be recent, because with authenticated users the Last-Modified header always
+ * refers to the time of the request. If the user accesses Drupal via a proxy
+ * server, and the proxy already has a cached copy of the anonymous page with an
+ * older Last-Modified date, the proxy may respond with 304 Not Modified, making
+ * the client think that the anonymous and authenticated pageviews are
+ * identical.
+ *
+ * @see drupal_page_set_cache()
+ */
+function drupal_page_header() {
+ $headers_sent = &drupal_static(__FUNCTION__, FALSE);
+ if ($headers_sent) {
+ return TRUE;
+ }
+ $headers_sent = TRUE;
+
+ $default_headers = array(
+ 'Expires' => 'Sun, 19 Nov 1978 05:00:00 GMT',
+ 'Last-Modified' => gmdate(DATE_RFC1123, REQUEST_TIME),
+ 'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
+ 'ETag' => '"' . REQUEST_TIME . '"',
+ );
+ drupal_send_headers($default_headers);
+}
+
+/**
+ * Sets HTTP headers in preparation for a cached page response.
+ *
+ * The headers allow as much as possible in proxies and browsers without any
+ * particular knowledge about the pages. Modules can override these headers
+ * using drupal_add_http_header().
+ *
+ * If the request is conditional (using If-Modified-Since and If-None-Match),
+ * and the conditions match those currently in the cache, a 304 Not Modified
+ * response is sent.
+ */
+function drupal_serve_page_from_cache(stdClass $cache) {
+ // Negotiate whether to use compression.
+ $page_compression = !empty($cache->data['page_compressed']);
+ $return_compressed = $page_compression && isset($_SERVER['HTTP_ACCEPT_ENCODING']) && strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') !== FALSE;
+
+ // Get headers set in hook_boot(). Keys are lower-case.
+ $hook_boot_headers = drupal_get_http_header();
+
+ // Headers generated in this function, that may be replaced or unset using
+ // drupal_add_http_headers(). Keys are mixed-case.
+ $default_headers = array();
+
+ foreach ($cache->data['headers'] as $name => $value) {
+ // In the case of a 304 response, certain headers must be sent, and the
+ // remaining may not (see RFC 2616, section 10.3.5). Do not override
+ // headers set in hook_boot().
+ $name_lower = strtolower($name);
+ if (in_array($name_lower, array('content-location', 'expires', 'cache-control', 'vary')) && !isset($hook_boot_headers[$name_lower])) {
+ drupal_add_http_header($name, $value);
+ unset($cache->data['headers'][$name]);
+ }
+ }
+
+ // If the client sent a session cookie, a cached copy will only be served
+ // to that one particular client due to Vary: Cookie. Thus, do not set
+ // max-age > 0, allowing the page to be cached by external proxies, when a
+ // session cookie is present unless the Vary header has been replaced or
+ // unset in hook_boot().
+ $max_age = !isset($_COOKIE[session_name()]) || isset($hook_boot_headers['vary']) ? variable_get('page_cache_maximum_age', 0) : 0;
+ $default_headers['Cache-Control'] = 'public, max-age=' . $max_age;
+
+ // Entity tag should change if the output changes.
+ $etag = '"' . $cache->created . '-' . intval($return_compressed) . '"';
+ header('Etag: ' . $etag);
+
+ // See if the client has provided the required HTTP headers.
+ $if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) : FALSE;
+ $if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? stripslashes($_SERVER['HTTP_IF_NONE_MATCH']) : FALSE;
+
+ if ($if_modified_since && $if_none_match
+ && $if_none_match == $etag // etag must match
+ && $if_modified_since == $cache->created) { // if-modified-since must match
+ header($_SERVER['SERVER_PROTOCOL'] . ' 304 Not Modified');
+ drupal_send_headers($default_headers);
+ return;
+ }
+
+ // Send the remaining headers.
+ foreach ($cache->data['headers'] as $name => $value) {
+ drupal_add_http_header($name, $value);
+ }
+
+ $default_headers['Last-Modified'] = gmdate(DATE_RFC1123, $cache->created);
+
+ // HTTP/1.0 proxies does not support the Vary header, so prevent any caching
+ // by sending an Expires date in the past. HTTP/1.1 clients ignores the
+ // Expires header if a Cache-Control: max-age= directive is specified (see RFC
+ // 2616, section 14.9.3).
+ $default_headers['Expires'] = 'Sun, 19 Nov 1978 05:00:00 GMT';
+
+ drupal_send_headers($default_headers);
+
+ // Allow HTTP proxies to cache pages for anonymous users without a session
+ // cookie. The Vary header is used to indicates the set of request-header
+ // fields that fully determines whether a cache is permitted to use the
+ // response to reply to a subsequent request for a given URL without
+ // revalidation. If a Vary header has been set in hook_boot(), it is assumed
+ // that the module knows how to cache the page.
+ if (!isset($hook_boot_headers['vary']) && !variable_get('omit_vary_cookie')) {
+ header('Vary: Cookie');
+ }
+
+ if ($page_compression) {
+ header('Vary: Accept-Encoding', FALSE);
+ // If page_compression is enabled, the cache contains gzipped data.
+ if ($return_compressed) {
+ // $cache->data['body'] is already gzip'ed, so make sure
+ // zlib.output_compression does not compress it once more.
+ ini_set('zlib.output_compression', '0');
+ header('Content-Encoding: gzip');
+ }
+ else {
+ // The client does not support compression, so unzip the data in the
+ // cache. Strip the gzip header and run uncompress.
+ $cache->data['body'] = gzinflate(substr(substr($cache->data['body'], 10), 0, -8));
+ }
+ }
+
+ // Print the page.
+ print $cache->data['body'];
+}
+
+/**
+ * Defines the critical hooks that force modules to always be loaded.
+ */
+function bootstrap_hooks() {
+ return array('boot', 'exit', 'watchdog', 'language_init');
+}
+
+/**
+ * Unserializes and appends elements from a serialized string.
+ *
+ * @param $obj
+ * The object to which the elements are appended.
+ * @param $field
+ * The attribute of $obj whose value should be unserialized.
+ */
+function drupal_unpack($obj, $field = 'data') {
+ if ($obj->$field && $data = unserialize($obj->$field)) {
+ foreach ($data as $key => $value) {
+ if (!empty($key) && !isset($obj->$key)) {
+ $obj->$key = $value;
+ }
+ }
+ }
+ return $obj;
+}
+
+/**
+ * Translates a string to the current language or to a given language.
+ *
+ * The t() function serves two purposes. First, at run-time it translates
+ * user-visible text into the appropriate language. Second, various mechanisms
+ * that figure out what text needs to be translated work off t() -- the text
+ * inside t() calls is added to the database of strings to be translated.
+ * These strings are expected to be in English, so the first argument should
+ * always be in English. To enable a fully-translatable site, it is important
+ * that all human-readable text that will be displayed on the site or sent to
+ * a user is passed through the t() function, or a related function. See the
+ * @link http://drupal.org/node/322729 Localization API @endlink pages for
+ * more information, including recommendations on how to break up or not
+ * break up strings for translation.
+ *
+ * @section sec_translating_vars Translating Variables
+ * You should never use t() to translate variables, such as calling
+ * @code t($text); @endcode, unless the text that the variable holds has been
+ * passed through t() elsewhere (e.g., $text is one of several translated
+ * literal strings in an array). It is especially important never to call
+ * @code t($user_text); @endcode, where $user_text is some text that a user
+ * entered - doing that can lead to cross-site scripting and other security
+ * problems. However, you can use variable substitution in your string, to put
+ * variable text such as user names or link URLs into translated text. Variable
+ * substitution looks like this:
+ * @code
+ * $text = t("@name's blog", array('@name' => format_username($account)));
+ * @endcode
+ * Basically, you can put variables like @name into your string, and t() will
+ * substitute their sanitized values at translation time. (See the
+ * Localization API pages referenced above and the documentation of
+ * format_string() for details about how to define variables in your string.)
+ * Translators can then rearrange the string as necessary for the language
+ * (e.g., in Spanish, it might be "blog de @name").
+ *
+ * @section sec_alt_funcs_install Use During Installation Phase
+ * During the Drupal installation phase, some resources used by t() wil not be
+ * available to code that needs localization. See st() and get_t() for
+ * alternatives.
+ *
+ * @param $string
+ * A string containing the English string to translate.
+ * @param $args
+ * An associative array of replacements to make after translation. Based
+ * on the first character of the key, the value is escaped and/or themed.
+ * See format_string() for details.
+ * @param $options
+ * An associative array of additional options, with the following elements:
+ * - 'langcode' (defaults to the current language): The language code to
+ * translate to a language other than what is used to display the page.
+ * - 'context' (defaults to the empty context): The context the source string
+ * belongs to.
+ *
+ * @return
+ * The translated string.
+ *
+ * @see st()
+ * @see get_t()
+ * @see format_string()
+ * @ingroup sanitization
+ */
+function t($string, array $args = array(), array $options = array()) {
+ global $language;
+ static $custom_strings;
+
+ // Merge in default.
+ if (empty($options['langcode'])) {
+ $options['langcode'] = isset($language->language) ? $language->language : 'en';
+ }
+ if (empty($options['context'])) {
+ $options['context'] = '';
+ }
+
+ // First, check for an array of customized strings. If present, use the array
+ // *instead of* database lookups. This is a high performance way to provide a
+ // handful of string replacements. See settings.php for examples.
+ // Cache the $custom_strings variable to improve performance.
+ if (!isset($custom_strings[$options['langcode']])) {
+ $custom_strings[$options['langcode']] = variable_get('locale_custom_strings_' . $options['langcode'], array());
+ }
+ // Custom strings work for English too, even if locale module is disabled.
+ if (isset($custom_strings[$options['langcode']][$options['context']][$string])) {
+ $string = $custom_strings[$options['langcode']][$options['context']][$string];
+ }
+ // Translate with locale module if enabled.
+ elseif ($options['langcode'] != 'en' && function_exists('locale')) {
+ $string = locale($string, $options['context'], $options['langcode']);
+ }
+ if (empty($args)) {
+ return $string;
+ }
+ else {
+ return format_string($string, $args);
+ }
+}
+
+/**
+ * Formats a string for HTML display by replacing variable placeholders.
+ *
+ * This function replaces variable placeholders in a string with the requested
+ * values and escapes the values so they can be safely displayed as HTML. It
+ * should be used on any unknown text that is intended to be printed to an HTML
+ * page (especially text that may have come from untrusted users, since in that
+ * case it prevents cross-site scripting and other security problems).
+ *
+ * In most cases, you should use t() rather than calling this function
+ * directly, since it will translate the text (on non-English-only sites) in
+ * addition to formatting it.
+ *
+ * @param $string
+ * A string containing placeholders.
+ * @param $args
+ * An associative array of replacements to make. Occurrences in $string of
+ * any key in $args are replaced with the corresponding value, after optional
+ * sanitization and formatting. The type of sanitization and formatting
+ * depends on the first character of the key:
+ * - @variable: Escaped to HTML using check_plain(). Use this as the default
+ * choice for anything displayed on a page on the site.
+ * - %variable: Escaped to HTML and formatted using drupal_placeholder(),
+ * which makes it display as <em>emphasized</em> text.
+ * - !variable: Inserted as is, with no sanitization or formatting. Only use
+ * this for text that has already been prepared for HTML display (for
+ * example, user-supplied text that has already been run through
+ * check_plain() previously, or is expected to contain some limited HTML
+ * tags and has already been run through filter_xss() previously).
+ *
+ * @see t()
+ * @ingroup sanitization
+ */
+function format_string($string, array $args = array()) {
+ // Transform arguments before inserting them.
+ foreach ($args as $key => $value) {
+ switch ($key[0]) {
+ case '@':
+ // Escaped only.
+ $args[$key] = check_plain($value);
+ break;
+
+ case '%':
+ default:
+ // Escaped and placeholder.
+ $args[$key] = drupal_placeholder($value);
+ break;
+
+ case '!':
+ // Pass-through.
+ }
+ }
+ return strtr($string, $args);
+}
+
+/**
+ * Encodes special characters in a plain-text string for display as HTML.
+ *
+ * Also validates strings as UTF-8 to prevent cross site scripting attacks on
+ * Internet Explorer 6.
+ *
+ * @param $text
+ * The text to be checked or processed.
+ *
+ * @return
+ * An HTML safe version of $text, or an empty string if $text is not
+ * valid UTF-8.
+ *
+ * @see drupal_validate_utf8()
+ * @ingroup sanitization
+ */
+function check_plain($text) {
+ return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
+}
+
+/**
+ * Checks whether a string is valid UTF-8.
+ *
+ * All functions designed to filter input should use drupal_validate_utf8
+ * to ensure they operate on valid UTF-8 strings to prevent bypass of the
+ * filter.
+ *
+ * When text containing an invalid UTF-8 lead byte (0xC0 - 0xFF) is presented
+ * as UTF-8 to Internet Explorer 6, the program may misinterpret subsequent
+ * bytes. When these subsequent bytes are HTML control characters such as
+ * quotes or angle brackets, parts of the text that were deemed safe by filters
+ * end up in locations that are potentially unsafe; An onerror attribute that
+ * is outside of a tag, and thus deemed safe by a filter, can be interpreted
+ * by the browser as if it were inside the tag.
+ *
+ * The function does not return FALSE for strings containing character codes
+ * above U+10FFFF, even though these are prohibited by RFC 3629.
+ *
+ * @param $text
+ * The text to check.
+ *
+ * @return
+ * TRUE if the text is valid UTF-8, FALSE if not.
+ */
+function drupal_validate_utf8($text) {
+ if (strlen($text) == 0) {
+ return TRUE;
+ }
+ // With the PCRE_UTF8 modifier 'u', preg_match() fails silently on strings
+ // containing invalid UTF-8 byte sequences. It does not reject character
+ // codes above U+10FFFF (represented by 4 or more octets), though.
+ return (preg_match('/^./us', $text) == 1);
+}
+
+/**
+ * Returns the equivalent of Apache's $_SERVER['REQUEST_URI'] variable.
+ *
+ * Because $_SERVER['REQUEST_URI'] is only available on Apache, we generate an
+ * equivalent using other environment variables.
+ */
+function request_uri() {
+ if (isset($_SERVER['REQUEST_URI'])) {
+ $uri = $_SERVER['REQUEST_URI'];
+ }
+ else {
+ if (isset($_SERVER['argv'])) {
+ $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['argv'][0];
+ }
+ elseif (isset($_SERVER['QUERY_STRING'])) {
+ $uri = $_SERVER['SCRIPT_NAME'] . '?' . $_SERVER['QUERY_STRING'];
+ }
+ else {
+ $uri = $_SERVER['SCRIPT_NAME'];
+ }
+ }
+ // Prevent multiple slashes to avoid cross site requests via the Form API.
+ $uri = '/' . ltrim($uri, '/');
+
+ return $uri;
+}
+
+/**
+ * Logs an exception.
+ *
+ * This is a wrapper function for watchdog() which automatically decodes an
+ * exception.
+ *
+ * @param $type
+ * The category to which this message belongs.
+ * @param $exception
+ * The exception that is going to be logged.
+ * @param $message
+ * The message to store in the log. If empty, a text that contains all useful
+ * information about the passed-in exception is used.
+ * @param $variables
+ * Array of variables to replace in the message on display. Defaults to the
+ * return value of drupal_decode_exception().
+ * @param $severity
+ * The severity of the message, as per RFC 3164.
+ * @param $link
+ * A link to associate with the message.
+ *
+ * @see watchdog()
+ * @see drupal_decode_exception()
+ */
+function watchdog_exception($type, Exception $exception, $message = NULL, $variables = array(), $severity = WATCHDOG_ERROR, $link = NULL) {
+
+ // Use a default value if $message is not set.
+ if (empty($message)) {
+ // The exception message is run through check_plain() by _drupal_decode_exception().
+ $message = '%type: !message in %function (line %line of %file).';
+ }
+ // $variables must be an array so that we can add the exception information.
+ if (!is_array($variables)) {
+ $variables = array();
+ }
+
+ require_once DRUPAL_ROOT . '/includes/errors.inc';
+ $variables += _drupal_decode_exception($exception);
+ watchdog($type, $message, $variables, $severity, $link);
+}
+
+/**
+ * Logs a system message.
+ *
+ * @param $type
+ * The category to which this message belongs. Can be any string, but the
+ * general practice is to use the name of the module calling watchdog().
+ * @param $message
+ * The message to store in the log. Keep $message translatable
+ * by not concatenating dynamic values into it! Variables in the
+ * message should be added by using placeholder strings alongside
+ * the variables argument to declare the value of the placeholders.
+ * See t() for documentation on how $message and $variables interact.
+ * @param $variables
+ * Array of variables to replace in the message on display or
+ * NULL if message is already translated or not possible to
+ * translate.
+ * @param $severity
+ * The severity of the message; one of the following values as defined in
+ * @link http://www.faqs.org/rfcs/rfc3164.html RFC 3164: @endlink
+ * - WATCHDOG_EMERGENCY: Emergency, system is unusable.
+ * - WATCHDOG_ALERT: Alert, action must be taken immediately.
+ * - WATCHDOG_CRITICAL: Critical conditions.
+ * - WATCHDOG_ERROR: Error conditions.
+ * - WATCHDOG_WARNING: Warning conditions.
+ * - WATCHDOG_NOTICE: (default) Normal but significant conditions.
+ * - WATCHDOG_INFO: Informational messages.
+ * - WATCHDOG_DEBUG: Debug-level messages.
+ * @param $link
+ * A link to associate with the message.
+ *
+ * @see watchdog_severity_levels()
+ * @see hook_watchdog()
+ */
+function watchdog($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
+ global $user, $base_root;
+
+ static $in_error_state = FALSE;
+
+ // It is possible that the error handling will itself trigger an error. In that case, we could
+ // end up in an infinite loop. To avoid that, we implement a simple static semaphore.
+ if (!$in_error_state && function_exists('module_implements')) {
+ $in_error_state = TRUE;
+
+ // The user object may not exist in all conditions, so 0 is substituted if needed.
+ $user_uid = isset($user->uid) ? $user->uid : 0;
+
+ // Prepare the fields to be logged
+ $log_entry = array(
+ 'type' => $type,
+ 'message' => $message,
+ 'variables' => $variables,
+ 'severity' => $severity,
+ 'link' => $link,
+ 'user' => $user,
+ 'uid' => $user_uid,
+ 'request_uri' => $base_root . request_uri(),
+ 'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
+ 'ip' => ip_address(),
+ // Request time isn't accurate for long processes, use time() instead.
+ 'timestamp' => time(),
+ );
+
+ // Call the logging hooks to log/process the message
+ foreach (module_implements('watchdog') as $module) {
+ module_invoke($module, 'watchdog', $log_entry);
+ }
+
+ // It is critical that the semaphore is only cleared here, in the parent
+ // watchdog() call (not outside the loop), to prevent recursive execution.
+ $in_error_state = FALSE;
+ }
+}
+
+/**
+ * Sets a message to display to the user.
+ *
+ * Messages are stored in a session variable and displayed in page.tpl.php via
+ * the $messages theme variable.
+ *
+ * Example usage:
+ * @code
+ * drupal_set_message(t('An error occurred and processing did not complete.'), 'error');
+ * @endcode
+ *
+ * @param string $message
+ * (optional) The translated message to be displayed to the user. For
+ * consistency with other messages, it should begin with a capital letter and
+ * end with a period.
+ * @param string $type
+ * (optional) The message's type. Defaults to 'status'. These values are
+ * supported:
+ * - 'status'
+ * - 'warning'
+ * - 'error'
+ * @param bool $repeat
+ * (optional) If this is FALSE and the message is already set, then the
+ * message won't be repeated. Defaults to TRUE.
+ *
+ * @return array|null
+ * A multidimensional array with keys corresponding to the set message types.
+ * The indexed array values of each contain the set messages for that type.
+ * Or, if there are no messages set, the function returns NULL.
+ *
+ * @see drupal_get_messages()
+ * @see theme_status_messages()
+ */
+function drupal_set_message($message = NULL, $type = 'status', $repeat = TRUE) {
+ if ($message) {
+ if (!isset($_SESSION['messages'][$type])) {
+ $_SESSION['messages'][$type] = array();
+ }
+
+ if ($repeat || !in_array($message, $_SESSION['messages'][$type])) {
+ $_SESSION['messages'][$type][] = $message;
+ }
+
+ // Mark this page as being uncacheable.
+ drupal_page_is_cacheable(FALSE);
+ }
+
+ // Messages not set when DB connection fails.
+ return isset($_SESSION['messages']) ? $_SESSION['messages'] : NULL;
+}
+
+/**
+ * Returns all messages that have been set with drupal_set_message().
+ *
+ * @param string $type
+ * (optional) Limit the messages returned by type. Defaults to NULL, meaning
+ * all types. These values are supported:
+ * - NULL
+ * - 'status'
+ * - 'warning'
+ * - 'error'
+ * @param bool $clear_queue
+ * (optional) If this is TRUE, the queue will be cleared of messages of the
+ * type specified in the $type parameter. Otherwise the queue will be left
+ * intact. Defaults to TRUE.
+ *
+ * @return array
+ * A multidimensional array with keys corresponding to the set message types.
+ * The indexed array values of each contain the set messages for that type.
+ * The messages returned are limited to the type specified in the $type
+ * parameter. If there are no messages of the specified type, an empty array
+ * is returned.
+ *
+ * @see drupal_set_message()
+ * @see theme_status_messages()
+ */
+function drupal_get_messages($type = NULL, $clear_queue = TRUE) {
+ if ($messages = drupal_set_message()) {
+ if ($type) {
+ if ($clear_queue) {
+ unset($_SESSION['messages'][$type]);
+ }
+ if (isset($messages[$type])) {
+ return array($type => $messages[$type]);
+ }
+ }
+ else {
+ if ($clear_queue) {
+ unset($_SESSION['messages']);
+ }
+ return $messages;
+ }
+ }
+ return array();
+}
+
+/**
+ * Gets the title of the current page.
+ *
+ * The title is displayed on the page and in the title bar.
+ *
+ * @return
+ * The current page's title.
+ */
+function drupal_get_title() {
+ $title = drupal_set_title();
+
+ // During a bootstrap, menu.inc is not included and thus we cannot provide a title.
+ if (!isset($title) && function_exists('menu_get_active_title')) {
+ $title = check_plain(menu_get_active_title());
+ }
+
+ return $title;
+}
+
+/**
+ * Sets the title of the current page.
+ *
+ * The title is displayed on the page and in the title bar.
+ *
+ * @param $title
+ * Optional string value to assign to the page title; or if set to NULL
+ * (default), leaves the current title unchanged.
+ * @param $output
+ * Optional flag - normally should be left as CHECK_PLAIN. Only set to
+ * PASS_THROUGH if you have already removed any possibly dangerous code
+ * from $title using a function like check_plain() or filter_xss(). With this
+ * flag the string will be passed through unchanged.
+ *
+ * @return
+ * The updated title of the current page.
+ */
+function drupal_set_title($title = NULL, $output = CHECK_PLAIN) {
+ $stored_title = &drupal_static(__FUNCTION__);
+
+ if (isset($title)) {
+ $stored_title = ($output == PASS_THROUGH) ? $title : check_plain($title);
+ }
+
+ return $stored_title;
+}
+
+/**
+ * Checks to see if an IP address has been blocked.
+ *
+ * Blocked IP addresses are stored in the database by default. However for
+ * performance reasons we allow an override in settings.php. This allows us
+ * to avoid querying the database at this critical stage of the bootstrap if
+ * an administrative interface for IP address blocking is not required.
+ *
+ * @param $ip
+ * IP address to check.
+ *
+ * @return bool
+ * TRUE if access is denied, FALSE if access is allowed.
+ */
+function drupal_is_denied($ip) {
+ // Because this function is called on every page request, we first check
+ // for an array of IP addresses in settings.php before querying the
+ // database.
+ $blocked_ips = variable_get('blocked_ips');
+ $denied = FALSE;
+ if (isset($blocked_ips) && is_array($blocked_ips)) {
+ $denied = in_array($ip, $blocked_ips);
+ }
+ // Only check if database.inc is loaded already. If
+ // $conf['page_cache_without_database'] = TRUE; is set in settings.php,
+ // then the database won't be loaded here so the IPs in the database
+ // won't be denied. However the user asked explicitly not to use the
+ // database and also in this case it's quite likely that the user relies
+ // on higher performance solutions like a firewall.
+ elseif (class_exists('Database', FALSE)) {
+ $denied = (bool)db_query("SELECT 1 FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField();
+ }
+ return $denied;
+}
+
+/**
+ * Handles denied users.
+ *
+ * @param $ip
+ * IP address to check. Prints a message and exits if access is denied.
+ */
+function drupal_block_denied($ip) {
+ // Deny access to blocked IP addresses - t() is not yet available.
+ if (drupal_is_denied($ip)) {
+ header($_SERVER['SERVER_PROTOCOL'] . ' 403 Forbidden');
+ print 'Sorry, ' . check_plain(ip_address()) . ' has been banned.';
+ exit();
+ }
+}
+
+/**
+ * Returns a URL-safe, base64 encoded string of highly randomized bytes (over the full 8-bit range).
+ *
+ * @param $byte_count
+ * The number of random bytes to fetch and base64 encode.
+ *
+ * @return string
+ * The base64 encoded result will have a length of up to 4 * $byte_count.
+ */
+function drupal_random_key($byte_count = 32) {
+ return drupal_base64_encode(drupal_random_bytes($byte_count));
+}
+
+/**
+ * Returns a URL-safe, base64 encoded version of the supplied string.
+ *
+ * @param $string
+ * The string to convert to base64.
+ *
+ * @return string
+ */
+function drupal_base64_encode($string) {
+ $data = base64_encode($string);
+ // Modify the output so it's safe to use in URLs.
+ return strtr($data, array('+' => '-', '/' => '_', '=' => ''));
+}
+
+/**
+ * Returns a string of highly randomized bytes (over the full 8-bit range).
+ *
+ * This function is better than simply calling mt_rand() or any other built-in
+ * PHP function because it can return a long string of bytes (compared to < 4
+ * bytes normally from mt_rand()) and uses the best available pseudo-random
+ * source.
+ *
+ * @param $count
+ * The number of characters (bytes) to return in the string.
+ */
+function drupal_random_bytes($count) {
+ // $random_state does not use drupal_static as it stores random bytes.
+ static $random_state, $bytes, $has_openssl;
+
+ $missing_bytes = $count - strlen($bytes);
+
+ if ($missing_bytes > 0) {
+ // PHP versions prior 5.3.4 experienced openssl_random_pseudo_bytes()
+ // locking on Windows and rendered it unusable.
+ if (!isset($has_openssl)) {
+ $has_openssl = version_compare(PHP_VERSION, '5.3.4', '>=') && function_exists('openssl_random_pseudo_bytes');
+ }
+
+ // openssl_random_pseudo_bytes() will find entropy in a system-dependent
+ // way.
+ if ($has_openssl) {
+ $bytes .= openssl_random_pseudo_bytes($missing_bytes);
+ }
+
+ // Else, read directly from /dev/urandom, which is available on many *nix
+ // systems and is considered cryptographically secure.
+ elseif ($fh = @fopen('/dev/urandom', 'rb')) {
+ // PHP only performs buffered reads, so in reality it will always read
+ // at least 4096 bytes. Thus, it costs nothing extra to read and store
+ // that much so as to speed any additional invocations.
+ $bytes .= fread($fh, max(4096, $missing_bytes));
+ fclose($fh);
+ }
+
+ // If we couldn't get enough entropy, this simple hash-based PRNG will
+ // generate a good set of pseudo-random bytes on any system.
+ // Note that it may be important that our $random_state is passed
+ // through hash() prior to being rolled into $output, that the two hash()
+ // invocations are different, and that the extra input into the first one -
+ // the microtime() - is prepended rather than appended. This is to avoid
+ // directly leaking $random_state via the $output stream, which could
+ // allow for trivial prediction of further "random" numbers.
+ if (strlen($bytes) < $count) {
+ // Initialize on the first call. The contents of $_SERVER includes a mix of
+ // user-specific and system information that varies a little with each page.
+ if (!isset($random_state)) {
+ $random_state = print_r($_SERVER, TRUE);
+ if (function_exists('getmypid')) {
+ // Further initialize with the somewhat random PHP process ID.
+ $random_state .= getmypid();
+ }
+ $bytes = '';
+ }
+
+ do {
+ $random_state = hash('sha256', microtime() . mt_rand() . $random_state);
+ $bytes .= hash('sha256', mt_rand() . $random_state, TRUE);
+ }
+ while (strlen($bytes) < $count);
+ }
+ }
+ $output = substr($bytes, 0, $count);
+ $bytes = substr($bytes, $count);
+ return $output;
+}
+
+/**
+ * Calculates a base-64 encoded, URL-safe sha-256 hmac.
+ *
+ * @param string $data
+ * String to be validated with the hmac.
+ * @param string $key
+ * A secret string key.
+ *
+ * @return string
+ * A base-64 encoded sha-256 hmac, with + replaced with -, / with _ and
+ * any = padding characters removed.
+ */
+function drupal_hmac_base64($data, $key) {
+ // Casting $data and $key to strings here is necessary to avoid empty string
+ // results of the hash function if they are not scalar values. As this
+ // function is used in security-critical contexts like token validation it is
+ // important that it never returns an empty string.
+ $hmac = base64_encode(hash_hmac('sha256', (string) $data, (string) $key, TRUE));
+ // Modify the hmac so it's safe to use in URLs.
+ return strtr($hmac, array('+' => '-', '/' => '_', '=' => ''));
+}
+
+/**
+ * Calculates a base-64 encoded, URL-safe sha-256 hash.
+ *
+ * @param $data
+ * String to be hashed.
+ *
+ * @return
+ * A base-64 encoded sha-256 hash, with + replaced with -, / with _ and
+ * any = padding characters removed.
+ */
+function drupal_hash_base64($data) {
+ $hash = base64_encode(hash('sha256', $data, TRUE));
+ // Modify the hash so it's safe to use in URLs.
+ return strtr($hash, array('+' => '-', '/' => '_', '=' => ''));
+}
+
+/**
+ * Merges multiple arrays, recursively, and returns the merged array.
+ *
+ * This function is similar to PHP's array_merge_recursive() function, but it
+ * handles non-array values differently. When merging values that are not both
+ * arrays, the latter value replaces the former rather than merging with it.
+ *
+ * Example:
+ * @code
+ * $link_options_1 = array('fragment' => 'x', 'attributes' => array('title' => t('X'), 'class' => array('a', 'b')));
+ * $link_options_2 = array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('c', 'd')));
+ *
+ * // This results in array('fragment' => array('x', 'y'), 'attributes' => array('title' => array(t('X'), t('Y')), 'class' => array('a', 'b', 'c', 'd'))).
+ * $incorrect = array_merge_recursive($link_options_1, $link_options_2);
+ *
+ * // This results in array('fragment' => 'y', 'attributes' => array('title' => t('Y'), 'class' => array('a', 'b', 'c', 'd'))).
+ * $correct = drupal_array_merge_deep($link_options_1, $link_options_2);
+ * @endcode
+ *
+ * @param ...
+ * Arrays to merge.
+ *
+ * @return
+ * The merged array.
+ *
+ * @see drupal_array_merge_deep_array()
+ */
+function drupal_array_merge_deep() {
+ $args = func_get_args();
+ return drupal_array_merge_deep_array($args);
+}
+
+/**
+ * Merges multiple arrays, recursively, and returns the merged array.
+ *
+ * This function is equivalent to drupal_array_merge_deep(), except the
+ * input arrays are passed as a single array parameter rather than a variable
+ * parameter list.
+ *
+ * The following are equivalent:
+ * - drupal_array_merge_deep($a, $b);
+ * - drupal_array_merge_deep_array(array($a, $b));
+ *
+ * The following are also equivalent:
+ * - call_user_func_array('drupal_array_merge_deep', $arrays_to_merge);
+ * - drupal_array_merge_deep_array($arrays_to_merge);
+ *
+ * @see drupal_array_merge_deep()
+ */
+function drupal_array_merge_deep_array($arrays) {
+ $result = array();
+
+ foreach ($arrays as $array) {
+ foreach ($array as $key => $value) {
+ // Renumber integer keys as array_merge_recursive() does. Note that PHP
+ // automatically converts array keys that are integer strings (e.g., '1')
+ // to integers.
+ if (is_integer($key)) {
+ $result[] = $value;
+ }
+ // Recurse when both values are arrays.
+ elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) {
+ $result[$key] = drupal_array_merge_deep_array(array($result[$key], $value));
+ }
+ // Otherwise, use the latter value, overriding any previous value.
+ else {
+ $result[$key] = $value;
+ }
+ }
+ }
+
+ return $result;
+}
+
+/**
+ * Generates a default anonymous $user object.
+ *
+ * @return Object - the user object.
+ */
+function drupal_anonymous_user() {
+ $user = variable_get('drupal_anonymous_user_object', new stdClass);
+ $user->uid = 0;
+ $user->hostname = ip_address();
+ $user->roles = array();
+ $user->roles[DRUPAL_ANONYMOUS_RID] = 'anonymous user';
+ $user->cache = 0;
+ return $user;
+}
+
+/**
+ * Ensures Drupal is bootstrapped to the specified phase.
+ *
+ * In order to bootstrap Drupal from another PHP script, you can use this code:
+ * @code
+ * define('DRUPAL_ROOT', '/path/to/drupal');
+ * require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
+ * drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
+ * @endcode
+ *
+ * @param $phase
+ * A constant telling which phase to bootstrap to. When you bootstrap to a
+ * particular phase, all earlier phases are run automatically. Possible
+ * values:
+ * - DRUPAL_BOOTSTRAP_CONFIGURATION: Initializes configuration.
+ * - DRUPAL_BOOTSTRAP_PAGE_CACHE: Tries to serve a cached page.
+ * - DRUPAL_BOOTSTRAP_DATABASE: Initializes the database layer.
+ * - DRUPAL_BOOTSTRAP_VARIABLES: Initializes the variable system.
+ * - DRUPAL_BOOTSTRAP_SESSION: Initializes session handling.
+ * - DRUPAL_BOOTSTRAP_PAGE_HEADER: Sets up the page header.
+ * - DRUPAL_BOOTSTRAP_LANGUAGE: Finds out the language of the page.
+ * - DRUPAL_BOOTSTRAP_FULL: Fully loads Drupal. Validates and fixes input
+ * data.
+ * @param $new_phase
+ * A boolean, set to FALSE if calling drupal_bootstrap from inside a
+ * function called from drupal_bootstrap (recursion).
+ *
+ * @return
+ * The most recently completed phase.
+ */
+function drupal_bootstrap($phase = NULL, $new_phase = TRUE) {
+ // Not drupal_static(), because does not depend on any run-time information.
+ static $phases = array(
+ DRUPAL_BOOTSTRAP_CONFIGURATION,
+ DRUPAL_BOOTSTRAP_PAGE_CACHE,
+ DRUPAL_BOOTSTRAP_DATABASE,
+ DRUPAL_BOOTSTRAP_VARIABLES,
+ DRUPAL_BOOTSTRAP_SESSION,
+ DRUPAL_BOOTSTRAP_PAGE_HEADER,
+ DRUPAL_BOOTSTRAP_LANGUAGE,
+ DRUPAL_BOOTSTRAP_FULL,
+ );
+ // Not drupal_static(), because the only legitimate API to control this is to
+ // call drupal_bootstrap() with a new phase parameter.
+ static $final_phase;
+ // Not drupal_static(), because it's impossible to roll back to an earlier
+ // bootstrap state.
+ static $stored_phase = -1;
+
+ // When not recursing, store the phase name so it's not forgotten while
+ // recursing.
+ if ($new_phase) {
+ $final_phase = $phase;
+ }
+ if (isset($phase)) {
+ // Call a phase if it has not been called before and is below the requested
+ // phase.
+ while ($phases && $phase > $stored_phase && $final_phase > $stored_phase) {
+ $current_phase = array_shift($phases);
+
+ // This function is re-entrant. Only update the completed phase when the
+ // current call actually resulted in a progress in the bootstrap process.
+ if ($current_phase > $stored_phase) {
+ $stored_phase = $current_phase;
+ }
+
+ switch ($current_phase) {
+ case DRUPAL_BOOTSTRAP_CONFIGURATION:
+ _drupal_bootstrap_configuration();
+ break;
+
+ case DRUPAL_BOOTSTRAP_PAGE_CACHE:
+ _drupal_bootstrap_page_cache();
+ break;
+
+ case DRUPAL_BOOTSTRAP_DATABASE:
+ _drupal_bootstrap_database();
+ break;
+
+ case DRUPAL_BOOTSTRAP_VARIABLES:
+ _drupal_bootstrap_variables();
+ break;
+
+ case DRUPAL_BOOTSTRAP_SESSION:
+ require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
+ drupal_session_initialize();
+ break;
+
+ case DRUPAL_BOOTSTRAP_PAGE_HEADER:
+ _drupal_bootstrap_page_header();
+ break;
+
+ case DRUPAL_BOOTSTRAP_LANGUAGE:
+ drupal_language_initialize();
+ break;
+
+ case DRUPAL_BOOTSTRAP_FULL:
+ require_once DRUPAL_ROOT . '/includes/common.inc';
+ _drupal_bootstrap_full();
+ break;
+ }
+ }
+ }
+ return $stored_phase;
+}
+
+/**
+ * Returns the time zone of the current user.
+ */
+function drupal_get_user_timezone() {
+ global $user;
+ if (variable_get('configurable_timezones', 1) && $user->uid && $user->timezone) {
+ return $user->timezone;
+ }
+ else {
+ // Ignore PHP strict notice if time zone has not yet been set in the php.ini
+ // configuration.
+ return variable_get('date_default_timezone', @date_default_timezone_get());
+ }
+}
+
+/**
+ * Gets a salt useful for hardening against SQL injection.
+ *
+ * @return
+ * A salt based on information in settings.php, not in the database.
+ */
+function drupal_get_hash_salt() {
+ global $drupal_hash_salt, $databases;
+ // If the $drupal_hash_salt variable is empty, a hash of the serialized
+ // database credentials is used as a fallback salt.
+ return empty($drupal_hash_salt) ? hash('sha256', serialize($databases)) : $drupal_hash_salt;
+}
+
+/**
+ * Provides custom PHP error handling.
+ *
+ * @param $error_level
+ * The level of the error raised.
+ * @param $message
+ * The error message.
+ * @param $filename
+ * The filename that the error was raised in.
+ * @param $line
+ * The line number the error was raised at.
+ * @param $context
+ * An array that points to the active symbol table at the point the error
+ * occurred.
+ */
+function _drupal_error_handler($error_level, $message, $filename, $line, $context) {
+ require_once DRUPAL_ROOT . '/includes/errors.inc';
+ _drupal_error_handler_real($error_level, $message, $filename, $line, $context);
+}
+
+/**
+ * Provides custom PHP exception handling.
+ *
+ * Uncaught exceptions are those not enclosed in a try/catch block. They are
+ * always fatal: the execution of the script will stop as soon as the exception
+ * handler exits.
+ *
+ * @param $exception
+ * The exception object that was thrown.
+ */
+function _drupal_exception_handler($exception) {
+ require_once DRUPAL_ROOT . '/includes/errors.inc';
+
+ try {
+ // Log the message to the watchdog and return an error page to the user.
+ _drupal_log_error(_drupal_decode_exception($exception), TRUE);
+ }
+ catch (Exception $exception2) {
+ // Another uncaught exception was thrown while handling the first one.
+ // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
+ if (error_displayable()) {
+ print '<h1>Additional uncaught exception thrown while handling exception.</h1>';
+ print '<h2>Original</h2><p>' . _drupal_render_exception_safe($exception) . '</p>';
+ print '<h2>Additional</h2><p>' . _drupal_render_exception_safe($exception2) . '</p><hr />';
+ }
+ }
+}
+
+/**
+ * Sets up the script environment and loads settings.php.
+ */
+function _drupal_bootstrap_configuration() {
+ // Set the Drupal custom error handler.
+ set_error_handler('_drupal_error_handler');
+ set_exception_handler('_drupal_exception_handler');
+
+ drupal_environment_initialize();
+ // Start a page timer:
+ timer_start('page');
+ // Initialize the configuration, including variables from settings.php.
+ drupal_settings_initialize();
+}
+
+/**
+ * Attempts to serve a page from the cache.
+ */
+function _drupal_bootstrap_page_cache() {
+ global $user;
+
+ // Allow specifying special cache handlers in settings.php, like
+ // using memcached or files for storing cache information.
+ require_once DRUPAL_ROOT . '/includes/cache.inc';
+ foreach (variable_get('cache_backends', array()) as $include) {
+ require_once DRUPAL_ROOT . '/' . $include;
+ }
+ // Check for a cache mode force from settings.php.
+ if (variable_get('page_cache_without_database')) {
+ $cache_enabled = TRUE;
+ }
+ else {
+ drupal_bootstrap(DRUPAL_BOOTSTRAP_VARIABLES, FALSE);
+ $cache_enabled = variable_get('cache');
+ }
+ drupal_block_denied(ip_address());
+ // If there is no session cookie and cache is enabled (or forced), try
+ // to serve a cached page.
+ if (!isset($_COOKIE[session_name()]) && $cache_enabled) {
+ // Make sure there is a user object because its timestamp will be
+ // checked, hook_boot might check for anonymous user etc.
+ $user = drupal_anonymous_user();
+ // Get the page from the cache.
+ $cache = drupal_page_get_cache();
+ // If there is a cached page, display it.
+ if (is_object($cache)) {
+ header('X-Drupal-Cache: HIT');
+ // Restore the metadata cached with the page.
+ $_GET['q'] = $cache->data['path'];
+ drupal_set_title($cache->data['title'], PASS_THROUGH);
+ date_default_timezone_set(drupal_get_user_timezone());
+ // If the skipping of the bootstrap hooks is not enforced, call
+ // hook_boot.
+ if (variable_get('page_cache_invoke_hooks', TRUE)) {
+ bootstrap_invoke_all('boot');
+ }
+ drupal_serve_page_from_cache($cache);
+ // If the skipping of the bootstrap hooks is not enforced, call
+ // hook_exit.
+ if (variable_get('page_cache_invoke_hooks', TRUE)) {
+ bootstrap_invoke_all('exit');
+ }
+ // We are done.
+ exit;
+ }
+ else {
+ header('X-Drupal-Cache: MISS');
+ }
+ }
+}
+
+/**
+ * Initializes the database system and registers autoload functions.
+ */
+function _drupal_bootstrap_database() {
+ // Redirect the user to the installation script if Drupal has not been
+ // installed yet (i.e., if no $databases array has been defined in the
+ // settings.php file) and we are not already installing.
+ if (empty($GLOBALS['databases']) && !drupal_installation_attempted()) {
+ include_once DRUPAL_ROOT . '/includes/install.inc';
+ install_goto('install.php');
+ }
+
+ // The user agent header is used to pass a database prefix in the request when
+ // running tests. However, for security reasons, it is imperative that we
+ // validate we ourselves made the request.
+ if ($test_prefix = drupal_valid_test_ua()) {
+ // Set the test run id for use in other parts of Drupal.
+ $test_info = &$GLOBALS['drupal_test_info'];
+ $test_info['test_run_id'] = $test_prefix;
+ $test_info['in_child_site'] = TRUE;
+
+ foreach ($GLOBALS['databases']['default'] as &$value) {
+ // Extract the current default database prefix.
+ if (!isset($value['prefix'])) {
+ $current_prefix = '';
+ }
+ elseif (is_array($value['prefix'])) {
+ $current_prefix = $value['prefix']['default'];
+ }
+ else {
+ $current_prefix = $value['prefix'];
+ }
+
+ // Remove the current database prefix and replace it by our own.
+ $value['prefix'] = array(
+ 'default' => $current_prefix . $test_prefix,
+ );
+ }
+ }
+
+ // Initialize the database system. Note that the connection
+ // won't be initialized until it is actually requested.
+ require_once DRUPAL_ROOT . '/includes/database/database.inc';
+
+ // Register autoload functions so that we can access classes and interfaces.
+ // The database autoload routine comes first so that we can load the database
+ // system without hitting the database. That is especially important during
+ // the install or upgrade process.
+ spl_autoload_register('drupal_autoload_class');
+ spl_autoload_register('drupal_autoload_interface');
+}
+
+/**
+ * Loads system variables and all enabled bootstrap modules.
+ */
+function _drupal_bootstrap_variables() {
+ global $conf;
+
+ // Initialize the lock system.
+ require_once DRUPAL_ROOT . '/' . variable_get('lock_inc', 'includes/lock.inc');
+ lock_initialize();
+
+ // Load variables from the database, but do not overwrite variables set in settings.php.
+ $conf = variable_initialize(isset($conf) ? $conf : array());
+ // Load bootstrap modules.
+ require_once DRUPAL_ROOT . '/includes/module.inc';
+ module_load_all(TRUE);
+}
+
+/**
+ * Invokes hook_boot(), initializes locking system, and sends HTTP headers.
+ */
+function _drupal_bootstrap_page_header() {
+ bootstrap_invoke_all('boot');
+
+ if (!drupal_is_cli()) {
+ ob_start();
+ drupal_page_header();
+ }
+}
+
+/**
+ * Returns the current bootstrap phase for this Drupal process.
+ *
+ * The current phase is the one most recently completed by drupal_bootstrap().
+ *
+ * @see drupal_bootstrap()
+ */
+function drupal_get_bootstrap_phase() {
+ return drupal_bootstrap();
+}
+
+/**
+ * Returns the test prefix if this is an internal request from SimpleTest.
+ *
+ * @return
+ * Either the simpletest prefix (the string "simpletest" followed by any
+ * number of digits) or FALSE if the user agent does not contain a valid
+ * HMAC and timestamp.
+ */
+function drupal_valid_test_ua() {
+ // No reason to reset this.
+ static $test_prefix;
+
+ if (isset($test_prefix)) {
+ return $test_prefix;
+ }
+
+ if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/^(simpletest\d+);(.+);(.+);(.+)$/", $_SERVER['HTTP_USER_AGENT'], $matches)) {
+ list(, $prefix, $time, $salt, $hmac) = $matches;
+ $check_string = $prefix . ';' . $time . ';' . $salt;
+ // We use the salt from settings.php to make the HMAC key, since
+ // the database is not yet initialized and we can't access any Drupal variables.
+ // The file properties add more entropy not easily accessible to others.
+ $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
+ $time_diff = REQUEST_TIME - $time;
+ // Since we are making a local request a 5 second time window is allowed,
+ // and the HMAC must match.
+ if ($time_diff >= 0 && $time_diff <= 5 && $hmac == drupal_hmac_base64($check_string, $key)) {
+ $test_prefix = $prefix;
+ return $test_prefix;
+ }
+ }
+
+ $test_prefix = FALSE;
+ return $test_prefix;
+}
+
+/**
+ * Generates a user agent string with a HMAC and timestamp for simpletest.
+ */
+function drupal_generate_test_ua($prefix) {
+ static $key;
+
+ if (!isset($key)) {
+ // We use the salt from settings.php to make the HMAC key, since
+ // the database is not yet initialized and we can't access any Drupal variables.
+ // The file properties add more entropy not easily accessible to others.
+ $key = drupal_get_hash_salt() . filectime(__FILE__) . fileinode(__FILE__);
+ }
+ // Generate a moderately secure HMAC based on the database credentials.
+ $salt = uniqid('', TRUE);
+ $check_string = $prefix . ';' . time() . ';' . $salt;
+ return $check_string . ';' . drupal_hmac_base64($check_string, $key);
+}
+
+/**
+ * Enables use of the theme system without requiring database access.
+ *
+ * Loads and initializes the theme system for site installs, updates and when
+ * the site is in maintenance mode. This also applies when the database fails.
+ *
+ * @see _drupal_maintenance_theme()
+ */
+function drupal_maintenance_theme() {
+ require_once DRUPAL_ROOT . '/includes/theme.maintenance.inc';
+ _drupal_maintenance_theme();
+}
+
+/**
+ * Returns a simple 404 Not Found page.
+ *
+ * If fast 404 pages are enabled, and this is a matching page then print a
+ * simple 404 page and exit.
+ *
+ * This function is called from drupal_deliver_html_page() at the time when a
+ * a normal 404 page is generated, but it can also optionally be called directly
+ * from settings.php to prevent a Drupal bootstrap on these pages. See
+ * documentation in settings.php for the benefits and drawbacks of using this.
+ *
+ * Paths to dynamically-generated content, such as image styles, should also be
+ * accounted for in this function.
+ */
+function drupal_fast_404() {
+ $exclude_paths = variable_get('404_fast_paths_exclude', FALSE);
+ if ($exclude_paths && !preg_match($exclude_paths, $_GET['q'])) {
+ $fast_paths = variable_get('404_fast_paths', FALSE);
+ if ($fast_paths && preg_match($fast_paths, $_GET['q'])) {
+ drupal_add_http_header('Status', '404 Not Found');
+ $fast_404_html = variable_get('404_fast_html', '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>');
+ // Replace @path in the variable with the page path.
+ print strtr($fast_404_html, array('@path' => check_plain(request_uri())));
+ exit;
+ }
+ }
+}
+
+/**
+ * Returns TRUE if a Drupal installation is currently being attempted.
+ */
+function drupal_installation_attempted() {
+ return defined('MAINTENANCE_MODE') && MAINTENANCE_MODE == 'install';
+}
+
+/**
+ * Returns the name of the proper localization function.
+ *
+ * get_t() exists to support localization for code that might run during
+ * the installation phase, when some elements of the system might not have
+ * loaded.
+ *
+ * This would include implementations of hook_install(), which could run
+ * during the Drupal installation phase, and might also be run during
+ * non-installation time, such as while installing the module from the the
+ * module administration page.
+ *
+ * Example usage:
+ * @code
+ * $t = get_t();
+ * $translated = $t('translate this');
+ * @endcode
+ *
+ * Use t() if your code will never run during the Drupal installation phase.
+ * Use st() if your code will only run during installation and never any other
+ * time. Use get_t() if your code could run in either circumstance.
+ *
+ * @see t()
+ * @see st()
+ * @ingroup sanitization
+ */
+function get_t() {
+ static $t;
+ // This is not converted to drupal_static because there is no point in
+ // resetting this as it can not change in the course of a request.
+ if (!isset($t)) {
+ $t = drupal_installation_attempted() ? 'st' : 't';
+ }
+ return $t;
+}
+
+/**
+ * Initializes all the defined language types.
+ */
+function drupal_language_initialize() {
+ $types = language_types();
+
+ // Ensure the language is correctly returned, even without multilanguage
+ // support. Also make sure we have a $language fallback, in case a language
+ // negotiation callback needs to do a full bootstrap.
+ // Useful for eg. XML/HTML 'lang' attributes.
+ $default = language_default();
+ foreach ($types as $type) {
+ $GLOBALS[$type] = $default;
+ }
+ if (drupal_multilingual()) {
+ include_once DRUPAL_ROOT . '/includes/language.inc';
+ foreach ($types as $type) {
+ $GLOBALS[$type] = language_initialize($type);
+ }
+ // Allow modules to react on language system initialization in multilingual
+ // environments.
+ bootstrap_invoke_all('language_init');
+ }
+}
+
+/**
+ * Returns a list of the built-in language types.
+ *
+ * @return
+ * An array of key-values pairs where the key is the language type and the
+ * value is its configurability.
+ */
+function drupal_language_types() {
+ return array(
+ LANGUAGE_TYPE_INTERFACE => TRUE,
+ LANGUAGE_TYPE_CONTENT => FALSE,
+ LANGUAGE_TYPE_URL => FALSE,
+ );
+}
+
+/**
+ * Returns TRUE if there is more than one language enabled.
+ *
+ * @return
+ * TRUE if more than one language is enabled.
+ */
+function drupal_multilingual() {
+ // The "language_count" variable stores the number of enabled languages to
+ // avoid unnecessarily querying the database when building the list of
+ // enabled languages on monolingual sites.
+ return variable_get('language_count', 1) > 1;
+}
+
+/**
+ * Returns an array of the available language types.
+ *
+ * @return
+ * An array of all language types where the keys of each are the language type
+ * name and its value is its configurability (TRUE/FALSE).
+ */
+function language_types() {
+ return array_keys(variable_get('language_types', drupal_language_types()));
+}
+
+/**
+ * Returns a list of installed languages, indexed by the specified key.
+ *
+ * @param $field
+ * (optional) The field to index the list with.
+ *
+ * @return
+ * An associative array, keyed on the values of $field.
+ * - If $field is 'weight' or 'enabled', the array is nested, with the outer
+ * array's values each being associative arrays with language codes as
+ * keys and language objects as values.
+ * - For all other values of $field, the array is only one level deep, and
+ * the array's values are language objects.
+ */
+function language_list($field = 'language') {
+ $languages = &drupal_static(__FUNCTION__);
+ // Init language list
+ if (!isset($languages)) {
+ if (drupal_multilingual() || module_exists('locale')) {
+ $languages['language'] = db_query('SELECT * FROM {languages} ORDER BY weight ASC, name ASC')->fetchAllAssoc('language');
+ // Users cannot uninstall the native English language. However, we allow
+ // it to be hidden from the installed languages. Therefore, at least one
+ // other language must be enabled then.
+ if (!$languages['language']['en']->enabled && !variable_get('language_native_enabled', TRUE)) {
+ unset($languages['language']['en']);
+ }
+ }
+ else {
+ // No locale module, so use the default language only.
+ $default = language_default();
+ $languages['language'][$default->language] = $default;
+ }
+ }
+
+ // Return the array indexed by the right field
+ if (!isset($languages[$field])) {
+ $languages[$field] = array();
+ foreach ($languages['language'] as $lang) {
+ // Some values should be collected into an array
+ if (in_array($field, array('enabled', 'weight'))) {
+ $languages[$field][$lang->$field][$lang->language] = $lang;
+ }
+ else {
+ $languages[$field][$lang->$field] = $lang;
+ }
+ }
+ }
+ return $languages[$field];
+}
+
+/**
+ * Returns the default language used on the site
+ *
+ * @param $property
+ * Optional property of the language object to return
+ */
+function language_default($property = NULL) {
+ $language = variable_get('language_default', (object) array('language' => 'en', 'name' => 'English', 'native' => 'English', 'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '', 'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''));
+ return $property ? $language->$property : $language;
+}
+
+/**
+ * Returns the requested URL path of the page being viewed.
+ *
+ * Examples:
+ * - http://example.com/node/306 returns "node/306".
+ * - http://example.com/drupalfolder/node/306 returns "node/306" while
+ * base_path() returns "/drupalfolder/".
+ * - http://example.com/path/alias (which is a path alias for node/306) returns
+ * "path/alias" as opposed to the internal path.
+ * - http://example.com/index.php returns an empty string (meaning: front page).
+ * - http://example.com/index.php?page=1 returns an empty string.
+ *
+ * @return
+ * The requested Drupal URL path.
+ *
+ * @see current_path()
+ */
+function request_path() {
+ static $path;
+
+ if (isset($path)) {
+ return $path;
+ }
+
+ if (isset($_GET['q']) && is_string($_GET['q'])) {
+ // This is a request with a ?q=foo/bar query string. $_GET['q'] is
+ // overwritten in drupal_path_initialize(), but request_path() is called
+ // very early in the bootstrap process, so the original value is saved in
+ // $path and returned in later calls.
+ $path = $_GET['q'];
+ }
+ elseif (isset($_SERVER['REQUEST_URI'])) {
+ // This request is either a clean URL, or 'index.php', or nonsense.
+ // Extract the path from REQUEST_URI.
+ $request_path = strtok($_SERVER['REQUEST_URI'], '?');
+ $base_path_len = strlen(rtrim(dirname($_SERVER['SCRIPT_NAME']), '\/'));
+ // Unescape and strip $base_path prefix, leaving q without a leading slash.
+ $path = substr(urldecode($request_path), $base_path_len + 1);
+ // If the path equals the script filename, either because 'index.php' was
+ // explicitly provided in the URL, or because the server added it to
+ // $_SERVER['REQUEST_URI'] even when it wasn't provided in the URL (some
+ // versions of Microsoft IIS do this), the front page should be served.
+ if ($path == basename($_SERVER['PHP_SELF'])) {
+ $path = '';
+ }
+ }
+ else {
+ // This is the front page.
+ $path = '';
+ }
+
+ // Under certain conditions Apache's RewriteRule directive prepends the value
+ // assigned to $_GET['q'] with a slash. Moreover we can always have a trailing
+ // slash in place, hence we need to normalize $_GET['q'].
+ $path = trim($path, '/');
+
+ return $path;
+}
+
+/**
+ * Returns a component of the current Drupal path.
+ *
+ * When viewing a page at the path "admin/structure/types", for example, arg(0)
+ * returns "admin", arg(1) returns "structure", and arg(2) returns "types".
+ *
+ * Avoid use of this function where possible, as resulting code is hard to
+ * read. In menu callback functions, attempt to use named arguments. See the
+ * explanation in menu.inc for how to construct callbacks that take arguments.
+ * When attempting to use this function to load an element from the current
+ * path, e.g. loading the node on a node page, use menu_get_object() instead.
+ *
+ * @param $index
+ * The index of the component, where each component is separated by a '/'
+ * (forward-slash), and where the first component has an index of 0 (zero).
+ * @param $path
+ * A path to break into components. Defaults to the path of the current page.
+ *
+ * @return
+ * The component specified by $index, or NULL if the specified component was
+ * not found. If called without arguments, it returns an array containing all
+ * the components of the current path.
+ */
+function arg($index = NULL, $path = NULL) {
+ // Even though $arguments doesn't need to be resettable for any functional
+ // reasons (the result of explode() does not depend on any run-time
+ // information), it should be resettable anyway in case a module needs to
+ // free up the memory used by it.
+ // Use the advanced drupal_static() pattern, since this is called very often.
+ static $drupal_static_fast;
+ if (!isset($drupal_static_fast)) {
+ $drupal_static_fast['arguments'] = &drupal_static(__FUNCTION__);
+ }
+ $arguments = &$drupal_static_fast['arguments'];
+
+ if (!isset($path)) {
+ $path = $_GET['q'];
+ }
+ if (!isset($arguments[$path])) {
+ $arguments[$path] = explode('/', $path);
+ }
+ if (!isset($index)) {
+ return $arguments[$path];
+ }
+ if (isset($arguments[$path][$index])) {
+ return $arguments[$path][$index];
+ }
+}
+
+/**
+ * Returns the IP address of the client machine.
+ *
+ * If Drupal is behind a reverse proxy, we use the X-Forwarded-For header
+ * instead of $_SERVER['REMOTE_ADDR'], which would be the IP address of
+ * the proxy server, and not the client's. The actual header name can be
+ * configured by the reverse_proxy_header variable.
+ *
+ * @return
+ * IP address of client machine, adjusted for reverse proxy and/or cluster
+ * environments.
+ */
+function ip_address() {
+ $ip_address = &drupal_static(__FUNCTION__);
+
+ if (!isset($ip_address)) {
+ $ip_address = $_SERVER['REMOTE_ADDR'];
+
+ if (variable_get('reverse_proxy', 0)) {
+ $reverse_proxy_header = variable_get('reverse_proxy_header', 'HTTP_X_FORWARDED_FOR');
+ if (!empty($_SERVER[$reverse_proxy_header])) {
+ // If an array of known reverse proxy IPs is provided, then trust
+ // the XFF header if request really comes from one of them.
+ $reverse_proxy_addresses = variable_get('reverse_proxy_addresses', array());
+
+ // Turn XFF header into an array.
+ $forwarded = explode(',', $_SERVER[$reverse_proxy_header]);
+
+ // Trim the forwarded IPs; they may have been delimited by commas and spaces.
+ $forwarded = array_map('trim', $forwarded);
+
+ // Tack direct client IP onto end of forwarded array.
+ $forwarded[] = $ip_address;
+
+ // Eliminate all trusted IPs.
+ $untrusted = array_diff($forwarded, $reverse_proxy_addresses);
+
+ // The right-most IP is the most specific we can trust.
+ $ip_address = array_pop($untrusted);
+ }
+ }
+ }
+
+ return $ip_address;
+}
+
+/**
+ * @addtogroup schemaapi
+ * @{
+ */
+
+/**
+ * Gets the schema definition of a table, or the whole database schema.
+ *
+ * The returned schema will include any modifications made by any
+ * module that implements hook_schema_alter().
+ *
+ * @param $table
+ * The name of the table. If not given, the schema of all tables is returned.
+ * @param $rebuild
+ * If true, the schema will be rebuilt instead of retrieved from the cache.
+ */
+function drupal_get_schema($table = NULL, $rebuild = FALSE) {
+ static $schema;
+
+ if ($rebuild || !isset($table)) {
+ $schema = drupal_get_complete_schema($rebuild);
+ }
+ elseif (!isset($schema)) {
+ $schema = new SchemaCache();
+ }
+
+ if (!isset($table)) {
+ return $schema;
+ }
+ if (isset($schema[$table])) {
+ return $schema[$table];
+ }
+ else {
+ return FALSE;
+ }
+}
+
+/**
+ * Extends DrupalCacheArray to allow for dynamic building of the schema cache.
+ */
+class SchemaCache extends DrupalCacheArray {
+
+ /**
+ * Constructs a SchemaCache object.
+ */
+ public function __construct() {
+ // Cache by request method.
+ parent::__construct('schema:runtime:' . ($_SERVER['REQUEST_METHOD'] == 'GET'), 'cache');
+ }
+
+ /**
+ * Overrides DrupalCacheArray::resolveCacheMiss().
+ */
+ protected function resolveCacheMiss($offset) {
+ $complete_schema = drupal_get_complete_schema();
+ $value = isset($complete_schema[$offset]) ? $complete_schema[$offset] : NULL;
+ $this->storage[$offset] = $value;
+ $this->persist($offset);
+ return $value;
+ }
+}
+
+/**
+ * Gets the whole database schema.
+ *
+ * The returned schema will include any modifications made by any
+ * module that implements hook_schema_alter().
+ *
+ * @param $rebuild
+ * If true, the schema will be rebuilt instead of retrieved from the cache.
+ */
+function drupal_get_complete_schema($rebuild = FALSE) {
+ static $schema = array();
+
+ if (empty($schema) || $rebuild) {
+ // Try to load the schema from cache.
+ if (!$rebuild && $cached = cache_get('schema')) {
+ $schema = $cached->data;
+ }
+ // Otherwise, rebuild the schema cache.
+ else {
+ $schema = array();
+ // Load the .install files to get hook_schema.
+ // On some databases this function may be called before bootstrap has
+ // been completed, so we force the functions we need to load just in case.
+ if (function_exists('module_load_all_includes')) {
+ // This function can be called very early in the bootstrap process, so
+ // we force the module_list() cache to be refreshed to ensure that it
+ // contains the complete list of modules before we go on to call
+ // module_load_all_includes().
+ module_list(TRUE);
+ module_load_all_includes('install');
+ }
+
+ require_once DRUPAL_ROOT . '/includes/common.inc';
+ // Invoke hook_schema for all modules.
+ foreach (module_implements('schema') as $module) {
+ // Cast the result of hook_schema() to an array, as a NULL return value
+ // would cause array_merge() to set the $schema variable to NULL as well.
+ // That would break modules which use $schema further down the line.
+ $current = (array) module_invoke($module, 'schema');
+ // Set 'module' and 'name' keys for each table, and remove descriptions,
+ // as they needlessly slow down cache_get() for every single request.
+ _drupal_schema_initialize($current, $module);
+ $schema = array_merge($schema, $current);
+ }
+
+ drupal_alter('schema', $schema);
+ // If the schema is empty, avoid saving it: some database engines require
+ // the schema to perform queries, and this could lead to infinite loops.
+ if (!empty($schema) && (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL)) {
+ cache_set('schema', $schema);
+ }
+ if ($rebuild) {
+ cache_clear_all('schema:', 'cache', TRUE);
+ }
+ }
+ }
+
+ return $schema;
+}
+
+/**
+ * @} End of "addtogroup schemaapi".
+ */
+
+
+/**
+ * @addtogroup registry
+ * @{
+ */
+
+/**
+ * Confirms that an interface is available.
+ *
+ * This function is rarely called directly. Instead, it is registered as an
+ * spl_autoload() handler, and PHP calls it for us when necessary.
+ *
+ * @param $interface
+ * The name of the interface to check or load.
+ *
+ * @return
+ * TRUE if the interface is currently available, FALSE otherwise.
+ */
+function drupal_autoload_interface($interface) {
+ return _registry_check_code('interface', $interface);
+}
+
+/**
+ * Confirms that a class is available.
+ *
+ * This function is rarely called directly. Instead, it is registered as an
+ * spl_autoload() handler, and PHP calls it for us when necessary.
+ *
+ * @param $class
+ * The name of the class to check or load.
+ *
+ * @return
+ * TRUE if the class is currently available, FALSE otherwise.
+ */
+function drupal_autoload_class($class) {
+ return _registry_check_code('class', $class);
+}
+
+/**
+ * Checks for a resource in the registry.
+ *
+ * @param $type
+ * The type of resource we are looking up, or one of the constants
+ * REGISTRY_RESET_LOOKUP_CACHE or REGISTRY_WRITE_LOOKUP_CACHE, which
+ * signal that we should reset or write the cache, respectively.
+ * @param $name
+ * The name of the resource, or NULL if either of the REGISTRY_* constants
+ * is passed in.
+ *
+ * @return
+ * TRUE if the resource was found, FALSE if not.
+ * NULL if either of the REGISTRY_* constants is passed in as $type.
+ */
+function _registry_check_code($type, $name = NULL) {
+ static $lookup_cache, $cache_update_needed;
+
+ if ($type == 'class' && class_exists($name) || $type == 'interface' && interface_exists($name)) {
+ return TRUE;
+ }
+
+ if (!isset($lookup_cache)) {
+ $lookup_cache = array();
+ if ($cache = cache_get('lookup_cache', 'cache_bootstrap')) {
+ $lookup_cache = $cache->data;
+ }
+ }
+
+ // When we rebuild the registry, we need to reset this cache so
+ // we don't keep lookups for resources that changed during the rebuild.
+ if ($type == REGISTRY_RESET_LOOKUP_CACHE) {
+ $cache_update_needed = TRUE;
+ $lookup_cache = NULL;
+ return;
+ }
+
+ // Called from drupal_page_footer, we write to permanent storage if there
+ // changes to the lookup cache for this request.
+ if ($type == REGISTRY_WRITE_LOOKUP_CACHE) {
+ if ($cache_update_needed) {
+ cache_set('lookup_cache', $lookup_cache, 'cache_bootstrap');
+ }
+ return;
+ }
+
+ // $type is either 'interface' or 'class', so we only need the first letter to
+ // keep the cache key unique.
+ $cache_key = $type[0] . $name;
+ if (isset($lookup_cache[$cache_key])) {
+ if ($lookup_cache[$cache_key]) {
+ require_once DRUPAL_ROOT . '/' . $lookup_cache[$cache_key];
+ }
+ return (bool) $lookup_cache[$cache_key];
+ }
+
+ // This function may get called when the default database is not active, but
+ // there is no reason we'd ever want to not use the default database for
+ // this query.
+ $file = Database::getConnection('default', 'default')->query("SELECT filename FROM {registry} WHERE name = :name AND type = :type", array(
+ ':name' => $name,
+ ':type' => $type,
+ ))
+ ->fetchField();
+
+ // Flag that we've run a lookup query and need to update the cache.
+ $cache_update_needed = TRUE;
+
+ // Misses are valuable information worth caching, so cache even if
+ // $file is FALSE.
+ $lookup_cache[$cache_key] = $file;
+
+ if ($file) {
+ require_once DRUPAL_ROOT . '/' . $file;
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+}
+
+/**
+ * Rescans all enabled modules and rebuilds the registry.
+ *
+ * Rescans all code in modules or includes directories, storing the location of
+ * each interface or class in the database.
+ */
+function registry_rebuild() {
+ system_rebuild_module_data();
+ registry_update();
+}
+
+/**
+ * Updates the registry based on the latest files listed in the database.
+ *
+ * This function should be used when system_rebuild_module_data() does not need
+ * to be called, because it is already known that the list of files in the
+ * {system} table matches those in the file system.
+ *
+ * @return
+ * TRUE if the registry was rebuilt, FALSE if another thread was rebuilding
+ * in parallel and the current thread just waited for completion.
+ *
+ * @see registry_rebuild()
+ */
+function registry_update() {
+ // install_system_module() calls module_enable() which calls into this
+ // function during initial system installation, so the lock system is neither
+ // loaded nor does its storage exist yet.
+ $in_installer = drupal_installation_attempted();
+ if (!$in_installer && !lock_acquire(__FUNCTION__)) {
+ // Another request got the lock, wait for it to finish.
+ lock_wait(__FUNCTION__);
+ return FALSE;
+ }
+
+ require_once DRUPAL_ROOT . '/includes/registry.inc';
+ _registry_update();
+
+ if (!$in_installer) {
+ lock_release(__FUNCTION__);
+ }
+ return TRUE;
+}
+
+/**
+ * @} End of "addtogroup registry".
+ */
+
+/**
+ * Provides central static variable storage.
+ *
+ * All functions requiring a static variable to persist or cache data within
+ * a single page request are encouraged to use this function unless it is
+ * absolutely certain that the static variable will not need to be reset during
+ * the page request. By centralizing static variable storage through this
+ * function, other functions can rely on a consistent API for resetting any
+ * other function's static variables.
+ *
+ * Example:
+ * @code
+ * function language_list($field = 'language') {
+ * $languages = &drupal_static(__FUNCTION__);
+ * if (!isset($languages)) {
+ * // If this function is being called for the first time after a reset,
+ * // query the database and execute any other code needed to retrieve
+ * // information about the supported languages.
+ * ...
+ * }
+ * if (!isset($languages[$field])) {
+ * // If this function is being called for the first time for a particular
+ * // index field, then execute code needed to index the information already
+ * // available in $languages by the desired field.
+ * ...
+ * }
+ * // Subsequent invocations of this function for a particular index field
+ * // skip the above two code blocks and quickly return the already indexed
+ * // information.
+ * return $languages[$field];
+ * }
+ * function locale_translate_overview_screen() {
+ * // When building the content for the translations overview page, make
+ * // sure to get completely fresh information about the supported languages.
+ * drupal_static_reset('language_list');
+ * ...
+ * }
+ * @endcode
+ *
+ * In a few cases, a function can have certainty that there is no legitimate
+ * use-case for resetting that function's static variable. This is rare,
+ * because when writing a function, it's hard to forecast all the situations in
+ * which it will be used. A guideline is that if a function's static variable
+ * does not depend on any information outside of the function that might change
+ * during a single page request, then it's ok to use the "static" keyword
+ * instead of the drupal_static() function.
+ *
+ * Example:
+ * @code
+ * function actions_do(...) {
+ * // $stack tracks the number of recursive calls.
+ * static $stack;
+ * $stack++;
+ * if ($stack > variable_get('actions_max_stack', 35)) {
+ * ...
+ * return;
+ * }
+ * ...
+ * $stack--;
+ * }
+ * @endcode
+ *
+ * In a few cases, a function needs a resettable static variable, but the
+ * function is called many times (100+) during a single page request, so
+ * every microsecond of execution time that can be removed from the function
+ * counts. These functions can use a more cumbersome, but faster variant of
+ * calling drupal_static(). It works by storing the reference returned by
+ * drupal_static() in the calling function's own static variable, thereby
+ * removing the need to call drupal_static() for each iteration of the function.
+ * Conceptually, it replaces:
+ * @code
+ * $foo = &drupal_static(__FUNCTION__);
+ * @endcode
+ * with:
+ * @code
+ * // Unfortunately, this does not work.
+ * static $foo = &drupal_static(__FUNCTION__);
+ * @endcode
+ * However, the above line of code does not work, because PHP only allows static
+ * variables to be initializied by literal values, and does not allow static
+ * variables to be assigned to references.
+ * - http://php.net/manual/language.variables.scope.php#language.variables.scope.static
+ * - http://php.net/manual/language.variables.scope.php#language.variables.scope.references
+ * The example below shows the syntax needed to work around both limitations.
+ * For benchmarks and more information, see http://drupal.org/node/619666.
+ *
+ * Example:
+ * @code
+ * function user_access($string, $account = NULL) {
+ * // Use the advanced drupal_static() pattern, since this is called very often.
+ * static $drupal_static_fast;
+ * if (!isset($drupal_static_fast)) {
+ * $drupal_static_fast['perm'] = &drupal_static(__FUNCTION__);
+ * }
+ * $perm = &$drupal_static_fast['perm'];
+ * ...
+ * }
+ * @endcode
+ *
+ * @param $name
+ * Globally unique name for the variable. For a function with only one static,
+ * variable, the function name (e.g. via the PHP magic __FUNCTION__ constant)
+ * is recommended. For a function with multiple static variables add a
+ * distinguishing suffix to the function name for each one.
+ * @param $default_value
+ * Optional default value.
+ * @param $reset
+ * TRUE to reset a specific named variable, or all variables if $name is NULL.
+ * Resetting every variable should only be used, for example, for running
+ * unit tests with a clean environment. Should be used only though via
+ * function drupal_static_reset() and the return value should not be used in
+ * this case.
+ *
+ * @return
+ * Returns a variable by reference.
+ *
+ * @see drupal_static_reset()
+ */
+function &drupal_static($name, $default_value = NULL, $reset = FALSE) {
+ static $data = array(), $default = array();
+ // First check if dealing with a previously defined static variable.
+ if (isset($data[$name]) || array_key_exists($name, $data)) {
+ // Non-NULL $name and both $data[$name] and $default[$name] statics exist.
+ if ($reset) {
+ // Reset pre-existing static variable to its default value.
+ $data[$name] = $default[$name];
+ }
+ return $data[$name];
+ }
+ // Neither $data[$name] nor $default[$name] static variables exist.
+ if (isset($name)) {
+ if ($reset) {
+ // Reset was called before a default is set and yet a variable must be
+ // returned.
+ return $data;
+ }
+ // First call with new non-NULL $name. Initialize a new static variable.
+ $default[$name] = $data[$name] = $default_value;
+ return $data[$name];
+ }
+ // Reset all: ($name == NULL). This needs to be done one at a time so that
+ // references returned by earlier invocations of drupal_static() also get
+ // reset.
+ foreach ($default as $name => $value) {
+ $data[$name] = $value;
+ }
+ // As the function returns a reference, the return should always be a
+ // variable.
+ return $data;
+}
+
+/**
+ * Resets one or all centrally stored static variable(s).
+ *
+ * @param $name
+ * Name of the static variable to reset. Omit to reset all variables.
+ */
+function drupal_static_reset($name = NULL) {
+ drupal_static($name, NULL, TRUE);
+}
+
+/**
+ * Detects whether the current script is running in a command-line environment.
+ */
+function drupal_is_cli() {
+ return (!isset($_SERVER['SERVER_SOFTWARE']) && (php_sapi_name() == 'cli' || (is_numeric($_SERVER['argc']) && $_SERVER['argc'] > 0)));
+}
+
+/**
+ * Formats text for emphasized display in a placeholder inside a sentence.
+ *
+ * Used automatically by format_string().
+ *
+ * @param $text
+ * The text to format (plain-text).
+ *
+ * @return
+ * The formatted text (html).
+ */
+function drupal_placeholder($text) {
+ return '<em class="placeholder">' . check_plain($text) . '</em>';
+}
+
+/**
+ * Registers a function for execution on shutdown.
+ *
+ * Wrapper for register_shutdown_function() that catches thrown exceptions to
+ * avoid "Exception thrown without a stack frame in Unknown".
+ *
+ * @param $callback
+ * The shutdown function to register.
+ * @param ...
+ * Additional arguments to pass to the shutdown function.
+ *
+ * @return
+ * Array of shutdown functions to be executed.
+ *
+ * @see register_shutdown_function()
+ * @ingroup php_wrappers
+ */
+function &drupal_register_shutdown_function($callback = NULL) {
+ // We cannot use drupal_static() here because the static cache is reset during
+ // batch processing, which breaks batch handling.
+ static $callbacks = array();
+
+ if (isset($callback)) {
+ // Only register the internal shutdown function once.
+ if (empty($callbacks)) {
+ register_shutdown_function('_drupal_shutdown_function');
+ }
+ $args = func_get_args();
+ array_shift($args);
+ // Save callback and arguments
+ $callbacks[] = array('callback' => $callback, 'arguments' => $args);
+ }
+ return $callbacks;
+}
+
+/**
+ * Executes registered shutdown functions.
+ */
+function _drupal_shutdown_function() {
+ $callbacks = &drupal_register_shutdown_function();
+
+ // Set the CWD to DRUPAL_ROOT as it is not guaranteed to be the same as it
+ // was in the normal context of execution.
+ chdir(DRUPAL_ROOT);
+
+ try {
+ while (list($key, $callback) = each($callbacks)) {
+ call_user_func_array($callback['callback'], $callback['arguments']);
+ }
+ }
+ catch (Exception $exception) {
+ // If we are displaying errors, then do so with no possibility of a further uncaught exception being thrown.
+ require_once DRUPAL_ROOT . '/includes/errors.inc';
+ if (error_displayable()) {
+ print '<h1>Uncaught exception thrown in shutdown function.</h1>';
+ print '<p>' . _drupal_render_exception_safe($exception) . '</p><hr />';
+ }
+ }
+}
+
+/**
+ * Compares the memory required for an operation to the available memory.
+ *
+ * @param $required
+ * The memory required for the operation, expressed as a number of bytes with
+ * optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8bytes,
+ * 9mbytes).
+ * @param $memory_limit
+ * (optional) The memory limit for the operation, expressed as a number of
+ * bytes with optional SI or IEC binary unit prefix (e.g. 2, 3K, 5MB, 10G,
+ * 6GiB, 8bytes, 9mbytes). If no value is passed, the current PHP
+ * memory_limit will be used. Defaults to NULL.
+ *
+ * @return
+ * TRUE if there is sufficient memory to allow the operation, or FALSE
+ * otherwise.
+ */
+function drupal_check_memory_limit($required, $memory_limit = NULL) {
+ if (!isset($memory_limit)) {
+ $memory_limit = ini_get('memory_limit');
+ }
+
+ // There is sufficient memory if:
+ // - No memory limit is set.
+ // - The memory limit is set to unlimited (-1).
+ // - The memory limit is greater than the memory required for the operation.
+ return ((!$memory_limit) || ($memory_limit == -1) || (parse_size($memory_limit) >= parse_size($required)));
+}
diff --git a/kolab.org/www/drupal-7.26/includes/cache-install.inc b/kolab.org/www/drupal-7.26/includes/cache-install.inc
new file mode 100644
index 0000000..9e0dd01
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/cache-install.inc
@@ -0,0 +1,74 @@
+<?php
+
+/**
+ * @file
+ * Provides a stub cache implementation to be used during installation.
+ */
+
+/**
+ * Defines a stub cache implementation to be used during installation.
+ *
+ * The stub implementation is needed when database access is not yet available.
+ * Because Drupal's caching system never requires that cached data be present,
+ * these stub functions can short-circuit the process and sidestep the need for
+ * any persistent storage. Obviously, using this cache implementation during
+ * normal operations would have a negative impact on performance.
+ */
+class DrupalFakeCache extends DrupalDatabaseCache implements DrupalCacheInterface {
+
+ /**
+ * Overrides DrupalDatabaseCache::get().
+ */
+ function get($cid) {
+ return FALSE;
+ }
+
+ /**
+ * Overrides DrupalDatabaseCache::getMultiple().
+ */
+ function getMultiple(&$cids) {
+ return array();
+ }
+
+ /**
+ * Overrides DrupalDatabaseCache::set().
+ */
+ function set($cid, $data, $expire = CACHE_PERMANENT) {
+ }
+
+ /**
+ * Overrides DrupalDatabaseCache::clear().
+ */
+ function clear($cid = NULL, $wildcard = FALSE) {
+ // If there is a database cache, attempt to clear it whenever possible. The
+ // reason for doing this is that the database cache can accumulate data
+ // during installation due to any full bootstraps that may occur at the
+ // same time (for example, Ajax requests triggered by the installer). If we
+ // didn't try to clear it whenever this function is called, the data in the
+ // cache would become stale; for example, the installer sometimes calls
+ // variable_set(), which updates the {variable} table and then clears the
+ // cache to make sure that the next page request picks up the new value.
+ // Not actually clearing the cache here therefore leads old variables to be
+ // loaded on the first page requests after installation, which can cause
+ // subtle bugs, some of which would not be fixed unless the site
+ // administrator cleared the cache manually.
+ try {
+ if (class_exists('Database')) {
+ parent::clear($cid, $wildcard);
+ }
+ }
+ // If the attempt at clearing the cache causes an error, that means that
+ // either the database connection is not set up yet or the relevant cache
+ // table in the database has not yet been created, so we can safely do
+ // nothing here.
+ catch (Exception $e) {
+ }
+ }
+
+ /**
+ * Overrides DrupalDatabaseCache::isEmpty().
+ */
+ function isEmpty() {
+ return TRUE;
+ }
+}
diff --git a/kolab.org/www/drupal-7.26/includes/cache.inc b/kolab.org/www/drupal-7.26/includes/cache.inc
new file mode 100644
index 0000000..09f4d75
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/cache.inc
@@ -0,0 +1,575 @@
+<?php
+
+/**
+ * @file
+ * Functions and interfaces for cache handling.
+ */
+
+/**
+ * Gets the cache object for a cache bin.
+ *
+ * By default, this returns an instance of the DrupalDatabaseCache class.
+ * Classes implementing DrupalCacheInterface can register themselves both as a
+ * default implementation and for specific bins.
+ *
+ * @param $bin
+ * The cache bin for which the cache object should be returned.
+ * @return DrupalCacheInterface
+ * The cache object associated with the specified bin.
+ *
+ * @see DrupalCacheInterface
+ */
+function _cache_get_object($bin) {
+ // We do not use drupal_static() here because we do not want to change the
+ // storage of a cache bin mid-request.
+ static $cache_objects;
+ if (!isset($cache_objects[$bin])) {
+ $class = variable_get('cache_class_' . $bin);
+ if (!isset($class)) {
+ $class = variable_get('cache_default_class', 'DrupalDatabaseCache');
+ }
+ $cache_objects[$bin] = new $class($bin);
+ }
+ return $cache_objects[$bin];
+}
+
+/**
+ * Returns data from the persistent cache.
+ *
+ * Data may be stored as either plain text or as serialized data. cache_get
+ * will automatically return unserialized objects and arrays.
+ *
+ * @param $cid
+ * The cache ID of the data to retrieve.
+ * @param $bin
+ * The cache bin to store the data in. Valid core values are 'cache_block',
+ * 'cache_bootstrap', 'cache_field', 'cache_filter', 'cache_form',
+ * 'cache_menu', 'cache_page', 'cache_path', 'cache_update' or 'cache' for
+ * the default cache.
+ *
+ * @return
+ * The cache or FALSE on failure.
+ *
+ * @see cache_set()
+ */
+function cache_get($cid, $bin = 'cache') {
+ return _cache_get_object($bin)->get($cid);
+}
+
+/**
+ * Returns data from the persistent cache when given an array of cache IDs.
+ *
+ * @param $cids
+ * An array of cache IDs for the data to retrieve. This is passed by
+ * reference, and will have the IDs successfully returned from cache removed.
+ * @param $bin
+ * The cache bin where the data is stored.
+ *
+ * @return
+ * An array of the items successfully returned from cache indexed by cid.
+ */
+function cache_get_multiple(array &$cids, $bin = 'cache') {
+ return _cache_get_object($bin)->getMultiple($cids);
+}
+
+/**
+ * Stores data in the persistent cache.
+ *
+ * The persistent cache is split up into several cache bins. In the default
+ * cache implementation, each cache bin corresponds to a database table by the
+ * same name. Other implementations might want to store several bins in data
+ * structures that get flushed together. While it is not a problem for most
+ * cache bins if the entries in them are flushed before their expire time, some
+ * might break functionality or are extremely expensive to recalculate. The
+ * other bins are expired automatically by core. Contributed modules can add
+ * additional bins and get them expired automatically by implementing
+ * hook_flush_caches().
+ *
+ * The reasons for having several bins are as follows:
+ * - Smaller bins mean smaller database tables and allow for faster selects and
+ * inserts.
+ * - We try to put fast changing cache items and rather static ones into
+ * different bins. The effect is that only the fast changing bins will need a
+ * lot of writes to disk. The more static bins will also be better cacheable
+ * with MySQL's query cache.
+ *
+ * @param $cid
+ * The cache ID of the data to store.
+ * @param $data
+ * The data to store in the cache. Complex data types will be automatically
+ * serialized before insertion. Strings will be stored as plain text and are
+ * not serialized.
+ * @param $bin
+ * The cache bin to store the data in. Valid core values are:
+ * - cache: (default) Generic cache storage bin (used for theme registry,
+ * locale date, list of simpletest tests, etc.).
+ * - cache_block: Stores the content of various blocks.
+ * - cache_bootstrap: Stores the class registry, the system list of modules,
+ * the list of which modules implement which hooks, and the Drupal variable
+ * list.
+ * - cache_field: Stores the field data belonging to a given object.
+ * - cache_filter: Stores filtered pieces of content.
+ * - cache_form: Stores multistep forms. Flushing this bin means that some
+ * forms displayed to users lose their state and the data already submitted
+ * to them. This bin should not be flushed before its expired time.
+ * - cache_menu: Stores the structure of visible navigation menus per page.
+ * - cache_page: Stores generated pages for anonymous users. It is flushed
+ * very often, whenever a page changes, at least for every node and comment
+ * submission. This is the only bin affected by the page cache setting on
+ * the administrator panel.
+ * - cache_path: Stores the system paths that have an alias.
+ * @param $expire
+ * One of the following values:
+ * - CACHE_PERMANENT: Indicates that the item should never be removed unless
+ * explicitly told to using cache_clear_all() with a cache ID.
+ * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
+ * general cache wipe.
+ * - A Unix timestamp: Indicates that the item should be kept at least until
+ * the given time, after which it behaves like CACHE_TEMPORARY.
+ *
+ * @see _update_cache_set()
+ * @see cache_get()
+ */
+function cache_set($cid, $data, $bin = 'cache', $expire = CACHE_PERMANENT) {
+ return _cache_get_object($bin)->set($cid, $data, $expire);
+}
+
+/**
+ * Expires data from the cache.
+ *
+ * If called with the arguments $cid and $bin set to NULL or omitted, then
+ * expirable entries will be cleared from the cache_page and cache_block bins,
+ * and the $wildcard argument is ignored.
+ *
+ * @param $cid
+ * If set, the cache ID or an array of cache IDs. Otherwise, all cache entries
+ * that can expire are deleted. The $wildcard argument will be ignored if set
+ * to NULL.
+ * @param $bin
+ * If set, the cache bin to delete from. Mandatory argument if $cid is set.
+ * @param $wildcard
+ * If TRUE, the $cid argument must contain a string value and cache IDs
+ * starting with $cid are deleted in addition to the exact cache ID specified
+ * by $cid. If $wildcard is TRUE and $cid is '*', the entire cache is emptied.
+ */
+function cache_clear_all($cid = NULL, $bin = NULL, $wildcard = FALSE) {
+ if (!isset($cid) && !isset($bin)) {
+ // Clear the block cache first, so stale data will
+ // not end up in the page cache.
+ if (module_exists('block')) {
+ cache_clear_all(NULL, 'cache_block');
+ }
+ cache_clear_all(NULL, 'cache_page');
+ return;
+ }
+ return _cache_get_object($bin)->clear($cid, $wildcard);
+}
+
+/**
+ * Checks if a cache bin is empty.
+ *
+ * A cache bin is considered empty if it does not contain any valid data for any
+ * cache ID.
+ *
+ * @param $bin
+ * The cache bin to check.
+ *
+ * @return
+ * TRUE if the cache bin specified is empty.
+ */
+function cache_is_empty($bin) {
+ return _cache_get_object($bin)->isEmpty();
+}
+
+/**
+ * Defines an interface for cache implementations.
+ *
+ * All cache implementations have to implement this interface.
+ * DrupalDatabaseCache provides the default implementation, which can be
+ * consulted as an example.
+ *
+ * To make Drupal use your implementation for a certain cache bin, you have to
+ * set a variable with the name of the cache bin as its key and the name of
+ * your class as its value. For example, if your implementation of
+ * DrupalCacheInterface was called MyCustomCache, the following line would make
+ * Drupal use it for the 'cache_page' bin:
+ * @code
+ * variable_set('cache_class_cache_page', 'MyCustomCache');
+ * @endcode
+ *
+ * Additionally, you can register your cache implementation to be used by
+ * default for all cache bins by setting the variable 'cache_default_class' to
+ * the name of your implementation of the DrupalCacheInterface, e.g.
+ * @code
+ * variable_set('cache_default_class', 'MyCustomCache');
+ * @endcode
+ *
+ * To implement a completely custom cache bin, use the same variable format:
+ * @code
+ * variable_set('cache_class_custom_bin', 'MyCustomCache');
+ * @endcode
+ * To access your custom cache bin, specify the name of the bin when storing
+ * or retrieving cached data:
+ * @code
+ * cache_set($cid, $data, 'custom_bin', $expire);
+ * cache_get($cid, 'custom_bin');
+ * @endcode
+ *
+ * @see _cache_get_object()
+ * @see DrupalDatabaseCache
+ */
+interface DrupalCacheInterface {
+
+ /**
+ * Returns data from the persistent cache.
+ *
+ * Data may be stored as either plain text or as serialized data. cache_get()
+ * will automatically return unserialized objects and arrays.
+ *
+ * @param $cid
+ * The cache ID of the data to retrieve.
+ *
+ * @return
+ * The cache or FALSE on failure.
+ */
+ function get($cid);
+
+ /**
+ * Returns data from the persistent cache when given an array of cache IDs.
+ *
+ * @param $cids
+ * An array of cache IDs for the data to retrieve. This is passed by
+ * reference, and will have the IDs successfully returned from cache
+ * removed.
+ *
+ * @return
+ * An array of the items successfully returned from cache indexed by cid.
+ */
+ function getMultiple(&$cids);
+
+ /**
+ * Stores data in the persistent cache.
+ *
+ * @param $cid
+ * The cache ID of the data to store.
+ * @param $data
+ * The data to store in the cache. Complex data types will be automatically
+ * serialized before insertion.
+ * Strings will be stored as plain text and not serialized.
+ * @param $expire
+ * One of the following values:
+ * - CACHE_PERMANENT: Indicates that the item should never be removed unless
+ * explicitly told to using cache_clear_all() with a cache ID.
+ * - CACHE_TEMPORARY: Indicates that the item should be removed at the next
+ * general cache wipe.
+ * - A Unix timestamp: Indicates that the item should be kept at least until
+ * the given time, after which it behaves like CACHE_TEMPORARY.
+ */
+ function set($cid, $data, $expire = CACHE_PERMANENT);
+
+
+ /**
+ * Expires data from the cache.
+ *
+ * If called without arguments, expirable entries will be cleared from the
+ * cache_page and cache_block bins.
+ *
+ * @param $cid
+ * If set, the cache ID or an array of cache IDs. Otherwise, all cache
+ * entries that can expire are deleted. The $wildcard argument will be
+ * ignored if set to NULL.
+ * @param $wildcard
+ * If TRUE, the $cid argument must contain a string value and cache IDs
+ * starting with $cid are deleted in addition to the exact cache ID
+ * specified by $cid. If $wildcard is TRUE and $cid is '*', the entire
+ * cache is emptied.
+ */
+ function clear($cid = NULL, $wildcard = FALSE);
+
+ /**
+ * Checks if a cache bin is empty.
+ *
+ * A cache bin is considered empty if it does not contain any valid data for
+ * any cache ID.
+ *
+ * @return
+ * TRUE if the cache bin specified is empty.
+ */
+ function isEmpty();
+}
+
+/**
+ * Defines a default cache implementation.
+ *
+ * This is Drupal's default cache implementation. It uses the database to store
+ * cached data. Each cache bin corresponds to a database table by the same name.
+ */
+class DrupalDatabaseCache implements DrupalCacheInterface {
+ protected $bin;
+
+ /**
+ * Constructs a DrupalDatabaseCache object.
+ *
+ * @param $bin
+ * The cache bin for which the object is created.
+ */
+ function __construct($bin) {
+ $this->bin = $bin;
+ }
+
+ /**
+ * Implements DrupalCacheInterface::get().
+ */
+ function get($cid) {
+ $cids = array($cid);
+ $cache = $this->getMultiple($cids);
+ return reset($cache);
+ }
+
+ /**
+ * Implements DrupalCacheInterface::getMultiple().
+ */
+ function getMultiple(&$cids) {
+ try {
+ // Garbage collection necessary when enforcing a minimum cache lifetime.
+ $this->garbageCollection($this->bin);
+
+ // When serving cached pages, the overhead of using db_select() was found
+ // to add around 30% overhead to the request. Since $this->bin is a
+ // variable, this means the call to db_query() here uses a concatenated
+ // string. This is highly discouraged under any other circumstances, and
+ // is used here only due to the performance overhead we would incur
+ // otherwise. When serving an uncached page, the overhead of using
+ // db_select() is a much smaller proportion of the request.
+ $result = db_query('SELECT cid, data, created, expire, serialized FROM {' . db_escape_table($this->bin) . '} WHERE cid IN (:cids)', array(':cids' => $cids));
+ $cache = array();
+ foreach ($result as $item) {
+ $item = $this->prepareItem($item);
+ if ($item) {
+ $cache[$item->cid] = $item;
+ }
+ }
+ $cids = array_diff($cids, array_keys($cache));
+ return $cache;
+ }
+ catch (Exception $e) {
+ // If the database is never going to be available, cache requests should
+ // return FALSE in order to allow exception handling to occur.
+ return array();
+ }
+ }
+
+ /**
+ * Garbage collection for get() and getMultiple().
+ *
+ * @param $bin
+ * The bin being requested.
+ */
+ protected function garbageCollection() {
+ $cache_lifetime = variable_get('cache_lifetime', 0);
+
+ // Clean-up the per-user cache expiration session data, so that the session
+ // handler can properly clean-up the session data for anonymous users.
+ if (isset($_SESSION['cache_expiration'])) {
+ $expire = REQUEST_TIME - $cache_lifetime;
+ foreach ($_SESSION['cache_expiration'] as $bin => $timestamp) {
+ if ($timestamp < $expire) {
+ unset($_SESSION['cache_expiration'][$bin]);
+ }
+ }
+ if (!$_SESSION['cache_expiration']) {
+ unset($_SESSION['cache_expiration']);
+ }
+ }
+
+ // Garbage collection of temporary items is only necessary when enforcing
+ // a minimum cache lifetime.
+ if (!$cache_lifetime) {
+ return;
+ }
+ // When cache lifetime is in force, avoid running garbage collection too
+ // often since this will remove temporary cache items indiscriminately.
+ $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
+ if ($cache_flush && ($cache_flush + $cache_lifetime <= REQUEST_TIME)) {
+ // Reset the variable immediately to prevent a meltdown in heavy load situations.
+ variable_set('cache_flush_' . $this->bin, 0);
+ // Time to flush old cache data
+ db_delete($this->bin)
+ ->condition('expire', CACHE_PERMANENT, '<>')
+ ->condition('expire', $cache_flush, '<=')
+ ->execute();
+ }
+ }
+
+ /**
+ * Prepares a cached item.
+ *
+ * Checks that items are either permanent or did not expire, and unserializes
+ * data as appropriate.
+ *
+ * @param $cache
+ * An item loaded from cache_get() or cache_get_multiple().
+ *
+ * @return
+ * The item with data unserialized as appropriate or FALSE if there is no
+ * valid item to load.
+ */
+ protected function prepareItem($cache) {
+ global $user;
+
+ if (!isset($cache->data)) {
+ return FALSE;
+ }
+ // If the cached data is temporary and subject to a per-user minimum
+ // lifetime, compare the cache entry timestamp with the user session
+ // cache_expiration timestamp. If the cache entry is too old, ignore it.
+ if ($cache->expire != CACHE_PERMANENT && variable_get('cache_lifetime', 0) && isset($_SESSION['cache_expiration'][$this->bin]) && $_SESSION['cache_expiration'][$this->bin] > $cache->created) {
+ // Ignore cache data that is too old and thus not valid for this user.
+ return FALSE;
+ }
+
+ // If the data is permanent or not subject to a minimum cache lifetime,
+ // unserialize and return the cached data.
+ if ($cache->serialized) {
+ $cache->data = unserialize($cache->data);
+ }
+
+ return $cache;
+ }
+
+ /**
+ * Implements DrupalCacheInterface::set().
+ */
+ function set($cid, $data, $expire = CACHE_PERMANENT) {
+ $fields = array(
+ 'serialized' => 0,
+ 'created' => REQUEST_TIME,
+ 'expire' => $expire,
+ );
+ if (!is_string($data)) {
+ $fields['data'] = serialize($data);
+ $fields['serialized'] = 1;
+ }
+ else {
+ $fields['data'] = $data;
+ $fields['serialized'] = 0;
+ }
+
+ try {
+ db_merge($this->bin)
+ ->key(array('cid' => $cid))
+ ->fields($fields)
+ ->execute();
+ }
+ catch (Exception $e) {
+ // The database may not be available, so we'll ignore cache_set requests.
+ }
+ }
+
+ /**
+ * Implements DrupalCacheInterface::clear().
+ */
+ function clear($cid = NULL, $wildcard = FALSE) {
+ global $user;
+
+ if (empty($cid)) {
+ if (variable_get('cache_lifetime', 0)) {
+ // We store the time in the current user's session. We then simulate
+ // that the cache was flushed for this user by not returning cached
+ // data that was cached before the timestamp.
+ $_SESSION['cache_expiration'][$this->bin] = REQUEST_TIME;
+
+ $cache_flush = variable_get('cache_flush_' . $this->bin, 0);
+ if ($cache_flush == 0) {
+ // This is the first request to clear the cache, start a timer.
+ variable_set('cache_flush_' . $this->bin, REQUEST_TIME);
+ }
+ elseif (REQUEST_TIME > ($cache_flush + variable_get('cache_lifetime', 0))) {
+ // Clear the cache for everyone, cache_lifetime seconds have
+ // passed since the first request to clear the cache.
+ db_delete($this->bin)
+ ->condition('expire', CACHE_PERMANENT, '<>')
+ ->condition('expire', REQUEST_TIME, '<')
+ ->execute();
+ variable_set('cache_flush_' . $this->bin, 0);
+ }
+ }
+ else {
+ // No minimum cache lifetime, flush all temporary cache entries now.
+ db_delete($this->bin)
+ ->condition('expire', CACHE_PERMANENT, '<>')
+ ->condition('expire', REQUEST_TIME, '<')
+ ->execute();
+ }
+ }
+ else {
+ if ($wildcard) {
+ if ($cid == '*') {
+ // Check if $this->bin is a cache table before truncating. Other
+ // cache_clear_all() operations throw a PDO error in this situation,
+ // so we don't need to verify them first. This ensures that non-cache
+ // tables cannot be truncated accidentally.
+ if ($this->isValidBin()) {
+ db_truncate($this->bin)->execute();
+ }
+ else {
+ throw new Exception(t('Invalid or missing cache bin specified: %bin', array('%bin' => $this->bin)));
+ }
+ }
+ else {
+ db_delete($this->bin)
+ ->condition('cid', db_like($cid) . '%', 'LIKE')
+ ->execute();
+ }
+ }
+ elseif (is_array($cid)) {
+ // Delete in chunks when a large array is passed.
+ do {
+ db_delete($this->bin)
+ ->condition('cid', array_splice($cid, 0, 1000), 'IN')
+ ->execute();
+ }
+ while (count($cid));
+ }
+ else {
+ db_delete($this->bin)
+ ->condition('cid', $cid)
+ ->execute();
+ }
+ }
+ }
+
+ /**
+ * Implements DrupalCacheInterface::isEmpty().
+ */
+ function isEmpty() {
+ $this->garbageCollection();
+ $query = db_select($this->bin);
+ $query->addExpression('1');
+ $result = $query->range(0, 1)
+ ->execute()
+ ->fetchField();
+ return empty($result);
+ }
+
+ /**
+ * Checks if $this->bin represents a valid cache table.
+ *
+ * This check is required to ensure that non-cache tables are not truncated
+ * accidentally when calling cache_clear_all().
+ *
+ * @return boolean
+ */
+ function isValidBin() {
+ if ($this->bin == 'cache' || substr($this->bin, 0, 6) == 'cache_') {
+ // Skip schema check for bins with standard table names.
+ return TRUE;
+ }
+ // These fields are required for any cache table.
+ $fields = array('cid', 'data', 'expire', 'created', 'serialized');
+ // Load the table schema.
+ $schema = drupal_get_schema($this->bin);
+ // Confirm that all fields are present.
+ return isset($schema['fields']) && !array_diff($fields, array_keys($schema['fields']));
+ }
+}
diff --git a/kolab.org/www/drupal-7.26/includes/common.inc b/kolab.org/www/drupal-7.26/includes/common.inc
new file mode 100644
index 0000000..3b4bf58
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/common.inc
@@ -0,0 +1,8224 @@
+<?php
+
+/**
+ * @file
+ * Common functions that many Drupal modules will need to reference.
+ *
+ * The functions that are critical and need to be available even when serving
+ * a cached page are instead located in bootstrap.inc.
+ */
+
+/**
+ * @defgroup php_wrappers PHP wrapper functions
+ * @{
+ * Functions that are wrappers or custom implementations of PHP functions.
+ *
+ * Certain PHP functions should not be used in Drupal. Instead, Drupal's
+ * replacement functions should be used.
+ *
+ * For example, for improved or more secure UTF8-handling, or RFC-compliant
+ * handling of URLs in Drupal.
+ *
+ * For ease of use and memorizing, all these wrapper functions use the same name
+ * as the original PHP function, but prefixed with "drupal_". Beware, however,
+ * that not all wrapper functions support the same arguments as the original
+ * functions.
+ *
+ * You should always use these wrapper functions in your code.
+ *
+ * Wrong:
+ * @code
+ * $my_substring = substr($original_string, 0, 5);
+ * @endcode
+ *
+ * Correct:
+ * @code
+ * $my_substring = drupal_substr($original_string, 0, 5);
+ * @endcode
+ *
+ * @}
+ */
+
+/**
+ * Return status for saving which involved creating a new item.
+ */
+define('SAVED_NEW', 1);
+
+/**
+ * Return status for saving which involved an update to an existing item.
+ */
+define('SAVED_UPDATED', 2);
+
+/**
+ * Return status for saving which deleted an existing item.
+ */
+define('SAVED_DELETED', 3);
+
+/**
+ * The default group for system CSS files added to the page.
+ */
+define('CSS_SYSTEM', -100);
+
+/**
+ * The default group for module CSS files added to the page.
+ */
+define('CSS_DEFAULT', 0);
+
+/**
+ * The default group for theme CSS files added to the page.
+ */
+define('CSS_THEME', 100);
+
+/**
+ * The default group for JavaScript and jQuery libraries added to the page.
+ */
+define('JS_LIBRARY', -100);
+
+/**
+ * The default group for module JavaScript code added to the page.
+ */
+define('JS_DEFAULT', 0);
+
+/**
+ * The default group for theme JavaScript code added to the page.
+ */
+define('JS_THEME', 100);
+
+/**
+ * Error code indicating that the request exceeded the specified timeout.
+ *
+ * @see drupal_http_request()
+ */
+define('HTTP_REQUEST_TIMEOUT', -1);
+
+/**
+ * @defgroup block_caching Block Caching
+ * @{
+ * Constants that define each block's caching state.
+ *
+ * Modules specify how their blocks can be cached in their hook_block_info()
+ * implementations. Caching can be turned off (DRUPAL_NO_CACHE), managed by the
+ * module declaring the block (DRUPAL_CACHE_CUSTOM), or managed by the core
+ * Block module. If the Block module is managing the cache, you can specify that
+ * the block is the same for every page and user (DRUPAL_CACHE_GLOBAL), or that
+ * it can change depending on the page (DRUPAL_CACHE_PER_PAGE) or by user
+ * (DRUPAL_CACHE_PER_ROLE or DRUPAL_CACHE_PER_USER). Page and user settings can
+ * be combined with a bitwise-binary or operator; for example,
+ * DRUPAL_CACHE_PER_ROLE | DRUPAL_CACHE_PER_PAGE means that the block can change
+ * depending on the user role or page it is on.
+ *
+ * The block cache is cleared in cache_clear_all(), and uses the same clearing
+ * policy than page cache (node, comment, user, taxonomy added or updated...).
+ * Blocks requiring more fine-grained clearing might consider disabling the
+ * built-in block cache (DRUPAL_NO_CACHE) and roll their own.
+ *
+ * Note that user 1 is excluded from block caching.
+ */
+
+/**
+ * The block should not get cached.
+ *
+ * This setting should be used:
+ * - For simple blocks (notably those that do not perform any db query), where
+ * querying the db cache would be more expensive than directly generating the
+ * content.
+ * - For blocks that change too frequently.
+ */
+define('DRUPAL_NO_CACHE', -1);
+
+/**
+ * The block is handling its own caching in its hook_block_view().
+ *
+ * This setting is useful when time based expiration is needed or a site uses a
+ * node access which invalidates standard block cache.
+ */
+define('DRUPAL_CACHE_CUSTOM', -2);
+
+/**
+ * The block or element can change depending on the user's roles.
+ *
+ * This is the default setting for blocks, used when the block does not specify
+ * anything.
+ */
+define('DRUPAL_CACHE_PER_ROLE', 0x0001);
+
+/**
+ * The block or element can change depending on the user.
+ *
+ * This setting can be resource-consuming for sites with large number of users,
+ * and thus should only be used when DRUPAL_CACHE_PER_ROLE is not sufficient.
+ */
+define('DRUPAL_CACHE_PER_USER', 0x0002);
+
+/**
+ * The block or element can change depending on the page being viewed.
+ */
+define('DRUPAL_CACHE_PER_PAGE', 0x0004);
+
+/**
+ * The block or element is the same for every user and page that it is visible.
+ */
+define('DRUPAL_CACHE_GLOBAL', 0x0008);
+
+/**
+ * @} End of "defgroup block_caching".
+ */
+
+/**
+ * Adds content to a specified region.
+ *
+ * @param $region
+ * Page region the content is added to.
+ * @param $data
+ * Content to be added.
+ */
+function drupal_add_region_content($region = NULL, $data = NULL) {
+ static $content = array();
+
+ if (isset($region) && isset($data)) {
+ $content[$region][] = $data;
+ }
+ return $content;
+}
+
+/**
+ * Gets assigned content for a given region.
+ *
+ * @param $region
+ * A specified region to fetch content for. If NULL, all regions will be
+ * returned.
+ * @param $delimiter
+ * Content to be inserted between imploded array elements.
+ */
+function drupal_get_region_content($region = NULL, $delimiter = ' ') {
+ $content = drupal_add_region_content();
+ if (isset($region)) {
+ if (isset($content[$region]) && is_array($content[$region])) {
+ return implode($delimiter, $content[$region]);
+ }
+ }
+ else {
+ foreach (array_keys($content) as $region) {
+ if (is_array($content[$region])) {
+ $content[$region] = implode($delimiter, $content[$region]);
+ }
+ }
+ return $content;
+ }
+}
+
+/**
+ * Gets the name of the currently active installation profile.
+ *
+ * When this function is called during Drupal's initial installation process,
+ * the name of the profile that's about to be installed is stored in the global
+ * installation state. At all other times, the standard Drupal systems variable
+ * table contains the name of the current profile, and we can call
+ * variable_get() to determine what one is active.
+ *
+ * @return $profile
+ * The name of the installation profile.
+ */
+function drupal_get_profile() {
+ global $install_state;
+
+ if (isset($install_state['parameters']['profile'])) {
+ $profile = $install_state['parameters']['profile'];
+ }
+ else {
+ $profile = variable_get('install_profile', 'standard');
+ }
+
+ return $profile;
+}
+
+
+/**
+ * Sets the breadcrumb trail for the current page.
+ *
+ * @param $breadcrumb
+ * Array of links, starting with "home" and proceeding up to but not including
+ * the current page.
+ */
+function drupal_set_breadcrumb($breadcrumb = NULL) {
+ $stored_breadcrumb = &drupal_static(__FUNCTION__);
+
+ if (isset($breadcrumb)) {
+ $stored_breadcrumb = $breadcrumb;
+ }
+ return $stored_breadcrumb;
+}
+
+/**
+ * Gets the breadcrumb trail for the current page.
+ */
+function drupal_get_breadcrumb() {
+ $breadcrumb = drupal_set_breadcrumb();
+
+ if (!isset($breadcrumb)) {
+ $breadcrumb = menu_get_active_breadcrumb();
+ }
+
+ return $breadcrumb;
+}
+
+/**
+ * Returns a string containing RDF namespace declarations for use in XML and
+ * XHTML output.
+ */
+function drupal_get_rdf_namespaces() {
+ $xml_rdf_namespaces = array();
+
+ // Serializes the RDF namespaces in XML namespace syntax.
+ if (function_exists('rdf_get_namespaces')) {
+ foreach (rdf_get_namespaces() as $prefix => $uri) {
+ $xml_rdf_namespaces[] = 'xmlns:' . $prefix . '="' . $uri . '"';
+ }
+ }
+ return count($xml_rdf_namespaces) ? "\n " . implode("\n ", $xml_rdf_namespaces) : '';
+}
+
+/**
+ * Adds output to the HEAD tag of the HTML page.
+ *
+ * This function can be called as long as the headers aren't sent. Pass no
+ * arguments (or NULL for both) to retrieve the currently stored elements.
+ *
+ * @param $data
+ * A renderable array. If the '#type' key is not set then 'html_tag' will be
+ * added as the default '#type'.
+ * @param $key
+ * A unique string key to allow implementations of hook_html_head_alter() to
+ * identify the element in $data. Required if $data is not NULL.
+ *
+ * @return
+ * An array of all stored HEAD elements.
+ *
+ * @see theme_html_tag()
+ */
+function drupal_add_html_head($data = NULL, $key = NULL) {
+ $stored_head = &drupal_static(__FUNCTION__);
+
+ if (!isset($stored_head)) {
+ // Make sure the defaults, including Content-Type, come first.
+ $stored_head = _drupal_default_html_head();
+ }
+
+ if (isset($data) && isset($key)) {
+ if (!isset($data['#type'])) {
+ $data['#type'] = 'html_tag';
+ }
+ $stored_head[$key] = $data;
+ }
+ return $stored_head;
+}
+
+/**
+ * Returns elements that are always displayed in the HEAD tag of the HTML page.
+ */
+function _drupal_default_html_head() {
+ // Add default elements. Make sure the Content-Type comes first because the
+ // IE browser may be vulnerable to XSS via encoding attacks from any content
+ // that comes before this META tag, such as a TITLE tag.
+ $elements['system_meta_content_type'] = array(
+ '#type' => 'html_tag',
+ '#tag' => 'meta',
+ '#attributes' => array(
+ 'http-equiv' => 'Content-Type',
+ 'content' => 'text/html; charset=utf-8',
+ ),
+ // Security: This always has to be output first.
+ '#weight' => -1000,
+ );
+ // Show Drupal and the major version number in the META GENERATOR tag.
+ // Get the major version.
+ list($version, ) = explode('.', VERSION);
+ $elements['system_meta_generator'] = array(
+ '#type' => 'html_tag',
+ '#tag' => 'meta',
+ '#attributes' => array(
+ 'name' => 'Generator',
+ 'content' => 'Drupal ' . $version . ' (http://drupal.org)',
+ ),
+ );
+ // Also send the generator in the HTTP header.
+ $elements['system_meta_generator']['#attached']['drupal_add_http_header'][] = array('X-Generator', $elements['system_meta_generator']['#attributes']['content']);
+ return $elements;
+}
+
+/**
+ * Retrieves output to be displayed in the HEAD tag of the HTML page.
+ */
+function drupal_get_html_head() {
+ $elements = drupal_add_html_head();
+ drupal_alter('html_head', $elements);
+ return drupal_render($elements);
+}
+
+/**
+ * Adds a feed URL for the current page.
+ *
+ * This function can be called as long the HTML header hasn't been sent.
+ *
+ * @param $url
+ * An internal system path or a fully qualified external URL of the feed.
+ * @param $title
+ * The title of the feed.
+ */
+function drupal_add_feed($url = NULL, $title = '') {
+ $stored_feed_links = &drupal_static(__FUNCTION__, array());
+
+ if (isset($url)) {
+ $stored_feed_links[$url] = theme('feed_icon', array('url' => $url, 'title' => $title));
+
+ drupal_add_html_head_link(array(
+ 'rel' => 'alternate',
+ 'type' => 'application/rss+xml',
+ 'title' => $title,
+ // Force the URL to be absolute, for consistency with other <link> tags
+ // output by Drupal.
+ 'href' => url($url, array('absolute' => TRUE)),
+ ));
+ }
+ return $stored_feed_links;
+}
+
+/**
+ * Gets the feed URLs for the current page.
+ *
+ * @param $delimiter
+ * A delimiter to split feeds by.
+ */
+function drupal_get_feeds($delimiter = "\n") {
+ $feeds = drupal_add_feed();
+ return implode($feeds, $delimiter);
+}
+
+/**
+ * @defgroup http_handling HTTP handling
+ * @{
+ * Functions to properly handle HTTP responses.
+ */
+
+/**
+ * Processes a URL query parameter array to remove unwanted elements.
+ *
+ * @param $query
+ * (optional) An array to be processed. Defaults to $_GET.
+ * @param $exclude
+ * (optional) A list of $query array keys to remove. Use "parent[child]" to
+ * exclude nested items. Defaults to array('q').
+ * @param $parent
+ * Internal use only. Used to build the $query array key for nested items.
+ *
+ * @return
+ * An array containing query parameters, which can be used for url().
+ */
+function drupal_get_query_parameters(array $query = NULL, array $exclude = array('q'), $parent = '') {
+ // Set defaults, if none given.
+ if (!isset($query)) {
+ $query = $_GET;
+ }
+ // If $exclude is empty, there is nothing to filter.
+ if (empty($exclude)) {
+ return $query;
+ }
+ elseif (!$parent) {
+ $exclude = array_flip($exclude);
+ }
+
+ $params = array();
+ foreach ($query as $key => $value) {
+ $string_key = ($parent ? $parent . '[' . $key . ']' : $key);
+ if (isset($exclude[$string_key])) {
+ continue;
+ }
+
+ if (is_array($value)) {
+ $params[$key] = drupal_get_query_parameters($value, $exclude, $string_key);
+ }
+ else {
+ $params[$key] = $value;
+ }
+ }
+
+ return $params;
+}
+
+/**
+ * Splits a URL-encoded query string into an array.
+ *
+ * @param $query
+ * The query string to split.
+ *
+ * @return
+ * An array of URL decoded couples $param_name => $value.
+ */
+function drupal_get_query_array($query) {
+ $result = array();
+ if (!empty($query)) {
+ foreach (explode('&', $query) as $param) {
+ $param = explode('=', $param);
+ $result[$param[0]] = isset($param[1]) ? rawurldecode($param[1]) : '';
+ }
+ }
+ return $result;
+}
+
+/**
+ * Parses an array into a valid, rawurlencoded query string.
+ *
+ * This differs from http_build_query() as we need to rawurlencode() (instead of
+ * urlencode()) all query parameters.
+ *
+ * @param $query
+ * The query parameter array to be processed, e.g. $_GET.
+ * @param $parent
+ * Internal use only. Used to build the $query array key for nested items.
+ *
+ * @return
+ * A rawurlencoded string which can be used as or appended to the URL query
+ * string.
+ *
+ * @see drupal_get_query_parameters()
+ * @ingroup php_wrappers
+ */
+function drupal_http_build_query(array $query, $parent = '') {
+ $params = array();
+
+ foreach ($query as $key => $value) {
+ $key = ($parent ? $parent . '[' . rawurlencode($key) . ']' : rawurlencode($key));
+
+ // Recurse into children.
+ if (is_array($value)) {
+ $params[] = drupal_http_build_query($value, $key);
+ }
+ // If a query parameter value is NULL, only append its key.
+ elseif (!isset($value)) {
+ $params[] = $key;
+ }
+ else {
+ // For better readability of paths in query strings, we decode slashes.
+ $params[] = $key . '=' . str_replace('%2F', '/', rawurlencode($value));
+ }
+ }
+
+ return implode('&', $params);
+}
+
+/**
+ * Prepares a 'destination' URL query parameter for use with drupal_goto().
+ *
+ * Used to direct the user back to the referring page after completing a form.
+ * By default the current URL is returned. If a destination exists in the
+ * previous request, that destination is returned. As such, a destination can
+ * persist across multiple pages.
+ *
+ * @return
+ * An associative array containing the key:
+ * - destination: The path provided via the destination query string or, if
+ * not available, the current path.
+ *
+ * @see current_path()
+ * @see drupal_goto()
+ */
+function drupal_get_destination() {
+ $destination = &drupal_static(__FUNCTION__);
+
+ if (isset($destination)) {
+ return $destination;
+ }
+
+ if (isset($_GET['destination'])) {
+ $destination = array('destination' => $_GET['destination']);
+ }
+ else {
+ $path = $_GET['q'];
+ $query = drupal_http_build_query(drupal_get_query_parameters());
+ if ($query != '') {
+ $path .= '?' . $query;
+ }
+ $destination = array('destination' => $path);
+ }
+ return $destination;
+}
+
+/**
+ * Parses a system URL string into an associative array suitable for url().
+ *
+ * This function should only be used for URLs that have been generated by the
+ * system, such as via url(). It should not be used for URLs that come from
+ * external sources, or URLs that link to external resources.
+ *
+ * The returned array contains a 'path' that may be passed separately to url().
+ * For example:
+ * @code
+ * $options = drupal_parse_url($_GET['destination']);
+ * $my_url = url($options['path'], $options);
+ * $my_link = l('Example link', $options['path'], $options);
+ * @endcode
+ *
+ * This is required, because url() does not support relative URLs containing a
+ * query string or fragment in its $path argument. Instead, any query string
+ * needs to be parsed into an associative query parameter array in
+ * $options['query'] and the fragment into $options['fragment'].
+ *
+ * @param $url
+ * The URL string to parse, f.e. $_GET['destination'].
+ *
+ * @return
+ * An associative array containing the keys:
+ * - 'path': The path of the URL. If the given $url is external, this includes
+ * the scheme and host.
+ * - 'query': An array of query parameters of $url, if existent.
+ * - 'fragment': The fragment of $url, if existent.
+ *
+ * @see url()
+ * @see drupal_goto()
+ * @ingroup php_wrappers
+ */
+function drupal_parse_url($url) {
+ $options = array(
+ 'path' => NULL,
+ 'query' => array(),
+ 'fragment' => '',
+ );
+
+ // External URLs: not using parse_url() here, so we do not have to rebuild
+ // the scheme, host, and path without having any use for it.
+ if (strpos($url, '://') !== FALSE) {
+ // Split off everything before the query string into 'path'.
+ $parts = explode('?', $url);
+ $options['path'] = $parts[0];
+ // If there is a query string, transform it into keyed query parameters.
+ if (isset($parts[1])) {
+ $query_parts = explode('#', $parts[1]);
+ parse_str($query_parts[0], $options['query']);
+ // Take over the fragment, if there is any.
+ if (isset($query_parts[1])) {
+ $options['fragment'] = $query_parts[1];
+ }
+ }
+ }
+ // Internal URLs.
+ else {
+ // parse_url() does not support relative URLs, so make it absolute. E.g. the
+ // relative URL "foo/bar:1" isn't properly parsed.
+ $parts = parse_url('http://example.com/' . $url);
+ // Strip the leading slash that was just added.
+ $options['path'] = substr($parts['path'], 1);
+ if (isset($parts['query'])) {
+ parse_str($parts['query'], $options['query']);
+ }
+ if (isset($parts['fragment'])) {
+ $options['fragment'] = $parts['fragment'];
+ }
+ }
+ // The 'q' parameter contains the path of the current page if clean URLs are
+ // disabled. It overrides the 'path' of the URL when present, even if clean
+ // URLs are enabled, due to how Apache rewriting rules work.
+ if (isset($options['query']['q'])) {
+ $options['path'] = $options['query']['q'];
+ unset($options['query']['q']);
+ }
+
+ return $options;
+}
+
+/**
+ * Encodes a Drupal path for use in a URL.
+ *
+ * For aesthetic reasons slashes are not escaped.
+ *
+ * Note that url() takes care of calling this function, so a path passed to that
+ * function should not be encoded in advance.
+ *
+ * @param $path
+ * The Drupal path to encode.
+ */
+function drupal_encode_path($path) {
+ return str_replace('%2F', '/', rawurlencode($path));
+}
+
+/**
+ * Sends the user to a different page.
+ *
+ * This issues an on-site HTTP redirect. The function makes sure the redirected
+ * URL is formatted correctly.
+ *
+ * Usually the redirected URL is constructed from this function's input
+ * parameters. However you may override that behavior by setting a
+ * destination in either the $_REQUEST-array (i.e. by using
+ * the query string of an URI) This is used to direct the user back to
+ * the proper page after completing a form. For example, after editing
+ * a post on the 'admin/content'-page or after having logged on using the
+ * 'user login'-block in a sidebar. The function drupal_get_destination()
+ * can be used to help set the destination URL.
+ *
+ * Drupal will ensure that messages set by drupal_set_message() and other
+ * session data are written to the database before the user is redirected.
+ *
+ * This function ends the request; use it instead of a return in your menu
+ * callback.
+ *
+ * @param $path
+ * (optional) A Drupal path or a full URL, which will be passed to url() to
+ * compute the redirect for the URL.
+ * @param $options
+ * (optional) An associative array of additional URL options to pass to url().
+ * @param $http_response_code
+ * (optional) The HTTP status code to use for the redirection, defaults to
+ * 302. The valid values for 3xx redirection status codes are defined in
+ * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.3 RFC 2616 @endlink
+ * and the
+ * @link http://tools.ietf.org/html/draft-reschke-http-status-308-07 draft for the new HTTP status codes: @endlink
+ * - 301: Moved Permanently (the recommended value for most redirects).
+ * - 302: Found (default in Drupal and PHP, sometimes used for spamming search
+ * engines).
+ * - 303: See Other.
+ * - 304: Not Modified.
+ * - 305: Use Proxy.
+ * - 307: Temporary Redirect.
+ *
+ * @see drupal_get_destination()
+ * @see url()
+ */
+function drupal_goto($path = '', array $options = array(), $http_response_code = 302) {
+ // A destination in $_GET always overrides the function arguments.
+ // We do not allow absolute URLs to be passed via $_GET, as this can be an attack vector.
+ if (isset($_GET['destination']) && !url_is_external($_GET['destination'])) {
+ $destination = drupal_parse_url($_GET['destination']);
+ $path = $destination['path'];
+ $options['query'] = $destination['query'];
+ $options['fragment'] = $destination['fragment'];
+ }
+
+ drupal_alter('drupal_goto', $path, $options, $http_response_code);
+
+ // The 'Location' HTTP header must be absolute.
+ $options['absolute'] = TRUE;
+
+ $url = url($path, $options);
+
+ header('Location: ' . $url, TRUE, $http_response_code);
+
+ // The "Location" header sends a redirect status code to the HTTP daemon. In
+ // some cases this can be wrong, so we make sure none of the code below the
+ // drupal_goto() call gets executed upon redirection.
+ drupal_exit($url);
+}
+
+/**
+ * Delivers a "site is under maintenance" message to the browser.
+ *
+ * Page callback functions wanting to report a "site offline" message should
+ * return MENU_SITE_OFFLINE instead of calling drupal_site_offline(). However,
+ * functions that are invoked in contexts where that return value might not
+ * bubble up to menu_execute_active_handler() should call drupal_site_offline().
+ */
+function drupal_site_offline() {
+ drupal_deliver_page(MENU_SITE_OFFLINE);
+}
+
+/**
+ * Delivers a "page not found" error to the browser.
+ *
+ * Page callback functions wanting to report a "page not found" message should
+ * return MENU_NOT_FOUND instead of calling drupal_not_found(). However,
+ * functions that are invoked in contexts where that return value might not
+ * bubble up to menu_execute_active_handler() should call drupal_not_found().
+ */
+function drupal_not_found() {
+ drupal_deliver_page(MENU_NOT_FOUND);
+}
+
+/**
+ * Delivers an "access denied" error to the browser.
+ *
+ * Page callback functions wanting to report an "access denied" message should
+ * return MENU_ACCESS_DENIED instead of calling drupal_access_denied(). However,
+ * functions that are invoked in contexts where that return value might not
+ * bubble up to menu_execute_active_handler() should call
+ * drupal_access_denied().
+ */
+function drupal_access_denied() {
+ drupal_deliver_page(MENU_ACCESS_DENIED);
+}
+
+/**
+ * Performs an HTTP request.
+ *
+ * This is a flexible and powerful HTTP client implementation. Correctly
+ * handles GET, POST, PUT or any other HTTP requests. Handles redirects.
+ *
+ * @param $url
+ * A string containing a fully qualified URI.
+ * @param array $options
+ * (optional) An array that can have one or more of the following elements:
+ * - headers: An array containing request headers to send as name/value pairs.
+ * - method: A string containing the request method. Defaults to 'GET'.
+ * - data: A string containing the request body, formatted as
+ * 'param=value&param=value&...'. Defaults to NULL.
+ * - max_redirects: An integer representing how many times a redirect
+ * may be followed. Defaults to 3.
+ * - timeout: A float representing the maximum number of seconds the function
+ * call may take. The default is 30 seconds. If a timeout occurs, the error
+ * code is set to the HTTP_REQUEST_TIMEOUT constant.
+ * - context: A context resource created with stream_context_create().
+ *
+ * @return object
+ * An object that can have one or more of the following components:
+ * - request: A string containing the request body that was sent.
+ * - code: An integer containing the response status code, or the error code
+ * if an error occurred.
+ * - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
+ * - status_message: The status message from the response, if a response was
+ * received.
+ * - redirect_code: If redirected, an integer containing the initial response
+ * status code.
+ * - redirect_url: If redirected, a string containing the URL of the redirect
+ * target.
+ * - error: If an error occurred, the error message. Otherwise not set.
+ * - headers: An array containing the response headers as name/value pairs.
+ * HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
+ * easy access the array keys are returned in lower case.
+ * - data: A string containing the response body that was received.
+ */
+function drupal_http_request($url, array $options = array()) {
+ // Allow an alternate HTTP client library to replace Drupal's default
+ // implementation.
+ $override_function = variable_get('drupal_http_request_function', FALSE);
+ if (!empty($override_function) && function_exists($override_function)) {
+ return $override_function($url, $options);
+ }
+
+ $result = new stdClass();
+
+ // Parse the URL and make sure we can handle the schema.
+ $uri = @parse_url($url);
+
+ if ($uri == FALSE) {
+ $result->error = 'unable to parse URL';
+ $result->code = -1001;
+ return $result;
+ }
+
+ if (!isset($uri['scheme'])) {
+ $result->error = 'missing schema';
+ $result->code = -1002;
+ return $result;
+ }
+
+ timer_start(__FUNCTION__);
+
+ // Merge the default options.
+ $options += array(
+ 'headers' => array(),
+ 'method' => 'GET',
+ 'data' => NULL,
+ 'max_redirects' => 3,
+ 'timeout' => 30.0,
+ 'context' => NULL,
+ );
+
+ // Merge the default headers.
+ $options['headers'] += array(
+ 'User-Agent' => 'Drupal (+http://drupal.org/)',
+ );
+
+ // stream_socket_client() requires timeout to be a float.
+ $options['timeout'] = (float) $options['timeout'];
+
+ // Use a proxy if one is defined and the host is not on the excluded list.
+ $proxy_server = variable_get('proxy_server', '');
+ if ($proxy_server && _drupal_http_use_proxy($uri['host'])) {
+ // Set the scheme so we open a socket to the proxy server.
+ $uri['scheme'] = 'proxy';
+ // Set the path to be the full URL.
+ $uri['path'] = $url;
+ // Since the URL is passed as the path, we won't use the parsed query.
+ unset($uri['query']);
+
+ // Add in username and password to Proxy-Authorization header if needed.
+ if ($proxy_username = variable_get('proxy_username', '')) {
+ $proxy_password = variable_get('proxy_password', '');
+ $options['headers']['Proxy-Authorization'] = 'Basic ' . base64_encode($proxy_username . (!empty($proxy_password) ? ":" . $proxy_password : ''));
+ }
+ // Some proxies reject requests with any User-Agent headers, while others
+ // require a specific one.
+ $proxy_user_agent = variable_get('proxy_user_agent', '');
+ // The default value matches neither condition.
+ if ($proxy_user_agent === NULL) {
+ unset($options['headers']['User-Agent']);
+ }
+ elseif ($proxy_user_agent) {
+ $options['headers']['User-Agent'] = $proxy_user_agent;
+ }
+ }
+
+ switch ($uri['scheme']) {
+ case 'proxy':
+ // Make the socket connection to a proxy server.
+ $socket = 'tcp://' . $proxy_server . ':' . variable_get('proxy_port', 8080);
+ // The Host header still needs to match the real request.
+ $options['headers']['Host'] = $uri['host'];
+ $options['headers']['Host'] .= isset($uri['port']) && $uri['port'] != 80 ? ':' . $uri['port'] : '';
+ break;
+
+ case 'http':
+ case 'feed':
+ $port = isset($uri['port']) ? $uri['port'] : 80;
+ $socket = 'tcp://' . $uri['host'] . ':' . $port;
+ // RFC 2616: "non-standard ports MUST, default ports MAY be included".
+ // We don't add the standard port to prevent from breaking rewrite rules
+ // checking the host that do not take into account the port number.
+ $options['headers']['Host'] = $uri['host'] . ($port != 80 ? ':' . $port : '');
+ break;
+
+ case 'https':
+ // Note: Only works when PHP is compiled with OpenSSL support.
+ $port = isset($uri['port']) ? $uri['port'] : 443;
+ $socket = 'ssl://' . $uri['host'] . ':' . $port;
+ $options['headers']['Host'] = $uri['host'] . ($port != 443 ? ':' . $port : '');
+ break;
+
+ default:
+ $result->error = 'invalid schema ' . $uri['scheme'];
+ $result->code = -1003;
+ return $result;
+ }
+
+ if (empty($options['context'])) {
+ $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout']);
+ }
+ else {
+ // Create a stream with context. Allows verification of a SSL certificate.
+ $fp = @stream_socket_client($socket, $errno, $errstr, $options['timeout'], STREAM_CLIENT_CONNECT, $options['context']);
+ }
+
+ // Make sure the socket opened properly.
+ if (!$fp) {
+ // When a network error occurs, we use a negative number so it does not
+ // clash with the HTTP status codes.
+ $result->code = -$errno;
+ $result->error = trim($errstr) ? trim($errstr) : t('Error opening socket @socket', array('@socket' => $socket));
+
+ // Mark that this request failed. This will trigger a check of the web
+ // server's ability to make outgoing HTTP requests the next time that
+ // requirements checking is performed.
+ // See system_requirements().
+ variable_set('drupal_http_request_fails', TRUE);
+
+ return $result;
+ }
+
+ // Construct the path to act on.
+ $path = isset($uri['path']) ? $uri['path'] : '/';
+ if (isset($uri['query'])) {
+ $path .= '?' . $uri['query'];
+ }
+
+ // Only add Content-Length if we actually have any content or if it is a POST
+ // or PUT request. Some non-standard servers get confused by Content-Length in
+ // at least HEAD/GET requests, and Squid always requires Content-Length in
+ // POST/PUT requests.
+ $content_length = strlen($options['data']);
+ if ($content_length > 0 || $options['method'] == 'POST' || $options['method'] == 'PUT') {
+ $options['headers']['Content-Length'] = $content_length;
+ }
+
+ // If the server URL has a user then attempt to use basic authentication.
+ if (isset($uri['user'])) {
+ $options['headers']['Authorization'] = 'Basic ' . base64_encode($uri['user'] . (isset($uri['pass']) ? ':' . $uri['pass'] : ':'));
+ }
+
+ // If the database prefix is being used by SimpleTest to run the tests in a copied
+ // database then set the user-agent header to the database prefix so that any
+ // calls to other Drupal pages will run the SimpleTest prefixed database. The
+ // user-agent is used to ensure that multiple testing sessions running at the
+ // same time won't interfere with each other as they would if the database
+ // prefix were stored statically in a file or database variable.
+ $test_info = &$GLOBALS['drupal_test_info'];
+ if (!empty($test_info['test_run_id'])) {
+ $options['headers']['User-Agent'] = drupal_generate_test_ua($test_info['test_run_id']);
+ }
+
+ $request = $options['method'] . ' ' . $path . " HTTP/1.0\r\n";
+ foreach ($options['headers'] as $name => $value) {
+ $request .= $name . ': ' . trim($value) . "\r\n";
+ }
+ $request .= "\r\n" . $options['data'];
+ $result->request = $request;
+ // Calculate how much time is left of the original timeout value.
+ $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
+ if ($timeout > 0) {
+ stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
+ fwrite($fp, $request);
+ }
+
+ // Fetch response. Due to PHP bugs like http://bugs.php.net/bug.php?id=43782
+ // and http://bugs.php.net/bug.php?id=46049 we can't rely on feof(), but
+ // instead must invoke stream_get_meta_data() each iteration.
+ $info = stream_get_meta_data($fp);
+ $alive = !$info['eof'] && !$info['timed_out'];
+ $response = '';
+
+ while ($alive) {
+ // Calculate how much time is left of the original timeout value.
+ $timeout = $options['timeout'] - timer_read(__FUNCTION__) / 1000;
+ if ($timeout <= 0) {
+ $info['timed_out'] = TRUE;
+ break;
+ }
+ stream_set_timeout($fp, floor($timeout), floor(1000000 * fmod($timeout, 1)));
+ $chunk = fread($fp, 1024);
+ $response .= $chunk;
+ $info = stream_get_meta_data($fp);
+ $alive = !$info['eof'] && !$info['timed_out'] && $chunk;
+ }
+ fclose($fp);
+
+ if ($info['timed_out']) {
+ $result->code = HTTP_REQUEST_TIMEOUT;
+ $result->error = 'request timed out';
+ return $result;
+ }
+ // Parse response headers from the response body.
+ // Be tolerant of malformed HTTP responses that separate header and body with
+ // \n\n or \r\r instead of \r\n\r\n.
+ list($response, $result->data) = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
+ $response = preg_split("/\r\n|\n|\r/", $response);
+
+ // Parse the response status line.
+ list($protocol, $code, $status_message) = explode(' ', trim(array_shift($response)), 3);
+ $result->protocol = $protocol;
+ $result->status_message = $status_message;
+
+ $result->headers = array();
+
+ // Parse the response headers.
+ while ($line = trim(array_shift($response))) {
+ list($name, $value) = explode(':', $line, 2);
+ $name = strtolower($name);
+ if (isset($result->headers[$name]) && $name == 'set-cookie') {
+ // RFC 2109: the Set-Cookie response header comprises the token Set-
+ // Cookie:, followed by a comma-separated list of one or more cookies.
+ $result->headers[$name] .= ',' . trim($value);
+ }
+ else {
+ $result->headers[$name] = trim($value);
+ }
+ }
+
+ $responses = array(
+ 100 => 'Continue',
+ 101 => 'Switching Protocols',
+ 200 => 'OK',
+ 201 => 'Created',
+ 202 => 'Accepted',
+ 203 => 'Non-Authoritative Information',
+ 204 => 'No Content',
+ 205 => 'Reset Content',
+ 206 => 'Partial Content',
+ 300 => 'Multiple Choices',
+ 301 => 'Moved Permanently',
+ 302 => 'Found',
+ 303 => 'See Other',
+ 304 => 'Not Modified',
+ 305 => 'Use Proxy',
+ 307 => 'Temporary Redirect',
+ 400 => 'Bad Request',
+ 401 => 'Unauthorized',
+ 402 => 'Payment Required',
+ 403 => 'Forbidden',
+ 404 => 'Not Found',
+ 405 => 'Method Not Allowed',
+ 406 => 'Not Acceptable',
+ 407 => 'Proxy Authentication Required',
+ 408 => 'Request Time-out',
+ 409 => 'Conflict',
+ 410 => 'Gone',
+ 411 => 'Length Required',
+ 412 => 'Precondition Failed',
+ 413 => 'Request Entity Too Large',
+ 414 => 'Request-URI Too Large',
+ 415 => 'Unsupported Media Type',
+ 416 => 'Requested range not satisfiable',
+ 417 => 'Expectation Failed',
+ 500 => 'Internal Server Error',
+ 501 => 'Not Implemented',
+ 502 => 'Bad Gateway',
+ 503 => 'Service Unavailable',
+ 504 => 'Gateway Time-out',
+ 505 => 'HTTP Version not supported',
+ );
+ // RFC 2616 states that all unknown HTTP codes must be treated the same as the
+ // base code in their class.
+ if (!isset($responses[$code])) {
+ $code = floor($code / 100) * 100;
+ }
+ $result->code = $code;
+
+ switch ($code) {
+ case 200: // OK
+ case 304: // Not modified
+ break;
+ case 301: // Moved permanently
+ case 302: // Moved temporarily
+ case 307: // Moved temporarily
+ $location = $result->headers['location'];
+ $options['timeout'] -= timer_read(__FUNCTION__) / 1000;
+ if ($options['timeout'] <= 0) {
+ $result->code = HTTP_REQUEST_TIMEOUT;
+ $result->error = 'request timed out';
+ }
+ elseif ($options['max_redirects']) {
+ // Redirect to the new location.
+ $options['max_redirects']--;
+ $result = drupal_http_request($location, $options);
+ $result->redirect_code = $code;
+ }
+ if (!isset($result->redirect_url)) {
+ $result->redirect_url = $location;
+ }
+ break;
+ default:
+ $result->error = $status_message;
+ }
+
+ return $result;
+}
+
+/**
+ * Helper function for determining hosts excluded from needing a proxy.
+ *
+ * @return
+ * TRUE if a proxy should be used for this host.
+ */
+function _drupal_http_use_proxy($host) {
+ $proxy_exceptions = variable_get('proxy_exceptions', array('localhost', '127.0.0.1'));
+ return !in_array(strtolower($host), $proxy_exceptions, TRUE);
+}
+
+/**
+ * @} End of "HTTP handling".
+ */
+
+/**
+ * Strips slashes from a string or array of strings.
+ *
+ * Callback for array_walk() within fix_gpx_magic().
+ *
+ * @param $item
+ * An individual string or array of strings from superglobals.
+ */
+function _fix_gpc_magic(&$item) {
+ if (is_array($item)) {
+ array_walk($item, '_fix_gpc_magic');
+ }
+ else {
+ $item = stripslashes($item);
+ }
+}
+
+/**
+ * Strips slashes from $_FILES items.
+ *
+ * Callback for array_walk() within fix_gpc_magic().
+ *
+ * The tmp_name key is skipped keys since PHP generates single backslashes for
+ * file paths on Windows systems.
+ *
+ * @param $item
+ * An item from $_FILES.
+ * @param $key
+ * The key for the item within $_FILES.
+ *
+ * @see http://php.net/manual/features.file-upload.php#42280
+ */
+function _fix_gpc_magic_files(&$item, $key) {
+ if ($key != 'tmp_name') {
+ if (is_array($item)) {
+ array_walk($item, '_fix_gpc_magic_files');
+ }
+ else {
+ $item = stripslashes($item);
+ }
+ }
+}
+
+/**
+ * Fixes double-escaping caused by "magic quotes" in some PHP installations.
+ *
+ * @see _fix_gpc_magic()
+ * @see _fix_gpc_magic_files()
+ */
+function fix_gpc_magic() {
+ static $fixed = FALSE;
+ if (!$fixed && ini_get('magic_quotes_gpc')) {
+ array_walk($_GET, '_fix_gpc_magic');
+ array_walk($_POST, '_fix_gpc_magic');
+ array_walk($_COOKIE, '_fix_gpc_magic');
+ array_walk($_REQUEST, '_fix_gpc_magic');
+ array_walk($_FILES, '_fix_gpc_magic_files');
+ }
+ $fixed = TRUE;
+}
+
+/**
+ * @defgroup validation Input validation
+ * @{
+ * Functions to validate user input.
+ */
+
+/**
+ * Verifies the syntax of the given e-mail address.
+ *
+ * This uses the
+ * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
+ *
+ * @param $mail
+ * A string containing an e-mail address.
+ *
+ * @return
+ * TRUE if the address is in a valid format.
+ */
+function valid_email_address($mail) {
+ return (bool)filter_var($mail, FILTER_VALIDATE_EMAIL);
+}
+
+/**
+ * Verifies the syntax of the given URL.
+ *
+ * This function should only be used on actual URLs. It should not be used for
+ * Drupal menu paths, which can contain arbitrary characters.
+ * Valid values per RFC 3986.
+ * @param $url
+ * The URL to verify.
+ * @param $absolute
+ * Whether the URL is absolute (beginning with a scheme such as "http:").
+ *
+ * @return
+ * TRUE if the URL is in a valid format.
+ */
+function valid_url($url, $absolute = FALSE) {
+ if ($absolute) {
+ return (bool)preg_match("
+ /^ # Start at the beginning of the text
+ (?:ftp|https?|feed):\/\/ # Look for ftp, http, https or feed schemes
+ (?: # Userinfo (optional) which is typically
+ (?:(?:[\w\.\-\+!$&'\(\)*\+,;=]|%[0-9a-f]{2})+:)* # a username or a username and password
+ (?:[\w\.\-\+%!$&'\(\)*\+,;=]|%[0-9a-f]{2})+@ # combination
+ )?
+ (?:
+ (?:[a-z0-9\-\.]|%[0-9a-f]{2})+ # A domain name or a IPv4 address
+ |(?:\[(?:[0-9a-f]{0,4}:)*(?:[0-9a-f]{0,4})\]) # or a well formed IPv6 address
+ )
+ (?::[0-9]+)? # Server port number (optional)
+ (?:[\/|\?]
+ (?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2}) # The path and query (optional)
+ *)?
+ $/xi", $url);
+ }
+ else {
+ return (bool)preg_match("/^(?:[\w#!:\.\?\+=&@$'~*,;\/\(\)\[\]\-]|%[0-9a-f]{2})+$/i", $url);
+ }
+}
+
+/**
+ * @} End of "defgroup validation".
+ */
+
+/**
+ * Registers an event for the current visitor to the flood control mechanism.
+ *
+ * @param $name
+ * The name of an event.
+ * @param $window
+ * Optional number of seconds before this event expires. Defaults to 3600 (1
+ * hour). Typically uses the same value as the flood_is_allowed() $window
+ * parameter. Expired events are purged on cron run to prevent the flood table
+ * from growing indefinitely.
+ * @param $identifier
+ * Optional identifier (defaults to the current user's IP address).
+ */
+function flood_register_event($name, $window = 3600, $identifier = NULL) {
+ if (!isset($identifier)) {
+ $identifier = ip_address();
+ }
+ db_insert('flood')
+ ->fields(array(
+ 'event' => $name,
+ 'identifier' => $identifier,
+ 'timestamp' => REQUEST_TIME,
+ 'expiration' => REQUEST_TIME + $window,
+ ))
+ ->execute();
+}
+
+/**
+ * Makes the flood control mechanism forget an event for the current visitor.
+ *
+ * @param $name
+ * The name of an event.
+ * @param $identifier
+ * Optional identifier (defaults to the current user's IP address).
+ */
+function flood_clear_event($name, $identifier = NULL) {
+ if (!isset($identifier)) {
+ $identifier = ip_address();
+ }
+ db_delete('flood')
+ ->condition('event', $name)
+ ->condition('identifier', $identifier)
+ ->execute();
+}
+
+/**
+ * Checks whether a user is allowed to proceed with the specified event.
+ *
+ * Events can have thresholds saying that each user can only do that event
+ * a certain number of times in a time window. This function verifies that the
+ * current user has not exceeded this threshold.
+ *
+ * @param $name
+ * The unique name of the event.
+ * @param $threshold
+ * The maximum number of times each user can do this event per time window.
+ * @param $window
+ * Number of seconds in the time window for this event (default is 3600
+ * seconds, or 1 hour).
+ * @param $identifier
+ * Unique identifier of the current user. Defaults to their IP address.
+ *
+ * @return
+ * TRUE if the user is allowed to proceed. FALSE if they have exceeded the
+ * threshold and should not be allowed to proceed.
+ */
+function flood_is_allowed($name, $threshold, $window = 3600, $identifier = NULL) {
+ if (!isset($identifier)) {
+ $identifier = ip_address();
+ }
+ $number = db_query("SELECT COUNT(*) FROM {flood} WHERE event = :event AND identifier = :identifier AND timestamp > :timestamp", array(
+ ':event' => $name,
+ ':identifier' => $identifier,
+ ':timestamp' => REQUEST_TIME - $window))
+ ->fetchField();
+ return ($number < $threshold);
+}
+
+/**
+ * @defgroup sanitization Sanitization functions
+ * @{
+ * Functions to sanitize values.
+ *
+ * See http://drupal.org/writing-secure-code for information
+ * on writing secure code.
+ */
+
+/**
+ * Strips dangerous protocols (e.g. 'javascript:') from a URI.
+ *
+ * This function must be called for all URIs within user-entered input prior
+ * to being output to an HTML attribute value. It is often called as part of
+ * check_url() or filter_xss(), but those functions return an HTML-encoded
+ * string, so this function can be called independently when the output needs to
+ * be a plain-text string for passing to t(), l(), drupal_attributes(), or
+ * another function that will call check_plain() separately.
+ *
+ * @param $uri
+ * A plain-text URI that might contain dangerous protocols.
+ *
+ * @return
+ * A plain-text URI stripped of dangerous protocols. As with all plain-text
+ * strings, this return value must not be output to an HTML page without
+ * check_plain() being called on it. However, it can be passed to functions
+ * expecting plain-text strings.
+ *
+ * @see check_url()
+ */
+function drupal_strip_dangerous_protocols($uri) {
+ static $allowed_protocols;
+
+ if (!isset($allowed_protocols)) {
+ $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal')));
+ }
+
+ // Iteratively remove any invalid protocol found.
+ do {
+ $before = $uri;
+ $colonpos = strpos($uri, ':');
+ if ($colonpos > 0) {
+ // We found a colon, possibly a protocol. Verify.
+ $protocol = substr($uri, 0, $colonpos);
+ // If a colon is preceded by a slash, question mark or hash, it cannot
+ // possibly be part of the URL scheme. This must be a relative URL, which
+ // inherits the (safe) protocol of the base document.
+ if (preg_match('![/?#]!', $protocol)) {
+ break;
+ }
+ // Check if this is a disallowed protocol. Per RFC2616, section 3.2.3
+ // (URI Comparison) scheme comparison must be case-insensitive.
+ if (!isset($allowed_protocols[strtolower($protocol)])) {
+ $uri = substr($uri, $colonpos + 1);
+ }
+ }
+ } while ($before != $uri);
+
+ return $uri;
+}
+
+/**
+ * Strips dangerous protocols from a URI and encodes it for output to HTML.
+ *
+ * @param $uri
+ * A plain-text URI that might contain dangerous protocols.
+ *
+ * @return
+ * A URI stripped of dangerous protocols and encoded for output to an HTML
+ * attribute value. Because it is already encoded, it should not be set as a
+ * value within a $attributes array passed to drupal_attributes(), because
+ * drupal_attributes() expects those values to be plain-text strings. To pass
+ * a filtered URI to drupal_attributes(), call
+ * drupal_strip_dangerous_protocols() instead.
+ *
+ * @see drupal_strip_dangerous_protocols()
+ */
+function check_url($uri) {
+ return check_plain(drupal_strip_dangerous_protocols($uri));
+}
+
+/**
+ * Applies a very permissive XSS/HTML filter for admin-only use.
+ *
+ * Use only for fields where it is impractical to use the
+ * whole filter system, but where some (mainly inline) mark-up
+ * is desired (so check_plain() is not acceptable).
+ *
+ * Allows all tags that can be used inside an HTML body, save
+ * for scripts and styles.
+ */
+function filter_xss_admin($string) {
+ return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'article', 'aside', 'b', 'bdi', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'command', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure', 'footer', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'mark', 'menu', 'meter', 'nav', 'ol', 'output', 'p', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'small', 'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'time', 'tr', 'tt', 'u', 'ul', 'var', 'wbr'));
+}
+
+/**
+ * Filters HTML to prevent cross-site-scripting (XSS) vulnerabilities.
+ *
+ * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
+ * For examples of various XSS attacks, see: http://ha.ckers.org/xss.html.
+ *
+ * This code does four things:
+ * - Removes characters and constructs that can trick browsers.
+ * - Makes sure all HTML entities are well-formed.
+ * - Makes sure all HTML tags and attributes are well-formed.
+ * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
+ * javascript:).
+ *
+ * @param $string
+ * The string with raw HTML in it. It will be stripped of everything that can
+ * cause an XSS attack.
+ * @param $allowed_tags
+ * An array of allowed tags.
+ *
+ * @return
+ * An XSS safe version of $string, or an empty string if $string is not
+ * valid UTF-8.
+ *
+ * @see drupal_validate_utf8()
+ * @ingroup sanitization
+ */
+function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'blockquote', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
+ // Only operate on valid UTF-8 strings. This is necessary to prevent cross
+ // site scripting issues on Internet Explorer 6.
+ if (!drupal_validate_utf8($string)) {
+ return '';
+ }
+ // Store the text format.
+ _filter_xss_split($allowed_tags, TRUE);
+ // Remove NULL characters (ignored by some browsers).
+ $string = str_replace(chr(0), '', $string);
+ // Remove Netscape 4 JS entities.
+ $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
+
+ // Defuse all HTML entities.
+ $string = str_replace('&', '&amp;', $string);
+ // Change back only well-formed entities in our whitelist:
+ // Decimal numeric entities.
+ $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
+ // Hexadecimal numeric entities.
+ $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
+ // Named entities.
+ $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
+
+ return preg_replace_callback('%
+ (
+ <(?=[^a-zA-Z!/]) # a lone <
+ | # or
+ <!--.*?--> # a comment
+ | # or
+ <[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
+ | # or
+ > # just a >
+ )%x', '_filter_xss_split', $string);
+}
+
+/**
+ * Processes an HTML tag.
+ *
+ * @param $m
+ * An array with various meaning depending on the value of $store.
+ * If $store is TRUE then the array contains the allowed tags.
+ * If $store is FALSE then the array has one element, the HTML tag to process.
+ * @param $store
+ * Whether to store $m.
+ *
+ * @return
+ * If the element isn't allowed, an empty string. Otherwise, the cleaned up
+ * version of the HTML element.
+ */
+function _filter_xss_split($m, $store = FALSE) {
+ static $allowed_html;
+
+ if ($store) {
+ $allowed_html = array_flip($m);
+ return;
+ }
+
+ $string = $m[1];
+
+ if (substr($string, 0, 1) != '<') {
+ // We matched a lone ">" character.
+ return '&gt;';
+ }
+ elseif (strlen($string) == 1) {
+ // We matched a lone "<" character.
+ return '&lt;';
+ }
+
+ if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?|(<!--.*?-->)$%', $string, $matches)) {
+ // Seriously malformed.
+ return '';
+ }
+
+ $slash = trim($matches[1]);
+ $elem = &$matches[2];
+ $attrlist = &$matches[3];
+ $comment = &$matches[4];
+
+ if ($comment) {
+ $elem = '!--';
+ }
+
+ if (!isset($allowed_html[strtolower($elem)])) {
+ // Disallowed HTML element.
+ return '';
+ }
+
+ if ($comment) {
+ return $comment;
+ }
+
+ if ($slash != '') {
+ return "</$elem>";
+ }
+
+ // Is there a closing XHTML slash at the end of the attributes?
+ $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist, -1, $count);
+ $xhtml_slash = $count ? ' /' : '';
+
+ // Clean up attributes.
+ $attr2 = implode(' ', _filter_xss_attributes($attrlist));
+ $attr2 = preg_replace('/[<>]/', '', $attr2);
+ $attr2 = strlen($attr2) ? ' ' . $attr2 : '';
+
+ return "<$elem$attr2$xhtml_slash>";
+}
+
+/**
+ * Processes a string of HTML attributes.
+ *
+ * @return
+ * Cleaned up version of the HTML attributes.
+ */
+function _filter_xss_attributes($attr) {
+ $attrarr = array();
+ $mode = 0;
+ $attrname = '';
+
+ while (strlen($attr) != 0) {
+ // Was the last operation successful?
+ $working = 0;
+
+ switch ($mode) {
+ case 0:
+ // Attribute name, href for instance.
+ if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
+ $attrname = strtolower($match[1]);
+ $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
+ $working = $mode = 1;
+ $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
+ }
+ break;
+
+ case 1:
+ // Equals sign or valueless ("selected").
+ if (preg_match('/^\s*=\s*/', $attr)) {
+ $working = 1; $mode = 2;
+ $attr = preg_replace('/^\s*=\s*/', '', $attr);
+ break;
+ }
+
+ if (preg_match('/^\s+/', $attr)) {
+ $working = 1; $mode = 0;
+ if (!$skip) {
+ $attrarr[] = $attrname;
+ }
+ $attr = preg_replace('/^\s+/', '', $attr);
+ }
+ break;
+
+ case 2:
+ // Attribute value, a URL after href= for instance.
+ if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
+ $thisval = filter_xss_bad_protocol($match[1]);
+
+ if (!$skip) {
+ $attrarr[] = "$attrname=\"$thisval\"";
+ }
+ $working = 1;
+ $mode = 0;
+ $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
+ break;
+ }
+
+ if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
+ $thisval = filter_xss_bad_protocol($match[1]);
+
+ if (!$skip) {
+ $attrarr[] = "$attrname='$thisval'";
+ }
+ $working = 1; $mode = 0;
+ $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
+ break;
+ }
+
+ if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
+ $thisval = filter_xss_bad_protocol($match[1]);
+
+ if (!$skip) {
+ $attrarr[] = "$attrname=\"$thisval\"";
+ }
+ $working = 1; $mode = 0;
+ $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
+ }
+ break;
+ }
+
+ if ($working == 0) {
+ // Not well formed; remove and try again.
+ $attr = preg_replace('/
+ ^
+ (
+ "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
+ | # or
+ \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
+ | # or
+ \S # - a non-whitespace character
+ )* # any number of the above three
+ \s* # any number of whitespaces
+ /x', '', $attr);
+ $mode = 0;
+ }
+ }
+
+ // The attribute list ends with a valueless attribute like "selected".
+ if ($mode == 1 && !$skip) {
+ $attrarr[] = $attrname;
+ }
+ return $attrarr;
+}
+
+/**
+ * Processes an HTML attribute value and strips dangerous protocols from URLs.
+ *
+ * @param $string
+ * The string with the attribute value.
+ * @param $decode
+ * (deprecated) Whether to decode entities in the $string. Set to FALSE if the
+ * $string is in plain text, TRUE otherwise. Defaults to TRUE. This parameter
+ * is deprecated and will be removed in Drupal 8. To process a plain-text URI,
+ * call drupal_strip_dangerous_protocols() or check_url() instead.
+ *
+ * @return
+ * Cleaned up and HTML-escaped version of $string.
+ */
+function filter_xss_bad_protocol($string, $decode = TRUE) {
+ // Get the plain text representation of the attribute value (i.e. its meaning).
+ // @todo Remove the $decode parameter in Drupal 8, and always assume an HTML
+ // string that needs decoding.
+ if ($decode) {
+ if (!function_exists('decode_entities')) {
+ require_once DRUPAL_ROOT . '/includes/unicode.inc';
+ }
+
+ $string = decode_entities($string);
+ }
+ return check_plain(drupal_strip_dangerous_protocols($string));
+}
+
+/**
+ * @} End of "defgroup sanitization".
+ */
+
+/**
+ * @defgroup format Formatting
+ * @{
+ * Functions to format numbers, strings, dates, etc.
+ */
+
+/**
+ * Formats an RSS channel.
+ *
+ * Arbitrary elements may be added using the $args associative array.
+ */
+function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
+ global $language_content;
+ $langcode = $langcode ? $langcode : $language_content->language;
+
+ $output = "<channel>\n";
+ $output .= ' <title>' . check_plain($title) . "</title>\n";
+ $output .= ' <link>' . check_url($link) . "</link>\n";
+
+ // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
+ // We strip all HTML tags, but need to prevent double encoding from properly
+ // escaped source data (such as &amp becoming &amp;amp;).
+ $output .= ' <description>' . check_plain(decode_entities(strip_tags($description))) . "</description>\n";
+ $output .= ' <language>' . check_plain($langcode) . "</language>\n";
+ $output .= format_xml_elements($args);
+ $output .= $items;
+ $output .= "</channel>\n";
+
+ return $output;
+}
+
+/**
+ * Formats a single RSS item.
+ *
+ * Arbitrary elements may be added using the $args associative array.
+ */
+function format_rss_item($title, $link, $description, $args = array()) {
+ $output = "<item>\n";
+ $output .= ' <title>' . check_plain($title) . "</title>\n";
+ $output .= ' <link>' . check_url($link) . "</link>\n";
+ $output .= ' <description>' . check_plain($description) . "</description>\n";
+ $output .= format_xml_elements($args);
+ $output .= "</item>\n";
+
+ return $output;
+}
+
+/**
+ * Formats XML elements.
+ *
+ * @param $array
+ * An array where each item represents an element and is either a:
+ * - (key => value) pair (<key>value</key>)
+ * - Associative array with fields:
+ * - 'key': element name
+ * - 'value': element contents
+ * - 'attributes': associative array of element attributes
+ *
+ * In both cases, 'value' can be a simple string, or it can be another array
+ * with the same format as $array itself for nesting.
+ */
+function format_xml_elements($array) {
+ $output = '';
+ foreach ($array as $key => $value) {
+ if (is_numeric($key)) {
+ if ($value['key']) {
+ $output .= ' <' . $value['key'];
+ if (isset($value['attributes']) && is_array($value['attributes'])) {
+ $output .= drupal_attributes($value['attributes']);
+ }
+
+ if (isset($value['value']) && $value['value'] != '') {
+ $output .= '>' . (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) . '</' . $value['key'] . ">\n";
+ }
+ else {
+ $output .= " />\n";
+ }
+ }
+ }
+ else {
+ $output .= ' <' . $key . '>' . (is_array($value) ? format_xml_elements($value) : check_plain($value)) . "</$key>\n";
+ }
+ }
+ return $output;
+}
+
+/**
+ * Formats a string containing a count of items.
+ *
+ * This function ensures that the string is pluralized correctly. Since t() is
+ * called by this function, make sure not to pass already-localized strings to
+ * it.
+ *
+ * For example:
+ * @code
+ * $output = format_plural($node->comment_count, '1 comment', '@count comments');
+ * @endcode
+ *
+ * Example with additional replacements:
+ * @code
+ * $output = format_plural($update_count,
+ * 'Changed the content type of 1 post from %old-type to %new-type.',
+ * 'Changed the content type of @count posts from %old-type to %new-type.',
+ * array('%old-type' => $info->old_type, '%new-type' => $info->new_type));
+ * @endcode
+ *
+ * @param $count
+ * The item count to display.
+ * @param $singular
+ * The string for the singular case. Make sure it is clear this is singular,
+ * to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not
+ * use @count in the singular string.
+ * @param $plural
+ * The string for the plural case. Make sure it is clear this is plural, to
+ * ease translation. Use @count in place of the item count, as in
+ * "@count new comments".
+ * @param $args
+ * An associative array of replacements to make after translation. Instances
+ * of any key in this array are replaced with the corresponding value.
+ * Based on the first character of the key, the value is escaped and/or
+ * themed. See format_string(). Note that you do not need to include @count
+ * in this array; this replacement is done automatically for the plural case.
+ * @param $options
+ * An associative array of additional options. See t() for allowed keys.
+ *
+ * @return
+ * A translated string.
+ *
+ * @see t()
+ * @see format_string()
+ */
+function format_plural($count, $singular, $plural, array $args = array(), array $options = array()) {
+ $args['@count'] = $count;
+ if ($count == 1) {
+ return t($singular, $args, $options);
+ }
+
+ // Get the plural index through the gettext formula.
+ $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, isset($options['langcode']) ? $options['langcode'] : NULL) : -1;
+ // If the index cannot be computed, use the plural as a fallback (which
+ // allows for most flexiblity with the replaceable @count value).
+ if ($index < 0) {
+ return t($plural, $args, $options);
+ }
+ else {
+ switch ($index) {
+ case "0":
+ return t($singular, $args, $options);
+ case "1":
+ return t($plural, $args, $options);
+ default:
+ unset($args['@count']);
+ $args['@count[' . $index . ']'] = $count;
+ return t(strtr($plural, array('@count' => '@count[' . $index . ']')), $args, $options);
+ }
+ }
+}
+
+/**
+ * Parses a given byte count.
+ *
+ * @param $size
+ * A size expressed as a number of bytes with optional SI or IEC binary unit
+ * prefix (e.g. 2, 3K, 5MB, 10G, 6GiB, 8 bytes, 9mbytes).
+ *
+ * @return
+ * An integer representation of the size in bytes.
+ */
+function parse_size($size) {
+ $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
+ $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
+ if ($unit) {
+ // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
+ return round($size * pow(DRUPAL_KILOBYTE, stripos('bkmgtpezy', $unit[0])));
+ }
+ else {
+ return round($size);
+ }
+}
+
+/**
+ * Generates a string representation for the given byte count.
+ *
+ * @param $size
+ * A size in bytes.
+ * @param $langcode
+ * Optional language code to translate to a language other than what is used
+ * to display the page.
+ *
+ * @return
+ * A translated string representation of the size.
+ */
+function format_size($size, $langcode = NULL) {
+ if ($size < DRUPAL_KILOBYTE) {
+ return format_plural($size, '1 byte', '@count bytes', array(), array('langcode' => $langcode));
+ }
+ else {
+ $size = $size / DRUPAL_KILOBYTE; // Convert bytes to kilobytes.
+ $units = array(
+ t('@size KB', array(), array('langcode' => $langcode)),
+ t('@size MB', array(), array('langcode' => $langcode)),
+ t('@size GB', array(), array('langcode' => $langcode)),
+ t('@size TB', array(), array('langcode' => $langcode)),
+ t('@size PB', array(), array('langcode' => $langcode)),
+ t('@size EB', array(), array('langcode' => $langcode)),
+ t('@size ZB', array(), array('langcode' => $langcode)),
+ t('@size YB', array(), array('langcode' => $langcode)),
+ );
+ foreach ($units as $unit) {
+ if (round($size, 2) >= DRUPAL_KILOBYTE) {
+ $size = $size / DRUPAL_KILOBYTE;
+ }
+ else {
+ break;
+ }
+ }
+ return str_replace('@size', round($size, 2), $unit);
+ }
+}
+
+/**
+ * Formats a time interval with the requested granularity.
+ *
+ * @param $interval
+ * The length of the interval in seconds.
+ * @param $granularity
+ * How many different units to display in the string.
+ * @param $langcode
+ * Optional language code to translate to a language other than
+ * what is used to display the page.
+ *
+ * @return
+ * A translated string representation of the interval.
+ */
+function format_interval($interval, $granularity = 2, $langcode = NULL) {
+ $units = array(
+ '1 year|@count years' => 31536000,
+ '1 month|@count months' => 2592000,
+ '1 week|@count weeks' => 604800,
+ '1 day|@count days' => 86400,
+ '1 hour|@count hours' => 3600,
+ '1 min|@count min' => 60,
+ '1 sec|@count sec' => 1
+ );
+ $output = '';
+ foreach ($units as $key => $value) {
+ $key = explode('|', $key);
+ if ($interval >= $value) {
+ $output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
+ $interval %= $value;
+ $granularity--;
+ }
+
+ if ($granularity == 0) {
+ break;
+ }
+ }
+ return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
+}
+
+/**
+ * Formats a date, using a date type or a custom date format string.
+ *
+ * @param $timestamp
+ * A UNIX timestamp to format.
+ * @param $type
+ * (optional) The format to use, one of:
+ * - 'short', 'medium', or 'long' (the corresponding built-in date formats).
+ * - The name of a date type defined by a module in hook_date_format_types(),
+ * if it's been assigned a format.
+ * - The machine name of an administrator-defined date format.
+ * - 'custom', to use $format.
+ * Defaults to 'medium'.
+ * @param $format
+ * (optional) If $type is 'custom', a PHP date format string suitable for
+ * input to date(). Use a backslash to escape ordinary text, so it does not
+ * get interpreted as date format characters.
+ * @param $timezone
+ * (optional) Time zone identifier, as described at
+ * http://php.net/manual/timezones.php Defaults to the time zone used to
+ * display the page.
+ * @param $langcode
+ * (optional) Language code to translate to. Defaults to the language used to
+ * display the page.
+ *
+ * @return
+ * A translated date string in the requested format.
+ */
+function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
+ // Use the advanced drupal_static() pattern, since this is called very often.
+ static $drupal_static_fast;
+ if (!isset($drupal_static_fast)) {
+ $drupal_static_fast['timezones'] = &drupal_static(__FUNCTION__);
+ }
+ $timezones = &$drupal_static_fast['timezones'];
+
+ if (!isset($timezone)) {
+ $timezone = date_default_timezone_get();
+ }
+ // Store DateTimeZone objects in an array rather than repeatedly
+ // constructing identical objects over the life of a request.
+ if (!isset($timezones[$timezone])) {
+ $timezones[$timezone] = timezone_open($timezone);
+ }
+
+ // Use the default langcode if none is set.
+ global $language;
+ if (empty($langcode)) {
+ $langcode = isset($language->language) ? $language->language : 'en';
+ }
+
+ switch ($type) {
+ case 'short':
+ $format = variable_get('date_format_short', 'm/d/Y - H:i');
+ break;
+
+ case 'long':
+ $format = variable_get('date_format_long', 'l, F j, Y - H:i');
+ break;
+
+ case 'custom':
+ // No change to format.
+ break;
+
+ case 'medium':
+ default:
+ // Retrieve the format of the custom $type passed.
+ if ($type != 'medium') {
+ $format = variable_get('date_format_' . $type, '');
+ }
+ // Fall back to 'medium'.
+ if ($format === '') {
+ $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
+ }
+ break;
+ }
+
+ // Create a DateTime object from the timestamp.
+ $date_time = date_create('@' . $timestamp);
+ // Set the time zone for the DateTime object.
+ date_timezone_set($date_time, $timezones[$timezone]);
+
+ // Encode markers that should be translated. 'A' becomes '\xEF\AA\xFF'.
+ // xEF and xFF are invalid UTF-8 sequences, and we assume they are not in the
+ // input string.
+ // Paired backslashes are isolated to prevent errors in read-ahead evaluation.
+ // The read-ahead expression ensures that A matches, but not \A.
+ $format = preg_replace(array('/\\\\\\\\/', '/(?<!\\\\)([AaeDlMTF])/'), array("\xEF\\\\\\\\\xFF", "\xEF\\\\\$1\$1\xFF"), $format);
+
+ // Call date_format().
+ $format = date_format($date_time, $format);
+
+ // Pass the langcode to _format_date_callback().
+ _format_date_callback(NULL, $langcode);
+
+ // Translate the marked sequences.
+ return preg_replace_callback('/\xEF([AaeDlMTF]?)(.*?)\xFF/', '_format_date_callback', $format);
+}
+
+/**
+ * Returns an ISO8601 formatted date based on the given date.
+ *
+ * Callback for use within hook_rdf_mapping() implementations.
+ *
+ * @param $date
+ * A UNIX timestamp.
+ *
+ * @return string
+ * An ISO8601 formatted date.
+ */
+function date_iso8601($date) {
+ // The DATE_ISO8601 constant cannot be used here because it does not match
+ // date('c') and produces invalid RDF markup.
+ return date('c', $date);
+}
+
+/**
+ * Translates a formatted date string.
+ *
+ * Callback for preg_replace_callback() within format_date().
+ */
+function _format_date_callback(array $matches = NULL, $new_langcode = NULL) {
+ // We cache translations to avoid redundant and rather costly calls to t().
+ static $cache, $langcode;
+
+ if (!isset($matches)) {
+ $langcode = $new_langcode;
+ return;
+ }
+
+ $code = $matches[1];
+ $string = $matches[2];
+
+ if (!isset($cache[$langcode][$code][$string])) {
+ $options = array(
+ 'langcode' => $langcode,
+ );
+
+ if ($code == 'F') {
+ $options['context'] = 'Long month name';
+ }
+
+ if ($code == '') {
+ $cache[$langcode][$code][$string] = $string;
+ }
+ else {
+ $cache[$langcode][$code][$string] = t($string, array(), $options);
+ }
+ }
+ return $cache[$langcode][$code][$string];
+}
+
+/**
+ * Format a username.
+ *
+ * This is also the label callback implementation of
+ * callback_entity_info_label() for user_entity_info().
+ *
+ * By default, the passed-in object's 'name' property is used if it exists, or
+ * else, the site-defined value for the 'anonymous' variable. However, a module
+ * may override this by implementing hook_username_alter(&$name, $account).
+ *
+ * @see hook_username_alter()
+ *
+ * @param $account
+ * The account object for the user whose name is to be formatted.
+ *
+ * @return
+ * An unsanitized string with the username to display. The code receiving
+ * this result must ensure that check_plain() is called on it before it is
+ * printed to the page.
+ */
+function format_username($account) {
+ $name = !empty($account->name) ? $account->name : variable_get('anonymous', t('Anonymous'));
+ drupal_alter('username', $name, $account);
+ return $name;
+}
+
+/**
+ * @} End of "defgroup format".
+ */
+
+/**
+ * Generates an internal or external URL.
+ *
+ * When creating links in modules, consider whether l() could be a better
+ * alternative than url().
+ *
+ * @param $path
+ * (optional) The internal path or external URL being linked to, such as
+ * "node/34" or "http://example.com/foo". The default value is equivalent to
+ * passing in '<front>'. A few notes:
+ * - If you provide a full URL, it will be considered an external URL.
+ * - If you provide only the path (e.g. "node/34"), it will be
+ * considered an internal link. In this case, it should be a system URL,
+ * and it will be replaced with the alias, if one exists. Additional query
+ * arguments for internal paths must be supplied in $options['query'], not
+ * included in $path.
+ * - If you provide an internal path and $options['alias'] is set to TRUE, the
+ * path is assumed already to be the correct path alias, and the alias is
+ * not looked up.
+ * - The special string '<front>' generates a link to the site's base URL.
+ * - If your external URL contains a query (e.g. http://example.com/foo?a=b),
+ * then you can either URL encode the query keys and values yourself and
+ * include them in $path, or use $options['query'] to let this function
+ * URL encode them.
+ * @param $options
+ * (optional) An associative array of additional options, with the following
+ * elements:
+ * - 'query': An array of query key/value-pairs (without any URL-encoding) to
+ * append to the URL.
+ * - 'fragment': A fragment identifier (named anchor) to append to the URL.
+ * Do not include the leading '#' character.
+ * - 'absolute': Defaults to FALSE. Whether to force the output to be an
+ * absolute link (beginning with http:). Useful for links that will be
+ * displayed outside the site, such as in an RSS feed.
+ * - 'alias': Defaults to FALSE. Whether the given path is a URL alias
+ * already.
+ * - 'external': Whether the given path is an external URL.
+ * - 'language': An optional language object. If the path being linked to is
+ * internal to the site, $options['language'] is used to look up the alias
+ * for the URL. If $options['language'] is omitted, the global $language_url
+ * will be used.
+ * - 'https': Whether this URL should point to a secure location. If not
+ * defined, the current scheme is used, so the user stays on HTTP or HTTPS
+ * respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can
+ * only be enforced when the variable 'https' is set to TRUE.
+ * - 'base_url': Only used internally, to modify the base URL when a language
+ * dependent URL requires so.
+ * - 'prefix': Only used internally, to modify the path when a language
+ * dependent URL requires so.
+ * - 'script': The script filename in Drupal's root directory to use when
+ * clean URLs are disabled, such as 'index.php'. Defaults to an empty
+ * string, as most modern web servers automatically find 'index.php'. If
+ * clean URLs are disabled, the value of $path is appended as query
+ * parameter 'q' to $options['script'] in the returned URL. When deploying
+ * Drupal on a web server that cannot be configured to automatically find
+ * index.php, then hook_url_outbound_alter() can be implemented to force
+ * this value to 'index.php'.
+ * - 'entity_type': The entity type of the object that called url(). Only
+ * set if url() is invoked by entity_uri().
+ * - 'entity': The entity object (such as a node) for which the URL is being
+ * generated. Only set if url() is invoked by entity_uri().
+ *
+ * @return
+ * A string containing a URL to the given path.
+ */
+function url($path = NULL, array $options = array()) {
+ // Merge in defaults.
+ $options += array(
+ 'fragment' => '',
+ 'query' => array(),
+ 'absolute' => FALSE,
+ 'alias' => FALSE,
+ 'prefix' => ''
+ );
+
+ if (!isset($options['external'])) {
+ // Return an external link if $path contains an allowed absolute URL. Only
+ // call the slow drupal_strip_dangerous_protocols() if $path contains a ':'
+ // before any / ? or #. Note: we could use url_is_external($path) here, but
+ // that would require another function call, and performance inside url() is
+ // critical.
+ $colonpos = strpos($path, ':');
+ $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path);
+ }
+
+ // Preserve the original path before altering or aliasing.
+ $original_path = $path;
+
+ // Allow other modules to alter the outbound URL and options.
+ drupal_alter('url_outbound', $path, $options, $original_path);
+
+ if (isset($options['fragment']) && $options['fragment'] !== '') {
+ $options['fragment'] = '#' . $options['fragment'];
+ }
+
+ if ($options['external']) {
+ // Split off the fragment.
+ if (strpos($path, '#') !== FALSE) {
+ list($path, $old_fragment) = explode('#', $path, 2);
+ // If $options contains no fragment, take it over from the path.
+ if (isset($old_fragment) && !$options['fragment']) {
+ $options['fragment'] = '#' . $old_fragment;
+ }
+ }
+ // Append the query.
+ if ($options['query']) {
+ $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . drupal_http_build_query($options['query']);
+ }
+ if (isset($options['https']) && variable_get('https', FALSE)) {
+ if ($options['https'] === TRUE) {
+ $path = str_replace('http://', 'https://', $path);
+ }
+ elseif ($options['https'] === FALSE) {
+ $path = str_replace('https://', 'http://', $path);
+ }
+ }
+ // Reassemble.
+ return $path . $options['fragment'];
+ }
+
+ global $base_url, $base_secure_url, $base_insecure_url;
+
+ // The base_url might be rewritten from the language rewrite in domain mode.
+ if (!isset($options['base_url'])) {
+ if (isset($options['https']) && variable_get('https', FALSE)) {
+ if ($options['https'] === TRUE) {
+ $options['base_url'] = $base_secure_url;
+ $options['absolute'] = TRUE;
+ }
+ elseif ($options['https'] === FALSE) {
+ $options['base_url'] = $base_insecure_url;
+ $options['absolute'] = TRUE;
+ }
+ }
+ else {
+ $options['base_url'] = $base_url;
+ }
+ }
+
+ // The special path '<front>' links to the default front page.
+ if ($path == '<front>') {
+ $path = '';
+ }
+ elseif (!empty($path) && !$options['alias']) {
+ $language = isset($options['language']) && isset($options['language']->language) ? $options['language']->language : '';
+ $alias = drupal_get_path_alias($original_path, $language);
+ if ($alias != $original_path) {
+ $path = $alias;
+ }
+ }
+
+ $base = $options['absolute'] ? $options['base_url'] . '/' : base_path();
+ $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
+
+ // With Clean URLs.
+ if (!empty($GLOBALS['conf']['clean_url'])) {
+ $path = drupal_encode_path($prefix . $path);
+ if ($options['query']) {
+ return $base . $path . '?' . drupal_http_build_query($options['query']) . $options['fragment'];
+ }
+ else {
+ return $base . $path . $options['fragment'];
+ }
+ }
+ // Without Clean URLs.
+ else {
+ $path = $prefix . $path;
+ $query = array();
+ if (!empty($path)) {
+ $query['q'] = $path;
+ }
+ if ($options['query']) {
+ // We do not use array_merge() here to prevent overriding $path via query
+ // parameters.
+ $query += $options['query'];
+ }
+ $query = $query ? ('?' . drupal_http_build_query($query)) : '';
+ $script = isset($options['script']) ? $options['script'] : '';
+ return $base . $script . $query . $options['fragment'];
+ }
+}
+
+/**
+ * Returns TRUE if a path is external to Drupal (e.g. http://example.com).
+ *
+ * If a path cannot be assessed by Drupal's menu handler, then we must
+ * treat it as potentially insecure.
+ *
+ * @param $path
+ * The internal path or external URL being linked to, such as "node/34" or
+ * "http://example.com/foo".
+ *
+ * @return
+ * Boolean TRUE or FALSE, where TRUE indicates an external path.
+ */
+function url_is_external($path) {
+ $colonpos = strpos($path, ':');
+ // Avoid calling drupal_strip_dangerous_protocols() if there is any
+ // slash (/), hash (#) or question_mark (?) before the colon (:)
+ // occurrence - if any - as this would clearly mean it is not a URL.
+ return $colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && drupal_strip_dangerous_protocols($path) == $path;
+}
+
+/**
+ * Formats an attribute string for an HTTP header.
+ *
+ * @param $attributes
+ * An associative array of attributes such as 'rel'.
+ *
+ * @return
+ * A ; separated string ready for insertion in a HTTP header. No escaping is
+ * performed for HTML entities, so this string is not safe to be printed.
+ *
+ * @see drupal_add_http_header()
+ */
+function drupal_http_header_attributes(array $attributes = array()) {
+ foreach ($attributes as $attribute => &$data) {
+ if (is_array($data)) {
+ $data = implode(' ', $data);
+ }
+ $data = $attribute . '="' . $data . '"';
+ }
+ return $attributes ? ' ' . implode('; ', $attributes) : '';
+}
+
+/**
+ * Converts an associative array to an XML/HTML tag attribute string.
+ *
+ * Each array key and its value will be formatted into an attribute string.
+ * If a value is itself an array, then its elements are concatenated to a single
+ * space-delimited string (for example, a class attribute with multiple values).
+ *
+ * Attribute values are sanitized by running them through check_plain().
+ * Attribute names are not automatically sanitized. When using user-supplied
+ * attribute names, it is strongly recommended to allow only white-listed names,
+ * since certain attributes carry security risks and can be abused.
+ *
+ * Examples of security aspects when using drupal_attributes:
+ * @code
+ * // By running the value in the following statement through check_plain,
+ * // the malicious script is neutralized.
+ * drupal_attributes(array('title' => t('<script>steal_cookie();</script>')));
+ *
+ * // The statement below demonstrates dangerous use of drupal_attributes, and
+ * // will return an onmouseout attribute with JavaScript code that, when used
+ * // as attribute in a tag, will cause users to be redirected to another site.
+ * //
+ * // In this case, the 'onmouseout' attribute should not be whitelisted --
+ * // you don't want users to have the ability to add this attribute or others
+ * // that take JavaScript commands.
+ * drupal_attributes(array('onmouseout' => 'window.location="http://malicious.com/";')));
+ * @endcode
+ *
+ * @param $attributes
+ * An associative array of key-value pairs to be converted to attributes.
+ *
+ * @return
+ * A string ready for insertion in a tag (starts with a space).
+ *
+ * @ingroup sanitization
+ */
+function drupal_attributes(array $attributes = array()) {
+ foreach ($attributes as $attribute => &$data) {
+ $data = implode(' ', (array) $data);
+ $data = $attribute . '="' . check_plain($data) . '"';
+ }
+ return $attributes ? ' ' . implode(' ', $attributes) : '';
+}
+
+/**
+ * Formats an internal or external URL link as an HTML anchor tag.
+ *
+ * This function correctly handles aliased paths and adds an 'active' class
+ * attribute to links that point to the current page (for theming), so all
+ * internal links output by modules should be generated by this function if
+ * possible.
+ *
+ * However, for links enclosed in translatable text you should use t() and
+ * embed the HTML anchor tag directly in the translated string. For example:
+ * @code
+ * t('Visit the <a href="@url">settings</a> page', array('@url' => url('admin')));
+ * @endcode
+ * This keeps the context of the link title ('settings' in the example) for
+ * translators.
+ *
+ * @param string $text
+ * The translated link text for the anchor tag.
+ * @param string $path
+ * The internal path or external URL being linked to, such as "node/34" or
+ * "http://example.com/foo". After the url() function is called to construct
+ * the URL from $path and $options, the resulting URL is passed through
+ * check_plain() before it is inserted into the HTML anchor tag, to ensure
+ * well-formed HTML. See url() for more information and notes.
+ * @param array $options
+ * An associative array of additional options. Defaults to an empty array. It
+ * may contain the following elements.
+ * - 'attributes': An associative array of HTML attributes to apply to the
+ * anchor tag. If element 'class' is included, it must be an array; 'title'
+ * must be a string; other elements are more flexible, as they just need
+ * to work in a call to drupal_attributes($options['attributes']).
+ * - 'html' (default FALSE): Whether $text is HTML or just plain-text. For
+ * example, to make an image tag into a link, this must be set to TRUE, or
+ * you will see the escaped HTML image tag. $text is not sanitized if
+ * 'html' is TRUE. The calling function must ensure that $text is already
+ * safe.
+ * - 'language': An optional language object. If the path being linked to is
+ * internal to the site, $options['language'] is used to determine whether
+ * the link is "active", or pointing to the current page (the language as
+ * well as the path must match). This element is also used by url().
+ * - Additional $options elements used by the url() function.
+ *
+ * @return string
+ * An HTML string containing a link to the given path.
+ *
+ * @see url()
+ */
+function l($text, $path, array $options = array()) {
+ global $language_url;
+ static $use_theme = NULL;
+
+ // Merge in defaults.
+ $options += array(
+ 'attributes' => array(),
+ 'html' => FALSE,
+ );
+
+ // Append active class.
+ if (($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) &&
+ (empty($options['language']) || $options['language']->language == $language_url->language)) {
+ $options['attributes']['class'][] = 'active';
+ }
+
+ // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
+ // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
+ if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
+ $options['attributes']['title'] = strip_tags($options['attributes']['title']);
+ }
+
+ // Determine if rendering of the link is to be done with a theme function
+ // or the inline default. Inline is faster, but if the theme system has been
+ // loaded and a module or theme implements a preprocess or process function
+ // or overrides the theme_link() function, then invoke theme(). Preliminary
+ // benchmarks indicate that invoking theme() can slow down the l() function
+ // by 20% or more, and that some of the link-heavy Drupal pages spend more
+ // than 10% of the total page request time in the l() function.
+ if (!isset($use_theme) && function_exists('theme')) {
+ // Allow edge cases to prevent theme initialization and force inline link
+ // rendering.
+ if (variable_get('theme_link', TRUE)) {
+ drupal_theme_initialize();
+ $registry = theme_get_registry(FALSE);
+ // We don't want to duplicate functionality that's in theme(), so any
+ // hint of a module or theme doing anything at all special with the 'link'
+ // theme hook should simply result in theme() being called. This includes
+ // the overriding of theme_link() with an alternate function or template,
+ // the presence of preprocess or process functions, or the presence of
+ // include files.
+ $use_theme = !isset($registry['link']['function']) || ($registry['link']['function'] != 'theme_link');
+ $use_theme = $use_theme || !empty($registry['link']['preprocess functions']) || !empty($registry['link']['process functions']) || !empty($registry['link']['includes']);
+ }
+ else {
+ $use_theme = FALSE;
+ }
+ }
+ if ($use_theme) {
+ return theme('link', array('text' => $text, 'path' => $path, 'options' => $options));
+ }
+ // The result of url() is a plain-text URL. Because we are using it here
+ // in an HTML argument context, we need to encode it properly.
+ return '<a href="' . check_plain(url($path, $options)) . '"' . drupal_attributes($options['attributes']) . '>' . ($options['html'] ? $text : check_plain($text)) . '</a>';
+}
+
+/**
+ * Delivers a page callback result to the browser in the appropriate format.
+ *
+ * This function is most commonly called by menu_execute_active_handler(), but
+ * can also be called by error conditions such as drupal_not_found(),
+ * drupal_access_denied(), and drupal_site_offline().
+ *
+ * When a user requests a page, index.php calls menu_execute_active_handler(),
+ * which calls the 'page callback' function registered in hook_menu(). The page
+ * callback function can return one of:
+ * - NULL: to indicate no content.
+ * - An integer menu status constant: to indicate an error condition.
+ * - A string of HTML content.
+ * - A renderable array of content.
+ * Returning a renderable array rather than a string of HTML is preferred,
+ * because that provides modules with more flexibility in customizing the final
+ * result.
+ *
+ * When the page callback returns its constructed content to
+ * menu_execute_active_handler(), this function gets called. The purpose of
+ * this function is to determine the most appropriate 'delivery callback'
+ * function to route the content to. The delivery callback function then
+ * sends the content to the browser in the needed format. The default delivery
+ * callback is drupal_deliver_html_page(), which delivers the content as an HTML
+ * page, complete with blocks in addition to the content. This default can be
+ * overridden on a per menu router item basis by setting 'delivery callback' in
+ * hook_menu() or hook_menu_alter(), and can also be overridden on a per request
+ * basis in hook_page_delivery_callback_alter().
+ *
+ * For example, the same page callback function can be used for an HTML
+ * version of the page and an Ajax version of the page. The page callback
+ * function just needs to decide what content is to be returned and the
+ * delivery callback function will send it as an HTML page or an Ajax
+ * response, as appropriate.
+ *
+ * In order for page callbacks to be reusable in different delivery formats,
+ * they should not issue any "print" or "echo" statements, but instead just
+ * return content.
+ *
+ * Also note that this function does not perform access checks. The delivery
+ * callback function specified in hook_menu(), hook_menu_alter(), or
+ * hook_page_delivery_callback_alter() will be called even if the router item
+ * access checks fail. This is intentional (it is needed for JSON and other
+ * purposes), but it has security implications. Do not call this function
+ * directly unless you understand the security implications, and be careful in
+ * writing delivery callbacks, so that they do not violate security. See
+ * drupal_deliver_html_page() for an example of a delivery callback that
+ * respects security.
+ *
+ * @param $page_callback_result
+ * The result of a page callback. Can be one of:
+ * - NULL: to indicate no content.
+ * - An integer menu status constant: to indicate an error condition.
+ * - A string of HTML content.
+ * - A renderable array of content.
+ * @param $default_delivery_callback
+ * (Optional) If given, it is the name of a delivery function most likely
+ * to be appropriate for the page request as determined by the calling
+ * function (e.g., menu_execute_active_handler()). If not given, it is
+ * determined from the menu router information of the current page.
+ *
+ * @see menu_execute_active_handler()
+ * @see hook_menu()
+ * @see hook_menu_alter()
+ * @see hook_page_delivery_callback_alter()
+ */
+function drupal_deliver_page($page_callback_result, $default_delivery_callback = NULL) {
+ if (!isset($default_delivery_callback) && ($router_item = menu_get_item())) {
+ $default_delivery_callback = $router_item['delivery_callback'];
+ }
+ $delivery_callback = !empty($default_delivery_callback) ? $default_delivery_callback : 'drupal_deliver_html_page';
+ // Give modules a chance to alter the delivery callback used, based on
+ // request-time context (e.g., HTTP request headers).
+ drupal_alter('page_delivery_callback', $delivery_callback);
+ if (function_exists($delivery_callback)) {
+ $delivery_callback($page_callback_result);
+ }
+ else {
+ // If a delivery callback is specified, but doesn't exist as a function,
+ // something is wrong, but don't print anything, since it's not known
+ // what format the response needs to be in.
+ watchdog('delivery callback not found', 'callback %callback not found: %q.', array('%callback' => $delivery_callback, '%q' => $_GET['q']), WATCHDOG_ERROR);
+ }
+}
+
+/**
+ * Packages and sends the result of a page callback to the browser as HTML.
+ *
+ * @param $page_callback_result
+ * The result of a page callback. Can be one of:
+ * - NULL: to indicate no content.
+ * - An integer menu status constant: to indicate an error condition.
+ * - A string of HTML content.
+ * - A renderable array of content.
+ *
+ * @see drupal_deliver_page()
+ */
+function drupal_deliver_html_page($page_callback_result) {
+ // Emit the correct charset HTTP header, but not if the page callback
+ // result is NULL, since that likely indicates that it printed something
+ // in which case, no further headers may be sent, and not if code running
+ // for this page request has already set the content type header.
+ if (isset($page_callback_result) && is_null(drupal_get_http_header('Content-Type'))) {
+ drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
+ }
+
+ // Send appropriate HTTP-Header for browsers and search engines.
+ global $language;
+ drupal_add_http_header('Content-Language', $language->language);
+
+ // Menu status constants are integers; page content is a string or array.
+ if (is_int($page_callback_result)) {
+ // @todo: Break these up into separate functions?
+ switch ($page_callback_result) {
+ case MENU_NOT_FOUND:
+ // Print a 404 page.
+ drupal_add_http_header('Status', '404 Not Found');
+
+ watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
+
+ // Check for and return a fast 404 page if configured.
+ drupal_fast_404();
+
+ // Keep old path for reference, and to allow forms to redirect to it.
+ if (!isset($_GET['destination'])) {
+ $_GET['destination'] = $_GET['q'];
+ }
+
+ $path = drupal_get_normal_path(variable_get('site_404', ''));
+ if ($path && $path != $_GET['q']) {
+ // Custom 404 handler. Set the active item in case there are tabs to
+ // display, or other dependencies on the path.
+ menu_set_active_item($path);
+ $return = menu_execute_active_handler($path, FALSE);
+ }
+
+ if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
+ // Standard 404 handler.
+ drupal_set_title(t('Page not found'));
+ $return = t('The requested page "@path" could not be found.', array('@path' => request_uri()));
+ }
+
+ drupal_set_page_content($return);
+ $page = element_info('page');
+ print drupal_render_page($page);
+ break;
+
+ case MENU_ACCESS_DENIED:
+ // Print a 403 page.
+ drupal_add_http_header('Status', '403 Forbidden');
+ watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
+
+ // Keep old path for reference, and to allow forms to redirect to it.
+ if (!isset($_GET['destination'])) {
+ $_GET['destination'] = $_GET['q'];
+ }
+
+ $path = drupal_get_normal_path(variable_get('site_403', ''));
+ if ($path && $path != $_GET['q']) {
+ // Custom 403 handler. Set the active item in case there are tabs to
+ // display or other dependencies on the path.
+ menu_set_active_item($path);
+ $return = menu_execute_active_handler($path, FALSE);
+ }
+
+ if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
+ // Standard 403 handler.
+ drupal_set_title(t('Access denied'));
+ $return = t('You are not authorized to access this page.');
+ }
+
+ print drupal_render_page($return);
+ break;
+
+ case MENU_SITE_OFFLINE:
+ // Print a 503 page.
+ drupal_maintenance_theme();
+ drupal_add_http_header('Status', '503 Service unavailable');
+ drupal_set_title(t('Site under maintenance'));
+ print theme('maintenance_page', array('content' => filter_xss_admin(variable_get('maintenance_mode_message',
+ t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal')))))));
+ break;
+ }
+ }
+ elseif (isset($page_callback_result)) {
+ // Print anything besides a menu constant, assuming it's not NULL or
+ // undefined.
+ print drupal_render_page($page_callback_result);
+ }
+
+ // Perform end-of-request tasks.
+ drupal_page_footer();
+}
+
+/**
+ * Performs end-of-request tasks.
+ *
+ * This function sets the page cache if appropriate, and allows modules to
+ * react to the closing of the page by calling hook_exit().
+ */
+function drupal_page_footer() {
+ global $user;
+
+ module_invoke_all('exit');
+
+ // Commit the user session, if needed.
+ drupal_session_commit();
+
+ if (variable_get('cache', 0) && ($cache = drupal_page_set_cache())) {
+ drupal_serve_page_from_cache($cache);
+ }
+ else {
+ ob_flush();
+ }
+
+ _registry_check_code(REGISTRY_WRITE_LOOKUP_CACHE);
+ drupal_cache_system_paths();
+ module_implements_write_cache();
+ system_run_automated_cron();
+}
+
+/**
+ * Performs end-of-request tasks.
+ *
+ * In some cases page requests need to end without calling drupal_page_footer().
+ * In these cases, call drupal_exit() instead. There should rarely be a reason
+ * to call exit instead of drupal_exit();
+ *
+ * @param $destination
+ * If this function is called from drupal_goto(), then this argument
+ * will be a fully-qualified URL that is the destination of the redirect.
+ * This should be passed along to hook_exit() implementations.
+ */
+function drupal_exit($destination = NULL) {
+ if (drupal_get_bootstrap_phase() == DRUPAL_BOOTSTRAP_FULL) {
+ if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
+ module_invoke_all('exit', $destination);
+ }
+ drupal_session_commit();
+ }
+ exit;
+}
+
+/**
+ * Forms an associative array from a linear array.
+ *
+ * This function walks through the provided array and constructs an associative
+ * array out of it. The keys of the resulting array will be the values of the
+ * input array. The values will be the same as the keys unless a function is
+ * specified, in which case the output of the function is used for the values
+ * instead.
+ *
+ * @param $array
+ * A linear array.
+ * @param $function
+ * A name of a function to apply to all values before output.
+ *
+ * @return
+ * An associative array.
+ */
+function drupal_map_assoc($array, $function = NULL) {
+ // array_combine() fails with empty arrays:
+ // http://bugs.php.net/bug.php?id=34857.
+ $array = !empty($array) ? array_combine($array, $array) : array();
+ if (is_callable($function)) {
+ $array = array_map($function, $array);
+ }
+ return $array;
+}
+
+/**
+ * Attempts to set the PHP maximum execution time.
+ *
+ * This function is a wrapper around the PHP function set_time_limit().
+ * When called, set_time_limit() restarts the timeout counter from zero.
+ * In other words, if the timeout is the default 30 seconds, and 25 seconds
+ * into script execution a call such as set_time_limit(20) is made, the
+ * script will run for a total of 45 seconds before timing out.
+ *
+ * It also means that it is possible to decrease the total time limit if
+ * the sum of the new time limit and the current time spent running the
+ * script is inferior to the original time limit. It is inherent to the way
+ * set_time_limit() works, it should rather be called with an appropriate
+ * value every time you need to allocate a certain amount of time
+ * to execute a task than only once at the beginning of the script.
+ *
+ * Before calling set_time_limit(), we check if this function is available
+ * because it could be disabled by the server administrator. We also hide all
+ * the errors that could occur when calling set_time_limit(), because it is
+ * not possible to reliably ensure that PHP or a security extension will
+ * not issue a warning/error if they prevent the use of this function.
+ *
+ * @param $time_limit
+ * An integer specifying the new time limit, in seconds. A value of 0
+ * indicates unlimited execution time.
+ *
+ * @ingroup php_wrappers
+ */
+function drupal_set_time_limit($time_limit) {
+ if (function_exists('set_time_limit')) {
+ @set_time_limit($time_limit);
+ }
+}
+
+/**
+ * Returns the path to a system item (module, theme, etc.).
+ *
+ * @param $type
+ * The type of the item (i.e. theme, theme_engine, module, profile).
+ * @param $name
+ * The name of the item for which the path is requested.
+ *
+ * @return
+ * The path to the requested item or an empty string if the item is not found.
+ */
+function drupal_get_path($type, $name) {
+ return dirname(drupal_get_filename($type, $name));
+}
+
+/**
+ * Returns the base URL path (i.e., directory) of the Drupal installation.
+ *
+ * base_path() adds a "/" to the beginning and end of the returned path if the
+ * path is not empty. At the very least, this will return "/".
+ *
+ * Examples:
+ * - http://example.com returns "/" because the path is empty.
+ * - http://example.com/drupal/folder returns "/drupal/folder/".
+ */
+function base_path() {
+ return $GLOBALS['base_path'];
+}
+
+/**
+ * Adds a LINK tag with a distinct 'rel' attribute to the page's HEAD.
+ *
+ * This function can be called as long the HTML header hasn't been sent, which
+ * on normal pages is up through the preprocess step of theme('html'). Adding
+ * a link will overwrite a prior link with the exact same 'rel' and 'href'
+ * attributes.
+ *
+ * @param $attributes
+ * Associative array of element attributes including 'href' and 'rel'.
+ * @param $header
+ * Optional flag to determine if a HTTP 'Link:' header should be sent.
+ */
+function drupal_add_html_head_link($attributes, $header = FALSE) {
+ $element = array(
+ '#tag' => 'link',
+ '#attributes' => $attributes,
+ );
+ $href = $attributes['href'];
+
+ if ($header) {
+ // Also add a HTTP header "Link:".
+ $href = '<' . check_plain($attributes['href']) . '>;';
+ unset($attributes['href']);
+ $element['#attached']['drupal_add_http_header'][] = array('Link', $href . drupal_http_header_attributes($attributes), TRUE);
+ }
+
+ drupal_add_html_head($element, 'drupal_add_html_head_link:' . $attributes['rel'] . ':' . $href);
+}
+
+/**
+ * Adds a cascading stylesheet to the stylesheet queue.
+ *
+ * Calling drupal_static_reset('drupal_add_css') will clear all cascading
+ * stylesheets added so far.
+ *
+ * If CSS aggregation/compression is enabled, all cascading style sheets added
+ * with $options['preprocess'] set to TRUE will be merged into one aggregate
+ * file and compressed by removing all extraneous white space.
+ * Preprocessed inline stylesheets will not be aggregated into this single file;
+ * instead, they are just compressed upon output on the page. Externally hosted
+ * stylesheets are never aggregated or compressed.
+ *
+ * The reason for aggregating the files is outlined quite thoroughly here:
+ * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
+ * to request overhead, one bigger file just loads faster than two smaller ones
+ * half its size."
+ *
+ * $options['preprocess'] should be only set to TRUE when a file is required for
+ * all typical visitors and most pages of a site. It is critical that all
+ * preprocessed files are added unconditionally on every page, even if the
+ * files do not happen to be needed on a page. This is normally done by calling
+ * drupal_add_css() in a hook_init() implementation.
+ *
+ * Non-preprocessed files should only be added to the page when they are
+ * actually needed.
+ *
+ * @param $data
+ * (optional) The stylesheet data to be added, depending on what is passed
+ * through to the $options['type'] parameter:
+ * - 'file': The path to the CSS file relative to the base_path(), or a
+ * stream wrapper URI. For example: "modules/devel/devel.css" or
+ * "public://generated_css/stylesheet_1.css". Note that Modules should
+ * always prefix the names of their CSS files with the module name; for
+ * example, system-menus.css rather than simply menus.css. Themes can
+ * override module-supplied CSS files based on their filenames, and this
+ * prefixing helps prevent confusing name collisions for theme developers.
+ * See drupal_get_css() where the overrides are performed. Also, if the
+ * direction of the current language is right-to-left (Hebrew, Arabic,
+ * etc.), the function will also look for an RTL CSS file and append it to
+ * the list. The name of this file should have an '-rtl.css' suffix. For
+ * example, a CSS file called 'mymodule-name.css' will have a
+ * 'mymodule-name-rtl.css' file added to the list, if exists in the same
+ * directory. This CSS file should contain overrides for properties which
+ * should be reversed or otherwise different in a right-to-left display.
+ * - 'inline': A string of CSS that should be placed in the given scope. Note
+ * that it is better practice to use 'file' stylesheets, rather than
+ * 'inline', as the CSS would then be aggregated and cached.
+ * - 'external': The absolute path to an external CSS file that is not hosted
+ * on the local server. These files will not be aggregated if CSS
+ * aggregation is enabled.
+ * @param $options
+ * (optional) A string defining the 'type' of CSS that is being added in the
+ * $data parameter ('file', 'inline', or 'external'), or an array which can
+ * have any or all of the following keys:
+ * - 'type': The type of stylesheet being added. Available options are 'file',
+ * 'inline' or 'external'. Defaults to 'file'.
+ * - 'basename': Force a basename for the file being added. Modules are
+ * expected to use stylesheets with unique filenames, but integration of
+ * external libraries may make this impossible. The basename of
+ * 'modules/node/node.css' is 'node.css'. If the external library "node.js"
+ * ships with a 'node.css', then a different, unique basename would be
+ * 'node.js.css'.
+ * - 'group': A number identifying the group in which to add the stylesheet.
+ * Available constants are:
+ * - CSS_SYSTEM: Any system-layer CSS.
+ * - CSS_DEFAULT: (default) Any module-layer CSS.
+ * - CSS_THEME: Any theme-layer CSS.
+ * The group number serves as a weight: the markup for loading a stylesheet
+ * within a lower weight group is output to the page before the markup for
+ * loading a stylesheet within a higher weight group, so CSS within higher
+ * weight groups take precendence over CSS within lower weight groups.
+ * - 'every_page': For optimal front-end performance when aggregation is
+ * enabled, this should be set to TRUE if the stylesheet is present on every
+ * page of the website for users for whom it is present at all. This
+ * defaults to FALSE. It is set to TRUE for stylesheets added via module and
+ * theme .info files. Modules that add stylesheets within hook_init()
+ * implementations, or from other code that ensures that the stylesheet is
+ * added to all website pages, should also set this flag to TRUE. All
+ * stylesheets within the same group that have the 'every_page' flag set to
+ * TRUE and do not have 'preprocess' set to FALSE are aggregated together
+ * into a single aggregate file, and that aggregate file can be reused
+ * across a user's entire site visit, leading to faster navigation between
+ * pages. However, stylesheets that are only needed on pages less frequently
+ * visited, can be added by code that only runs for those particular pages,
+ * and that code should not set the 'every_page' flag. This minimizes the
+ * size of the aggregate file that the user needs to download when first
+ * visiting the website. Stylesheets without the 'every_page' flag are
+ * aggregated into a separate aggregate file. This other aggregate file is
+ * likely to change from page to page, and each new aggregate file needs to
+ * be downloaded when first encountered, so it should be kept relatively
+ * small by ensuring that most commonly needed stylesheets are added to
+ * every page.
+ * - 'weight': The weight of the stylesheet specifies the order in which the
+ * CSS will appear relative to other stylesheets with the same group and
+ * 'every_page' flag. The exact ordering of stylesheets is as follows:
+ * - First by group.
+ * - Then by the 'every_page' flag, with TRUE coming before FALSE.
+ * - Then by weight.
+ * - Then by the order in which the CSS was added. For example, all else
+ * being the same, a stylesheet added by a call to drupal_add_css() that
+ * happened later in the page request gets added to the page after one for
+ * which drupal_add_css() happened earlier in the page request.
+ * - 'media': The media type for the stylesheet, e.g., all, print, screen.
+ * Defaults to 'all'.
+ * - 'preprocess': If TRUE and CSS aggregation/compression is enabled, the
+ * styles will be aggregated and compressed. Defaults to TRUE.
+ * - 'browsers': An array containing information specifying which browsers
+ * should load the CSS item. See drupal_pre_render_conditional_comments()
+ * for details.
+ *
+ * @return
+ * An array of queued cascading stylesheets.
+ *
+ * @see drupal_get_css()
+ */
+function drupal_add_css($data = NULL, $options = NULL) {
+ $css = &drupal_static(__FUNCTION__, array());
+
+ // Construct the options, taking the defaults into consideration.
+ if (isset($options)) {
+ if (!is_array($options)) {
+ $options = array('type' => $options);
+ }
+ }
+ else {
+ $options = array();
+ }
+
+ // Create an array of CSS files for each media type first, since each type needs to be served
+ // to the browser differently.
+ if (isset($data)) {
+ $options += array(
+ 'type' => 'file',
+ 'group' => CSS_DEFAULT,
+ 'weight' => 0,
+ 'every_page' => FALSE,
+ 'media' => 'all',
+ 'preprocess' => TRUE,
+ 'data' => $data,
+ 'browsers' => array(),
+ );
+ $options['browsers'] += array(
+ 'IE' => TRUE,
+ '!IE' => TRUE,
+ );
+
+ // Files with a query string cannot be preprocessed.
+ if ($options['type'] === 'file' && $options['preprocess'] && strpos($options['data'], '?') !== FALSE) {
+ $options['preprocess'] = FALSE;
+ }
+
+ // Always add a tiny value to the weight, to conserve the insertion order.
+ $options['weight'] += count($css) / 1000;
+
+ // Add the data to the CSS array depending on the type.
+ switch ($options['type']) {
+ case 'inline':
+ // For inline stylesheets, we don't want to use the $data as the array
+ // key as $data could be a very long string of CSS.
+ $css[] = $options;
+ break;
+ default:
+ // Local and external files must keep their name as the associative key
+ // so the same CSS file is not be added twice.
+ $css[$data] = $options;
+ }
+ }
+
+ return $css;
+}
+
+/**
+ * Returns a themed representation of all stylesheets to attach to the page.
+ *
+ * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
+ * This ensures proper cascading of styles so themes can easily override
+ * module styles through CSS selectors.
+ *
+ * Themes may replace module-defined CSS files by adding a stylesheet with the
+ * same filename. For example, themes/bartik/system-menus.css would replace
+ * modules/system/system-menus.css. This allows themes to override complete
+ * CSS files, rather than specific selectors, when necessary.
+ *
+ * If the original CSS file is being overridden by a theme, the theme is
+ * responsible for supplying an accompanying RTL CSS file to replace the
+ * module's.
+ *
+ * @param $css
+ * (optional) An array of CSS files. If no array is provided, the default
+ * stylesheets array is used instead.
+ * @param $skip_alter
+ * (optional) If set to TRUE, this function skips calling drupal_alter() on
+ * $css, useful when the calling function passes a $css array that has already
+ * been altered.
+ *
+ * @return
+ * A string of XHTML CSS tags.
+ *
+ * @see drupal_add_css()
+ */
+function drupal_get_css($css = NULL, $skip_alter = FALSE) {
+ if (!isset($css)) {
+ $css = drupal_add_css();
+ }
+
+ // Allow modules and themes to alter the CSS items.
+ if (!$skip_alter) {
+ drupal_alter('css', $css);
+ }
+
+ // Sort CSS items, so that they appear in the correct order.
+ uasort($css, 'drupal_sort_css_js');
+
+ // Provide the page with information about the individual CSS files used,
+ // information not otherwise available when CSS aggregation is enabled. The
+ // setting is attached later in this function, but is set here, so that CSS
+ // files removed below are still considered "used" and prevented from being
+ // added in a later AJAX request.
+ // Skip if no files were added to the page or jQuery.extend() will overwrite
+ // the Drupal.settings.ajaxPageState.css object with an empty array.
+ if (!empty($css)) {
+ // Cast the array to an object to be on the safe side even if not empty.
+ $setting['ajaxPageState']['css'] = (object) array_fill_keys(array_keys($css), 1);
+ }
+
+ // Remove the overridden CSS files. Later CSS files override former ones.
+ $previous_item = array();
+ foreach ($css as $key => $item) {
+ if ($item['type'] == 'file') {
+ // If defined, force a unique basename for this file.
+ $basename = isset($item['basename']) ? $item['basename'] : drupal_basename($item['data']);
+ if (isset($previous_item[$basename])) {
+ // Remove the previous item that shared the same base name.
+ unset($css[$previous_item[$basename]]);
+ }
+ $previous_item[$basename] = $key;
+ }
+ }
+
+ // Render the HTML needed to load the CSS.
+ $styles = array(
+ '#type' => 'styles',
+ '#items' => $css,
+ );
+
+ if (!empty($setting)) {
+ $styles['#attached']['js'][] = array('type' => 'setting', 'data' => $setting);
+ }
+
+ return drupal_render($styles);
+}
+
+/**
+ * Sorts CSS and JavaScript resources.
+ *
+ * Callback for uasort() within:
+ * - drupal_get_css()
+ * - drupal_get_js()
+ *
+ * This sort order helps optimize front-end performance while providing modules
+ * and themes with the necessary control for ordering the CSS and JavaScript
+ * appearing on a page.
+ *
+ * @param $a
+ * First item for comparison. The compared items should be associative arrays
+ * of member items from drupal_add_css() or drupal_add_js().
+ * @param $b
+ * Second item for comparison.
+ *
+ * @see drupal_add_css()
+ * @see drupal_add_js()
+ */
+function drupal_sort_css_js($a, $b) {
+ // First order by group, so that, for example, all items in the CSS_SYSTEM
+ // group appear before items in the CSS_DEFAULT group, which appear before
+ // all items in the CSS_THEME group. Modules may create additional groups by
+ // defining their own constants.
+ if ($a['group'] < $b['group']) {
+ return -1;
+ }
+ elseif ($a['group'] > $b['group']) {
+ return 1;
+ }
+ // Within a group, order all infrequently needed, page-specific files after
+ // common files needed throughout the website. Separating this way allows for
+ // the aggregate file generated for all of the common files to be reused
+ // across a site visit without being cut by a page using a less common file.
+ elseif ($a['every_page'] && !$b['every_page']) {
+ return -1;
+ }
+ elseif (!$a['every_page'] && $b['every_page']) {
+ return 1;
+ }
+ // Finally, order by weight.
+ elseif ($a['weight'] < $b['weight']) {
+ return -1;
+ }
+ elseif ($a['weight'] > $b['weight']) {
+ return 1;
+ }
+ else {
+ return 0;
+ }
+}
+
+/**
+ * Default callback to group CSS items.
+ *
+ * This function arranges the CSS items that are in the #items property of the
+ * styles element into groups. Arranging the CSS items into groups serves two
+ * purposes. When aggregation is enabled, files within a group are aggregated
+ * into a single file, significantly improving page loading performance by
+ * minimizing network traffic overhead. When aggregation is disabled, grouping
+ * allows multiple files to be loaded from a single STYLE tag, enabling sites
+ * with many modules enabled or a complex theme being used to stay within IE's
+ * 31 CSS inclusion tag limit: http://drupal.org/node/228818.
+ *
+ * This function puts multiple items into the same group if they are groupable
+ * and if they are for the same 'media' and 'browsers'. Items of the 'file' type
+ * are groupable if their 'preprocess' flag is TRUE, items of the 'inline' type
+ * are always groupable, and items of the 'external' type are never groupable.
+ * This function also ensures that the process of grouping items does not change
+ * their relative order. This requirement may result in multiple groups for the
+ * same type, media, and browsers, if needed to accommodate other items in
+ * between.
+ *
+ * @param $css
+ * An array of CSS items, as returned by drupal_add_css(), but after
+ * alteration performed by drupal_get_css().
+ *
+ * @return
+ * An array of CSS groups. Each group contains the same keys (e.g., 'media',
+ * 'data', etc.) as a CSS item from the $css parameter, with the value of
+ * each key applying to the group as a whole. Each group also contains an
+ * 'items' key, which is the subset of items from $css that are in the group.
+ *
+ * @see drupal_pre_render_styles()
+ * @see system_element_info()
+ */
+function drupal_group_css($css) {
+ $groups = array();
+ // If a group can contain multiple items, we track the information that must
+ // be the same for each item in the group, so that when we iterate the next
+ // item, we can determine if it can be put into the current group, or if a
+ // new group needs to be made for it.
+ $current_group_keys = NULL;
+ // When creating a new group, we pre-increment $i, so by initializing it to
+ // -1, the first group will have index 0.
+ $i = -1;
+ foreach ($css as $item) {
+ // The browsers for which the CSS item needs to be loaded is part of the
+ // information that determines when a new group is needed, but the order of
+ // keys in the array doesn't matter, and we don't want a new group if all
+ // that's different is that order.
+ ksort($item['browsers']);
+
+ // If the item can be grouped with other items, set $group_keys to an array
+ // of information that must be the same for all items in its group. If the
+ // item can't be grouped with other items, set $group_keys to FALSE. We
+ // put items into a group that can be aggregated together: whether they will
+ // be aggregated is up to the _drupal_css_aggregate() function or an
+ // override of that function specified in hook_css_alter(), but regardless
+ // of the details of that function, a group represents items that can be
+ // aggregated. Since a group may be rendered with a single HTML tag, all
+ // items in the group must share the same information that would need to be
+ // part of that HTML tag.
+ switch ($item['type']) {
+ case 'file':
+ // Group file items if their 'preprocess' flag is TRUE.
+ // Help ensure maximum reuse of aggregate files by only grouping
+ // together items that share the same 'group' value and 'every_page'
+ // flag. See drupal_add_css() for details about that.
+ $group_keys = $item['preprocess'] ? array($item['type'], $item['group'], $item['every_page'], $item['media'], $item['browsers']) : FALSE;
+ break;
+ case 'inline':
+ // Always group inline items.
+ $group_keys = array($item['type'], $item['media'], $item['browsers']);
+ break;
+ case 'external':
+ // Do not group external items.
+ $group_keys = FALSE;
+ break;
+ }
+
+ // If the group keys don't match the most recent group we're working with,
+ // then a new group must be made.
+ if ($group_keys !== $current_group_keys) {
+ $i++;
+ // Initialize the new group with the same properties as the first item
+ // being placed into it. The item's 'data' and 'weight' properties are
+ // unique to the item and should not be carried over to the group.
+ $groups[$i] = $item;
+ unset($groups[$i]['data'], $groups[$i]['weight']);
+ $groups[$i]['items'] = array();
+ $current_group_keys = $group_keys ? $group_keys : NULL;
+ }
+
+ // Add the item to the current group.
+ $groups[$i]['items'][] = $item;
+ }
+ return $groups;
+}
+
+/**
+ * Default callback to aggregate CSS files and inline content.
+ *
+ * Having the browser load fewer CSS files results in much faster page loads
+ * than when it loads many small files. This function aggregates files within
+ * the same group into a single file unless the site-wide setting to do so is
+ * disabled (commonly the case during site development). To optimize download,
+ * it also compresses the aggregate files by removing comments, whitespace, and
+ * other unnecessary content. Additionally, this functions aggregates inline
+ * content together, regardless of the site-wide aggregation setting.
+ *
+ * @param $css_groups
+ * An array of CSS groups as returned by drupal_group_css(). This function
+ * modifies the group's 'data' property for each group that is aggregated.
+ *
+ * @see drupal_group_css()
+ * @see drupal_pre_render_styles()
+ * @see system_element_info()
+ */
+function drupal_aggregate_css(&$css_groups) {
+ $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
+
+ // For each group that needs aggregation, aggregate its items.
+ foreach ($css_groups as $key => $group) {
+ switch ($group['type']) {
+ // If a file group can be aggregated into a single file, do so, and set
+ // the group's data property to the file path of the aggregate file.
+ case 'file':
+ if ($group['preprocess'] && $preprocess_css) {
+ $css_groups[$key]['data'] = drupal_build_css_cache($group['items']);
+ }
+ break;
+ // Aggregate all inline CSS content into the group's data property.
+ case 'inline':
+ $css_groups[$key]['data'] = '';
+ foreach ($group['items'] as $item) {
+ $css_groups[$key]['data'] .= drupal_load_stylesheet_content($item['data'], $item['preprocess']);
+ }
+ break;
+ }
+ }
+}
+
+/**
+ * #pre_render callback to add the elements needed for CSS tags to be rendered.
+ *
+ * For production websites, LINK tags are preferable to STYLE tags with @import
+ * statements, because:
+ * - They are the standard tag intended for linking to a resource.
+ * - On Firefox 2 and perhaps other browsers, CSS files included with @import
+ * statements don't get saved when saving the complete web page for offline
+ * use: http://drupal.org/node/145218.
+ * - On IE, if only LINK tags and no @import statements are used, all the CSS
+ * files are downloaded in parallel, resulting in faster page load, but if
+ * @import statements are used and span across multiple STYLE tags, all the
+ * ones from one STYLE tag must be downloaded before downloading begins for
+ * the next STYLE tag. Furthermore, IE7 does not support media declaration on
+ * the @import statement, so multiple STYLE tags must be used when different
+ * files are for different media types. Non-IE browsers always download in
+ * parallel, so this is an IE-specific performance quirk:
+ * http://www.stevesouders.com/blog/2009/04/09/dont-use-import/.
+ *
+ * However, IE has an annoying limit of 31 total CSS inclusion tags
+ * (http://drupal.org/node/228818) and LINK tags are limited to one file per
+ * tag, whereas STYLE tags can contain multiple @import statements allowing
+ * multiple files to be loaded per tag. When CSS aggregation is disabled, a
+ * Drupal site can easily have more than 31 CSS files that need to be loaded, so
+ * using LINK tags exclusively would result in a site that would display
+ * incorrectly in IE. Depending on different needs, different strategies can be
+ * employed to decide when to use LINK tags and when to use STYLE tags.
+ *
+ * The strategy employed by this function is to use LINK tags for all aggregate
+ * files and for all files that cannot be aggregated (e.g., if 'preprocess' is
+ * set to FALSE or the type is 'external'), and to use STYLE tags for groups
+ * of files that could be aggregated together but aren't (e.g., if the site-wide
+ * aggregation setting is disabled). This results in all LINK tags when
+ * aggregation is enabled, a guarantee that as many or only slightly more tags
+ * are used with aggregation disabled than enabled (so that if the limit were to
+ * be crossed with aggregation enabled, the site developer would also notice the
+ * problem while aggregation is disabled), and an easy way for a developer to
+ * view HTML source while aggregation is disabled and know what files will be
+ * aggregated together when aggregation becomes enabled.
+ *
+ * This function evaluates the aggregation enabled/disabled condition on a group
+ * by group basis by testing whether an aggregate file has been made for the
+ * group rather than by testing the site-wide aggregation setting. This allows
+ * this function to work correctly even if modules have implemented custom
+ * logic for grouping and aggregating files.
+ *
+ * @param $element
+ * A render array containing:
+ * - '#items': The CSS items as returned by drupal_add_css() and altered by
+ * drupal_get_css().
+ * - '#group_callback': A function to call to group #items to enable the use
+ * of fewer tags by aggregating files and/or using multiple @import
+ * statements within a single tag.
+ * - '#aggregate_callback': A function to call to aggregate the items within
+ * the groups arranged by the #group_callback function.
+ *
+ * @return
+ * A render array that will render to a string of XHTML CSS tags.
+ *
+ * @see drupal_get_css()
+ */
+function drupal_pre_render_styles($elements) {
+ // Group and aggregate the items.
+ if (isset($elements['#group_callback'])) {
+ $elements['#groups'] = $elements['#group_callback']($elements['#items']);
+ }
+ if (isset($elements['#aggregate_callback'])) {
+ $elements['#aggregate_callback']($elements['#groups']);
+ }
+
+ // A dummy query-string is added to filenames, to gain control over
+ // browser-caching. The string changes on every update or full cache
+ // flush, forcing browsers to load a new copy of the files, as the
+ // URL changed.
+ $query_string = variable_get('css_js_query_string', '0');
+
+ // For inline CSS to validate as XHTML, all CSS containing XHTML needs to be
+ // wrapped in CDATA. To make that backwards compatible with HTML 4, we need to
+ // comment out the CDATA-tag.
+ $embed_prefix = "\n<!--/*--><![CDATA[/*><!--*/\n";
+ $embed_suffix = "\n/*]]>*/-->\n";
+
+ // Defaults for LINK and STYLE elements.
+ $link_element_defaults = array(
+ '#type' => 'html_tag',
+ '#tag' => 'link',
+ '#attributes' => array(
+ 'type' => 'text/css',
+ 'rel' => 'stylesheet',
+ ),
+ );
+ $style_element_defaults = array(
+ '#type' => 'html_tag',
+ '#tag' => 'style',
+ '#attributes' => array(
+ 'type' => 'text/css',
+ ),
+ );
+
+ // Loop through each group.
+ foreach ($elements['#groups'] as $group) {
+ switch ($group['type']) {
+ // For file items, there are three possibilites.
+ // - The group has been aggregated: in this case, output a LINK tag for
+ // the aggregate file.
+ // - The group can be aggregated but has not been (most likely because
+ // the site administrator disabled the site-wide setting): in this case,
+ // output as few STYLE tags for the group as possible, using @import
+ // statement for each file in the group. This enables us to stay within
+ // IE's limit of 31 total CSS inclusion tags.
+ // - The group contains items not eligible for aggregation (their
+ // 'preprocess' flag has been set to FALSE): in this case, output a LINK
+ // tag for each file.
+ case 'file':
+ // The group has been aggregated into a single file: output a LINK tag
+ // for the aggregate file.
+ if (isset($group['data'])) {
+ $element = $link_element_defaults;
+ $element['#attributes']['href'] = file_create_url($group['data']);
+ $element['#attributes']['media'] = $group['media'];
+ $element['#browsers'] = $group['browsers'];
+ $elements[] = $element;
+ }
+ // The group can be aggregated, but hasn't been: combine multiple items
+ // into as few STYLE tags as possible.
+ elseif ($group['preprocess']) {
+ $import = array();
+ foreach ($group['items'] as $item) {
+ // A theme's .info file may have an entry for a file that doesn't
+ // exist as a way of overriding a module or base theme CSS file from
+ // being added to the page. Normally, file_exists() calls that need
+ // to run for every page request should be minimized, but this one
+ // is okay, because it only runs when CSS aggregation is disabled.
+ // On a server under heavy enough load that file_exists() calls need
+ // to be minimized, CSS aggregation should be enabled, in which case
+ // this code is not run. When aggregation is enabled,
+ // drupal_load_stylesheet() checks file_exists(), but only when
+ // building the aggregate file, which is then reused for many page
+ // requests.
+ if (file_exists($item['data'])) {
+ // The dummy query string needs to be added to the URL to control
+ // browser-caching. IE7 does not support a media type on the
+ // @import statement, so we instead specify the media for the
+ // group on the STYLE tag.
+ $import[] = '@import url("' . check_plain(file_create_url($item['data']) . '?' . $query_string) . '");';
+ }
+ }
+ // In addition to IE's limit of 31 total CSS inclusion tags, it also
+ // has a limit of 31 @import statements per STYLE tag.
+ while (!empty($import)) {
+ $import_batch = array_slice($import, 0, 31);
+ $import = array_slice($import, 31);
+ $element = $style_element_defaults;
+ $element['#value'] = implode("\n", $import_batch);
+ $element['#attributes']['media'] = $group['media'];
+ $element['#browsers'] = $group['browsers'];
+ $elements[] = $element;
+ }
+ }
+ // The group contains items ineligible for aggregation: output a LINK
+ // tag for each file.
+ else {
+ foreach ($group['items'] as $item) {
+ $element = $link_element_defaults;
+ // We do not check file_exists() here, because this code runs for
+ // files whose 'preprocess' is set to FALSE, and therefore, even
+ // when aggregation is enabled, and we want to avoid needlessly
+ // taxing a server that may be under heavy load. The file_exists()
+ // performed above for files whose 'preprocess' is TRUE is done for
+ // the benefit of theme .info files, but code that deals with files
+ // whose 'preprocess' is FALSE is responsible for ensuring the file
+ // exists.
+ // The dummy query string needs to be added to the URL to control
+ // browser-caching.
+ $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
+ $element['#attributes']['href'] = file_create_url($item['data']) . $query_string_separator . $query_string;
+ $element['#attributes']['media'] = $item['media'];
+ $element['#browsers'] = $group['browsers'];
+ $elements[] = $element;
+ }
+ }
+ break;
+ // For inline content, the 'data' property contains the CSS content. If
+ // the group's 'data' property is set, then output it in a single STYLE
+ // tag. Otherwise, output a separate STYLE tag for each item.
+ case 'inline':
+ if (isset($group['data'])) {
+ $element = $style_element_defaults;
+ $element['#value'] = $group['data'];
+ $element['#value_prefix'] = $embed_prefix;
+ $element['#value_suffix'] = $embed_suffix;
+ $element['#attributes']['media'] = $group['media'];
+ $element['#browsers'] = $group['browsers'];
+ $elements[] = $element;
+ }
+ else {
+ foreach ($group['items'] as $item) {
+ $element = $style_element_defaults;
+ $element['#value'] = $item['data'];
+ $element['#value_prefix'] = $embed_prefix;
+ $element['#value_suffix'] = $embed_suffix;
+ $element['#attributes']['media'] = $item['media'];
+ $element['#browsers'] = $group['browsers'];
+ $elements[] = $element;
+ }
+ }
+ break;
+ // Output a LINK tag for each external item. The item's 'data' property
+ // contains the full URL.
+ case 'external':
+ foreach ($group['items'] as $item) {
+ $element = $link_element_defaults;
+ $element['#attributes']['href'] = $item['data'];
+ $element['#attributes']['media'] = $item['media'];
+ $element['#browsers'] = $group['browsers'];
+ $elements[] = $element;
+ }
+ break;
+ }
+ }
+
+ return $elements;
+}
+
+/**
+ * Aggregates and optimizes CSS files into a cache file in the files directory.
+ *
+ * The file name for the CSS cache file is generated from the hash of the
+ * aggregated contents of the files in $css. This forces proxies and browsers
+ * to download new CSS when the CSS changes.
+ *
+ * The cache file name is retrieved on a page load via a lookup variable that
+ * contains an associative array. The array key is the hash of the file names
+ * in $css while the value is the cache file name. The cache file is generated
+ * in two cases. First, if there is no file name value for the key, which will
+ * happen if a new file name has been added to $css or after the lookup
+ * variable is emptied to force a rebuild of the cache. Second, the cache file
+ * is generated if it is missing on disk. Old cache files are not deleted
+ * immediately when the lookup variable is emptied, but are deleted after a set
+ * period by drupal_delete_file_if_stale(). This ensures that files referenced
+ * by a cached page will still be available.
+ *
+ * @param $css
+ * An array of CSS files to aggregate and compress into one file.
+ *
+ * @return
+ * The URI of the CSS cache file, or FALSE if the file could not be saved.
+ */
+function drupal_build_css_cache($css) {
+ $data = '';
+ $uri = '';
+ $map = variable_get('drupal_css_cache_files', array());
+ // Create a new array so that only the file names are used to create the hash.
+ // This prevents new aggregates from being created unnecessarily.
+ $css_data = array();
+ foreach ($css as $css_file) {
+ $css_data[] = $css_file['data'];
+ }
+ $key = hash('sha256', serialize($css_data));
+ if (isset($map[$key])) {
+ $uri = $map[$key];
+ }
+
+ if (empty($uri) || !file_exists($uri)) {
+ // Build aggregate CSS file.
+ foreach ($css as $stylesheet) {
+ // Only 'file' stylesheets can be aggregated.
+ if ($stylesheet['type'] == 'file') {
+ $contents = drupal_load_stylesheet($stylesheet['data'], TRUE);
+
+ // Build the base URL of this CSS file: start with the full URL.
+ $css_base_url = file_create_url($stylesheet['data']);
+ // Move to the parent.
+ $css_base_url = substr($css_base_url, 0, strrpos($css_base_url, '/'));
+ // Simplify to a relative URL if the stylesheet URL starts with the
+ // base URL of the website.
+ if (substr($css_base_url, 0, strlen($GLOBALS['base_root'])) == $GLOBALS['base_root']) {
+ $css_base_url = substr($css_base_url, strlen($GLOBALS['base_root']));
+ }
+
+ _drupal_build_css_path(NULL, $css_base_url . '/');
+ // Anchor all paths in the CSS with its base URL, ignoring external and absolute paths.
+ $data .= preg_replace_callback('/url\(\s*[\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\s*\)/i', '_drupal_build_css_path', $contents);
+ }
+ }
+
+ // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
+ // @import rules must proceed any other style, so we move those to the top.
+ $regexp = '/@import[^;]+;/i';
+ preg_match_all($regexp, $data, $matches);
+ $data = preg_replace($regexp, '', $data);
+ $data = implode('', $matches[0]) . $data;
+
+ // Prefix filename to prevent blocking by firewalls which reject files
+ // starting with "ad*".
+ $filename = 'css_' . drupal_hash_base64($data) . '.css';
+ // Create the css/ within the files folder.
+ $csspath = 'public://css';
+ $uri = $csspath . '/' . $filename;
+ // Create the CSS file.
+ file_prepare_directory($csspath, FILE_CREATE_DIRECTORY);
+ if (!file_exists($uri) && !file_unmanaged_save_data($data, $uri, FILE_EXISTS_REPLACE)) {
+ return FALSE;
+ }
+ // If CSS gzip compression is enabled, clean URLs are enabled (which means
+ // that rewrite rules are working) and the zlib extension is available then
+ // create a gzipped version of this file. This file is served conditionally
+ // to browsers that accept gzip using .htaccess rules.
+ if (variable_get('css_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
+ if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($data, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
+ return FALSE;
+ }
+ }
+ // Save the updated map.
+ $map[$key] = $uri;
+ variable_set('drupal_css_cache_files', $map);
+ }
+ return $uri;
+}
+
+/**
+ * Prefixes all paths within a CSS file for drupal_build_css_cache().
+ */
+function _drupal_build_css_path($matches, $base = NULL) {
+ $_base = &drupal_static(__FUNCTION__);
+ // Store base path for preg_replace_callback.
+ if (isset($base)) {
+ $_base = $base;
+ }
+
+ // Prefix with base and remove '../' segments where possible.
+ $path = $_base . $matches[1];
+ $last = '';
+ while ($path != $last) {
+ $last = $path;
+ $path = preg_replace('`(^|/)(?!\.\./)([^/]+)/\.\./`', '$1', $path);
+ }
+ return 'url(' . $path . ')';
+}
+
+/**
+ * Loads the stylesheet and resolves all @import commands.
+ *
+ * Loads a stylesheet and replaces @import commands with the contents of the
+ * imported file. Use this instead of file_get_contents when processing
+ * stylesheets.
+ *
+ * The returned contents are compressed removing white space and comments only
+ * when CSS aggregation is enabled. This optimization will not apply for
+ * color.module enabled themes with CSS aggregation turned off.
+ *
+ * @param $file
+ * Name of the stylesheet to be processed.
+ * @param $optimize
+ * Defines if CSS contents should be compressed or not.
+ * @param $reset_basepath
+ * Used internally to facilitate recursive resolution of @import commands.
+ *
+ * @return
+ * Contents of the stylesheet, including any resolved @import commands.
+ */
+function drupal_load_stylesheet($file, $optimize = NULL, $reset_basepath = TRUE) {
+ // These statics are not cache variables, so we don't use drupal_static().
+ static $_optimize, $basepath;
+ if ($reset_basepath) {
+ $basepath = '';
+ }
+ // Store the value of $optimize for preg_replace_callback with nested
+ // @import loops.
+ if (isset($optimize)) {
+ $_optimize = $optimize;
+ }
+
+ // Stylesheets are relative one to each other. Start by adding a base path
+ // prefix provided by the parent stylesheet (if necessary).
+ if ($basepath && !file_uri_scheme($file)) {
+ $file = $basepath . '/' . $file;
+ }
+ // Store the parent base path to restore it later.
+ $parent_base_path = $basepath;
+ // Set the current base path to process possible child imports.
+ $basepath = dirname($file);
+
+ // Load the CSS stylesheet. We suppress errors because themes may specify
+ // stylesheets in their .info file that don't exist in the theme's path,
+ // but are merely there to disable certain module CSS files.
+ $content = '';
+ if ($contents = @file_get_contents($file)) {
+ // Return the processed stylesheet.
+ $content = drupal_load_stylesheet_content($contents, $_optimize);
+ }
+
+ // Restore the parent base path as the file and its childen are processed.
+ $basepath = $parent_base_path;
+ return $content;
+}
+
+/**
+ * Processes the contents of a stylesheet for aggregation.
+ *
+ * @param $contents
+ * The contents of the stylesheet.
+ * @param $optimize
+ * (optional) Boolean whether CSS contents should be minified. Defaults to
+ * FALSE.
+ *
+ * @return
+ * Contents of the stylesheet including the imported stylesheets.
+ */
+function drupal_load_stylesheet_content($contents, $optimize = FALSE) {
+ // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
+ $contents = preg_replace('/^@charset\s+[\'"](\S*?)\b[\'"];/i', '', $contents);
+
+ if ($optimize) {
+ // Perform some safe CSS optimizations.
+ // Regexp to match comment blocks.
+ $comment = '/\*[^*]*\*+(?:[^/*][^*]*\*+)*/';
+ // Regexp to match double quoted strings.
+ $double_quot = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"';
+ // Regexp to match single quoted strings.
+ $single_quot = "'[^'\\\\]*(?:\\\\.[^'\\\\]*)*'";
+ // Strip all comment blocks, but keep double/single quoted strings.
+ $contents = preg_replace(
+ "<($double_quot|$single_quot)|$comment>Ss",
+ "$1",
+ $contents
+ );
+ // Remove certain whitespace.
+ // There are different conditions for removing leading and trailing
+ // whitespace.
+ // @see http://php.net/manual/regexp.reference.subpatterns.php
+ $contents = preg_replace('<
+ # Strip leading and trailing whitespace.
+ \s*([@{};,])\s*
+ # Strip only leading whitespace from:
+ # - Closing parenthesis: Retain "@media (bar) and foo".
+ | \s+([\)])
+ # Strip only trailing whitespace from:
+ # - Opening parenthesis: Retain "@media (bar) and foo".
+ # - Colon: Retain :pseudo-selectors.
+ | ([\(:])\s+
+ >xS',
+ // Only one of the three capturing groups will match, so its reference
+ // will contain the wanted value and the references for the
+ // two non-matching groups will be replaced with empty strings.
+ '$1$2$3',
+ $contents
+ );
+ // End the file with a new line.
+ $contents = trim($contents);
+ $contents .= "\n";
+ }
+
+ // Replaces @import commands with the actual stylesheet content.
+ // This happens recursively but omits external files.
+ $contents = preg_replace_callback('/@import\s*(?:url\(\s*)?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\s*\)?\s*;/', '_drupal_load_stylesheet', $contents);
+ return $contents;
+}
+
+/**
+ * Loads stylesheets recursively and returns contents with corrected paths.
+ *
+ * This function is used for recursive loading of stylesheets and
+ * returns the stylesheet content with all url() paths corrected.
+ */
+function _drupal_load_stylesheet($matches) {
+ $filename = $matches[1];
+ // Load the imported stylesheet and replace @import commands in there as well.
+ $file = drupal_load_stylesheet($filename, NULL, FALSE);
+
+ // Determine the file's directory.
+ $directory = dirname($filename);
+ // If the file is in the current directory, make sure '.' doesn't appear in
+ // the url() path.
+ $directory = $directory == '.' ? '' : $directory .'/';
+
+ // Alter all internal url() paths. Leave external paths alone. We don't need
+ // to normalize absolute paths here (i.e. remove folder/... segments) because
+ // that will be done later.
+ return preg_replace('/url\(\s*([\'"]?)(?![a-z]+:|\/+)/i', 'url(\1'. $directory, $file);
+}
+
+/**
+ * Deletes old cached CSS files.
+ */
+function drupal_clear_css_cache() {
+ variable_del('drupal_css_cache_files');
+ file_scan_directory('public://css', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
+}
+
+/**
+ * Callback to delete files modified more than a set time ago.
+ */
+function drupal_delete_file_if_stale($uri) {
+ // Default stale file threshold is 30 days.
+ if (REQUEST_TIME - filemtime($uri) > variable_get('drupal_stale_file_threshold', 2592000)) {
+ file_unmanaged_delete($uri);
+ }
+}
+
+/**
+ * Prepares a string for use as a CSS identifier (element, class, or ID name).
+ *
+ * http://www.w3.org/TR/CSS21/syndata.html#characters shows the syntax for valid
+ * CSS identifiers (including element names, classes, and IDs in selectors.)
+ *
+ * @param $identifier
+ * The identifier to clean.
+ * @param $filter
+ * An array of string replacements to use on the identifier.
+ *
+ * @return
+ * The cleaned identifier.
+ */
+function drupal_clean_css_identifier($identifier, $filter = array(' ' => '-', '_' => '-', '/' => '-', '[' => '-', ']' => '')) {
+ // By default, we filter using Drupal's coding standards.
+ $identifier = strtr($identifier, $filter);
+
+ // Valid characters in a CSS identifier are:
+ // - the hyphen (U+002D)
+ // - a-z (U+0030 - U+0039)
+ // - A-Z (U+0041 - U+005A)
+ // - the underscore (U+005F)
+ // - 0-9 (U+0061 - U+007A)
+ // - ISO 10646 characters U+00A1 and higher
+ // We strip out any character not in the above list.
+ $identifier = preg_replace('/[^\x{002D}\x{0030}-\x{0039}\x{0041}-\x{005A}\x{005F}\x{0061}-\x{007A}\x{00A1}-\x{FFFF}]/u', '', $identifier);
+
+ return $identifier;
+}
+
+/**
+ * Prepares a string for use as a valid class name.
+ *
+ * Do not pass one string containing multiple classes as they will be
+ * incorrectly concatenated with dashes, i.e. "one two" will become "one-two".
+ *
+ * @param $class
+ * The class name to clean.
+ *
+ * @return
+ * The cleaned class name.
+ */
+function drupal_html_class($class) {
+ // The output of this function will never change, so this uses a normal
+ // static instead of drupal_static().
+ static $classes = array();
+
+ if (!isset($classes[$class])) {
+ $classes[$class] = drupal_clean_css_identifier(drupal_strtolower($class));
+ }
+ return $classes[$class];
+}
+
+/**
+ * Prepares a string for use as a valid HTML ID and guarantees uniqueness.
+ *
+ * This function ensures that each passed HTML ID value only exists once on the
+ * page. By tracking the already returned ids, this function enables forms,
+ * blocks, and other content to be output multiple times on the same page,
+ * without breaking (X)HTML validation.
+ *
+ * For already existing IDs, a counter is appended to the ID string. Therefore,
+ * JavaScript and CSS code should not rely on any value that was generated by
+ * this function and instead should rely on manually added CSS classes or
+ * similarly reliable constructs.
+ *
+ * Two consecutive hyphens separate the counter from the original ID. To manage
+ * uniqueness across multiple Ajax requests on the same page, Ajax requests
+ * POST an array of all IDs currently present on the page, which are used to
+ * prime this function's cache upon first invocation.
+ *
+ * To allow reverse-parsing of IDs submitted via Ajax, any multiple consecutive
+ * hyphens in the originally passed $id are replaced with a single hyphen.
+ *
+ * @param $id
+ * The ID to clean.
+ *
+ * @return
+ * The cleaned ID.
+ */
+function drupal_html_id($id) {
+ // If this is an Ajax request, then content returned by this page request will
+ // be merged with content already on the base page. The HTML IDs must be
+ // unique for the fully merged content. Therefore, initialize $seen_ids to
+ // take into account IDs that are already in use on the base page.
+ $seen_ids_init = &drupal_static(__FUNCTION__ . ':init');
+ if (!isset($seen_ids_init)) {
+ // Ideally, Drupal would provide an API to persist state information about
+ // prior page requests in the database, and we'd be able to add this
+ // function's $seen_ids static variable to that state information in order
+ // to have it properly initialized for this page request. However, no such
+ // page state API exists, so instead, ajax.js adds all of the in-use HTML
+ // IDs to the POST data of Ajax submissions. Direct use of $_POST is
+ // normally not recommended as it could open up security risks, but because
+ // the raw POST data is cast to a number before being returned by this
+ // function, this usage is safe.
+ if (empty($_POST['ajax_html_ids'])) {
+ $seen_ids_init = array();
+ }
+ else {
+ // This function ensures uniqueness by appending a counter to the base id
+ // requested by the calling function after the first occurrence of that
+ // requested id. $_POST['ajax_html_ids'] contains the ids as they were
+ // returned by this function, potentially with the appended counter, so
+ // we parse that to reconstruct the $seen_ids array.
+ if (isset($_POST['ajax_html_ids'][0]) && strpos($_POST['ajax_html_ids'][0], ',') === FALSE) {
+ $ajax_html_ids = $_POST['ajax_html_ids'];
+ }
+ else {
+ // jquery.form.js may send the server a comma-separated string as the
+ // first element of an array (see http://drupal.org/node/1575060), so
+ // we need to convert it to an array in that case.
+ $ajax_html_ids = explode(',', $_POST['ajax_html_ids'][0]);
+ }
+ foreach ($ajax_html_ids as $seen_id) {
+ // We rely on '--' being used solely for separating a base id from the
+ // counter, which this function ensures when returning an id.
+ $parts = explode('--', $seen_id, 2);
+ if (!empty($parts[1]) && is_numeric($parts[1])) {
+ list($seen_id, $i) = $parts;
+ }
+ else {
+ $i = 1;
+ }
+ if (!isset($seen_ids_init[$seen_id]) || ($i > $seen_ids_init[$seen_id])) {
+ $seen_ids_init[$seen_id] = $i;
+ }
+ }
+ }
+ }
+ $seen_ids = &drupal_static(__FUNCTION__, $seen_ids_init);
+
+ $id = strtr(drupal_strtolower($id), array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
+
+ // As defined in http://www.w3.org/TR/html4/types.html#type-name, HTML IDs can
+ // only contain letters, digits ([0-9]), hyphens ("-"), underscores ("_"),
+ // colons (":"), and periods ("."). We strip out any character not in that
+ // list. Note that the CSS spec doesn't allow colons or periods in identifiers
+ // (http://www.w3.org/TR/CSS21/syndata.html#characters), so we strip those two
+ // characters as well.
+ $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
+
+ // Removing multiple consecutive hyphens.
+ $id = preg_replace('/\-+/', '-', $id);
+ // Ensure IDs are unique by appending a counter after the first occurrence.
+ // The counter needs to be appended with a delimiter that does not exist in
+ // the base ID. Requiring a unique delimiter helps ensure that we really do
+ // return unique IDs and also helps us re-create the $seen_ids array during
+ // Ajax requests.
+ if (isset($seen_ids[$id])) {
+ $id = $id . '--' . ++$seen_ids[$id];
+ }
+ else {
+ $seen_ids[$id] = 1;
+ }
+
+ return $id;
+}
+
+/**
+ * Provides a standard HTML class name that identifies a page region.
+ *
+ * It is recommended that template preprocess functions apply this class to any
+ * page region that is output by the theme (Drupal core already handles this in
+ * the standard template preprocess implementation). Standardizing the class
+ * names in this way allows modules to implement certain features, such as
+ * drag-and-drop or dynamic Ajax loading, in a theme-independent way.
+ *
+ * @param $region
+ * The name of the page region (for example, 'page_top' or 'content').
+ *
+ * @return
+ * An HTML class that identifies the region (for example, 'region-page-top'
+ * or 'region-content').
+ *
+ * @see template_preprocess_region()
+ */
+function drupal_region_class($region) {
+ return drupal_html_class("region-$region");
+}
+
+/**
+ * Adds a JavaScript file, setting, or inline code to the page.
+ *
+ * The behavior of this function depends on the parameters it is called with.
+ * Generally, it handles the addition of JavaScript to the page, either as
+ * reference to an existing file or as inline code. The following actions can be
+ * performed using this function:
+ * - Add a file ('file'): Adds a reference to a JavaScript file to the page.
+ * - Add inline JavaScript code ('inline'): Executes a piece of JavaScript code
+ * on the current page by placing the code directly in the page (for example,
+ * to tell the user that a new message arrived, by opening a pop up, alert
+ * box, etc.). This should only be used for JavaScript that cannot be executed
+ * from a file. When adding inline code, make sure that you are not relying on
+ * $() being the jQuery function. Wrap your code in
+ * @code (function ($) {... })(jQuery); @endcode
+ * or use jQuery() instead of $().
+ * - Add external JavaScript ('external'): Allows the inclusion of external
+ * JavaScript files that are not hosted on the local server. Note that these
+ * external JavaScript references do not get aggregated when preprocessing is
+ * on.
+ * - Add settings ('setting'): Adds settings to Drupal's global storage of
+ * JavaScript settings. Per-page settings are required by some modules to
+ * function properly. All settings will be accessible at Drupal.settings.
+ *
+ * Examples:
+ * @code
+ * drupal_add_js('misc/collapse.js');
+ * drupal_add_js('misc/collapse.js', 'file');
+ * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });', 'inline');
+ * drupal_add_js('jQuery(document).ready(function () { alert("Hello!"); });',
+ * array('type' => 'inline', 'scope' => 'footer', 'weight' => 5)
+ * );
+ * drupal_add_js('http://example.com/example.js', 'external');
+ * drupal_add_js(array('myModule' => array('key' => 'value')), 'setting');
+ * @endcode
+ *
+ * Calling drupal_static_reset('drupal_add_js') will clear all JavaScript added
+ * so far.
+ *
+ * If JavaScript aggregation is enabled, all JavaScript files added with
+ * $options['preprocess'] set to TRUE will be merged into one aggregate file.
+ * Preprocessed inline JavaScript will not be aggregated into this single file.
+ * Externally hosted JavaScripts are never aggregated.
+ *
+ * The reason for aggregating the files is outlined quite thoroughly here:
+ * http://www.die.net/musings/page_load_time/ "Load fewer external objects. Due
+ * to request overhead, one bigger file just loads faster than two smaller ones
+ * half its size."
+ *
+ * $options['preprocess'] should be only set to TRUE when a file is required for
+ * all typical visitors and most pages of a site. It is critical that all
+ * preprocessed files are added unconditionally on every page, even if the
+ * files are not needed on a page. This is normally done by calling
+ * drupal_add_js() in a hook_init() implementation.
+ *
+ * Non-preprocessed files should only be added to the page when they are
+ * actually needed.
+ *
+ * @param $data
+ * (optional) If given, the value depends on the $options parameter, or
+ * $options['type'] if $options is passed as an associative array:
+ * - 'file': Path to the file relative to base_path().
+ * - 'inline': The JavaScript code that should be placed in the given scope.
+ * - 'external': The absolute path to an external JavaScript file that is not
+ * hosted on the local server. These files will not be aggregated if
+ * JavaScript aggregation is enabled.
+ * - 'setting': An associative array with configuration options. The array is
+ * merged directly into Drupal.settings. All modules should wrap their
+ * actual configuration settings in another variable to prevent conflicts in
+ * the Drupal.settings namespace. Items added with a string key will replace
+ * existing settings with that key; items with numeric array keys will be
+ * added to the existing settings array.
+ * @param $options
+ * (optional) A string defining the type of JavaScript that is being added in
+ * the $data parameter ('file'/'setting'/'inline'/'external'), or an
+ * associative array. JavaScript settings should always pass the string
+ * 'setting' only. Other types can have the following elements in the array:
+ * - type: The type of JavaScript that is to be added to the page. Allowed
+ * values are 'file', 'inline', 'external' or 'setting'. Defaults
+ * to 'file'.
+ * - scope: The location in which you want to place the script. Possible
+ * values are 'header' or 'footer'. If your theme implements different
+ * regions, you can also use these. Defaults to 'header'.
+ * - group: A number identifying the group in which to add the JavaScript.
+ * Available constants are:
+ * - JS_LIBRARY: Any libraries, settings, or jQuery plugins.
+ * - JS_DEFAULT: Any module-layer JavaScript.
+ * - JS_THEME: Any theme-layer JavaScript.
+ * The group number serves as a weight: JavaScript within a lower weight
+ * group is presented on the page before JavaScript within a higher weight
+ * group.
+ * - every_page: For optimal front-end performance when aggregation is
+ * enabled, this should be set to TRUE if the JavaScript is present on every
+ * page of the website for users for whom it is present at all. This
+ * defaults to FALSE. It is set to TRUE for JavaScript files that are added
+ * via module and theme .info files. Modules that add JavaScript within
+ * hook_init() implementations, or from other code that ensures that the
+ * JavaScript is added to all website pages, should also set this flag to
+ * TRUE. All JavaScript files within the same group and that have the
+ * 'every_page' flag set to TRUE and do not have 'preprocess' set to FALSE
+ * are aggregated together into a single aggregate file, and that aggregate
+ * file can be reused across a user's entire site visit, leading to faster
+ * navigation between pages. However, JavaScript that is only needed on
+ * pages less frequently visited, can be added by code that only runs for
+ * those particular pages, and that code should not set the 'every_page'
+ * flag. This minimizes the size of the aggregate file that the user needs
+ * to download when first visiting the website. JavaScript without the
+ * 'every_page' flag is aggregated into a separate aggregate file. This
+ * other aggregate file is likely to change from page to page, and each new
+ * aggregate file needs to be downloaded when first encountered, so it
+ * should be kept relatively small by ensuring that most commonly needed
+ * JavaScript is added to every page.
+ * - weight: A number defining the order in which the JavaScript is added to
+ * the page relative to other JavaScript with the same 'scope', 'group',
+ * and 'every_page' value. In some cases, the order in which the JavaScript
+ * is presented on the page is very important. jQuery, for example, must be
+ * added to the page before any jQuery code is run, so jquery.js uses the
+ * JS_LIBRARY group and a weight of -20, jquery.once.js (a library drupal.js
+ * depends on) uses the JS_LIBRARY group and a weight of -19, drupal.js uses
+ * the JS_LIBRARY group and a weight of -1, other libraries use the
+ * JS_LIBRARY group and a weight of 0 or higher, and all other scripts use
+ * one of the other group constants. The exact ordering of JavaScript is as
+ * follows:
+ * - First by scope, with 'header' first, 'footer' last, and any other
+ * scopes provided by a custom theme coming in between, as determined by
+ * the theme.
+ * - Then by group.
+ * - Then by the 'every_page' flag, with TRUE coming before FALSE.
+ * - Then by weight.
+ * - Then by the order in which the JavaScript was added. For example, all
+ * else being the same, JavaScript added by a call to drupal_add_js() that
+ * happened later in the page request gets added to the page after one for
+ * which drupal_add_js() happened earlier in the page request.
+ * - defer: If set to TRUE, the defer attribute is set on the <script>
+ * tag. Defaults to FALSE.
+ * - cache: If set to FALSE, the JavaScript file is loaded anew on every page
+ * call; in other words, it is not cached. Used only when 'type' references
+ * a JavaScript file. Defaults to TRUE.
+ * - preprocess: If TRUE and JavaScript aggregation is enabled, the script
+ * file will be aggregated. Defaults to TRUE.
+ *
+ * @return
+ * The current array of JavaScript files, settings, and in-line code,
+ * including Drupal defaults, anything previously added with calls to
+ * drupal_add_js(), and this function call's additions.
+ *
+ * @see drupal_get_js()
+ */
+function drupal_add_js($data = NULL, $options = NULL) {
+ $javascript = &drupal_static(__FUNCTION__, array());
+
+ // Construct the options, taking the defaults into consideration.
+ if (isset($options)) {
+ if (!is_array($options)) {
+ $options = array('type' => $options);
+ }
+ }
+ else {
+ $options = array();
+ }
+ $options += drupal_js_defaults($data);
+
+ // Preprocess can only be set if caching is enabled.
+ $options['preprocess'] = $options['cache'] ? $options['preprocess'] : FALSE;
+
+ // Tweak the weight so that files of the same weight are included in the
+ // order of the calls to drupal_add_js().
+ $options['weight'] += count($javascript) / 1000;
+
+ if (isset($data)) {
+ // Add jquery.js and drupal.js, as well as the basePath setting, the
+ // first time a JavaScript file is added.
+ if (empty($javascript)) {
+ // url() generates the prefix using hook_url_outbound_alter(). Instead of
+ // running the hook_url_outbound_alter() again here, extract the prefix
+ // from url().
+ url('', array('prefix' => &$prefix));
+ $javascript = array(
+ 'settings' => array(
+ 'data' => array(
+ array('basePath' => base_path()),
+ array('pathPrefix' => empty($prefix) ? '' : $prefix),
+ ),
+ 'type' => 'setting',
+ 'scope' => 'header',
+ 'group' => JS_LIBRARY,
+ 'every_page' => TRUE,
+ 'weight' => 0,
+ ),
+ 'misc/drupal.js' => array(
+ 'data' => 'misc/drupal.js',
+ 'type' => 'file',
+ 'scope' => 'header',
+ 'group' => JS_LIBRARY,
+ 'every_page' => TRUE,
+ 'weight' => -1,
+ 'preprocess' => TRUE,
+ 'cache' => TRUE,
+ 'defer' => FALSE,
+ ),
+ );
+ // Register all required libraries.
+ drupal_add_library('system', 'jquery', TRUE);
+ drupal_add_library('system', 'jquery.once', TRUE);
+ }
+
+ switch ($options['type']) {
+ case 'setting':
+ // All JavaScript settings are placed in the header of the page with
+ // the library weight so that inline scripts appear afterwards.
+ $javascript['settings']['data'][] = $data;
+ break;
+
+ case 'inline':
+ $javascript[] = $options;
+ break;
+
+ default: // 'file' and 'external'
+ // Local and external files must keep their name as the associative key
+ // so the same JavaScript file is not added twice.
+ $javascript[$options['data']] = $options;
+ }
+ }
+ return $javascript;
+}
+
+/**
+ * Constructs an array of the defaults that are used for JavaScript items.
+ *
+ * @param $data
+ * (optional) The default data parameter for the JavaScript item array.
+ *
+ * @see drupal_get_js()
+ * @see drupal_add_js()
+ */
+function drupal_js_defaults($data = NULL) {
+ return array(
+ 'type' => 'file',
+ 'group' => JS_DEFAULT,
+ 'every_page' => FALSE,
+ 'weight' => 0,
+ 'scope' => 'header',
+ 'cache' => TRUE,
+ 'defer' => FALSE,
+ 'preprocess' => TRUE,
+ 'version' => NULL,
+ 'data' => $data,
+ );
+}
+
+/**
+ * Returns a themed presentation of all JavaScript code for the current page.
+ *
+ * References to JavaScript files are placed in a certain order: first, all
+ * 'core' files, then all 'module' and finally all 'theme' JavaScript files
+ * are added to the page. Then, all settings are output, followed by 'inline'
+ * JavaScript code. If running update.php, all preprocessing is disabled.
+ *
+ * Note that hook_js_alter(&$javascript) is called during this function call
+ * to allow alterations of the JavaScript during its presentation. Calls to
+ * drupal_add_js() from hook_js_alter() will not be added to the output
+ * presentation. The correct way to add JavaScript during hook_js_alter()
+ * is to add another element to the $javascript array, deriving from
+ * drupal_js_defaults(). See locale_js_alter() for an example of this.
+ *
+ * @param $scope
+ * (optional) The scope for which the JavaScript rules should be returned.
+ * Defaults to 'header'.
+ * @param $javascript
+ * (optional) An array with all JavaScript code. Defaults to the default
+ * JavaScript array for the given scope.
+ * @param $skip_alter
+ * (optional) If set to TRUE, this function skips calling drupal_alter() on
+ * $javascript, useful when the calling function passes a $javascript array
+ * that has already been altered.
+ *
+ * @return
+ * All JavaScript code segments and includes for the scope as HTML tags.
+ *
+ * @see drupal_add_js()
+ * @see locale_js_alter()
+ * @see drupal_js_defaults()
+ */
+function drupal_get_js($scope = 'header', $javascript = NULL, $skip_alter = FALSE) {
+ if (!isset($javascript)) {
+ $javascript = drupal_add_js();
+ }
+ if (empty($javascript)) {
+ return '';
+ }
+
+ // Allow modules to alter the JavaScript.
+ if (!$skip_alter) {
+ drupal_alter('js', $javascript);
+ }
+
+ // Filter out elements of the given scope.
+ $items = array();
+ foreach ($javascript as $key => $item) {
+ if ($item['scope'] == $scope) {
+ $items[$key] = $item;
+ }
+ }
+
+ $output = '';
+ // The index counter is used to keep aggregated and non-aggregated files in
+ // order by weight.
+ $index = 1;
+ $processed = array();
+ $files = array();
+ $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
+
+ // A dummy query-string is added to filenames, to gain control over
+ // browser-caching. The string changes on every update or full cache
+ // flush, forcing browsers to load a new copy of the files, as the
+ // URL changed. Files that should not be cached (see drupal_add_js())
+ // get REQUEST_TIME as query-string instead, to enforce reload on every
+ // page request.
+ $default_query_string = variable_get('css_js_query_string', '0');
+
+ // For inline JavaScript to validate as XHTML, all JavaScript containing
+ // XHTML needs to be wrapped in CDATA. To make that backwards compatible
+ // with HTML 4, we need to comment out the CDATA-tag.
+ $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
+ $embed_suffix = "\n//--><!]]>\n";
+
+ // Since JavaScript may look for arguments in the URL and act on them, some
+ // third-party code might require the use of a different query string.
+ $js_version_string = variable_get('drupal_js_version_query_string', 'v=');
+
+ // Sort the JavaScript so that it appears in the correct order.
+ uasort($items, 'drupal_sort_css_js');
+
+ // Provide the page with information about the individual JavaScript files
+ // used, information not otherwise available when aggregation is enabled.
+ $setting['ajaxPageState']['js'] = array_fill_keys(array_keys($items), 1);
+ unset($setting['ajaxPageState']['js']['settings']);
+ drupal_add_js($setting, 'setting');
+
+ // If we're outputting the header scope, then this might be the final time
+ // that drupal_get_js() is running, so add the setting to this output as well
+ // as to the drupal_add_js() cache. If $items['settings'] doesn't exist, it's
+ // because drupal_get_js() was intentionally passed a $javascript argument
+ // stripped off settings, potentially in order to override how settings get
+ // output, so in this case, do not add the setting to this output.
+ if ($scope == 'header' && isset($items['settings'])) {
+ $items['settings']['data'][] = $setting;
+ }
+
+ // Loop through the JavaScript to construct the rendered output.
+ $element = array(
+ '#tag' => 'script',
+ '#value' => '',
+ '#attributes' => array(
+ 'type' => 'text/javascript',
+ ),
+ );
+ foreach ($items as $item) {
+ $query_string = empty($item['version']) ? $default_query_string : $js_version_string . $item['version'];
+
+ switch ($item['type']) {
+ case 'setting':
+ $js_element = $element;
+ $js_element['#value_prefix'] = $embed_prefix;
+ $js_element['#value'] = 'jQuery.extend(Drupal.settings, ' . drupal_json_encode(drupal_array_merge_deep_array($item['data'])) . ");";
+ $js_element['#value_suffix'] = $embed_suffix;
+ $output .= theme('html_tag', array('element' => $js_element));
+ break;
+
+ case 'inline':
+ $js_element = $element;
+ if ($item['defer']) {
+ $js_element['#attributes']['defer'] = 'defer';
+ }
+ $js_element['#value_prefix'] = $embed_prefix;
+ $js_element['#value'] = $item['data'];
+ $js_element['#value_suffix'] = $embed_suffix;
+ $processed[$index++] = theme('html_tag', array('element' => $js_element));
+ break;
+
+ case 'file':
+ $js_element = $element;
+ if (!$item['preprocess'] || !$preprocess_js) {
+ if ($item['defer']) {
+ $js_element['#attributes']['defer'] = 'defer';
+ }
+ $query_string_separator = (strpos($item['data'], '?') !== FALSE) ? '&' : '?';
+ $js_element['#attributes']['src'] = file_create_url($item['data']) . $query_string_separator . ($item['cache'] ? $query_string : REQUEST_TIME);
+ $processed[$index++] = theme('html_tag', array('element' => $js_element));
+ }
+ else {
+ // By increasing the index for each aggregated file, we maintain
+ // the relative ordering of JS by weight. We also set the key such
+ // that groups are split by items sharing the same 'group' value and
+ // 'every_page' flag. While this potentially results in more aggregate
+ // files, it helps make each one more reusable across a site visit,
+ // leading to better front-end performance of a website as a whole.
+ // See drupal_add_js() for details.
+ $key = 'aggregate_' . $item['group'] . '_' . $item['every_page'] . '_' . $index;
+ $processed[$key] = '';
+ $files[$key][$item['data']] = $item;
+ }
+ break;
+
+ case 'external':
+ $js_element = $element;
+ // Preprocessing for external JavaScript files is ignored.
+ if ($item['defer']) {
+ $js_element['#attributes']['defer'] = 'defer';
+ }
+ $js_element['#attributes']['src'] = $item['data'];
+ $processed[$index++] = theme('html_tag', array('element' => $js_element));
+ break;
+ }
+ }
+
+ // Aggregate any remaining JS files that haven't already been output.
+ if ($preprocess_js && count($files) > 0) {
+ foreach ($files as $key => $file_set) {
+ $uri = drupal_build_js_cache($file_set);
+ // Only include the file if was written successfully. Errors are logged
+ // using watchdog.
+ if ($uri) {
+ $preprocess_file = file_create_url($uri);
+ $js_element = $element;
+ $js_element['#attributes']['src'] = $preprocess_file;
+ $processed[$key] = theme('html_tag', array('element' => $js_element));
+ }
+ }
+ }
+
+ // Keep the order of JS files consistent as some are preprocessed and others are not.
+ // Make sure any inline or JS setting variables appear last after libraries have loaded.
+ return implode('', $processed) . $output;
+}
+
+/**
+ * Adds attachments to a render() structure.
+ *
+ * Libraries, JavaScript, CSS and other types of custom structures are attached
+ * to elements using the #attached property. The #attached property is an
+ * associative array, where the keys are the the attachment types and the values
+ * are the attached data. For example:
+ * @code
+ * $build['#attached'] = array(
+ * 'js' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.js'),
+ * 'css' => array(drupal_get_path('module', 'taxonomy') . '/taxonomy.css'),
+ * );
+ * @endcode
+ *
+ * 'js', 'css', and 'library' are types that get special handling. For any
+ * other kind of attached data, the array key must be the full name of the
+ * callback function and each value an array of arguments. For example:
+ * @code
+ * $build['#attached']['drupal_add_http_header'] = array(
+ * array('Content-Type', 'application/rss+xml; charset=utf-8'),
+ * );
+ * @endcode
+ *
+ * External 'js' and 'css' files can also be loaded. For example:
+ * @code
+ * $build['#attached']['js'] = array(
+ * 'http://code.jquery.com/jquery-1.4.2.min.js' => array(
+ * 'type' => 'external',
+ * ),
+ * );
+ * @endcode
+ *
+ * @param $elements
+ * The structured array describing the data being rendered.
+ * @param $group
+ * The default group of JavaScript and CSS being added. This is only applied
+ * to the stylesheets and JavaScript items that don't have an explicit group
+ * assigned to them.
+ * @param $dependency_check
+ * When TRUE, will exit if a given library's dependencies are missing. When
+ * set to FALSE, will continue to add the libraries, even though one or more
+ * dependencies are missing. Defaults to FALSE.
+ * @param $every_page
+ * Set to TRUE to indicate that the attachments are added to every page on the
+ * site. Only attachments with the every_page flag set to TRUE can participate
+ * in JavaScript/CSS aggregation.
+ *
+ * @return
+ * FALSE if there were any missing library dependencies; TRUE if all library
+ * dependencies were met.
+ *
+ * @see drupal_add_library()
+ * @see drupal_add_js()
+ * @see drupal_add_css()
+ * @see drupal_render()
+ */
+function drupal_process_attached($elements, $group = JS_DEFAULT, $dependency_check = FALSE, $every_page = NULL) {
+ // Add defaults to the special attached structures that should be processed differently.
+ $elements['#attached'] += array(
+ 'library' => array(),
+ 'js' => array(),
+ 'css' => array(),
+ );
+
+ // Add the libraries first.
+ $success = TRUE;
+ foreach ($elements['#attached']['library'] as $library) {
+ if (drupal_add_library($library[0], $library[1], $every_page) === FALSE) {
+ $success = FALSE;
+ // Exit if the dependency is missing.
+ if ($dependency_check) {
+ return $success;
+ }
+ }
+ }
+ unset($elements['#attached']['library']);
+
+ // Add both the JavaScript and the CSS.
+ // The parameters for drupal_add_js() and drupal_add_css() require special
+ // handling.
+ foreach (array('js', 'css') as $type) {
+ foreach ($elements['#attached'][$type] as $data => $options) {
+ // If the value is not an array, it's a filename and passed as first
+ // (and only) argument.
+ if (!is_array($options)) {
+ $data = $options;
+ $options = NULL;
+ }
+ // In some cases, the first parameter ($data) is an array. Arrays can't be
+ // passed as keys in PHP, so we have to get $data from the value array.
+ if (is_numeric($data)) {
+ $data = $options['data'];
+ unset($options['data']);
+ }
+ // Apply the default group if it isn't explicitly given.
+ if (!isset($options['group'])) {
+ $options['group'] = $group;
+ }
+ // Set the every_page flag if one was passed.
+ if (isset($every_page)) {
+ $options['every_page'] = $every_page;
+ }
+ call_user_func('drupal_add_' . $type, $data, $options);
+ }
+ unset($elements['#attached'][$type]);
+ }
+
+ // Add additional types of attachments specified in the render() structure.
+ // Libraries, JavaScript and CSS have been added already, as they require
+ // special handling.
+ foreach ($elements['#attached'] as $callback => $options) {
+ if (function_exists($callback)) {
+ foreach ($elements['#attached'][$callback] as $args) {
+ call_user_func_array($callback, $args);
+ }
+ }
+ }
+
+ return $success;
+}
+
+/**
+ * Adds JavaScript to change the state of an element based on another element.
+ *
+ * A "state" means a certain property on a DOM element, such as "visible" or
+ * "checked". A state can be applied to an element, depending on the state of
+ * another element on the page. In general, states depend on HTML attributes and
+ * DOM element properties, which change due to user interaction.
+ *
+ * Since states are driven by JavaScript only, it is important to understand
+ * that all states are applied on presentation only, none of the states force
+ * any server-side logic, and that they will not be applied for site visitors
+ * without JavaScript support. All modules implementing states have to make
+ * sure that the intended logic also works without JavaScript being enabled.
+ *
+ * #states is an associative array in the form of:
+ * @code
+ * array(
+ * STATE1 => CONDITIONS_ARRAY1,
+ * STATE2 => CONDITIONS_ARRAY2,
+ * ...
+ * )
+ * @endcode
+ * Each key is the name of a state to apply to the element, such as 'visible'.
+ * Each value is a list of conditions that denote when the state should be
+ * applied.
+ *
+ * Multiple different states may be specified to act on complex conditions:
+ * @code
+ * array(
+ * 'visible' => CONDITIONS,
+ * 'checked' => OTHER_CONDITIONS,
+ * )
+ * @endcode
+ *
+ * Every condition is a key/value pair, whose key is a jQuery selector that
+ * denotes another element on the page, and whose value is an array of
+ * conditions, which must bet met on that element:
+ * @code
+ * array(
+ * 'visible' => array(
+ * JQUERY_SELECTOR => REMOTE_CONDITIONS,
+ * JQUERY_SELECTOR => REMOTE_CONDITIONS,
+ * ...
+ * ),
+ * )
+ * @endcode
+ * All conditions must be met for the state to be applied.
+ *
+ * Each remote condition is a key/value pair specifying conditions on the other
+ * element that need to be met to apply the state to the element:
+ * @code
+ * array(
+ * 'visible' => array(
+ * ':input[name="remote_checkbox"]' => array('checked' => TRUE),
+ * ),
+ * )
+ * @endcode
+ *
+ * For example, to show a textfield only when a checkbox is checked:
+ * @code
+ * $form['toggle_me'] = array(
+ * '#type' => 'checkbox',
+ * '#title' => t('Tick this box to type'),
+ * );
+ * $form['settings'] = array(
+ * '#type' => 'textfield',
+ * '#states' => array(
+ * // Only show this field when the 'toggle_me' checkbox is enabled.
+ * 'visible' => array(
+ * ':input[name="toggle_me"]' => array('checked' => TRUE),
+ * ),
+ * ),
+ * );
+ * @endcode
+ *
+ * The following states may be applied to an element:
+ * - enabled
+ * - disabled
+ * - required
+ * - optional
+ * - visible
+ * - invisible
+ * - checked
+ * - unchecked
+ * - expanded
+ * - collapsed
+ *
+ * The following states may be used in remote conditions:
+ * - empty
+ * - filled
+ * - checked
+ * - unchecked
+ * - expanded
+ * - collapsed
+ * - value
+ *
+ * The following states exist for both elements and remote conditions, but are
+ * not fully implemented and may not change anything on the element:
+ * - relevant
+ * - irrelevant
+ * - valid
+ * - invalid
+ * - touched
+ * - untouched
+ * - readwrite
+ * - readonly
+ *
+ * When referencing select lists and radio buttons in remote conditions, a
+ * 'value' condition must be used:
+ * @code
+ * '#states' => array(
+ * // Show the settings if 'bar' has been selected for 'foo'.
+ * 'visible' => array(
+ * ':input[name="foo"]' => array('value' => 'bar'),
+ * ),
+ * ),
+ * @endcode
+ *
+ * @param $elements
+ * A renderable array element having a #states property as described above.
+ *
+ * @see form_example_states_form()
+ */
+function drupal_process_states(&$elements) {
+ $elements['#attached']['library'][] = array('system', 'drupal.states');
+ $elements['#attached']['js'][] = array(
+ 'type' => 'setting',
+ 'data' => array('states' => array('#' . $elements['#id'] => $elements['#states'])),
+ );
+}
+
+/**
+ * Adds multiple JavaScript or CSS files at the same time.
+ *
+ * A library defines a set of JavaScript and/or CSS files, optionally using
+ * settings, and optionally requiring another library. For example, a library
+ * can be a jQuery plugin, a JavaScript framework, or a CSS framework. This
+ * function allows modules to load a library defined/shipped by itself or a
+ * depending module, without having to add all files of the library separately.
+ * Each library is only loaded once.
+ *
+ * @param $module
+ * The name of the module that registered the library.
+ * @param $name
+ * The name of the library to add.
+ * @param $every_page
+ * Set to TRUE if this library is added to every page on the site. Only items
+ * with the every_page flag set to TRUE can participate in aggregation.
+ *
+ * @return
+ * TRUE if the library was successfully added; FALSE if the library or one of
+ * its dependencies could not be added.
+ *
+ * @see drupal_get_library()
+ * @see hook_library()
+ * @see hook_library_alter()
+ */
+function drupal_add_library($module, $name, $every_page = NULL) {
+ $added = &drupal_static(__FUNCTION__, array());
+
+ // Only process the library if it exists and it was not added already.
+ if (!isset($added[$module][$name])) {
+ if ($library = drupal_get_library($module, $name)) {
+ // Add all components within the library.
+ $elements['#attached'] = array(
+ 'library' => $library['dependencies'],
+ 'js' => $library['js'],
+ 'css' => $library['css'],
+ );
+ $added[$module][$name] = drupal_process_attached($elements, JS_LIBRARY, TRUE, $every_page);
+ }
+ else {
+ // Requested library does not exist.
+ $added[$module][$name] = FALSE;
+ }
+ }
+
+ return $added[$module][$name];
+}
+
+/**
+ * Retrieves information for a JavaScript/CSS library.
+ *
+ * Library information is statically cached. Libraries are keyed by module for
+ * several reasons:
+ * - Libraries are not unique. Multiple modules might ship with the same library
+ * in a different version or variant. This registry cannot (and does not
+ * attempt to) prevent library conflicts.
+ * - Modules implementing and thereby depending on a library that is registered
+ * by another module can only rely on that module's library.
+ * - Two (or more) modules can still register the same library and use it
+ * without conflicts in case the libraries are loaded on certain pages only.
+ *
+ * @param $module
+ * The name of a module that registered a library.
+ * @param $name
+ * (optional) The name of a registered library to retrieve. By default, all
+ * libraries registered by $module are returned.
+ *
+ * @return
+ * The definition of the requested library, if $name was passed and it exists,
+ * or FALSE if it does not exist. If no $name was passed, an associative array
+ * of libraries registered by $module is returned (which may be empty).
+ *
+ * @see drupal_add_library()
+ * @see hook_library()
+ * @see hook_library_alter()
+ *
+ * @todo The purpose of drupal_get_*() is completely different to other page
+ * requisite API functions; find and use a different name.
+ */
+function drupal_get_library($module, $name = NULL) {
+ $libraries = &drupal_static(__FUNCTION__, array());
+
+ if (!isset($libraries[$module])) {
+ // Retrieve all libraries associated with the module.
+ $module_libraries = module_invoke($module, 'library');
+ if (empty($module_libraries)) {
+ $module_libraries = array();
+ }
+ // Allow modules to alter the module's registered libraries.
+ drupal_alter('library', $module_libraries, $module);
+
+ foreach ($module_libraries as $key => $data) {
+ if (is_array($data)) {
+ // Add default elements to allow for easier processing.
+ $module_libraries[$key] += array('dependencies' => array(), 'js' => array(), 'css' => array());
+ foreach ($module_libraries[$key]['js'] as $file => $options) {
+ $module_libraries[$key]['js'][$file]['version'] = $module_libraries[$key]['version'];
+ }
+ }
+ }
+ $libraries[$module] = $module_libraries;
+ }
+ if (isset($name)) {
+ if (!isset($libraries[$module][$name])) {
+ $libraries[$module][$name] = FALSE;
+ }
+ return $libraries[$module][$name];
+ }
+ return $libraries[$module];
+}
+
+/**
+ * Assists in adding the tableDrag JavaScript behavior to a themed table.
+ *
+ * Draggable tables should be used wherever an outline or list of sortable items
+ * needs to be arranged by an end-user. Draggable tables are very flexible and
+ * can manipulate the value of form elements placed within individual columns.
+ *
+ * To set up a table to use drag and drop in place of weight select-lists or in
+ * place of a form that contains parent relationships, the form must be themed
+ * into a table. The table must have an ID attribute set. If using
+ * theme_table(), the ID may be set as follows:
+ * @code
+ * $output = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));
+ * return $output;
+ * @endcode
+ *
+ * In the theme function for the form, a special class must be added to each
+ * form element within the same column, "grouping" them together.
+ *
+ * In a situation where a single weight column is being sorted in the table, the
+ * classes could be added like this (in the theme function):
+ * @code
+ * $form['my_elements'][$delta]['weight']['#attributes']['class'] = array('my-elements-weight');
+ * @endcode
+ *
+ * Each row of the table must also have a class of "draggable" in order to
+ * enable the drag handles:
+ * @code
+ * $row = array(...);
+ * $rows[] = array(
+ * 'data' => $row,
+ * 'class' => array('draggable'),
+ * );
+ * @endcode
+ *
+ * When tree relationships are present, the two additional classes
+ * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
+ * - Rows with the 'tabledrag-leaf' class cannot have child rows.
+ * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
+ *
+ * Calling drupal_add_tabledrag() would then be written as such:
+ * @code
+ * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
+ * @endcode
+ *
+ * In a more complex case where there are several groups in one column (such as
+ * the block regions on the admin/structure/block page), a separate subgroup
+ * class must also be added to differentiate the groups.
+ * @code
+ * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = array('my-elements-weight', 'my-elements-weight-' . $region);
+ * @endcode
+ *
+ * $group is still 'my-element-weight', and the additional $subgroup variable
+ * will be passed in as 'my-elements-weight-' . $region. This also means that
+ * you'll need to call drupal_add_tabledrag() once for every region added.
+ *
+ * @code
+ * foreach ($regions as $region) {
+ * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-' . $region);
+ * }
+ * @endcode
+ *
+ * In a situation where tree relationships are present, adding multiple
+ * subgroups is not necessary, because the table will contain indentations that
+ * provide enough information about the sibling and parent relationships. See
+ * theme_menu_overview_form() for an example creating a table containing parent
+ * relationships.
+ *
+ * Note that this function should be called from the theme layer, such as in a
+ * .tpl.php file, theme_ function, or in a template_preprocess function, not in
+ * a form declaration. Though the same JavaScript could be added to the page
+ * using drupal_add_js() directly, this function helps keep template files
+ * clean and readable. It also prevents tabledrag.js from being added twice
+ * accidentally.
+ *
+ * @param $table_id
+ * String containing the target table's id attribute. If the table does not
+ * have an id, one will need to be set, such as <table id="my-module-table">.
+ * @param $action
+ * String describing the action to be done on the form item. Either 'match'
+ * 'depth', or 'order'. Match is typically used for parent relationships.
+ * Order is typically used to set weights on other form elements with the same
+ * group. Depth updates the target element with the current indentation.
+ * @param $relationship
+ * String describing where the $action variable should be performed. Either
+ * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
+ * up the tree. Sibling will look for fields in the same group in rows above
+ * and below it. Self affects the dragged row itself. Group affects the
+ * dragged row, plus any children below it (the entire dragged group).
+ * @param $group
+ * A class name applied on all related form elements for this action.
+ * @param $subgroup
+ * (optional) If the group has several subgroups within it, this string should
+ * contain the class name identifying fields in the same subgroup.
+ * @param $source
+ * (optional) If the $action is 'match', this string should contain the class
+ * name identifying what field will be used as the source value when matching
+ * the value in $subgroup.
+ * @param $hidden
+ * (optional) The column containing the field elements may be entirely hidden
+ * from view dynamically when the JavaScript is loaded. Set to FALSE if the
+ * column should not be hidden.
+ * @param $limit
+ * (optional) Limit the maximum amount of parenting in this table.
+ * @see block-admin-display-form.tpl.php
+ * @see theme_menu_overview_form()
+ */
+function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
+ $js_added = &drupal_static(__FUNCTION__, FALSE);
+ if (!$js_added) {
+ // Add the table drag JavaScript to the page before the module JavaScript
+ // to ensure that table drag behaviors are registered before any module
+ // uses it.
+ drupal_add_library('system', 'jquery.cookie');
+ drupal_add_js('misc/tabledrag.js', array('weight' => -1));
+ $js_added = TRUE;
+ }
+
+ // If a subgroup or source isn't set, assume it is the same as the group.
+ $target = isset($subgroup) ? $subgroup : $group;
+ $source = isset($source) ? $source : $target;
+ $settings['tableDrag'][$table_id][$group][] = array(
+ 'target' => $target,
+ 'source' => $source,
+ 'relationship' => $relationship,
+ 'action' => $action,
+ 'hidden' => $hidden,
+ 'limit' => $limit,
+ );
+ drupal_add_js($settings, 'setting');
+}
+
+/**
+ * Aggregates JavaScript files into a cache file in the files directory.
+ *
+ * The file name for the JavaScript cache file is generated from the hash of
+ * the aggregated contents of the files in $files. This forces proxies and
+ * browsers to download new JavaScript when the JavaScript changes.
+ *
+ * The cache file name is retrieved on a page load via a lookup variable that
+ * contains an associative array. The array key is the hash of the names in
+ * $files while the value is the cache file name. The cache file is generated
+ * in two cases. First, if there is no file name value for the key, which will
+ * happen if a new file name has been added to $files or after the lookup
+ * variable is emptied to force a rebuild of the cache. Second, the cache file
+ * is generated if it is missing on disk. Old cache files are not deleted
+ * immediately when the lookup variable is emptied, but are deleted after a set
+ * period by drupal_delete_file_if_stale(). This ensures that files referenced
+ * by a cached page will still be available.
+ *
+ * @param $files
+ * An array of JavaScript files to aggregate and compress into one file.
+ *
+ * @return
+ * The URI of the cache file, or FALSE if the file could not be saved.
+ */
+function drupal_build_js_cache($files) {
+ $contents = '';
+ $uri = '';
+ $map = variable_get('drupal_js_cache_files', array());
+ // Create a new array so that only the file names are used to create the hash.
+ // This prevents new aggregates from being created unnecessarily.
+ $js_data = array();
+ foreach ($files as $file) {
+ $js_data[] = $file['data'];
+ }
+ $key = hash('sha256', serialize($js_data));
+ if (isset($map[$key])) {
+ $uri = $map[$key];
+ }
+
+ if (empty($uri) || !file_exists($uri)) {
+ // Build aggregate JS file.
+ foreach ($files as $path => $info) {
+ if ($info['preprocess']) {
+ // Append a ';' and a newline after each JS file to prevent them from running together.
+ $contents .= file_get_contents($path) . ";\n";
+ }
+ }
+ // Prefix filename to prevent blocking by firewalls which reject files
+ // starting with "ad*".
+ $filename = 'js_' . drupal_hash_base64($contents) . '.js';
+ // Create the js/ within the files folder.
+ $jspath = 'public://js';
+ $uri = $jspath . '/' . $filename;
+ // Create the JS file.
+ file_prepare_directory($jspath, FILE_CREATE_DIRECTORY);
+ if (!file_exists($uri) && !file_unmanaged_save_data($contents, $uri, FILE_EXISTS_REPLACE)) {
+ return FALSE;
+ }
+ // If JS gzip compression is enabled, clean URLs are enabled (which means
+ // that rewrite rules are working) and the zlib extension is available then
+ // create a gzipped version of this file. This file is served conditionally
+ // to browsers that accept gzip using .htaccess rules.
+ if (variable_get('js_gzip_compression', TRUE) && variable_get('clean_url', 0) && extension_loaded('zlib')) {
+ if (!file_exists($uri . '.gz') && !file_unmanaged_save_data(gzencode($contents, 9, FORCE_GZIP), $uri . '.gz', FILE_EXISTS_REPLACE)) {
+ return FALSE;
+ }
+ }
+ $map[$key] = $uri;
+ variable_set('drupal_js_cache_files', $map);
+ }
+ return $uri;
+}
+
+/**
+ * Deletes old cached JavaScript files and variables.
+ */
+function drupal_clear_js_cache() {
+ variable_del('javascript_parsed');
+ variable_del('drupal_js_cache_files');
+ file_scan_directory('public://js', '/.*/', array('callback' => 'drupal_delete_file_if_stale'));
+}
+
+/**
+ * Converts a PHP variable into its JavaScript equivalent.
+ *
+ * We use HTML-safe strings, with several characters escaped.
+ *
+ * @see drupal_json_decode()
+ * @see drupal_json_encode_helper()
+ * @ingroup php_wrappers
+ */
+function drupal_json_encode($var) {
+ // The PHP version cannot change within a request.
+ static $php530;
+
+ if (!isset($php530)) {
+ $php530 = version_compare(PHP_VERSION, '5.3.0', '>=');
+ }
+
+ if ($php530) {
+ // Encode <, >, ', &, and " using the json_encode() options parameter.
+ return json_encode($var, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
+ }
+
+ // json_encode() escapes <, >, ', &, and " using its options parameter, but
+ // does not support this parameter prior to PHP 5.3.0. Use a helper instead.
+ include_once DRUPAL_ROOT . '/includes/json-encode.inc';
+ return drupal_json_encode_helper($var);
+}
+
+/**
+ * Converts an HTML-safe JSON string into its PHP equivalent.
+ *
+ * @see drupal_json_encode()
+ * @ingroup php_wrappers
+ */
+function drupal_json_decode($var) {
+ return json_decode($var, TRUE);
+}
+
+/**
+ * Returns data in JSON format.
+ *
+ * This function should be used for JavaScript callback functions returning
+ * data in JSON format. It sets the header for JavaScript output.
+ *
+ * @param $var
+ * (optional) If set, the variable will be converted to JSON and output.
+ */
+function drupal_json_output($var = NULL) {
+ // We are returning JSON, so tell the browser.
+ drupal_add_http_header('Content-Type', 'application/json');
+
+ if (isset($var)) {
+ echo drupal_json_encode($var);
+ }
+}
+
+/**
+ * Ensures the private key variable used to generate tokens is set.
+ *
+ * @return
+ * The private key.
+ */
+function drupal_get_private_key() {
+ if (!($key = variable_get('drupal_private_key', 0))) {
+ $key = drupal_random_key();
+ variable_set('drupal_private_key', $key);
+ }
+ return $key;
+}
+
+/**
+ * Generates a token based on $value, the user session, and the private key.
+ *
+ * @param $value
+ * An additional value to base the token on.
+ *
+ * @return string
+ * A 43-character URL-safe token for validation, based on the user session ID,
+ * the hash salt provided from drupal_get_hash_salt(), and the
+ * 'drupal_private_key' configuration variable.
+ *
+ * @see drupal_get_hash_salt()
+ */
+function drupal_get_token($value = '') {
+ return drupal_hmac_base64($value, session_id() . drupal_get_private_key() . drupal_get_hash_salt());
+}
+
+/**
+ * Validates a token based on $value, the user session, and the private key.
+ *
+ * @param $token
+ * The token to be validated.
+ * @param $value
+ * An additional value to base the token on.
+ * @param $skip_anonymous
+ * Set to true to skip token validation for anonymous users.
+ *
+ * @return
+ * True for a valid token, false for an invalid token. When $skip_anonymous
+ * is true, the return value will always be true for anonymous users.
+ */
+function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
+ global $user;
+ return (($skip_anonymous && $user->uid == 0) || ($token === drupal_get_token($value)));
+}
+
+function _drupal_bootstrap_full() {
+ static $called = FALSE;
+
+ if ($called) {
+ return;
+ }
+ $called = TRUE;
+ require_once DRUPAL_ROOT . '/' . variable_get('path_inc', 'includes/path.inc');
+ require_once DRUPAL_ROOT . '/includes/theme.inc';
+ require_once DRUPAL_ROOT . '/includes/pager.inc';
+ require_once DRUPAL_ROOT . '/' . variable_get('menu_inc', 'includes/menu.inc');
+ require_once DRUPAL_ROOT . '/includes/tablesort.inc';
+ require_once DRUPAL_ROOT . '/includes/file.inc';
+ require_once DRUPAL_ROOT . '/includes/unicode.inc';
+ require_once DRUPAL_ROOT . '/includes/image.inc';
+ require_once DRUPAL_ROOT . '/includes/form.inc';
+ require_once DRUPAL_ROOT . '/includes/mail.inc';
+ require_once DRUPAL_ROOT . '/includes/actions.inc';
+ require_once DRUPAL_ROOT . '/includes/ajax.inc';
+ require_once DRUPAL_ROOT . '/includes/token.inc';
+ require_once DRUPAL_ROOT . '/includes/errors.inc';
+
+ // Detect string handling method
+ unicode_check();
+ // Undo magic quotes
+ fix_gpc_magic();
+ // Load all enabled modules
+ module_load_all();
+ // Make sure all stream wrappers are registered.
+ file_get_stream_wrappers();
+ // Ensure mt_rand is reseeded, to prevent random values from one page load
+ // being exploited to predict random values in subsequent page loads.
+ $seed = unpack("L", drupal_random_bytes(4));
+ mt_srand($seed[1]);
+
+ $test_info = &$GLOBALS['drupal_test_info'];
+ if (!empty($test_info['in_child_site'])) {
+ // Running inside the simpletest child site, log fatal errors to test
+ // specific file directory.
+ ini_set('log_errors', 1);
+ ini_set('error_log', 'public://error.log');
+ }
+
+ // Initialize $_GET['q'] prior to invoking hook_init().
+ drupal_path_initialize();
+
+ // Let all modules take action before the menu system handles the request.
+ // We do not want this while running update.php.
+ if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
+ // Prior to invoking hook_init(), initialize the theme (potentially a custom
+ // one for this page), so that:
+ // - Modules with hook_init() implementations that call theme() or
+ // theme_get_registry() don't initialize the incorrect theme.
+ // - The theme can have hook_*_alter() implementations affect page building
+ // (e.g., hook_form_alter(), hook_node_view_alter(), hook_page_alter()),
+ // ahead of when rendering starts.
+ menu_set_custom_theme();
+ drupal_theme_initialize();
+ module_invoke_all('init');
+ }
+}
+
+/**
+ * Stores the current page in the cache.
+ *
+ * If page_compression is enabled, a gzipped version of the page is stored in
+ * the cache to avoid compressing the output on each request. The cache entry
+ * is unzipped in the relatively rare event that the page is requested by a
+ * client without gzip support.
+ *
+ * Page compression requires the PHP zlib extension
+ * (http://php.net/manual/ref.zlib.php).
+ *
+ * @see drupal_page_header()
+ */
+function drupal_page_set_cache() {
+ global $base_root;
+
+ if (drupal_page_is_cacheable()) {
+
+ // Check whether the current page might be compressed.
+ $page_compressed = variable_get('page_compression', TRUE) && extension_loaded('zlib');
+
+ $cache = (object) array(
+ 'cid' => $base_root . request_uri(),
+ 'data' => array(
+ 'path' => $_GET['q'],
+ 'body' => ob_get_clean(),
+ 'title' => drupal_get_title(),
+ 'headers' => array(),
+ // We need to store whether page was compressed or not,
+ // because by the time it is read, the configuration might change.
+ 'page_compressed' => $page_compressed,
+ ),
+ 'expire' => CACHE_TEMPORARY,
+ 'created' => REQUEST_TIME,
+ );
+
+ // Restore preferred header names based on the lower-case names returned
+ // by drupal_get_http_header().
+ $header_names = _drupal_set_preferred_header_name();
+ foreach (drupal_get_http_header() as $name_lower => $value) {
+ $cache->data['headers'][$header_names[$name_lower]] = $value;
+ if ($name_lower == 'expires') {
+ // Use the actual timestamp from an Expires header if available.
+ $cache->expire = strtotime($value);
+ }
+ }
+
+ if ($cache->data['body']) {
+ if ($page_compressed) {
+ $cache->data['body'] = gzencode($cache->data['body'], 9, FORCE_GZIP);
+ }
+ cache_set($cache->cid, $cache->data, 'cache_page', $cache->expire);
+ }
+ return $cache;
+ }
+}
+
+/**
+ * Executes a cron run when called.
+ *
+ * Do not call this function from a test. Use $this->cronRun() instead.
+ *
+ * @return
+ * TRUE if cron ran successfully.
+ */
+function drupal_cron_run() {
+ // Allow execution to continue even if the request gets canceled.
+ @ignore_user_abort(TRUE);
+
+ // Prevent session information from being saved while cron is running.
+ $original_session_saving = drupal_save_session();
+ drupal_save_session(FALSE);
+
+ // Force the current user to anonymous to ensure consistent permissions on
+ // cron runs.
+ $original_user = $GLOBALS['user'];
+ $GLOBALS['user'] = drupal_anonymous_user();
+
+ // Try to allocate enough time to run all the hook_cron implementations.
+ drupal_set_time_limit(240);
+
+ $return = FALSE;
+ // Grab the defined cron queues.
+ $queues = module_invoke_all('cron_queue_info');
+ drupal_alter('cron_queue_info', $queues);
+
+ // Try to acquire cron lock.
+ if (!lock_acquire('cron', 240.0)) {
+ // Cron is still running normally.
+ watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
+ }
+ else {
+ // Make sure every queue exists. There is no harm in trying to recreate an
+ // existing queue.
+ foreach ($queues as $queue_name => $info) {
+ DrupalQueue::get($queue_name)->createQueue();
+ }
+ // Register shutdown callback.
+ drupal_register_shutdown_function('drupal_cron_cleanup');
+
+ // Iterate through the modules calling their cron handlers (if any):
+ foreach (module_implements('cron') as $module) {
+ // Do not let an exception thrown by one module disturb another.
+ try {
+ module_invoke($module, 'cron');
+ }
+ catch (Exception $e) {
+ watchdog_exception('cron', $e);
+ }
+ }
+
+ // Record cron time.
+ variable_set('cron_last', REQUEST_TIME);
+ watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
+
+ // Release cron lock.
+ lock_release('cron');
+
+ // Return TRUE so other functions can check if it did run successfully
+ $return = TRUE;
+ }
+
+ foreach ($queues as $queue_name => $info) {
+ if (!empty($info['skip on cron'])) {
+ // Do not run if queue wants to skip.
+ continue;
+ }
+ $function = $info['worker callback'];
+ $end = time() + (isset($info['time']) ? $info['time'] : 15);
+ $queue = DrupalQueue::get($queue_name);
+ while (time() < $end && ($item = $queue->claimItem())) {
+ $function($item->data);
+ $queue->deleteItem($item);
+ }
+ }
+ // Restore the user.
+ $GLOBALS['user'] = $original_user;
+ drupal_save_session($original_session_saving);
+
+ return $return;
+}
+
+/**
+ * Shutdown function: Performs cron cleanup.
+ *
+ * @see drupal_cron_run()
+ * @see drupal_register_shutdown_function()
+ */
+function drupal_cron_cleanup() {
+ // See if the semaphore is still locked.
+ if (variable_get('cron_semaphore', FALSE)) {
+ watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
+
+ // Release cron semaphore.
+ variable_del('cron_semaphore');
+ }
+}
+
+/**
+ * Returns information about system object files (modules, themes, etc.).
+ *
+ * This function is used to find all or some system object files (module files,
+ * theme files, etc.) that exist on the site. It searches in several locations,
+ * depending on what type of object you are looking for. For instance, if you
+ * are looking for modules and call:
+ * @code
+ * drupal_system_listing("/\.module$/", "modules", 'name', 0);
+ * @endcode
+ * this function will search the site-wide modules directory (i.e., /modules/),
+ * your installation profile's directory (i.e.,
+ * /profiles/your_site_profile/modules/), the all-sites directory (i.e.,
+ * /sites/all/modules/), and your site-specific directory (i.e.,
+ * /sites/your_site_dir/modules/), in that order, and return information about
+ * all of the files ending in .module in those directories.
+ *
+ * The information is returned in an associative array, which can be keyed on
+ * the file name ($key = 'filename'), the file name without the extension ($key
+ * = 'name'), or the full file stream URI ($key = 'uri'). If you use a key of
+ * 'filename' or 'name', files found later in the search will take precedence
+ * over files found earlier (unless they belong to a module or theme not
+ * compatible with Drupal core); if you choose a key of 'uri', you will get all
+ * files found.
+ *
+ * @param string $mask
+ * The preg_match() regular expression for the files to find.
+ * @param string $directory
+ * The subdirectory name in which the files are found. For example,
+ * 'modules' will search in sub-directories of the top-level /modules
+ * directory, sub-directories of /sites/all/modules/, etc.
+ * @param string $key
+ * The key to be used for the associative array returned. Possible values are
+ * 'uri', for the file's URI; 'filename', for the basename of the file; and
+ * 'name' for the name of the file without the extension. If you choose 'name'
+ * or 'filename', only the highest-precedence file will be returned.
+ * @param int $min_depth
+ * Minimum depth of directories to return files from, relative to each
+ * directory searched. For instance, a minimum depth of 2 would find modules
+ * inside /modules/node/tests, but not modules directly in /modules/node.
+ *
+ * @return array
+ * An associative array of file objects, keyed on the chosen key. Each element
+ * in the array is an object containing file information, with properties:
+ * - 'uri': Full URI of the file.
+ * - 'filename': File name.
+ * - 'name': Name of file without the extension.
+ */
+function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
+ $config = conf_path();
+
+ $searchdir = array($directory);
+ $files = array();
+
+ // The 'profiles' directory contains pristine collections of modules and
+ // themes as organized by a distribution. It is pristine in the same way
+ // that /modules is pristine for core; users should avoid changing anything
+ // there in favor of sites/all or sites/<domain> directories.
+ $profiles = array();
+ $profile = drupal_get_profile();
+ // For SimpleTest to be able to test modules packaged together with a
+ // distribution we need to include the profile of the parent site (in which
+ // test runs are triggered).
+ if (drupal_valid_test_ua()) {
+ $testing_profile = variable_get('simpletest_parent_profile', FALSE);
+ if ($testing_profile && $testing_profile != $profile) {
+ $profiles[] = $testing_profile;
+ }
+ }
+ // In case both profile directories contain the same extension, the actual
+ // profile always has precedence.
+ $profiles[] = $profile;
+ foreach ($profiles as $profile) {
+ if (file_exists("profiles/$profile/$directory")) {
+ $searchdir[] = "profiles/$profile/$directory";
+ }
+ }
+
+ // Always search sites/all/* as well as the global directories.
+ $searchdir[] = 'sites/all/' . $directory;
+
+ if (file_exists("$config/$directory")) {
+ $searchdir[] = "$config/$directory";
+ }
+
+ // Get current list of items.
+ if (!function_exists('file_scan_directory')) {
+ require_once DRUPAL_ROOT . '/includes/file.inc';
+ }
+ foreach ($searchdir as $dir) {
+ $files_to_add = file_scan_directory($dir, $mask, array('key' => $key, 'min_depth' => $min_depth));
+
+ // Duplicate files found in later search directories take precedence over
+ // earlier ones, so we want them to overwrite keys in our resulting
+ // $files array.
+ // The exception to this is if the later file is from a module or theme not
+ // compatible with Drupal core. This may occur during upgrades of Drupal
+ // core when new modules exist in core while older contrib modules with the
+ // same name exist in a directory such as sites/all/modules/.
+ foreach (array_intersect_key($files_to_add, $files) as $file_key => $file) {
+ // If it has no info file, then we just behave liberally and accept the
+ // new resource on the list for merging.
+ if (file_exists($info_file = dirname($file->uri) . '/' . $file->name . '.info')) {
+ // Get the .info file for the module or theme this file belongs to.
+ $info = drupal_parse_info_file($info_file);
+
+ // If the module or theme is incompatible with Drupal core, remove it
+ // from the array for the current search directory, so it is not
+ // overwritten when merged with the $files array.
+ if (isset($info['core']) && $info['core'] != DRUPAL_CORE_COMPATIBILITY) {
+ unset($files_to_add[$file_key]);
+ }
+ }
+ }
+ $files = array_merge($files, $files_to_add);
+ }
+
+ return $files;
+}
+
+/**
+ * Sets the main page content value for later use.
+ *
+ * Given the nature of the Drupal page handling, this will be called once with
+ * a string or array. We store that and return it later as the block is being
+ * displayed.
+ *
+ * @param $content
+ * A string or renderable array representing the body of the page.
+ *
+ * @return
+ * If called without $content, a renderable array representing the body of
+ * the page.
+ */
+function drupal_set_page_content($content = NULL) {
+ $content_block = &drupal_static(__FUNCTION__, NULL);
+ $main_content_display = &drupal_static('system_main_content_added', FALSE);
+
+ if (!empty($content)) {
+ $content_block = (is_array($content) ? $content : array('main' => array('#markup' => $content)));
+ }
+ else {
+ // Indicate that the main content has been requested. We assume that
+ // the module requesting the content will be adding it to the page.
+ // A module can indicate that it does not handle the content by setting
+ // the static variable back to FALSE after calling this function.
+ $main_content_display = TRUE;
+ return $content_block;
+ }
+}
+
+/**
+ * #pre_render callback to render #browsers into #prefix and #suffix.
+ *
+ * @param $elements
+ * A render array with a '#browsers' property. The '#browsers' property can
+ * contain any or all of the following keys:
+ * - 'IE': If FALSE, the element is not rendered by Internet Explorer. If
+ * TRUE, the element is rendered by Internet Explorer. Can also be a string
+ * containing an expression for Internet Explorer to evaluate as part of a
+ * conditional comment. For example, this can be set to 'lt IE 7' for the
+ * element to be rendered in Internet Explorer 6, but not in Internet
+ * Explorer 7 or higher. Defaults to TRUE.
+ * - '!IE': If FALSE, the element is not rendered by browsers other than
+ * Internet Explorer. If TRUE, the element is rendered by those browsers.
+ * Defaults to TRUE.
+ * Examples:
+ * - To render an element in all browsers, '#browsers' can be left out or set
+ * to array('IE' => TRUE, '!IE' => TRUE).
+ * - To render an element in Internet Explorer only, '#browsers' can be set
+ * to array('!IE' => FALSE).
+ * - To render an element in Internet Explorer 6 only, '#browsers' can be set
+ * to array('IE' => 'lt IE 7', '!IE' => FALSE).
+ * - To render an element in Internet Explorer 8 and higher and in all other
+ * browsers, '#browsers' can be set to array('IE' => 'gte IE 8').
+ *
+ * @return
+ * The passed-in element with markup for conditional comments potentially
+ * added to '#prefix' and '#suffix'.
+ */
+function drupal_pre_render_conditional_comments($elements) {
+ $browsers = isset($elements['#browsers']) ? $elements['#browsers'] : array();
+ $browsers += array(
+ 'IE' => TRUE,
+ '!IE' => TRUE,
+ );
+
+ // If rendering in all browsers, no need for conditional comments.
+ if ($browsers['IE'] === TRUE && $browsers['!IE']) {
+ return $elements;
+ }
+
+ // Determine the conditional comment expression for Internet Explorer to
+ // evaluate.
+ if ($browsers['IE'] === TRUE) {
+ $expression = 'IE';
+ }
+ elseif ($browsers['IE'] === FALSE) {
+ $expression = '!IE';
+ }
+ else {
+ $expression = $browsers['IE'];
+ }
+
+ // Wrap the element's potentially existing #prefix and #suffix properties with
+ // conditional comment markup. The conditional comment expression is evaluated
+ // by Internet Explorer only. To control the rendering by other browsers,
+ // either the "downlevel-hidden" or "downlevel-revealed" technique must be
+ // used. See http://en.wikipedia.org/wiki/Conditional_comment for details.
+ $elements += array(
+ '#prefix' => '',
+ '#suffix' => '',
+ );
+ if (!$browsers['!IE']) {
+ // "downlevel-hidden".
+ $elements['#prefix'] = "\n<!--[if $expression]>\n" . $elements['#prefix'];
+ $elements['#suffix'] .= "<![endif]-->\n";
+ }
+ else {
+ // "downlevel-revealed".
+ $elements['#prefix'] = "\n<!--[if $expression]><!-->\n" . $elements['#prefix'];
+ $elements['#suffix'] .= "<!--<![endif]-->\n";
+ }
+
+ return $elements;
+}
+
+/**
+ * #pre_render callback to render a link into #markup.
+ *
+ * Doing so during pre_render gives modules a chance to alter the link parts.
+ *
+ * @param $elements
+ * A structured array whose keys form the arguments to l():
+ * - #title: The link text to pass as argument to l().
+ * - #href: The URL path component to pass as argument to l().
+ * - #options: (optional) An array of options to pass to l().
+ *
+ * @return
+ * The passed-in elements containing a rendered link in '#markup'.
+ */
+function drupal_pre_render_link($element) {
+ // By default, link options to pass to l() are normally set in #options.
+ $element += array('#options' => array());
+ // However, within the scope of renderable elements, #attributes is a valid
+ // way to specify attributes, too. Take them into account, but do not override
+ // attributes from #options.
+ if (isset($element['#attributes'])) {
+ $element['#options'] += array('attributes' => array());
+ $element['#options']['attributes'] += $element['#attributes'];
+ }
+
+ // This #pre_render callback can be invoked from inside or outside of a Form
+ // API context, and depending on that, a HTML ID may be already set in
+ // different locations. #options should have precedence over Form API's #id.
+ // #attributes have been taken over into #options above already.
+ if (isset($element['#options']['attributes']['id'])) {
+ $element['#id'] = $element['#options']['attributes']['id'];
+ }
+ elseif (isset($element['#id'])) {
+ $element['#options']['attributes']['id'] = $element['#id'];
+ }
+
+ // Conditionally invoke ajax_pre_render_element(), if #ajax is set.
+ if (isset($element['#ajax']) && !isset($element['#ajax_processed'])) {
+ // If no HTML ID was found above, automatically create one.
+ if (!isset($element['#id'])) {
+ $element['#id'] = $element['#options']['attributes']['id'] = drupal_html_id('ajax-link');
+ }
+ // If #ajax['path] was not specified, use the href as Ajax request URL.
+ if (!isset($element['#ajax']['path'])) {
+ $element['#ajax']['path'] = $element['#href'];
+ $element['#ajax']['options'] = $element['#options'];
+ }
+ $element = ajax_pre_render_element($element);
+ }
+
+ $element['#markup'] = l($element['#title'], $element['#href'], $element['#options']);
+ return $element;
+}
+
+/**
+ * #pre_render callback that collects child links into a single array.
+ *
+ * This function can be added as a pre_render callback for a renderable array,
+ * usually one which will be themed by theme_links(). It iterates through all
+ * unrendered children of the element, collects any #links properties it finds,
+ * merges them into the parent element's #links array, and prevents those
+ * children from being rendered separately.
+ *
+ * The purpose of this is to allow links to be logically grouped into related
+ * categories, so that each child group can be rendered as its own list of
+ * links if drupal_render() is called on it, but calling drupal_render() on the
+ * parent element will still produce a single list containing all the remaining
+ * links, regardless of what group they were in.
+ *
+ * A typical example comes from node links, which are stored in a renderable
+ * array similar to this:
+ * @code
+ * $node->content['links'] = array(
+ * '#theme' => 'links__node',
+ * '#pre_render' => array('drupal_pre_render_links'),
+ * 'comment' => array(
+ * '#theme' => 'links__node__comment',
+ * '#links' => array(
+ * // An array of links associated with node comments, suitable for
+ * // passing in to theme_links().
+ * ),
+ * ),
+ * 'statistics' => array(
+ * '#theme' => 'links__node__statistics',
+ * '#links' => array(
+ * // An array of links associated with node statistics, suitable for
+ * // passing in to theme_links().
+ * ),
+ * ),
+ * 'translation' => array(
+ * '#theme' => 'links__node__translation',
+ * '#links' => array(
+ * // An array of links associated with node translation, suitable for
+ * // passing in to theme_links().
+ * ),
+ * ),
+ * );
+ * @endcode
+ *
+ * In this example, the links are grouped by functionality, which can be
+ * helpful to themers who want to display certain kinds of links independently.
+ * For example, adding this code to node.tpl.php will result in the comment
+ * links being rendered as a single list:
+ * @code
+ * print render($content['links']['comment']);
+ * @endcode
+ *
+ * (where $node->content has been transformed into $content before handing
+ * control to the node.tpl.php template).
+ *
+ * The pre_render function defined here allows the above flexibility, but also
+ * allows the following code to be used to render all remaining links into a
+ * single list, regardless of their group:
+ * @code
+ * print render($content['links']);
+ * @endcode
+ *
+ * In the above example, this will result in the statistics and translation
+ * links being rendered together in a single list (but not the comment links,
+ * which were rendered previously on their own).
+ *
+ * Because of the way this function works, the individual properties of each
+ * group (for example, a group-specific #theme property such as
+ * 'links__node__comment' in the example above, or any other property such as
+ * #attributes or #pre_render that is attached to it) are only used when that
+ * group is rendered on its own. When the group is rendered together with other
+ * children, these child-specific properties are ignored, and only the overall
+ * properties of the parent are used.
+ */
+function drupal_pre_render_links($element) {
+ $element += array('#links' => array());
+ foreach (element_children($element) as $key) {
+ $child = &$element[$key];
+ // If the child has links which have not been printed yet and the user has
+ // access to it, merge its links in to the parent.
+ if (isset($child['#links']) && empty($child['#printed']) && (!isset($child['#access']) || $child['#access'])) {
+ $element['#links'] += $child['#links'];
+ // Mark the child as having been printed already (so that its links
+ // cannot be mistakenly rendered twice).
+ $child['#printed'] = TRUE;
+ }
+ }
+ return $element;
+}
+
+/**
+ * #pre_render callback to append contents in #markup to #children.
+ *
+ * This needs to be a #pre_render callback, because eventually assigned
+ * #theme_wrappers will expect the element's rendered content in #children.
+ * Note that if also a #theme is defined for the element, then the result of
+ * the theme callback will override #children.
+ *
+ * @param $elements
+ * A structured array using the #markup key.
+ *
+ * @return
+ * The passed-in elements, but #markup appended to #children.
+ *
+ * @see drupal_render()
+ */
+function drupal_pre_render_markup($elements) {
+ $elements['#children'] = $elements['#markup'];
+ return $elements;
+}
+
+/**
+ * Renders the page, including all theming.
+ *
+ * @param $page
+ * A string or array representing the content of a page. The array consists of
+ * the following keys:
+ * - #type: Value is always 'page'. This pushes the theming through
+ * page.tpl.php (required).
+ * - #show_messages: Suppress drupal_get_message() items. Used by Batch
+ * API (optional).
+ *
+ * @see hook_page_alter()
+ * @see element_info()
+ */
+function drupal_render_page($page) {
+ $main_content_display = &drupal_static('system_main_content_added', FALSE);
+
+ // Allow menu callbacks to return strings or arbitrary arrays to render.
+ // If the array returned is not of #type page directly, we need to fill
+ // in the page with defaults.
+ if (is_string($page) || (is_array($page) && (!isset($page['#type']) || ($page['#type'] != 'page')))) {
+ drupal_set_page_content($page);
+ $page = element_info('page');
+ }
+
+ // Modules can add elements to $page as needed in hook_page_build().
+ foreach (module_implements('page_build') as $module) {
+ $function = $module . '_page_build';
+ $function($page);
+ }
+ // Modules alter the $page as needed. Blocks are populated into regions like
+ // 'sidebar_first', 'footer', etc.
+ drupal_alter('page', $page);
+
+ // If no module has taken care of the main content, add it to the page now.
+ // This allows the site to still be usable even if no modules that
+ // control page regions (for example, the Block module) are enabled.
+ if (!$main_content_display) {
+ $page['content']['system_main'] = drupal_set_page_content();
+ }
+
+ return drupal_render($page);
+}
+
+/**
+ * Renders HTML given a structured array tree.
+ *
+ * Recursively iterates over each of the array elements, generating HTML code.
+ *
+ * Renderable arrays have two kinds of key/value pairs: properties and
+ * children. Properties have keys starting with '#' and their values influence
+ * how the array will be rendered. Children are all elements whose keys do not
+ * start with a '#'. Their values should be renderable arrays themselves,
+ * which will be rendered during the rendering of the parent array. The markup
+ * provided by the children is typically inserted into the markup generated by
+ * the parent array.
+ *
+ * HTML generation for a renderable array, and the treatment of any children,
+ * is controlled by two properties containing theme functions, #theme and
+ * #theme_wrappers.
+ *
+ * #theme is the theme function called first. If it is set and the element has
+ * any children, it is the responsibility of the theme function to render
+ * these children. For elements that are not allowed to have any children,
+ * e.g. buttons or textfields, the theme function can be used to render the
+ * element itself. If #theme is not present and the element has children, each
+ * child is itself rendered by a call to drupal_render(), and the results are
+ * concatenated.
+ *
+ * The #theme_wrappers property contains an array of theme functions which will
+ * be called, in order, after #theme has run. These can be used to add further
+ * markup around the rendered children; e.g., fieldsets add the required markup
+ * for a fieldset around their rendered child elements. All wrapper theme
+ * functions have to include the element's #children property in their output,
+ * as it contains the output of the previous theme functions and the rendered
+ * children.
+ *
+ * For example, for the form element type, by default only the #theme_wrappers
+ * property is set, which adds the form markup around the rendered child
+ * elements of the form. This allows you to set the #theme property on a
+ * specific form to a custom theme function, giving you complete control over
+ * the placement of the form's children while not at all having to deal with
+ * the form markup itself.
+ *
+ * drupal_render() can optionally cache the rendered output of elements to
+ * improve performance. To use drupal_render() caching, set the element's #cache
+ * property to an associative array with one or several of the following keys:
+ * - 'keys': An array of one or more keys that identify the element. If 'keys'
+ * is set, the cache ID is created automatically from these keys. See
+ * drupal_render_cid_create().
+ * - 'granularity' (optional): Define the cache granularity using binary
+ * combinations of the cache granularity constants, e.g.
+ * DRUPAL_CACHE_PER_USER to cache for each user separately or
+ * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE to cache separately for each
+ * page and role. If not specified the element is cached globally for each
+ * theme and language.
+ * - 'cid': Specify the cache ID directly. Either 'keys' or 'cid' is required.
+ * If 'cid' is set, 'keys' and 'granularity' are ignored. Use only if you
+ * have special requirements.
+ * - 'expire': Set to one of the cache lifetime constants.
+ * - 'bin': Specify a cache bin to cache the element in. Defaults to 'cache'.
+ *
+ * This function is usually called from within another function, like
+ * drupal_get_form() or a theme function. Elements are sorted internally
+ * using uasort(). Since this is expensive, when passing already sorted
+ * elements to drupal_render(), for example from a database query, set
+ * $elements['#sorted'] = TRUE to avoid sorting them a second time.
+ *
+ * drupal_render() flags each element with a '#printed' status to indicate that
+ * the element has been rendered, which allows individual elements of a given
+ * array to be rendered independently and prevents them from being rendered
+ * more than once on subsequent calls to drupal_render() (e.g., as part of a
+ * larger array). If the same array or array element is passed more than once
+ * to drupal_render(), it simply returns an empty string.
+ *
+ * @param array $elements
+ * The structured array describing the data to be rendered.
+ *
+ * @return string
+ * The rendered HTML.
+ */
+function drupal_render(&$elements) {
+ // Early-return nothing if user does not have access.
+ if (empty($elements) || (isset($elements['#access']) && !$elements['#access'])) {
+ return '';
+ }
+
+ // Do not print elements twice.
+ if (!empty($elements['#printed'])) {
+ return '';
+ }
+
+ // Try to fetch the element's markup from cache and return.
+ if (isset($elements['#cache'])) {
+ $cached_output = drupal_render_cache_get($elements);
+ if ($cached_output !== FALSE) {
+ return $cached_output;
+ }
+ }
+
+ // If #markup is set, ensure #type is set. This allows to specify just #markup
+ // on an element without setting #type.
+ if (isset($elements['#markup']) && !isset($elements['#type'])) {
+ $elements['#type'] = 'markup';
+ }
+
+ // If the default values for this element have not been loaded yet, populate
+ // them.
+ if (isset($elements['#type']) && empty($elements['#defaults_loaded'])) {
+ $elements += element_info($elements['#type']);
+ }
+
+ // Make any final changes to the element before it is rendered. This means
+ // that the $element or the children can be altered or corrected before the
+ // element is rendered into the final text.
+ if (isset($elements['#pre_render'])) {
+ foreach ($elements['#pre_render'] as $function) {
+ if (function_exists($function)) {
+ $elements = $function($elements);
+ }
+ }
+ }
+
+ // Allow #pre_render to abort rendering.
+ if (!empty($elements['#printed'])) {
+ return '';
+ }
+
+ // Get the children of the element, sorted by weight.
+ $children = element_children($elements, TRUE);
+
+ // Initialize this element's #children, unless a #pre_render callback already
+ // preset #children.
+ if (!isset($elements['#children'])) {
+ $elements['#children'] = '';
+ }
+ // Call the element's #theme function if it is set. Then any children of the
+ // element have to be rendered there.
+ if (isset($elements['#theme'])) {
+ $elements['#children'] = theme($elements['#theme'], $elements);
+ }
+ // If #theme was not set and the element has children, render them now.
+ // This is the same process as drupal_render_children() but is inlined
+ // for speed.
+ if ($elements['#children'] == '') {
+ foreach ($children as $key) {
+ $elements['#children'] .= drupal_render($elements[$key]);
+ }
+ }
+
+ // Let the theme functions in #theme_wrappers add markup around the rendered
+ // children.
+ if (isset($elements['#theme_wrappers'])) {
+ foreach ($elements['#theme_wrappers'] as $theme_wrapper) {
+ $elements['#children'] = theme($theme_wrapper, $elements);
+ }
+ }
+
+ // Filter the outputted content and make any last changes before the
+ // content is sent to the browser. The changes are made on $content
+ // which allows the output'ed text to be filtered.
+ if (isset($elements['#post_render'])) {
+ foreach ($elements['#post_render'] as $function) {
+ if (function_exists($function)) {
+ $elements['#children'] = $function($elements['#children'], $elements);
+ }
+ }
+ }
+
+ // Add any JavaScript state information associated with the element.
+ if (!empty($elements['#states'])) {
+ drupal_process_states($elements);
+ }
+
+ // Add additional libraries, CSS, JavaScript an other custom
+ // attached data associated with this element.
+ if (!empty($elements['#attached'])) {
+ drupal_process_attached($elements);
+ }
+
+ $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
+ $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
+ $output = $prefix . $elements['#children'] . $suffix;
+
+ // Cache the processed element if #cache is set.
+ if (isset($elements['#cache'])) {
+ drupal_render_cache_set($output, $elements);
+ }
+
+ $elements['#printed'] = TRUE;
+ return $output;
+}
+
+/**
+ * Renders children of an element and concatenates them.
+ *
+ * This renders all children of an element using drupal_render() and then
+ * joins them together into a single string.
+ *
+ * @param $element
+ * The structured array whose children shall be rendered.
+ * @param $children_keys
+ * If the keys of the element's children are already known, they can be passed
+ * in to save another run of element_children().
+ */
+function drupal_render_children(&$element, $children_keys = NULL) {
+ if ($children_keys === NULL) {
+ $children_keys = element_children($element);
+ }
+ $output = '';
+ foreach ($children_keys as $key) {
+ if (!empty($element[$key])) {
+ $output .= drupal_render($element[$key]);
+ }
+ }
+ return $output;
+}
+
+/**
+ * Renders an element.
+ *
+ * This function renders an element using drupal_render(). The top level
+ * element is shown with show() before rendering, so it will always be rendered
+ * even if hide() had been previously used on it.
+ *
+ * @param $element
+ * The element to be rendered.
+ *
+ * @return
+ * The rendered element.
+ *
+ * @see drupal_render()
+ * @see show()
+ * @see hide()
+ */
+function render(&$element) {
+ if (is_array($element)) {
+ show($element);
+ return drupal_render($element);
+ }
+ else {
+ // Safe-guard for inappropriate use of render() on flat variables: return
+ // the variable as-is.
+ return $element;
+ }
+}
+
+/**
+ * Hides an element from later rendering.
+ *
+ * The first time render() or drupal_render() is called on an element tree,
+ * as each element in the tree is rendered, it is marked with a #printed flag
+ * and the rendered children of the element are cached. Subsequent calls to
+ * render() or drupal_render() will not traverse the child tree of this element
+ * again: they will just use the cached children. So if you want to hide an
+ * element, be sure to call hide() on the element before its parent tree is
+ * rendered for the first time, as it will have no effect on subsequent
+ * renderings of the parent tree.
+ *
+ * @param $element
+ * The element to be hidden.
+ *
+ * @return
+ * The element.
+ *
+ * @see render()
+ * @see show()
+ */
+function hide(&$element) {
+ $element['#printed'] = TRUE;
+ return $element;
+}
+
+/**
+ * Shows a hidden element for later rendering.
+ *
+ * You can also use render($element), which shows the element while rendering
+ * it.
+ *
+ * The first time render() or drupal_render() is called on an element tree,
+ * as each element in the tree is rendered, it is marked with a #printed flag
+ * and the rendered children of the element are cached. Subsequent calls to
+ * render() or drupal_render() will not traverse the child tree of this element
+ * again: they will just use the cached children. So if you want to show an
+ * element, be sure to call show() on the element before its parent tree is
+ * rendered for the first time, as it will have no effect on subsequent
+ * renderings of the parent tree.
+ *
+ * @param $element
+ * The element to be shown.
+ *
+ * @return
+ * The element.
+ *
+ * @see render()
+ * @see hide()
+ */
+function show(&$element) {
+ $element['#printed'] = FALSE;
+ return $element;
+}
+
+/**
+ * Gets the rendered output of a renderable element from the cache.
+ *
+ * @param $elements
+ * A renderable array.
+ *
+ * @return
+ * A markup string containing the rendered content of the element, or FALSE
+ * if no cached copy of the element is available.
+ *
+ * @see drupal_render()
+ * @see drupal_render_cache_set()
+ */
+function drupal_render_cache_get($elements) {
+ if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
+ return FALSE;
+ }
+ $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
+
+ if (!empty($cid) && $cache = cache_get($cid, $bin)) {
+ // Add additional libraries, JavaScript, CSS and other data attached
+ // to this element.
+ if (isset($cache->data['#attached'])) {
+ drupal_process_attached($cache->data);
+ }
+ // Return the rendered output.
+ return $cache->data['#markup'];
+ }
+ return FALSE;
+}
+
+/**
+ * Caches the rendered output of a renderable element.
+ *
+ * This is called by drupal_render() if the #cache property is set on an
+ * element.
+ *
+ * @param $markup
+ * The rendered output string of $elements.
+ * @param $elements
+ * A renderable array.
+ *
+ * @see drupal_render_cache_get()
+ */
+function drupal_render_cache_set(&$markup, $elements) {
+ // Create the cache ID for the element.
+ if (!in_array($_SERVER['REQUEST_METHOD'], array('GET', 'HEAD')) || !$cid = drupal_render_cid_create($elements)) {
+ return FALSE;
+ }
+
+ // Cache implementations are allowed to modify the markup, to support
+ // replacing markup with edge-side include commands. The supporting cache
+ // backend will store the markup in some other key (like
+ // $data['#real-value']) and return an include command instead. When the
+ // ESI command is executed by the content accelerator, the real value can
+ // be retrieved and used.
+ $data['#markup'] = &$markup;
+ // Persist attached data associated with this element.
+ $attached = drupal_render_collect_attached($elements, TRUE);
+ if ($attached) {
+ $data['#attached'] = $attached;
+ }
+ $bin = isset($elements['#cache']['bin']) ? $elements['#cache']['bin'] : 'cache';
+ $expire = isset($elements['#cache']['expire']) ? $elements['#cache']['expire'] : CACHE_PERMANENT;
+ cache_set($cid, $data, $bin, $expire);
+}
+
+/**
+ * Collects #attached for an element and its children into a single array.
+ *
+ * When caching elements, it is necessary to collect all libraries, JavaScript
+ * and CSS into a single array, from both the element itself and all child
+ * elements. This allows drupal_render() to add these back to the page when the
+ * element is returned from cache.
+ *
+ * @param $elements
+ * The element to collect #attached from.
+ * @param $return
+ * Whether to return the attached elements and reset the internal static.
+ *
+ * @return
+ * The #attached array for this element and its descendants.
+ */
+function drupal_render_collect_attached($elements, $return = FALSE) {
+ $attached = &drupal_static(__FUNCTION__, array());
+
+ // Collect all #attached for this element.
+ if (isset($elements['#attached'])) {
+ foreach ($elements['#attached'] as $key => $value) {
+ if (!isset($attached[$key])) {
+ $attached[$key] = array();
+ }
+ $attached[$key] = array_merge($attached[$key], $value);
+ }
+ }
+ if ($children = element_children($elements)) {
+ foreach ($children as $child) {
+ drupal_render_collect_attached($elements[$child]);
+ }
+ }
+
+ // If this was the first call to the function, return all attached elements
+ // and reset the static cache.
+ if ($return) {
+ $return = $attached;
+ $attached = array();
+ return $return;
+ }
+}
+
+/**
+ * Prepares an element for caching based on a query.
+ *
+ * This smart caching strategy saves Drupal from querying and rendering to HTML
+ * when the underlying query is unchanged.
+ *
+ * Expensive queries should use the query builder to create the query and then
+ * call this function. Executing the query and formatting results should happen
+ * in a #pre_render callback.
+ *
+ * @param $query
+ * A select query object as returned by db_select().
+ * @param $function
+ * The name of the function doing this caching. A _pre_render suffix will be
+ * added to this string and is also part of the cache key in
+ * drupal_render_cache_set() and drupal_render_cache_get().
+ * @param $expire
+ * The cache expire time, passed eventually to cache_set().
+ * @param $granularity
+ * One or more granularity constants passed to drupal_render_cid_parts().
+ *
+ * @return
+ * A renderable array with the following keys and values:
+ * - #query: The passed-in $query.
+ * - #pre_render: $function with a _pre_render suffix.
+ * - #cache: An associative array prepared for drupal_render_cache_set().
+ */
+function drupal_render_cache_by_query($query, $function, $expire = CACHE_TEMPORARY, $granularity = NULL) {
+ $cache_keys = array_merge(array($function), drupal_render_cid_parts($granularity));
+ $query->preExecute();
+ $cache_keys[] = hash('sha256', serialize(array((string) $query, $query->getArguments())));
+ return array(
+ '#query' => $query,
+ '#pre_render' => array($function . '_pre_render'),
+ '#cache' => array(
+ 'keys' => $cache_keys,
+ 'expire' => $expire,
+ ),
+ );
+}
+
+/**
+ * Returns cache ID parts for building a cache ID.
+ *
+ * @param $granularity
+ * One or more cache granularity constants. For example, to cache separately
+ * for each user, use DRUPAL_CACHE_PER_USER. To cache separately for each
+ * page and role, use the expression:
+ * @code
+ * DRUPAL_CACHE_PER_PAGE | DRUPAL_CACHE_PER_ROLE
+ * @endcode
+ *
+ * @return
+ * An array of cache ID parts, always containing the active theme. If the
+ * locale module is enabled it also contains the active language. If
+ * $granularity was passed in, more parts are added.
+ */
+function drupal_render_cid_parts($granularity = NULL) {
+ global $theme, $base_root, $user;
+
+ $cid_parts[] = $theme;
+ // If Locale is enabled but we have only one language we do not need it as cid
+ // part.
+ if (drupal_multilingual()) {
+ foreach (language_types_configurable() as $language_type) {
+ $cid_parts[] = $GLOBALS[$language_type]->language;
+ }
+ }
+
+ if (!empty($granularity)) {
+ // 'PER_ROLE' and 'PER_USER' are mutually exclusive. 'PER_USER' can be a
+ // resource drag for sites with many users, so when a module is being
+ // equivocal, we favor the less expensive 'PER_ROLE' pattern.
+ if ($granularity & DRUPAL_CACHE_PER_ROLE) {
+ $cid_parts[] = 'r.' . implode(',', array_keys($user->roles));
+ }
+ elseif ($granularity & DRUPAL_CACHE_PER_USER) {
+ $cid_parts[] = "u.$user->uid";
+ }
+
+ if ($granularity & DRUPAL_CACHE_PER_PAGE) {
+ $cid_parts[] = $base_root . request_uri();
+ }
+ }
+
+ return $cid_parts;
+}
+
+/**
+ * Creates the cache ID for a renderable element.
+ *
+ * This creates the cache ID string, either by returning the #cache['cid']
+ * property if present or by building the cache ID out of the #cache['keys']
+ * and, optionally, the #cache['granularity'] properties.
+ *
+ * @param $elements
+ * A renderable array.
+ *
+ * @return
+ * The cache ID string, or FALSE if the element may not be cached.
+ */
+function drupal_render_cid_create($elements) {
+ if (isset($elements['#cache']['cid'])) {
+ return $elements['#cache']['cid'];
+ }
+ elseif (isset($elements['#cache']['keys'])) {
+ $granularity = isset($elements['#cache']['granularity']) ? $elements['#cache']['granularity'] : NULL;
+ // Merge in additional cache ID parts based provided by drupal_render_cid_parts().
+ $cid_parts = array_merge($elements['#cache']['keys'], drupal_render_cid_parts($granularity));
+ return implode(':', $cid_parts);
+ }
+ return FALSE;
+}
+
+/**
+ * Function used by uasort to sort structured arrays by weight.
+ */
+function element_sort($a, $b) {
+ $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
+ $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
+ if ($a_weight == $b_weight) {
+ return 0;
+ }
+ return ($a_weight < $b_weight) ? -1 : 1;
+}
+
+/**
+ * Array sorting callback; sorts elements by title.
+ */
+function element_sort_by_title($a, $b) {
+ $a_title = (is_array($a) && isset($a['#title'])) ? $a['#title'] : '';
+ $b_title = (is_array($b) && isset($b['#title'])) ? $b['#title'] : '';
+ return strnatcasecmp($a_title, $b_title);
+}
+
+/**
+ * Retrieves the default properties for the defined element type.
+ *
+ * @param $type
+ * An element type as defined by hook_element_info().
+ */
+function element_info($type) {
+ // Use the advanced drupal_static() pattern, since this is called very often.
+ static $drupal_static_fast;
+ if (!isset($drupal_static_fast)) {
+ $drupal_static_fast['cache'] = &drupal_static(__FUNCTION__);
+ }
+ $cache = &$drupal_static_fast['cache'];
+
+ if (!isset($cache)) {
+ $cache = module_invoke_all('element_info');
+ foreach ($cache as $element_type => $info) {
+ $cache[$element_type]['#type'] = $element_type;
+ }
+ // Allow modules to alter the element type defaults.
+ drupal_alter('element_info', $cache);
+ }
+
+ return isset($cache[$type]) ? $cache[$type] : array();
+}
+
+/**
+ * Retrieves a single property for the defined element type.
+ *
+ * @param $type
+ * An element type as defined by hook_element_info().
+ * @param $property_name
+ * The property within the element type that should be returned.
+ * @param $default
+ * (Optional) The value to return if the element type does not specify a
+ * value for the property. Defaults to NULL.
+ */
+function element_info_property($type, $property_name, $default = NULL) {
+ return (($info = element_info($type)) && array_key_exists($property_name, $info)) ? $info[$property_name] : $default;
+}
+
+/**
+ * Sorts a structured array by the 'weight' element.
+ *
+ * Note that the sorting is by the 'weight' array element, not by the render
+ * element property '#weight'.
+ *
+ * Callback for uasort() used in various functions.
+ *
+ * @param $a
+ * First item for comparison. The compared items should be associative arrays
+ * that optionally include a 'weight' element. For items without a 'weight'
+ * element, a default value of 0 will be used.
+ * @param $b
+ * Second item for comparison.
+ */
+function drupal_sort_weight($a, $b) {
+ $a_weight = (is_array($a) && isset($a['weight'])) ? $a['weight'] : 0;
+ $b_weight = (is_array($b) && isset($b['weight'])) ? $b['weight'] : 0;
+ if ($a_weight == $b_weight) {
+ return 0;
+ }
+ return ($a_weight < $b_weight) ? -1 : 1;
+}
+
+/**
+ * Array sorting callback; sorts elements by 'title' key.
+ */
+function drupal_sort_title($a, $b) {
+ if (!isset($b['title'])) {
+ return -1;
+ }
+ if (!isset($a['title'])) {
+ return 1;
+ }
+ return strcasecmp($a['title'], $b['title']);
+}
+
+/**
+ * Checks if the key is a property.
+ */
+function element_property($key) {
+ return $key[0] == '#';
+}
+
+/**
+ * Gets properties of a structured array element (keys beginning with '#').
+ */
+function element_properties($element) {
+ return array_filter(array_keys((array) $element), 'element_property');
+}
+
+/**
+ * Checks if the key is a child.
+ */
+function element_child($key) {
+ return !isset($key[0]) || $key[0] != '#';
+}
+
+/**
+ * Identifies the children of an element array, optionally sorted by weight.
+ *
+ * The children of a element array are those key/value pairs whose key does
+ * not start with a '#'. See drupal_render() for details.
+ *
+ * @param $elements
+ * The element array whose children are to be identified.
+ * @param $sort
+ * Boolean to indicate whether the children should be sorted by weight.
+ *
+ * @return
+ * The array keys of the element's children.
+ */
+function element_children(&$elements, $sort = FALSE) {
+ // Do not attempt to sort elements which have already been sorted.
+ $sort = isset($elements['#sorted']) ? !$elements['#sorted'] : $sort;
+
+ // Filter out properties from the element, leaving only children.
+ $children = array();
+ $sortable = FALSE;
+ foreach ($elements as $key => $value) {
+ if ($key === '' || $key[0] !== '#') {
+ $children[$key] = $value;
+ if (is_array($value) && isset($value['#weight'])) {
+ $sortable = TRUE;
+ }
+ }
+ }
+ // Sort the children if necessary.
+ if ($sort && $sortable) {
+ uasort($children, 'element_sort');
+ // Put the sorted children back into $elements in the correct order, to
+ // preserve sorting if the same element is passed through
+ // element_children() twice.
+ foreach ($children as $key => $child) {
+ unset($elements[$key]);
+ $elements[$key] = $child;
+ }
+ $elements['#sorted'] = TRUE;
+ }
+
+ return array_keys($children);
+}
+
+/**
+ * Returns the visible children of an element.
+ *
+ * @param $elements
+ * The parent element.
+ *
+ * @return
+ * The array keys of the element's visible children.
+ */
+function element_get_visible_children(array $elements) {
+ $visible_children = array();
+
+ foreach (element_children($elements) as $key) {
+ $child = $elements[$key];
+
+ // Skip un-accessible children.
+ if (isset($child['#access']) && !$child['#access']) {
+ continue;
+ }
+
+ // Skip value and hidden elements, since they are not rendered.
+ if (isset($child['#type']) && in_array($child['#type'], array('value', 'hidden'))) {
+ continue;
+ }
+
+ $visible_children[$key] = $child;
+ }
+
+ return array_keys($visible_children);
+}
+
+/**
+ * Sets HTML attributes based on element properties.
+ *
+ * @param $element
+ * The renderable element to process.
+ * @param $map
+ * An associative array whose keys are element property names and whose values
+ * are the HTML attribute names to set for corresponding the property; e.g.,
+ * array('#propertyname' => 'attributename'). If both names are identical
+ * except for the leading '#', then an attribute name value is sufficient and
+ * no property name needs to be specified.
+ */
+function element_set_attributes(array &$element, array $map) {
+ foreach ($map as $property => $attribute) {
+ // If the key is numeric, the attribute name needs to be taken over.
+ if (is_int($property)) {
+ $property = '#' . $attribute;
+ }
+ // Do not overwrite already existing attributes.
+ if (isset($element[$property]) && !isset($element['#attributes'][$attribute])) {
+ $element['#attributes'][$attribute] = $element[$property];
+ }
+ }
+}
+
+/**
+ * Recursively computes the difference of arrays with additional index check.
+ *
+ * This is a version of array_diff_assoc() that supports multidimensional
+ * arrays.
+ *
+ * @param array $array1
+ * The array to compare from.
+ * @param array $array2
+ * The array to compare to.
+ *
+ * @return array
+ * Returns an array containing all the values from array1 that are not present
+ * in array2.
+ */
+function drupal_array_diff_assoc_recursive($array1, $array2) {
+ $difference = array();
+
+ foreach ($array1 as $key => $value) {
+ if (is_array($value)) {
+ if (!array_key_exists($key, $array2) || !is_array($array2[$key])) {
+ $difference[$key] = $value;
+ }
+ else {
+ $new_diff = drupal_array_diff_assoc_recursive($value, $array2[$key]);
+ if (!empty($new_diff)) {
+ $difference[$key] = $new_diff;
+ }
+ }
+ }
+ elseif (!array_key_exists($key, $array2) || $array2[$key] !== $value) {
+ $difference[$key] = $value;
+ }
+ }
+
+ return $difference;
+}
+
+/**
+ * Sets a value in a nested array with variable depth.
+ *
+ * This helper function should be used when the depth of the array element you
+ * are changing may vary (that is, the number of parent keys is variable). It
+ * is primarily used for form structures and renderable arrays.
+ *
+ * Example:
+ * @code
+ * // Assume you have a 'signature' element somewhere in a form. It might be:
+ * $form['signature_settings']['signature'] = array(
+ * '#type' => 'text_format',
+ * '#title' => t('Signature'),
+ * );
+ * // Or, it might be further nested:
+ * $form['signature_settings']['user']['signature'] = array(
+ * '#type' => 'text_format',
+ * '#title' => t('Signature'),
+ * );
+ * @endcode
+ *
+ * To deal with the situation, the code needs to figure out the route to the
+ * element, given an array of parents that is either
+ * @code array('signature_settings', 'signature') @endcode in the first case or
+ * @code array('signature_settings', 'user', 'signature') @endcode in the second
+ * case.
+ *
+ * Without this helper function the only way to set the signature element in one
+ * line would be using eval(), which should be avoided:
+ * @code
+ * // Do not do this! Avoid eval().
+ * eval('$form[\'' . implode("']['", $parents) . '\'] = $element;');
+ * @endcode
+ *
+ * Instead, use this helper function:
+ * @code
+ * drupal_array_set_nested_value($form, $parents, $element);
+ * @endcode
+ *
+ * However if the number of array parent keys is static, the value should always
+ * be set directly rather than calling this function. For instance, for the
+ * first example we could just do:
+ * @code
+ * $form['signature_settings']['signature'] = $element;
+ * @endcode
+ *
+ * @param $array
+ * A reference to the array to modify.
+ * @param $parents
+ * An array of parent keys, starting with the outermost key.
+ * @param $value
+ * The value to set.
+ * @param $force
+ * (Optional) If TRUE, the value is forced into the structure even if it
+ * requires the deletion of an already existing non-array parent value. If
+ * FALSE, PHP throws an error if trying to add into a value that is not an
+ * array. Defaults to FALSE.
+ *
+ * @see drupal_array_get_nested_value()
+ */
+function drupal_array_set_nested_value(array &$array, array $parents, $value, $force = FALSE) {
+ $ref = &$array;
+ foreach ($parents as $parent) {
+ // PHP auto-creates container arrays and NULL entries without error if $ref
+ // is NULL, but throws an error if $ref is set, but not an array.
+ if ($force && isset($ref) && !is_array($ref)) {
+ $ref = array();
+ }
+ $ref = &$ref[$parent];
+ }
+ $ref = $value;
+}
+
+/**
+ * Retrieves a value from a nested array with variable depth.
+ *
+ * This helper function should be used when the depth of the array element being
+ * retrieved may vary (that is, the number of parent keys is variable). It is
+ * primarily used for form structures and renderable arrays.
+ *
+ * Without this helper function the only way to get a nested array value with
+ * variable depth in one line would be using eval(), which should be avoided:
+ * @code
+ * // Do not do this! Avoid eval().
+ * // May also throw a PHP notice, if the variable array keys do not exist.
+ * eval('$value = $array[\'' . implode("']['", $parents) . "'];");
+ * @endcode
+ *
+ * Instead, use this helper function:
+ * @code
+ * $value = drupal_array_get_nested_value($form, $parents);
+ * @endcode
+ *
+ * The return value will be NULL, regardless of whether the actual value is NULL
+ * or whether the requested key does not exist. If it is required to know
+ * whether the nested array key actually exists, pass a third argument that is
+ * altered by reference:
+ * @code
+ * $key_exists = NULL;
+ * $value = drupal_array_get_nested_value($form, $parents, $key_exists);
+ * if ($key_exists) {
+ * // ... do something with $value ...
+ * }
+ * @endcode
+ *
+ * However if the number of array parent keys is static, the value should always
+ * be retrieved directly rather than calling this function. For instance:
+ * @code
+ * $value = $form['signature_settings']['signature'];
+ * @endcode
+ *
+ * @param $array
+ * The array from which to get the value.
+ * @param $parents
+ * An array of parent keys of the value, starting with the outermost key.
+ * @param $key_exists
+ * (optional) If given, an already defined variable that is altered by
+ * reference.
+ *
+ * @return
+ * The requested nested value. Possibly NULL if the value is NULL or not all
+ * nested parent keys exist. $key_exists is altered by reference and is a
+ * Boolean that indicates whether all nested parent keys exist (TRUE) or not
+ * (FALSE). This allows to distinguish between the two possibilities when NULL
+ * is returned.
+ *
+ * @see drupal_array_set_nested_value()
+ */
+function &drupal_array_get_nested_value(array &$array, array $parents, &$key_exists = NULL) {
+ $ref = &$array;
+ foreach ($parents as $parent) {
+ if (is_array($ref) && array_key_exists($parent, $ref)) {
+ $ref = &$ref[$parent];
+ }
+ else {
+ $key_exists = FALSE;
+ $null = NULL;
+ return $null;
+ }
+ }
+ $key_exists = TRUE;
+ return $ref;
+}
+
+/**
+ * Determines whether a nested array contains the requested keys.
+ *
+ * This helper function should be used when the depth of the array element to be
+ * checked may vary (that is, the number of parent keys is variable). See
+ * drupal_array_set_nested_value() for details. It is primarily used for form
+ * structures and renderable arrays.
+ *
+ * If it is required to also get the value of the checked nested key, use
+ * drupal_array_get_nested_value() instead.
+ *
+ * If the number of array parent keys is static, this helper function is
+ * unnecessary and the following code can be used instead:
+ * @code
+ * $value_exists = isset($form['signature_settings']['signature']);
+ * $key_exists = array_key_exists('signature', $form['signature_settings']);
+ * @endcode
+ *
+ * @param $array
+ * The array with the value to check for.
+ * @param $parents
+ * An array of parent keys of the value, starting with the outermost key.
+ *
+ * @return
+ * TRUE if all the parent keys exist, FALSE otherwise.
+ *
+ * @see drupal_array_get_nested_value()
+ */
+function drupal_array_nested_key_exists(array $array, array $parents) {
+ // Although this function is similar to PHP's array_key_exists(), its
+ // arguments should be consistent with drupal_array_get_nested_value().
+ $key_exists = NULL;
+ drupal_array_get_nested_value($array, $parents, $key_exists);
+ return $key_exists;
+}
+
+/**
+ * Provides theme registration for themes across .inc files.
+ */
+function drupal_common_theme() {
+ return array(
+ // From theme.inc.
+ 'html' => array(
+ 'render element' => 'page',
+ 'template' => 'html',
+ ),
+ 'page' => array(
+ 'render element' => 'page',
+ 'template' => 'page',
+ ),
+ 'region' => array(
+ 'render element' => 'elements',
+ 'template' => 'region',
+ ),
+ 'status_messages' => array(
+ 'variables' => array('display' => NULL),
+ ),
+ 'link' => array(
+ 'variables' => array('text' => NULL, 'path' => NULL, 'options' => array()),
+ ),
+ 'links' => array(
+ 'variables' => array('links' => NULL, 'attributes' => array('class' => array('links')), 'heading' => array()),
+ ),
+ 'image' => array(
+ // HTML 4 and XHTML 1.0 always require an alt attribute. The HTML 5 draft
+ // allows the alt attribute to be omitted in some cases. Therefore,
+ // default the alt attribute to an empty string, but allow code calling
+ // theme('image') to pass explicit NULL for it to be omitted. Usually,
+ // neither omission nor an empty string satisfies accessibility
+ // requirements, so it is strongly encouraged for code calling
+ // theme('image') to pass a meaningful value for the alt variable.
+ // - http://www.w3.org/TR/REC-html40/struct/objects.html#h-13.8
+ // - http://www.w3.org/TR/xhtml1/dtds.html
+ // - http://dev.w3.org/html5/spec/Overview.html#alt
+ // The title attribute is optional in all cases, so it is omitted by
+ // default.
+ 'variables' => array('path' => NULL, 'width' => NULL, 'height' => NULL, 'alt' => '', 'title' => NULL, 'attributes' => array()),
+ ),
+ 'breadcrumb' => array(
+ 'variables' => array('breadcrumb' => NULL),
+ ),
+ 'help' => array(
+ 'variables' => array(),
+ ),
+ 'table' => array(
+ 'variables' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL, 'colgroups' => array(), 'sticky' => TRUE, 'empty' => ''),
+ ),
+ 'tablesort_indicator' => array(
+ 'variables' => array('style' => NULL),
+ ),
+ 'mark' => array(
+ 'variables' => array('type' => MARK_NEW),
+ ),
+ 'item_list' => array(
+ 'variables' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => array()),
+ ),
+ 'more_help_link' => array(
+ 'variables' => array('url' => NULL),
+ ),
+ 'feed_icon' => array(
+ 'variables' => array('url' => NULL, 'title' => NULL),
+ ),
+ 'more_link' => array(
+ 'variables' => array('url' => NULL, 'title' => NULL)
+ ),
+ 'username' => array(
+ 'variables' => array('account' => NULL),
+ ),
+ 'progress_bar' => array(
+ 'variables' => array('percent' => NULL, 'message' => NULL),
+ ),
+ 'indentation' => array(
+ 'variables' => array('size' => 1),
+ ),
+ 'html_tag' => array(
+ 'render element' => 'element',
+ ),
+ // From theme.maintenance.inc.
+ 'maintenance_page' => array(
+ 'variables' => array('content' => NULL, 'show_messages' => TRUE),
+ 'template' => 'maintenance-page',
+ ),
+ 'update_page' => array(
+ 'variables' => array('content' => NULL, 'show_messages' => TRUE),
+ ),
+ 'install_page' => array(
+ 'variables' => array('content' => NULL),
+ ),
+ 'task_list' => array(
+ 'variables' => array('items' => NULL, 'active' => NULL),
+ ),
+ 'authorize_message' => array(
+ 'variables' => array('message' => NULL, 'success' => TRUE),
+ ),
+ 'authorize_report' => array(
+ 'variables' => array('messages' => array()),
+ ),
+ // From pager.inc.
+ 'pager' => array(
+ 'variables' => array('tags' => array(), 'element' => 0, 'parameters' => array(), 'quantity' => 9),
+ ),
+ 'pager_first' => array(
+ 'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
+ ),
+ 'pager_previous' => array(
+ 'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
+ ),
+ 'pager_next' => array(
+ 'variables' => array('text' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
+ ),
+ 'pager_last' => array(
+ 'variables' => array('text' => NULL, 'element' => 0, 'parameters' => array()),
+ ),
+ 'pager_link' => array(
+ 'variables' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
+ ),
+ // From menu.inc.
+ 'menu_link' => array(
+ 'render element' => 'element',
+ ),
+ 'menu_tree' => array(
+ 'render element' => 'tree',
+ ),
+ 'menu_local_task' => array(
+ 'render element' => 'element',
+ ),
+ 'menu_local_action' => array(
+ 'render element' => 'element',
+ ),
+ 'menu_local_tasks' => array(
+ 'variables' => array('primary' => array(), 'secondary' => array()),
+ ),
+ // From form.inc.
+ 'select' => array(
+ 'render element' => 'element',
+ ),
+ 'fieldset' => array(
+ 'render element' => 'element',
+ ),
+ 'radio' => array(
+ 'render element' => 'element',
+ ),
+ 'radios' => array(
+ 'render element' => 'element',
+ ),
+ 'date' => array(
+ 'render element' => 'element',
+ ),
+ 'exposed_filters' => array(
+ 'render element' => 'form',
+ ),
+ 'checkbox' => array(
+ 'render element' => 'element',
+ ),
+ 'checkboxes' => array(
+ 'render element' => 'element',
+ ),
+ 'button' => array(
+ 'render element' => 'element',
+ ),
+ 'image_button' => array(
+ 'render element' => 'element',
+ ),
+ 'hidden' => array(
+ 'render element' => 'element',
+ ),
+ 'textfield' => array(
+ 'render element' => 'element',
+ ),
+ 'form' => array(
+ 'render element' => 'element',
+ ),
+ 'textarea' => array(
+ 'render element' => 'element',
+ ),
+ 'password' => array(
+ 'render element' => 'element',
+ ),
+ 'file' => array(
+ 'render element' => 'element',
+ ),
+ 'tableselect' => array(
+ 'render element' => 'element',
+ ),
+ 'form_element' => array(
+ 'render element' => 'element',
+ ),
+ 'form_required_marker' => array(
+ 'render element' => 'element',
+ ),
+ 'form_element_label' => array(
+ 'render element' => 'element',
+ ),
+ 'vertical_tabs' => array(
+ 'render element' => 'element',
+ ),
+ 'container' => array(
+ 'render element' => 'element',
+ ),
+ );
+}
+
+/**
+ * @addtogroup schemaapi
+ * @{
+ */
+
+/**
+ * Creates all tables defined in a module's hook_schema().
+ *
+ * Note: This function does not pass the module's schema through
+ * hook_schema_alter(). The module's tables will be created exactly as the
+ * module defines them.
+ *
+ * @param $module
+ * The module for which the tables will be created.
+ */
+function drupal_install_schema($module) {
+ $schema = drupal_get_schema_unprocessed($module);
+ _drupal_schema_initialize($schema, $module, FALSE);
+
+ foreach ($schema as $name => $table) {
+ db_create_table($name, $table);
+ }
+}
+
+/**
+ * Removes all tables defined in a module's hook_schema().
+ *
+ * Note: This function does not pass the module's schema through
+ * hook_schema_alter(). The module's tables will be created exactly as the
+ * module defines them.
+ *
+ * @param $module
+ * The module for which the tables will be removed.
+ *
+ * @return
+ * An array of arrays with the following key/value pairs:
+ * - success: a boolean indicating whether the query succeeded.
+ * - query: the SQL query(s) executed, passed through check_plain().
+ */
+function drupal_uninstall_schema($module) {
+ $schema = drupal_get_schema_unprocessed($module);
+ _drupal_schema_initialize($schema, $module, FALSE);
+
+ foreach ($schema as $table) {
+ if (db_table_exists($table['name'])) {
+ db_drop_table($table['name']);
+ }
+ }
+}
+
+/**
+ * Returns the unprocessed and unaltered version of a module's schema.
+ *
+ * Use this function only if you explicitly need the original
+ * specification of a schema, as it was defined in a module's
+ * hook_schema(). No additional default values will be set,
+ * hook_schema_alter() is not invoked and these unprocessed
+ * definitions won't be cached.
+ *
+ * This function can be used to retrieve a schema specification in
+ * hook_schema(), so it allows you to derive your tables from existing
+ * specifications.
+ *
+ * It is also used by drupal_install_schema() and
+ * drupal_uninstall_schema() to ensure that a module's tables are
+ * created exactly as specified without any changes introduced by a
+ * module that implements hook_schema_alter().
+ *
+ * @param $module
+ * The module to which the table belongs.
+ * @param $table
+ * The name of the table. If not given, the module's complete schema
+ * is returned.
+ */
+function drupal_get_schema_unprocessed($module, $table = NULL) {
+ // Load the .install file to get hook_schema.
+ module_load_install($module);
+ $schema = module_invoke($module, 'schema');
+
+ if (isset($table) && isset($schema[$table])) {
+ return $schema[$table];
+ }
+ elseif (!empty($schema)) {
+ return $schema;
+ }
+ return array();
+}
+
+/**
+ * Fills in required default values for table definitions from hook_schema().
+ *
+ * @param $schema
+ * The schema definition array as it was returned by the module's
+ * hook_schema().
+ * @param $module
+ * The module for which hook_schema() was invoked.
+ * @param $remove_descriptions
+ * (optional) Whether to additionally remove 'description' keys of all tables
+ * and fields to improve performance of serialize() and unserialize().
+ * Defaults to TRUE.
+ */
+function _drupal_schema_initialize(&$schema, $module, $remove_descriptions = TRUE) {
+ // Set the name and module key for all tables.
+ foreach ($schema as $name => &$table) {
+ if (empty($table['module'])) {
+ $table['module'] = $module;
+ }
+ if (!isset($table['name'])) {
+ $table['name'] = $name;
+ }
+ if ($remove_descriptions) {
+ unset($table['description']);
+ foreach ($table['fields'] as &$field) {
+ unset($field['description']);
+ }
+ }
+ }
+}
+
+/**
+ * Retrieves a list of fields from a table schema.
+ *
+ * The returned list is suitable for use in an SQL query.
+ *
+ * @param $table
+ * The name of the table from which to retrieve fields.
+ * @param
+ * An optional prefix to to all fields.
+ *
+ * @return An array of fields.
+ */
+function drupal_schema_fields_sql($table, $prefix = NULL) {
+ $schema = drupal_get_schema($table);
+ $fields = array_keys($schema['fields']);
+ if ($prefix) {
+ $columns = array();
+ foreach ($fields as $field) {
+ $columns[] = "$prefix.$field";
+ }
+ return $columns;
+ }
+ else {
+ return $fields;
+ }
+}
+
+/**
+ * Saves (inserts or updates) a record to the database based upon the schema.
+ *
+ * Do not use drupal_write_record() within hook_update_N() functions, since the
+ * database schema cannot be relied upon when a user is running a series of
+ * updates. Instead, use db_insert() or db_update() to save the record.
+ *
+ * @param $table
+ * The name of the table; this must be defined by a hook_schema()
+ * implementation.
+ * @param $record
+ * An object or array representing the record to write, passed in by
+ * reference. If inserting a new record, values not provided in $record will
+ * be populated in $record and in the database with the default values from
+ * the schema, as well as a single serial (auto-increment) field (if present).
+ * If updating an existing record, only provided values are updated in the
+ * database, and $record is not modified.
+ * @param $primary_keys
+ * To indicate that this is a new record to be inserted, omit this argument.
+ * If this is an update, this argument specifies the primary keys' field
+ * names. If there is only 1 field in the key, you may pass in a string; if
+ * there are multiple fields in the key, pass in an array.
+ *
+ * @return
+ * If the record insert or update failed, returns FALSE. If it succeeded,
+ * returns SAVED_NEW or SAVED_UPDATED, depending on the operation performed.
+ */
+function drupal_write_record($table, &$record, $primary_keys = array()) {
+ // Standardize $primary_keys to an array.
+ if (is_string($primary_keys)) {
+ $primary_keys = array($primary_keys);
+ }
+
+ $schema = drupal_get_schema($table);
+ if (empty($schema)) {
+ return FALSE;
+ }
+
+ $object = (object) $record;
+ $fields = array();
+
+ // Go through the schema to determine fields to write.
+ foreach ($schema['fields'] as $field => $info) {
+ if ($info['type'] == 'serial') {
+ // Skip serial types if we are updating.
+ if (!empty($primary_keys)) {
+ continue;
+ }
+ // Track serial field so we can helpfully populate them after the query.
+ // NOTE: Each table should come with one serial field only.
+ $serial = $field;
+ }
+
+ // Skip field if it is in $primary_keys as it is unnecessary to update a
+ // field to the value it is already set to.
+ if (in_array($field, $primary_keys)) {
+ continue;
+ }
+
+ if (!property_exists($object, $field)) {
+ // Skip fields that are not provided, default values are already known
+ // by the database.
+ continue;
+ }
+
+ // Build array of fields to update or insert.
+ if (empty($info['serialize'])) {
+ $fields[$field] = $object->$field;
+ }
+ else {
+ $fields[$field] = serialize($object->$field);
+ }
+
+ // Type cast to proper datatype, except when the value is NULL and the
+ // column allows this.
+ //
+ // MySQL PDO silently casts e.g. FALSE and '' to 0 when inserting the value
+ // into an integer column, but PostgreSQL PDO does not. Also type cast NULL
+ // when the column does not allow this.
+ if (isset($object->$field) || !empty($info['not null'])) {
+ if ($info['type'] == 'int' || $info['type'] == 'serial') {
+ $fields[$field] = (int) $fields[$field];
+ }
+ elseif ($info['type'] == 'float') {
+ $fields[$field] = (float) $fields[$field];
+ }
+ else {
+ $fields[$field] = (string) $fields[$field];
+ }
+ }
+ }
+
+ if (empty($fields)) {
+ return;
+ }
+
+ // Build the SQL.
+ if (empty($primary_keys)) {
+ // We are doing an insert.
+ $options = array('return' => Database::RETURN_INSERT_ID);
+ if (isset($serial) && isset($fields[$serial])) {
+ // If the serial column has been explicitly set with an ID, then we don't
+ // require the database to return the last insert id.
+ if ($fields[$serial]) {
+ $options['return'] = Database::RETURN_AFFECTED;
+ }
+ // If a serial column does exist with no value (i.e. 0) then remove it as
+ // the database will insert the correct value for us.
+ else {
+ unset($fields[$serial]);
+ }
+ }
+ $query = db_insert($table, $options)->fields($fields);
+ $return = SAVED_NEW;
+ }
+ else {
+ $query = db_update($table)->fields($fields);
+ foreach ($primary_keys as $key) {
+ $query->condition($key, $object->$key);
+ }
+ $return = SAVED_UPDATED;
+ }
+
+ // Execute the SQL.
+ if ($query_return = $query->execute()) {
+ if (isset($serial)) {
+ // If the database was not told to return the last insert id, it will be
+ // because we already know it.
+ if (isset($options) && $options['return'] != Database::RETURN_INSERT_ID) {
+ $object->$serial = $fields[$serial];
+ }
+ else {
+ $object->$serial = $query_return;
+ }
+ }
+ }
+ // If we have a single-field primary key but got no insert ID, the
+ // query failed. Note that we explicitly check for FALSE, because
+ // a valid update query which doesn't change any values will return
+ // zero (0) affected rows.
+ elseif ($query_return === FALSE && count($primary_keys) == 1) {
+ $return = FALSE;
+ }
+
+ // If we are inserting, populate empty fields with default values.
+ if (empty($primary_keys)) {
+ foreach ($schema['fields'] as $field => $info) {
+ if (isset($info['default']) && !property_exists($object, $field)) {
+ $object->$field = $info['default'];
+ }
+ }
+ }
+
+ // If we began with an array, convert back.
+ if (is_array($record)) {
+ $record = (array) $object;
+ }
+
+ return $return;
+}
+
+/**
+ * @} End of "addtogroup schemaapi".
+ */
+
+/**
+ * Parses Drupal module and theme .info files.
+ *
+ * Info files are NOT for placing arbitrary theme and module-specific settings.
+ * Use variable_get() and variable_set() for that.
+ *
+ * Information stored in a module .info file:
+ * - name: The real name of the module for display purposes.
+ * - description: A brief description of the module.
+ * - dependencies: An array of shortnames of other modules this module requires.
+ * - package: The name of the package of modules this module belongs to.
+ *
+ * See forum.info for an example of a module .info file.
+ *
+ * Information stored in a theme .info file:
+ * - name: The real name of the theme for display purposes.
+ * - description: Brief description.
+ * - screenshot: Path to screenshot relative to the theme's .info file.
+ * - engine: Theme engine; typically phptemplate.
+ * - base: Name of a base theme, if applicable; e.g., base = zen.
+ * - regions: Listed regions; e.g., region[left] = Left sidebar.
+ * - features: Features available; e.g., features[] = logo.
+ * - stylesheets: Theme stylesheets; e.g., stylesheets[all][] = my-style.css.
+ * - scripts: Theme scripts; e.g., scripts[] = my-script.js.
+ *
+ * See bartik.info for an example of a theme .info file.
+ *
+ * @param $filename
+ * The file we are parsing. Accepts file with relative or absolute path.
+ *
+ * @return
+ * The info array.
+ *
+ * @see drupal_parse_info_format()
+ */
+function drupal_parse_info_file($filename) {
+ $info = &drupal_static(__FUNCTION__, array());
+
+ if (!isset($info[$filename])) {
+ if (!file_exists($filename)) {
+ $info[$filename] = array();
+ }
+ else {
+ $data = file_get_contents($filename);
+ $info[$filename] = drupal_parse_info_format($data);
+ }
+ }
+ return $info[$filename];
+}
+
+/**
+ * Parses data in Drupal's .info format.
+ *
+ * Data should be in an .ini-like format to specify values. White-space
+ * generally doesn't matter, except inside values:
+ * @code
+ * key = value
+ * key = "value"
+ * key = 'value'
+ * key = "multi-line
+ * value"
+ * key = 'multi-line
+ * value'
+ * key
+ * =
+ * 'value'
+ * @endcode
+ *
+ * Arrays are created using a HTTP GET alike syntax:
+ * @code
+ * key[] = "numeric array"
+ * key[index] = "associative array"
+ * key[index][] = "nested numeric array"
+ * key[index][index] = "nested associative array"
+ * @endcode
+ *
+ * PHP constants are substituted in, but only when used as the entire value.
+ * Comments should start with a semi-colon at the beginning of a line.
+ *
+ * @param $data
+ * A string to parse.
+ *
+ * @return
+ * The info array.
+ *
+ * @see drupal_parse_info_file()
+ */
+function drupal_parse_info_format($data) {
+ $info = array();
+ $constants = get_defined_constants();
+
+ if (preg_match_all('
+ @^\s* # Start at the beginning of a line, ignoring leading whitespace
+ ((?:
+ [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
+ \[[^\[\]]*\] # unless they are balanced and not nested
+ )+?)
+ \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
+ (?:
+ ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
+ (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
+ ([^\r\n]*?) # Non-quoted string
+ )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
+ @msx', $data, $matches, PREG_SET_ORDER)) {
+ foreach ($matches as $match) {
+ // Fetch the key and value string.
+ $i = 0;
+ foreach (array('key', 'value1', 'value2', 'value3') as $var) {
+ $$var = isset($match[++$i]) ? $match[$i] : '';
+ }
+ $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
+
+ // Parse array syntax.
+ $keys = preg_split('/\]?\[/', rtrim($key, ']'));
+ $last = array_pop($keys);
+ $parent = &$info;
+
+ // Create nested arrays.
+ foreach ($keys as $key) {
+ if ($key == '') {
+ $key = count($parent);
+ }
+ if (!isset($parent[$key]) || !is_array($parent[$key])) {
+ $parent[$key] = array();
+ }
+ $parent = &$parent[$key];
+ }
+
+ // Handle PHP constants.
+ if (isset($constants[$value])) {
+ $value = $constants[$value];
+ }
+
+ // Insert actual value.
+ if ($last == '') {
+ $last = count($parent);
+ }
+ $parent[$last] = $value;
+ }
+ }
+
+ return $info;
+}
+
+/**
+ * Returns a list of severity levels, as defined in RFC 3164.
+ *
+ * @return
+ * Array of the possible severity levels for log messages.
+ *
+ * @see http://www.ietf.org/rfc/rfc3164.txt
+ * @see watchdog()
+ * @ingroup logging_severity_levels
+ */
+function watchdog_severity_levels() {
+ return array(
+ WATCHDOG_EMERGENCY => t('emergency'),
+ WATCHDOG_ALERT => t('alert'),
+ WATCHDOG_CRITICAL => t('critical'),
+ WATCHDOG_ERROR => t('error'),
+ WATCHDOG_WARNING => t('warning'),
+ WATCHDOG_NOTICE => t('notice'),
+ WATCHDOG_INFO => t('info'),
+ WATCHDOG_DEBUG => t('debug'),
+ );
+}
+
+
+/**
+ * Explodes a string of tags into an array.
+ *
+ * @see drupal_implode_tags()
+ */
+function drupal_explode_tags($tags) {
+ // This regexp allows the following types of user input:
+ // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
+ $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
+ preg_match_all($regexp, $tags, $matches);
+ $typed_tags = array_unique($matches[1]);
+
+ $tags = array();
+ foreach ($typed_tags as $tag) {
+ // If a user has escaped a term (to demonstrate that it is a group,
+ // or includes a comma or quote character), we remove the escape
+ // formatting so to save the term into the database as the user intends.
+ $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
+ if ($tag != "") {
+ $tags[] = $tag;
+ }
+ }
+
+ return $tags;
+}
+
+/**
+ * Implodes an array of tags into a string.
+ *
+ * @see drupal_explode_tags()
+ */
+function drupal_implode_tags($tags) {
+ $encoded_tags = array();
+ foreach ($tags as $tag) {
+ // Commas and quotes in tag names are special cases, so encode them.
+ if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
+ $tag = '"' . str_replace('"', '""', $tag) . '"';
+ }
+
+ $encoded_tags[] = $tag;
+ }
+ return implode(', ', $encoded_tags);
+}
+
+/**
+ * Flushes all cached data on the site.
+ *
+ * Empties cache tables, rebuilds the menu cache and theme registries, and
+ * invokes a hook so that other modules' cache data can be cleared as well.
+ */
+function drupal_flush_all_caches() {
+ // Change query-strings on css/js files to enforce reload for all users.
+ _drupal_flush_css_js();
+
+ registry_rebuild();
+ drupal_clear_css_cache();
+ drupal_clear_js_cache();
+
+ // Rebuild the theme data. Note that the module data is rebuilt above, as
+ // part of registry_rebuild().
+ system_rebuild_theme_data();
+ drupal_theme_rebuild();
+
+ entity_info_cache_clear();
+ node_types_rebuild();
+ // node_menu() defines menu items based on node types so it needs to come
+ // after node types are rebuilt.
+ menu_rebuild();
+
+ // Synchronize to catch any actions that were added or removed.
+ actions_synchronize();
+
+ // Don't clear cache_form - in-progress form submissions may break.
+ // Ordered so clearing the page cache will always be the last action.
+ $core = array('cache', 'cache_path', 'cache_filter', 'cache_bootstrap', 'cache_page');
+ $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
+ foreach ($cache_tables as $table) {
+ cache_clear_all('*', $table, TRUE);
+ }
+
+ // Rebuild the bootstrap module list. We do this here so that developers
+ // can get new hook_boot() implementations registered without having to
+ // write a hook_update_N() function.
+ _system_update_bootstrap_status();
+}
+
+/**
+ * Changes the dummy query string added to all CSS and JavaScript files.
+ *
+ * Changing the dummy query string appended to CSS and JavaScript files forces
+ * all browsers to reload fresh files.
+ */
+function _drupal_flush_css_js() {
+ // The timestamp is converted to base 36 in order to make it more compact.
+ variable_set('css_js_query_string', base_convert(REQUEST_TIME, 10, 36));
+}
+
+/**
+ * Outputs debug information.
+ *
+ * The debug information is passed on to trigger_error() after being converted
+ * to a string using _drupal_debug_message().
+ *
+ * @param $data
+ * Data to be output.
+ * @param $label
+ * Label to prefix the data.
+ * @param $print_r
+ * Flag to switch between print_r() and var_export() for data conversion to
+ * string. Set $print_r to TRUE when dealing with a recursive data structure
+ * as var_export() will generate an error.
+ */
+function debug($data, $label = NULL, $print_r = FALSE) {
+ // Print $data contents to string.
+ $string = check_plain($print_r ? print_r($data, TRUE) : var_export($data, TRUE));
+
+ // Display values with pre-formatting to increase readability.
+ $string = '<pre>' . $string . '</pre>';
+
+ trigger_error(trim($label ? "$label: $string" : $string));
+}
+
+/**
+ * Parses a dependency for comparison by drupal_check_incompatibility().
+ *
+ * @param $dependency
+ * A dependency string, for example 'foo (>=7.x-4.5-beta5, 3.x)'.
+ *
+ * @return
+ * An associative array with three keys:
+ * - 'name' includes the name of the thing to depend on (e.g. 'foo').
+ * - 'original_version' contains the original version string (which can be
+ * used in the UI for reporting incompatibilities).
+ * - 'versions' is a list of associative arrays, each containing the keys
+ * 'op' and 'version'. 'op' can be one of: '=', '==', '!=', '<>', '<',
+ * '<=', '>', or '>='. 'version' is one piece like '4.5-beta3'.
+ * Callers should pass this structure to drupal_check_incompatibility().
+ *
+ * @see drupal_check_incompatibility()
+ */
+function drupal_parse_dependency($dependency) {
+ // We use named subpatterns and support every op that version_compare
+ // supports. Also, op is optional and defaults to equals.
+ $p_op = '(?P<operation>!=|==|=|<|<=|>|>=|<>)?';
+ // Core version is always optional: 7.x-2.x and 2.x is treated the same.
+ $p_core = '(?:' . preg_quote(DRUPAL_CORE_COMPATIBILITY) . '-)?';
+ $p_major = '(?P<major>\d+)';
+ // By setting the minor version to x, branches can be matched.
+ $p_minor = '(?P<minor>(?:\d+|x)(?:-[A-Za-z]+\d+)?)';
+ $value = array();
+ $parts = explode('(', $dependency, 2);
+ $value['name'] = trim($parts[0]);
+ if (isset($parts[1])) {
+ $value['original_version'] = ' (' . $parts[1];
+ foreach (explode(',', $parts[1]) as $version) {
+ if (preg_match("/^\s*$p_op\s*$p_core$p_major\.$p_minor/", $version, $matches)) {
+ $op = !empty($matches['operation']) ? $matches['operation'] : '=';
+ if ($matches['minor'] == 'x') {
+ // Drupal considers "2.x" to mean any version that begins with
+ // "2" (e.g. 2.0, 2.9 are all "2.x"). PHP's version_compare(),
+ // on the other hand, treats "x" as a string; so to
+ // version_compare(), "2.x" is considered less than 2.0. This
+ // means that >=2.x and <2.x are handled by version_compare()
+ // as we need, but > and <= are not.
+ if ($op == '>' || $op == '<=') {
+ $matches['major']++;
+ }
+ // Equivalence can be checked by adding two restrictions.
+ if ($op == '=' || $op == '==') {
+ $value['versions'][] = array('op' => '<', 'version' => ($matches['major'] + 1) . '.x');
+ $op = '>=';
+ }
+ }
+ $value['versions'][] = array('op' => $op, 'version' => $matches['major'] . '.' . $matches['minor']);
+ }
+ }
+ }
+ return $value;
+}
+
+/**
+ * Checks whether a version is compatible with a given dependency.
+ *
+ * @param $v
+ * The parsed dependency structure from drupal_parse_dependency().
+ * @param $current_version
+ * The version to check against (like 4.2).
+ *
+ * @return
+ * NULL if compatible, otherwise the original dependency version string that
+ * caused the incompatibility.
+ *
+ * @see drupal_parse_dependency()
+ */
+function drupal_check_incompatibility($v, $current_version) {
+ if (!empty($v['versions'])) {
+ foreach ($v['versions'] as $required_version) {
+ if ((isset($required_version['op']) && !version_compare($current_version, $required_version['version'], $required_version['op']))) {
+ return $v['original_version'];
+ }
+ }
+ }
+}
+
+/**
+ * Get the entity info array of an entity type.
+ *
+ * @param $entity_type
+ * The entity type, e.g. node, for which the info shall be returned, or NULL
+ * to return an array with info about all types.
+ *
+ * @see hook_entity_info()
+ * @see hook_entity_info_alter()
+ */
+function entity_get_info($entity_type = NULL) {
+ global $language;
+
+ // Use the advanced drupal_static() pattern, since this is called very often.
+ static $drupal_static_fast;
+ if (!isset($drupal_static_fast)) {
+ $drupal_static_fast['entity_info'] = &drupal_static(__FUNCTION__);
+ }
+ $entity_info = &$drupal_static_fast['entity_info'];
+
+ // hook_entity_info() includes translated strings, so each language is cached
+ // separately.
+ $langcode = $language->language;
+
+ if (empty($entity_info)) {
+ if ($cache = cache_get("entity_info:$langcode")) {
+ $entity_info = $cache->data;
+ }
+ else {
+ $entity_info = module_invoke_all('entity_info');
+ // Merge in default values.
+ foreach ($entity_info as $name => $data) {
+ $entity_info[$name] += array(
+ 'fieldable' => FALSE,
+ 'controller class' => 'DrupalDefaultEntityController',
+ 'static cache' => TRUE,
+ 'field cache' => TRUE,
+ 'load hook' => $name . '_load',
+ 'bundles' => array(),
+ 'view modes' => array(),
+ 'entity keys' => array(),
+ 'translation' => array(),
+ );
+ $entity_info[$name]['entity keys'] += array(
+ 'revision' => '',
+ 'bundle' => '',
+ );
+ foreach ($entity_info[$name]['view modes'] as $view_mode => $view_mode_info) {
+ $entity_info[$name]['view modes'][$view_mode] += array(
+ 'custom settings' => FALSE,
+ );
+ }
+ // If no bundle key is provided, assume a single bundle, named after
+ // the entity type.
+ if (empty($entity_info[$name]['entity keys']['bundle']) && empty($entity_info[$name]['bundles'])) {
+ $entity_info[$name]['bundles'] = array($name => array('label' => $entity_info[$name]['label']));
+ }
+ // Prepare entity schema fields SQL info for
+ // DrupalEntityControllerInterface::buildQuery().
+ if (isset($entity_info[$name]['base table'])) {
+ $entity_info[$name]['schema_fields_sql']['base table'] = drupal_schema_fields_sql($entity_info[$name]['base table']);
+ if (isset($entity_info[$name]['revision table'])) {
+ $entity_info[$name]['schema_fields_sql']['revision table'] = drupal_schema_fields_sql($entity_info[$name]['revision table']);
+ }
+ }
+ }
+ // Let other modules alter the entity info.
+ drupal_alter('entity_info', $entity_info);
+ cache_set("entity_info:$langcode", $entity_info);
+ }
+ }
+
+ if (empty($entity_type)) {
+ return $entity_info;
+ }
+ elseif (isset($entity_info[$entity_type])) {
+ return $entity_info[$entity_type];
+ }
+}
+
+/**
+ * Resets the cached information about entity types.
+ */
+function entity_info_cache_clear() {
+ drupal_static_reset('entity_get_info');
+ // Clear all languages.
+ cache_clear_all('entity_info:', 'cache', TRUE);
+}
+
+/**
+ * Helper function to extract id, vid, and bundle name from an entity.
+ *
+ * @param $entity_type
+ * The entity type; e.g. 'node' or 'user'.
+ * @param $entity
+ * The entity from which to extract values.
+ *
+ * @return
+ * A numerically indexed array (not a hash table) containing these
+ * elements:
+ * - 0: Primary ID of the entity.
+ * - 1: Revision ID of the entity, or NULL if $entity_type is not versioned.
+ * - 2: Bundle name of the entity, or NULL if $entity_type has no bundles.
+ */
+function entity_extract_ids($entity_type, $entity) {
+ $info = entity_get_info($entity_type);
+
+ // Objects being created might not have id/vid yet.
+ $id = isset($entity->{$info['entity keys']['id']}) ? $entity->{$info['entity keys']['id']} : NULL;
+ $vid = ($info['entity keys']['revision'] && isset($entity->{$info['entity keys']['revision']})) ? $entity->{$info['entity keys']['revision']} : NULL;
+
+ if (!empty($info['entity keys']['bundle'])) {
+ // Explicitly fail for malformed entities missing the bundle property.
+ if (!isset($entity->{$info['entity keys']['bundle']}) || $entity->{$info['entity keys']['bundle']} === '') {
+ throw new EntityMalformedException(t('Missing bundle property on entity of type @entity_type.', array('@entity_type' => $entity_type)));
+ }
+ $bundle = $entity->{$info['entity keys']['bundle']};
+ }
+ else {
+ // The entity type provides no bundle key: assume a single bundle, named
+ // after the entity type.
+ $bundle = $entity_type;
+ }
+
+ return array($id, $vid, $bundle);
+}
+
+/**
+ * Helper function to assemble an object structure with initial ids.
+ *
+ * This function can be seen as reciprocal to entity_extract_ids().
+ *
+ * @param $entity_type
+ * The entity type; e.g. 'node' or 'user'.
+ * @param $ids
+ * A numerically indexed array, as returned by entity_extract_ids().
+ *
+ * @return
+ * An entity structure, initialized with the ids provided.
+ *
+ * @see entity_extract_ids()
+ */
+function entity_create_stub_entity($entity_type, $ids) {
+ $entity = new stdClass();
+ $info = entity_get_info($entity_type);
+ $entity->{$info['entity keys']['id']} = $ids[0];
+ if (!empty($info['entity keys']['revision']) && isset($ids[1])) {
+ $entity->{$info['entity keys']['revision']} = $ids[1];
+ }
+ if (!empty($info['entity keys']['bundle']) && isset($ids[2])) {
+ $entity->{$info['entity keys']['bundle']} = $ids[2];
+ }
+ return $entity;
+}
+
+/**
+ * Load entities from the database.
+ *
+ * The entities are stored in a static memory cache, and will not require
+ * database access if loaded again during the same page request.
+ *
+ * The actual loading is done through a class that has to implement the
+ * DrupalEntityControllerInterface interface. By default,
+ * DrupalDefaultEntityController is used. Entity types can specify that a
+ * different class should be used by setting the 'controller class' key in
+ * hook_entity_info(). These classes can either implement the
+ * DrupalEntityControllerInterface interface, or, most commonly, extend the
+ * DrupalDefaultEntityController class. See node_entity_info() and the
+ * NodeController in node.module as an example.
+ *
+ * @param $entity_type
+ * The entity type to load, e.g. node or user.
+ * @param $ids
+ * An array of entity IDs, or FALSE to load all entities.
+ * @param $conditions
+ * (deprecated) An associative array of conditions on the base table, where
+ * the keys are the database fields and the values are the values those
+ * fields must have. Instead, it is preferable to use EntityFieldQuery to
+ * retrieve a list of entity IDs loadable by this function.
+ * @param $reset
+ * Whether to reset the internal cache for the requested entity type.
+ *
+ * @return
+ * An array of entity objects indexed by their ids. When no results are
+ * found, an empty array is returned.
+ *
+ * @todo Remove $conditions in Drupal 8.
+ *
+ * @see hook_entity_info()
+ * @see DrupalEntityControllerInterface
+ * @see DrupalDefaultEntityController
+ * @see EntityFieldQuery
+ */
+function entity_load($entity_type, $ids = FALSE, $conditions = array(), $reset = FALSE) {
+ if ($reset) {
+ entity_get_controller($entity_type)->resetCache();
+ }
+ return entity_get_controller($entity_type)->load($ids, $conditions);
+}
+
+/**
+ * Loads the unchanged, i.e. not modified, entity from the database.
+ *
+ * Unlike entity_load() this function ensures the entity is directly loaded from
+ * the database, thus bypassing any static cache. In particular, this function
+ * is useful to determine changes by comparing the entity being saved to the
+ * stored entity.
+ *
+ * @param $entity_type
+ * The entity type to load, e.g. node or user.
+ * @param $id
+ * The ID of the entity to load.
+ *
+ * @return
+ * The unchanged entity, or FALSE if the entity cannot be loaded.
+ */
+function entity_load_unchanged($entity_type, $id) {
+ entity_get_controller($entity_type)->resetCache(array($id));
+ $result = entity_get_controller($entity_type)->load(array($id));
+ return reset($result);
+}
+
+/**
+ * Get the entity controller class for an entity type.
+ */
+function entity_get_controller($entity_type) {
+ $controllers = &drupal_static(__FUNCTION__, array());
+ if (!isset($controllers[$entity_type])) {
+ $type_info = entity_get_info($entity_type);
+ $class = $type_info['controller class'];
+ $controllers[$entity_type] = new $class($entity_type);
+ }
+ return $controllers[$entity_type];
+}
+
+/**
+ * Invoke hook_entity_prepare_view().
+ *
+ * If adding a new entity similar to nodes, comments or users, you should
+ * invoke this function during the ENTITY_build_content() or
+ * ENTITY_view_multiple() phases of rendering to allow other modules to alter
+ * the objects during this phase. This is needed for situations where
+ * information needs to be loaded outside of ENTITY_load() - particularly
+ * when loading entities into one another - i.e. a user object into a node, due
+ * to the potential for unwanted side-effects such as caching and infinite
+ * recursion. By convention, entity_prepare_view() is called after
+ * field_attach_prepare_view() to allow entity level hooks to act on content
+ * loaded by field API.
+ *
+ * @param $entity_type
+ * The type of entity, i.e. 'node', 'user'.
+ * @param $entities
+ * The entity objects which are being prepared for view, keyed by object ID.
+ * @param $langcode
+ * (optional) A language code to be used for rendering. Defaults to the global
+ * content language of the current request.
+ *
+ * @see hook_entity_prepare_view()
+ */
+function entity_prepare_view($entity_type, $entities, $langcode = NULL) {
+ if (!isset($langcode)) {
+ $langcode = $GLOBALS['language_content']->language;
+ }
+
+ // To ensure hooks are only run once per entity, check for an
+ // entity_view_prepared flag and only process items without it.
+ // @todo: resolve this more generally for both entity and field level hooks.
+ $prepare = array();
+ foreach ($entities as $id => $entity) {
+ if (empty($entity->entity_view_prepared)) {
+ // Add this entity to the items to be prepared.
+ $prepare[$id] = $entity;
+
+ // Mark this item as prepared.
+ $entity->entity_view_prepared = TRUE;
+ }
+ }
+
+ if (!empty($prepare)) {
+ module_invoke_all('entity_prepare_view', $prepare, $entity_type, $langcode);
+ }
+}
+
+/**
+ * Returns the URI elements of an entity.
+ *
+ * @param $entity_type
+ * The entity type; e.g. 'node' or 'user'.
+ * @param $entity
+ * The entity for which to generate a path.
+ * @return
+ * An array containing the 'path' and 'options' keys used to build the URI of
+ * the entity, and matching the signature of url(). NULL if the entity has no
+ * URI of its own.
+ */
+function entity_uri($entity_type, $entity) {
+ $info = entity_get_info($entity_type);
+ list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);
+
+ // A bundle-specific callback takes precedence over the generic one for the
+ // entity type.
+ if (isset($info['bundles'][$bundle]['uri callback'])) {
+ $uri_callback = $info['bundles'][$bundle]['uri callback'];
+ }
+ elseif (isset($info['uri callback'])) {
+ $uri_callback = $info['uri callback'];
+ }
+ else {
+ return NULL;
+ }
+
+ // Invoke the callback to get the URI. If there is no callback, return NULL.
+ if (isset($uri_callback) && function_exists($uri_callback)) {
+ $uri = $uri_callback($entity);
+ // Pass the entity data to url() so that alter functions do not need to
+ // lookup this entity again.
+ $uri['options']['entity_type'] = $entity_type;
+ $uri['options']['entity'] = $entity;
+ return $uri;
+ }
+}
+
+/**
+ * Returns the label of an entity.
+ *
+ * See the 'label callback' component of the hook_entity_info() return value
+ * for more information.
+ *
+ * @param $entity_type
+ * The entity type; e.g., 'node' or 'user'.
+ * @param $entity
+ * The entity for which to generate the label.
+ *
+ * @return
+ * The entity label, or FALSE if not found.
+ */
+function entity_label($entity_type, $entity) {
+ $label = FALSE;
+ $info = entity_get_info($entity_type);
+ if (isset($info['label callback']) && function_exists($info['label callback'])) {
+ $label = $info['label callback']($entity, $entity_type);
+ }
+ elseif (!empty($info['entity keys']['label']) && isset($entity->{$info['entity keys']['label']})) {
+ $label = $entity->{$info['entity keys']['label']};
+ }
+
+ return $label;
+}
+
+/**
+ * Returns the language of an entity.
+ *
+ * @param $entity_type
+ * The entity type; e.g., 'node' or 'user'.
+ * @param $entity
+ * The entity for which to get the language.
+ *
+ * @return
+ * A valid language code or NULL if the entity has no language support.
+ */
+function entity_language($entity_type, $entity) {
+ $info = entity_get_info($entity_type);
+
+ // Invoke the callback to get the language. If there is no callback, try to
+ // get it from a property of the entity, otherwise NULL.
+ if (isset($info['language callback']) && function_exists($info['language callback'])) {
+ $langcode = $info['language callback']($entity_type, $entity);
+ }
+ elseif (!empty($info['entity keys']['language']) && isset($entity->{$info['entity keys']['language']})) {
+ $langcode = $entity->{$info['entity keys']['language']};
+ }
+ else {
+ // The value returned in D8 would be LANGUAGE_NONE, we cannot use it here to
+ // preserve backward compatibility. In fact this function has been
+ // introduced very late in the D7 life cycle, mainly as the proper default
+ // for field_attach_form(). By returning LANGUAGE_NONE when no language
+ // information is available, we would introduce a potentially BC-breaking
+ // API change, since field_attach_form() defaults to the default language
+ // instead of LANGUAGE_NONE. Moreover this allows us to distinguish between
+ // entities that have no language specified from ones that do not have
+ // language support at all.
+ $langcode = NULL;
+ }
+
+ return $langcode;
+}
+
+/**
+ * Attaches field API validation to entity forms.
+ */
+function entity_form_field_validate($entity_type, $form, &$form_state) {
+ // All field attach API functions act on an entity object, but during form
+ // validation, we don't have one. $form_state contains the entity as it was
+ // prior to processing the current form submission, and we must not update it
+ // until we have fully validated the submitted input. Therefore, for
+ // validation, act on a pseudo entity created out of the form values.
+ $pseudo_entity = (object) $form_state['values'];
+ field_attach_form_validate($entity_type, $pseudo_entity, $form, $form_state);
+}
+
+/**
+ * Copies submitted values to entity properties for simple entity forms.
+ *
+ * During the submission handling of an entity form's "Save", "Preview", and
+ * possibly other buttons, the form state's entity needs to be updated with the
+ * submitted form values. Each entity form implements its own builder function
+ * for doing this, appropriate for the particular entity and form, whereas
+ * modules may specify additional builder functions in $form['#entity_builders']
+ * for copying the form values of added form elements to entity properties.
+ * Many of the main entity builder functions can call this helper function to
+ * re-use its logic of copying $form_state['values'][PROPERTY] values to
+ * $entity->PROPERTY for all entries in $form_state['values'] that are not field
+ * data, and calling field_attach_submit() to copy field data. Apart from that
+ * this helper invokes any additional builder functions that have been specified
+ * in $form['#entity_builders'].
+ *
+ * For some entity forms (e.g., forms with complex non-field data and forms that
+ * simultaneously edit multiple entities), this behavior may be inappropriate,
+ * so the builder function for such forms needs to implement the required
+ * functionality instead of calling this function.
+ */
+function entity_form_submit_build_entity($entity_type, $entity, $form, &$form_state) {
+ $info = entity_get_info($entity_type);
+ list(, , $bundle) = entity_extract_ids($entity_type, $entity);
+
+ // Copy top-level form values that are not for fields to entity properties,
+ // without changing existing entity properties that are not being edited by
+ // this form. Copying field values must be done using field_attach_submit().
+ $values_excluding_fields = $info['fieldable'] ? array_diff_key($form_state['values'], field_info_instances($entity_type, $bundle)) : $form_state['values'];
+ foreach ($values_excluding_fields as $key => $value) {
+ $entity->$key = $value;
+ }
+
+ // Invoke all specified builders for copying form values to entity properties.
+ if (isset($form['#entity_builders'])) {
+ foreach ($form['#entity_builders'] as $function) {
+ $function($entity_type, $entity, $form, $form_state);
+ }
+ }
+
+ // Copy field values to the entity.
+ if ($info['fieldable']) {
+ field_attach_submit($entity_type, $entity, $form, $form_state);
+ }
+}
+
+/**
+ * Performs one or more XML-RPC request(s).
+ *
+ * Usage example:
+ * @code
+ * $result = xmlrpc('http://example.com/xmlrpc.php', array(
+ * 'service.methodName' => array($parameter, $second, $third),
+ * ));
+ * @endcode
+ *
+ * @param $url
+ * An absolute URL of the XML-RPC endpoint.
+ * @param $args
+ * An associative array whose keys are the methods to call and whose values
+ * are the arguments to pass to the respective method. If multiple methods
+ * are specified, a system.multicall is performed.
+ * @param $options
+ * (optional) An array of options to pass along to drupal_http_request().
+ *
+ * @return
+ * For one request:
+ * Either the return value of the method on success, or FALSE.
+ * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
+ * For multiple requests:
+ * An array of results. Each result will either be the result
+ * returned by the method called, or an xmlrpc_error object if the call
+ * failed. See xmlrpc_error().
+ */
+function xmlrpc($url, $args, $options = array()) {
+ require_once DRUPAL_ROOT . '/includes/xmlrpc.inc';
+ return _xmlrpc($url, $args, $options);
+}
+
+/**
+ * Retrieves a list of all available archivers.
+ *
+ * @see hook_archiver_info()
+ * @see hook_archiver_info_alter()
+ */
+function archiver_get_info() {
+ $archiver_info = &drupal_static(__FUNCTION__, array());
+
+ if (empty($archiver_info)) {
+ $cache = cache_get('archiver_info');
+ if ($cache === FALSE) {
+ // Rebuild the cache and save it.
+ $archiver_info = module_invoke_all('archiver_info');
+ drupal_alter('archiver_info', $archiver_info);
+ uasort($archiver_info, 'drupal_sort_weight');
+ cache_set('archiver_info', $archiver_info);
+ }
+ else {
+ $archiver_info = $cache->data;
+ }
+ }
+
+ return $archiver_info;
+}
+
+/**
+ * Returns a string of supported archive extensions.
+ *
+ * @return
+ * A space-separated string of extensions suitable for use by the file
+ * validation system.
+ */
+function archiver_get_extensions() {
+ $valid_extensions = array();
+ foreach (archiver_get_info() as $archive) {
+ foreach ($archive['extensions'] as $extension) {
+ foreach (explode('.', $extension) as $part) {
+ if (!in_array($part, $valid_extensions)) {
+ $valid_extensions[] = $part;
+ }
+ }
+ }
+ }
+ return implode(' ', $valid_extensions);
+}
+
+/**
+ * Creates the appropriate archiver for the specified file.
+ *
+ * @param $file
+ * The full path of the archive file. Note that stream wrapper paths are
+ * supported, but not remote ones.
+ *
+ * @return
+ * A newly created instance of the archiver class appropriate
+ * for the specified file, already bound to that file.
+ * If no appropriate archiver class was found, will return FALSE.
+ */
+function archiver_get_archiver($file) {
+ // Archivers can only work on local paths
+ $filepath = drupal_realpath($file);
+ if (!is_file($filepath)) {
+ throw new Exception(t('Archivers can only operate on local files: %file not supported', array('%file' => $file)));
+ }
+ $archiver_info = archiver_get_info();
+
+ foreach ($archiver_info as $implementation) {
+ foreach ($implementation['extensions'] as $extension) {
+ // Because extensions may be multi-part, such as .tar.gz,
+ // we cannot use simpler approaches like substr() or pathinfo().
+ // This method isn't quite as clean but gets the job done.
+ // Also note that the file may not yet exist, so we cannot rely
+ // on fileinfo() or other disk-level utilities.
+ if (strrpos($filepath, '.' . $extension) === strlen($filepath) - strlen('.' . $extension)) {
+ return new $implementation['class']($filepath);
+ }
+ }
+ }
+}
+
+/**
+ * Assembles the Drupal Updater registry.
+ *
+ * An Updater is a class that knows how to update various parts of the Drupal
+ * file system, for example to update modules that have newer releases, or to
+ * install a new theme.
+ *
+ * @return
+ * The Drupal Updater class registry.
+ *
+ * @see hook_updater_info()
+ * @see hook_updater_info_alter()
+ */
+function drupal_get_updaters() {
+ $updaters = &drupal_static(__FUNCTION__);
+ if (!isset($updaters)) {
+ $updaters = module_invoke_all('updater_info');
+ drupal_alter('updater_info', $updaters);
+ uasort($updaters, 'drupal_sort_weight');
+ }
+ return $updaters;
+}
+
+/**
+ * Assembles the Drupal FileTransfer registry.
+ *
+ * @return
+ * The Drupal FileTransfer class registry.
+ *
+ * @see FileTransfer
+ * @see hook_filetransfer_info()
+ * @see hook_filetransfer_info_alter()
+ */
+function drupal_get_filetransfer_info() {
+ $info = &drupal_static(__FUNCTION__);
+ if (!isset($info)) {
+ // Since we have to manually set the 'file path' default for each
+ // module separately, we can't use module_invoke_all().
+ $info = array();
+ foreach (module_implements('filetransfer_info') as $module) {
+ $function = $module . '_filetransfer_info';
+ if (function_exists($function)) {
+ $result = $function();
+ if (isset($result) && is_array($result)) {
+ foreach ($result as &$values) {
+ if (empty($values['file path'])) {
+ $values['file path'] = drupal_get_path('module', $module);
+ }
+ }
+ $info = array_merge_recursive($info, $result);
+ }
+ }
+ }
+ drupal_alter('filetransfer_info', $info);
+ uasort($info, 'drupal_sort_weight');
+ }
+ return $info;
+}
diff --git a/kolab.org/www/drupal-7.26/includes/database/database.inc b/kolab.org/www/drupal-7.26/includes/database/database.inc
new file mode 100644
index 0000000..604dd4c
--- /dev/null
+++ b/kolab.org/www/drupal-7.26/includes/database/database.inc
@@ -0,0 +1,3039 @@
+<?php
+
+/**
+ * @file
+ * Core systems for the database layer.
+ *
+ * Classes required for basic functioning of the database system should be
+ * placed in this file. All utility functions should also be placed in this
+ * file only, as they cannot auto-load the way classes can.
+ */
+
+/**
+ * @defgroup database Database abstraction layer
+ * @{
+ * Allow the use of different database servers using the same code base.
+ *
+ * Drupal provides a database abstraction layer to provide developers with
+ * the ability to support multiple database servers easily. The intent of
+ * this layer is to preserve the syntax and power of SQL as much as possible,
+ * but also allow developers a way to leverage more complex functionality in
+ * a unified way. It also provides a structured interface for dynamically
+ * constructing queries when appropriate, and enforcing security checks and
+ * similar good practices.
+ *
+ * The system is built atop PHP's PDO (PHP Data Objects) database API and
+ * inherits much of its syntax and semantics.
+ *
+ * Most Drupal database SELECT queries are performed by a call to db_query() or
+ * db_query_range(). Module authors should also consider using the PagerDefault
+ * Extender for queries that return results that need to be presented on
+ * multiple pages, and the Tablesort Extender for generating appropriate queries
+ * for sortable tables.
+ *
+ * For example, one might wish to return a list of the most recent 10 nodes
+ * authored by a given user. Instead of directly issuing the SQL query
+ * @code
+ * SELECT n.nid, n.title, n.created FROM node n WHERE n.uid = $uid LIMIT 0, 10;
+ * @endcode
+ * one would instead call the Drupal functions:
+ * @code
+ * $result = db_query_range('SELECT n.nid, n.title, n.created
+ * FROM {node} n WHERE n.uid = :uid', 0, 10, array(':uid' => $uid));
+ * foreach ($result as $record) {
+ * // Perform operations on $record->title, etc. here.
+ * }
+ * @endcode
+ * Curly braces are used around "node" to provide table prefixing via
+ * DatabaseConnection::prefixTables(). The explicit use of a user ID is pulled
+ * out into an argument passed to db_query() so that SQL injection attacks
+ * from user input can be caught and nullified. The LIMIT syntax varies between
+ * database servers, so that is abstracted into db_query_range() arguments.
+ * Finally, note the PDO-based ability to iterate over the result set using
+ * foreach ().
+ *
+ * All queries are passed as a prepared statement string. A
+ * prepared statement is a "template" of a query that omits literal or variable
+ * values in favor of placeholders. The values to place into those
+ * placeholders are passed separately, and the database driver handles
+ * inserting the values into the query in a secure fashion. That means you
+ * should never quote or string-escape a value to be inserted into the query.
+ *
+ * There are two formats for placeholders: named and unnamed. Named placeholders
+ * are strongly preferred in all cases as they are more flexible and
+ * self-documenting. Named placeholders should start with a colon ":" and can be
+ * followed by one or more letters, numbers or underscores.
+ *
+ * Named placeholders begin with a colon followed by a unique string. Example:
+ * @code
+ * SELECT nid, title FROM {node} WHERE uid=:uid;
+ * @endcode
+ *
+ * ":uid" is a placeholder that will be replaced with a literal value when
+ * the query is executed. A given placeholder label cannot be repeated in a
+ * given query, even if the value should be the same. When using named
+ * placeholders, the array of arguments to the query must be an associative
+ * array where keys are a placeholder label (e.g., :uid) and the value is the
+ * corresponding value to use. The array may be in any order.
+ *
+ * Unnamed placeholders are simply a question mark. Example:
+ * @code
+ * SELECT nid, title FROM {node} WHERE uid=?;
+ * @endcode
+ *
+ * In this case, the array of arguments must be an indexed array of values to
+ * use in the exact same order as the placeholders in the query.
+ *
+ * Note that placeholders should be a "complete" value. For example, when
+ * running a LIKE query the SQL wildcard character, %, should be part of the
+ * value, not the query itself. Thus, the following is incorrect:
+ * @code
+ * SELECT nid, title FROM {node} WHERE title LIKE :title%;
+ * @endcode
+ * It should instead read:
+ * @code
+ * SELECT nid, title FROM {node} WHERE title LIKE :title;
+ * @endcode
+ * and the value for :title should include a % as appropriate. Again, note the
+ * lack of quotation marks around :title. Because the value is not inserted
+ * into the query as one big string but as an explicitly separate value, the
+ * database server knows where the query ends and a value begins. That is
+ * considerably more secure against SQL injection than trying to remember
+ * which values need quotation marks and string escaping and which don't.
+ *
+ * INSERT, UPDATE, and DELETE queries need special care in order to behave
+ * consistently across all different databases. Therefore, they use a special
+ * object-oriented API for defining a query structurally. For example, rather
+ * than:
+ * @code
+ * INSERT INTO node (nid, title, body) VALUES (1, 'my title', 'my body');
+ * @endcode
+ * one would instead write:
+ * @code
+ * $fields = array('nid' => 1, 'title' => 'my title', 'body' => 'my body');
+ * db_insert('node')->fields($fields)->execute();
+ * @endcode
+ * This method allows databases that need special data type handling to do so,
+ * while also allowing optimizations such as multi-insert queries. UPDATE and
+ * DELETE queries have a similar pattern.
+ *
+ * Drupal also supports transactions, including a transparent fallback for
+ * databases that do not support transactions. To start a new transaction,
+ * simply call $txn = db_transaction(); in your own code. The transaction will
+ * remain open for as long as the variable $txn remains in scope. When $txn is
+ * destroyed, the transaction will be committed. If your transaction is nested
+ * inside of another then Drupal will track each transaction and only commit
+ * the outer-most transaction when the last transaction object goes out out of
+ * scope, that is, all relevant queries completed successfully.
+ *
+ * Example:
+ * @code
+ * function my_transaction_function() {
+ * // The transaction opens here.
+ * $txn = db_transaction();
+ *
+ * try {
+ * $id = db_insert('example')
+ * ->fields(array(
+ * 'field1' => 'mystring',
+ * 'field2' => 5,
+ * ))
+ * ->execute();
+ *
+ * my_other_function($id);
+ *
+ * return $id;
+ * }
+ * catch (Exception $e) {
+ * // Something went wrong somewhere, so roll back now.
+ * $txn->rollback();
+ * // Log the exception to watchdog.
+ * watchdog_exception('type', $e);
+ * }
+ *
+ * // $txn goes out of scope here. Unless the transaction was rolled back, it
+ * // gets automatically committed here.
+ * }
+ *
+ * function my_other_function($id) {
+ * // The transaction is still open here.
+ *
+ * if ($id % 2 == 0) {
+ * db_update('example')
+ * ->condition('id', $id)
+ * ->fields(array('field2' => 10))
+ * ->execute();
+ * }
+ * }
+ * @endcode
+ *
+ * @see http://drupal.org/developing/api/database
+ */
+
+
+/**
+ * Base Database API class.
+ *
+ * This class provides a Drupal-specific extension of the PDO database
+ * abstraction class in PHP. Every database driver implementation must provide a
+ * concrete implementation of it to support special handling required by that
+ * database.
+ *
+ * @see http://php.net/manual/book.pdo.php
+ */
+abstract class DatabaseConnection extends PDO {
+
+ /**
+ * The database target this connection is for.
+ *
+ * We need this information for later auditing and logging.
+ *
+ * @var string
+ */
+ protected $target = NULL;
+
+ /**
+ * The key representing this connection.
+ *
+ * The key is a unique string which identifies a database connection. A
+ * connection can be a single server or a cluster of master and slaves (use
+ * target to pick between master and slave).
+ *
+ * @var string
+ */
+ protected $key = NULL;
+
+ /**
+ * The current database logging object for this connection.
+ *
+ * @var DatabaseLog
+ */
+ protected $logger = NULL;
+
+ /**
+ * Tracks the number of "layers" of transactions currently active.
+ *
+ * On many databases transactions cannot nest. Instead, we track
+ * nested calls to transactions and collapse them into a single
+ * transaction.
+ *
+ * @var array
+ */
+ protected $transactionLayers = array();
+
+ /**
+ * Index of what driver-specific class to use for various operations.
+ *
+ * @var array
+ */
+ protected $driverClasses = array();
+
+ /**
+ * The name of the Statement class for this connection.
+ *
+ * @var string
+ */
+ protected $statementClass = 'DatabaseStatementBase';
+
+ /**
+ * Whether this database connection supports transactions.
+ *
+ * @var bool
+ */
+ protected $transactionSupport = TRUE;
+
+ /**
+ * Whether this database connection supports transactional DDL.
+ *
+ * Set to FALSE by default because few databases support this feature.
+ *
+ * @var bool
+ */
+ protected $transactionalDDLSupport = FALSE;
+
+ /**
+ * An index used to generate unique temporary table names.
+ *
+ * @var integer
+ */
+ protected $temporaryNameIndex = 0;
+
+ /**
+ * The connection information for this connection object.
+ *
+ * @var array
+ */
+ protected $connectionOptions = array();
+
+ /**
+ * The schema object for this connection.
+ *
+ * @var object
+ */
+ protected $schema = NULL;
+
+ /**
+ * The prefixes used by this database connection.
+ *
+ * @var array
+ */
+ protected $prefixes = array();
+
+ /**
+ * List of search values for use in prefixTables().
+ *
+ * @var array
+ */
+ protected $prefixSearch = array();
+
+ /**
+ * List of replacement values for use in prefixTables().
+ *
+ * @var array
+ */
+ protected $prefixReplace = array();
+
+ function __construct($dsn, $username, $password, $driver_options = array()) {
+ // Initialize and prepare the connection prefix.
+ $this->setPrefix(isset($this->connectionOptions['prefix']) ? $this->connectionOptions['prefix'] : '');
+
+ // Because the other methods don't seem to work right.
+ $driver_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
+
+ // Call PDO::__construct and PDO::setAttribute.
+ parent::__construct($dsn, $username, $password, $driver_options);
+
+ // Set a Statement class, unless the driver opted out.
+ if (!empty($this->statementClass)) {
+ $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array($this->statementClass, array($this)));
+ }
+ }
+
+ /**
+ * Destroys this Connection object.
+ *
+ * PHP does not destruct an object if it is still referenced in other
+ * variables. In case of PDO database connection objects, PHP only closes the
+ * connection when the PDO object is destructed, so any references to this
+ * object may cause the number of maximum allowed connections to be exceeded.
+ */
+ public function destroy() {
+ // Destroy all references to this connection by setting them to NULL.
+ // The Statement class attribute only accepts a new value that presents a
+ // proper callable, so we reset it to PDOStatement.
+ $this->setAttribute(PDO::ATTR_STATEMENT_CLASS, array('PDOStatement', array()));
+ $this->schema = NULL;
+ }
+
+ /**
+ * Returns the default query options for any given query.
+ *
+ * A given query can be customized with a number of option flags in an
+ * associative array:
+ * - target: The database "target" against which to execute a query. Valid
+ * values are "default" or "slave". The system will first try to open a
+ * connection to a database specified with the user-supplied key. If one
+ * is not available, it will silently fall back to the "default" target.
+ * If multiple databases connections are specified with the same target,
+ * one will be selected at random for the duration of the request.
+ * - fetch: This element controls how rows from a result set will be
+ * returned. Legal values include PDO::FETCH_ASSOC, PDO::FETCH_BOTH,
+ * PDO::FETCH_OBJ, PDO::FETCH_NUM, or a string representing the name of a
+ * class. If a string is specified, each record will be fetched into a new
+ * object of that class. The behavior of all other values is defined by PDO.
+ * See http://php.net/manual/pdostatement.fetch.php
+ * - return: Depending on the type of query, different return values may be
+ * meaningful. This directive instructs the system which type of return
+ * value is desired. The system will generally set the correct value
+ * automatically, so it is extremely rare that a module developer will ever
+ * need to specify this value. Setting it incorrectly will likely lead to
+ * unpredictable results or fatal errors. Legal values include:
+ * - Database::RETURN_STATEMENT: Return the prepared statement object for
+ * the query. This is usually only meaningful for SELECT queries, where
+ * the statement object is how one accesses the result set returned by the
+ * query.
+ * - Database::RETURN_AFFECTED: Return the number of rows affected by an
+ * UPDATE or DELETE query. Be aware that means the number of rows actually
+ * changed, not the number of rows matched by the WHERE clause.
+ * - Database::RETURN_INSERT_ID: Return the sequence ID (primary key)
+ * created by an INSERT statement on a table that contains a serial
+ * column.
+ * - Database::RETURN_NULL: Do not return anything, as there is no
+ * meaningful value to return. That is the case for INSERT queries on
+ * tables that do not contain a serial column.
+ * - throw_exception: By default, the database system will catch any errors
+ * on a query as an Exception, log it, and then rethrow it so that code
+ * further up the call chain can take an appropriate action. To suppress
+ * that behavior and simply return NULL on failure, set this option to
+ * FALSE.
+ *
+ * @return
+ * An array of default query options.
+ */
+ protected function defaultOptions() {
+ return array(
+ 'target' => 'default',
+ 'fetch' => PDO::FETCH_OBJ,
+ 'return' => Database::RETURN_STATEMENT,
+ 'throw_exception' => TRUE,
+ );
+ }
+
+ /**
+ * Returns the connection information for this connection object.
+ *
+ * Note that Database::getConnectionInfo() is for requesting information
+ * about an arbitrary database connection that is defined. This method
+ * is for requesting the connection information of this specific
+ * open connection object.
+ *
+ * @return
+ * An array of the connection information. The exact list of
+ * properties is driver-dependent.
+ */
+ public function getConnectionOptions() {
+ return $this->connectionOptions;
+ }
+
+ /**
+ * Set the list of prefixes used by this database connection.
+ *
+ * @param $prefix
+ * The prefixes, in any of the multiple forms documented in
+ * default.settings.php.
+ */
+ protected function setPrefix($prefix) {
+ if (is_array($prefix)) {
+ $this->prefixes = $prefix + array('default' => '');
+ }
+ else {
+ $this->prefixes = array('default' => $prefix);
+ }
+
+ // Set up variables for use in prefixTables(). Replace table-specific
+ // prefixes first.
+ $this->prefixSearch = array();
+ $this->prefixReplace = array();
+ foreach ($this->prefixes as $key => $val) {
+ if ($key != 'default') {
+ $this->prefixSearch[] = '{' . $key . '}';
+ $this->prefixReplace[] = $val . $key;
+ }
+ }
+ // Then replace remaining tables with the default prefix.
+ $this->prefixSearch[] = '{';
+ $this->prefixReplace[] = $this->prefixes['default'];
+ $this->prefixSearch[] = '}';
+ $this->prefixReplace[] = '';
+ }
+
+ /**
+ * Appends a database prefix to all tables in a query.
+ *
+ * Queries sent to Drupal should wrap all table names in curly brackets. This
+ * function searches for this syntax and adds Drupal's table prefix to all
+ * tables, allowing Drupal to coexist with other systems in the same database
+ * and/or schema if necessary.
+ *
+ * @param $sql
+ * A string containing a partial or entire SQL query.
+ *
+ * @return
+ * The properly-prefixed string.
+ */
+ public function prefixTables($sql) {
+ return str_replace($this->prefixSearch, $this->prefixReplace, $sql);
+ }
+
+ /**
+ * Find the prefix for a table.
+ *
+ * This function is for when you want to know the prefix of a table. This
+ * is not used in prefixTables due to performance reasons.
+ */
+ public function tablePrefix($table = 'default') {
+ if (isset($this->prefixes[$table])) {
+ return $this->prefixes[$table];
+ }
+ else {
+ return $this->prefixes['default'];
+ }
+ }
+
+ /**
+ * Prepares a query string and returns the prepared statement.
+ *
+ * This method caches prepared statements, reusing them when
+ * possible. It also prefixes tables names enclosed in curly-braces.
+ *
+ * @param $query
+ * The query string as SQL, with curly-braces surrounding the
+ * table names.
+ *
+ * @return DatabaseStatementInterface
+ * A PDO prepared statement ready for its execute() method.
+ */
+ public function prepareQuery($query) {
+ $query = $this->prefixTables($query);
+
+ // Call PDO::prepare.
+ return parent::prepare($query);
+ }
+
+ /**
+ * Tells this connection object what its target value is.
+ *
+ * This is needed for logging and auditing. It's sloppy to do in the
+ * constructor because the constructor for child classes has a different
+ * signature. We therefore also ensure that this function is only ever
+ * called once.
+ *
+ * @param $target
+ * The target this connection is for. Set to NULL (default) to disable
+ * logging entirely.
+ */
+ public function setTarget($target = NULL) {
+ if (!isset($this->target)) {
+ $this->target = $target;
+ }
+ }
+
+ /**
+ * Returns the target this connection is associated with.
+ *
+ * @return
+ * The target string of this connection.
+ */
+ public function getTarget() {
+ return $this->target;
+ }
+
+ /**
+ * Tells this connection object what its key is.
+ *
+ * @param $target
+ * The key this connection is for.
+ */
+ public function setKey($key) {
+ if (!isset($this->key)) {
+ $this->key = $key;
+ }
+ }
+
+ /**
+ * Returns the key this connection is associated with.
+ *
+ * @return
+ * The key of this connection.
+ */
+ public function getKey() {
+ return $this->key;
+ }
+
+ /**
+ * Associates a logging object with this connection.
+ *
+ * @param $logger
+ * The logging object we want to use.
+ */
+ public function setLogger(DatabaseLog $logger) {
+ $this->logger = $logger;
+ }
+
+ /**
+ * Gets the current logging object for this connection.
+ *
+ * @return DatabaseLog
+ * The current logging object for this connection. If there isn't one,
+ * NULL is returned.
+ */
+ public function getLogger() {
+ return $this->logger;
+ }
+
+ /**
+ * Creates the appropriate sequence name for a given table and serial field.
+ *
+ * This information is exposed to all database drivers, although it is only
+ * useful on some of them. This method is table prefix-aware.
+ *
+ * @param $table
+ * The table name to use for the sequence.
+ * @param $field
+ * The field name to use for the sequence.
+ *
+ * @return
+ * A table prefix-parsed string for the sequence name.
+ */
+ public function makeSequenceName($table, $field) {
+ return $this->prefixTables('{' . $table . '}_' . $field . '_seq');
+ }
+
+ /**
+ * Flatten an array of query comments into a single comment string.
+ *
+ * The comment string will be sanitized to avoid SQL injection attacks.
+ *
+ * @param $comments
+ * An array of query comment strings.
+ *
+ * @return
+ * A sanitized comment string.
+ */
+ public function makeComment($comments) {
+ if (empty($comments))
+ return '';
+
+ // Flatten the array of comments.
+ $comment = implode('; ', $comments);
+
+ // Sanitize the comment string so as to avoid SQL injection attacks.
+ return '/* ' . $this->filterComment($comment) . ' */ ';
+ }
+
+ /**
+ * Sanitize a query comment string.
+ *
+ * Ensure a query comment does not include strings such as "* /" that might
+ * terminate the comment early. This avoids SQL injection attacks via the
+ * query comment. The comment strings in this example are separated by a
+ * space to avoid PHP parse errors.
+ *
+ * For example, the comment:
+ * @code
+ * db_update('example')
+ * ->condition('id', $id)
+ * ->fields(array('field2' => 10))
+ * ->comment('Exploit * / DROP TABLE node; --')
+ * ->execute()
+ * @endcode
+ *
+ * Would result in the following SQL statement being generated:
+ * @code
+ * "/ * Exploit * / DROP TABLE node; -- * / UPDATE example SET field2=..."
+ * @endcode
+ *
+ * Unless the comment is sanitised first, the SQL server would drop the
+ * node table and ignore the rest of the SQL statement.
+ *
+ * @param $comment
+ * A query comment string.
+ *
+ * @return
+ * A sanitized version of the query comment string.
+ */
+ protected function filterComment($comment = '') {
+ return preg_replace('/(\/\*\s*)|(\s*\*\/)/', '', $comment);
+ }
+
+ /**
+ * Executes a query string against the database.
+ *
+ * This method provides a central handler for the actual execution of every
+ * query. All queries executed by Drupal are executed as PDO prepared
+ * statements.
+ *
+ * @param $query
+ * The query to execute. In most cases this will be a string containing
+ * an SQL query with placeholders. An already-prepared instance of
+ * DatabaseStatementInterface may also be passed in order to allow calling
+ * code to manually bind variables to a query. If a
+ * DatabaseStatementInterface is passed, the $args array will be ignored.
+ * It is extremely rare that module code will need to pass a statement
+ * object to this method. It is used primarily for database drivers for
+ * databases that require special LOB field handling.
+ * @param $args
+ * An array of arguments for the prepared statement. If the prepared
+ * statement uses ? placeholders, this array must be an indexed array.
+ * If it contains named placeholders, it must be an associative array.
+ * @param $options
+ * An associative array of options to control how the query is run. See
+ * the documentation for DatabaseConnection::defaultOptions() for details.
+ *
+ * @return DatabaseStatementInterface
+ * This method will return one of: the executed statement, the number of
+ * rows affected by the query (not the number matched), or the generated
+ * insert IT of the last query, depending on the value of
+ * $options['return']. Typically that value will be set by default or a
+ * query builder and should not be set by a user. If there is an error,
+ * this method will return NULL and may throw an exception if
+ * $options['throw_exception'] is TRUE.
+ *
+ * @throws PDOException
+ */
+ public function query($query, array $args = array(), $options = array()) {
+
+ // Use default values if not already set.
+ $options += $this->defaultOptions();
+
+ try {
+ // We allow either a pre-bound statement object or a literal string.
+ // In either case, we want to end up with an executed statement object,
+ // which we pass to PDOStatement::execute.
+ if ($query instanceof DatabaseStatementInterface) {
+ $stmt = $query;
+ $stmt->execute(NULL, $options);
+ }
+ else {
+ $this->expandArguments($query, $args);
+ $stmt = $this->prepareQuery($query);
+ $stmt->execute($args, $options);
+ }
+
+ // Depending on the type of query we may need to return a different value.
+ // See DatabaseConnection::defaultOptions() for a description of each
+ // value.
+ switch ($options['return']) {
+ case Database::RETURN_STATEMENT:
+ return $stmt;
+ case Database::RETURN_AFFECTED:
+ return $stmt->rowCount();
+ case Database::RETURN_INSERT_ID:
+ return $this->lastInsertId();
+ case Database::RETURN_NULL:
+ return;
+ default:
+ throw new PDOException('Invalid return directive: ' . $options['return']);
+ }
+ }
+ catch (PDOException $e) {
+ if ($options['throw_exception']) {
+ // Add additional debug information.
+ if ($query instanceof DatabaseStatementInterface) {
+ $e->query_string = $stmt->getQueryString();
+ }
+ else {
+ $e->query_string = $query;
+ }
+ $e->args = $args;
+ throw $e;
+ }
+ return NULL;
+ }
+ }
+
+ /**
+ * Expands out shorthand placeholders.
+ *
+ * Drupal supports an alternate syntax for doing arrays of values. We
+ * therefore need to expand them out into a full, executable query string.
+ *
+ * @param $query
+ * The query string to modify.
+ * @param $args
+ * The arguments for the query.
+ *
+ * @return
+ * TRUE if the query was modified, FALSE otherwise.
+ */
+ protected function expandArguments(&$query, &$args) {
+ $modified = FALSE;
+
+ // If the placeholder value to insert is an array, assume that we need
+ // to expand it out into a comma-delimited set of placeholders.
+ foreach (array_filter($args, 'is_array') as $key => $data) {
+ $new_keys = array();
+ foreach ($data as $i => $value) {
+ // This assumes that there are no other placeholders that use the same
+ // name. For example, if the array placeholder is defined as :example
+ // and there is already an :example_2 placeholder, this will generate
+ // a duplicate key. We do not account for that as the calling code
+ // is already broken if that happens.
+ $new_keys[$key . '_' . $i] = $value;
+ }
+
+ // Update the query with the new placeholders.
+ // preg_replace is necessary to ensure the replacement does not affect
+ // placeholders that start with the same exact text. For example, if the
+ // query contains the placeholders :foo and :foobar, and :foo has an
+ // array of values, using str_replace would affect both placeholders,
+ // but using the following preg_replace would only affect :foo because
+ // it is followed by a non-word character.
+ $query = preg_replace('#' . $key . '\b#', implode(', ', array_keys($new_keys)), $query);
+
+ // Update the args array with the new placeholders.
+ unset($args[$key]);
+ $args += $new_keys;
+
+ $modified = TRUE;
+ }
+
+ return $modified;
+ }
+
+ /**
+ * Gets the driver-specific override class if any for the specified class.
+ *
+ * @param string $class
+ * The class for which we want the potentially driver-specific class.
+ * @param array $files
+ * The name of the files in which the driver-specific class can be.
+ * @param $use_autoload
+ * If TRUE, attempt to load classes using PHP's autoload capability
+ * as well as the manual approach here.
+ * @return string
+ * The name of the class that should be used for this driver.
+ */
+ public function getDriverClass($class, array $files = array(), $use_autoload = FALSE) {
+ if (empty($this->driverClasses[$class])) {
+ $driver = $this->driver();
+ $this->driverClasses[$class] = $class . '_' . $driver;
+ Database::loadDriverFile($driver, $files);
+ if (!class_exists($this->driverClasses[$class], $use_autoload)) {
+ $this->driverClasses[$class] = $class;
+ }
+ }
+ return $this->driverClasses[$class];
+ }
+
+ /**
+ * Prepares and returns a SELECT query object.
+ *
+ * @param $table
+ * The base table for this query, that is, the first table in the FROM
+ * clause. This table will also be used as the "base" table for query_alter
+ * hook implementations.
+ * @param $alias
+ * The alias of the base table of this query.
+ * @param $options
+ * An array of options on the query.
+ *
+ * @return SelectQueryInterface
+ * An appropriate SelectQuery object for this database connection. Note that
+ * it may be a driver-specific subclass of SelectQuery, depending on the
+ * driver.
+ *
+ * @see SelectQuery
+ */
+ public function select($table, $alias = NULL, array $options = array()) {
+ $class = $this->getDriverClass('SelectQuery', array('query.inc', 'select.inc'));
+ return new $class($table, $alias, $this, $options);
+ }
+
+ /**
+ * Prepares and returns an INSERT query object.
+ *
+ * @param $options
+ * An array of options on the query.
+ *
+ * @return InsertQuery
+ * A new InsertQuery object.
+ *
+ * @see InsertQuery
+ */
+ public function insert($table, array $options = array()) {
+ $class = $this->getDriverClass('InsertQuery', array('query.inc'));
+ return new $class($this, $table, $options);
+ }
+
+ /**
+ * Prepares and returns a MERGE query object.
+ *
+ * @param $options
+ * An array of options on the query.
+ *
+ * @return MergeQuery
+ * A new MergeQuery object.
+ *
+ * @see MergeQuery
+ */
+ public function merge($table, array $options = array()) {
+ $class = $this->getDriverClass('MergeQuery', array('query.inc'));
+ return new $class($this, $table, $options);
+ }
+
+
+ /**
+ * Prepares and returns an UPDATE query object.
+ *
+ * @param $options
+ * An array of options on the query.
+ *
+ * @return UpdateQuery
+ * A new UpdateQuery object.
+ *
+ * @see UpdateQuery
+ */
+ public function update($table, array $options = array()) {
+ $class = $this->getDriverClass('UpdateQuery', array('query.inc'));
+ return new $class($this, $table, $options);
+ }
+
+ /**
+ * Prepares and returns a DELETE query object.
+ *
+ * @param $options
+ * An array of options on the query.
+ *
+ * @return DeleteQuery
+ * A new DeleteQuery object.
+ *
+ * @see DeleteQuery
+ */
+ public function delete($table, array $options = array()) {
+ $class = $this->getDriverClass('DeleteQuery', array('query.inc'));
+ return new $class($this, $table, $options);
+ }
+
+ /**
+ * Prepares and returns a TRUNCATE query object.
+ *
+ * @param $options
+ * An array of options on the query.
+ *
+ * @return TruncateQuery
+ * A new TruncateQuery object.
+ *
+ * @see TruncateQuery
+ */
+ public function truncate($table, array $options = array()) {
+ $class = $this->getDriverClass('TruncateQuery', array('query.inc'));
+ return new $class($this, $table, $options);
+ }
+
+ /**
+ * Returns a DatabaseSchema object for manipulating the schema.
+ *
+ * This method will lazy-load the appropriate schema library file.
+ *
+ * @return DatabaseSchema
+ * The DatabaseSchema object for this connection.
+ */
+ public function schema() {
+ if (empty($this->schema)) {
+ $class = $this->getDriverClass('DatabaseSchema', array('schema.inc'));
+ if (class_exists($class)) {
+ $this->schema = new $class($this);
+ }
+ }
+ return $this->schema;
+ }
+
+ /**
+ * Escapes a table name string.
+ *
+ * Force all table names to be strictly alphanumeric-plus-underscore.
+ * For some database drivers, it may also wrap the table name in
+ * database-specific escape characters.
+ *
+ * @return
+ * The sanitized table name string.
+ */
+ public function escapeTable($table) {
+ return preg_replace('/[^A-Za-z0-9_.]+/', '', $table);
+ }
+
+ /**
+ * Escapes a field name string.
+ *
+ * Force all field names to be strictly alphanumeric-plus-underscore.
+ * For some database drivers, it may also wrap the field name in
+ * database-specific escape characters.
+ *
+ * @return
+ * The sanitized field name string.
+ */
+ public function escapeField($field) {
+ return preg_replace('/[^A-Za-z0-9_.]+/', '', $field);
+ }
+
+ /**
+ * Escapes an alias name string.
+ *
+ * Force all alias names to be strictly alphanumeric-plus-underscore. In
+ * contrast to DatabaseConnection::escapeField() /
+ * DatabaseConnection::escapeTable(), this doesn't allow the period (".")
+ * because that is not allowed in aliases.
+ *
+ * @return
+ * The sanitized field name string.
+ */
+ public function escapeAlias($field) {
+ return preg_replace('/[^A-Za-z0-9_]+/', '', $field);
+ }
+
+ /**
+ * Escapes characters that work as wildcard characters in a LIKE pattern.
+ *
+ * The wildcard characters "%" and "_" as well as backslash are prefixed with
+ * a backslash. Use this to do a search for a verbatim string without any
+ * wildcard behavior.
+ *
+ * For example, the following does a case-insensitive query for all rows whose
+ * name starts with $prefix:
+ * @code
+ * $result = db_query(
+ * 'SELECT * FROM person WHERE name LIKE :pattern',
+ * array(':pattern' => db_like($prefix) . '%')
+ * );
+ * @endcode
+ *
+ * Backslash is defined as escape character for LIKE patterns in
+ * DatabaseCondition::mapConditionOperator().
+ *
+ * @param $string
+ * The string to escape.
+ *
+ * @return
+ * The escaped string.
+ */
+ public function escapeLike($string) {
+ return addcslashes($string, '\%_');
+ }
+
+ /**
+ * Determines if there is an active transaction open.
+ *
+ * @return
+ * TRUE if we're currently in a transaction, FALSE otherwise.
+ */
+ public function inTransaction() {
+ return ($this->transactionDepth() > 0);
+ }
+
+ /**
+ * Determines current transaction depth.
+ */
+ public function transactionDepth() {
+ return count($this->transactionLayers);
+ }
+
+ /**
+ * Returns a new DatabaseTransaction object on this connection.
+ *
+ * @param $name
+ * Optional name of the savepoint.
+ *
+ * @return DatabaseTransaction
+ * A DatabaseTransaction object.
+ *
+ * @see DatabaseTransaction
+ */
+ public function startTransaction($name = '') {
+ $class = $this->getDriverClass('DatabaseTransaction');
+ return new $class($this, $name);
+ }
+
+ /**
+ * Rolls back the transaction entirely or to a named savepoint.
+ *
+ * This method throws an exception if no transaction is active.
+ *
+ * @param $savepoint_name
+ * The name of the savepoint. The default, 'drupal_transaction', will roll
+ * the entire transaction back.
+ *
+ * @throws DatabaseTransactionNoActiveException
+ *
+ * @see DatabaseTransaction::rollback()
+ */
+ public function rollback($savepoint_name = 'drupal_transaction') {
+ if (!$this->supportsTransactions()) {
+ return;
+ }
+ if (!$this->inTransaction()) {
+ throw new DatabaseTransactionNoActiveException();
+ }
+ // A previous rollback to an earlier savepoint may mean that the savepoint
+ // in question has already been accidentally committed.
+ if (!isset($this->transactionLayers[$savepoint_name])) {
+ throw new DatabaseTransactionNoActiveException();
+ }
+
+ // We need to find the point we're rolling back to, all other savepoints
+ // before are no longer needed. If we rolled back other active savepoints,
+ // we need to throw an exception.
+ $rolled_back_other_active_savepoints = FALSE;
+ while ($savepoint = array_pop($this->transactionLayers)) {
+ if ($savepoint == $savepoint_name) {
+ // If it is the last the transaction in the stack, then it is not a
+ // savepoint, it is the transaction itself so we will need to roll back
+ // the transaction rather than a savepoint.
+ if (empty($this->transactionLayers)) {
+ break;
+ }
+ $this->query('ROLLBACK TO SAVEPOINT ' . $savepoint);
+ $this->popCommittableTransactions();
+ if ($rolled_back_other_active_savepoints) {
+ throw new DatabaseTransactionOutOfOrderException();
+ }
+ return;
+ }
+ else {
+ $rolled_back_other_active_savepoints = TRUE;
+ }
+ }
+ parent::rollBack();
+ if ($rolled_back_other_active_savepoints) {
+ throw new DatabaseTransactionOutOfOrderException();
+ }
+ }
+
+ /**
+ * Increases the depth of transaction nesting.
+ *
+ * If no transaction is already active, we begin a new transaction.
+ *
+ * @throws DatabaseTransactionNameNonUniqueException
+ *
+ * @see DatabaseTransaction
+ */
+ public function pushTransaction($name) {
+ if (!$this->supportsTransactions()) {
+ return;
+ }
+ if (isset($this->transactionLayers[$name])) {
+ throw new DatabaseTransactionNameNonUniqueException($name . " is already in use.");
+ }
+ // If we're already in a transaction then we want to create a savepoint
+ // rather than try to create another transaction.
+ if ($this->inTransaction()) {
+ $this->query('SAVEPOINT ' . $name);
+ }
+ else {
+ parent::beginTransaction();
+ }
+ $this->transactionLayers[$name] = $name;
+ }
+
+ /**
+ * Decreases the depth of transaction nesting.
+ *
+ * If we pop off the last transaction layer, then we either commit or roll
+ * back the transaction as necessary. If no transaction is active, we return
+ * because the transaction may have manually been rolled back.
+ *
+ * @param $name
+ * The name of the savepoint
+ *
+ * @throws DatabaseTransactionNoActiveException
+ * @throws DatabaseTransactionCommitFailedException
+ *
+ * @see DatabaseTransaction
+ */
+ public function popTransaction($name) {
+ if (!$this->supportsTransactions()) {
+ return;
+ }
+ // The transaction has already been committed earlier. There is nothing we
+ // need to do. If this transaction was part of an earlier out-of-order
+ // rollback, an exception would already have been thrown by
+ // Database::rollback().
+ if (!isset($this->transactionLayers[$name])) {
+ return;
+ }
+
+ // Mark this layer as committable.
+ $this->transactionLayers[$name] = FALSE;
+ $this->popCommittableTransactions();
+ }
+
+ /**
+ * Internal function: commit all the transaction layers that can commit.
+ */
+ protected function popCommittableTransactions() {
+ // Commit all the committable layers.
+ foreach (array_reverse($this->transactionLayers) as $name => $active) {
+ // Stop once we found an active transaction.
+ if ($active) {
+ break;
+ }
+
+ // If there are no more layers left then we should commit.
+ unset($this->transactionLayers[$name]);
+ if (empty($this->transactionLayers)) {
+ if (!parent::commit()) {
+ throw new DatabaseTransactionCommitFailedException();
+ }
+ }
+ else {
+ $this->query('RELEASE SAVEPOINT ' . $name);
+ }
+ }
+ }
+
+ /**
+ * Runs a limited-range query on this database object.
+ *
+ * Use this as a substitute for ->query() when a subset of the query is to be
+ * returned. User-supplied arguments to the query should be passed in as
+ * separate parameters so that they can be properly escaped to avoid SQL
+ * injection attacks.
+ *
+ * @param $query
+ * A string containing an SQL query.
+ * @param $args
+ * An array of values to substitute into the query at placeholder markers.
+ * @param $from
+ * The first result row to return.
+ * @param $count
+ * The maximum number of result rows to return.
+ * @param $options
+ * An array of options on the query.
+ *
+ * @return DatabaseStatementInterface
+ * A database query result resource, or NULL if the query was not executed
+ * correctly.
+ */
+ abstract public function queryRange($query, $from, $count, array $args = array(), array $options = array());
+
+ /**
+ * Generates a temporary table name.
+ *
+ * @return
+ * A table name.
+ */
+ protected function generateTemporaryTableName() {
+ return "db_temporary_" . $this->temporaryNameIndex++;
+ }
+
+ /**
+ * Runs a SELECT query and stores its results in a temporary table.
+ *
+ * Use this as a substitute for ->query() when the results need to stored
+ * in a temporary table. Temporary tables exist for the duration of the page
+ * request. User-supplied arguments to the query should be passed in as
+ * separate parameters so that they can be properly escaped to avoid SQL
+ * injection attacks.
+ *
+ * Note that if you need to know how many results were returned, you should do
+ * a SELECT COUNT(*) on the temporary table afterwards.
+ *
+ * @param $query
+ * A string containing a normal SELECT SQL query.
+ * @param $args
+ * An array of values to substitute into the query at placeholder markers.
+ * @param $options
+ * An associative array of options to control how the query is run. See
+ * the documentation for DatabaseConnection::defaultOptions() for details.
+ *
+ * @return
+ * The name of the temporary table.
+ */
+ abstract function queryTemporary($query, array $args = array(), array $options = array());
+
+ /**
+ * Returns the type of database driver.
+ *
+ * This is not necessarily the same as the type of the database itself. For
+ * instance, there could be two MySQL drivers, mysql and mysql_mock. This
+ * function would return different values for each, but both would return
+ * "mysql" for databaseType().
+ */
+ abstract public function driver();
+
+ /**
+ * Returns the version of the database server.
+ */
+ public function version() {
+ return $this->getAttribute(PDO::ATTR_SERVER_VERSION);
+ }
+
+ /**
+ * Determines if this driver supports transactions.
+ *
+ * @return
+ * TRUE if this connection supports transactions, FALSE otherwise.
+ */
+ public function supportsTransactions() {
+ return $this->transactionSupport;
+ }
+
+ /**
+ * Determines if this driver supports transactional DDL.
+ *
+ * DDL queries are those that change the schema, such as ALTER queries.
+ *
+ * @return
+ * TRUE if this connection supports transactions for DDL queries, FALSE
+ * otherwise.
+ */
+ public function supportsTransactionalDDL() {
+ return $this->transactionalDDLSupport;
+ }
+
+ /**
+ * Returns the name of the PDO driver for this connection.
+ */
+ abstract public function databaseType();
+
+
+ /**
+ * Gets any special processing requirements for the condition operator.
+ *
+ * Some condition types require special processing, such as IN, because
+ * the value data they pass in is not a simple value. This is a simple
+ * overridable lookup function. Database connections should define only
+ * those operators they wish to be handled differently than the default.
+ *
+ * @param $operator
+ * The condition operator, such as "IN", "BETWEEN", etc. Case-sensitive.
+ *
+ * @return
+ * The extra handling directives for the specified operator, or NULL.
+ *
+ * @see DatabaseCondition::compile()
+ */
+ abstract public function mapConditionOperator($operator);
+
+ /**
+ * Throws an exception to deny direct access to transaction commits.
+ *
+ * We do not want to allow users to commit transactions at any time, only
+ * by destroying the transaction object or allowing it to go out of scope.
+ * A direct commit bypasses all of the safety checks we've built on top of
+ * PDO's transaction routines.
+ *
+ * @throws DatabaseTransactionExplicitCommitNotAllowedException
+ *
+ * @see DatabaseTransaction
+ */
+ public function commit() {
+ throw new DatabaseTransactionExplicitCommitNotAllowedException();
+ }
+
+ /**
+ * Retrieves an unique id from a given sequence.
+ *
+ * Use this function if for some reason you can't use a serial field. For
+ * example, MySQL has no ways of reading of the current value of a sequence
+ * and PostgreSQL can not advance the sequence to be larger than a given
+ * value. Or sometimes you just need a unique integer.
+ *
+ * @param $existing_id
+ * After a database import, it might be that the sequences table is behind,
+ * so by passing in the maximum existing id, it can be assured that we
+ * never issue the same id.
+ *
+ * @return
+ * An integer number larger than any number returned by earlier calls and
+ * also larger than the $existing_id if one was passed in.
+ */
+ abstract public function nextId($existing_id = 0);
+}
+
+/**
+ * Primary front-controller for the database system.
+ *
+ * This class is uninstantiatable and un-extendable. It acts to encapsulate
+ * all control and shepherding of database connections into a single location
+ * without the use of globals.
+ */
+abstract class Database {
+
+ /**
+ * Flag to indicate a query call should simply return NULL.
+ *
+ * This is used for queries that have no reasonable return value anyway, such
+ * as INSERT statements to a table without a serial primary key.
+ */
+ const RETURN_NULL = 0;
+
+ /**
+ * Flag to indicate a query call should return the prepared statement.
+ */
+ const RETURN_STATEMENT = 1;
+
+ /**
+ * Flag to indicate a query call should return the number of affected rows.
+ */
+ const RETURN_AFFECTED = 2;
+
+ /**
+ * Flag to indicate a query call should return the "last insert id".
+ */
+ const RETURN_INSERT_ID = 3;
+
+ /**
+ * An nested array of all active connections. It is keyed by database name
+ * and target.
+ *
+ * @var array
+ */
+ static protected $connections = array();
+
+ /**
+ * A processed copy of the database connection information from settings.php.
+ *
+ * @var array
+ */
+ static protected $databaseInfo = NULL;
+
+ /**
+ * A list of key/target credentials to simply ignore.
+ *
+ * @var array
+ */
+ static protected $ignoreTargets = array();
+
+ /**
+ * The key of the currently active database connection.
+ *
+ * @var string
+ */
+ static protected $activeKey = 'default';
+
+ /**
+ * An array of active query log objects.
+ *
+ * Every connection has one and only one logger object for all targets and
+ * logging keys.
+ *
+ * array(
+ * '$db_key' => DatabaseLog object.
+ * );
+ *
+ * @var array
+ */
+ static protected $logs = array();
+
+ /**
+ * Starts logging a given logging key on the specified connection.
+ *
+ * @param $logging_key
+ * The logging key to log.
+ * @param $key
+ * The database connection key for which we want to log.
+ *
+ * @return DatabaseLog
+ * The query log object. Note that the log object does support richer
+ * methods than the few exposed through the Database class, so in some
+ * cases it may be desirable to access it directly.
+ *
+ * @see DatabaseLog
+ */
+ final public static function startLog($logging_key, $key = 'default') {
+ if (empty(self::$logs[$key])) {
+ self::$logs[$key] = new DatabaseLog($key);
+
+ // Every target already active for this connection key needs to have the
+ // logging object associated with it.
+ if (!empty(self::$connections[$key])) {
+ foreach (self::$connections[$key] as $connection) {
+ $connection->setLogger(self::$logs[$key]);
+ }
+ }
+ }
+
+ self::$logs[$key]->start($logging_key);
+ return self::$logs[$key];
+ }
+
+ /**
+ * Retrieves the queries logged on for given logging key.
+ *
+ * This method also ends logging for the specified key. To get the query log
+ * to date without ending the logger request the logging object by starting
+ * it again (which does nothing to an open log key) and call methods on it as
+ * desired.
+ *
+ * @param $logging_key
+ * The logging key to log.
+ * @param $key
+ * The database connection key for which we want to log.
+ *
+ * @return array
+ * The query log for the specified logging key and connection.
+ *
+ * @see DatabaseLog
+ */
+ final public static function getLog($logging_key, $key = 'default') {
+ if (empty(self::$logs[$key])) {
+ return NULL;
+ }
+ $queries = self::$logs[$key]->get($logging_key);
+ self::$logs[$key]->end($logging_key);
+ return $queries;
+ }
+
+ /**
+ * Gets the connection object for the specified database key and target.
+ *
+ * @param $target
+ * The database target name.
+ * @param $key
+ * The database connection key. Defaults to NULL which means the active key.
+ *
+ * @return DatabaseConnection
+ * The corresponding connection object.
+ */
+ final public static function getConnection($target = 'default', $key = NULL) {
+ if (!isset($key)) {
+ // By default, we want the active connection, set in setActiveConnection.
+ $key = self::$activeKey;
+ }
+ // If the requested target does not exist, or if it is ignored, we fall back
+ // to the default target. The target is typically either "default" or
+ // "slave", indicating to use a slave SQL server if one is available. If
+ // it's not available, then the default/master server is the correct server
+ // to use.
+ if (!empty(self::$ignoreTargets[$key][$target]) || !isset(self::$databaseInfo[$key][$target])) {
+ $target = 'default';
+ }
+
+ if (!isset(self::$connections[$key][$target])) {
+ // If necessary, a new connection is opened.
+ self::$connections[$key][$target] = self::openConnection($key, $target);
+ }
+ return self::$connections[$key][$target];
+ }
+
+ /**
+ * Determines if there is an active connection.
+ *
+ * Note that this method will return FALSE if no connection has been
+ * established yet, even if one could be.
+ *
+ * @return
+ * TRUE if there is at least one database connection established, FALSE
+ * otherwise.
+ */
+ final public static function isActiveConnection() {
+ return !empty(self::$activeKey) && !empty(self::$connections) && !empty(self::$connections[self::$activeKey]);
+ }
+
+ /**
+ * Sets the active connection to the specified key.
+ *
+ * @return
+ * The previous database connection key.
+ */
+ final public static function setActiveConnection($key = 'default') {
+ if (empty(self::$databaseInfo)) {
+ self::parseConnectionInfo();
+ }
+
+ if (!empty(self::$databaseInfo[$key])) {
+ $old_key = self::$activeKey;
+ self::$activeKey = $key;
+ return $old_key;
+ }
+ }
+
+ /**
+ * Process the configuration file for database information.
+ */
+ final public static function parseConnectionInfo() {
+ global $databases;
+
+ $database_info = is_array($databases) ? $databases : array();
+ foreach ($database_info as $index => $info) {
+ foreach ($database_info[$index] as $target => $value) {
+ // If there is no "driver" property, then we assume it's an array of
+ // possible connections for this target. Pick one at random. That allows
+ // us to have, for example, multiple slave servers.
+ if (empty($value['driver'])) {
+ $database_info[$index][$target] = $database_info[$index][$target][mt_rand(0, count($database_info[$index][$target]) - 1)];
+ }
+
+ // Parse the prefix information.
+ if (!isset($database_info[$index][$target]['prefix'])) {
+ // Default to an empty prefix.
+ $database_info[$index][$target]['prefix'] = array(
+ 'default' => '',
+ );
+ }
+ elseif (!is_array($database_info[$index][$target]['prefix'])) {
+ // Transform the flat form into an array form.
+ $database_info[$index][$target]['prefix'] = array(
+ 'default' => $database_info[$index][$target]['prefix'],
+ );
+ }
+ }
+ }
+
+ if (!is_array(self::$databaseInfo)) {
+ self::$databaseInfo = $database_info;
+ }
+
+ // Merge the new $database_info into the existing.
+ // array_merge_recursive() cannot be used, as it would make multiple
+ // database, user, and password keys in the same database array.
+ else {
+ foreach ($database_info as $database_key => $database_values) {
+ foreach ($database_values as $target => $target_values) {
+ self::$databaseInfo[$database_key][$target] = $target_values;
+ }
+ }
+ }
+ }
+
+ /**
+ * Adds database connection information for a given key/target.
+ *
+ * This method allows the addition of new connection credentials at runtime.
+ * Under normal circumstances the preferred way to specify database
+ * credentials is via settings.php. However, this method allows them to be
+ * added at arbitrary times, such as during unit tests, when connecting to
+ * admin-defined third party databases, etc.
+ *
+ * If the given key/target pair already exists, this method will be ignored.
+ *
+ * @param $key
+ * The database key.
+ * @param $target
+ * The database target name.
+ * @param $info
+ * The database connection information, as it would be defined in
+ * settings.php. Note that the structure of this array will depend on the
+ * database driver it is connecting to.
+ */
+ public static function addConnectionInfo($key, $target, $info) {
+ if (empty(self::$databaseInfo[$key][$target])) {
+ self::$databaseInfo[$key][$target] = $info;
+ }
+ }
+
+ /**
+ * Gets information on the specified database connection.
+ *
+ * @param $connection
+ * The connection key for which we want information.
+ */
+ final public static function getConnectionInfo($key = 'default') {
+ if (empty(self::$databaseInfo)) {
+ self::parseConnectionInfo();
+ }
+
+ if (!empty(self::$databaseInfo[$key])) {
+ return self::$databaseInfo[$key];
+ }
+ }
+
+ /**
+ * Rename a connection and its corresponding connection information.
+ *
+ * @param $old_key
+ * The old connection key.
+ * @param $new_key
+ * The new connection key.
+ * @return
+ * TRUE in case of success, FALSE otherwise.
+ */
+ final public static function renameConnection($old_key, $new_key) {
+ if (empty(self::$databaseInfo)) {
+ self::parseConnectionInfo();
+ }
+
+ if (!empty(self::$databaseInfo[$old_key]) && empty(self::$databaseInfo[$new_key])) {
+ // Migrate the database connection information.
+ self::$databaseInfo[$new_key] = self::$databaseInfo[$old_key];
+ unset(self::$databaseInfo[$old_key]);
+
+ // Migrate over the DatabaseConnection object if it exists.
+ if (isset(self::$connections[$old_key])) {
+ self::$connections[$new_key] = self::$connections[$old_key];
+ unset(self::$connections[$old_key]);
+ }
+
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+ }
+
+ /**
+ * Remove a connection and its corresponding connection information.
+ *
+ * @param $key
+ * The connection key.
+ * @return
+ * TRUE in case of success, FALSE otherwise.
+ */
+ final public static function removeConnection($key) {
+ if (isset(self::$databaseInfo[$key])) {
+ self::closeConnection(NULL, $key);
+ unset(self::$databaseInfo[$key]);
+ return TRUE;
+ }
+ else {
+ return FALSE;
+ }
+ }
+
+ /**
+ * Opens a connection to the server specified by the given key and target.
+ *
+ * @param $key
+ * The database connection key, as specified in settings.php. The default is
+ * "default".
+ * @param $target
+ * The database target to open.
+ *
+ * @throws DatabaseConnectionNotDefinedException
+ * @throws DatabaseDriverNotSpecifiedException
+ */
+ final protected static function openConnection($key, $target) {
+ if (empty(self::$databaseInfo)) {
+ self::parseConnectionInfo();
+ }
+
+ // If the requested database does not exist then it is an unrecoverable
+ // error.
+ if (!isset(self::$databaseInfo[$key])) {
+ throw new DatabaseConnectionNotDefinedException('The specified database connection is not defined: ' . $key);
+ }
+
+ if (!$driver = self::$databaseInfo[$key][$target]['driver']) {
+ throw new DatabaseDriverNotSpecifiedException('Driver not specified for this database connection: ' . $key);
+ }
+
+ // We cannot rely on the registry yet, because the registry requires an
+ // open database connection.
+ $driver_class = 'DatabaseConnection_' . $driver;
+ require_once DRUPAL_ROOT . '/includes/database/' . $driver . '/database.inc';
+ $new_connection = new $driver_class(self::$databaseInfo[$key][$target]);
+ $new_connection->setTarget($target);
+ $new_connection->setKey($key);
+
+ // If we have any active logging objects for this connection key, we need
+ // to associate them with the connection we just opened.
+ if (!empty(self::$logs[$key])) {
+ $new_connection->setLogger(self::$logs[$key]);
+ }
+
+ return $new_connection;
+ }
+
+ /**
+ * Closes a connection to the server specified by the given key and target.
+ *
+ * @param $target
+ * The database target name. Defaults to NULL meaning that all target
+ * connections will be closed.
+ * @param $key
+ * The database connection key. Defaults to NULL which means the active key.
+ */
+ public static function closeConnection($target = NULL, $key = NULL) {
+ // Gets the active connection by default.
+ if (!isset($key)) {
+ $key = self::$activeKey;
+ }
+ // To close a connection, it needs to be set to NULL and removed from the
+ // static variable. In all cases, closeConnection() might be called for a
+ // connection that was not opened yet, in which case the key is not defined
+ // yet and we just ensure that the connection key is undefined.
+ if (isset($target)) {
+ if (isset(self::$connections[$key][$target])) {
+ self::$connections[$key][$target]->destroy();
+ self::$connections[$key][$target] = NULL;
+ }
+ unset(self::$connections[$key][$target]);
+ }
+ else {
+ if (isset(self::$connections[$key])) {
+ foreach (self::$connections[$key] as $target => $connection) {
+ self::$connections[$key][$target]->destroy();
+ self::$connections[$key][$target] = NULL;
+ }
+ }
+ unset(self::$connections[$key]);
+ }
+ }
+
+ /**
+ * Instructs the system to temporarily ignore a given key/target.
+ *
+ * At times we need to temporarily disable slave queries. To do so, call this
+ * method with the database key and the target to disable. That database key
+ * will then always fall back to 'default' for that key, even if it's defined.
+ *
+ * @param $key
+ * The database connection key.
+ * @param $target
+ * The target of the specified key to ignore.
+ */
+ public static function ignoreTarget($key, $target) {
+ self::$ignoreTargets[$key][$target] = TRUE;
+ }
+
+ /**
+ * Load a file for the database that might hold a class.
+ *
+ * @param $driver
+ * The name of the driver.
+ * @param array $files
+ * The name of the files the driver specific class can be.
+ */
+ public static function loadDriverFile($driver, array $files = array()) {
+ static $base_path;
+
+ if (empty($base_path)) {
+ $base_path = dirname(realpath(__FILE__));
+ }
+
+ $driver_base_path = "$base_path/$driver";
+ foreach ($files as $file) {
+ // Load the base file first so that classes extending base classes will
+ // have the base class loaded.
+ foreach (array("$base_path/$file", "$driver_base_path/$file") as $filename) {
+ // The OS caches file_exists() and PHP caches require_once(), so
+ // we'll let both of those take care of performance here.
+ if (file_exists($filename)) {
+ require_once $filename;
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Exception for when popTransaction() is called with no active transaction.
+ */
+class DatabaseTransactionNoActiveException extends Exception { }
+
+/**
+ * Exception thrown when a savepoint or transaction name occurs twice.
+ */
+class DatabaseTransactionNameNonUniqueException extends Exception { }
+
+/**
+ * Exception thrown when a commit() function fails.
+ */
+class DatabaseTransactionCommitFailedException extends Exception { }
+
+/**
+ * Exception to deny attempts to explicitly manage transactions.
+ *
+ * This exception will be thrown when the PDO connection commit() is called.
+ * Code should never call this method directly.
+ */
+class DatabaseTransactionExplicitCommitNotAllowedException extends Exception { }
+
+/**
+ * Exception thrown when a rollback() resulted in other active transactions being rolled-back.
+ */
+class DatabaseTransactionOutOfOrderException extends Exception { }
+
+/**
+ * Exception thrown for merge queries that do not make semantic sense.
+ *
+ * There are many ways that a merge query could be malformed. They should all
+ * throw this exception and set an appropriately descriptive message.
+ */
+class InvalidMergeQueryException extends Exception {}
+
+/**
+ * Exception thrown if an insert query specifies a field twice.
+ *
+ * It is not allowed to specify a field as default and insert field, this
+ * exception is thrown if that is the case.
+ */
+class FieldsOverlapException extends Exception {}
+
+/**
+ * Exception thrown if an insert query doesn't specify insert or default fields.
+ */
+class NoFieldsException extends Exception {}
+
+/**
+ * Exception thrown if an undefined database connection is requested.
+ */
+class DatabaseConnectionNotDefinedException extends Exception {}
+
+/**
+ * Exception thrown if no driver is specified for a database connection.
+ */
+class DatabaseDriverNotSpecifiedException extends Exception {}
+
+
+/**
+ * A wrapper class for creating and managing database transactions.
+ *
+ * Not all databases or database configurations support transactions. For
+ * example, MySQL MyISAM tables do not. It is also easy to begin a transaction
+ * and then forget to commit it, which can lead to connection errors when
+ * another transaction is started.
+ *
+ * This class acts as a wrapper for transactions. To begin a transaction,
+ * simply instantiate it. When the object goes out of scope and is destroyed
+ * it will automatically commit. It also will check to see if the specified
+ * connection supports transactions. If not, it will simply skip any transaction
+ * commands, allowing user-space code to proceed normally. The only difference
+ * is that rollbacks won't actually do anything.
+ *
+ * In the vast majority of cases, you should not instantiate this class
+ * directly. Instead, call ->startTransaction(), from the appropriate connection
+ * object.
+ */
+class DatabaseTransaction {
+
+ /**
+ * The connection object for this transaction.
+ *
+ * @var DatabaseConnection
+ */
+ protected $connection;
+
+ /**
+ * A boolean value to indicate whether this transaction has been rolled back.
+ *
+ * @var Boolean
+ */
+ protected $rolledBack = FALSE;
+
+ /**
+ * The name of the transaction.
+ *
+ * This is used to label the transaction savepoint. It will be overridden to
+ * 'drupal_transaction' if there is no transaction depth.
+ */
+ protected $name;
+
+ public function __construct(DatabaseConnection $connection, $name = NULL) {
+ $this->connection = $connection;
+ // If there is no transaction depth, then no transaction has started. Name
+ // the transaction 'drupal_transaction'.
+ if (!$depth = $connection->transactionDepth()) {
+ $this->name = 'drupal_transaction';
+ }
+ // Within transactions, savepoints are used. Each savepoint requires a
+ // name. So if no name is present we need to create one.
+ elseif (!$name) {
+ $this->name = 'savepoint_' . $depth;
+ }
+ else {
+ $this->name = $name;
+ }
+ $this->connection->pushTransaction($this->name);
+ }
+
+ public function __destruct() {
+ // If we rolled back then the transaction would have already been popped.
+ if (!$this->rolledBack) {
+ $this->connection->popTransaction($this->name);
+ }
+ }
+
+ /**
+ * Retrieves the name of the transaction or savepoint.
+ */
+ public function name() {
+ return $this->name;
+ }
+
+ /**
+ * Rolls back the current transaction.
+ *
+ * This is just a wrapper method to rollback whatever transaction stack we are
+ * currently in, which is managed by the connection object itself. Note that
+ * logging (preferable with watchdog_exception()) needs to happen after a
+ * transaction has been rolled back or the log messages will be rolled back
+ * too.
+ *
+ * @see DatabaseConnection::rollback()
+ * @see watchdog_exception()
+ */
+ public function rollback() {
+ $this->rolledBack = TRUE;
+ $this->connection->rollback($this->name);
+ }
+}
+
+/**
+ * Represents a prepared statement.
+ *
+ * Some methods in that class are purposefully commented out. Due to a change in
+ * how PHP defines PDOStatement, we can't define a signature for those methods
+ * that will work the same way between versions older than 5.2.6 and later
+ * versions. See http://bugs.php.net/bug.php?id=42452 for more details.
+ *
+ * Child implementations should either extend PDOStatement:
+ * @code
+ * class DatabaseStatement_oracle extends PDOStatement implements DatabaseStatementInterface {}
+ * @endcode
+ * or define their own class. If defining their own class, they will also have
+ * to implement either the Iterator or IteratorAggregate interface before
+ * DatabaseStatementInterface:
+ * @code
+ * class DatabaseStatement_oracle implements Iterator, DatabaseStatementInterface {}
+ * @endcode
+ */
+interface DatabaseStatementInterface extends Traversable {
+
+ /**
+ * Executes a prepared statement
+ *
+ * @param $args
+ * An array of values with as many elements as there are bound parameters in
+ * the SQL statement being executed.
+ * @param $options
+ * An array of options for this query.
+ *
+ * @return
+ * TRUE on success, or FALSE on failure.
+ */
+ public function execute($args = array(), $options = array());
+
+ /**
+ * Gets the query string of this statement.
+ *
+ * @return
+ * The query string, in its form with placeholders.
+ */
+ public function getQueryString();
+
+ /**
+ * Returns the number of rows affected by the last SQL statement.
+ *
+ * @return
+ * The number of rows affected by the last DELETE, INSERT, or UPDATE
+ * statement executed.
+ */
+ public function rowCount();
+
+ /**
+ * Sets the default fetch mode for this statement.
+ *
+ * See http://php.net/manual/pdo.constants.php for the definition of the
+ * constants used.
+ *
+ * @param $mode
+ * One of the PDO::FETCH_* constants.
+ * @param $a1
+ * An option depending of the fetch mode specified by $mode:
+ * - for PDO::FETCH_COLUMN, the index of the column to fetch
+ * - for PDO::FETCH_CLASS, the name of the class to create
+ * - for PDO::FETCH_INTO, the object to add the data to
+ * @param $a2
+ * If $mode is PDO::FETCH_CLASS, the optional arguments to pass to the
+ * constructor.
+ */
+ // public function setFetchMode($mode, $a1 = NULL, $a2 = array());
+
+ /**
+ * Fetches the next row from a result set.
+ *
+ * See http://php.net/manual/pdo.constants.php for the definition of the
+ * constants used.
+ *
+ * @param $mode
+ * One of the PDO::FETCH_* constants.
+ * Default to what was specified by setFetchMode().
+ * @param $cursor_orientation
+ * Not implemented in all database drivers, don't use.
+ * @param $cursor_offset
+ * Not implemented in all database drivers, don't use.
+ *
+ * @return
+ * A result, formatted according to $mode.
+ */
+ // public function fetch($mode = NULL, $cursor_orientation = NULL, $cursor_offset = NULL);
+
+ /**
+ * Returns a single field from the next record of a result set.
+ *
+ * @param $index
+ * The numeric index of the field to return. Defaults to the first field.
+ *
+ * @return