Newer
Older
Dries Buytaert
committed
// $Id$
/**
* @file
* Common functions that many Drupal modules will need to reference.
*
* The functions that are critical and need to be available even when serving
* a cached page are instead located in bootstrap.inc.
*/
Steven Wittens
committed
/**
* Return status for saving which involved creating a new item.
*/
define('SAVED_NEW', 1);
/**
* Return status for saving which involved an update to an existing item.
*/
define('SAVED_UPDATED', 2);
/**
* Return status for saving which deleted an existing item.
*/
define('SAVED_DELETED', 3);
/**
* Set content for a specified region.
*
* @param $region
* Page region the content is assigned to.
* @param $data
* Content to be set.
*/
function drupal_set_content($region = NULL, $data = NULL) {
static $content = array();
if (!is_null($region) && !is_null($data)) {
$content[$region][] = $data;
}
return $content;
}
/**
* Get assigned content.
*
* @param $region
* A specified region to fetch content for. If NULL, all regions will be
* returned.
* @param $delimiter
* Content to be inserted between exploded array elements.
*/
function drupal_get_content($region = NULL, $delimiter = ' ') {
$content = drupal_set_content();
if (isset($region)) {
if (isset($content[$region]) && is_array($content[$region])) {
}
else {
foreach (array_keys($content) as $region) {
if (is_array($content[$region])) {
$content[$region] = implode($delimiter, $content[$region]);
}
}
return $content;
}
}
* @param $breadcrumb
* Array of links, starting with "home" and proceeding up to but not including
* the current page.
function drupal_set_breadcrumb($breadcrumb = NULL) {
static $stored_breadcrumb;
if (!is_null($breadcrumb)) {
$stored_breadcrumb = $breadcrumb;
}
return $stored_breadcrumb;
}
function drupal_get_breadcrumb() {
$breadcrumb = drupal_set_breadcrumb();
if (is_null($breadcrumb)) {
$breadcrumb = menu_get_active_breadcrumb();
}
return $breadcrumb;
}
*/
function drupal_set_html_head($data = NULL) {
/**
* Retrieve output to be displayed in the head tag of the HTML page.
*/
$output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
return $output . drupal_set_html_head();
}
* Reset the static variable which holds the aliases mapped for this request.
function drupal_clear_path_cache() {
drupal_lookup_path('wipe');
* Note: When sending a Content-Type header, always include a 'charset' type,
* too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
*/
function drupal_set_header($header = NULL) {
// We use an array to guarantee there are no leading or trailing delimiters.
// Otherwise, header('') could get called when serving the page later, which
// ends HTTP headers prematurely on some PHP versions.
static $stored_headers = array();
$stored_headers[] = $header;
return implode("\n", $stored_headers);
function drupal_get_headers() {
return drupal_set_header();
}
* Add a feed URL for the current page.
*
* @param $url
* A url for the feed.
* @param $title
* The title of the feed.
function drupal_add_feed($url = NULL, $title = '') {
static $stored_feed_links = array();
Gábor Hojtsy
committed
if (!is_null($url) && !isset($stored_feed_links[$url])) {
$stored_feed_links[$url] = theme('feed_icon', $url, $title);
drupal_add_link(array('rel' => 'alternate',
'type' => 'application/rss+xml',
'title' => $title,
'href' => $url));
}
return $stored_feed_links;
}
/**
* Get the feed URLs for the current page.
*
* @param $delimiter
* A delimiter to split feeds by.
*/
function drupal_get_feeds($delimiter = "\n") {
$feeds = drupal_add_feed();
return implode($feeds, $delimiter);
}
Gerhard Killesreiter
committed
/**
* Parse an array into a valid urlencoded query string.
*
* @param $query
* The array to be processed e.g. $_GET.
Gerhard Killesreiter
committed
* @param $exclude
* The array filled with keys to be excluded. Use parent[child] to exclude
* nested items.
Gerhard Killesreiter
committed
* @param $parent
* Should not be passed, only used in recursive calls.
Gerhard Killesreiter
committed
* @return
* An urlencoded string which can be appended to/as the URL query string.
Gerhard Killesreiter
committed
*/
function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
$params = array();
foreach ($query as $key => $value) {
Gerhard Killesreiter
committed
if ($parent) {
$key = $parent .'['. $key .']';
Gerhard Killesreiter
committed
}
if (in_array($key, $exclude)) {
Gerhard Killesreiter
committed
continue;
}
if (is_array($value)) {
$params[] = drupal_query_string_encode($value, $exclude, $key);
}
else {
$params[] = $key .'='. drupal_urlencode($value);
Gerhard Killesreiter
committed
}
}
return implode('&', $params);
}
/**
* Prepare a destination query string for use in combination with drupal_goto().
* Used to direct the user back to the referring page after completing a form.
* By default the current URL is returned. If a destination exists in the
* previous request, that destination is returned. As such, a destination can
* persist across multiple pages.
*
* @see drupal_goto()
*/
function drupal_get_destination() {
if (isset($_REQUEST['destination'])) {
Dries Buytaert
committed
return 'destination='. urlencode($_REQUEST['destination']);
}
else {
// Use $_GET here to retrieve the original path in source form.
$path = isset($_GET['q']) ? $_GET['q'] : '';
Gerhard Killesreiter
committed
$query = drupal_query_string_encode($_GET, array('q'));
if ($query != '') {
$path .= '?'. $query;
Gerhard Killesreiter
committed
}
Gerhard Killesreiter
committed
return 'destination='. urlencode($path);
}
}
* This issues an on-site HTTP redirect. The function makes sure the redirected
* URL is formatted correctly.
* Usually the redirected URL is constructed from this function's input
* parameters. However you may override that behavior by setting a
* <em>destination</em> in either the $_REQUEST-array (i.e. by using
* the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
* using a hidden form field). This is used to direct the user back to
* the proper page after completing a form. For example, after editing
* a post on the 'admin/content/node'-page or after having logged on using the
* 'user login'-block in a sidebar. The function drupal_get_destination()
* can be used to help set the destination URL.
*
* It is advised to use drupal_goto() instead of PHP's header(), because
* drupal_goto() will append the user's session ID to the URI when PHP is
* compiled with "--enable-trans-sid". In addition, Drupal will ensure that
Dries Buytaert
committed
* messages set by drupal_set_message() and other session data are written to
* the database before the user is redirected.
*
* This function ends the request; use it rather than a print theme('page')
* statement in your menu callback.
*
* @param $path
* A Drupal path or a full URL.
* A query string component, if any.
* A destination fragment identifier (named anchor).
* @param $http_response_code
* Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
* - 301 Moved Permanently (the recommended value for most redirects)
* - 302 Found (default in Drupal and PHP, sometimes used for spamming search
* engines)
* - 303 See Other
* - 304 Not Modified
* - 305 Use Proxy
* - 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")
* Note: Other values are defined by RFC 2616, but are rarely used and poorly
* supported.
* @see drupal_get_destination()
function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
if (isset($_REQUEST['destination'])) {
extract(parse_url(urldecode($_REQUEST['destination'])));
}
else if (isset($_REQUEST['edit']['destination'])) {
extract(parse_url(urldecode($_REQUEST['edit']['destination'])));
}
$url = url($path, array('query' => $query, 'fragment' => $fragment, 'absolute' => TRUE));
// Allow modules to react to the end of the page request before redirecting.
Dries Buytaert
committed
// Even though session_write_close() is registered as a shutdown function, we
// need all session data written to the database before redirecting.
Dries Buytaert
committed
session_write_close();
Dries Buytaert
committed
Dries Buytaert
committed
header('Location: '. $url, TRUE, $http_response_code);
// The "Location" header sends a redirect status code to the HTTP daemon. In
// some cases this can be wrong, so we make sure none of the code below the
// drupal_goto() call gets executed upon redirection.
Dries Buytaert
committed
/**
* Generates a site off-line message.
Dries Buytaert
committed
*/
function drupal_site_offline() {
drupal_maintenance_theme();
Dries Buytaert
committed
drupal_set_header('HTTP/1.1 503 Service unavailable');
drupal_set_title(t('Site off-line'));
Steven Wittens
committed
print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
Dries Buytaert
committed
}
/**
* Generates a 404 error if the request can not be handled.
*/
Dries Buytaert
committed
drupal_set_header('HTTP/1.1 404 Not Found');
watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
// Keep old path for reference.
if (!isset($_REQUEST['destination'])) {
$_REQUEST['destination'] = $_GET['q'];
}
Gábor Hojtsy
committed
// Set the active item in case there are tabs to display, or other
// dependencies on the path.
menu_set_active_item($path);
Dries Buytaert
committed
$return = menu_execute_active_handler($path);
Gerhard Killesreiter
committed
}
if (empty($return)) {
drupal_set_title(t('Page not found'));
Steven Wittens
committed
$return = '';
// To conserve CPU and bandwidth, omit the blocks.
Dries Buytaert
committed
print theme('page', $return, FALSE);
/**
* Generates a 403 error if the request is not allowed.
*/
function drupal_access_denied() {
Dries Buytaert
committed
drupal_set_header('HTTP/1.1 403 Forbidden');
watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
// Keep old path for reference.
if (!isset($_REQUEST['destination'])) {
$_REQUEST['destination'] = $_GET['q'];
}
// Set the active item in case there are tabs to display or other
Gábor Hojtsy
committed
// dependencies on the path.
menu_set_active_item($path);
Dries Buytaert
committed
$return = menu_execute_active_handler($path);
Gerhard Killesreiter
committed
}
if (empty($return)) {
drupal_set_title(t('Access denied'));
$return = t('You are not authorized to access this page.');
print theme('page', $return);
* This is a flexible and powerful HTTP client implementation. Correctly handles
* GET, POST, PUT or any other HTTP requests. Handles redirects.
*
* @param $url
* A string containing a fully qualified URI.
* @param $headers
* An array containing an HTTP header => value pair.
* @param $method
* A string defining the HTTP request to use.
* @param $data
* A string containing data to include in the request.
* @param $retry
* An integer representing how many times to retry the request in case of a
* redirect.
* @return
* An object containing the HTTP request headers, response code, headers,
* data and redirect status.
*/
function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
$result = new stdClass();
// Parse the URL and make sure we can handle the schema.
Dries Buytaert
committed
$port = isset($uri['port']) ? $uri['port'] : 80;
$host = $uri['host'] . ($port != 80 ? ':'. $port : '');
Dries Buytaert
committed
$fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
$port = isset($uri['port']) ? $uri['port'] : 443;
$host = $uri['host'] . ($port != 443 ? ':'. $port : '');
Dries Buytaert
committed
$fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
// When a network error occurs, we make sure that it is a negative number so
// it can clash with the HTTP status codes.
Dries Buytaert
committed
$result->code = -$errno;
$result->error = trim($errstr);
$path = isset($uri['path']) ? $uri['path'] : '/';
if (isset($uri['query'])) {
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
// We don't add the port to prevent from breaking rewrite rules checking the
// host that do not take into account the port number.
'Host' => "Host: $host",
Dries Buytaert
committed
'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
'Content-Length' => 'Content-Length: '. strlen($data)
// If the server url has a user then attempt to use basic authentication
if (isset($uri['user'])) {
$defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
}
$request = $method .' '. $path ." HTTP/1.0\r\n";
$request .= implode("\r\n", $defaults);
$request .= "\r\n\r\n";
if ($data) {
}
$result->request = $request;
fwrite($fp, $request);
// Fetch response.
Dries Buytaert
committed
while (!feof($fp) && $chunk = fread($fp, 1024)) {
$response .= $chunk;
Dries Buytaert
committed
list($split, $result->data) = explode("\r\n\r\n", $response, 2);
$split = preg_split("/\r\n|\n|\r/", $split);
Dries Buytaert
committed
list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
Dries Buytaert
committed
while ($line = trim(array_shift($split))) {
if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
// RFC 2109: the Set-Cookie response header comprises the token Set-
// Cookie:, followed by a comma-separated list of one or more cookies.
$result->headers[$header] .= ','. trim($value);
}
else {
$result->headers[$header] = trim($value);
}
}
$responses = array(
100 => 'Continue', 101 => 'Switching Protocols',
200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
);
// RFC 2616 states that all unknown HTTP codes must be treated the same as the
// base code in their class.
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
switch ($code) {
case 200: // OK
case 304: // Not modified
break;
case 301: // Moved permanently
case 302: // Moved temporarily
case 307: // Moved temporarily
$location = $result->headers['Location'];
if ($retry) {
$result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
$result->redirect_code = $result->code;
}
$result->redirect_url = $location;
break;
default:
$result->error = $text;
}
$result->code = $code;
return $result;
}
* Log errors as defined by administrator.
* - 0 = Log errors to database.
* - 1 = Log errors to database and to screen.
Gábor Hojtsy
committed
function drupal_error_handler($errno, $message, $filename, $line, $context) {
// If the @ error suppression operator was used, error_reporting is
// temporarily set to 0.
Neil Drumm
committed
if (error_reporting() == 0) {
return;
}
if ($errno & (E_ALL)) {
$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');
Gábor Hojtsy
committed
// For database errors, we want the line number/file name of the place that
// the query was originally called, not _db_query().
if (isset($context[DB_ERROR])) {
$backtrace = array_reverse(debug_backtrace());
// List of functions where SQL queries can originate.
$query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
// Determine where query function was called, and adjust line/file
// accordingly.
foreach ($backtrace as $index => $function) {
if (in_array($function['function'], $query_functions)) {
$line = $backtrace[$index]['line'];
$filename = $backtrace[$index]['file'];
break;
}
}
}
$entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';
// Force display of error messages in update.php.
if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
drupal_set_message($entry, 'error');
watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
array_walk($item, '_fix_gpc_magic');
}
else {
Neil Drumm
committed
/**
* Helper function to strip slashes from $_FILES skipping over the tmp_name keys
* since PHP generates single backslashes for file paths on Windows systems.
*
* tmp_name does not have backslashes added see
* http://php.net/manual/en/features.file-upload.php#42280
*/
function _fix_gpc_magic_files(&$item, $key) {
if ($key != 'tmp_name') {
if (is_array($item)) {
array_walk($item, '_fix_gpc_magic_files');
}
else {
$item = stripslashes($item);
}
}
}
* Fix double-escaping problems caused by "magic quotes" in some PHP installations.
static $fixed = FALSE;
array_walk($_GET, '_fix_gpc_magic');
array_walk($_POST, '_fix_gpc_magic');
array_walk($_COOKIE, '_fix_gpc_magic');
array_walk($_REQUEST, '_fix_gpc_magic');
Neil Drumm
committed
array_walk($_FILES, '_fix_gpc_magic_files');
$fixed = TRUE;
Gábor Hojtsy
committed
* Translate strings to the page language or a given language.
* All human-readable text that will be displayed somewhere within a page should
* be run through the t() function.
*
* Examples:
* @code
* if (!$info || !$info['extension']) {
* form_set_error('picture_upload', t('The uploaded file was not an image.'));
* }
*
* $form['submit'] = array(
* '#type' => 'submit',
* '#value' => t('Log in'),
* );
* @endcode
*
* Any text within t() can be extracted by translators and changed into
* the equivalent text in their native language.
*
* Special variables called "placeholders" are used to signal dynamic
* information in a string which should not be translated. Placeholders
* can also be used for text that may change from time to time
* (such as link paths) to be changed without requiring updates to translations.
*
* For example:
* @code
* $output = t('There are currently %members and %visitors online.', array(
* '%members' => format_plural($total_users, '1 user', '@count users'),
* '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
* @endcode
*
* There are three styles of placeholders:
* - !variable, which indicates that the text should be inserted as-is. This is
* useful for inserting variables into things like e-mail.
* @code
* $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))));
* @endcode
*
* - @variable, which indicates that the text should be run through check_plain,
* to strip out HTML characters. Use this for any output that's displayed within
* a Drupal page.
* @code
* drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
* @endcode
*
* - %variable, which indicates that the string should be highlighted with
* theme_placeholder() which shows up by default as <em>emphasized</em>.
* @code
* $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
* When using t(), try to put entire sentences and strings in one t() call.
* This makes it easier for translators, as it provides context as to what each
* word refers to. HTML markup within translation strings is allowed, but should
* be avoided if possible. The exception are embedded links; link titles add a
* context for translators, so should be kept in the main string.
* Here is an example of incorrect usage of t():
* @code
* $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
* @endcode
*
* Here is an example of t() used correctly:
* @code
* $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
* @endcode
*
* Also avoid escaping quotation marks wherever possible.
*
* Incorrect:
* @code
* $output .= t('Don\'t click me.');
* @endcode
*
* Correct:
* $output .= t("Don't click me.");
* @param $args
* An associative array of replacements to make after translation. Incidences
* Based on the first character of the key, the value is escaped and/or themed:
* - !variable: inserted as is
* - @variable: escape plain text to HTML (check_plain)
* - %variable: escape text and theme as a placeholder for user-submitted
* content (check_plain + theme_placeholder)
Gábor Hojtsy
committed
* @param $langcode
* Optional language code to translate to a language other than what is used
* to display the page.
Gábor Hojtsy
committed
function t($string, $args = array(), $langcode = NULL) {
global $language;
static $custom_strings;
Gábor Hojtsy
committed
$langcode = isset($langcode) ? $langcode : $language->language;
// First, check for an array of customized strings. If present, use the array
// *instead of* database lookups. This is a high performance way to provide a
// handful of string replacements. See settings.php for examples.
// Cache the $custom_strings variable to improve performance.
Gábor Hojtsy
committed
if (!isset($custom_strings[$langcode])) {
$custom_strings[$langcode] = variable_get('locale_custom_strings_'. $langcode, array());
}
// Custom strings work for English too, even if locale module is disabled.
Gábor Hojtsy
committed
if (isset($custom_strings[$langcode][$string])) {
$string = $custom_strings[$langcode][$string];
}
// Translate with locale module if enabled.
Gábor Hojtsy
committed
elseif (function_exists('locale') && $langcode != 'en') {
$string = locale($string, $langcode);
Gábor Hojtsy
committed
if (empty($args)) {
// Transform arguments before inserting them.
foreach ($args as $key => $value) {
Neil Drumm
committed
switch ($key[0]) {
case '@':
// Escaped only.
Neil Drumm
committed
$args[$key] = check_plain($value);
break;
Neil Drumm
committed
case '%':
default:
// Escaped and placeholder.
Neil Drumm
committed
$args[$key] = theme('placeholder', $value);
break;
Neil Drumm
committed
case '!':
// Pass-through.
Neil Drumm
committed
}
}
Dries Buytaert
committed
/**
* Verify the syntax of the given e-mail address.
*
* Empty e-mail addresses are allowed. See RFC 2822 for details.
Dries Buytaert
committed
*
* A string containing an e-mail address.
Dries Buytaert
committed
*/
Dries Buytaert
committed
$user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
Dries Buytaert
committed
$domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
Dries Buytaert
committed
$ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
$ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
Dries Buytaert
committed
}
* This function should only be used on actual URLs. It should not be used for
* Drupal menu paths, which can contain arbitrary characters.
*
* Whether the URL is absolute (beginning with a scheme such as "http:").
Dries Buytaert
committed
$allowed_characters = '[a-z0-9\/:_\-_\.\?\$,;~=#&%\+]';
Dries Buytaert
committed
if ($absolute) {
return preg_match("/^(http|https|ftp):\/\/". $allowed_characters ."+$/i", $url);
Dries Buytaert
committed
}
else {
return preg_match("/^". $allowed_characters ."+$/i", $url);
Dries Buytaert
committed
}
/**
* Register an event for the current visitor (hostname/IP) to the flood control mechanism.
*
* @param $name
* The name of an event.
Dries Buytaert
committed
db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, ip_address(), time());
}
/**
* Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
*
* The user is allowed to proceed if he did not trigger the specified event more
* than $threshold times per hour.
*
* @param $name
* The name of the event.
* @param $number
* The maximum number of the specified event per hour (per visitor).
* @return
* True if the user did not exceed the hourly threshold. False otherwise.
Dries Buytaert
committed
$number = db_result(db_query("SELECT COUNT(*) FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, ip_address(), time() - 3600));
Kjartan Mannes
committed
function check_file($filename) {
return is_uploaded_file($filename);
/**
* Prepare a URL for use in an HTML attribute. Strips harmful protocols.
*/
function check_url($uri) {
return filter_xss_bad_protocol($uri, FALSE);
/**
* Formats an RSS channel.
*
* Arbitrary elements may be added using the $args associative array.
*/
Gábor Hojtsy
committed
function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
global $language;
$langcode = $langcode ? $langcode : $language->language;
$output .= ' <title>'. check_plain($title) ."</title>\n";
$output .= ' <link>'. check_url($link) ."</link>\n";
// The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
// We strip all HTML tags, but need to prevent double encoding from properly
// escaped source data (such as & becoming &amp;).
$output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
Gábor Hojtsy
committed
$output .= ' <language>'. check_plain($langcode) ."</language>\n";
$output .= format_xml_elements($args);
$output .= $items;
$output .= "</channel>\n";
return $output;
}
/**
* Format a single RSS item.
*
* Arbitrary elements may be added using the $args associative array.
*/
function format_rss_item($title, $link, $description, $args = array()) {
$output .= ' <title>'. check_plain($title) ."</title>\n";
$output .= ' <link>'. check_url($link) ."</link>\n";
$output .= ' <description>'. check_plain($description) ."</description>\n";
$output .= format_xml_elements($args);
$output .= "</item>\n";
return $output;
}
/**
* Format XML elements.
*
* @param $array
* An array where each item represent an element and is either a:
* - (key => value) pair (<key>value</key>)
* - Associative array with fields:
* - 'key': element name
* - 'value': element contents
* - 'attributes': associative array of element attributes
*
* In both cases, 'value' can be a simple string, or it can be another array
* with the same format as $array itself for nesting.
*/
function format_xml_elements($array) {
Steven Wittens
committed
$output = '';
foreach ($array as $key => $value) {
if (is_numeric($key)) {
Dries Buytaert
committed
if (isset($value['attributes']) && is_array($value['attributes'])) {
if ($value['value'] != '') {
$output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
$output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
* This function ensures that the string is pluralized correctly. Since t() is
* called by this function, make sure not to pass already-localized strings to
* it.
* For example:
* @code
* $output = format_plural($node->comment_count, '1 comment', '@count comments');
* @endcode
*
* Example with additional replacements:
* @code
* $output = format_plural($update_count,
* 'Changed the content type of 1 post from %old-type to %new-type.',
* 'Changed the content type of @count posts from %old-type to %new-type.',
* array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));
* @endcode
*
* @param $count
* The item count to display.
* @param $singular
* The string for the singular case. Please make sure it is clear this is
* singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
* Do not use @count in the singular string.
* @param $plural
* The string for the plural case. Please make sure it is clear this is plural,
* to ease translation. Use @count in place of the item count, as in "@count
* @param $args
* An associative array of replacements to make after translation. Incidences
* of any key in this array are replaced with the corresponding value.
* Based on the first character of the key, the value is escaped and/or themed:
* - !variable: inserted as is
* - @variable: escape plain text to HTML (check_plain)
* - %variable: escape text and theme as a placeholder for user-submitted
* content (check_plain + theme_placeholder)
* Note that you do not need to include @count in this array.
* This replacement is done automatically for the plural case.
Gábor Hojtsy
committed
* @param $langcode
* Optional language code to translate to a language other than
* what is used to display the page.
Gábor Hojtsy
committed
function format_plural($count, $singular, $plural, $args = array(), $langcode = NULL) {
Gábor Hojtsy
committed
$args['@count'] = $count;