2
// $Id: common.inc,v 1.611 2007/01/10 23:30:07 unconed Exp $
6
* Common functions that many Drupal modules will need to reference.
8
* The functions that are critical and need to be available even when serving
9
* a cached page are instead located in bootstrap.inc.
13
* Return status for saving which involved creating a new item.
15
define('SAVED_NEW', 1);
18
* Return status for saving which involved an update to an existing item.
20
define('SAVED_UPDATED', 2);
23
* Return status for saving which deleted an existing item.
25
define('SAVED_DELETED', 3);
28
* Set content for a specified region.
31
* Page region the content is assigned to.
36
function drupal_set_content($region = NULL, $data = NULL) {
37
static $content = array();
39
if (!is_null($region) && !is_null($data)) {
40
$content[$region][] = $data;
46
* Get assigned content.
49
* A specified region to fetch content for. If NULL, all regions will be returned.
52
* Content to be inserted between exploded array elements.
54
function drupal_get_content($region = NULL, $delimiter = ' ') {
55
$content = drupal_set_content();
57
if (isset($content[$region]) && is_array($content[$region])) {
58
return implode($delimiter, $content[$region]);
62
foreach (array_keys($content) as $region) {
63
if (is_array($content[$region])) {
64
$content[$region] = implode($delimiter, $content[$region]);
72
* Set the breadcrumb trail for the current page.
75
* Array of links, starting with "home" and proceeding up to but not including
78
function drupal_set_breadcrumb($breadcrumb = NULL) {
79
static $stored_breadcrumb;
81
if (!is_null($breadcrumb)) {
82
$stored_breadcrumb = $breadcrumb;
84
return $stored_breadcrumb;
88
* Get the breadcrumb trail for the current page.
90
function drupal_get_breadcrumb() {
91
$breadcrumb = drupal_set_breadcrumb();
93
if (is_null($breadcrumb)) {
94
$breadcrumb = menu_get_active_breadcrumb();
101
* Add output to the head tag of the HTML page.
102
* This function can be called as long the headers aren't sent.
104
function drupal_set_html_head($data = NULL) {
105
static $stored_head = '';
107
if (!is_null($data)) {
108
$stored_head .= $data ."\n";
114
* Retrieve output to be displayed in the head tag of the HTML page.
116
function drupal_get_html_head() {
117
$output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
118
return $output . drupal_set_html_head();
122
* Reset the static variable which holds the aliases mapped for this request.
124
function drupal_clear_path_cache() {
125
drupal_lookup_path('wipe');
129
* Set an HTTP response header for the current page.
131
* Note: when sending a Content-Type header, always include a 'charset' type
132
* too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
134
function drupal_set_header($header = NULL) {
135
// We use an array to guarantee there are no leading or trailing delimiters.
136
// Otherwise, header('') could get called when serving the page later, which
137
// ends HTTP headers prematurely on some PHP versions.
138
static $stored_headers = array();
140
if (strlen($header)) {
142
$stored_headers[] = $header;
144
return implode("\n", $stored_headers);
148
* Get the HTTP response headers for the current page.
150
function drupal_get_headers() {
151
return drupal_set_header();
155
* Add a feed URL for the current page.
158
* The url for the feed
160
* The title of the feed
162
function drupal_add_feed($url = NULL, $title = '') {
163
static $stored_feed_links = array();
165
if (!is_null($url)) {
166
$stored_feed_links[$url] = theme('feed_icon', $url);
168
drupal_add_link(array('rel' => 'alternate',
169
'type' => 'application/rss+xml',
173
return $stored_feed_links;
177
* Get the feed URLs for the current page.
180
* The delimiter to split feeds by
182
function drupal_get_feeds($delimiter = "\n") {
183
$feeds = drupal_add_feed();
184
return implode($feeds, $delimiter);
188
* @name HTTP handling
190
* Functions to properly handle HTTP responses.
194
* Parse an array into a valid urlencoded query string.
197
* The array to be processed e.g. $_GET
199
* The array filled with keys to be excluded. Use parent[child] to exclude nested items.
201
* If TRUE, the keys and values are both urlencoded.
203
* Should not be passed, only used in recursive calls
205
* urlencoded string which can be appended to/as the URL query string
207
function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
210
foreach ($query as $key => $value) {
211
$key = drupal_urlencode($key);
213
$key = $parent .'['. $key .']';
216
if (in_array($key, $exclude)) {
220
if (is_array($value)) {
221
$params[] = drupal_query_string_encode($value, $exclude, $key);
224
$params[] = $key .'='. drupal_urlencode($value);
228
return implode('&', $params);
232
* Prepare a destination query string for use in combination with
233
* drupal_goto(). Used to direct the user back to the referring page
234
* after completing a form. By default the current URL is returned.
235
* If a destination exists in the previous request, that destination
236
* is returned. As such, a destination can persist across multiple
241
function drupal_get_destination() {
242
if (isset($_REQUEST['destination'])) {
243
return 'destination='. urlencode($_REQUEST['destination']);
246
// Use $_GET here to retrieve the original path in source form.
247
$path = isset($_GET['q']) ? $_GET['q'] : '';
248
$query = drupal_query_string_encode($_GET, array('q'));
250
$path .= '?'. $query;
252
return 'destination='. urlencode($path);
257
* Send the user to a different Drupal page.
259
* This issues an on-site HTTP redirect. The function makes sure the redirected
260
* URL is formatted correctly.
262
* Usually the redirected URL is constructed from this function's input
263
* parameters. However you may override that behavior by setting a
264
* <em>destination</em> in either the $_REQUEST-array (i.e. by using
265
* the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
266
* using a hidden form field). This is used to direct the user back to
267
* the proper page after completing a form. For example, after editing
268
* a post on the 'admin/content/node'-page or after having logged on using the
269
* 'user login'-block in a sidebar. The function drupal_get_destination()
270
* can be used to help set the destination URL.
272
* It is advised to use drupal_goto() instead of PHP's header(), because
273
* drupal_goto() will append the user's session ID to the URI when PHP is
274
* compiled with "--enable-trans-sid".
276
* This function ends the request; use it rather than a print theme('page')
277
* statement in your menu callback.
280
* A Drupal path or a full URL.
282
* The query string component, if any.
284
* The destination fragment identifier (named anchor).
285
* @param $http_response_code
286
* Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
287
* - 301 Moved Permanently (the recommended value for most redirects)
288
* - 302 Found (default in Drupal and PHP, sometimes used for spamming search
293
* - 307 Temporary Redirect (an alternative to "503 Site Down for Maintenance")
294
* Note: Other values are defined by RFC 2616, but are rarely used and poorly
296
* @see drupal_get_destination()
298
function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
299
if (isset($_REQUEST['destination'])) {
300
extract(parse_url(urldecode($_REQUEST['destination'])));
302
else if (isset($_REQUEST['edit']['destination'])) {
303
extract(parse_url(urldecode($_REQUEST['edit']['destination'])));
306
$url = url($path, $query, $fragment, TRUE);
308
// Before the redirect, allow modules to react to the end of the page request.
309
module_invoke_all('exit', $url);
311
header('Location: '. $url, TRUE, $http_response_code);
313
// The "Location" header sends a REDIRECT status code to the http
314
// daemon. In some cases this can go wrong, so we make sure none
315
// of the code below the drupal_goto() call gets executed when we redirect.
320
* Generates a site off-line message
322
function drupal_site_offline() {
323
drupal_set_header('HTTP/1.1 503 Service unavailable');
324
drupal_set_title(t('Site off-line'));
325
print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
326
t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
330
* Generates a 404 error if the request can not be handled.
332
function drupal_not_found() {
333
drupal_set_header('HTTP/1.1 404 Not Found');
335
watchdog('page not found', check_plain($_GET['q']), WATCHDOG_WARNING);
337
// Keep old path for reference
338
if (!isset($_REQUEST['destination'])) {
339
$_REQUEST['destination'] = $_GET['q'];
342
$path = drupal_get_normal_path(variable_get('site_404', ''));
343
if ($path && $path != $_GET['q']) {
344
menu_set_active_item($path);
345
$return = menu_execute_active_handler();
348
// Redirect to a non-existent menu item to make possible tabs disappear.
349
menu_set_active_item('');
352
if (empty($return)) {
353
drupal_set_title(t('Page not found'));
355
// To conserve CPU and bandwidth, omit the blocks
356
print theme('page', $return, FALSE);
360
* Generates a 403 error if the request is not allowed.
362
function drupal_access_denied() {
363
drupal_set_header('HTTP/1.1 403 Forbidden');
364
watchdog('access denied', check_plain($_GET['q']), WATCHDOG_WARNING);
366
// Keep old path for reference
367
if (!isset($_REQUEST['destination'])) {
368
$_REQUEST['destination'] = $_GET['q'];
371
$path = drupal_get_normal_path(variable_get('site_403', ''));
372
if ($path && $path != $_GET['q']) {
373
menu_set_active_item($path);
374
$return = menu_execute_active_handler();
377
// Redirect to a non-existent menu item to make possible tabs disappear.
378
menu_set_active_item('');
381
if (empty($return)) {
382
drupal_set_title(t('Access denied'));
383
$return = t('You are not authorized to access this page.');
385
print theme('page', $return);
389
* Perform an HTTP request.
391
* This is a flexible and powerful HTTP client implementation. Correctly handles
392
* GET, POST, PUT or any other HTTP requests. Handles redirects.
395
* A string containing a fully qualified URI.
397
* An array containing an HTTP header => value pair.
399
* A string defining the HTTP request to use.
401
* A string containing data to include in the request.
403
* An integer representing how many times to retry the request in case of a
406
* An object containing the HTTP request headers, response code, headers,
407
* data, and redirect status.
409
function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
410
$result = new stdClass();
412
// Parse the URL, and make sure we can handle the schema.
413
$uri = parse_url($url);
414
switch ($uri['scheme']) {
416
$port = isset($uri['port']) ? $uri['port'] : 80;
417
$host = $uri['host'] . ($port != 80 ? ':'. $port : '');
418
$fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
421
// Note: Only works for PHP 4.3 compiled with OpenSSL.
422
$port = isset($uri['port']) ? $uri['port'] : 443;
423
$host = $uri['host'] . ($port != 443 ? ':'. $port : '');
424
$fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
427
$result->error = 'invalid schema '. $uri['scheme'];
431
// Make sure the socket opened properly.
433
$result->error = trim($errno .' '. $errstr);
437
// Construct the path to act on.
438
$path = isset($uri['path']) ? $uri['path'] : '/';
439
if (isset($uri['query'])) {
440
$path .= '?'. $uri['query'];
443
// Create HTTP request.
445
// RFC 2616: "non-standard ports MUST, default ports MAY be included".
446
// We don't add the port to prevent from breaking rewrite rules checking
447
// the host that do not take into account the port number.
448
'Host' => "Host: $host",
449
'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
450
'Content-Length' => 'Content-Length: '. strlen($data)
453
foreach ($headers as $header => $value) {
454
$defaults[$header] = $header .': '. $value;
457
$request = $method .' '. $path ." HTTP/1.0\r\n";
458
$request .= implode("\r\n", $defaults);
459
$request .= "\r\n\r\n";
461
$request .= $data ."\r\n";
463
$result->request = $request;
465
fwrite($fp, $request);
469
while (!feof($fp) && $chunk = fread($fp, 1024)) {
475
list($split, $result->data) = explode("\r\n\r\n", $response, 2);
476
$split = preg_split("/\r\n|\n|\r/", $split);
478
list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
479
$result->headers = array();
482
while ($line = trim(array_shift($split))) {
483
list($header, $value) = explode(':', $line, 2);
484
if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
485
// RFC 2109: the Set-Cookie response header comprises the token Set-
486
// Cookie:, followed by a comma-separated list of one or more cookies.
487
$result->headers[$header] .= ','. trim($value);
490
$result->headers[$header] = trim($value);
495
100 => 'Continue', 101 => 'Switching Protocols',
496
200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
497
300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
498
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',
499
500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
501
// RFC 2616 states that all unknown HTTP codes must be treated the same as
502
// the base code in their class.
503
if (!isset($responses[$code])) {
504
$code = floor($code / 100) * 100;
509
case 304: // Not modified
511
case 301: // Moved permanently
512
case 302: // Moved temporarily
513
case 307: // Moved temporarily
514
$location = $result->headers['Location'];
517
$result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
518
$result->redirect_code = $result->code;
520
$result->redirect_url = $location;
524
$result->error = $text;
527
$result->code = $code;
531
* @} End of "HTTP handling".
535
* Log errors as defined by administrator
537
* 0 = Log errors to database.
538
* 1 = Log errors to database and to screen.
540
function error_handler($errno, $message, $filename, $line) {
541
// If the @ error suppression operator was used, error_reporting is temporarily set to 0
542
if (error_reporting() == 0) {
546
if ($errno & (E_ALL ^ E_NOTICE)) {
547
$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');
548
$entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';
550
// Force display of error messages in update.php
551
if (variable_get('error_level', 1) == 1 || strstr($_SERVER['PHP_SELF'], 'update.php')) {
552
drupal_set_message($entry, 'error');
555
watchdog('php', t('%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line)), WATCHDOG_ERROR);
559
function _fix_gpc_magic(&$item) {
560
if (is_array($item)) {
561
array_walk($item, '_fix_gpc_magic');
564
$item = stripslashes($item);
569
* Helper function to strip slashes from $_FILES skipping over the tmp_name keys
570
* since PHP generates single backslashes for file paths on Windows systems.
572
* tmp_name does not have backslashes added see
573
* http://php.net/manual/en/features.file-upload.php#42280
575
function _fix_gpc_magic_files(&$item, $key) {
576
if ($key != 'tmp_name') {
577
if (is_array($item)) {
578
array_walk($item, '_fix_gpc_magic_files');
581
$item = stripslashes($item);
587
* Correct double-escaping problems caused by "magic quotes" in some PHP
590
function fix_gpc_magic() {
591
static $fixed = FALSE;
592
if (!$fixed && ini_get('magic_quotes_gpc')) {
593
array_walk($_GET, '_fix_gpc_magic');
594
array_walk($_POST, '_fix_gpc_magic');
595
array_walk($_COOKIE, '_fix_gpc_magic');
596
array_walk($_REQUEST, '_fix_gpc_magic');
597
array_walk($_FILES, '_fix_gpc_magic_files');
603
* Initialize the localization system.
605
function locale_initialize() {
608
if (function_exists('i18n_get_lang')) {
609
return i18n_get_lang();
612
if (function_exists('locale')) {
613
$languages = locale_supported_languages();
614
$languages = $languages['name'];
617
// Ensure the locale/language is correctly returned, even without locale.module.
618
// Useful for e.g. XML/HTML 'lang' attributes.
619
$languages = array('en' => 'English');
621
if ($user->uid && isset($languages[$user->language])) {
622
return $user->language;
625
return key($languages);
630
* Translate strings to the current locale.
632
* All human-readable text that will be displayed somewhere within a page should be
633
* run through the t() function.
637
* if (!$info || !$info['extension']) {
638
* form_set_error('picture_upload', t('The uploaded file was not an image.'));
641
* $form['submit'] = array(
642
* '#type' => 'submit',
643
* '#value' => t('Log in'),
647
* Any text within t() can be extracted by translators and changed into
648
* the equivalent text in their native language.
650
* Special variables called "placeholders" are used to signal dynamic
651
* information in a string which should not be translated. Placeholders
652
* can also be used for text that may change from time to time
653
* (such as link paths) to be changed without requiring updates to translations.
657
* $output = t('There are currently %members and %visitors online.', array(
658
* '%members' => format_plural($total_users, '1 user', '@count users'),
659
* '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
662
* There are three styles of placeholders:
663
* - !variable, which indicates that the text should be inserted as-is. This is
664
* useful for inserting variables into things like e-mail.
666
* $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", NULL, NULL, TRUE)));
669
* - @variable, which indicates that the text should be run through check_plain,
670
* to strip out HTML characters. Use this for any output that's displayed within
673
* drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
676
* - %variable, which indicates that the string should be highlighted with
677
* theme_placeholder() which shows up by default as <em>emphasized</em>.
679
* watchdog('mail', t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name)));
682
* When using t(), try to put entire sentences and strings in one t() call.
683
* This makes it easier for translators, as it provides context as to what
684
* each word refers to. HTML markup within translation strings is allowed,
685
* but should be avoided if possible. The exception is embedded links; link
686
* titles add additional context for translators so should be kept in the main
689
* Here is an example of an incorrect use if t():
691
* $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
694
* Here is an example of t() used correctly:
696
* $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
699
* Also avoid escaping quotation marks wherever possible.
703
* $output .= t('Don\'t click me.');
708
* $output .= t("Don't click me.");
712
* A string containing the English string to translate.
714
* An associative array of replacements to make after translation. Incidences
715
* of any key in this array are replaced with the corresponding value.
716
* Based on the first character of the key, the value is escaped and/or themed:
717
* - !variable: inserted as is
718
* - @variable: escape plain text to HTML (check_plain)
719
* - %variable: escape text and theme as a placeholder for user-submitted
720
* content (check_plain + theme_placeholder)
722
* The translated string.
724
function t($string, $args = 0) {
726
if (function_exists('locale') && $locale != 'en') {
727
$string = locale($string);
733
// Transform arguments before inserting them
734
foreach ($args as $key => $value) {
738
$args[$key] = check_plain($value);
740
// Escaped and placeholder
743
$args[$key] = theme('placeholder', $value);
749
return strtr($string, $args);
754
* @defgroup validation Input validation
756
* Functions to validate user input.
760
* Verify the syntax of the given e-mail address.
762
* Empty e-mail addresses are allowed. See RFC 2822 for details.
765
* A string containing an e-mail address.
767
* TRUE if the address is in a valid format.
769
function valid_email_address($mail) {
770
$user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
771
$domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
772
$ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
773
$ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
775
return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
779
* Verify the syntax of the given URL.
781
* This function should only be used on actual URLs. It should not be used for
782
* Drupal menu paths, which can contain arbitrary characters.
787
* Whether the URL is absolute (beginning with a scheme such as "http:").
789
* TRUE if the URL is in a valid format.
791
function valid_url($url, $absolute = FALSE) {
792
$allowed_characters = '[a-z0-9\/:_\-_\.\?\$,;~=#&%\+]';
794
return preg_match("/^(http|https|ftp):\/\/". $allowed_characters ."+$/i", $url);
797
return preg_match("/^". $allowed_characters ."+$/i", $url);
802
* Register an event for the current visitor (hostname/IP) to the flood control mechanism.
805
* The name of the event.
807
function flood_register_event($name) {
808
db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, $_SERVER['REMOTE_ADDR'], time());
812
* Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
813
* The user is allowed to proceed if he did not trigger the specified event more than
814
* $threshold times per hour.
817
* The name of the event.
819
* The maximum number of the specified event per hour (per visitor).
821
* True if the user did not exceed the hourly threshold. False otherwise.
823
function flood_is_allowed($name, $threshold) {
824
$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));
825
return ($number < $threshold ? TRUE : FALSE);
828
function check_file($filename) {
829
return is_uploaded_file($filename);
833
* Prepare a URL for use in an HTML attribute. Strips harmful protocols.
836
function check_url($uri) {
837
return filter_xss_bad_protocol($uri, FALSE);
841
* @defgroup format Formatting
843
* Functions to format numbers, strings, dates, etc.
847
* Formats an RSS channel.
849
* Arbitrary elements may be added using the $args associative array.
851
function format_rss_channel($title, $link, $description, $items, $language = 'en', $args = array()) {
852
// arbitrary elements may be added using the $args associative array
854
$output = "<channel>\n";
855
$output .= ' <title>'. check_plain($title) ."</title>\n";
856
$output .= ' <link>'. check_url($link) ."</link>\n";
858
// The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
859
// We strip all HTML tags, but need to prevent double encoding from properly
860
// escaped source data (such as & becoming &amp;).
861
$output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
862
$output .= ' <language>'. check_plain($language) ."</language>\n";
863
$output .= format_xml_elements($args);
865
$output .= "</channel>\n";
871
* Format a single RSS item.
873
* Arbitrary elements may be added using the $args associative array.
875
function format_rss_item($title, $link, $description, $args = array()) {
876
$output = "<item>\n";
877
$output .= ' <title>'. check_plain($title) ."</title>\n";
878
$output .= ' <link>'. check_url($link) ."</link>\n";
879
$output .= ' <description>'. check_plain($description) ."</description>\n";
880
$output .= format_xml_elements($args);
881
$output .= "</item>\n";
887
* Format XML elements.
890
* An array where each item represent an element and is either a:
891
* - (key => value) pair (<key>value</key>)
892
* - Associative array with fields:
893
* - 'key': element name
894
* - 'value': element contents
895
* - 'attributes': associative array of element attributes
897
* In both cases, 'value' can be a simple string, or it can be another array
898
* with the same format as $array itself for nesting.
900
function format_xml_elements($array) {
901
foreach ($array as $key => $value) {
902
if (is_numeric($key)) {
904
$output .= ' <'. $value['key'];
905
if (isset($value['attributes']) && is_array($value['attributes'])) {
906
$output .= drupal_attributes($value['attributes']);
909
if ($value['value'] != '') {
910
$output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
918
$output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
925
* Format a string containing a count of items.
927
* This function ensures that the string is pluralized correctly. Since t() is
928
* called by this function, make sure not to pass already-localized strings to it.
931
* The item count to display.
933
* The string for the singular case. Please make sure it is clear this is
934
* singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
936
* The string for the plural case. Please make sure it is clear this is plural,
937
* to ease translation. Use @count in place of the item count, as in "@count
940
* A translated string.
942
function format_plural($count, $singular, $plural) {
943
if ($count == 1) return t($singular, array("@count" => $count));
945
// get the plural index through the gettext formula
946
$index = (function_exists('locale_get_plural')) ? locale_get_plural($count) : -1;
947
if ($index < 0) { // backward compatibility
948
return t($plural, array("@count" => $count));
953
return t($singular, array("@count" => $count));
955
return t($plural, array("@count" => $count));
957
return t(strtr($plural, array("@count" => '@count['. $index .']')), array('@count['. $index .']' => $count));
963
* Parse a given byte count.
966
* The size expressed as a number of bytes with optional SI size and unit
967
* suffix (e.g. 2, 3K, 5MB, 10G).
969
* An integer representation of the size.
971
function parse_size($size) {
975
'm' => 1048576, // 1024 * 1024
976
'g' => 1073741824, // 1024 * 1024 * 1024
978
if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
979
return $match[1] * $suffixes[drupal_strtolower($match[2])];
984
* Generate a string representation for the given byte count.
989
* A translated string representation of the size.
991
function format_size($size) {
993
return format_plural($size, '1 byte', '@count bytes');
996
$size = round($size / 1024, 2);
999
$size = round($size / 1024, 2);
1002
return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix));
1007
* Format a time interval with the requested granularity.
1010
* The length of the interval in seconds.
1011
* @param $granularity
1012
* How many different units to display in the string.
1014
* A translated string representation of the interval.
1016
function format_interval($timestamp, $granularity = 2) {
1017
$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);
1019
foreach ($units as $key => $value) {
1020
$key = explode('|', $key);
1021
if ($timestamp >= $value) {
1022
$output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1]);
1023
$timestamp %= $value;
1027
if ($granularity == 0) {
1031
return $output ? $output : t('0 sec');
1035
* Format a date with the given configured format or a custom format string.
1037
* Drupal allows administrators to select formatting strings for 'small',
1038
* 'medium' and 'large' date formats. This function can handle these formats,
1039
* as well as any custom format.
1042
* The exact date to format, as a UNIX timestamp.
1044
* The format to use. Can be "small", "medium" or "large" for the preconfigured
1045
* date formats. If "custom" is specified, then $format is required as well.
1047
* A PHP date format string as required by date(). A backslash should be used
1048
* before a character to avoid interpreting the character as part of a date
1051
* Time zone offset in seconds; if omitted, the user's time zone is used.
1053
* A translated date string in the requested format.
1055
function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL) {
1056
if (!isset($timezone)) {
1058
if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
1059
$timezone = $user->timezone;
1062
$timezone = variable_get('date_default_timezone', 0);
1066
$timestamp += $timezone;
1070
$format = variable_get('date_format_short', 'm/d/Y - H:i');
1073
$format = variable_get('date_format_long', 'l, F j, Y - H:i');
1076
// No change to format
1080
$format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
1083
$max = strlen($format);
1085
for ($i = 0; $i < $max; $i++) {
1087
if (strpos('AaDFlM', $c) !== FALSE) {
1088
$date .= t(gmdate($c, $timestamp));
1090
else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
1091
$date .= gmdate($c, $timestamp);
1093
else if ($c == 'r') {
1094
$date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone);
1096
else if ($c == 'O') {
1097
$date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
1099
else if ($c == 'Z') {
1102
else if ($c == '\\') {
1103
$date .= $format[++$i];
1114
* @} End of "defgroup format".
1118
* Generate a URL from a Drupal menu path. Will also pass-through existing URLs.
1121
* The Drupal path being linked to, such as "admin/content/node", or an existing URL
1122
* like "http://drupal.org/".
1124
* A query string to append to the link or URL.
1126
* A fragment identifier (named anchor) to append to the link. If an existing
1127
* URL with a fragment identifier is used, it will be replaced. Note, do not
1130
* Whether to force the output to be an absolute link (beginning with http:).
1131
* Useful for links that will be displayed outside the site, such as in an
1134
* a string containing a URL to the given path.
1136
* When creating links in modules, consider whether l() could be a better
1137
* alternative than url().
1139
function url($path = NULL, $query = NULL, $fragment = NULL, $absolute = FALSE) {
1140
if (isset($fragment)) {
1141
$fragment = '#'. $fragment;
1144
// Return an external link if $path contains an allowed absolute URL.
1145
// Only call the slow filter_xss_bad_protocol if $path contains a ':' before any / ? or #.
1146
$colonpos = strpos($path, ':');
1147
if ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path)) {
1148
// Split off the fragment
1149
if (strpos($path, '#') !== FALSE) {
1150
list($path, $old_fragment) = explode('#', $path, 2);
1151
if (isset($old_fragment) && !isset($fragment)) {
1152
$fragment = '#'. $old_fragment;
1156
if (isset($query)) {
1157
$path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $query;
1160
return $path . $fragment;
1167
if (empty($script)) {
1168
// On some web servers, such as IIS, we can't omit "index.php". So, we
1169
// generate "index.php?q=foo" instead of "?q=foo" on anything that is not
1171
$script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php' : '';
1174
// Cache the clean_url variable to improve performance.
1175
if (!isset($clean_url)) {
1176
$clean_url = (bool)variable_get('clean_url', '0');
1179
$base = ($absolute ? $base_url . '/' : base_path());
1181
// The special path '<front>' links to the default front page.
1182
if (!empty($path) && $path != '<front>') {
1183
$path = drupal_get_path_alias($path);
1184
$path = drupal_urlencode($path);
1186
if (isset($query)) {
1187
return $base . $script .'?q='. $path .'&'. $query . $fragment;
1190
return $base . $script .'?q='. $path . $fragment;
1194
if (isset($query)) {
1195
return $base . $path .'?'. $query . $fragment;
1198
return $base . $path . $fragment;
1203
if (isset($query)) {
1204
return $base . $script .'?'. $query . $fragment;
1207
return $base . $fragment;
1213
* Format an attribute string to insert in a tag.
1215
* @param $attributes
1216
* An associative array of HTML attributes.
1218
* An HTML string ready for insertion in a tag.
1220
function drupal_attributes($attributes = array()) {
1221
if (is_array($attributes)) {
1223
foreach ($attributes as $key => $value) {
1224
$t .= " $key=".'"'. check_plain($value) .'"';
1231
* Format an internal Drupal link.
1233
* This function correctly handles aliased paths, and allows themes to highlight
1234
* links to the current page correctly, so all internal links output by modules
1235
* should be generated by this function if possible.
1238
* The text to be enclosed with the anchor tag.
1240
* The Drupal path being linked to, such as "admin/content/node". Can be an external
1242
* - If you provide the full URL, it will be considered an
1244
* - If you provide only the path (e.g. "admin/content/node"), it is considered an
1245
* internal link. In this case, it must be a system URL as the url() function
1246
* will generate the alias.
1247
* @param $attributes
1248
* An associative array of HTML attributes to apply to the anchor tag.
1250
* A query string to append to the link.
1252
* A fragment identifier (named anchor) to append to the link.
1254
* Whether to force the output to be an absolute link (beginning with http:).
1255
* Useful for links that will be displayed outside the site, such as in an RSS
1258
* Whether the title is HTML, or just plain-text. For example for making an
1259
* image a link, this must be set to TRUE, or else you will see the encoded
1262
* an HTML string containing a link to the given path.
1264
function l($text, $path, $attributes = array(), $query = NULL, $fragment = NULL, $absolute = FALSE, $html = FALSE) {
1265
if ($path == $_GET['q']) {
1266
if (isset($attributes['class'])) {
1267
$attributes['class'] .= ' active';
1270
$attributes['class'] = 'active';
1273
return '<a href="'. check_url(url($path, $query, $fragment, $absolute)) .'"'. drupal_attributes($attributes) .'>'. ($html ? $text : check_plain($text)) .'</a>';
1277
* Perform end-of-request tasks.
1279
* This function sets the page cache if appropriate, and allows modules to
1280
* react to the closing of the page by calling hook_exit().
1282
function drupal_page_footer() {
1283
if (variable_get('cache', 0)) {
1287
module_invoke_all('exit');
1291
* Form an associative array from a linear array.
1293
* This function walks through the provided array and constructs an associative
1294
* array out of it. The keys of the resulting array will be the values of the
1295
* input array. The values will be the same as the keys unless a function is
1296
* specified, in which case the output of the function is used for the values
1302
* The name of a function to apply to all values before output.
1304
* An associative array.
1306
function drupal_map_assoc($array, $function = NULL) {
1307
if (!isset($function)) {
1309
foreach ($array as $value) {
1310
$result[$value] = $value;
1314
elseif (function_exists($function)) {
1316
foreach ($array as $value) {
1317
$result[$value] = $function($value);
1324
* Evaluate a string of PHP code.
1326
* This is a wrapper around PHP's eval(). It uses output buffering to capture both
1327
* returned and printed text. Unlike eval(), we require code to be surrounded by
1328
* <?php ?> tags; in other words, we evaluate the code as if it were a stand-alone
1331
* Using this wrapper also ensures that the PHP code which is evaluated can not
1332
* overwrite any variables in the calling code, unlike a regular eval() call.
1335
* The code to evaluate.
1337
* A string containing the printed output of the code, followed by the returned
1338
* output of the code.
1340
function drupal_eval($code) {
1342
print eval('?>'. $code);
1343
$output = ob_get_contents();
1349
* Returns the path to a system item (module, theme, etc.).
1352
* The type of the item (i.e. theme, theme_engine, module).
1354
* The name of the item for which the path is requested.
1357
* The path to the requested item.
1359
function drupal_get_path($type, $name) {
1360
return dirname(drupal_get_filename($type, $name));
1364
* Returns the base URL path of the Drupal installation.
1365
* At the very least, this will always default to /.
1367
function base_path() {
1368
return $GLOBALS['base_path'];
1372
* Provide a substitute clone() function for PHP4.
1374
function drupal_clone($object) {
1375
return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
1379
* Add a <link> tag to the page's HEAD.
1381
function drupal_add_link($attributes) {
1382
drupal_set_html_head('<link'. drupal_attributes($attributes) ." />\n");
1386
* Adds a CSS file to the stylesheet queue.
1389
* (optional) The path to the CSS file relative to the base_path(), e.g.,
1390
* /modules/devel/devel.css.
1392
* (optional) The type of stylesheet that is being added. Types are: module
1395
* (optional) The media type for the stylesheet, e.g., all, print, screen.
1396
* @param $preprocess
1397
* (optional) Should this CSS file be aggregated and compressed if this
1398
* feature has been turned on under the performance section?
1400
* What does this actually mean?
1401
* CSS preprocessing is the process of aggregating a bunch of separate CSS
1402
* files into one file that is then compressed by removing all extraneous
1405
* The reason for merging the CSS files is outlined quite thoroughly here:
1406
* http://www.die.net/musings/page_load_time/
1407
* "Load fewer external objects. Due to request overhead, one bigger file
1408
* just loads faster than two smaller ones half its size."
1410
* However, you should *not* preprocess every file as this can lead to
1411
* redundant caches. You should set $preprocess = FALSE when:
1413
* - Your styles are only used rarely on the site. This could be a special
1414
* admin page, the homepage, or a handful of pages that does not represent
1415
* the majority of the pages on your site.
1417
* Typical candidates for caching are for example styles for nodes across
1418
* the site, or used in the theme.
1420
* An array of CSS files.
1422
function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
1423
static $css = array();
1425
// Create an array of CSS files for each media type first, since each type needs to be served
1426
// to the browser differently.
1428
// This check is necessary to ensure proper cascading of styles and is faster than an asort().
1429
if (!isset($css[$media])) {
1430
$css[$media] = array('module' => array(), 'theme' => array());
1432
$css[$media][$type][$path] = $preprocess;
1439
* Returns a themed representation of all stylesheets that should be attached to the page.
1440
* It loads the CSS in order, with 'core' CSS first, then 'module' CSS, then 'theme' CSS files.
1441
* This ensures proper cascading of styles for easy overriding in modules and themes.
1444
* (optional) An array of CSS files. If no array is provided, the default stylesheets array is used instead.
1446
* A string of XHTML CSS tags.
1448
function drupal_get_css($css = NULL) {
1451
$css = drupal_add_css();
1454
$preprocess_css = variable_get('preprocess_css', FALSE);
1455
$directory = file_directory_path();
1456
$is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
1458
foreach ($css as $media => $types) {
1459
// If CSS preprocessing is off, we still need to output the styles.
1460
// Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
1461
foreach ($types as $type => $files) {
1462
foreach ($types[$type] as $file => $preprocess) {
1463
if (!$preprocess || !($is_writable && $preprocess_css)) {
1464
// If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
1465
// regardless of whether preprocessing is on or off.
1466
if (!$preprocess && $type == 'module') {
1467
$no_module_preprocess .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
1469
// If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
1470
// regardless of whether preprocessing is on or off.
1471
else if (!$preprocess && $type == 'theme') {
1472
$no_theme_preprocess .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
1475
$output .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $file .'";</style>' ."\n";
1481
if ($is_writable && $preprocess_css) {
1482
$filename = md5(serialize($types)) .'.css';
1483
$preprocess_file = drupal_build_css_cache($types, $filename);
1484
$output .= '<style type="text/css" media="'. $media .'">@import "'. base_path() . $preprocess_file .'";</style>'. "\n";
1488
return $no_module_preprocess . $output . $no_theme_preprocess;
1492
* Aggregate and optimize CSS files, putting them in the files directory.
1495
* An array of types of CSS files (e.g., screen, print) to aggregate and compress into one file.
1497
* The name of the aggregate CSS file.
1499
* The name of the CSS file.
1501
function drupal_build_css_cache($types, $filename) {
1504
// Create the css/ within the files folder.
1505
$csspath = file_create_path('css');
1506
file_check_directory($csspath, FILE_CREATE_DIRECTORY);
1508
if (!file_exists($csspath .'/'. $filename)) {
1509
// Build aggregate CSS file.
1510
foreach ($types as $type) {
1511
foreach ($type as $file => $cache) {
1513
$contents = file_get_contents($file);
1514
// Return the path to where this CSS file originated from, stripping off the name of the file at the end of the path.
1515
$path = base_path() . substr($file, 0, strrpos($file, '/')) .'/';
1516
// Wraps all @import arguments in url().
1517
$contents = preg_replace('/@import\s+(?!url)[\'"]?(\S*)\b[\'"]?/i', '@import url("\1")', $contents);
1518
// Fix all paths within this CSS file, ignoring absolute paths.
1519
$data .= preg_replace('/url\(([\'"]?)(?![a-z]+:)/i', 'url(\1'. $path . '\2', $contents);
1524
// @import rules must proceed any other style, so we move those to the top.
1525
$regexp = '/@import[^;]+;/i';
1526
preg_match_all($regexp, $data, $matches);
1527
$data = preg_replace($regexp, '', $data);
1528
$data = implode('', $matches[0]) . $data;
1530
// Perform some safe CSS optimizations.
1531
$data = preg_replace('<
1532
\s*([@{}:;,]|\)\s|\s\()\s* | # Remove whitespace around separators, but keep space around parentheses.
1533
/\*([^*\\\\]|\*(?!/))+\*/ | # Remove comments that are not CSS hacks.
1534
[\n\r] # Remove line breaks.
1537
// Create the CSS file.
1538
file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
1540
return $csspath .'/'. $filename;
1544
* Delete all cached CSS files.
1546
function drupal_clear_css_cache() {
1547
file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
1551
* Add a JavaScript file, setting or inline code to the page.
1553
* The behavior of this function depends on the parameters it is called with.
1554
* Generally, it handles the addition of JavaScript to the page, either as
1555
* reference to an existing file or as inline code. The following actions can be
1556
* performed using this function:
1558
* - Add a file ('core', 'module' and 'theme'):
1559
* Adds a reference to a JavaScript file to the page. JavaScript files
1560
* are placed in a certain order, from 'core' first, to 'module' and finally
1561
* 'theme' so that files, that are added later, can override previously added
1564
* - Add inline JavaScript code ('inline'):
1565
* Executes a piece of JavaScript code on the current page by placing the code
1566
* directly in the page. This can, for example, be useful to tell the user that
1567
* a new message arrived, by opening a pop up, alert box etc.
1569
* - Add settings ('setting'):
1570
* Adds a setting to Drupal's global storage of JavaScript settings. Per-page
1571
* settings are required by some modules to function properly. The settings
1572
* will be accessible at Drupal.settings.
1575
* (optional) If given, the value depends on the $type parameter:
1576
* - 'core', 'module' or 'theme': Path to the file relative to base_path().
1577
* - 'inline': The JavaScript code that should be placed in the given scope.
1578
* - 'setting': An array with configuration options as associative array. The
1579
* array is directly placed in Drupal.settings. You might want to wrap your
1580
* actual configuration settings in another variable to prevent the pollution
1581
* of the Drupal.settings namespace.
1583
* (optional) The type of JavaScript that should be added to the page. Allowed
1584
* values are 'core', 'module', 'theme', 'inline' and 'setting'. You
1585
* can, however, specify any value. It is treated as a reference to a JavaScript
1586
* file. Defaults to 'module'.
1588
* (optional) The location in which you want to place the script. Possible
1589
* values are 'header' and 'footer' by default. If your theme implements
1590
* different locations, however, you can also use these.
1592
* (optional) If set to TRUE, the defer attribute is set on the <script> tag.
1593
* Defaults to FALSE. This parameter is not used with $type == 'setting'.
1595
* (optional) If set to FALSE, the JavaScript file is loaded anew on every page
1596
* call, that means, it is not cached. Defaults to TRUE. Used only when $type
1597
* references a JavaScript file.
1599
* If the first parameter is NULL, the JavaScript array that has been built so
1600
* far for $scope is returned.
1602
function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE) {
1603
if (!is_null($data)) {
1604
_drupal_add_js('misc/jquery.js', 'core', 'header', FALSE, $cache);
1605
_drupal_add_js('misc/drupal.js', 'core', 'header', FALSE, $cache);
1607
return _drupal_add_js($data, $type, $scope, $defer, $cache);
1611
* Helper function for drupal_add_js().
1613
function _drupal_add_js($data, $type, $scope, $defer, $cache) {
1614
static $javascript = array();
1616
if (!isset($javascript[$scope])) {
1617
$javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
1620
if (!isset($javascript[$scope][$type])) {
1621
$javascript[$scope][$type] = array();
1624
if (!is_null($data)) {
1627
$javascript[$scope][$type][] = $data;
1630
$javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
1633
$javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer);
1637
return $javascript[$scope];
1641
* Returns a themed presentation of all JavaScript code for the current page.
1642
* References to JavaScript files are placed in a certain order: first, all
1643
* 'core' files, then all 'module' and finally all 'theme' JavaScript files
1644
* are added to the page. Then, all settings are output, followed by 'inline'
1648
* (optional) The scope for which the JavaScript rules should be returned.
1649
* Defaults to 'header'.
1650
* @parameter $javascript
1651
* (optional) An array with all JavaScript code. Defaults to the default
1652
* JavaScript array for the given scope.
1654
* All JavaScript code segments and includes for the scope as HTML tags.
1656
function drupal_get_js($scope = 'header', $javascript = NULL) {
1658
if (is_null($javascript)) {
1659
$javascript = drupal_add_js(NULL, NULL, $scope);
1662
foreach ($javascript as $type => $data) {
1663
if (!$data) continue;
1667
$output .= '<script type="text/javascript">Drupal.extend({ settings: '. drupal_to_js(call_user_func_array('array_merge_recursive', $data)) ." });</script>\n";
1670
foreach ($data as $info) {
1671
$output .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .'>'. $info['code'] ."</script>\n";
1675
foreach ($data as $path => $info) {
1676
$output .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .' src="'. check_url(base_path() . $path) . ($info['cache'] ? '' : '?'. time()) ."\"></script>\n";
1685
* Converts a PHP variable into its Javascript equivalent.
1687
* We use HTML-safe strings, i.e. with <, > and & escaped.
1689
function drupal_to_js($var) {
1690
switch (gettype($var)) {
1692
return $var ? 'true' : 'false'; // Lowercase necessary!
1698
return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
1699
array('\r', '\n', '\x3c', '\x3e', '\x26'),
1700
addslashes($var)) .'"';
1702
if (array_keys($var) === range(0, sizeof($var) - 1)) {
1704
foreach ($var as $v) {
1705
$output[] = drupal_to_js($v);
1707
return '[ '. implode(', ', $output) .' ]';
1712
foreach ($var as $k => $v) {
1713
$output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
1715
return '{ '. implode(', ', $output) .' }';
1722
* Wrapper around urlencode() which avoids Apache quirks.
1724
* Should be used when placing arbitrary data in an URL. Note that Drupal paths
1725
* are urlencoded() when passed through url() and do not require urlencoding()
1726
* of individual components.
1729
* - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
1730
* in Apache where it 404s on any path containing '%2F'.
1731
* - mod_rewrite's unescapes %-encoded ampersands and hashes when clean URLs
1732
* are used, which are interpreted as delimiters by PHP. These characters are
1733
* double escaped so PHP will still see the encoded version.
1738
function drupal_urlencode($text) {
1739
if (variable_get('clean_url', '0')) {
1740
return str_replace(array('%2F', '%26', '%23'),
1741
array('/', '%2526', '%2523'),
1745
return str_replace('%2F', '/', urlencode($text));
1750
* Ensure the private key variable used to generate tokens is set.
1755
function drupal_get_private_key() {
1756
if (!($key = variable_get('drupal_private_key', 0))) {
1757
$key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
1758
variable_set('drupal_private_key', $key);
1764
* Generate a token based on $value, the current user session and private key.
1767
* An additional value to base the token on
1769
function drupal_get_token($value = '') {
1770
$private_key = drupal_get_private_key();
1771
return md5(session_id() . $value . $private_key);
1775
* Validate a token based on $value, the current user session and private key.
1778
* The token to be validated.
1780
* An additional value to base the token on.
1781
* @param $skip_anonymous
1782
* Set to true to skip token validation for anonymous users.
1784
* True for a valid token, false for an invalid token. When $skip_anonymous is true, the return value will always be true for anonymous users.
1786
function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
1788
return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
1792
* Performs one or more XML-RPC request(s).
1795
* An absolute URL of the XML-RPC endpoint.
1797
* http://www.example.com/xmlrpc.php
1800
* The method name followed by a variable number of arguments to the method.
1801
* For multiple requests (system.multicall):
1802
* An array of call arrays. Each call array follows the pattern of the single
1803
* request: method name followed by the arguments to the method.
1806
* Either the return value of the method on success, or FALSE.
1807
* If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
1808
* For multiple requests:
1809
* An array of results. Each result will either be the result
1810
* returned by the method called, or an xmlrpc_error object if the call
1811
* failed. See xmlrpc_error().
1813
function xmlrpc($url) {
1814
require_once './includes/xmlrpc.inc';
1815
$args = func_get_args();
1816
return call_user_func_array('_xmlrpc', $args);
1819
function _drupal_bootstrap_full() {
1827
require_once './includes/theme.inc';
1828
require_once './includes/pager.inc';
1829
require_once './includes/menu.inc';
1830
require_once './includes/tablesort.inc';
1831
require_once './includes/file.inc';
1832
require_once './includes/unicode.inc';
1833
require_once './includes/image.inc';
1834
require_once './includes/form.inc';
1835
// Set the Drupal custom error handler.
1836
set_error_handler('error_handler');
1837
// Emit the correct charset HTTP header.
1838
drupal_set_header('Content-Type: text/html; charset=utf-8');
1839
// Detect string handling method
1841
// Undo magic quotes
1843
// Load all enabled modules
1845
// Initialize the localization system. Depends on i18n.module being loaded already.
1846
$locale = locale_initialize();
1847
// Let all modules take action before menu system handles the reqest
1848
module_invoke_all('init');
1853
* Store the current page in the cache.
1855
* We try to store a gzipped version of the cache. This requires the
1856
* PHP zlib extension (http://php.net/manual/en/ref.zlib.php).
1857
* Presence of the extension is checked by testing for the function
1858
* gzencode. There are two compression algorithms: gzip and deflate.
1859
* The majority of all modern browsers support gzip or both of them.
1860
* We thus only deal with the gzip variant and unzip the cache in case
1861
* the browser does not accept gzip encoding.
1863
* @see drupal_page_header
1865
function page_set_cache() {
1866
global $user, $base_root;
1868
if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && count(drupal_get_messages(NULL, FALSE)) == 0) {
1869
// This will fail in some cases, see page_get_cache() for the explanation.
1870
if ($data = ob_get_contents()) {
1872
if (function_exists('gzencode')) {
1873
// We do not store the data in case the zlib mode is deflate.
1874
// This should be rarely happening.
1875
if (zlib_get_coding_type() == 'deflate') {
1878
else if (zlib_get_coding_type() == FALSE) {
1879
$data = gzencode($data, 9, FORCE_GZIP);
1881
// The remaining case is 'gzip' which means the data is
1882
// already compressed and nothing left to do but to store it.
1885
if ($cache && $data) {
1886
cache_set($base_root . request_uri(), 'cache_page', $data, CACHE_TEMPORARY, drupal_get_headers());
1893
* Send an e-mail message, using Drupal variables and default settings.
1894
* More information in the <a href="http://php.net/manual/en/function.mail.php">
1895
* PHP function reference for mail()</a>
1897
* A key to identify the mail sent, for altering.
1899
* The mail address or addresses where the message will be send to. The
1900
* formatting of this string must comply with RFC 2822. Some examples are:
1902
* user@example.com, anotheruser@example.com
1903
* User <user@example.com>
1904
* User <user@example.com>, Another User <anotheruser@example.com>
1906
* Subject of the e-mail to be sent. This must not contain any newline
1907
* characters, or the mail may not be sent properly.
1909
* Message to be sent. Drupal will format the correct line endings for you.
1911
* Sets From, Reply-To, Return-Path and Error-To to this value, if given.
1913
* Associative array containing the headers to add. This is typically
1914
* used to add extra headers (From, Cc, and Bcc).
1915
* <em>When sending mail, the mail must contain a From header.</em>
1916
* @return Returns TRUE if the mail was successfully accepted for delivery,
1919
function drupal_mail($mailkey, $to, $subject, $body, $from = NULL, $headers = array()) {
1921
'MIME-Version' => '1.0',
1922
'Content-Type' => 'text/plain; charset=UTF-8; format=flowed',
1923
'Content-Transfer-Encoding' => '8Bit',
1924
'X-Mailer' => 'Drupal'
1927
$defaults['From'] = $defaults['Reply-To'] = $defaults['Return-Path'] = $defaults['Errors-To'] = $from;
1929
$headers = array_merge($defaults, $headers);
1930
// Custom hook traversal to allow pass by reference
1931
foreach (module_implements('mail_alter') AS $module) {
1932
$function = $module .'_mail_alter';
1933
$function($mailkey, $to, $subject, $body, $from, $headers);
1935
// Allow for custom mail backend
1936
if (variable_get('smtp_library', '') && file_exists(variable_get('smtp_library', ''))) {
1937
include_once './' . variable_get('smtp_library', '');
1938
return drupal_mail_wrapper($mailkey, $to, $subject, $body, $from, $headers);
1942
** Note: if you are having problems with sending mail, or mails look wrong
1943
** when they are received you may have to modify the str_replace to suit
1945
** - \r\n will work under dos and windows.
1946
** - \n will work for linux, unix and BSDs.
1947
** - \r will work for macs.
1949
** According to RFC 2646, it's quite rude to not wrap your e-mails:
1951
** "The Text/Plain media type is the lowest common denominator of
1952
** Internet e-mail, with lines of no more than 997 characters (by
1953
** convention usually no more than 80), and where the CRLF sequence
1954
** represents a line break [MIME-IMT]."
1958
** http://www.rfc-editor.org/rfc/rfc2646.txt
1961
$mimeheaders = array();
1962
foreach ($headers as $name => $value) {
1963
$mimeheaders[] = $name .': '. mime_header_encode($value);
1967
mime_header_encode($subject),
1968
str_replace("\r", '', $body),
1969
join("\n", $mimeheaders)
1975
* Executes a cron run when called
1977
* Returns TRUE if ran successfully
1979
function drupal_cron_run() {
1980
// If not in 'safe mode', increase the maximum execution time:
1981
if (!ini_get('safe_mode')) {
1982
set_time_limit(240);
1985
// Fetch the cron semaphore
1986
$semaphore = variable_get('cron_semaphore', FALSE);
1989
if (time() - $semaphore > 3600) {
1990
// Either cron has been running for more than an hour or the semaphore
1991
// was not reset due to a database error.
1992
watchdog('cron', t('Cron has been running for more than an hour and is most likely stuck.'), WATCHDOG_ERROR);
1994
// Release cron semaphore
1995
variable_del('cron_semaphore');
1998
// Cron is still running normally.
1999
watchdog('cron', t('Attempting to re-run cron while it is already running.'), WATCHDOG_WARNING);
2003
// Register shutdown callback
2004
register_shutdown_function('drupal_cron_cleanup');
2006
// Lock cron semaphore
2007
variable_set('cron_semaphore', time());
2009
// Iterate through the modules calling their cron handlers (if any):
2010
module_invoke_all('cron');
2013
variable_set('cron_last', time());
2014
watchdog('cron', t('Cron run completed.'), WATCHDOG_NOTICE);
2016
// Release cron semaphore
2017
variable_del('cron_semaphore');
2019
// Return TRUE so other functions can check if it did run successfully
2025
* Shutdown function for cron cleanup.
2027
function drupal_cron_cleanup() {
2028
// See if the semaphore is still locked.
2029
if (variable_get('cron_semaphore', FALSE)) {
2030
watchdog('cron', t('Cron run exceeded the time limit and was aborted.'), WATCHDOG_WARNING);
2032
// Release cron semaphore
2033
variable_del('cron_semaphore');
2038
* Returns an array of files objects of the given type from the site-wide
2039
* directory (i.e. modules/), the all-sites directory (i.e.
2040
* sites/all/modules/), the profiles directory, and site-specific directory
2041
* (i.e. sites/somesite/modules/). The returned array will be keyed using the
2042
* key specified (name, basename, filename). Using name or basename will cause
2043
* site-specific files to be prioritized over similar files in the default
2044
* directories. That is, if a file with the same name appears in both the
2045
* site-wide directory and site-specific directory, only the site-specific
2046
* version will be included.
2049
* The regular expression of the files to find.
2051
* The subdirectory name in which the files are found. For example,
2052
* 'modules' will search in both modules/ and
2053
* sites/somesite/modules/.
2055
* The key to be passed to file_scan_directory().
2057
* Minimum depth of directories to return files from.
2060
* An array of file objects of the specified type.
2062
function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
2064
$config = conf_path();
2066
// When this function is called during Drupal's initial installation process,
2067
// the name of the profile that's about to be installed is stored in the global
2068
// $profile variable. At all other times, the standard Drupal systems variable
2069
// table contains the name of the current profile, and we can call variable_get()
2070
// to determine what one is active.
2071
if (!isset($profile)) {
2072
$profile = variable_get('install_profile', 'default');
2074
$searchdir = array($directory);
2077
// Always search sites/all/* as well as the global directories
2078
$searchdir[] = 'sites/all/'. $directory;
2080
// The 'profiles' directory contains pristine collections of modules and
2081
// themes as organized by a distribution. It is pristine in the same way
2082
// that /modules is pristine for core; users should avoid changing anything
2083
// there in favor of sites/all or sites/<domain> directories.
2084
if (file_exists("profiles/$profile/$directory")) {
2085
$searchdir[] = "profiles/$profile/$directory";
2088
if (file_exists("$config/$directory")) {
2089
$searchdir[] = "$config/$directory";
2092
// Get current list of items
2093
foreach ($searchdir as $dir) {
2094
$files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
2101
* Renders HTML given a structured array tree. Recursively iterates over each
2102
* of the array elements, generating HTML code. This function is usually
2103
* called from within a another function, like drupal_get_form() or node_view().
2106
* The structured array describing the data to be rendered.
2108
* The rendered HTML.
2110
function drupal_render(&$elements) {
2111
if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
2116
// Either the elements did not go through form_builder or one of the children
2118
if (!isset($elements['#sorted'])) {
2119
uasort($elements, "_element_sort");
2121
if (!isset($elements['#children'])) {
2122
$children = element_children($elements);
2123
/* Render all the children that use a theme function */
2124
if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
2125
$elements['#theme_used'] = TRUE;
2127
$previous = array();
2128
foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
2129
$previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
2131
// If we rendered a single element, then we will skip the renderer.
2132
if (empty($children)) {
2133
$elements['#printed'] = TRUE;
2136
$elements['#value'] = '';
2138
$elements['#type'] = 'markup';
2140
unset($elements['#prefix'], $elements['#suffix']);
2141
$content = theme($elements['#theme'], $elements);
2143
foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
2144
$elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
2147
/* render each of the children using drupal_render and concatenate them */
2148
if (!isset($content) || $content === '') {
2149
foreach ($children as $key) {
2150
$content .= drupal_render($elements[$key]);
2154
if (isset($content) && $content !== '') {
2155
$elements['#children'] = $content;
2158
// Until now, we rendered the children, here we render the element itself
2159
if (!isset($elements['#printed'])) {
2160
$content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
2161
$elements['#printed'] = TRUE;
2164
if (isset($content) && $content !== '') {
2165
$prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
2166
$suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
2167
return $prefix . $content . $suffix;
2172
* Function used by uasort in drupal_render() to sort structured arrays
2175
function _element_sort($a, $b) {
2176
$a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
2177
$b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
2178
if ($a_weight == $b_weight) {
2181
return ($a_weight < $b_weight) ? -1 : 1;
2185
* Check if the key is a property.
2187
function element_property($key) {
2188
return $key[0] == '#';
2192
* Get properties of a structured array element. Properties begin with '#'.
2194
function element_properties($element) {
2195
return array_filter(array_keys((array) $element), 'element_property');
2199
* Check if the key is a child.
2201
function element_child($key) {
2202
return $key[0] != '#';
2206
* Get keys of a structured array tree element that are not properties
2207
* (i.e., do not begin with '#').
2209
function element_children($element) {
2210
return array_filter(array_keys((array) $element), 'element_child');