common.inc
<?php
function drupal_set_breadcrumb($breadcrumb = NULL) {
static $stored_breadcrumb;
if (isset($breadcrumb)) {
$stored_breadcrumb = $breadcrumb;
}
return $stored_breadcrumb;
}
function drupal_get_breadcrumb() {
$breadcrumb = drupal_set_breadcrumb();
if (!isset($breadcrumb)) {
$breadcrumb = menu_get_active_breadcrumb();
}
return $breadcrumb;
}
function drupal_set_html_head($data = NULL) {
static $stored_head = '';
if (!is_null($data)) {
$stored_head .= $data ."\n";
}
return $stored_head;
}
function drupal_get_html_head() {
global $base_url;
$output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
$output .= "<base href=\"$base_url/\" />\n";
$output .= theme('stylesheet_import', 'misc/drupal.css');
return $output . drupal_set_html_head();
}
function drupal_rebuild_path_map() {
drupal_get_path_map('rebuild');
}
function drupal_get_normal_path($path) {
if (($map = drupal_get_path_map()) && isset($map[$path])) {
return $map[$path];
}
elseif (function_exists('conf_url_rewrite')) {
return conf_url_rewrite($path, 'incoming');
}
else {
return $path;
}
}
function drupal_set_header($header = NULL) {
static $stored_headers = array();
if (strlen($header)) {
header($header);
$stored_headers[] = $header;
}
return implode("\n", $stored_headers);
}
function drupal_get_headers() {
return drupal_set_header();
}
function drupal_get_destination() {
$destination[] = $_GET['q'];
$params = array('from', 'sort', 'order');
foreach ($params as $param) {
if (isset($_GET[$param])) {
$destination[] = "$param=". $_GET[$param];
}
}
return 'destination='. urlencode(implode('&', $destination));
}
function drupal_goto($path = '', $query = NULL, $fragment = NULL) {
if ($_REQUEST['destination']) {
extract(parse_url($_REQUEST['destination']));
}
else if ($_REQUEST['edit']['destination']) {
extract(parse_url($_REQUEST['edit']['destination']));
}
$url = url($path, $query, $fragment, TRUE);
if (ini_get('session.use_trans_sid') && session_id() && !strstr($url, session_id())) {
$sid = session_name() . '=' . session_id();
if (strstr($url, '?') && !strstr($url, $sid)) {
$url = $url .'&'. $sid;
}
else {
$url = $url .'?'. $sid;
}
}
module_invoke_all('exit', $url);
header('Location: '. $url);
exit();
}
function drupal_not_found() {
drupal_set_header('HTTP/1.0 404 Not Found');
watchdog('page not found', t('%page not found.', array('%page' => theme('placeholder', $_GET['q']))), WATCHDOG_WARNING);
$path = drupal_get_normal_path(variable_get('site_404', ''));
$status = MENU_NOT_FOUND;
if ($path && $path != $_GET['q']) {
menu_set_active_item($path);
$status = menu_execute_active_handler();
}
if ($status != MENU_FOUND) {
drupal_set_title(t('Page not found'));
print theme('page', '');
}
}
function drupal_access_denied() {
drupal_set_header('HTTP/1.0 403 Forbidden');
watchdog('access denied', t('%page denied access.', array('%page' => theme('placeholder', $_GET['q']))), WATCHDOG_WARNING, l(t('view'), $_GET['q']));
$path = drupal_get_normal_path(variable_get('site_403', ''));
$status = MENU_NOT_FOUND;
if ($path && $path != $_GET['q']) {
menu_set_active_item($path);
$status = menu_execute_active_handler();
}
if ($status != MENU_FOUND) {
drupal_set_title(t('Access denied'));
print theme('page', message_access());
}
}
function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
$result = new StdClass();
$uri = parse_url($url);
switch ($uri['scheme']) {
case 'http':
$fp = @fsockopen($uri['host'], ($uri['port'] ? $uri['port'] : 80), $errno, $errstr, 15);
break;
case 'https':
$fp = @fsockopen('ssl://'. $uri['host'], ($uri['port'] ? $uri['port'] : 443), $errno, $errstr, 20);
break;
default:
$result->error = 'invalid schema '. $uri['scheme'];
return $result;
}
if (!$fp) {
$result->error = trim($errno .' '. $errstr);
return $result;
}
$path = $uri['path'] ? $uri['path'] : '/';
if ($uri['query']) {
$path .= '?'. $uri['query'];
}
$defaults = array(
'Host' => 'Host: '. $uri['host'],
'User-Agent' => 'User-Agent: Drupal (+http://www.drupal.org/)',
'Content-Length' => 'Content-Length: '. strlen($data)
);
foreach ($headers as $header => $value) {
$defaults[$header] = $header .': '. $value;
}
$request = $method .' '. $path ." HTTP/1.0\r\n";
$request .= implode("\r\n", $defaults);
$request .= "\r\n\r\n";
if ($data) {
$request .= $data ."\r\n";
}
$result->request = $request;
fwrite($fp, $request);
$response = '';
while (!feof($fp) && $data = fread($fp, 1024)) {
$response .= $data;
}
fclose($fp);
list($headers, $result->data) = explode("\r\n\r\n", $response, 2);
$headers = preg_split("/\r\n|\n|\r/", $headers);
list($protocol, $code, $text) = explode(' ', trim(array_shift($headers)), 3);
$result->headers = array();
while ($line = trim(array_shift($headers))) {
list($header, $value) = explode(':', $line, 2);
$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'
);
if (!isset($responses[$code])) {
$code = floor($code / 100) * 100;
}
switch ($code) {
case 200: case 304: break;
case 301: case 302: case 307: $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;
}
function error_handler($errno, $message, $filename, $line) {
if ($errno & (E_ALL ^ E_NOTICE)) {
$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');
$entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';
if (variable_get('error_level', 1) == 1) {
print '<pre>'. $entry .'</pre>';
}
watchdog('php', t('%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line)), WATCHDOG_ERROR);
}
}
function _fix_gpc_magic(&$item) {
if (is_array($item)) {
array_walk($item, '_fix_gpc_magic');
}
else {
$item = stripslashes($item);
}
}
function fix_gpc_magic() {
static $fixed = false;
if (!$fixed && ini_get('magic_quotes_gpc')) {
array_walk($_GET, '_fix_gpc_magic');
array_walk($_POST, '_fix_gpc_magic');
array_walk($_COOKIE, '_fix_gpc_magic');
array_walk($_REQUEST, '_fix_gpc_magic');
$fixed = true;
}
}
function array2object($array) {
if (is_array($array)) {
$object = new StdClass();
foreach ($array as $key => $value) {
$object->$key = $value;
}
}
else {
$object = $array;
}
return $object;
}
function object2array($object) {
if (is_object($object)) {
foreach ($object as $key => $value) {
$array[$key] = $value;
}
}
else {
$array = $object;
}
return $array;
}
function message_access() {
return t('You are not authorized to access this page.');
}
function message_na() {
return t('n/a');
}
function locale_initialize() {
global $user;
if (function_exists('i18n_get_lang')) {
return i18n_get_lang();
}
if (function_exists('locale')) {
$languages = locale_supported_languages();
$languages = $languages['name'];
}
else {
$languages = array('en' => 'English');
}
if ($user->uid && $languages[$user->language]) {
return $user->language;
}
else {
return key($languages);
}
}
function t($string, $args = 0) {
global $locale;
if (function_exists('locale') && $locale != 'en') {
$string = locale($string);
}
if (!$args) {
return $string;
}
else {
return strtr($string, $args);
}
}
function valid_email_address($mail) {
$user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
$domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
$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);
}
function valid_url($url, $absolute = FALSE) {
$allowed_characters = '[a-z0-9\/:_\-_\.\?\$,~=#&%\+]';
if ($absolute) {
return preg_match("/^(http|https|ftp):\/\/". $allowed_characters ."+$/i", $url);
}
else {
return preg_match("/^". $allowed_characters ."+$/i", $url);
}
}
function flood_register_event($name) {
db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, $_SERVER['REMOTE_ADDR'], time());
}
function flood_is_allowed($name, $threshold) {
$number = db_num_rows(db_query("SELECT event FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, $_SERVER['REMOTE_ADDR'], time() - 3600));
return ($number < $threshold ? TRUE : FALSE);
}
function check_file($filename) {
return is_uploaded_file($filename);
}
function check_url($uri) {
return filter_xss_bad_protocol($uri, FALSE);
}
function format_rss_channel($title, $link, $description, $items, $language = 'en', $args = array()) {
$output = "<channel>\n";
$output .= ' <title>'. check_plain($title) ."</title>\n";
$output .= ' <link>'. check_url($link) ."</link>\n";
$output .= ' <description>'. check_plain($description) ."</description>\n";
$output .= ' <language>'. check_plain($language) ."</language>\n";
foreach ($args as $key => $value) {
$output .= ' <'. $key .'>'. check_plain($value) ."</$key>\n";
}
$output .= $items;
$output .= "</channel>\n";
return $output;
}
function format_rss_item($title, $link, $description, $args = array()) {
$output = "<item>\n";
$output .= ' <title>'. check_plain($title) ."</title>\n";
$output .= ' <link>'. check_url($link) ."</link>\n";
$output .= ' <description>'. check_plain($description) ."</description>\n";
foreach ($args as $key => $value) {
if (is_array($value)) {
if ($value['key']) {
$output .= ' <'. $value['key'];
if (is_array($value['attributes'])) {
$output .= drupal_attributes($value['attributes']);
}
if ($value['value']) {
$output .= '>'. $value['value'] .'</'. $value['key'] .">\n";
}
else {
$output .= " />\n";
}
}
}
else {
$output .= ' <'. $key .'>'. check_plain($value) ."</$key>\n";
}
}
$output .= "</item>\n";
return $output;
}
function format_plural($count, $singular, $plural) {
if ($count == 1) return t($singular, array("%count" => $count));
$index = (function_exists('locale')) ? locale_get_plural($count) : -1;
if ($index < 0) { return t($plural, array("%count" => $count));
}
else {
switch ($index) {
case "0":
return t($singular, array("%count" => $count));
case "1":
return t($plural, array("%count" => $count));
default:
return t(strtr($plural, array("%count" => '%count['. $index .']')), array('%count['. $index .']' => $count));
}
}
}
function format_size($size) {
$suffix = t('bytes');
if ($size > 1024) {
$size = round($size / 1024, 2);
$suffix = t('KB');
}
if ($size > 1024) {
$size = round($size / 1024, 2);
$suffix = t('MB');
}
return t('%size %suffix', array('%size' => $size, '%suffix' => $suffix));
}
function format_interval($timestamp, $granularity = 2) {
$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);
$output = '';
foreach ($units as $key => $value) {
$key = explode('|', $key);
if ($timestamp >= $value) {
$output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1]);
$timestamp %= $value;
$granularity--;
}
if ($granularity == 0) {
break;
}
}
return $output ? $output : t('0 sec');
}
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL) {
if ($timezone === NULL) {
global $user;
if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
$timezone = $user->timezone;
}
else {
$timezone = variable_get('date_default_timezone', 0);
}
}
$timestamp += $timezone;
switch ($type) {
case 'small':
$format = variable_get('date_format_short', 'm/d/Y - H:i');
break;
case 'large':
$format = variable_get('date_format_long', 'l, F j, Y - H:i');
break;
case 'custom':
break;
case 'medium':
default:
$format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
}
$max = strlen($format);
$date = '';
for ($i = 0; $i < $max; $i++) {
$c = $format{$i};
if (strpos('AaDFlM', $c) !== false) {
$date .= t(gmdate($c, $timestamp));
}
else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== false) {
$date .= gmdate($c, $timestamp);
}
else if ($c == 'r') {
$date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone);
}
else if ($c == 'O') {
$date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
}
else if ($c == 'Z') {
$date .= $timezone;
}
else if ($c == '\\') {
$date .= $format[++$i];
}
else {
$date .= $c;
}
}
return $date;
}
function format_name($object) {
if ($object->uid && $object->name) {
if (strlen($object->name) > 20) {
$name = truncate_utf8($object->name, 15) .'...';
}
else {
$name = $object->name;
}
if (user_access('access user profiles')) {
$output = l($name, 'user/'. $object->uid, array('title' => t('View user profile.')));
}
else {
$output = check_plain($name);
}
}
else if ($object->name) {
if ($object->homepage) {
$output = '<a href="'. check_url($object->homepage) .'">'. check_plain($object->name) .'</a>';
}
else {
$output = check_plain($object->name);
}
$output .= ' ('. t('not verified') .')';
}
else {
$output = variable_get('anonymous', 'Anonymous');
}
return $output;
}
function drupal_check_token() {
global $user;
if ($user->uid && ($_SERVER['REQUEST_METHOD'] == 'POST') && !(isset($_POST['edit']) && isset($_POST['edit']['token']) && drupal_valid_token($_POST['edit']['token']))) {
drupal_set_message(t('Validation error. Please try again.'), 'error');
$_POST = array();
}
}
function drupal_get_private_key() {
if (!($key = variable_get('drupal_private_key', 0))) {
$key = mt_rand();
variable_set('drupal_private_key', $key);
}
return $key;
}
function drupal_get_token($value = '') {
$private_key = drupal_get_private_key();
return md5(session_id() . $value . $private_key);
}
function drupal_valid_token($token, $value = '') {
return ($token == md5(session_id() . $value . variable_get('drupal_private_key', '')));
}
function form_token() {
return form_hidden('token', drupal_get_token());
}
function form($form, $method = 'post', $action = NULL, $attributes = NULL) {
if (!$action) {
$action = request_uri();
}
return '<form action="'. check_url($action) .'" method="'. $method .'"'. drupal_attributes($attributes) .">\n". $form . form_token() ."\n</form>\n";
}
function form_set_error($name, $message) {
$GLOBALS['form'][$name] = $message;
drupal_set_message($message, 'error');
}
function form_get_errors() {
if (array_key_exists('form', $GLOBALS)) {
return $GLOBALS['form'];
}
}
function _form_get_error($name) {
if (array_key_exists('form', $GLOBALS)) {
return $GLOBALS['form'][$name];
}
}
function _form_get_class($name, $required, $error) {
return $name. ($required ? ' required' : '') . ($error ? ' error' : '');
}
function form_item($title, $value, $description = NULL, $id = NULL, $required = FALSE, $error = FALSE) {
return theme('form_element', $title, $value, $description, $id, $required, $error);
}
function form_group($legend, $group, $description = NULL) {
return '<fieldset>' . ($legend ? '<legend>'. check_plain($legend) .'</legend>' : '') . $group . ($description ? '<div class="description">'. $description .'</div>' : '') . "</fieldset>\n";
}
function form_radio($title, $name, $value = 1, $checked = FALSE, $description = NULL, $attributes = NULL, $required = FALSE) {
$element = '<input type="radio" class="'. _form_get_class('form-radio', $required, _form_get_error($name)) .'" name="edit['. $name .']" value="'. check_plain($value) .'"'. ($checked ? ' checked="checked"' : '') . drupal_attributes($attributes) .' />';
if (!is_null($title)) {
$element = '<label class="option">'. $element .' '. $title .'</label>';
}
return theme('form_element', NULL, $element, $description, $name, $required, _form_get_error($name));
}
function form_radios($title, $name, $value, $options, $description = NULL, $required = FALSE, $attributes = NULL) {
if (count($options) > 0) {
$choices = '';
foreach ($options as $key => $choice) {
$choices .= '<label class="option"><input type="radio" class="form-radio" name="edit['. $name .']" value="'. check_plain($key) .'"'. ($key == $value ? ' checked="checked"' : ''). drupal_attributes($attributes) .' /> '. $choice .'</label><br />';
}
return theme('form_element', $title,