webmaster@1: \n";
webmaster@1: return $output . drupal_set_html_head();
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Reset the static variable which holds the aliases mapped for this request.
webmaster@1: */
webmaster@1: function drupal_clear_path_cache() {
webmaster@1: drupal_lookup_path('wipe');
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Set an HTTP response header for the current page.
webmaster@1: *
webmaster@1: * Note: When sending a Content-Type header, always include a 'charset' type,
webmaster@1: * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
webmaster@1: */
webmaster@1: function drupal_set_header($header = NULL) {
webmaster@1: // We use an array to guarantee there are no leading or trailing delimiters.
webmaster@1: // Otherwise, header('') could get called when serving the page later, which
webmaster@1: // ends HTTP headers prematurely on some PHP versions.
webmaster@1: static $stored_headers = array();
webmaster@1:
webmaster@1: if (strlen($header)) {
webmaster@1: header($header);
webmaster@1: $stored_headers[] = $header;
webmaster@1: }
webmaster@1: return implode("\n", $stored_headers);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Get the HTTP response headers for the current page.
webmaster@1: */
webmaster@1: function drupal_get_headers() {
webmaster@1: return drupal_set_header();
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Add a feed URL for the current page.
webmaster@1: *
webmaster@1: * @param $url
webmaster@1: * A url for the feed.
webmaster@1: * @param $title
webmaster@1: * The title of the feed.
webmaster@1: */
webmaster@1: function drupal_add_feed($url = NULL, $title = '') {
webmaster@1: static $stored_feed_links = array();
webmaster@1:
webmaster@1: if (!is_null($url) && !isset($stored_feed_links[$url])) {
webmaster@1: $stored_feed_links[$url] = theme('feed_icon', $url, $title);
webmaster@1:
webmaster@1: drupal_add_link(array('rel' => 'alternate',
webmaster@1: 'type' => 'application/rss+xml',
webmaster@1: 'title' => $title,
webmaster@1: 'href' => $url));
webmaster@1: }
webmaster@1: return $stored_feed_links;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Get the feed URLs for the current page.
webmaster@1: *
webmaster@1: * @param $delimiter
webmaster@1: * A delimiter to split feeds by.
webmaster@1: */
webmaster@1: function drupal_get_feeds($delimiter = "\n") {
webmaster@1: $feeds = drupal_add_feed();
webmaster@1: return implode($feeds, $delimiter);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @name HTTP handling
webmaster@1: * @{
webmaster@1: * Functions to properly handle HTTP responses.
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Parse an array into a valid urlencoded query string.
webmaster@1: *
webmaster@1: * @param $query
webmaster@1: * The array to be processed e.g. $_GET.
webmaster@1: * @param $exclude
webmaster@1: * The array filled with keys to be excluded. Use parent[child] to exclude
webmaster@1: * nested items.
webmaster@1: * @param $parent
webmaster@1: * Should not be passed, only used in recursive calls.
webmaster@1: * @return
webmaster@1: * An urlencoded string which can be appended to/as the URL query string.
webmaster@1: */
webmaster@1: function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
webmaster@1: $params = array();
webmaster@1:
webmaster@1: foreach ($query as $key => $value) {
webmaster@1: $key = drupal_urlencode($key);
webmaster@1: if ($parent) {
webmaster@1: $key = $parent .'['. $key .']';
webmaster@1: }
webmaster@1:
webmaster@1: if (in_array($key, $exclude)) {
webmaster@1: continue;
webmaster@1: }
webmaster@1:
webmaster@1: if (is_array($value)) {
webmaster@1: $params[] = drupal_query_string_encode($value, $exclude, $key);
webmaster@1: }
webmaster@1: else {
webmaster@1: $params[] = $key .'='. drupal_urlencode($value);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: return implode('&', $params);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Prepare a destination query string for use in combination with drupal_goto().
webmaster@1: *
webmaster@1: * Used to direct the user back to the referring page after completing a form.
webmaster@1: * By default the current URL is returned. If a destination exists in the
webmaster@1: * previous request, that destination is returned. As such, a destination can
webmaster@1: * persist across multiple pages.
webmaster@1: *
webmaster@1: * @see drupal_goto()
webmaster@1: */
webmaster@1: function drupal_get_destination() {
webmaster@1: if (isset($_REQUEST['destination'])) {
webmaster@1: return 'destination='. urlencode($_REQUEST['destination']);
webmaster@1: }
webmaster@1: else {
webmaster@1: // Use $_GET here to retrieve the original path in source form.
webmaster@1: $path = isset($_GET['q']) ? $_GET['q'] : '';
webmaster@1: $query = drupal_query_string_encode($_GET, array('q'));
webmaster@1: if ($query != '') {
webmaster@1: $path .= '?'. $query;
webmaster@1: }
webmaster@1: return 'destination='. urlencode($path);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Send the user to a different Drupal page.
webmaster@1: *
webmaster@1: * This issues an on-site HTTP redirect. The function makes sure the redirected
webmaster@1: * URL is formatted correctly.
webmaster@1: *
webmaster@1: * Usually the redirected URL is constructed from this function's input
webmaster@1: * parameters. However you may override that behavior by setting a
webmaster@7: * destination in either the $_REQUEST-array (i.e. by using
webmaster@1: * the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
webmaster@1: * using a hidden form field). This is used to direct the user back to
webmaster@1: * the proper page after completing a form. For example, after editing
webmaster@1: * a post on the 'admin/content/node'-page or after having logged on using the
webmaster@1: * 'user login'-block in a sidebar. The function drupal_get_destination()
webmaster@1: * can be used to help set the destination URL.
webmaster@1: *
webmaster@1: * Drupal will ensure that messages set by drupal_set_message() and other
webmaster@1: * session data are written to the database before the user is redirected.
webmaster@1: *
webmaster@1: * This function ends the request; use it rather than a print theme('page')
webmaster@1: * statement in your menu callback.
webmaster@1: *
webmaster@1: * @param $path
webmaster@1: * A Drupal path or a full URL.
webmaster@1: * @param $query
webmaster@1: * A query string component, if any.
webmaster@1: * @param $fragment
webmaster@1: * A destination fragment identifier (named anchor).
webmaster@1: * @param $http_response_code
webmaster@1: * Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
webmaster@1: * - 301 Moved Permanently (the recommended value for most redirects)
webmaster@1: * - 302 Found (default in Drupal and PHP, sometimes used for spamming search
webmaster@1: * engines)
webmaster@1: * - 303 See Other
webmaster@1: * - 304 Not Modified
webmaster@1: * - 305 Use Proxy
webmaster@1: * - 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")
webmaster@1: * Note: Other values are defined by RFC 2616, but are rarely used and poorly
webmaster@1: * supported.
webmaster@1: * @see drupal_get_destination()
webmaster@1: */
webmaster@1: function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
webmaster@1:
webmaster@1: if (isset($_REQUEST['destination'])) {
webmaster@1: extract(parse_url(urldecode($_REQUEST['destination'])));
webmaster@1: }
webmaster@1: else if (isset($_REQUEST['edit']['destination'])) {
webmaster@1: extract(parse_url(urldecode($_REQUEST['edit']['destination'])));
webmaster@1: }
webmaster@1:
webmaster@1: $url = url($path, array('query' => $query, 'fragment' => $fragment, 'absolute' => TRUE));
webmaster@1: // Remove newlines from the URL to avoid header injection attacks.
webmaster@1: $url = str_replace(array("\n", "\r"), '', $url);
webmaster@1:
webmaster@1: // Allow modules to react to the end of the page request before redirecting.
webmaster@1: // We do not want this while running update.php.
webmaster@1: if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
webmaster@1: module_invoke_all('exit', $url);
webmaster@1: }
webmaster@1:
webmaster@1: // Even though session_write_close() is registered as a shutdown function, we
webmaster@1: // need all session data written to the database before redirecting.
webmaster@1: session_write_close();
webmaster@1:
webmaster@1: header('Location: '. $url, TRUE, $http_response_code);
webmaster@1:
webmaster@1: // The "Location" header sends a redirect status code to the HTTP daemon. In
webmaster@1: // some cases this can be wrong, so we make sure none of the code below the
webmaster@1: // drupal_goto() call gets executed upon redirection.
webmaster@1: exit();
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Generates a site off-line message.
webmaster@1: */
webmaster@1: function drupal_site_offline() {
webmaster@1: drupal_maintenance_theme();
webmaster@1: drupal_set_header('HTTP/1.1 503 Service unavailable');
webmaster@1: drupal_set_title(t('Site off-line'));
webmaster@1: print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
webmaster@1: t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Generates a 404 error if the request can not be handled.
webmaster@1: */
webmaster@1: function drupal_not_found() {
webmaster@1: drupal_set_header('HTTP/1.1 404 Not Found');
webmaster@1:
webmaster@1: watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
webmaster@1:
webmaster@1: // Keep old path for reference.
webmaster@1: if (!isset($_REQUEST['destination'])) {
webmaster@1: $_REQUEST['destination'] = $_GET['q'];
webmaster@1: }
webmaster@1:
webmaster@1: $path = drupal_get_normal_path(variable_get('site_404', ''));
webmaster@1: if ($path && $path != $_GET['q']) {
webmaster@1: // Set the active item in case there are tabs to display, or other
webmaster@1: // dependencies on the path.
webmaster@1: menu_set_active_item($path);
webmaster@1: $return = menu_execute_active_handler($path);
webmaster@1: }
webmaster@1:
webmaster@1: if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
webmaster@1: drupal_set_title(t('Page not found'));
webmaster@1: $return = t('The requested page could not be found.');
webmaster@1: }
webmaster@1:
webmaster@1: // To conserve CPU and bandwidth, omit the blocks.
webmaster@1: print theme('page', $return, FALSE);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Generates a 403 error if the request is not allowed.
webmaster@1: */
webmaster@1: function drupal_access_denied() {
webmaster@1: drupal_set_header('HTTP/1.1 403 Forbidden');
webmaster@1: watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
webmaster@1:
webmaster@1: // Keep old path for reference.
webmaster@1: if (!isset($_REQUEST['destination'])) {
webmaster@1: $_REQUEST['destination'] = $_GET['q'];
webmaster@1: }
webmaster@1:
webmaster@1: $path = drupal_get_normal_path(variable_get('site_403', ''));
webmaster@1: if ($path && $path != $_GET['q']) {
webmaster@1: // Set the active item in case there are tabs to display or other
webmaster@1: // dependencies on the path.
webmaster@1: menu_set_active_item($path);
webmaster@1: $return = menu_execute_active_handler($path);
webmaster@1: }
webmaster@1:
webmaster@1: if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
webmaster@1: drupal_set_title(t('Access denied'));
webmaster@1: $return = t('You are not authorized to access this page.');
webmaster@1: }
webmaster@1: print theme('page', $return);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Perform an HTTP request.
webmaster@1: *
webmaster@1: * This is a flexible and powerful HTTP client implementation. Correctly handles
webmaster@1: * GET, POST, PUT or any other HTTP requests. Handles redirects.
webmaster@1: *
webmaster@1: * @param $url
webmaster@1: * A string containing a fully qualified URI.
webmaster@1: * @param $headers
webmaster@1: * An array containing an HTTP header => value pair.
webmaster@1: * @param $method
webmaster@1: * A string defining the HTTP request to use.
webmaster@1: * @param $data
webmaster@1: * A string containing data to include in the request.
webmaster@1: * @param $retry
webmaster@1: * An integer representing how many times to retry the request in case of a
webmaster@1: * redirect.
webmaster@1: * @return
webmaster@1: * An object containing the HTTP request headers, response code, headers,
webmaster@1: * data and redirect status.
webmaster@1: */
webmaster@1: function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
webmaster@1: static $self_test = FALSE;
webmaster@1: $result = new stdClass();
webmaster@1: // Try to clear the drupal_http_request_fails variable if it's set. We
webmaster@1: // can't tie this call to any error because there is no surefire way to
webmaster@1: // tell whether a request has failed, so we add the check to places where
webmaster@1: // some parsing has failed.
webmaster@1: if (!$self_test && variable_get('drupal_http_request_fails', FALSE)) {
webmaster@1: $self_test = TRUE;
webmaster@1: $works = module_invoke('system', 'check_http_request');
webmaster@1: $self_test = FALSE;
webmaster@1: if (!$works) {
webmaster@1: // Do not bother with further operations if we already know that we
webmaster@1: // have no chance.
webmaster@1: $result->error = t("The server can't issue HTTP requests");
webmaster@1: return $result;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: // Parse the URL and make sure we can handle the schema.
webmaster@1: $uri = parse_url($url);
webmaster@1:
webmaster@9: if ($uri == FALSE) {
webmaster@9: $result->error = 'unable to parse URL';
webmaster@9: return $result;
webmaster@9: }
webmaster@9:
webmaster@9: if (!isset($uri['scheme'])) {
webmaster@9: $result->error = 'missing schema';
webmaster@9: return $result;
webmaster@9: }
webmaster@9:
webmaster@1: switch ($uri['scheme']) {
webmaster@1: case 'http':
webmaster@1: $port = isset($uri['port']) ? $uri['port'] : 80;
webmaster@1: $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
webmaster@1: $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
webmaster@1: break;
webmaster@1: case 'https':
webmaster@1: // Note: Only works for PHP 4.3 compiled with OpenSSL.
webmaster@1: $port = isset($uri['port']) ? $uri['port'] : 443;
webmaster@1: $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
webmaster@1: $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
webmaster@1: break;
webmaster@1: default:
webmaster@1: $result->error = 'invalid schema '. $uri['scheme'];
webmaster@1: return $result;
webmaster@1: }
webmaster@1:
webmaster@1: // Make sure the socket opened properly.
webmaster@1: if (!$fp) {
webmaster@1: // When a network error occurs, we use a negative number so it does not
webmaster@1: // clash with the HTTP status codes.
webmaster@1: $result->code = -$errno;
webmaster@1: $result->error = trim($errstr);
webmaster@1: return $result;
webmaster@1: }
webmaster@1:
webmaster@1: // Construct the path to act on.
webmaster@1: $path = isset($uri['path']) ? $uri['path'] : '/';
webmaster@1: if (isset($uri['query'])) {
webmaster@1: $path .= '?'. $uri['query'];
webmaster@1: }
webmaster@1:
webmaster@1: // Create HTTP request.
webmaster@1: $defaults = array(
webmaster@1: // RFC 2616: "non-standard ports MUST, default ports MAY be included".
webmaster@1: // We don't add the port to prevent from breaking rewrite rules checking the
webmaster@1: // host that do not take into account the port number.
webmaster@1: 'Host' => "Host: $host",
webmaster@1: 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
webmaster@1: 'Content-Length' => 'Content-Length: '. strlen($data)
webmaster@1: );
webmaster@1:
webmaster@1: // If the server url has a user then attempt to use basic authentication
webmaster@1: if (isset($uri['user'])) {
webmaster@1: $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
webmaster@1: }
webmaster@1:
webmaster@1: foreach ($headers as $header => $value) {
webmaster@1: $defaults[$header] = $header .': '. $value;
webmaster@1: }
webmaster@1:
webmaster@1: $request = $method .' '. $path ." HTTP/1.0\r\n";
webmaster@1: $request .= implode("\r\n", $defaults);
webmaster@1: $request .= "\r\n\r\n";
webmaster@1: if ($data) {
webmaster@1: $request .= $data ."\r\n";
webmaster@1: }
webmaster@1: $result->request = $request;
webmaster@1:
webmaster@1: fwrite($fp, $request);
webmaster@1:
webmaster@1: // Fetch response.
webmaster@1: $response = '';
webmaster@1: while (!feof($fp) && $chunk = fread($fp, 1024)) {
webmaster@1: $response .= $chunk;
webmaster@1: }
webmaster@1: fclose($fp);
webmaster@1:
webmaster@1: // Parse response.
webmaster@1: list($split, $result->data) = explode("\r\n\r\n", $response, 2);
webmaster@1: $split = preg_split("/\r\n|\n|\r/", $split);
webmaster@1:
webmaster@1: list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
webmaster@1: $result->headers = array();
webmaster@1:
webmaster@1: // Parse headers.
webmaster@1: while ($line = trim(array_shift($split))) {
webmaster@1: list($header, $value) = explode(':', $line, 2);
webmaster@1: if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
webmaster@1: // RFC 2109: the Set-Cookie response header comprises the token Set-
webmaster@1: // Cookie:, followed by a comma-separated list of one or more cookies.
webmaster@1: $result->headers[$header] .= ','. trim($value);
webmaster@1: }
webmaster@1: else {
webmaster@1: $result->headers[$header] = trim($value);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: $responses = array(
webmaster@1: 100 => 'Continue', 101 => 'Switching Protocols',
webmaster@1: 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
webmaster@1: 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
webmaster@1: 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',
webmaster@1: 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
webmaster@1: );
webmaster@1: // RFC 2616 states that all unknown HTTP codes must be treated the same as the
webmaster@1: // base code in their class.
webmaster@1: if (!isset($responses[$code])) {
webmaster@1: $code = floor($code / 100) * 100;
webmaster@1: }
webmaster@1:
webmaster@1: switch ($code) {
webmaster@1: case 200: // OK
webmaster@1: case 304: // Not modified
webmaster@1: break;
webmaster@1: case 301: // Moved permanently
webmaster@1: case 302: // Moved temporarily
webmaster@1: case 307: // Moved temporarily
webmaster@1: $location = $result->headers['Location'];
webmaster@1:
webmaster@1: if ($retry) {
webmaster@1: $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
webmaster@1: $result->redirect_code = $result->code;
webmaster@1: }
webmaster@1: $result->redirect_url = $location;
webmaster@1:
webmaster@1: break;
webmaster@1: default:
webmaster@1: $result->error = $text;
webmaster@1: }
webmaster@1:
webmaster@1: $result->code = $code;
webmaster@1: return $result;
webmaster@1: }
webmaster@1: /**
webmaster@1: * @} End of "HTTP handling".
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Log errors as defined by administrator.
webmaster@1: *
webmaster@1: * Error levels:
webmaster@1: * - 0 = Log errors to database.
webmaster@1: * - 1 = Log errors to database and to screen.
webmaster@1: */
webmaster@1: function drupal_error_handler($errno, $message, $filename, $line, $context) {
webmaster@7: // If the @ error suppression operator was used, error_reporting will have
webmaster@7: // been temporarily set to 0.
webmaster@1: if (error_reporting() == 0) {
webmaster@1: return;
webmaster@1: }
webmaster@1:
webmaster@1: if ($errno & (E_ALL ^ E_NOTICE)) {
webmaster@1: $types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
webmaster@1:
webmaster@1: // For database errors, we want the line number/file name of the place that
webmaster@1: // the query was originally called, not _db_query().
webmaster@1: if (isset($context[DB_ERROR])) {
webmaster@1: $backtrace = array_reverse(debug_backtrace());
webmaster@1:
webmaster@1: // List of functions where SQL queries can originate.
webmaster@1: $query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
webmaster@1:
webmaster@1: // Determine where query function was called, and adjust line/file
webmaster@1: // accordingly.
webmaster@1: foreach ($backtrace as $index => $function) {
webmaster@1: if (in_array($function['function'], $query_functions)) {
webmaster@1: $line = $backtrace[$index]['line'];
webmaster@1: $filename = $backtrace[$index]['file'];
webmaster@1: break;
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: $entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';
webmaster@1:
webmaster@1: // Force display of error messages in update.php.
webmaster@1: if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
webmaster@1: drupal_set_message($entry, 'error');
webmaster@1: }
webmaster@1:
webmaster@1: watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: function _fix_gpc_magic(&$item) {
webmaster@1: if (is_array($item)) {
webmaster@1: array_walk($item, '_fix_gpc_magic');
webmaster@1: }
webmaster@1: else {
webmaster@1: $item = stripslashes($item);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Helper function to strip slashes from $_FILES skipping over the tmp_name keys
webmaster@1: * since PHP generates single backslashes for file paths on Windows systems.
webmaster@1: *
webmaster@1: * tmp_name does not have backslashes added see
webmaster@1: * http://php.net/manual/en/features.file-upload.php#42280
webmaster@1: */
webmaster@1: function _fix_gpc_magic_files(&$item, $key) {
webmaster@1: if ($key != 'tmp_name') {
webmaster@1: if (is_array($item)) {
webmaster@1: array_walk($item, '_fix_gpc_magic_files');
webmaster@1: }
webmaster@1: else {
webmaster@1: $item = stripslashes($item);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Fix double-escaping problems caused by "magic quotes" in some PHP installations.
webmaster@1: */
webmaster@1: function fix_gpc_magic() {
webmaster@1: static $fixed = FALSE;
webmaster@1: if (!$fixed && ini_get('magic_quotes_gpc')) {
webmaster@1: array_walk($_GET, '_fix_gpc_magic');
webmaster@1: array_walk($_POST, '_fix_gpc_magic');
webmaster@1: array_walk($_COOKIE, '_fix_gpc_magic');
webmaster@1: array_walk($_REQUEST, '_fix_gpc_magic');
webmaster@1: array_walk($_FILES, '_fix_gpc_magic_files');
webmaster@1: $fixed = TRUE;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Translate strings to the page language or a given language.
webmaster@1: *
webmaster@1: * All human-readable text that will be displayed somewhere within a page should
webmaster@1: * be run through the t() function.
webmaster@1: *
webmaster@1: * Examples:
webmaster@1: * @code
webmaster@1: * if (!$info || !$info['extension']) {
webmaster@1: * form_set_error('picture_upload', t('The uploaded file was not an image.'));
webmaster@1: * }
webmaster@1: *
webmaster@1: * $form['submit'] = array(
webmaster@1: * '#type' => 'submit',
webmaster@1: * '#value' => t('Log in'),
webmaster@1: * );
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * Any text within t() can be extracted by translators and changed into
webmaster@1: * the equivalent text in their native language.
webmaster@1: *
webmaster@1: * Special variables called "placeholders" are used to signal dynamic
webmaster@1: * information in a string which should not be translated. Placeholders
webmaster@1: * can also be used for text that may change from time to time
webmaster@1: * (such as link paths) to be changed without requiring updates to translations.
webmaster@1: *
webmaster@1: * For example:
webmaster@1: * @code
webmaster@1: * $output = t('There are currently %members and %visitors online.', array(
webmaster@1: * '%members' => format_plural($total_users, '1 user', '@count users'),
webmaster@1: * '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * There are three styles of placeholders:
webmaster@1: * - !variable, which indicates that the text should be inserted as-is. This is
webmaster@1: * useful for inserting variables into things like e-mail.
webmaster@1: * @code
webmaster@1: * $message[] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE))));
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * - @variable, which indicates that the text should be run through check_plain,
webmaster@1: * to escape HTML characters. Use this for any output that's displayed within
webmaster@1: * a Drupal page.
webmaster@1: * @code
webmaster@1: * drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * - %variable, which indicates that the string should be HTML escaped and
webmaster@1: * highlighted with theme_placeholder() which shows up by default as
webmaster@1: * emphasized.
webmaster@1: * @code
webmaster@1: * $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * When using t(), try to put entire sentences and strings in one t() call.
webmaster@1: * This makes it easier for translators, as it provides context as to what each
webmaster@1: * word refers to. HTML markup within translation strings is allowed, but should
webmaster@1: * be avoided if possible. The exception are embedded links; link titles add a
webmaster@1: * context for translators, so should be kept in the main string.
webmaster@1: *
webmaster@1: * Here is an example of incorrect usage of t():
webmaster@1: * @code
webmaster@1: * $output .= t('
Go to the @contact-page.
', array('@contact-page' => l(t('contact page'), 'contact')));
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * Here is an example of t() used correctly:
webmaster@1: * @code
webmaster@1: * $output .= '
'. t('Go to the contact page.', array('@contact-page' => url('contact'))) .'
';
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * Also avoid escaping quotation marks wherever possible.
webmaster@1: *
webmaster@1: * Incorrect:
webmaster@1: * @code
webmaster@1: * $output .= t('Don\'t click me.');
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * Correct:
webmaster@1: * @code
webmaster@1: * $output .= t("Don't click me.");
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * @param $string
webmaster@1: * A string containing the English string to translate.
webmaster@1: * @param $args
webmaster@1: * An associative array of replacements to make after translation. Incidences
webmaster@1: * of any key in this array are replaced with the corresponding value.
webmaster@1: * Based on the first character of the key, the value is escaped and/or themed:
webmaster@1: * - !variable: inserted as is
webmaster@1: * - @variable: escape plain text to HTML (check_plain)
webmaster@1: * - %variable: escape text and theme as a placeholder for user-submitted
webmaster@1: * content (check_plain + theme_placeholder)
webmaster@1: * @param $langcode
webmaster@1: * Optional language code to translate to a language other than what is used
webmaster@1: * to display the page.
webmaster@1: * @return
webmaster@1: * The translated string.
webmaster@1: */
webmaster@1: function t($string, $args = array(), $langcode = NULL) {
webmaster@1: global $language;
webmaster@1: static $custom_strings;
webmaster@1:
webmaster@1: $langcode = isset($langcode) ? $langcode : $language->language;
webmaster@1:
webmaster@1: // First, check for an array of customized strings. If present, use the array
webmaster@1: // *instead of* database lookups. This is a high performance way to provide a
webmaster@1: // handful of string replacements. See settings.php for examples.
webmaster@1: // Cache the $custom_strings variable to improve performance.
webmaster@1: if (!isset($custom_strings[$langcode])) {
webmaster@1: $custom_strings[$langcode] = variable_get('locale_custom_strings_'. $langcode, array());
webmaster@1: }
webmaster@1: // Custom strings work for English too, even if locale module is disabled.
webmaster@1: if (isset($custom_strings[$langcode][$string])) {
webmaster@1: $string = $custom_strings[$langcode][$string];
webmaster@1: }
webmaster@1: // Translate with locale module if enabled.
webmaster@1: elseif (function_exists('locale') && $langcode != 'en') {
webmaster@1: $string = locale($string, $langcode);
webmaster@1: }
webmaster@1: if (empty($args)) {
webmaster@1: return $string;
webmaster@1: }
webmaster@1: else {
webmaster@1: // Transform arguments before inserting them.
webmaster@1: foreach ($args as $key => $value) {
webmaster@1: switch ($key[0]) {
webmaster@1: case '@':
webmaster@1: // Escaped only.
webmaster@1: $args[$key] = check_plain($value);
webmaster@1: break;
webmaster@1:
webmaster@1: case '%':
webmaster@1: default:
webmaster@1: // Escaped and placeholder.
webmaster@1: $args[$key] = theme('placeholder', $value);
webmaster@1: break;
webmaster@1:
webmaster@1: case '!':
webmaster@1: // Pass-through.
webmaster@1: }
webmaster@1: }
webmaster@1: return strtr($string, $args);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @defgroup validation Input validation
webmaster@1: * @{
webmaster@1: * Functions to validate user input.
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Verify the syntax of the given e-mail address.
webmaster@1: *
webmaster@1: * Empty e-mail addresses are allowed. See RFC 2822 for details.
webmaster@1: *
webmaster@1: * @param $mail
webmaster@1: * A string containing an e-mail address.
webmaster@1: * @return
webmaster@1: * TRUE if the address is in a valid format.
webmaster@1: */
webmaster@1: function valid_email_address($mail) {
webmaster@1: $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
webmaster@1: $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
webmaster@1: $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
webmaster@1: $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
webmaster@1:
webmaster@1: return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Verify the syntax of the given URL.
webmaster@1: *
webmaster@1: * This function should only be used on actual URLs. It should not be used for
webmaster@1: * Drupal menu paths, which can contain arbitrary characters.
webmaster@1: *
webmaster@1: * @param $url
webmaster@1: * The URL to verify.
webmaster@1: * @param $absolute
webmaster@1: * Whether the URL is absolute (beginning with a scheme such as "http:").
webmaster@1: * @return
webmaster@1: * TRUE if the URL is in a valid format.
webmaster@1: */
webmaster@1: function valid_url($url, $absolute = FALSE) {
webmaster@1: $allowed_characters = '[a-z0-9\/:_\-_\.\?\$,;~=#&%\+]';
webmaster@1: if ($absolute) {
webmaster@1: return preg_match("/^(http|https|ftp):\/\/". $allowed_characters ."+$/i", $url);
webmaster@1: }
webmaster@1: else {
webmaster@1: return preg_match("/^". $allowed_characters ."+$/i", $url);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @} End of "defgroup validation".
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Register an event for the current visitor (hostname/IP) to the flood control mechanism.
webmaster@1: *
webmaster@1: * @param $name
webmaster@1: * The name of an event.
webmaster@1: */
webmaster@1: function flood_register_event($name) {
webmaster@1: db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, ip_address(), time());
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
webmaster@1: *
webmaster@1: * The user is allowed to proceed if he did not trigger the specified event more
webmaster@1: * than $threshold times per hour.
webmaster@1: *
webmaster@1: * @param $name
webmaster@1: * The name of the event.
webmaster@1: * @param $number
webmaster@1: * The maximum number of the specified event per hour (per visitor).
webmaster@1: * @return
webmaster@1: * True if the user did not exceed the hourly threshold. False otherwise.
webmaster@1: */
webmaster@1: function flood_is_allowed($name, $threshold) {
webmaster@1: $number = db_result(db_query("SELECT COUNT(*) FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, ip_address(), time() - 3600));
webmaster@1: return ($number < $threshold ? TRUE : FALSE);
webmaster@1: }
webmaster@1:
webmaster@1: function check_file($filename) {
webmaster@1: return is_uploaded_file($filename);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Prepare a URL for use in an HTML attribute. Strips harmful protocols.
webmaster@1: */
webmaster@1: function check_url($uri) {
webmaster@1: return filter_xss_bad_protocol($uri, FALSE);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @defgroup format Formatting
webmaster@1: * @{
webmaster@1: * Functions to format numbers, strings, dates, etc.
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Formats an RSS channel.
webmaster@1: *
webmaster@1: * Arbitrary elements may be added using the $args associative array.
webmaster@1: */
webmaster@1: function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
webmaster@1: global $language;
webmaster@1: $langcode = $langcode ? $langcode : $language->language;
webmaster@1:
webmaster@1: $output = "\n";
webmaster@1: $output .= ' '. check_plain($title) ."\n";
webmaster@1: $output .= ' '. check_url($link) ."\n";
webmaster@1:
webmaster@1: // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
webmaster@1: // We strip all HTML tags, but need to prevent double encoding from properly
webmaster@1: // escaped source data (such as & becoming &).
webmaster@1: $output .= ' '. check_plain(decode_entities(strip_tags($description))) ."\n";
webmaster@1: $output .= ' '. check_plain($langcode) ."\n";
webmaster@1: $output .= format_xml_elements($args);
webmaster@1: $output .= $items;
webmaster@1: $output .= "\n";
webmaster@1:
webmaster@1: return $output;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Format a single RSS item.
webmaster@1: *
webmaster@1: * Arbitrary elements may be added using the $args associative array.
webmaster@1: */
webmaster@1: function format_rss_item($title, $link, $description, $args = array()) {
webmaster@1: $output = "\n";
webmaster@1: $output .= ' '. check_plain($title) ."\n";
webmaster@1: $output .= ' '. check_url($link) ."\n";
webmaster@1: $output .= ' '. check_plain($description) ."\n";
webmaster@1: $output .= format_xml_elements($args);
webmaster@1: $output .= "\n";
webmaster@1:
webmaster@1: return $output;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Format XML elements.
webmaster@1: *
webmaster@1: * @param $array
webmaster@1: * An array where each item represent an element and is either a:
webmaster@1: * - (key => value) pair (value)
webmaster@1: * - Associative array with fields:
webmaster@1: * - 'key': element name
webmaster@1: * - 'value': element contents
webmaster@1: * - 'attributes': associative array of element attributes
webmaster@1: *
webmaster@1: * In both cases, 'value' can be a simple string, or it can be another array
webmaster@1: * with the same format as $array itself for nesting.
webmaster@1: */
webmaster@1: function format_xml_elements($array) {
webmaster@1: $output = '';
webmaster@1: foreach ($array as $key => $value) {
webmaster@1: if (is_numeric($key)) {
webmaster@1: if ($value['key']) {
webmaster@1: $output .= ' <'. $value['key'];
webmaster@1: if (isset($value['attributes']) && is_array($value['attributes'])) {
webmaster@1: $output .= drupal_attributes($value['attributes']);
webmaster@1: }
webmaster@1:
webmaster@1: if ($value['value'] != '') {
webmaster@1: $output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .''. $value['key'] .">\n";
webmaster@1: }
webmaster@1: else {
webmaster@1: $output .= " />\n";
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1: else {
webmaster@1: $output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."$key>\n";
webmaster@1: }
webmaster@1: }
webmaster@1: return $output;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Format a string containing a count of items.
webmaster@1: *
webmaster@1: * This function ensures that the string is pluralized correctly. Since t() is
webmaster@1: * called by this function, make sure not to pass already-localized strings to
webmaster@1: * it.
webmaster@1: *
webmaster@1: * For example:
webmaster@1: * @code
webmaster@1: * $output = format_plural($node->comment_count, '1 comment', '@count comments');
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * Example with additional replacements:
webmaster@1: * @code
webmaster@1: * $output = format_plural($update_count,
webmaster@1: * 'Changed the content type of 1 post from %old-type to %new-type.',
webmaster@1: * 'Changed the content type of @count posts from %old-type to %new-type.',
webmaster@1: * array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * @param $count
webmaster@1: * The item count to display.
webmaster@1: * @param $singular
webmaster@1: * The string for the singular case. Please make sure it is clear this is
webmaster@1: * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
webmaster@1: * Do not use @count in the singular string.
webmaster@1: * @param $plural
webmaster@1: * The string for the plural case. Please make sure it is clear this is plural,
webmaster@1: * to ease translation. Use @count in place of the item count, as in "@count
webmaster@1: * new comments".
webmaster@1: * @param $args
webmaster@1: * An associative array of replacements to make after translation. Incidences
webmaster@1: * of any key in this array are replaced with the corresponding value.
webmaster@1: * Based on the first character of the key, the value is escaped and/or themed:
webmaster@1: * - !variable: inserted as is
webmaster@1: * - @variable: escape plain text to HTML (check_plain)
webmaster@1: * - %variable: escape text and theme as a placeholder for user-submitted
webmaster@1: * content (check_plain + theme_placeholder)
webmaster@1: * Note that you do not need to include @count in this array.
webmaster@1: * This replacement is done automatically for the plural case.
webmaster@1: * @param $langcode
webmaster@1: * Optional language code to translate to a language other than
webmaster@1: * what is used to display the page.
webmaster@1: * @return
webmaster@1: * A translated string.
webmaster@1: */
webmaster@1: function format_plural($count, $singular, $plural, $args = array(), $langcode = NULL) {
webmaster@1: $args['@count'] = $count;
webmaster@1: if ($count == 1) {
webmaster@1: return t($singular, $args, $langcode);
webmaster@1: }
webmaster@1:
webmaster@1: // Get the plural index through the gettext formula.
webmaster@1: $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, $langcode) : -1;
webmaster@1: // Backwards compatibility.
webmaster@1: if ($index < 0) {
webmaster@1: return t($plural, $args, $langcode);
webmaster@1: }
webmaster@1: else {
webmaster@1: switch ($index) {
webmaster@1: case "0":
webmaster@1: return t($singular, $args, $langcode);
webmaster@1: case "1":
webmaster@1: return t($plural, $args, $langcode);
webmaster@1: default:
webmaster@1: unset($args['@count']);
webmaster@1: $args['@count['. $index .']'] = $count;
webmaster@1: return t(strtr($plural, array('@count' => '@count['. $index .']')), $args, $langcode);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Parse a given byte count.
webmaster@1: *
webmaster@1: * @param $size
webmaster@1: * A size expressed as a number of bytes with optional SI size and unit
webmaster@1: * suffix (e.g. 2, 3K, 5MB, 10G).
webmaster@1: * @return
webmaster@1: * An integer representation of the size.
webmaster@1: */
webmaster@1: function parse_size($size) {
webmaster@1: $suffixes = array(
webmaster@1: '' => 1,
webmaster@1: 'k' => 1024,
webmaster@1: 'm' => 1048576, // 1024 * 1024
webmaster@1: 'g' => 1073741824, // 1024 * 1024 * 1024
webmaster@1: );
webmaster@1: if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
webmaster@1: return $match[1] * $suffixes[drupal_strtolower($match[2])];
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Generate a string representation for the given byte count.
webmaster@1: *
webmaster@1: * @param $size
webmaster@1: * A size in bytes.
webmaster@1: * @param $langcode
webmaster@1: * Optional language code to translate to a language other than what is used
webmaster@1: * to display the page.
webmaster@1: * @return
webmaster@1: * A translated string representation of the size.
webmaster@1: */
webmaster@1: function format_size($size, $langcode = NULL) {
webmaster@1: if ($size < 1024) {
webmaster@1: return format_plural($size, '1 byte', '@count bytes', array(), $langcode);
webmaster@1: }
webmaster@1: else {
webmaster@1: $size = round($size / 1024, 2);
webmaster@1: $suffix = t('KB', array(), $langcode);
webmaster@1: if ($size >= 1024) {
webmaster@1: $size = round($size / 1024, 2);
webmaster@1: $suffix = t('MB', array(), $langcode);
webmaster@1: }
webmaster@1: return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix), $langcode);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Format a time interval with the requested granularity.
webmaster@1: *
webmaster@1: * @param $timestamp
webmaster@1: * The length of the interval in seconds.
webmaster@1: * @param $granularity
webmaster@1: * How many different units to display in the string.
webmaster@1: * @param $langcode
webmaster@1: * Optional language code to translate to a language other than
webmaster@1: * what is used to display the page.
webmaster@1: * @return
webmaster@1: * A translated string representation of the interval.
webmaster@1: */
webmaster@1: function format_interval($timestamp, $granularity = 2, $langcode = NULL) {
webmaster@1: $units = array('1 year|@count years' => 31536000, '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);
webmaster@1: $output = '';
webmaster@1: foreach ($units as $key => $value) {
webmaster@1: $key = explode('|', $key);
webmaster@1: if ($timestamp >= $value) {
webmaster@1: $output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1], array(), $langcode);
webmaster@1: $timestamp %= $value;
webmaster@1: $granularity--;
webmaster@1: }
webmaster@1:
webmaster@1: if ($granularity == 0) {
webmaster@1: break;
webmaster@1: }
webmaster@1: }
webmaster@1: return $output ? $output : t('0 sec', array(), $langcode);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Format a date with the given configured format or a custom format string.
webmaster@1: *
webmaster@1: * Drupal allows administrators to select formatting strings for 'small',
webmaster@1: * 'medium' and 'large' date formats. This function can handle these formats,
webmaster@1: * as well as any custom format.
webmaster@1: *
webmaster@1: * @param $timestamp
webmaster@1: * The exact date to format, as a UNIX timestamp.
webmaster@1: * @param $type
webmaster@1: * The format to use. Can be "small", "medium" or "large" for the preconfigured
webmaster@1: * date formats. If "custom" is specified, then $format is required as well.
webmaster@1: * @param $format
webmaster@1: * A PHP date format string as required by date(). A backslash should be used
webmaster@1: * before a character to avoid interpreting the character as part of a date
webmaster@1: * format.
webmaster@1: * @param $timezone
webmaster@1: * Time zone offset in seconds; if omitted, the user's time zone is used.
webmaster@1: * @param $langcode
webmaster@1: * Optional language code to translate to a language other than what is used
webmaster@1: * to display the page.
webmaster@1: * @return
webmaster@1: * A translated date string in the requested format.
webmaster@1: */
webmaster@1: function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
webmaster@1: if (!isset($timezone)) {
webmaster@1: global $user;
webmaster@1: if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
webmaster@1: $timezone = $user->timezone;
webmaster@1: }
webmaster@1: else {
webmaster@1: $timezone = variable_get('date_default_timezone', 0);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: $timestamp += $timezone;
webmaster@1:
webmaster@1: switch ($type) {
webmaster@1: case 'small':
webmaster@1: $format = variable_get('date_format_short', 'm/d/Y - H:i');
webmaster@1: break;
webmaster@1: case 'large':
webmaster@1: $format = variable_get('date_format_long', 'l, F j, Y - H:i');
webmaster@1: break;
webmaster@1: case 'custom':
webmaster@1: // No change to format.
webmaster@1: break;
webmaster@1: case 'medium':
webmaster@1: default:
webmaster@1: $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
webmaster@1: }
webmaster@1:
webmaster@1: $max = strlen($format);
webmaster@1: $date = '';
webmaster@1: for ($i = 0; $i < $max; $i++) {
webmaster@1: $c = $format[$i];
webmaster@1: if (strpos('AaDlM', $c) !== FALSE) {
webmaster@1: $date .= t(gmdate($c, $timestamp), array(), $langcode);
webmaster@1: }
webmaster@1: else if ($c == 'F') {
webmaster@1: // Special treatment for long month names: May is both an abbreviation
webmaster@1: // and a full month name in English, but other languages have
webmaster@1: // different abbreviations.
webmaster@1: $date .= trim(t('!long-month-name '. gmdate($c, $timestamp), array('!long-month-name' => ''), $langcode));
webmaster@1: }
webmaster@1: else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
webmaster@1: $date .= gmdate($c, $timestamp);
webmaster@1: }
webmaster@1: else if ($c == 'r') {
webmaster@1: $date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone, $langcode);
webmaster@1: }
webmaster@1: else if ($c == 'O') {
webmaster@1: $date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
webmaster@1: }
webmaster@1: else if ($c == 'Z') {
webmaster@1: $date .= $timezone;
webmaster@1: }
webmaster@1: else if ($c == '\\') {
webmaster@1: $date .= $format[++$i];
webmaster@1: }
webmaster@1: else {
webmaster@1: $date .= $c;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: return $date;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @} End of "defgroup format".
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Generate a URL from a Drupal menu path. Will also pass-through existing URLs.
webmaster@1: *
webmaster@1: * @param $path
webmaster@1: * The Drupal path being linked to, such as "admin/content/node", or an
webmaster@1: * existing URL like "http://drupal.org/". The special path
webmaster@1: * '' may also be given and will generate the site's base URL.
webmaster@1: * @param $options
webmaster@1: * An associative array of additional options, with the following keys:
webmaster@7: * - 'query'
webmaster@1: * A query string to append to the link, or an array of query key/value
webmaster@1: * properties.
webmaster@7: * - 'fragment'
webmaster@1: * A fragment identifier (or named anchor) to append to the link.
webmaster@1: * Do not include the '#' character.
webmaster@7: * - 'absolute' (default FALSE)
webmaster@1: * Whether to force the output to be an absolute link (beginning with
webmaster@1: * http:). Useful for links that will be displayed outside the site, such
webmaster@1: * as in an RSS feed.
webmaster@7: * - 'alias' (default FALSE)
webmaster@1: * Whether the given path is an alias already.
webmaster@7: * - 'external'
webmaster@1: * Whether the given path is an external URL.
webmaster@7: * - 'language'
webmaster@1: * An optional language object. Used to build the URL to link to and
webmaster@1: * look up the proper alias for the link.
webmaster@7: * - 'base_url'
webmaster@1: * Only used internally, to modify the base URL when a language dependent
webmaster@1: * URL requires so.
webmaster@7: * - 'prefix'
webmaster@1: * Only used internally, to modify the path when a language dependent URL
webmaster@1: * requires so.
webmaster@1: * @return
webmaster@1: * A string containing a URL to the given path.
webmaster@1: *
webmaster@1: * When creating links in modules, consider whether l() could be a better
webmaster@1: * alternative than url().
webmaster@1: */
webmaster@1: function url($path = NULL, $options = array()) {
webmaster@1: // Merge in defaults.
webmaster@1: $options += array(
webmaster@1: 'fragment' => '',
webmaster@1: 'query' => '',
webmaster@1: 'absolute' => FALSE,
webmaster@1: 'alias' => FALSE,
webmaster@1: 'prefix' => ''
webmaster@1: );
webmaster@1: if (!isset($options['external'])) {
webmaster@1: // Return an external link if $path contains an allowed absolute URL.
webmaster@1: // Only call the slow filter_xss_bad_protocol if $path contains a ':' before
webmaster@1: // any / ? or #.
webmaster@1: $colonpos = strpos($path, ':');
webmaster@1: $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path));
webmaster@1: }
webmaster@1:
webmaster@1: // May need language dependent rewriting if language.inc is present.
webmaster@1: if (function_exists('language_url_rewrite')) {
webmaster@1: language_url_rewrite($path, $options);
webmaster@1: }
webmaster@1: if ($options['fragment']) {
webmaster@1: $options['fragment'] = '#'. $options['fragment'];
webmaster@1: }
webmaster@1: if (is_array($options['query'])) {
webmaster@1: $options['query'] = drupal_query_string_encode($options['query']);
webmaster@1: }
webmaster@1:
webmaster@1: if ($options['external']) {
webmaster@1: // Split off the fragment.
webmaster@1: if (strpos($path, '#') !== FALSE) {
webmaster@1: list($path, $old_fragment) = explode('#', $path, 2);
webmaster@1: if (isset($old_fragment) && !$options['fragment']) {
webmaster@1: $options['fragment'] = '#'. $old_fragment;
webmaster@1: }
webmaster@1: }
webmaster@1: // Append the query.
webmaster@1: if ($options['query']) {
webmaster@1: $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $options['query'];
webmaster@1: }
webmaster@1: // Reassemble.
webmaster@1: return $path . $options['fragment'];
webmaster@1: }
webmaster@1:
webmaster@1: global $base_url;
webmaster@1: static $script;
webmaster@1: static $clean_url;
webmaster@1:
webmaster@1: if (!isset($script)) {
webmaster@1: // On some web servers, such as IIS, we can't omit "index.php". So, we
webmaster@1: // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
webmaster@1: // Apache.
webmaster@1: $script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php' : '';
webmaster@1: }
webmaster@1:
webmaster@1: // Cache the clean_url variable to improve performance.
webmaster@1: if (!isset($clean_url)) {
webmaster@1: $clean_url = (bool)variable_get('clean_url', '0');
webmaster@1: }
webmaster@1:
webmaster@1: if (!isset($options['base_url'])) {
webmaster@1: // The base_url might be rewritten from the language rewrite in domain mode.
webmaster@1: $options['base_url'] = $base_url;
webmaster@1: }
webmaster@1:
webmaster@1: // Preserve the original path before aliasing.
webmaster@1: $original_path = $path;
webmaster@1:
webmaster@1: // The special path '' links to the default front page.
webmaster@1: if ($path == '') {
webmaster@1: $path = '';
webmaster@1: }
webmaster@1: elseif (!empty($path) && !$options['alias']) {
webmaster@1: $path = drupal_get_path_alias($path, isset($options['language']) ? $options['language']->language : '');
webmaster@1: }
webmaster@1:
webmaster@1: if (function_exists('custom_url_rewrite_outbound')) {
webmaster@1: // Modules may alter outbound links by reference.
webmaster@1: custom_url_rewrite_outbound($path, $options, $original_path);
webmaster@1: }
webmaster@1:
webmaster@1: $base = $options['absolute'] ? $options['base_url'] .'/' : base_path();
webmaster@1: $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
webmaster@1: $path = drupal_urlencode($prefix . $path);
webmaster@1:
webmaster@1: if ($clean_url) {
webmaster@1: // With Clean URLs.
webmaster@1: if ($options['query']) {
webmaster@1: return $base . $path .'?'. $options['query'] . $options['fragment'];
webmaster@1: }
webmaster@1: else {
webmaster@1: return $base . $path . $options['fragment'];
webmaster@1: }
webmaster@1: }
webmaster@1: else {
webmaster@1: // Without Clean URLs.
webmaster@1: $variables = array();
webmaster@1: if (!empty($path)) {
webmaster@1: $variables[] = 'q='. $path;
webmaster@1: }
webmaster@1: if (!empty($options['query'])) {
webmaster@1: $variables[] = $options['query'];
webmaster@1: }
webmaster@1: if ($query = join('&', $variables)) {
webmaster@1: return $base . $script .'?'. $query . $options['fragment'];
webmaster@1: }
webmaster@1: else {
webmaster@1: return $base . $options['fragment'];
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Format an attribute string to insert in a tag.
webmaster@1: *
webmaster@1: * @param $attributes
webmaster@1: * An associative array of HTML attributes.
webmaster@1: * @return
webmaster@1: * An HTML string ready for insertion in a tag.
webmaster@1: */
webmaster@1: function drupal_attributes($attributes = array()) {
webmaster@1: if (is_array($attributes)) {
webmaster@1: $t = '';
webmaster@1: foreach ($attributes as $key => $value) {
webmaster@1: $t .= " $key=".'"'. check_plain($value) .'"';
webmaster@1: }
webmaster@1: return $t;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Format an internal Drupal link.
webmaster@1: *
webmaster@1: * This function correctly handles aliased paths, and allows themes to highlight
webmaster@1: * links to the current page correctly, so all internal links output by modules
webmaster@1: * should be generated by this function if possible.
webmaster@1: *
webmaster@1: * @param $text
webmaster@1: * The text to be enclosed with the anchor tag.
webmaster@1: * @param $path
webmaster@1: * The Drupal path being linked to, such as "admin/content/node". Can be an
webmaster@1: * external or internal URL.
webmaster@1: * - If you provide the full URL, it will be considered an external URL.
webmaster@1: * - If you provide only the path (e.g. "admin/content/node"), it is
webmaster@1: * considered an internal link. In this case, it must be a system URL
webmaster@1: * as the url() function will generate the alias.
webmaster@1: * - If you provide '', it generates a link to the site's
webmaster@1: * base URL (again via the url() function).
webmaster@1: * - If you provide a path, and 'alias' is set to TRUE (see below), it is
webmaster@1: * used as is.
webmaster@1: * @param $options
webmaster@1: * An associative array of additional options, with the following keys:
webmaster@7: * - 'attributes'
webmaster@1: * An associative array of HTML attributes to apply to the anchor tag.
webmaster@7: * - 'query'
webmaster@1: * A query string to append to the link, or an array of query key/value
webmaster@1: * properties.
webmaster@7: * - 'fragment'
webmaster@1: * A fragment identifier (named anchor) to append to the link.
webmaster@1: * Do not include the '#' character.
webmaster@7: * - 'absolute' (default FALSE)
webmaster@1: * Whether to force the output to be an absolute link (beginning with
webmaster@1: * http:). Useful for links that will be displayed outside the site, such
webmaster@1: * as in an RSS feed.
webmaster@7: * - 'html' (default FALSE)
webmaster@1: * Whether the title is HTML, or just plain-text. For example for making
webmaster@1: * an image a link, this must be set to TRUE, or else you will see the
webmaster@1: * escaped HTML.
webmaster@7: * - 'alias' (default FALSE)
webmaster@1: * Whether the given path is an alias already.
webmaster@1: * @return
webmaster@1: * an HTML string containing a link to the given path.
webmaster@1: */
webmaster@1: function l($text, $path, $options = array()) {
webmaster@1: // Merge in defaults.
webmaster@1: $options += array(
webmaster@1: 'attributes' => array(),
webmaster@1: 'html' => FALSE,
webmaster@1: );
webmaster@1:
webmaster@1: // Append active class.
webmaster@1: if ($path == $_GET['q'] || ($path == '' && drupal_is_front_page())) {
webmaster@1: if (isset($options['attributes']['class'])) {
webmaster@1: $options['attributes']['class'] .= ' active';
webmaster@1: }
webmaster@1: else {
webmaster@1: $options['attributes']['class'] = 'active';
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
webmaster@1: // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
webmaster@1: if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
webmaster@1: $options['attributes']['title'] = strip_tags($options['attributes']['title']);
webmaster@1: }
webmaster@1:
webmaster@1: return ''. ($options['html'] ? $text : check_plain($text)) .'';
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Perform end-of-request tasks.
webmaster@1: *
webmaster@1: * This function sets the page cache if appropriate, and allows modules to
webmaster@1: * react to the closing of the page by calling hook_exit().
webmaster@1: */
webmaster@1: function drupal_page_footer() {
webmaster@1: if (variable_get('cache', CACHE_DISABLED) != CACHE_DISABLED) {
webmaster@1: page_set_cache();
webmaster@1: }
webmaster@1:
webmaster@1: module_invoke_all('exit');
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Form an associative array from a linear array.
webmaster@1: *
webmaster@1: * This function walks through the provided array and constructs an associative
webmaster@1: * array out of it. The keys of the resulting array will be the values of the
webmaster@1: * input array. The values will be the same as the keys unless a function is
webmaster@1: * specified, in which case the output of the function is used for the values
webmaster@1: * instead.
webmaster@1: *
webmaster@1: * @param $array
webmaster@1: * A linear array.
webmaster@1: * @param $function
webmaster@1: * A name of a function to apply to all values before output.
webmaster@1: * @result
webmaster@1: * An associative array.
webmaster@1: */
webmaster@1: function drupal_map_assoc($array, $function = NULL) {
webmaster@1: if (!isset($function)) {
webmaster@1: $result = array();
webmaster@1: foreach ($array as $value) {
webmaster@1: $result[$value] = $value;
webmaster@1: }
webmaster@1: return $result;
webmaster@1: }
webmaster@1: elseif (function_exists($function)) {
webmaster@1: $result = array();
webmaster@1: foreach ($array as $value) {
webmaster@1: $result[$value] = $function($value);
webmaster@1: }
webmaster@1: return $result;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Evaluate a string of PHP code.
webmaster@1: *
webmaster@1: * This is a wrapper around PHP's eval(). It uses output buffering to capture both
webmaster@1: * returned and printed text. Unlike eval(), we require code to be surrounded by
webmaster@1: * tags; in other words, we evaluate the code as if it were a stand-alone
webmaster@1: * PHP file.
webmaster@1: *
webmaster@1: * Using this wrapper also ensures that the PHP code which is evaluated can not
webmaster@1: * overwrite any variables in the calling code, unlike a regular eval() call.
webmaster@1: *
webmaster@1: * @param $code
webmaster@1: * The code to evaluate.
webmaster@1: * @return
webmaster@1: * A string containing the printed output of the code, followed by the returned
webmaster@1: * output of the code.
webmaster@1: */
webmaster@1: function drupal_eval($code) {
webmaster@1: global $theme_path, $theme_info, $conf;
webmaster@1:
webmaster@1: // Store current theme path.
webmaster@1: $old_theme_path = $theme_path;
webmaster@1:
webmaster@1: // Restore theme_path to the theme, as long as drupal_eval() executes,
webmaster@1: // so code evaluted will not see the caller module as the current theme.
webmaster@1: // If theme info is not initialized get the path from theme_default.
webmaster@1: if (!isset($theme_info)) {
webmaster@1: $theme_path = drupal_get_path('theme', $conf['theme_default']);
webmaster@1: }
webmaster@1: else {
webmaster@1: $theme_path = dirname($theme_info->filename);
webmaster@1: }
webmaster@1:
webmaster@1: ob_start();
webmaster@1: print eval('?>'. $code);
webmaster@1: $output = ob_get_contents();
webmaster@1: ob_end_clean();
webmaster@1:
webmaster@1: // Recover original theme path.
webmaster@1: $theme_path = $old_theme_path;
webmaster@1:
webmaster@1: return $output;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Returns the path to a system item (module, theme, etc.).
webmaster@1: *
webmaster@1: * @param $type
webmaster@1: * The type of the item (i.e. theme, theme_engine, module).
webmaster@1: * @param $name
webmaster@1: * The name of the item for which the path is requested.
webmaster@1: *
webmaster@1: * @return
webmaster@1: * The path to the requested item.
webmaster@1: */
webmaster@1: function drupal_get_path($type, $name) {
webmaster@1: return dirname(drupal_get_filename($type, $name));
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Returns the base URL path of the Drupal installation.
webmaster@1: * At the very least, this will always default to /.
webmaster@1: */
webmaster@1: function base_path() {
webmaster@1: return $GLOBALS['base_path'];
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Provide a substitute clone() function for PHP4.
webmaster@1: */
webmaster@1: function drupal_clone($object) {
webmaster@1: return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Add a tag to the page's HEAD.
webmaster@1: */
webmaster@1: function drupal_add_link($attributes) {
webmaster@1: drupal_set_html_head('\n");
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Adds a CSS file to the stylesheet queue.
webmaster@1: *
webmaster@1: * @param $path
webmaster@1: * (optional) The path to the CSS file relative to the base_path(), e.g.,
webmaster@1: * /modules/devel/devel.css.
webmaster@1: *
webmaster@1: * Modules should always prefix the names of their CSS files with the module
webmaster@1: * name, for example: system-menus.css rather than simply menus.css. Themes
webmaster@1: * can override module-supplied CSS files based on their filenames, and this
webmaster@1: * prefixing helps prevent confusing name collisions for theme developers.
webmaster@3: * See drupal_get_css where the overrides are performed.
webmaster@1: *
webmaster@1: * If the direction of the current language is right-to-left (Hebrew,
webmaster@1: * Arabic, etc.), the function will also look for an RTL CSS file and append
webmaster@1: * it to the list. The name of this file should have an '-rtl.css' suffix.
webmaster@1: * For example a CSS file called 'name.css' will have a 'name-rtl.css'
webmaster@1: * file added to the list, if exists in the same directory. This CSS file
webmaster@1: * should contain overrides for properties which should be reversed or
webmaster@1: * otherwise different in a right-to-left display.
webmaster@1: * @param $type
webmaster@1: * (optional) The type of stylesheet that is being added. Types are: module
webmaster@1: * or theme.
webmaster@1: * @param $media
webmaster@1: * (optional) The media type for the stylesheet, e.g., all, print, screen.
webmaster@1: * @param $preprocess
webmaster@1: * (optional) Should this CSS file be aggregated and compressed if this
webmaster@1: * feature has been turned on under the performance section?
webmaster@1: *
webmaster@1: * What does this actually mean?
webmaster@1: * CSS preprocessing is the process of aggregating a bunch of separate CSS
webmaster@1: * files into one file that is then compressed by removing all extraneous
webmaster@1: * white space.
webmaster@1: *
webmaster@1: * The reason for merging the CSS files is outlined quite thoroughly here:
webmaster@1: * http://www.die.net/musings/page_load_time/
webmaster@1: * "Load fewer external objects. Due to request overhead, one bigger file
webmaster@1: * just loads faster than two smaller ones half its size."
webmaster@1: *
webmaster@1: * However, you should *not* preprocess every file as this can lead to
webmaster@1: * redundant caches. You should set $preprocess = FALSE when:
webmaster@1: *
webmaster@1: * - Your styles are only used rarely on the site. This could be a special
webmaster@1: * admin page, the homepage, or a handful of pages that does not represent
webmaster@1: * the majority of the pages on your site.
webmaster@1: *
webmaster@1: * Typical candidates for caching are for example styles for nodes across
webmaster@1: * the site, or used in the theme.
webmaster@1: * @return
webmaster@1: * An array of CSS files.
webmaster@1: */
webmaster@1: function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
webmaster@1: static $css = array();
webmaster@1: global $language;
webmaster@1:
webmaster@1: // Create an array of CSS files for each media type first, since each type needs to be served
webmaster@1: // to the browser differently.
webmaster@1: if (isset($path)) {
webmaster@1: // This check is necessary to ensure proper cascading of styles and is faster than an asort().
webmaster@1: if (!isset($css[$media])) {
webmaster@1: $css[$media] = array('module' => array(), 'theme' => array());
webmaster@1: }
webmaster@1: $css[$media][$type][$path] = $preprocess;
webmaster@1:
webmaster@1: // If the current language is RTL, add the CSS file with RTL overrides.
webmaster@1: if (defined('LANGUAGE_RTL') && $language->direction == LANGUAGE_RTL) {
webmaster@1: $rtl_path = str_replace('.css', '-rtl.css', $path);
webmaster@1: if (file_exists($rtl_path)) {
webmaster@1: $css[$media][$type][$rtl_path] = $preprocess;
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: return $css;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Returns a themed representation of all stylesheets that should be attached to the page.
webmaster@1: *
webmaster@3: * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
webmaster@3: * This ensures proper cascading of styles so themes can easily override
webmaster@3: * module styles through CSS selectors.
webmaster@3: *
webmaster@3: * Themes may replace module-defined CSS files by adding a stylesheet with the
webmaster@3: * same filename. For example, themes/garland/system-menus.css would replace
webmaster@3: * modules/system/system-menus.css. This allows themes to override complete
webmaster@3: * CSS files, rather than specific selectors, when necessary.
webmaster@3: *
webmaster@3: * If the original CSS file is being overridden by a theme, the theme is
webmaster@3: * responsible for supplying an accompanying RTL CSS file to replace the
webmaster@3: * module's.
webmaster@1: *
webmaster@1: * @param $css
webmaster@1: * (optional) An array of CSS files. If no array is provided, the default
webmaster@1: * stylesheets array is used instead.
webmaster@1: * @return
webmaster@1: * A string of XHTML CSS tags.
webmaster@1: */
webmaster@1: function drupal_get_css($css = NULL) {
webmaster@1: $output = '';
webmaster@1: if (!isset($css)) {
webmaster@1: $css = drupal_add_css();
webmaster@1: }
webmaster@1: $no_module_preprocess = '';
webmaster@1: $no_theme_preprocess = '';
webmaster@1:
webmaster@1: $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
webmaster@1: $directory = file_directory_path();
webmaster@1: $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
webmaster@1:
webmaster@1: // A dummy query-string is added to filenames, to gain control over
webmaster@1: // browser-caching. The string changes on every update or full cache
webmaster@1: // flush, forcing browsers to load a new copy of the files, as the
webmaster@1: // URL changed.
webmaster@1: $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
webmaster@1:
webmaster@1: foreach ($css as $media => $types) {
webmaster@1: // If CSS preprocessing is off, we still need to output the styles.
webmaster@1: // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
webmaster@1: foreach ($types as $type => $files) {
webmaster@3: if ($type == 'module') {
webmaster@3: // Setup theme overrides for module styles.
webmaster@3: $theme_styles = array();
webmaster@3: foreach (array_keys($css[$media]['theme']) as $theme_style) {
webmaster@3: $theme_styles[] = basename($theme_style);
webmaster@3: }
webmaster@3: }
webmaster@1: foreach ($types[$type] as $file => $preprocess) {
webmaster@3: // If the theme supplies its own style using the name of the module style, skip its inclusion.
webmaster@3: // This includes any RTL styles associated with its main LTR counterpart.
webmaster@3: if ($type == 'module' && in_array(str_replace('-rtl.css', '.css', basename($file)), $theme_styles)) {
webmaster@7: // Unset the file to prevent its inclusion when CSS aggregation is enabled.
webmaster@7: unset($types[$type][$file]);
webmaster@3: continue;
webmaster@3: }
webmaster@7: // Only include the stylesheet if it exists.
webmaster@7: if (file_exists($file)) {
webmaster@7: if (!$preprocess || !($is_writable && $preprocess_css)) {
webmaster@7: // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
webmaster@7: // regardless of whether preprocessing is on or off.
webmaster@7: if (!$preprocess && $type == 'module') {
webmaster@7: $no_module_preprocess .= ''."\n";
webmaster@7: }
webmaster@7: // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
webmaster@7: // regardless of whether preprocessing is on or off.
webmaster@7: else if (!$preprocess && $type == 'theme') {
webmaster@7: $no_theme_preprocess .= ''."\n";
webmaster@7: }
webmaster@7: else {
webmaster@7: $output .= ''."\n";
webmaster@7: }
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: if ($is_writable && $preprocess_css) {
webmaster@1: $filename = md5(serialize($types) . $query_string) .'.css';
webmaster@1: $preprocess_file = drupal_build_css_cache($types, $filename);
webmaster@1: $output .= ''."\n";
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: return $no_module_preprocess . $output . $no_theme_preprocess;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Aggregate and optimize CSS files, putting them in the files directory.
webmaster@1: *
webmaster@1: * @param $types
webmaster@1: * An array of types of CSS files (e.g., screen, print) to aggregate and
webmaster@1: * compress into one file.
webmaster@1: * @param $filename
webmaster@1: * The name of the aggregate CSS file.
webmaster@1: * @return
webmaster@1: * The name of the CSS file.
webmaster@1: */
webmaster@1: function drupal_build_css_cache($types, $filename) {
webmaster@1: $data = '';
webmaster@1:
webmaster@1: // Create the css/ within the files folder.
webmaster@1: $csspath = file_create_path('css');
webmaster@1: file_check_directory($csspath, FILE_CREATE_DIRECTORY);
webmaster@1:
webmaster@1: if (!file_exists($csspath .'/'. $filename)) {
webmaster@1: // Build aggregate CSS file.
webmaster@1: foreach ($types as $type) {
webmaster@1: foreach ($type as $file => $cache) {
webmaster@1: if ($cache) {
webmaster@1: $contents = drupal_load_stylesheet($file, TRUE);
webmaster@1: // Return the path to where this CSS file originated from.
webmaster@1: $base = base_path() . dirname($file) .'/';
webmaster@1: _drupal_build_css_path(NULL, $base);
webmaster@1: // Prefix all paths within this CSS file, ignoring external and absolute paths.
webmaster@1: $data .= preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $contents);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
webmaster@1: // @import rules must proceed any other style, so we move those to the top.
webmaster@1: $regexp = '/@import[^;]+;/i';
webmaster@1: preg_match_all($regexp, $data, $matches);
webmaster@1: $data = preg_replace($regexp, '', $data);
webmaster@1: $data = implode('', $matches[0]) . $data;
webmaster@1:
webmaster@1: // Create the CSS file.
webmaster@1: file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
webmaster@1: }
webmaster@1: return $csspath .'/'. $filename;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Helper function for drupal_build_css_cache().
webmaster@1: *
webmaster@1: * This function will prefix all paths within a CSS file.
webmaster@1: */
webmaster@1: function _drupal_build_css_path($matches, $base = NULL) {
webmaster@1: static $_base;
webmaster@1: // Store base path for preg_replace_callback.
webmaster@1: if (isset($base)) {
webmaster@1: $_base = $base;
webmaster@1: }
webmaster@1:
webmaster@1: // Prefix with base and remove '../' segments where possible.
webmaster@1: $path = $_base . $matches[1];
webmaster@1: $last = '';
webmaster@1: while ($path != $last) {
webmaster@1: $last = $path;
webmaster@1: $path = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $path);
webmaster@1: }
webmaster@1: return 'url('. $path .')';
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Loads the stylesheet and resolves all @import commands.
webmaster@1: *
webmaster@1: * Loads a stylesheet and replaces @import commands with the contents of the
webmaster@1: * imported file. Use this instead of file_get_contents when processing
webmaster@1: * stylesheets.
webmaster@1: *
webmaster@1: * The returned contents are compressed removing white space and comments only
webmaster@1: * when CSS aggregation is enabled. This optimization will not apply for
webmaster@1: * color.module enabled themes with CSS aggregation turned off.
webmaster@1: *
webmaster@1: * @param $file
webmaster@1: * Name of the stylesheet to be processed.
webmaster@1: * @param $optimize
webmaster@1: * Defines if CSS contents should be compressed or not.
webmaster@1: * @return
webmaster@1: * Contents of the stylesheet including the imported stylesheets.
webmaster@1: */
webmaster@1: function drupal_load_stylesheet($file, $optimize = NULL) {
webmaster@1: static $_optimize;
webmaster@1: // Store optimization parameter for preg_replace_callback with nested @import loops.
webmaster@1: if (isset($optimize)) {
webmaster@1: $_optimize = $optimize;
webmaster@1: }
webmaster@1:
webmaster@1: $contents = '';
webmaster@1: if (file_exists($file)) {
webmaster@1: // Load the local CSS stylesheet.
webmaster@1: $contents = file_get_contents($file);
webmaster@1:
webmaster@1: // Change to the current stylesheet's directory.
webmaster@1: $cwd = getcwd();
webmaster@1: chdir(dirname($file));
webmaster@1:
webmaster@1: // Replaces @import commands with the actual stylesheet content.
webmaster@1: // This happens recursively but omits external files.
webmaster@1: $contents = preg_replace_callback('/@import\s*(?:url\()?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\)?;/', '_drupal_load_stylesheet', $contents);
webmaster@1: // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
webmaster@1: $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
webmaster@1:
webmaster@1: if ($_optimize) {
webmaster@1: // Perform some safe CSS optimizations.
webmaster@1: $contents = preg_replace('<
webmaster@1: \s*([@{}:;,]|\)\s|\s\()\s* | # Remove whitespace around separators, but keep space around parentheses.
webmaster@1: /\*([^*\\\\]|\*(?!/))+\*/ | # Remove comments that are not CSS hacks.
webmaster@1: [\n\r] # Remove line breaks.
webmaster@1: >x', '\1', $contents);
webmaster@1: }
webmaster@1:
webmaster@1: // Change back directory.
webmaster@1: chdir($cwd);
webmaster@1: }
webmaster@1:
webmaster@1: return $contents;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Loads stylesheets recursively and returns contents with corrected paths.
webmaster@1: *
webmaster@1: * This function is used for recursive loading of stylesheets and
webmaster@1: * returns the stylesheet content with all url() paths corrected.
webmaster@1: */
webmaster@1: function _drupal_load_stylesheet($matches) {
webmaster@1: $filename = $matches[1];
webmaster@1: // Load the imported stylesheet and replace @import commands in there as well.
webmaster@1: $file = drupal_load_stylesheet($filename);
webmaster@1: // Alter all url() paths, but not external.
webmaster@1: return preg_replace('/url\(([\'"]?)(?![a-z]+:)([^\'")]+)[\'"]?\)?;/i', 'url(\1'. dirname($filename) .'/', $file);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Delete all cached CSS files.
webmaster@1: */
webmaster@1: function drupal_clear_css_cache() {
webmaster@1: file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Add a JavaScript file, setting or inline code to the page.
webmaster@1: *
webmaster@1: * The behavior of this function depends on the parameters it is called with.
webmaster@1: * Generally, it handles the addition of JavaScript to the page, either as
webmaster@1: * reference to an existing file or as inline code. The following actions can be
webmaster@1: * performed using this function:
webmaster@1: *
webmaster@1: * - Add a file ('core', 'module' and 'theme'):
webmaster@1: * Adds a reference to a JavaScript file to the page. JavaScript files
webmaster@1: * are placed in a certain order, from 'core' first, to 'module' and finally
webmaster@1: * 'theme' so that files, that are added later, can override previously added
webmaster@1: * files with ease.
webmaster@1: *
webmaster@1: * - Add inline JavaScript code ('inline'):
webmaster@1: * Executes a piece of JavaScript code on the current page by placing the code
webmaster@1: * directly in the page. This can, for example, be useful to tell the user that
webmaster@1: * a new message arrived, by opening a pop up, alert box etc.
webmaster@1: *
webmaster@1: * - Add settings ('setting'):
webmaster@1: * Adds a setting to Drupal's global storage of JavaScript settings. Per-page
webmaster@1: * settings are required by some modules to function properly. The settings
webmaster@1: * will be accessible at Drupal.settings.
webmaster@1: *
webmaster@1: * @param $data
webmaster@1: * (optional) If given, the value depends on the $type parameter:
webmaster@1: * - 'core', 'module' or 'theme': Path to the file relative to base_path().
webmaster@1: * - 'inline': The JavaScript code that should be placed in the given scope.
webmaster@1: * - 'setting': An array with configuration options as associative array. The
webmaster@1: * array is directly placed in Drupal.settings. You might want to wrap your
webmaster@1: * actual configuration settings in another variable to prevent the pollution
webmaster@1: * of the Drupal.settings namespace.
webmaster@1: * @param $type
webmaster@1: * (optional) The type of JavaScript that should be added to the page. Allowed
webmaster@1: * values are 'core', 'module', 'theme', 'inline' and 'setting'. You
webmaster@1: * can, however, specify any value. It is treated as a reference to a JavaScript
webmaster@1: * file. Defaults to 'module'.
webmaster@1: * @param $scope
webmaster@1: * (optional) The location in which you want to place the script. Possible
webmaster@1: * values are 'header' and 'footer' by default. If your theme implements
webmaster@1: * different locations, however, you can also use these.
webmaster@1: * @param $defer
webmaster@1: * (optional) If set to TRUE, the defer attribute is set on the \n";
webmaster@1: break;
webmaster@1: case 'inline':
webmaster@1: foreach ($data as $info) {
webmaster@1: $output .= '\n";
webmaster@1: }
webmaster@1: break;
webmaster@1: default:
webmaster@1: // If JS preprocessing is off, we still need to output the scripts.
webmaster@1: // Additionally, go through any remaining scripts if JS preprocessing is on and output the non-cached ones.
webmaster@1: foreach ($data as $path => $info) {
webmaster@1: if (!$info['preprocess'] || !$is_writable || !$preprocess_js) {
webmaster@1: $no_preprocess[$type] .= '\n";
webmaster@1: }
webmaster@1: else {
webmaster@1: $files[$path] = $info;
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: // Aggregate any remaining JS files that haven't already been output.
webmaster@1: if ($is_writable && $preprocess_js && count($files) > 0) {
webmaster@1: $filename = md5(serialize($files) . $query_string) .'.js';
webmaster@1: $preprocess_file = drupal_build_js_cache($files, $filename);
webmaster@1: $preprocessed .= ''."\n";
webmaster@1: }
webmaster@1:
webmaster@1: // Keep the order of JS files consistent as some are preprocessed and others are not.
webmaster@1: // Make sure any inline or JS setting variables appear last after libraries have loaded.
webmaster@1: $output = $preprocessed . implode('', $no_preprocess) . $output;
webmaster@1:
webmaster@1: return $output;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Assist in adding the tableDrag JavaScript behavior to a themed table.
webmaster@1: *
webmaster@1: * Draggable tables should be used wherever an outline or list of sortable items
webmaster@1: * needs to be arranged by an end-user. Draggable tables are very flexible and
webmaster@1: * can manipulate the value of form elements placed within individual columns.
webmaster@1: *
webmaster@1: * To set up a table to use drag and drop in place of weight select-lists or
webmaster@1: * in place of a form that contains parent relationships, the form must be
webmaster@1: * themed into a table. The table must have an id attribute set. If using
webmaster@1: * theme_table(), the id may be set as such:
webmaster@1: * @code
webmaster@1: * $output = theme('table', $header, $rows, array('id' => 'my-module-table'));
webmaster@1: * return $output;
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * In the theme function for the form, a special class must be added to each
webmaster@1: * form element within the same column, "grouping" them together.
webmaster@1: *
webmaster@1: * In a situation where a single weight column is being sorted in the table, the
webmaster@1: * classes could be added like this (in the theme function):
webmaster@1: * @code
webmaster@1: * $form['my_elements'][$delta]['weight']['#attributes']['class'] = "my-elements-weight";
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * Each row of the table must also have a class of "draggable" in order to enable the
webmaster@1: * drag handles:
webmaster@1: * @code
webmaster@1: * $row = array(...);
webmaster@1: * $rows[] = array(
webmaster@1: * 'data' => $row,
webmaster@1: * 'class' => 'draggable',
webmaster@1: * );
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * When tree relationships are present, the two additional classes
webmaster@1: * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
webmaster@1: * - Rows with the 'tabledrag-leaf' class cannot have child rows.
webmaster@1: * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
webmaster@1: *
webmaster@1: * Calling drupal_add_tabledrag() would then be written as such:
webmaster@1: * @code
webmaster@1: * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * In a more complex case where there are several groups in one column (such as
webmaster@1: * the block regions on the admin/build/block page), a separate subgroup class
webmaster@1: * must also be added to differentiate the groups.
webmaster@1: * @code
webmaster@1: * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = "my-elements-weight my-elements-weight-". $region;
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * $group is still 'my-element-weight', and the additional $subgroup variable
webmaster@1: * will be passed in as 'my-elements-weight-'. $region. This also means that
webmaster@1: * you'll need to call drupal_add_tabledrag() once for every region added.
webmaster@1: *
webmaster@1: * @code
webmaster@1: * foreach ($regions as $region) {
webmaster@1: * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-'. $region);
webmaster@1: * }
webmaster@1: * @endcode
webmaster@1: *
webmaster@1: * In a situation where tree relationships are present, adding multiple
webmaster@1: * subgroups is not necessary, because the table will contain indentations that
webmaster@1: * provide enough information about the sibling and parent relationships.
webmaster@1: * See theme_menu_overview_form() for an example creating a table containing
webmaster@1: * parent relationships.
webmaster@1: *
webmaster@1: * Please note that this function should be called from the theme layer, such as
webmaster@1: * in a .tpl.php file, theme_ function, or in a template_preprocess function,
webmaster@1: * not in a form declartion. Though the same JavaScript could be added to the
webmaster@1: * page using drupal_add_js() directly, this function helps keep template files
webmaster@1: * clean and readable. It also prevents tabledrag.js from being added twice
webmaster@1: * accidentally.
webmaster@1: *
webmaster@1: * @param $table_id
webmaster@1: * String containing the target table's id attribute. If the table does not
webmaster@1: * have an id, one will need to be set, such as
.
webmaster@1: * @param $action
webmaster@1: * String describing the action to be done on the form item. Either 'match'
webmaster@1: * 'depth', or 'order'. Match is typically used for parent relationships.
webmaster@1: * Order is typically used to set weights on other form elements with the same
webmaster@1: * group. Depth updates the target element with the current indentation.
webmaster@1: * @param $relationship
webmaster@1: * String describing where the $action variable should be performed. Either
webmaster@1: * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
webmaster@1: * up the tree. Sibling will look for fields in the same group in rows above
webmaster@1: * and below it. Self affects the dragged row itself. Group affects the
webmaster@1: * dragged row, plus any children below it (the entire dragged group).
webmaster@1: * @param $group
webmaster@1: * A class name applied on all related form elements for this action.
webmaster@1: * @param $subgroup
webmaster@1: * (optional) If the group has several subgroups within it, this string should
webmaster@1: * contain the class name identifying fields in the same subgroup.
webmaster@1: * @param $source
webmaster@1: * (optional) If the $action is 'match', this string should contain the class
webmaster@1: * name identifying what field will be used as the source value when matching
webmaster@1: * the value in $subgroup.
webmaster@1: * @param $hidden
webmaster@1: * (optional) The column containing the field elements may be entirely hidden
webmaster@1: * from view dynamically when the JavaScript is loaded. Set to FALSE if the
webmaster@1: * column should not be hidden.
webmaster@1: * @param $limit
webmaster@1: * (optional) Limit the maximum amount of parenting in this table.
webmaster@1: * @see block-admin-display-form.tpl.php
webmaster@1: * @see theme_menu_overview_form()
webmaster@1: */
webmaster@1: function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
webmaster@1: static $js_added = FALSE;
webmaster@1: if (!$js_added) {
webmaster@1: drupal_add_js('misc/tabledrag.js', 'core');
webmaster@1: $js_added = TRUE;
webmaster@1: }
webmaster@1:
webmaster@1: // If a subgroup or source isn't set, assume it is the same as the group.
webmaster@1: $target = isset($subgroup) ? $subgroup : $group;
webmaster@1: $source = isset($source) ? $source : $target;
webmaster@1: $settings['tableDrag'][$table_id][$group][] = array(
webmaster@1: 'target' => $target,
webmaster@1: 'source' => $source,
webmaster@1: 'relationship' => $relationship,
webmaster@1: 'action' => $action,
webmaster@1: 'hidden' => $hidden,
webmaster@1: 'limit' => $limit,
webmaster@1: );
webmaster@1: drupal_add_js($settings, 'setting');
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Aggregate JS files, putting them in the files directory.
webmaster@1: *
webmaster@1: * @param $files
webmaster@1: * An array of JS files to aggregate and compress into one file.
webmaster@1: * @param $filename
webmaster@1: * The name of the aggregate JS file.
webmaster@1: * @return
webmaster@1: * The name of the JS file.
webmaster@1: */
webmaster@1: function drupal_build_js_cache($files, $filename) {
webmaster@1: $contents = '';
webmaster@1:
webmaster@1: // Create the js/ within the files folder.
webmaster@1: $jspath = file_create_path('js');
webmaster@1: file_check_directory($jspath, FILE_CREATE_DIRECTORY);
webmaster@1:
webmaster@1: if (!file_exists($jspath .'/'. $filename)) {
webmaster@1: // Build aggregate JS file.
webmaster@1: foreach ($files as $path => $info) {
webmaster@1: if ($info['preprocess']) {
webmaster@1: // Append a ';' after each JS file to prevent them from running together.
webmaster@1: $contents .= file_get_contents($path) .';';
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: // Create the JS file.
webmaster@1: file_save_data($contents, $jspath .'/'. $filename, FILE_EXISTS_REPLACE);
webmaster@1: }
webmaster@1:
webmaster@1: return $jspath .'/'. $filename;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Delete all cached JS files.
webmaster@1: */
webmaster@1: function drupal_clear_js_cache() {
webmaster@1: file_scan_directory(file_create_path('js'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
webmaster@1: variable_set('javascript_parsed', array());
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Converts a PHP variable into its Javascript equivalent.
webmaster@1: *
webmaster@1: * We use HTML-safe strings, i.e. with <, > and & escaped.
webmaster@1: */
webmaster@1: function drupal_to_js($var) {
webmaster@1: switch (gettype($var)) {
webmaster@1: case 'boolean':
webmaster@1: return $var ? 'true' : 'false'; // Lowercase necessary!
webmaster@1: case 'integer':
webmaster@1: case 'double':
webmaster@1: return $var;
webmaster@1: case 'resource':
webmaster@1: case 'string':
webmaster@1: return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
webmaster@1: array('\r', '\n', '\x3c', '\x3e', '\x26'),
webmaster@1: addslashes($var)) .'"';
webmaster@1: case 'array':
webmaster@1: // Arrays in JSON can't be associative. If the array is empty or if it
webmaster@1: // has sequential whole number keys starting with 0, it's not associative
webmaster@1: // so we can go ahead and convert it as an array.
webmaster@1: if (empty ($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
webmaster@1: $output = array();
webmaster@1: foreach ($var as $v) {
webmaster@1: $output[] = drupal_to_js($v);
webmaster@1: }
webmaster@1: return '[ '. implode(', ', $output) .' ]';
webmaster@1: }
webmaster@1: // Otherwise, fall through to convert the array as an object.
webmaster@1: case 'object':
webmaster@1: $output = array();
webmaster@1: foreach ($var as $k => $v) {
webmaster@1: $output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
webmaster@1: }
webmaster@1: return '{ '. implode(', ', $output) .' }';
webmaster@1: default:
webmaster@1: return 'null';
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Return data in JSON format.
webmaster@1: *
webmaster@1: * This function should be used for JavaScript callback functions returning
webmaster@1: * data in JSON format. It sets the header for JavaScript output.
webmaster@1: *
webmaster@1: * @param $var
webmaster@1: * (optional) If set, the variable will be converted to JSON and output.
webmaster@1: */
webmaster@1: function drupal_json($var = NULL) {
webmaster@1: // We are returning JavaScript, so tell the browser.
webmaster@1: drupal_set_header('Content-Type: text/javascript; charset=utf-8');
webmaster@1:
webmaster@1: if (isset($var)) {
webmaster@1: echo drupal_to_js($var);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Wrapper around urlencode() which avoids Apache quirks.
webmaster@1: *
webmaster@1: * Should be used when placing arbitrary data in an URL. Note that Drupal paths
webmaster@1: * are urlencoded() when passed through url() and do not require urlencoding()
webmaster@1: * of individual components.
webmaster@1: *
webmaster@1: * Notes:
webmaster@1: * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
webmaster@1: * in Apache where it 404s on any path containing '%2F'.
webmaster@1: * - mod_rewrite unescapes %-encoded ampersands, hashes, and slashes when clean
webmaster@1: * URLs are used, which are interpreted as delimiters by PHP. These
webmaster@1: * characters are double escaped so PHP will still see the encoded version.
webmaster@1: * - With clean URLs, Apache changes '//' to '/', so every second slash is
webmaster@1: * double escaped.
webmaster@1: *
webmaster@1: * @param $text
webmaster@1: * String to encode
webmaster@1: */
webmaster@1: function drupal_urlencode($text) {
webmaster@1: if (variable_get('clean_url', '0')) {
webmaster@1: return str_replace(array('%2F', '%26', '%23', '//'),
webmaster@1: array('/', '%2526', '%2523', '/%252F'),
webmaster@1: rawurlencode($text));
webmaster@1: }
webmaster@1: else {
webmaster@1: return str_replace('%2F', '/', rawurlencode($text));
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Ensure the private key variable used to generate tokens is set.
webmaster@1: *
webmaster@1: * @return
webmaster@1: * The private key.
webmaster@1: */
webmaster@1: function drupal_get_private_key() {
webmaster@1: if (!($key = variable_get('drupal_private_key', 0))) {
webmaster@1: $key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
webmaster@1: variable_set('drupal_private_key', $key);
webmaster@1: }
webmaster@1: return $key;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Generate a token based on $value, the current user session and private key.
webmaster@1: *
webmaster@1: * @param $value
webmaster@1: * An additional value to base the token on.
webmaster@1: */
webmaster@1: function drupal_get_token($value = '') {
webmaster@1: $private_key = drupal_get_private_key();
webmaster@1: return md5(session_id() . $value . $private_key);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Validate a token based on $value, the current user session and private key.
webmaster@1: *
webmaster@1: * @param $token
webmaster@1: * The token to be validated.
webmaster@1: * @param $value
webmaster@1: * An additional value to base the token on.
webmaster@1: * @param $skip_anonymous
webmaster@1: * Set to true to skip token validation for anonymous users.
webmaster@1: * @return
webmaster@1: * True for a valid token, false for an invalid token. When $skip_anonymous
webmaster@1: * is true, the return value will always be true for anonymous users.
webmaster@1: */
webmaster@1: function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
webmaster@1: global $user;
webmaster@1: return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Performs one or more XML-RPC request(s).
webmaster@1: *
webmaster@1: * @param $url
webmaster@1: * An absolute URL of the XML-RPC endpoint.
webmaster@1: * Example:
webmaster@1: * http://www.example.com/xmlrpc.php
webmaster@1: * @param ...
webmaster@1: * For one request:
webmaster@1: * The method name followed by a variable number of arguments to the method.
webmaster@1: * For multiple requests (system.multicall):
webmaster@1: * An array of call arrays. Each call array follows the pattern of the single
webmaster@1: * request: method name followed by the arguments to the method.
webmaster@1: * @return
webmaster@1: * For one request:
webmaster@1: * Either the return value of the method on success, or FALSE.
webmaster@1: * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
webmaster@1: * For multiple requests:
webmaster@1: * An array of results. Each result will either be the result
webmaster@1: * returned by the method called, or an xmlrpc_error object if the call
webmaster@1: * failed. See xmlrpc_error().
webmaster@1: */
webmaster@1: function xmlrpc($url) {
webmaster@1: require_once './includes/xmlrpc.inc';
webmaster@1: $args = func_get_args();
webmaster@1: return call_user_func_array('_xmlrpc', $args);
webmaster@1: }
webmaster@1:
webmaster@1: function _drupal_bootstrap_full() {
webmaster@1: static $called;
webmaster@1:
webmaster@1: if ($called) {
webmaster@1: return;
webmaster@1: }
webmaster@1: $called = 1;
webmaster@1: require_once './includes/theme.inc';
webmaster@1: require_once './includes/pager.inc';
webmaster@1: require_once './includes/menu.inc';
webmaster@1: require_once './includes/tablesort.inc';
webmaster@1: require_once './includes/file.inc';
webmaster@1: require_once './includes/unicode.inc';
webmaster@1: require_once './includes/image.inc';
webmaster@1: require_once './includes/form.inc';
webmaster@1: require_once './includes/mail.inc';
webmaster@1: require_once './includes/actions.inc';
webmaster@1: // Set the Drupal custom error handler.
webmaster@1: set_error_handler('drupal_error_handler');
webmaster@1: // Emit the correct charset HTTP header.
webmaster@1: drupal_set_header('Content-Type: text/html; charset=utf-8');
webmaster@1: // Detect string handling method
webmaster@1: unicode_check();
webmaster@1: // Undo magic quotes
webmaster@1: fix_gpc_magic();
webmaster@1: // Load all enabled modules
webmaster@1: module_load_all();
webmaster@1: // Let all modules take action before menu system handles the request
webmaster@1: // We do not want this while running update.php.
webmaster@1: if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
webmaster@1: module_invoke_all('init');
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Store the current page in the cache.
webmaster@1: *
webmaster@1: * We try to store a gzipped version of the cache. This requires the
webmaster@1: * PHP zlib extension (http://php.net/manual/en/ref.zlib.php).
webmaster@1: * Presence of the extension is checked by testing for the function
webmaster@1: * gzencode. There are two compression algorithms: gzip and deflate.
webmaster@1: * The majority of all modern browsers support gzip or both of them.
webmaster@1: * We thus only deal with the gzip variant and unzip the cache in case
webmaster@1: * the browser does not accept gzip encoding.
webmaster@1: *
webmaster@1: * @see drupal_page_header
webmaster@1: */
webmaster@1: function page_set_cache() {
webmaster@1: global $user, $base_root;
webmaster@1:
webmaster@1: if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && page_get_cache(TRUE)) {
webmaster@1: // This will fail in some cases, see page_get_cache() for the explanation.
webmaster@1: if ($data = ob_get_contents()) {
webmaster@1: $cache = TRUE;
webmaster@1: if (variable_get('page_compression', TRUE) && function_exists('gzencode')) {
webmaster@1: // We do not store the data in case the zlib mode is deflate.
webmaster@1: // This should be rarely happening.
webmaster@1: if (zlib_get_coding_type() == 'deflate') {
webmaster@1: $cache = FALSE;
webmaster@1: }
webmaster@1: else if (zlib_get_coding_type() == FALSE) {
webmaster@1: $data = gzencode($data, 9, FORCE_GZIP);
webmaster@1: }
webmaster@1: // The remaining case is 'gzip' which means the data is
webmaster@1: // already compressed and nothing left to do but to store it.
webmaster@1: }
webmaster@1: ob_end_flush();
webmaster@1: if ($cache && $data) {
webmaster@1: cache_set($base_root . request_uri(), $data, 'cache_page', CACHE_TEMPORARY, drupal_get_headers());
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Executes a cron run when called
webmaster@1: * @return
webmaster@1: * Returns TRUE if ran successfully
webmaster@1: */
webmaster@1: function drupal_cron_run() {
webmaster@1: // If not in 'safe mode', increase the maximum execution time:
webmaster@1: if (!ini_get('safe_mode')) {
webmaster@1: set_time_limit(240);
webmaster@1: }
webmaster@1:
webmaster@1: // Fetch the cron semaphore
webmaster@1: $semaphore = variable_get('cron_semaphore', FALSE);
webmaster@1:
webmaster@1: if ($semaphore) {
webmaster@1: if (time() - $semaphore > 3600) {
webmaster@1: // Either cron has been running for more than an hour or the semaphore
webmaster@1: // was not reset due to a database error.
webmaster@1: watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);
webmaster@1:
webmaster@1: // Release cron semaphore
webmaster@1: variable_del('cron_semaphore');
webmaster@1: }
webmaster@1: else {
webmaster@1: // Cron is still running normally.
webmaster@1: watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
webmaster@1: }
webmaster@1: }
webmaster@1: else {
webmaster@1: // Register shutdown callback
webmaster@1: register_shutdown_function('drupal_cron_cleanup');
webmaster@1:
webmaster@1: // Lock cron semaphore
webmaster@1: variable_set('cron_semaphore', time());
webmaster@1:
webmaster@1: // Iterate through the modules calling their cron handlers (if any):
webmaster@1: module_invoke_all('cron');
webmaster@1:
webmaster@1: // Record cron time
webmaster@1: variable_set('cron_last', time());
webmaster@1: watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
webmaster@1:
webmaster@1: // Release cron semaphore
webmaster@1: variable_del('cron_semaphore');
webmaster@1:
webmaster@1: // Return TRUE so other functions can check if it did run successfully
webmaster@1: return TRUE;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Shutdown function for cron cleanup.
webmaster@1: */
webmaster@1: function drupal_cron_cleanup() {
webmaster@1: // See if the semaphore is still locked.
webmaster@1: if (variable_get('cron_semaphore', FALSE)) {
webmaster@1: watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
webmaster@1:
webmaster@1: // Release cron semaphore
webmaster@1: variable_del('cron_semaphore');
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Return an array of system file objects.
webmaster@1: *
webmaster@1: * Returns an array of file objects of the given type from the site-wide
webmaster@1: * directory (i.e. modules/), the all-sites directory (i.e.
webmaster@1: * sites/all/modules/), the profiles directory, and site-specific directory
webmaster@1: * (i.e. sites/somesite/modules/). The returned array will be keyed using the
webmaster@1: * key specified (name, basename, filename). Using name or basename will cause
webmaster@1: * site-specific files to be prioritized over similar files in the default
webmaster@1: * directories. That is, if a file with the same name appears in both the
webmaster@1: * site-wide directory and site-specific directory, only the site-specific
webmaster@1: * version will be included.
webmaster@1: *
webmaster@1: * @param $mask
webmaster@1: * The regular expression of the files to find.
webmaster@1: * @param $directory
webmaster@1: * The subdirectory name in which the files are found. For example,
webmaster@1: * 'modules' will search in both modules/ and
webmaster@1: * sites/somesite/modules/.
webmaster@1: * @param $key
webmaster@1: * The key to be passed to file_scan_directory().
webmaster@1: * @param $min_depth
webmaster@1: * Minimum depth of directories to return files from.
webmaster@1: *
webmaster@1: * @return
webmaster@1: * An array of file objects of the specified type.
webmaster@1: */
webmaster@1: function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
webmaster@1: global $profile;
webmaster@1: $config = conf_path();
webmaster@1:
webmaster@1: // When this function is called during Drupal's initial installation process,
webmaster@1: // the name of the profile that's about to be installed is stored in the global
webmaster@1: // $profile variable. At all other times, the standard Drupal systems variable
webmaster@1: // table contains the name of the current profile, and we can call variable_get()
webmaster@1: // to determine what one is active.
webmaster@1: if (!isset($profile)) {
webmaster@1: $profile = variable_get('install_profile', 'default');
webmaster@1: }
webmaster@1: $searchdir = array($directory);
webmaster@1: $files = array();
webmaster@1:
webmaster@1: // Always search sites/all/* as well as the global directories
webmaster@1: $searchdir[] = 'sites/all/'. $directory;
webmaster@1:
webmaster@1: // The 'profiles' directory contains pristine collections of modules and
webmaster@1: // themes as organized by a distribution. It is pristine in the same way
webmaster@1: // that /modules is pristine for core; users should avoid changing anything
webmaster@1: // there in favor of sites/all or sites/ directories.
webmaster@1: if (file_exists("profiles/$profile/$directory")) {
webmaster@1: $searchdir[] = "profiles/$profile/$directory";
webmaster@1: }
webmaster@1:
webmaster@1: if (file_exists("$config/$directory")) {
webmaster@1: $searchdir[] = "$config/$directory";
webmaster@1: }
webmaster@1:
webmaster@1: // Get current list of items
webmaster@1: foreach ($searchdir as $dir) {
webmaster@1: $files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
webmaster@1: }
webmaster@1:
webmaster@1: return $files;
webmaster@1: }
webmaster@1:
webmaster@1:
webmaster@1: /**
webmaster@1: * This dispatch function hands off structured Drupal arrays to type-specific
webmaster@1: * *_alter implementations. It ensures a consistent interface for all altering
webmaster@1: * operations.
webmaster@1: *
webmaster@1: * @param $type
webmaster@1: * The data type of the structured array. 'form', 'links',
webmaster@1: * 'node_content', and so on are several examples.
webmaster@1: * @param $data
webmaster@1: * The structured array to be altered.
webmaster@1: * @param ...
webmaster@1: * Any additional params will be passed on to the called
webmaster@1: * hook_$type_alter functions.
webmaster@1: */
webmaster@1: function drupal_alter($type, &$data) {
webmaster@1: // PHP's func_get_args() always returns copies of params, not references, so
webmaster@1: // drupal_alter() can only manipulate data that comes in via the required first
webmaster@1: // param. For the edge case functions that must pass in an arbitrary number of
webmaster@1: // alterable parameters (hook_form_alter() being the best example), an array of
webmaster@1: // those params can be placed in the __drupal_alter_by_ref key of the $data
webmaster@1: // array. This is somewhat ugly, but is an unavoidable consequence of a flexible
webmaster@1: // drupal_alter() function, and the limitations of func_get_args().
webmaster@1: // @todo: Remove this in Drupal 7.
webmaster@1: if (is_array($data) && isset($data['__drupal_alter_by_ref'])) {
webmaster@1: $by_ref_parameters = $data['__drupal_alter_by_ref'];
webmaster@1: unset($data['__drupal_alter_by_ref']);
webmaster@1: }
webmaster@1:
webmaster@1: // Hang onto a reference to the data array so that it isn't blown away later.
webmaster@1: // Also, merge in any parameters that need to be passed by reference.
webmaster@1: $args = array(&$data);
webmaster@1: if (isset($by_ref_parameters)) {
webmaster@1: $args = array_merge($args, $by_ref_parameters);
webmaster@1: }
webmaster@1:
webmaster@1: // Now, use func_get_args() to pull in any additional parameters passed into
webmaster@1: // the drupal_alter() call.
webmaster@1: $additional_args = func_get_args();
webmaster@1: array_shift($additional_args);
webmaster@1: array_shift($additional_args);
webmaster@1: $args = array_merge($args, $additional_args);
webmaster@1:
webmaster@1: foreach (module_implements($type .'_alter') as $module) {
webmaster@1: $function = $module .'_'. $type .'_alter';
webmaster@1: call_user_func_array($function, $args);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1:
webmaster@1: /**
webmaster@1: * Renders HTML given a structured array tree.
webmaster@1: *
webmaster@1: * Recursively iterates over each of the array elements, generating HTML code.
webmaster@1: * This function is usually called from within a another function, like
webmaster@1: * drupal_get_form() or node_view().
webmaster@1: *
webmaster@1: * @param $elements
webmaster@1: * The structured array describing the data to be rendered.
webmaster@1: * @return
webmaster@1: * The rendered HTML.
webmaster@1: */
webmaster@1: function drupal_render(&$elements) {
webmaster@1: if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
webmaster@1: return NULL;
webmaster@1: }
webmaster@1:
webmaster@1: // If the default values for this element haven't been loaded yet, populate
webmaster@1: // them.
webmaster@1: if (!isset($elements['#defaults_loaded']) || !$elements['#defaults_loaded']) {
webmaster@1: if ((!empty($elements['#type'])) && ($info = _element_info($elements['#type']))) {
webmaster@1: $elements += $info;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: // Make any final changes to the element before it is rendered. This means
webmaster@1: // that the $element or the children can be altered or corrected before the
webmaster@1: // element is rendered into the final text.
webmaster@1: if (isset($elements['#pre_render'])) {
webmaster@1: foreach ($elements['#pre_render'] as $function) {
webmaster@1: if (function_exists($function)) {
webmaster@1: $elements = $function($elements);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: $content = '';
webmaster@1: // Either the elements did not go through form_builder or one of the children
webmaster@1: // has a #weight.
webmaster@1: if (!isset($elements['#sorted'])) {
webmaster@1: uasort($elements, "element_sort");
webmaster@1: }
webmaster@1: $elements += array('#title' => NULL, '#description' => NULL);
webmaster@1: if (!isset($elements['#children'])) {
webmaster@1: $children = element_children($elements);
webmaster@7: // Render all the children that use a theme function.
webmaster@1: if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
webmaster@1: $elements['#theme_used'] = TRUE;
webmaster@1:
webmaster@1: $previous = array();
webmaster@1: foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
webmaster@1: $previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
webmaster@1: }
webmaster@1: // If we rendered a single element, then we will skip the renderer.
webmaster@1: if (empty($children)) {
webmaster@1: $elements['#printed'] = TRUE;
webmaster@1: }
webmaster@1: else {
webmaster@1: $elements['#value'] = '';
webmaster@1: }
webmaster@1: $elements['#type'] = 'markup';
webmaster@1:
webmaster@1: unset($elements['#prefix'], $elements['#suffix']);
webmaster@1: $content = theme($elements['#theme'], $elements);
webmaster@1:
webmaster@1: foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
webmaster@1: $elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
webmaster@1: }
webmaster@1: }
webmaster@7: // Render each of the children using drupal_render and concatenate them.
webmaster@1: if (!isset($content) || $content === '') {
webmaster@1: foreach ($children as $key) {
webmaster@1: $content .= drupal_render($elements[$key]);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1: if (isset($content) && $content !== '') {
webmaster@1: $elements['#children'] = $content;
webmaster@1: }
webmaster@1:
webmaster@1: // Until now, we rendered the children, here we render the element itself
webmaster@1: if (!isset($elements['#printed'])) {
webmaster@1: $content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
webmaster@1: $elements['#printed'] = TRUE;
webmaster@1: }
webmaster@1:
webmaster@1: if (isset($content) && $content !== '') {
webmaster@1: // Filter the outputted content and make any last changes before the
webmaster@1: // content is sent to the browser. The changes are made on $content
webmaster@1: // which allows the output'ed text to be filtered.
webmaster@1: if (isset($elements['#post_render'])) {
webmaster@1: foreach ($elements['#post_render'] as $function) {
webmaster@1: if (function_exists($function)) {
webmaster@1: $content = $function($content, $elements);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1: $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
webmaster@1: $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
webmaster@1: return $prefix . $content . $suffix;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Function used by uasort to sort structured arrays by weight.
webmaster@1: */
webmaster@1: function element_sort($a, $b) {
webmaster@1: $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
webmaster@1: $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
webmaster@1: if ($a_weight == $b_weight) {
webmaster@1: return 0;
webmaster@1: }
webmaster@1: return ($a_weight < $b_weight) ? -1 : 1;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Check if the key is a property.
webmaster@1: */
webmaster@1: function element_property($key) {
webmaster@1: return $key[0] == '#';
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Get properties of a structured array element. Properties begin with '#'.
webmaster@1: */
webmaster@1: function element_properties($element) {
webmaster@1: return array_filter(array_keys((array) $element), 'element_property');
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Check if the key is a child.
webmaster@1: */
webmaster@1: function element_child($key) {
webmaster@1: return !isset($key[0]) || $key[0] != '#';
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
webmaster@1: */
webmaster@1: function element_children($element) {
webmaster@1: return array_filter(array_keys((array) $element), 'element_child');
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Provide theme registration for themes across .inc files.
webmaster@1: */
webmaster@1: function drupal_common_theme() {
webmaster@1: return array(
webmaster@1: // theme.inc
webmaster@1: 'placeholder' => array(
webmaster@1: 'arguments' => array('text' => NULL)
webmaster@1: ),
webmaster@1: 'page' => array(
webmaster@1: 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
webmaster@1: 'template' => 'page',
webmaster@1: ),
webmaster@1: 'maintenance_page' => array(
webmaster@1: 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
webmaster@1: 'template' => 'maintenance-page',
webmaster@1: ),
webmaster@1: 'update_page' => array(
webmaster@1: 'arguments' => array('content' => NULL, 'show_messages' => TRUE),
webmaster@1: ),
webmaster@1: 'install_page' => array(
webmaster@1: 'arguments' => array('content' => NULL),
webmaster@1: ),
webmaster@1: 'task_list' => array(
webmaster@1: 'arguments' => array('items' => NULL, 'active' => NULL),
webmaster@1: ),
webmaster@1: 'status_messages' => array(
webmaster@1: 'arguments' => array('display' => NULL),
webmaster@1: ),
webmaster@1: 'links' => array(
webmaster@1: 'arguments' => array('links' => NULL, 'attributes' => array('class' => 'links')),
webmaster@1: ),
webmaster@1: 'image' => array(
webmaster@1: 'arguments' => array('path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
webmaster@1: ),
webmaster@1: 'breadcrumb' => array(
webmaster@1: 'arguments' => array('breadcrumb' => NULL),
webmaster@1: ),
webmaster@1: 'help' => array(
webmaster@1: 'arguments' => array(),
webmaster@1: ),
webmaster@1: 'submenu' => array(
webmaster@1: 'arguments' => array('links' => NULL),
webmaster@1: ),
webmaster@1: 'table' => array(
webmaster@1: 'arguments' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL),
webmaster@1: ),
webmaster@1: 'table_select_header_cell' => array(
webmaster@1: 'arguments' => array(),
webmaster@1: ),
webmaster@1: 'tablesort_indicator' => array(
webmaster@1: 'arguments' => array('style' => NULL),
webmaster@1: ),
webmaster@1: 'box' => array(
webmaster@1: 'arguments' => array('title' => NULL, 'content' => NULL, 'region' => 'main'),
webmaster@1: 'template' => 'box',
webmaster@1: ),
webmaster@1: 'block' => array(
webmaster@1: 'arguments' => array('block' => NULL),
webmaster@1: 'template' => 'block',
webmaster@1: ),
webmaster@1: 'mark' => array(
webmaster@1: 'arguments' => array('type' => MARK_NEW),
webmaster@1: ),
webmaster@1: 'item_list' => array(
webmaster@1: 'arguments' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => NULL),
webmaster@1: ),
webmaster@1: 'more_help_link' => array(
webmaster@1: 'arguments' => array('url' => NULL),
webmaster@1: ),
webmaster@1: 'xml_icon' => array(
webmaster@1: 'arguments' => array('url' => NULL),
webmaster@1: ),
webmaster@1: 'feed_icon' => array(
webmaster@1: 'arguments' => array('url' => NULL, 'title' => NULL),
webmaster@1: ),
webmaster@1: 'more_link' => array(
webmaster@1: 'arguments' => array('url' => NULL, 'title' => NULL)
webmaster@1: ),
webmaster@1: 'closure' => array(
webmaster@1: 'arguments' => array('main' => 0),
webmaster@1: ),
webmaster@1: 'blocks' => array(
webmaster@1: 'arguments' => array('region' => NULL),
webmaster@1: ),
webmaster@1: 'username' => array(
webmaster@1: 'arguments' => array('object' => NULL),
webmaster@1: ),
webmaster@1: 'progress_bar' => array(
webmaster@1: 'arguments' => array('percent' => NULL, 'message' => NULL),
webmaster@1: ),
webmaster@1: 'indentation' => array(
webmaster@1: 'arguments' => array('size' => 1),
webmaster@1: ),
webmaster@1: // from pager.inc
webmaster@1: 'pager' => array(
webmaster@1: 'arguments' => array('tags' => array(), 'limit' => 10, 'element' => 0, 'parameters' => array()),
webmaster@1: ),
webmaster@1: 'pager_first' => array(
webmaster@1: 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
webmaster@1: ),
webmaster@1: 'pager_previous' => array(
webmaster@1: 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
webmaster@1: ),
webmaster@1: 'pager_next' => array(
webmaster@1: 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
webmaster@1: ),
webmaster@1: 'pager_last' => array(
webmaster@1: 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
webmaster@1: ),
webmaster@1: 'pager_link' => array(
webmaster@1: 'arguments' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
webmaster@1: ),
webmaster@1: // from locale.inc
webmaster@1: 'locale_admin_manage_screen' => array(
webmaster@1: 'arguments' => array('form' => NULL),
webmaster@1: ),
webmaster@1: // from menu.inc
webmaster@1: 'menu_item_link' => array(
webmaster@1: 'arguments' => array('item' => NULL),
webmaster@1: ),
webmaster@1: 'menu_tree' => array(
webmaster@1: 'arguments' => array('tree' => NULL),
webmaster@1: ),
webmaster@1: 'menu_item' => array(
webmaster@1: 'arguments' => array('link' => NULL, 'has_children' => NULL, 'menu' => ''),
webmaster@1: ),
webmaster@1: 'menu_local_task' => array(
webmaster@1: 'arguments' => array('link' => NULL, 'active' => FALSE),
webmaster@1: ),
webmaster@1: 'menu_local_tasks' => array(
webmaster@1: 'arguments' => array(),
webmaster@1: ),
webmaster@1: // from form.inc
webmaster@1: 'select' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'fieldset' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'radio' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'radios' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'password_confirm' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'date' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'item' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'checkbox' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'checkboxes' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'submit' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'button' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'image_button' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'hidden' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'token' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'textfield' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'form' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'textarea' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'markup' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'password' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'file' => array(
webmaster@1: 'arguments' => array('element' => NULL),
webmaster@1: ),
webmaster@1: 'form_element' => array(
webmaster@1: 'arguments' => array('element' => NULL, 'value' => NULL),
webmaster@1: ),
webmaster@1: );
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @ingroup schemaapi
webmaster@1: * @{
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Get the schema definition of a table, or the whole database schema.
webmaster@1: *
webmaster@1: * The returned schema will include any modifications made by any
webmaster@1: * module that implements hook_schema_alter().
webmaster@1: *
webmaster@1: * @param $table
webmaster@1: * The name of the table. If not given, the schema of all tables is returned.
webmaster@1: * @param $rebuild
webmaster@1: * If true, the schema will be rebuilt instead of retrieved from the cache.
webmaster@1: */
webmaster@1: function drupal_get_schema($table = NULL, $rebuild = FALSE) {
webmaster@1: static $schema = array();
webmaster@1:
webmaster@1: if (empty($schema) || $rebuild) {
webmaster@1: // Try to load the schema from cache.
webmaster@1: if (!$rebuild && $cached = cache_get('schema')) {
webmaster@1: $schema = $cached->data;
webmaster@1: }
webmaster@1: // Otherwise, rebuild the schema cache.
webmaster@1: else {
webmaster@1: $schema = array();
webmaster@1: // Load the .install files to get hook_schema.
webmaster@1: module_load_all_includes('install');
webmaster@1:
webmaster@1: // Invoke hook_schema for all modules.
webmaster@1: foreach (module_implements('schema') as $module) {
webmaster@1: $current = module_invoke($module, 'schema');
webmaster@1: _drupal_initialize_schema($module, $current);
webmaster@1: $schema = array_merge($schema, $current);
webmaster@1: }
webmaster@1:
webmaster@1: drupal_alter('schema', $schema);
webmaster@1: cache_set('schema', $schema);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: if (!isset($table)) {
webmaster@1: return $schema;
webmaster@1: }
webmaster@1: elseif (isset($schema[$table])) {
webmaster@1: return $schema[$table];
webmaster@1: }
webmaster@1: else {
webmaster@1: return FALSE;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Create all tables that a module defines in its hook_schema().
webmaster@1: *
webmaster@1: * Note: This function does not pass the module's schema through
webmaster@1: * hook_schema_alter(). The module's tables will be created exactly as the
webmaster@1: * module defines them.
webmaster@1: *
webmaster@1: * @param $module
webmaster@1: * The module for which the tables will be created.
webmaster@1: * @return
webmaster@1: * An array of arrays with the following key/value pairs:
webmaster@7: * - success: a boolean indicating whether the query succeeded.
webmaster@7: * - query: the SQL query(s) executed, passed through check_plain().
webmaster@1: */
webmaster@1: function drupal_install_schema($module) {
webmaster@1: $schema = drupal_get_schema_unprocessed($module);
webmaster@1: _drupal_initialize_schema($module, $schema);
webmaster@1:
webmaster@1: $ret = array();
webmaster@1: foreach ($schema as $name => $table) {
webmaster@1: db_create_table($ret, $name, $table);
webmaster@1: }
webmaster@1: return $ret;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Remove all tables that a module defines in its hook_schema().
webmaster@1: *
webmaster@1: * Note: This function does not pass the module's schema through
webmaster@1: * hook_schema_alter(). The module's tables will be created exactly as the
webmaster@1: * module defines them.
webmaster@1: *
webmaster@1: * @param $module
webmaster@1: * The module for which the tables will be removed.
webmaster@1: * @return
webmaster@1: * An array of arrays with the following key/value pairs:
webmaster@7: * - success: a boolean indicating whether the query succeeded.
webmaster@7: * - query: the SQL query(s) executed, passed through check_plain().
webmaster@1: */
webmaster@1: function drupal_uninstall_schema($module) {
webmaster@1: $schema = drupal_get_schema_unprocessed($module);
webmaster@1: _drupal_initialize_schema($module, $schema);
webmaster@1:
webmaster@1: $ret = array();
webmaster@1: foreach ($schema as $table) {
webmaster@1: db_drop_table($ret, $table['name']);
webmaster@1: }
webmaster@1: return $ret;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Returns the unprocessed and unaltered version of a module's schema.
webmaster@1: *
webmaster@1: * Use this function only if you explicitly need the original
webmaster@1: * specification of a schema, as it was defined in a module's
webmaster@1: * hook_schema(). No additional default values will be set,
webmaster@1: * hook_schema_alter() is not invoked and these unprocessed
webmaster@1: * definitions won't be cached.
webmaster@1: *
webmaster@1: * This function can be used to retrieve a schema specification in
webmaster@1: * hook_schema(), so it allows you to derive your tables from existing
webmaster@1: * specifications.
webmaster@1: *
webmaster@1: * It is also used by drupal_install_schema() and
webmaster@1: * drupal_uninstall_schema() to ensure that a module's tables are
webmaster@1: * created exactly as specified without any changes introduced by a
webmaster@1: * module that implements hook_schema_alter().
webmaster@1: *
webmaster@1: * @param $module
webmaster@1: * The module to which the table belongs.
webmaster@1: * @param $table
webmaster@1: * The name of the table. If not given, the module's complete schema
webmaster@1: * is returned.
webmaster@1: */
webmaster@1: function drupal_get_schema_unprocessed($module, $table = NULL) {
webmaster@1: // Load the .install file to get hook_schema.
webmaster@1: module_load_include('install', $module);
webmaster@1: $schema = module_invoke($module, 'schema');
webmaster@1:
webmaster@1: if (!is_null($table) && isset($schema[$table])) {
webmaster@1: return $schema[$table];
webmaster@1: }
webmaster@1: else {
webmaster@1: return $schema;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Fill in required default values for table definitions returned by hook_schema().
webmaster@1: *
webmaster@1: * @param $module
webmaster@1: * The module for which hook_schema() was invoked.
webmaster@1: * @param $schema
webmaster@1: * The schema definition array as it was returned by the module's
webmaster@1: * hook_schema().
webmaster@1: */
webmaster@1: function _drupal_initialize_schema($module, &$schema) {
webmaster@1: // Set the name and module key for all tables.
webmaster@1: foreach ($schema as $name => $table) {
webmaster@1: if (empty($table['module'])) {
webmaster@1: $schema[$name]['module'] = $module;
webmaster@1: }
webmaster@1: if (!isset($table['name'])) {
webmaster@1: $schema[$name]['name'] = $name;
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Retrieve a list of fields from a table schema. The list is suitable for use in a SQL query.
webmaster@1: *
webmaster@1: * @param $table
webmaster@1: * The name of the table from which to retrieve fields.
webmaster@1: * @param
webmaster@1: * An optional prefix to to all fields.
webmaster@1: *
webmaster@1: * @return An array of fields.
webmaster@1: **/
webmaster@1: function drupal_schema_fields_sql($table, $prefix = NULL) {
webmaster@1: $schema = drupal_get_schema($table);
webmaster@1: $fields = array_keys($schema['fields']);
webmaster@1: if ($prefix) {
webmaster@1: $columns = array();
webmaster@1: foreach ($fields as $field) {
webmaster@1: $columns[] = "$prefix.$field";
webmaster@1: }
webmaster@1: return $columns;
webmaster@1: }
webmaster@1: else {
webmaster@1: return $fields;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Save a record to the database based upon the schema.
webmaster@1: *
webmaster@1: * Default values are filled in for missing items, and 'serial' (auto increment)
webmaster@1: * types are filled in with IDs.
webmaster@1: *
webmaster@1: * @param $table
webmaster@1: * The name of the table; this must exist in schema API.
webmaster@1: * @param $object
webmaster@1: * The object to write. This is a reference, as defaults according to
webmaster@1: * the schema may be filled in on the object, as well as ID on the serial
webmaster@1: * type(s). Both array an object types may be passed.
webmaster@1: * @param $update
webmaster@1: * If this is an update, specify the primary keys' field names. It is the
webmaster@1: * caller's responsibility to know if a record for this object already
webmaster@1: * exists in the database. If there is only 1 key, you may pass a simple string.
webmaster@1: * @return
webmaster@1: * Failure to write a record will return FALSE. Otherwise SAVED_NEW or
webmaster@1: * SAVED_UPDATED is returned depending on the operation performed. The
webmaster@1: * $object parameter contains values for any serial fields defined by
webmaster@1: * the $table. For example, $object->nid will be populated after inserting
webmaster@1: * a new node.
webmaster@1: */
webmaster@1: function drupal_write_record($table, &$object, $update = array()) {
webmaster@1: // Standardize $update to an array.
webmaster@1: if (is_string($update)) {
webmaster@1: $update = array($update);
webmaster@1: }
webmaster@1:
webmaster@7: $schema = drupal_get_schema($table);
webmaster@7: if (empty($schema)) {
webmaster@7: return FALSE;
webmaster@7: }
webmaster@9:
webmaster@1: // Convert to an object if needed.
webmaster@1: if (is_array($object)) {
webmaster@1: $object = (object) $object;
webmaster@1: $array = TRUE;
webmaster@1: }
webmaster@1: else {
webmaster@1: $array = FALSE;
webmaster@1: }
webmaster@1:
webmaster@1: $fields = $defs = $values = $serials = $placeholders = array();
webmaster@1:
webmaster@1: // Go through our schema, build SQL, and when inserting, fill in defaults for
webmaster@1: // fields that are not set.
webmaster@1: foreach ($schema['fields'] as $field => $info) {
webmaster@1: // Special case -- skip serial types if we are updating.
webmaster@1: if ($info['type'] == 'serial' && count($update)) {
webmaster@1: continue;
webmaster@1: }
webmaster@1:
webmaster@1: // For inserts, populate defaults from Schema if not already provided
webmaster@1: if (!isset($object->$field) && !count($update) && isset($info['default'])) {
webmaster@1: $object->$field = $info['default'];
webmaster@1: }
webmaster@1:
webmaster@1: // Track serial fields so we can helpfully populate them after the query.
webmaster@1: if ($info['type'] == 'serial') {
webmaster@1: $serials[] = $field;
webmaster@1: // Ignore values for serials when inserting data. Unsupported.
webmaster@1: unset($object->$field);
webmaster@1: }
webmaster@1:
webmaster@1: // Build arrays for the fields, placeholders, and values in our query.
webmaster@1: if (isset($object->$field)) {
webmaster@1: $fields[] = $field;
webmaster@1: $placeholders[] = db_type_placeholder($info['type']);
webmaster@1:
webmaster@1: if (empty($info['serialize'])) {
webmaster@1: $values[] = $object->$field;
webmaster@1: }
webmaster@1: else {
webmaster@1: $values[] = serialize($object->$field);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: // Build the SQL.
webmaster@1: $query = '';
webmaster@1: if (!count($update)) {
webmaster@1: $query = "INSERT INTO {". $table ."} (". implode(', ', $fields) .') VALUES ('. implode(', ', $placeholders) .')';
webmaster@1: $return = SAVED_NEW;
webmaster@1: }
webmaster@1: else {
webmaster@1: $query = '';
webmaster@1: foreach ($fields as $id => $field) {
webmaster@1: if ($query) {
webmaster@1: $query .= ', ';
webmaster@1: }
webmaster@1: $query .= $field .' = '. $placeholders[$id];
webmaster@1: }
webmaster@1:
webmaster@1: foreach ($update as $key){
webmaster@1: $conditions[] = "$key = ". db_type_placeholder($schema['fields'][$key]['type']);
webmaster@1: $values[] = $object->$key;
webmaster@1: }
webmaster@1:
webmaster@1: $query = "UPDATE {". $table ."} SET $query WHERE ". implode(' AND ', $conditions);
webmaster@1: $return = SAVED_UPDATED;
webmaster@1: }
webmaster@1:
webmaster@1: // Execute the SQL.
webmaster@1: if (db_query($query, $values)) {
webmaster@1: if ($serials) {
webmaster@1: // Get last insert ids and fill them in.
webmaster@1: foreach ($serials as $field) {
webmaster@1: $object->$field = db_last_insert_id($table, $field);
webmaster@1: }
webmaster@1: }
webmaster@1: }
webmaster@7: else {
webmaster@7: $return = FALSE;
webmaster@7: }
webmaster@7:
webmaster@7: // If we began with an array, convert back so we don't surprise the caller.
webmaster@7: if ($array) {
webmaster@7: $object = (array) $object;
webmaster@7: }
webmaster@7:
webmaster@7: return $return;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @} End of "ingroup schemaapi".
webmaster@1: */
webmaster@1:
webmaster@1: /**
webmaster@1: * Parse Drupal info file format.
webmaster@1: *
webmaster@1: * Files should use an ini-like format to specify values.
webmaster@1: * White-space generally doesn't matter, except inside values.
webmaster@1: * e.g.
webmaster@1: *
webmaster@1: * @verbatim
webmaster@1: * key = value
webmaster@1: * key = "value"
webmaster@1: * key = 'value'
webmaster@1: * key = "multi-line
webmaster@1: *
webmaster@1: * value"
webmaster@1: * key = 'multi-line
webmaster@1: *
webmaster@1: * value'
webmaster@1: * key
webmaster@1: * =
webmaster@1: * 'value'
webmaster@1: * @endverbatim
webmaster@1: *
webmaster@1: * Arrays are created using a GET-like syntax:
webmaster@1: *
webmaster@1: * @verbatim
webmaster@1: * key[] = "numeric array"
webmaster@1: * key[index] = "associative array"
webmaster@1: * key[index][] = "nested numeric array"
webmaster@1: * key[index][index] = "nested associative array"
webmaster@1: * @endverbatim
webmaster@1: *
webmaster@1: * PHP constants are substituted in, but only when used as the entire value:
webmaster@1: *
webmaster@1: * Comments should start with a semi-colon at the beginning of a line.
webmaster@1: *
webmaster@1: * This function is NOT for placing arbitrary module-specific settings. Use
webmaster@1: * variable_get() and variable_set() for that.
webmaster@1: *
webmaster@1: * Information stored in the module.info file:
webmaster@1: * - name: The real name of the module for display purposes.
webmaster@1: * - description: A brief description of the module.
webmaster@1: * - dependencies: An array of shortnames of other modules this module depends on.
webmaster@1: * - package: The name of the package of modules this module belongs to.
webmaster@1: *
webmaster@1: * Example of .info file:
webmaster@1: * @verbatim
webmaster@1: * name = Forum
webmaster@1: * description = Enables threaded discussions about general topics.
webmaster@1: * dependencies[] = taxonomy
webmaster@1: * dependencies[] = comment
webmaster@1: * package = Core - optional
webmaster@1: * version = VERSION
webmaster@1: * @endverbatim
webmaster@1: *
webmaster@1: * @param $filename
webmaster@1: * The file we are parsing. Accepts file with relative or absolute path.
webmaster@1: * @return
webmaster@1: * The info array.
webmaster@1: */
webmaster@1: function drupal_parse_info_file($filename) {
webmaster@1: $info = array();
webmaster@1:
webmaster@1: if (!file_exists($filename)) {
webmaster@1: return $info;
webmaster@1: }
webmaster@1:
webmaster@1: $data = file_get_contents($filename);
webmaster@1: if (preg_match_all('
webmaster@1: @^\s* # Start at the beginning of a line, ignoring leading whitespace
webmaster@1: ((?:
webmaster@1: [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
webmaster@1: \[[^\[\]]*\] # unless they are balanced and not nested
webmaster@1: )+?)
webmaster@1: \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
webmaster@1: (?:
webmaster@1: ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
webmaster@1: (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
webmaster@1: ([^\r\n]*?) # Non-quoted string
webmaster@1: )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
webmaster@1: @msx', $data, $matches, PREG_SET_ORDER)) {
webmaster@1: foreach ($matches as $match) {
webmaster@1: // Fetch the key and value string
webmaster@1: $i = 0;
webmaster@1: foreach (array('key', 'value1', 'value2', 'value3') as $var) {
webmaster@1: $$var = isset($match[++$i]) ? $match[$i] : '';
webmaster@1: }
webmaster@1: $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
webmaster@1:
webmaster@1: // Parse array syntax
webmaster@1: $keys = preg_split('/\]?\[/', rtrim($key, ']'));
webmaster@1: $last = array_pop($keys);
webmaster@1: $parent = &$info;
webmaster@1:
webmaster@1: // Create nested arrays
webmaster@1: foreach ($keys as $key) {
webmaster@1: if ($key == '') {
webmaster@1: $key = count($parent);
webmaster@1: }
webmaster@1: if (!isset($parent[$key]) || !is_array($parent[$key])) {
webmaster@1: $parent[$key] = array();
webmaster@1: }
webmaster@1: $parent = &$parent[$key];
webmaster@1: }
webmaster@1:
webmaster@1: // Handle PHP constants
webmaster@1: if (defined($value)) {
webmaster@1: $value = constant($value);
webmaster@1: }
webmaster@1:
webmaster@1: // Insert actual value
webmaster@1: if ($last == '') {
webmaster@1: $last = count($parent);
webmaster@1: }
webmaster@1: $parent[$last] = $value;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: return $info;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * @return
webmaster@1: * Array of the possible severity levels for log messages.
webmaster@1: *
webmaster@1: * @see watchdog
webmaster@1: */
webmaster@1: function watchdog_severity_levels() {
webmaster@1: return array(
webmaster@1: WATCHDOG_EMERG => t('emergency'),
webmaster@1: WATCHDOG_ALERT => t('alert'),
webmaster@1: WATCHDOG_CRITICAL => t('critical'),
webmaster@1: WATCHDOG_ERROR => t('error'),
webmaster@1: WATCHDOG_WARNING => t('warning'),
webmaster@1: WATCHDOG_NOTICE => t('notice'),
webmaster@1: WATCHDOG_INFO => t('info'),
webmaster@1: WATCHDOG_DEBUG => t('debug'),
webmaster@1: );
webmaster@1: }
webmaster@1:
webmaster@1:
webmaster@1: /**
webmaster@1: * Explode a string of given tags into an array.
webmaster@1: */
webmaster@1: function drupal_explode_tags($tags) {
webmaster@1: // This regexp allows the following types of user input:
webmaster@1: // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
webmaster@1: $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
webmaster@1: preg_match_all($regexp, $tags, $matches);
webmaster@1: $typed_tags = array_unique($matches[1]);
webmaster@1:
webmaster@1: $tags = array();
webmaster@1: foreach ($typed_tags as $tag) {
webmaster@1: // If a user has escaped a term (to demonstrate that it is a group,
webmaster@1: // or includes a comma or quote character), we remove the escape
webmaster@1: // formatting so to save the term into the database as the user intends.
webmaster@1: $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
webmaster@1: if ($tag != "") {
webmaster@1: $tags[] = $tag;
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: return $tags;
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Implode an array of tags into a string.
webmaster@1: */
webmaster@1: function drupal_implode_tags($tags) {
webmaster@1: $encoded_tags = array();
webmaster@1: foreach ($tags as $tag) {
webmaster@1: // Commas and quotes in tag names are special cases, so encode them.
webmaster@1: if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
webmaster@1: $tag = '"'. str_replace('"', '""', $tag) .'"';
webmaster@1: }
webmaster@1:
webmaster@1: $encoded_tags[] = $tag;
webmaster@1: }
webmaster@1: return implode(', ', $encoded_tags);
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Flush all cached data on the site.
webmaster@1: *
webmaster@1: * Empties cache tables, rebuilds the menu cache and theme registries, and
webmaster@7: * invokes a hook so that other modules' cache data can be cleared as well.
webmaster@1: */
webmaster@1: function drupal_flush_all_caches() {
webmaster@1: // Change query-strings on css/js files to enforce reload for all users.
webmaster@1: _drupal_flush_css_js();
webmaster@1:
webmaster@1: drupal_clear_css_cache();
webmaster@1: drupal_clear_js_cache();
webmaster@7: system_theme_data();
webmaster@1: drupal_rebuild_theme_registry();
webmaster@1: menu_rebuild();
webmaster@1: node_types_rebuild();
webmaster@1: // Don't clear cache_form - in-progress form submissions may break.
webmaster@1: // Ordered so clearing the page cache will always be the last action.
webmaster@1: $core = array('cache', 'cache_block', 'cache_filter', 'cache_page');
webmaster@1: $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
webmaster@1: foreach ($cache_tables as $table) {
webmaster@1: cache_clear_all('*', $table, TRUE);
webmaster@1: }
webmaster@1: }
webmaster@1:
webmaster@1: /**
webmaster@1: * Helper function to change query-strings on css/js files.
webmaster@1: *
webmaster@1: * Changes the character added to all css/js files as dummy query-string,
webmaster@1: * so that all browsers are forced to reload fresh files. We keep
webmaster@1: * 20 characters history (FIFO) to avoid repeats, but only the first
webmaster@1: * (newest) character is actually used on urls, to keep them short.
webmaster@1: * This is also called from update.php.
webmaster@1: */
webmaster@1: function _drupal_flush_css_js() {
webmaster@1: $string_history = variable_get('css_js_query_string', '00000000000000000000');
webmaster@1: $new_character = $string_history[0];
webmaster@1: $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
webmaster@1: while (strpos($string_history, $new_character) !== FALSE) {
webmaster@1: $new_character = $characters[mt_rand(0, strlen($characters) - 1)];
webmaster@1: }
webmaster@1: variable_set('css_js_query_string', $new_character . substr($string_history, 0, 19));
webmaster@1: }