annotate includes/common.inc @ 11:589fb7c02327 6.5

Drupal 6.5
author Franck Deroche <webmaster@defr.org>
date Tue, 23 Dec 2008 14:32:19 +0100
parents acef7ccb09b5
children 8b6c45761e01
rev   line source
webmaster@1 1 <?php
webmaster@11 2 // $Id: common.inc,v 1.756.2.27 2008/10/08 20:12:17 goba Exp $
webmaster@1 3
webmaster@1 4 /**
webmaster@1 5 * @file
webmaster@1 6 * Common functions that many Drupal modules will need to reference.
webmaster@1 7 *
webmaster@1 8 * The functions that are critical and need to be available even when serving
webmaster@1 9 * a cached page are instead located in bootstrap.inc.
webmaster@1 10 */
webmaster@1 11
webmaster@1 12 /**
webmaster@1 13 * Return status for saving which involved creating a new item.
webmaster@1 14 */
webmaster@1 15 define('SAVED_NEW', 1);
webmaster@1 16
webmaster@1 17 /**
webmaster@1 18 * Return status for saving which involved an update to an existing item.
webmaster@1 19 */
webmaster@1 20 define('SAVED_UPDATED', 2);
webmaster@1 21
webmaster@1 22 /**
webmaster@1 23 * Return status for saving which deleted an existing item.
webmaster@1 24 */
webmaster@1 25 define('SAVED_DELETED', 3);
webmaster@1 26
webmaster@1 27 /**
webmaster@1 28 * Set content for a specified region.
webmaster@1 29 *
webmaster@1 30 * @param $region
webmaster@1 31 * Page region the content is assigned to.
webmaster@1 32 * @param $data
webmaster@1 33 * Content to be set.
webmaster@1 34 */
webmaster@1 35 function drupal_set_content($region = NULL, $data = NULL) {
webmaster@1 36 static $content = array();
webmaster@1 37
webmaster@1 38 if (!is_null($region) && !is_null($data)) {
webmaster@1 39 $content[$region][] = $data;
webmaster@1 40 }
webmaster@1 41 return $content;
webmaster@1 42 }
webmaster@1 43
webmaster@1 44 /**
webmaster@1 45 * Get assigned content.
webmaster@1 46 *
webmaster@1 47 * @param $region
webmaster@1 48 * A specified region to fetch content for. If NULL, all regions will be
webmaster@1 49 * returned.
webmaster@1 50 * @param $delimiter
webmaster@1 51 * Content to be inserted between exploded array elements.
webmaster@1 52 */
webmaster@1 53 function drupal_get_content($region = NULL, $delimiter = ' ') {
webmaster@1 54 $content = drupal_set_content();
webmaster@1 55 if (isset($region)) {
webmaster@1 56 if (isset($content[$region]) && is_array($content[$region])) {
webmaster@1 57 return implode($delimiter, $content[$region]);
webmaster@1 58 }
webmaster@1 59 }
webmaster@1 60 else {
webmaster@1 61 foreach (array_keys($content) as $region) {
webmaster@1 62 if (is_array($content[$region])) {
webmaster@1 63 $content[$region] = implode($delimiter, $content[$region]);
webmaster@1 64 }
webmaster@1 65 }
webmaster@1 66 return $content;
webmaster@1 67 }
webmaster@1 68 }
webmaster@1 69
webmaster@1 70 /**
webmaster@1 71 * Set the breadcrumb trail for the current page.
webmaster@1 72 *
webmaster@1 73 * @param $breadcrumb
webmaster@1 74 * Array of links, starting with "home" and proceeding up to but not including
webmaster@1 75 * the current page.
webmaster@1 76 */
webmaster@1 77 function drupal_set_breadcrumb($breadcrumb = NULL) {
webmaster@1 78 static $stored_breadcrumb;
webmaster@1 79
webmaster@1 80 if (!is_null($breadcrumb)) {
webmaster@1 81 $stored_breadcrumb = $breadcrumb;
webmaster@1 82 }
webmaster@1 83 return $stored_breadcrumb;
webmaster@1 84 }
webmaster@1 85
webmaster@1 86 /**
webmaster@1 87 * Get the breadcrumb trail for the current page.
webmaster@1 88 */
webmaster@1 89 function drupal_get_breadcrumb() {
webmaster@1 90 $breadcrumb = drupal_set_breadcrumb();
webmaster@1 91
webmaster@1 92 if (is_null($breadcrumb)) {
webmaster@1 93 $breadcrumb = menu_get_active_breadcrumb();
webmaster@1 94 }
webmaster@1 95
webmaster@1 96 return $breadcrumb;
webmaster@1 97 }
webmaster@1 98
webmaster@1 99 /**
webmaster@1 100 * Add output to the head tag of the HTML page.
webmaster@1 101 *
webmaster@1 102 * This function can be called as long the headers aren't sent.
webmaster@1 103 */
webmaster@1 104 function drupal_set_html_head($data = NULL) {
webmaster@1 105 static $stored_head = '';
webmaster@1 106
webmaster@1 107 if (!is_null($data)) {
webmaster@1 108 $stored_head .= $data ."\n";
webmaster@1 109 }
webmaster@1 110 return $stored_head;
webmaster@1 111 }
webmaster@1 112
webmaster@1 113 /**
webmaster@1 114 * Retrieve output to be displayed in the head tag of the HTML page.
webmaster@1 115 */
webmaster@1 116 function drupal_get_html_head() {
webmaster@1 117 $output = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n";
webmaster@1 118 return $output . drupal_set_html_head();
webmaster@1 119 }
webmaster@1 120
webmaster@1 121 /**
webmaster@1 122 * Reset the static variable which holds the aliases mapped for this request.
webmaster@1 123 */
webmaster@1 124 function drupal_clear_path_cache() {
webmaster@1 125 drupal_lookup_path('wipe');
webmaster@1 126 }
webmaster@1 127
webmaster@1 128 /**
webmaster@1 129 * Set an HTTP response header for the current page.
webmaster@1 130 *
webmaster@1 131 * Note: When sending a Content-Type header, always include a 'charset' type,
webmaster@1 132 * too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
webmaster@1 133 */
webmaster@1 134 function drupal_set_header($header = NULL) {
webmaster@1 135 // We use an array to guarantee there are no leading or trailing delimiters.
webmaster@1 136 // Otherwise, header('') could get called when serving the page later, which
webmaster@1 137 // ends HTTP headers prematurely on some PHP versions.
webmaster@1 138 static $stored_headers = array();
webmaster@1 139
webmaster@1 140 if (strlen($header)) {
webmaster@1 141 header($header);
webmaster@1 142 $stored_headers[] = $header;
webmaster@1 143 }
webmaster@1 144 return implode("\n", $stored_headers);
webmaster@1 145 }
webmaster@1 146
webmaster@1 147 /**
webmaster@1 148 * Get the HTTP response headers for the current page.
webmaster@1 149 */
webmaster@1 150 function drupal_get_headers() {
webmaster@1 151 return drupal_set_header();
webmaster@1 152 }
webmaster@1 153
webmaster@1 154 /**
webmaster@1 155 * Add a feed URL for the current page.
webmaster@1 156 *
webmaster@1 157 * @param $url
webmaster@1 158 * A url for the feed.
webmaster@1 159 * @param $title
webmaster@1 160 * The title of the feed.
webmaster@1 161 */
webmaster@1 162 function drupal_add_feed($url = NULL, $title = '') {
webmaster@1 163 static $stored_feed_links = array();
webmaster@1 164
webmaster@1 165 if (!is_null($url) && !isset($stored_feed_links[$url])) {
webmaster@1 166 $stored_feed_links[$url] = theme('feed_icon', $url, $title);
webmaster@1 167
webmaster@1 168 drupal_add_link(array('rel' => 'alternate',
webmaster@1 169 'type' => 'application/rss+xml',
webmaster@1 170 'title' => $title,
webmaster@1 171 'href' => $url));
webmaster@1 172 }
webmaster@1 173 return $stored_feed_links;
webmaster@1 174 }
webmaster@1 175
webmaster@1 176 /**
webmaster@1 177 * Get the feed URLs for the current page.
webmaster@1 178 *
webmaster@1 179 * @param $delimiter
webmaster@1 180 * A delimiter to split feeds by.
webmaster@1 181 */
webmaster@1 182 function drupal_get_feeds($delimiter = "\n") {
webmaster@1 183 $feeds = drupal_add_feed();
webmaster@1 184 return implode($feeds, $delimiter);
webmaster@1 185 }
webmaster@1 186
webmaster@1 187 /**
webmaster@1 188 * @name HTTP handling
webmaster@1 189 * @{
webmaster@1 190 * Functions to properly handle HTTP responses.
webmaster@1 191 */
webmaster@1 192
webmaster@1 193 /**
webmaster@1 194 * Parse an array into a valid urlencoded query string.
webmaster@1 195 *
webmaster@1 196 * @param $query
webmaster@1 197 * The array to be processed e.g. $_GET.
webmaster@1 198 * @param $exclude
webmaster@1 199 * The array filled with keys to be excluded. Use parent[child] to exclude
webmaster@1 200 * nested items.
webmaster@1 201 * @param $parent
webmaster@1 202 * Should not be passed, only used in recursive calls.
webmaster@1 203 * @return
webmaster@1 204 * An urlencoded string which can be appended to/as the URL query string.
webmaster@1 205 */
webmaster@1 206 function drupal_query_string_encode($query, $exclude = array(), $parent = '') {
webmaster@1 207 $params = array();
webmaster@1 208
webmaster@1 209 foreach ($query as $key => $value) {
webmaster@1 210 $key = drupal_urlencode($key);
webmaster@1 211 if ($parent) {
webmaster@1 212 $key = $parent .'['. $key .']';
webmaster@1 213 }
webmaster@1 214
webmaster@1 215 if (in_array($key, $exclude)) {
webmaster@1 216 continue;
webmaster@1 217 }
webmaster@1 218
webmaster@1 219 if (is_array($value)) {
webmaster@1 220 $params[] = drupal_query_string_encode($value, $exclude, $key);
webmaster@1 221 }
webmaster@1 222 else {
webmaster@1 223 $params[] = $key .'='. drupal_urlencode($value);
webmaster@1 224 }
webmaster@1 225 }
webmaster@1 226
webmaster@1 227 return implode('&', $params);
webmaster@1 228 }
webmaster@1 229
webmaster@1 230 /**
webmaster@1 231 * Prepare a destination query string for use in combination with drupal_goto().
webmaster@1 232 *
webmaster@1 233 * Used to direct the user back to the referring page after completing a form.
webmaster@1 234 * By default the current URL is returned. If a destination exists in the
webmaster@1 235 * previous request, that destination is returned. As such, a destination can
webmaster@1 236 * persist across multiple pages.
webmaster@1 237 *
webmaster@1 238 * @see drupal_goto()
webmaster@1 239 */
webmaster@1 240 function drupal_get_destination() {
webmaster@1 241 if (isset($_REQUEST['destination'])) {
webmaster@1 242 return 'destination='. urlencode($_REQUEST['destination']);
webmaster@1 243 }
webmaster@1 244 else {
webmaster@1 245 // Use $_GET here to retrieve the original path in source form.
webmaster@1 246 $path = isset($_GET['q']) ? $_GET['q'] : '';
webmaster@1 247 $query = drupal_query_string_encode($_GET, array('q'));
webmaster@1 248 if ($query != '') {
webmaster@1 249 $path .= '?'. $query;
webmaster@1 250 }
webmaster@1 251 return 'destination='. urlencode($path);
webmaster@1 252 }
webmaster@1 253 }
webmaster@1 254
webmaster@1 255 /**
webmaster@1 256 * Send the user to a different Drupal page.
webmaster@1 257 *
webmaster@1 258 * This issues an on-site HTTP redirect. The function makes sure the redirected
webmaster@1 259 * URL is formatted correctly.
webmaster@1 260 *
webmaster@1 261 * Usually the redirected URL is constructed from this function's input
webmaster@1 262 * parameters. However you may override that behavior by setting a
webmaster@7 263 * destination in either the $_REQUEST-array (i.e. by using
webmaster@1 264 * the query string of an URI) or the $_REQUEST['edit']-array (i.e. by
webmaster@1 265 * using a hidden form field). This is used to direct the user back to
webmaster@1 266 * the proper page after completing a form. For example, after editing
webmaster@1 267 * a post on the 'admin/content/node'-page or after having logged on using the
webmaster@1 268 * 'user login'-block in a sidebar. The function drupal_get_destination()
webmaster@1 269 * can be used to help set the destination URL.
webmaster@1 270 *
webmaster@1 271 * Drupal will ensure that messages set by drupal_set_message() and other
webmaster@1 272 * session data are written to the database before the user is redirected.
webmaster@1 273 *
webmaster@1 274 * This function ends the request; use it rather than a print theme('page')
webmaster@1 275 * statement in your menu callback.
webmaster@1 276 *
webmaster@1 277 * @param $path
webmaster@1 278 * A Drupal path or a full URL.
webmaster@1 279 * @param $query
webmaster@1 280 * A query string component, if any.
webmaster@1 281 * @param $fragment
webmaster@1 282 * A destination fragment identifier (named anchor).
webmaster@1 283 * @param $http_response_code
webmaster@1 284 * Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
webmaster@1 285 * - 301 Moved Permanently (the recommended value for most redirects)
webmaster@1 286 * - 302 Found (default in Drupal and PHP, sometimes used for spamming search
webmaster@1 287 * engines)
webmaster@1 288 * - 303 See Other
webmaster@1 289 * - 304 Not Modified
webmaster@1 290 * - 305 Use Proxy
webmaster@1 291 * - 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")
webmaster@1 292 * Note: Other values are defined by RFC 2616, but are rarely used and poorly
webmaster@1 293 * supported.
webmaster@1 294 * @see drupal_get_destination()
webmaster@1 295 */
webmaster@1 296 function drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302) {
webmaster@1 297
webmaster@1 298 if (isset($_REQUEST['destination'])) {
webmaster@1 299 extract(parse_url(urldecode($_REQUEST['destination'])));
webmaster@1 300 }
webmaster@1 301 else if (isset($_REQUEST['edit']['destination'])) {
webmaster@1 302 extract(parse_url(urldecode($_REQUEST['edit']['destination'])));
webmaster@1 303 }
webmaster@1 304
webmaster@1 305 $url = url($path, array('query' => $query, 'fragment' => $fragment, 'absolute' => TRUE));
webmaster@1 306 // Remove newlines from the URL to avoid header injection attacks.
webmaster@1 307 $url = str_replace(array("\n", "\r"), '', $url);
webmaster@1 308
webmaster@1 309 // Allow modules to react to the end of the page request before redirecting.
webmaster@1 310 // We do not want this while running update.php.
webmaster@1 311 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
webmaster@1 312 module_invoke_all('exit', $url);
webmaster@1 313 }
webmaster@1 314
webmaster@1 315 // Even though session_write_close() is registered as a shutdown function, we
webmaster@1 316 // need all session data written to the database before redirecting.
webmaster@1 317 session_write_close();
webmaster@1 318
webmaster@1 319 header('Location: '. $url, TRUE, $http_response_code);
webmaster@1 320
webmaster@1 321 // The "Location" header sends a redirect status code to the HTTP daemon. In
webmaster@1 322 // some cases this can be wrong, so we make sure none of the code below the
webmaster@1 323 // drupal_goto() call gets executed upon redirection.
webmaster@1 324 exit();
webmaster@1 325 }
webmaster@1 326
webmaster@1 327 /**
webmaster@1 328 * Generates a site off-line message.
webmaster@1 329 */
webmaster@1 330 function drupal_site_offline() {
webmaster@1 331 drupal_maintenance_theme();
webmaster@1 332 drupal_set_header('HTTP/1.1 503 Service unavailable');
webmaster@1 333 drupal_set_title(t('Site off-line'));
webmaster@1 334 print theme('maintenance_page', filter_xss_admin(variable_get('site_offline_message',
webmaster@1 335 t('@site is currently under maintenance. We should be back shortly. Thank you for your patience.', array('@site' => variable_get('site_name', 'Drupal'))))));
webmaster@1 336 }
webmaster@1 337
webmaster@1 338 /**
webmaster@1 339 * Generates a 404 error if the request can not be handled.
webmaster@1 340 */
webmaster@1 341 function drupal_not_found() {
webmaster@1 342 drupal_set_header('HTTP/1.1 404 Not Found');
webmaster@1 343
webmaster@1 344 watchdog('page not found', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
webmaster@1 345
webmaster@1 346 // Keep old path for reference.
webmaster@1 347 if (!isset($_REQUEST['destination'])) {
webmaster@1 348 $_REQUEST['destination'] = $_GET['q'];
webmaster@1 349 }
webmaster@1 350
webmaster@1 351 $path = drupal_get_normal_path(variable_get('site_404', ''));
webmaster@1 352 if ($path && $path != $_GET['q']) {
webmaster@1 353 // Set the active item in case there are tabs to display, or other
webmaster@1 354 // dependencies on the path.
webmaster@1 355 menu_set_active_item($path);
webmaster@1 356 $return = menu_execute_active_handler($path);
webmaster@1 357 }
webmaster@1 358
webmaster@1 359 if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
webmaster@1 360 drupal_set_title(t('Page not found'));
webmaster@1 361 $return = t('The requested page could not be found.');
webmaster@1 362 }
webmaster@1 363
webmaster@1 364 // To conserve CPU and bandwidth, omit the blocks.
webmaster@1 365 print theme('page', $return, FALSE);
webmaster@1 366 }
webmaster@1 367
webmaster@1 368 /**
webmaster@1 369 * Generates a 403 error if the request is not allowed.
webmaster@1 370 */
webmaster@1 371 function drupal_access_denied() {
webmaster@1 372 drupal_set_header('HTTP/1.1 403 Forbidden');
webmaster@1 373 watchdog('access denied', check_plain($_GET['q']), NULL, WATCHDOG_WARNING);
webmaster@1 374
webmaster@1 375 // Keep old path for reference.
webmaster@1 376 if (!isset($_REQUEST['destination'])) {
webmaster@1 377 $_REQUEST['destination'] = $_GET['q'];
webmaster@1 378 }
webmaster@1 379
webmaster@1 380 $path = drupal_get_normal_path(variable_get('site_403', ''));
webmaster@1 381 if ($path && $path != $_GET['q']) {
webmaster@1 382 // Set the active item in case there are tabs to display or other
webmaster@1 383 // dependencies on the path.
webmaster@1 384 menu_set_active_item($path);
webmaster@1 385 $return = menu_execute_active_handler($path);
webmaster@1 386 }
webmaster@1 387
webmaster@1 388 if (empty($return) || $return == MENU_NOT_FOUND || $return == MENU_ACCESS_DENIED) {
webmaster@1 389 drupal_set_title(t('Access denied'));
webmaster@1 390 $return = t('You are not authorized to access this page.');
webmaster@1 391 }
webmaster@1 392 print theme('page', $return);
webmaster@1 393 }
webmaster@1 394
webmaster@1 395 /**
webmaster@1 396 * Perform an HTTP request.
webmaster@1 397 *
webmaster@1 398 * This is a flexible and powerful HTTP client implementation. Correctly handles
webmaster@1 399 * GET, POST, PUT or any other HTTP requests. Handles redirects.
webmaster@1 400 *
webmaster@1 401 * @param $url
webmaster@1 402 * A string containing a fully qualified URI.
webmaster@1 403 * @param $headers
webmaster@1 404 * An array containing an HTTP header => value pair.
webmaster@1 405 * @param $method
webmaster@1 406 * A string defining the HTTP request to use.
webmaster@1 407 * @param $data
webmaster@1 408 * A string containing data to include in the request.
webmaster@1 409 * @param $retry
webmaster@1 410 * An integer representing how many times to retry the request in case of a
webmaster@1 411 * redirect.
webmaster@1 412 * @return
webmaster@1 413 * An object containing the HTTP request headers, response code, headers,
webmaster@1 414 * data and redirect status.
webmaster@1 415 */
webmaster@1 416 function drupal_http_request($url, $headers = array(), $method = 'GET', $data = NULL, $retry = 3) {
webmaster@1 417 static $self_test = FALSE;
webmaster@1 418 $result = new stdClass();
webmaster@1 419 // Try to clear the drupal_http_request_fails variable if it's set. We
webmaster@1 420 // can't tie this call to any error because there is no surefire way to
webmaster@1 421 // tell whether a request has failed, so we add the check to places where
webmaster@1 422 // some parsing has failed.
webmaster@1 423 if (!$self_test && variable_get('drupal_http_request_fails', FALSE)) {
webmaster@1 424 $self_test = TRUE;
webmaster@1 425 $works = module_invoke('system', 'check_http_request');
webmaster@1 426 $self_test = FALSE;
webmaster@1 427 if (!$works) {
webmaster@1 428 // Do not bother with further operations if we already know that we
webmaster@1 429 // have no chance.
webmaster@1 430 $result->error = t("The server can't issue HTTP requests");
webmaster@1 431 return $result;
webmaster@1 432 }
webmaster@1 433 }
webmaster@1 434
webmaster@1 435 // Parse the URL and make sure we can handle the schema.
webmaster@1 436 $uri = parse_url($url);
webmaster@1 437
webmaster@9 438 if ($uri == FALSE) {
webmaster@9 439 $result->error = 'unable to parse URL';
webmaster@9 440 return $result;
webmaster@9 441 }
webmaster@9 442
webmaster@9 443 if (!isset($uri['scheme'])) {
webmaster@9 444 $result->error = 'missing schema';
webmaster@9 445 return $result;
webmaster@9 446 }
webmaster@9 447
webmaster@1 448 switch ($uri['scheme']) {
webmaster@1 449 case 'http':
webmaster@1 450 $port = isset($uri['port']) ? $uri['port'] : 80;
webmaster@1 451 $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
webmaster@1 452 $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
webmaster@1 453 break;
webmaster@1 454 case 'https':
webmaster@1 455 // Note: Only works for PHP 4.3 compiled with OpenSSL.
webmaster@1 456 $port = isset($uri['port']) ? $uri['port'] : 443;
webmaster@1 457 $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
webmaster@1 458 $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
webmaster@1 459 break;
webmaster@1 460 default:
webmaster@1 461 $result->error = 'invalid schema '. $uri['scheme'];
webmaster@1 462 return $result;
webmaster@1 463 }
webmaster@1 464
webmaster@1 465 // Make sure the socket opened properly.
webmaster@1 466 if (!$fp) {
webmaster@1 467 // When a network error occurs, we use a negative number so it does not
webmaster@1 468 // clash with the HTTP status codes.
webmaster@1 469 $result->code = -$errno;
webmaster@1 470 $result->error = trim($errstr);
webmaster@1 471 return $result;
webmaster@1 472 }
webmaster@1 473
webmaster@1 474 // Construct the path to act on.
webmaster@1 475 $path = isset($uri['path']) ? $uri['path'] : '/';
webmaster@1 476 if (isset($uri['query'])) {
webmaster@1 477 $path .= '?'. $uri['query'];
webmaster@1 478 }
webmaster@1 479
webmaster@1 480 // Create HTTP request.
webmaster@1 481 $defaults = array(
webmaster@1 482 // RFC 2616: "non-standard ports MUST, default ports MAY be included".
webmaster@1 483 // We don't add the port to prevent from breaking rewrite rules checking the
webmaster@1 484 // host that do not take into account the port number.
webmaster@1 485 'Host' => "Host: $host",
webmaster@1 486 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
webmaster@1 487 'Content-Length' => 'Content-Length: '. strlen($data)
webmaster@1 488 );
webmaster@1 489
webmaster@1 490 // If the server url has a user then attempt to use basic authentication
webmaster@1 491 if (isset($uri['user'])) {
webmaster@1 492 $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
webmaster@1 493 }
webmaster@1 494
webmaster@1 495 foreach ($headers as $header => $value) {
webmaster@1 496 $defaults[$header] = $header .': '. $value;
webmaster@1 497 }
webmaster@1 498
webmaster@1 499 $request = $method .' '. $path ." HTTP/1.0\r\n";
webmaster@1 500 $request .= implode("\r\n", $defaults);
webmaster@1 501 $request .= "\r\n\r\n";
webmaster@1 502 if ($data) {
webmaster@1 503 $request .= $data ."\r\n";
webmaster@1 504 }
webmaster@1 505 $result->request = $request;
webmaster@1 506
webmaster@1 507 fwrite($fp, $request);
webmaster@1 508
webmaster@1 509 // Fetch response.
webmaster@1 510 $response = '';
webmaster@1 511 while (!feof($fp) && $chunk = fread($fp, 1024)) {
webmaster@1 512 $response .= $chunk;
webmaster@1 513 }
webmaster@1 514 fclose($fp);
webmaster@1 515
webmaster@1 516 // Parse response.
webmaster@1 517 list($split, $result->data) = explode("\r\n\r\n", $response, 2);
webmaster@1 518 $split = preg_split("/\r\n|\n|\r/", $split);
webmaster@1 519
webmaster@1 520 list($protocol, $code, $text) = explode(' ', trim(array_shift($split)), 3);
webmaster@1 521 $result->headers = array();
webmaster@1 522
webmaster@1 523 // Parse headers.
webmaster@1 524 while ($line = trim(array_shift($split))) {
webmaster@1 525 list($header, $value) = explode(':', $line, 2);
webmaster@1 526 if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
webmaster@1 527 // RFC 2109: the Set-Cookie response header comprises the token Set-
webmaster@1 528 // Cookie:, followed by a comma-separated list of one or more cookies.
webmaster@1 529 $result->headers[$header] .= ','. trim($value);
webmaster@1 530 }
webmaster@1 531 else {
webmaster@1 532 $result->headers[$header] = trim($value);
webmaster@1 533 }
webmaster@1 534 }
webmaster@1 535
webmaster@1 536 $responses = array(
webmaster@1 537 100 => 'Continue', 101 => 'Switching Protocols',
webmaster@1 538 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
webmaster@1 539 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
webmaster@1 540 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
webmaster@1 541 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
webmaster@1 542 );
webmaster@1 543 // RFC 2616 states that all unknown HTTP codes must be treated the same as the
webmaster@1 544 // base code in their class.
webmaster@1 545 if (!isset($responses[$code])) {
webmaster@1 546 $code = floor($code / 100) * 100;
webmaster@1 547 }
webmaster@1 548
webmaster@1 549 switch ($code) {
webmaster@1 550 case 200: // OK
webmaster@1 551 case 304: // Not modified
webmaster@1 552 break;
webmaster@1 553 case 301: // Moved permanently
webmaster@1 554 case 302: // Moved temporarily
webmaster@1 555 case 307: // Moved temporarily
webmaster@1 556 $location = $result->headers['Location'];
webmaster@1 557
webmaster@1 558 if ($retry) {
webmaster@1 559 $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
webmaster@1 560 $result->redirect_code = $result->code;
webmaster@1 561 }
webmaster@1 562 $result->redirect_url = $location;
webmaster@1 563
webmaster@1 564 break;
webmaster@1 565 default:
webmaster@1 566 $result->error = $text;
webmaster@1 567 }
webmaster@1 568
webmaster@1 569 $result->code = $code;
webmaster@1 570 return $result;
webmaster@1 571 }
webmaster@1 572 /**
webmaster@1 573 * @} End of "HTTP handling".
webmaster@1 574 */
webmaster@1 575
webmaster@1 576 /**
webmaster@1 577 * Log errors as defined by administrator.
webmaster@1 578 *
webmaster@1 579 * Error levels:
webmaster@1 580 * - 0 = Log errors to database.
webmaster@1 581 * - 1 = Log errors to database and to screen.
webmaster@1 582 */
webmaster@1 583 function drupal_error_handler($errno, $message, $filename, $line, $context) {
webmaster@7 584 // If the @ error suppression operator was used, error_reporting will have
webmaster@7 585 // been temporarily set to 0.
webmaster@1 586 if (error_reporting() == 0) {
webmaster@1 587 return;
webmaster@1 588 }
webmaster@1 589
webmaster@1 590 if ($errno & (E_ALL ^ E_NOTICE)) {
webmaster@1 591 $types = array(1 => 'error', 2 => 'warning', 4 => 'parse error', 8 => 'notice', 16 => 'core error', 32 => 'core warning', 64 => 'compile error', 128 => 'compile warning', 256 => 'user error', 512 => 'user warning', 1024 => 'user notice', 2048 => 'strict warning', 4096 => 'recoverable fatal error');
webmaster@1 592
webmaster@1 593 // For database errors, we want the line number/file name of the place that
webmaster@1 594 // the query was originally called, not _db_query().
webmaster@1 595 if (isset($context[DB_ERROR])) {
webmaster@1 596 $backtrace = array_reverse(debug_backtrace());
webmaster@1 597
webmaster@1 598 // List of functions where SQL queries can originate.
webmaster@1 599 $query_functions = array('db_query', 'pager_query', 'db_query_range', 'db_query_temporary', 'update_sql');
webmaster@1 600
webmaster@1 601 // Determine where query function was called, and adjust line/file
webmaster@1 602 // accordingly.
webmaster@1 603 foreach ($backtrace as $index => $function) {
webmaster@1 604 if (in_array($function['function'], $query_functions)) {
webmaster@1 605 $line = $backtrace[$index]['line'];
webmaster@1 606 $filename = $backtrace[$index]['file'];
webmaster@1 607 break;
webmaster@1 608 }
webmaster@1 609 }
webmaster@1 610 }
webmaster@1 611
webmaster@1 612 $entry = $types[$errno] .': '. $message .' in '. $filename .' on line '. $line .'.';
webmaster@1 613
webmaster@1 614 // Force display of error messages in update.php.
webmaster@1 615 if (variable_get('error_level', 1) == 1 || strstr($_SERVER['SCRIPT_NAME'], 'update.php')) {
webmaster@1 616 drupal_set_message($entry, 'error');
webmaster@1 617 }
webmaster@1 618
webmaster@1 619 watchdog('php', '%message in %file on line %line.', array('%error' => $types[$errno], '%message' => $message, '%file' => $filename, '%line' => $line), WATCHDOG_ERROR);
webmaster@1 620 }
webmaster@1 621 }
webmaster@1 622
webmaster@1 623 function _fix_gpc_magic(&$item) {
webmaster@1 624 if (is_array($item)) {
webmaster@1 625 array_walk($item, '_fix_gpc_magic');
webmaster@1 626 }
webmaster@1 627 else {
webmaster@1 628 $item = stripslashes($item);
webmaster@1 629 }
webmaster@1 630 }
webmaster@1 631
webmaster@1 632 /**
webmaster@1 633 * Helper function to strip slashes from $_FILES skipping over the tmp_name keys
webmaster@1 634 * since PHP generates single backslashes for file paths on Windows systems.
webmaster@1 635 *
webmaster@1 636 * tmp_name does not have backslashes added see
webmaster@1 637 * http://php.net/manual/en/features.file-upload.php#42280
webmaster@1 638 */
webmaster@1 639 function _fix_gpc_magic_files(&$item, $key) {
webmaster@1 640 if ($key != 'tmp_name') {
webmaster@1 641 if (is_array($item)) {
webmaster@1 642 array_walk($item, '_fix_gpc_magic_files');
webmaster@1 643 }
webmaster@1 644 else {
webmaster@1 645 $item = stripslashes($item);
webmaster@1 646 }
webmaster@1 647 }
webmaster@1 648 }
webmaster@1 649
webmaster@1 650 /**
webmaster@1 651 * Fix double-escaping problems caused by "magic quotes" in some PHP installations.
webmaster@1 652 */
webmaster@1 653 function fix_gpc_magic() {
webmaster@1 654 static $fixed = FALSE;
webmaster@1 655 if (!$fixed && ini_get('magic_quotes_gpc')) {
webmaster@1 656 array_walk($_GET, '_fix_gpc_magic');
webmaster@1 657 array_walk($_POST, '_fix_gpc_magic');
webmaster@1 658 array_walk($_COOKIE, '_fix_gpc_magic');
webmaster@1 659 array_walk($_REQUEST, '_fix_gpc_magic');
webmaster@1 660 array_walk($_FILES, '_fix_gpc_magic_files');
webmaster@1 661 $fixed = TRUE;
webmaster@1 662 }
webmaster@1 663 }
webmaster@1 664
webmaster@1 665 /**
webmaster@1 666 * Translate strings to the page language or a given language.
webmaster@1 667 *
webmaster@1 668 * All human-readable text that will be displayed somewhere within a page should
webmaster@1 669 * be run through the t() function.
webmaster@1 670 *
webmaster@1 671 * Examples:
webmaster@1 672 * @code
webmaster@1 673 * if (!$info || !$info['extension']) {
webmaster@1 674 * form_set_error('picture_upload', t('The uploaded file was not an image.'));
webmaster@1 675 * }
webmaster@1 676 *
webmaster@1 677 * $form['submit'] = array(
webmaster@1 678 * '#type' => 'submit',
webmaster@1 679 * '#value' => t('Log in'),
webmaster@1 680 * );
webmaster@1 681 * @endcode
webmaster@1 682 *
webmaster@1 683 * Any text within t() can be extracted by translators and changed into
webmaster@1 684 * the equivalent text in their native language.
webmaster@1 685 *
webmaster@1 686 * Special variables called "placeholders" are used to signal dynamic
webmaster@1 687 * information in a string which should not be translated. Placeholders
webmaster@1 688 * can also be used for text that may change from time to time
webmaster@1 689 * (such as link paths) to be changed without requiring updates to translations.
webmaster@1 690 *
webmaster@1 691 * For example:
webmaster@1 692 * @code
webmaster@1 693 * $output = t('There are currently %members and %visitors online.', array(
webmaster@1 694 * '%members' => format_plural($total_users, '1 user', '@count users'),
webmaster@1 695 * '%visitors' => format_plural($guests->count, '1 guest', '@count guests')));
webmaster@1 696 * @endcode
webmaster@1 697 *
webmaster@1 698 * There are three styles of placeholders:
webmaster@1 699 * - !variable, which indicates that the text should be inserted as-is. This is
webmaster@1 700 * useful for inserting variables into things like e-mail.
webmaster@1 701 * @code
webmaster@1 702 * $message[] = t("If you don't want to receive such e-mails, you can change your settings at !url.", array('!url' => url("user/$account->uid", array('absolute' => TRUE))));
webmaster@1 703 * @endcode
webmaster@1 704 *
webmaster@1 705 * - @variable, which indicates that the text should be run through check_plain,
webmaster@1 706 * to escape HTML characters. Use this for any output that's displayed within
webmaster@1 707 * a Drupal page.
webmaster@1 708 * @code
webmaster@1 709 * drupal_set_title($title = t("@name's blog", array('@name' => $account->name)));
webmaster@1 710 * @endcode
webmaster@1 711 *
webmaster@1 712 * - %variable, which indicates that the string should be HTML escaped and
webmaster@1 713 * highlighted with theme_placeholder() which shows up by default as
webmaster@1 714 * <em>emphasized</em>.
webmaster@1 715 * @code
webmaster@1 716 * $message = t('%name-from sent %name-to an e-mail.', array('%name-from' => $user->name, '%name-to' => $account->name));
webmaster@1 717 * @endcode
webmaster@1 718 *
webmaster@1 719 * When using t(), try to put entire sentences and strings in one t() call.
webmaster@1 720 * This makes it easier for translators, as it provides context as to what each
webmaster@1 721 * word refers to. HTML markup within translation strings is allowed, but should
webmaster@1 722 * be avoided if possible. The exception are embedded links; link titles add a
webmaster@1 723 * context for translators, so should be kept in the main string.
webmaster@1 724 *
webmaster@1 725 * Here is an example of incorrect usage of t():
webmaster@1 726 * @code
webmaster@1 727 * $output .= t('<p>Go to the @contact-page.</p>', array('@contact-page' => l(t('contact page'), 'contact')));
webmaster@1 728 * @endcode
webmaster@1 729 *
webmaster@1 730 * Here is an example of t() used correctly:
webmaster@1 731 * @code
webmaster@1 732 * $output .= '<p>'. t('Go to the <a href="@contact-page">contact page</a>.', array('@contact-page' => url('contact'))) .'</p>';
webmaster@1 733 * @endcode
webmaster@1 734 *
webmaster@1 735 * Also avoid escaping quotation marks wherever possible.
webmaster@1 736 *
webmaster@1 737 * Incorrect:
webmaster@1 738 * @code
webmaster@1 739 * $output .= t('Don\'t click me.');
webmaster@1 740 * @endcode
webmaster@1 741 *
webmaster@1 742 * Correct:
webmaster@1 743 * @code
webmaster@1 744 * $output .= t("Don't click me.");
webmaster@1 745 * @endcode
webmaster@1 746 *
webmaster@1 747 * @param $string
webmaster@1 748 * A string containing the English string to translate.
webmaster@1 749 * @param $args
webmaster@1 750 * An associative array of replacements to make after translation. Incidences
webmaster@1 751 * of any key in this array are replaced with the corresponding value.
webmaster@1 752 * Based on the first character of the key, the value is escaped and/or themed:
webmaster@1 753 * - !variable: inserted as is
webmaster@1 754 * - @variable: escape plain text to HTML (check_plain)
webmaster@1 755 * - %variable: escape text and theme as a placeholder for user-submitted
webmaster@1 756 * content (check_plain + theme_placeholder)
webmaster@1 757 * @param $langcode
webmaster@1 758 * Optional language code to translate to a language other than what is used
webmaster@1 759 * to display the page.
webmaster@1 760 * @return
webmaster@1 761 * The translated string.
webmaster@1 762 */
webmaster@1 763 function t($string, $args = array(), $langcode = NULL) {
webmaster@1 764 global $language;
webmaster@1 765 static $custom_strings;
webmaster@1 766
webmaster@1 767 $langcode = isset($langcode) ? $langcode : $language->language;
webmaster@1 768
webmaster@1 769 // First, check for an array of customized strings. If present, use the array
webmaster@1 770 // *instead of* database lookups. This is a high performance way to provide a
webmaster@1 771 // handful of string replacements. See settings.php for examples.
webmaster@1 772 // Cache the $custom_strings variable to improve performance.
webmaster@1 773 if (!isset($custom_strings[$langcode])) {
webmaster@1 774 $custom_strings[$langcode] = variable_get('locale_custom_strings_'. $langcode, array());
webmaster@1 775 }
webmaster@1 776 // Custom strings work for English too, even if locale module is disabled.
webmaster@1 777 if (isset($custom_strings[$langcode][$string])) {
webmaster@1 778 $string = $custom_strings[$langcode][$string];
webmaster@1 779 }
webmaster@1 780 // Translate with locale module if enabled.
webmaster@1 781 elseif (function_exists('locale') && $langcode != 'en') {
webmaster@1 782 $string = locale($string, $langcode);
webmaster@1 783 }
webmaster@1 784 if (empty($args)) {
webmaster@1 785 return $string;
webmaster@1 786 }
webmaster@1 787 else {
webmaster@1 788 // Transform arguments before inserting them.
webmaster@1 789 foreach ($args as $key => $value) {
webmaster@1 790 switch ($key[0]) {
webmaster@1 791 case '@':
webmaster@1 792 // Escaped only.
webmaster@1 793 $args[$key] = check_plain($value);
webmaster@1 794 break;
webmaster@1 795
webmaster@1 796 case '%':
webmaster@1 797 default:
webmaster@1 798 // Escaped and placeholder.
webmaster@1 799 $args[$key] = theme('placeholder', $value);
webmaster@1 800 break;
webmaster@1 801
webmaster@1 802 case '!':
webmaster@1 803 // Pass-through.
webmaster@1 804 }
webmaster@1 805 }
webmaster@1 806 return strtr($string, $args);
webmaster@1 807 }
webmaster@1 808 }
webmaster@1 809
webmaster@1 810 /**
webmaster@1 811 * @defgroup validation Input validation
webmaster@1 812 * @{
webmaster@1 813 * Functions to validate user input.
webmaster@1 814 */
webmaster@1 815
webmaster@1 816 /**
webmaster@1 817 * Verify the syntax of the given e-mail address.
webmaster@1 818 *
webmaster@1 819 * Empty e-mail addresses are allowed. See RFC 2822 for details.
webmaster@1 820 *
webmaster@1 821 * @param $mail
webmaster@1 822 * A string containing an e-mail address.
webmaster@1 823 * @return
webmaster@1 824 * TRUE if the address is in a valid format.
webmaster@1 825 */
webmaster@1 826 function valid_email_address($mail) {
webmaster@1 827 $user = '[a-zA-Z0-9_\-\.\+\^!#\$%&*+\/\=\?\`\|\{\}~\']+';
webmaster@1 828 $domain = '(?:(?:[a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.?)+';
webmaster@1 829 $ipv4 = '[0-9]{1,3}(\.[0-9]{1,3}){3}';
webmaster@1 830 $ipv6 = '[0-9a-fA-F]{1,4}(\:[0-9a-fA-F]{1,4}){7}';
webmaster@1 831
webmaster@1 832 return preg_match("/^$user@($domain|(\[($ipv4|$ipv6)\]))$/", $mail);
webmaster@1 833 }
webmaster@1 834
webmaster@1 835 /**
webmaster@1 836 * Verify the syntax of the given URL.
webmaster@1 837 *
webmaster@1 838 * This function should only be used on actual URLs. It should not be used for
webmaster@1 839 * Drupal menu paths, which can contain arbitrary characters.
webmaster@1 840 *
webmaster@1 841 * @param $url
webmaster@1 842 * The URL to verify.
webmaster@1 843 * @param $absolute
webmaster@1 844 * Whether the URL is absolute (beginning with a scheme such as "http:").
webmaster@1 845 * @return
webmaster@1 846 * TRUE if the URL is in a valid format.
webmaster@1 847 */
webmaster@1 848 function valid_url($url, $absolute = FALSE) {
webmaster@1 849 $allowed_characters = '[a-z0-9\/:_\-_\.\?\$,;~=#&%\+]';
webmaster@1 850 if ($absolute) {
webmaster@1 851 return preg_match("/^(http|https|ftp):\/\/". $allowed_characters ."+$/i", $url);
webmaster@1 852 }
webmaster@1 853 else {
webmaster@1 854 return preg_match("/^". $allowed_characters ."+$/i", $url);
webmaster@1 855 }
webmaster@1 856 }
webmaster@1 857
webmaster@1 858 /**
webmaster@1 859 * @} End of "defgroup validation".
webmaster@1 860 */
webmaster@1 861
webmaster@1 862 /**
webmaster@1 863 * Register an event for the current visitor (hostname/IP) to the flood control mechanism.
webmaster@1 864 *
webmaster@1 865 * @param $name
webmaster@1 866 * The name of an event.
webmaster@1 867 */
webmaster@1 868 function flood_register_event($name) {
webmaster@1 869 db_query("INSERT INTO {flood} (event, hostname, timestamp) VALUES ('%s', '%s', %d)", $name, ip_address(), time());
webmaster@1 870 }
webmaster@1 871
webmaster@1 872 /**
webmaster@1 873 * Check if the current visitor (hostname/IP) is allowed to proceed with the specified event.
webmaster@1 874 *
webmaster@1 875 * The user is allowed to proceed if he did not trigger the specified event more
webmaster@1 876 * than $threshold times per hour.
webmaster@1 877 *
webmaster@1 878 * @param $name
webmaster@1 879 * The name of the event.
webmaster@1 880 * @param $number
webmaster@1 881 * The maximum number of the specified event per hour (per visitor).
webmaster@1 882 * @return
webmaster@1 883 * True if the user did not exceed the hourly threshold. False otherwise.
webmaster@1 884 */
webmaster@1 885 function flood_is_allowed($name, $threshold) {
webmaster@1 886 $number = db_result(db_query("SELECT COUNT(*) FROM {flood} WHERE event = '%s' AND hostname = '%s' AND timestamp > %d", $name, ip_address(), time() - 3600));
webmaster@1 887 return ($number < $threshold ? TRUE : FALSE);
webmaster@1 888 }
webmaster@1 889
webmaster@1 890 function check_file($filename) {
webmaster@1 891 return is_uploaded_file($filename);
webmaster@1 892 }
webmaster@1 893
webmaster@1 894 /**
webmaster@1 895 * Prepare a URL for use in an HTML attribute. Strips harmful protocols.
webmaster@1 896 */
webmaster@1 897 function check_url($uri) {
webmaster@1 898 return filter_xss_bad_protocol($uri, FALSE);
webmaster@1 899 }
webmaster@1 900
webmaster@1 901 /**
webmaster@1 902 * @defgroup format Formatting
webmaster@1 903 * @{
webmaster@1 904 * Functions to format numbers, strings, dates, etc.
webmaster@1 905 */
webmaster@1 906
webmaster@1 907 /**
webmaster@1 908 * Formats an RSS channel.
webmaster@1 909 *
webmaster@1 910 * Arbitrary elements may be added using the $args associative array.
webmaster@1 911 */
webmaster@1 912 function format_rss_channel($title, $link, $description, $items, $langcode = NULL, $args = array()) {
webmaster@1 913 global $language;
webmaster@1 914 $langcode = $langcode ? $langcode : $language->language;
webmaster@1 915
webmaster@1 916 $output = "<channel>\n";
webmaster@1 917 $output .= ' <title>'. check_plain($title) ."</title>\n";
webmaster@1 918 $output .= ' <link>'. check_url($link) ."</link>\n";
webmaster@1 919
webmaster@1 920 // The RSS 2.0 "spec" doesn't indicate HTML can be used in the description.
webmaster@1 921 // We strip all HTML tags, but need to prevent double encoding from properly
webmaster@1 922 // escaped source data (such as &amp becoming &amp;amp;).
webmaster@1 923 $output .= ' <description>'. check_plain(decode_entities(strip_tags($description))) ."</description>\n";
webmaster@1 924 $output .= ' <language>'. check_plain($langcode) ."</language>\n";
webmaster@1 925 $output .= format_xml_elements($args);
webmaster@1 926 $output .= $items;
webmaster@1 927 $output .= "</channel>\n";
webmaster@1 928
webmaster@1 929 return $output;
webmaster@1 930 }
webmaster@1 931
webmaster@1 932 /**
webmaster@1 933 * Format a single RSS item.
webmaster@1 934 *
webmaster@1 935 * Arbitrary elements may be added using the $args associative array.
webmaster@1 936 */
webmaster@1 937 function format_rss_item($title, $link, $description, $args = array()) {
webmaster@1 938 $output = "<item>\n";
webmaster@1 939 $output .= ' <title>'. check_plain($title) ."</title>\n";
webmaster@1 940 $output .= ' <link>'. check_url($link) ."</link>\n";
webmaster@1 941 $output .= ' <description>'. check_plain($description) ."</description>\n";
webmaster@1 942 $output .= format_xml_elements($args);
webmaster@1 943 $output .= "</item>\n";
webmaster@1 944
webmaster@1 945 return $output;
webmaster@1 946 }
webmaster@1 947
webmaster@1 948 /**
webmaster@1 949 * Format XML elements.
webmaster@1 950 *
webmaster@1 951 * @param $array
webmaster@1 952 * An array where each item represent an element and is either a:
webmaster@1 953 * - (key => value) pair (<key>value</key>)
webmaster@1 954 * - Associative array with fields:
webmaster@1 955 * - 'key': element name
webmaster@1 956 * - 'value': element contents
webmaster@1 957 * - 'attributes': associative array of element attributes
webmaster@1 958 *
webmaster@1 959 * In both cases, 'value' can be a simple string, or it can be another array
webmaster@1 960 * with the same format as $array itself for nesting.
webmaster@1 961 */
webmaster@1 962 function format_xml_elements($array) {
webmaster@1 963 $output = '';
webmaster@1 964 foreach ($array as $key => $value) {
webmaster@1 965 if (is_numeric($key)) {
webmaster@1 966 if ($value['key']) {
webmaster@1 967 $output .= ' <'. $value['key'];
webmaster@1 968 if (isset($value['attributes']) && is_array($value['attributes'])) {
webmaster@1 969 $output .= drupal_attributes($value['attributes']);
webmaster@1 970 }
webmaster@1 971
webmaster@1 972 if ($value['value'] != '') {
webmaster@1 973 $output .= '>'. (is_array($value['value']) ? format_xml_elements($value['value']) : check_plain($value['value'])) .'</'. $value['key'] .">\n";
webmaster@1 974 }
webmaster@1 975 else {
webmaster@1 976 $output .= " />\n";
webmaster@1 977 }
webmaster@1 978 }
webmaster@1 979 }
webmaster@1 980 else {
webmaster@1 981 $output .= ' <'. $key .'>'. (is_array($value) ? format_xml_elements($value) : check_plain($value)) ."</$key>\n";
webmaster@1 982 }
webmaster@1 983 }
webmaster@1 984 return $output;
webmaster@1 985 }
webmaster@1 986
webmaster@1 987 /**
webmaster@1 988 * Format a string containing a count of items.
webmaster@1 989 *
webmaster@1 990 * This function ensures that the string is pluralized correctly. Since t() is
webmaster@1 991 * called by this function, make sure not to pass already-localized strings to
webmaster@1 992 * it.
webmaster@1 993 *
webmaster@1 994 * For example:
webmaster@1 995 * @code
webmaster@1 996 * $output = format_plural($node->comment_count, '1 comment', '@count comments');
webmaster@1 997 * @endcode
webmaster@1 998 *
webmaster@1 999 * Example with additional replacements:
webmaster@1 1000 * @code
webmaster@1 1001 * $output = format_plural($update_count,
webmaster@1 1002 * 'Changed the content type of 1 post from %old-type to %new-type.',
webmaster@1 1003 * 'Changed the content type of @count posts from %old-type to %new-type.',
webmaster@1 1004 * array('%old-type' => $info->old_type, '%new-type' => $info->new_type)));
webmaster@1 1005 * @endcode
webmaster@1 1006 *
webmaster@1 1007 * @param $count
webmaster@1 1008 * The item count to display.
webmaster@1 1009 * @param $singular
webmaster@1 1010 * The string for the singular case. Please make sure it is clear this is
webmaster@1 1011 * singular, to ease translation (e.g. use "1 new comment" instead of "1 new").
webmaster@1 1012 * Do not use @count in the singular string.
webmaster@1 1013 * @param $plural
webmaster@1 1014 * The string for the plural case. Please make sure it is clear this is plural,
webmaster@1 1015 * to ease translation. Use @count in place of the item count, as in "@count
webmaster@1 1016 * new comments".
webmaster@1 1017 * @param $args
webmaster@1 1018 * An associative array of replacements to make after translation. Incidences
webmaster@1 1019 * of any key in this array are replaced with the corresponding value.
webmaster@1 1020 * Based on the first character of the key, the value is escaped and/or themed:
webmaster@1 1021 * - !variable: inserted as is
webmaster@1 1022 * - @variable: escape plain text to HTML (check_plain)
webmaster@1 1023 * - %variable: escape text and theme as a placeholder for user-submitted
webmaster@1 1024 * content (check_plain + theme_placeholder)
webmaster@1 1025 * Note that you do not need to include @count in this array.
webmaster@1 1026 * This replacement is done automatically for the plural case.
webmaster@1 1027 * @param $langcode
webmaster@1 1028 * Optional language code to translate to a language other than
webmaster@1 1029 * what is used to display the page.
webmaster@1 1030 * @return
webmaster@1 1031 * A translated string.
webmaster@1 1032 */
webmaster@1 1033 function format_plural($count, $singular, $plural, $args = array(), $langcode = NULL) {
webmaster@1 1034 $args['@count'] = $count;
webmaster@1 1035 if ($count == 1) {
webmaster@1 1036 return t($singular, $args, $langcode);
webmaster@1 1037 }
webmaster@1 1038
webmaster@1 1039 // Get the plural index through the gettext formula.
webmaster@1 1040 $index = (function_exists('locale_get_plural')) ? locale_get_plural($count, $langcode) : -1;
webmaster@1 1041 // Backwards compatibility.
webmaster@1 1042 if ($index < 0) {
webmaster@1 1043 return t($plural, $args, $langcode);
webmaster@1 1044 }
webmaster@1 1045 else {
webmaster@1 1046 switch ($index) {
webmaster@1 1047 case "0":
webmaster@1 1048 return t($singular, $args, $langcode);
webmaster@1 1049 case "1":
webmaster@1 1050 return t($plural, $args, $langcode);
webmaster@1 1051 default:
webmaster@1 1052 unset($args['@count']);
webmaster@1 1053 $args['@count['. $index .']'] = $count;
webmaster@1 1054 return t(strtr($plural, array('@count' => '@count['. $index .']')), $args, $langcode);
webmaster@1 1055 }
webmaster@1 1056 }
webmaster@1 1057 }
webmaster@1 1058
webmaster@1 1059 /**
webmaster@1 1060 * Parse a given byte count.
webmaster@1 1061 *
webmaster@1 1062 * @param $size
webmaster@1 1063 * A size expressed as a number of bytes with optional SI size and unit
webmaster@1 1064 * suffix (e.g. 2, 3K, 5MB, 10G).
webmaster@1 1065 * @return
webmaster@1 1066 * An integer representation of the size.
webmaster@1 1067 */
webmaster@1 1068 function parse_size($size) {
webmaster@1 1069 $suffixes = array(
webmaster@1 1070 '' => 1,
webmaster@1 1071 'k' => 1024,
webmaster@1 1072 'm' => 1048576, // 1024 * 1024
webmaster@1 1073 'g' => 1073741824, // 1024 * 1024 * 1024
webmaster@1 1074 );
webmaster@1 1075 if (preg_match('/([0-9]+)\s*(k|m|g)?(b?(ytes?)?)/i', $size, $match)) {
webmaster@1 1076 return $match[1] * $suffixes[drupal_strtolower($match[2])];
webmaster@1 1077 }
webmaster@1 1078 }
webmaster@1 1079
webmaster@1 1080 /**
webmaster@1 1081 * Generate a string representation for the given byte count.
webmaster@1 1082 *
webmaster@1 1083 * @param $size
webmaster@1 1084 * A size in bytes.
webmaster@1 1085 * @param $langcode
webmaster@1 1086 * Optional language code to translate to a language other than what is used
webmaster@1 1087 * to display the page.
webmaster@1 1088 * @return
webmaster@1 1089 * A translated string representation of the size.
webmaster@1 1090 */
webmaster@1 1091 function format_size($size, $langcode = NULL) {
webmaster@1 1092 if ($size < 1024) {
webmaster@1 1093 return format_plural($size, '1 byte', '@count bytes', array(), $langcode);
webmaster@1 1094 }
webmaster@1 1095 else {
webmaster@1 1096 $size = round($size / 1024, 2);
webmaster@1 1097 $suffix = t('KB', array(), $langcode);
webmaster@1 1098 if ($size >= 1024) {
webmaster@1 1099 $size = round($size / 1024, 2);
webmaster@1 1100 $suffix = t('MB', array(), $langcode);
webmaster@1 1101 }
webmaster@1 1102 return t('@size @suffix', array('@size' => $size, '@suffix' => $suffix), $langcode);
webmaster@1 1103 }
webmaster@1 1104 }
webmaster@1 1105
webmaster@1 1106 /**
webmaster@1 1107 * Format a time interval with the requested granularity.
webmaster@1 1108 *
webmaster@1 1109 * @param $timestamp
webmaster@1 1110 * The length of the interval in seconds.
webmaster@1 1111 * @param $granularity
webmaster@1 1112 * How many different units to display in the string.
webmaster@1 1113 * @param $langcode
webmaster@1 1114 * Optional language code to translate to a language other than
webmaster@1 1115 * what is used to display the page.
webmaster@1 1116 * @return
webmaster@1 1117 * A translated string representation of the interval.
webmaster@1 1118 */
webmaster@1 1119 function format_interval($timestamp, $granularity = 2, $langcode = NULL) {
webmaster@1 1120 $units = array('1 year|@count years' => 31536000, '1 week|@count weeks' => 604800, '1 day|@count days' => 86400, '1 hour|@count hours' => 3600, '1 min|@count min' => 60, '1 sec|@count sec' => 1);
webmaster@1 1121 $output = '';
webmaster@1 1122 foreach ($units as $key => $value) {
webmaster@1 1123 $key = explode('|', $key);
webmaster@1 1124 if ($timestamp >= $value) {
webmaster@1 1125 $output .= ($output ? ' ' : '') . format_plural(floor($timestamp / $value), $key[0], $key[1], array(), $langcode);
webmaster@1 1126 $timestamp %= $value;
webmaster@1 1127 $granularity--;
webmaster@1 1128 }
webmaster@1 1129
webmaster@1 1130 if ($granularity == 0) {
webmaster@1 1131 break;
webmaster@1 1132 }
webmaster@1 1133 }
webmaster@1 1134 return $output ? $output : t('0 sec', array(), $langcode);
webmaster@1 1135 }
webmaster@1 1136
webmaster@1 1137 /**
webmaster@1 1138 * Format a date with the given configured format or a custom format string.
webmaster@1 1139 *
webmaster@1 1140 * Drupal allows administrators to select formatting strings for 'small',
webmaster@1 1141 * 'medium' and 'large' date formats. This function can handle these formats,
webmaster@1 1142 * as well as any custom format.
webmaster@1 1143 *
webmaster@1 1144 * @param $timestamp
webmaster@1 1145 * The exact date to format, as a UNIX timestamp.
webmaster@1 1146 * @param $type
webmaster@1 1147 * The format to use. Can be "small", "medium" or "large" for the preconfigured
webmaster@1 1148 * date formats. If "custom" is specified, then $format is required as well.
webmaster@1 1149 * @param $format
webmaster@1 1150 * A PHP date format string as required by date(). A backslash should be used
webmaster@1 1151 * before a character to avoid interpreting the character as part of a date
webmaster@1 1152 * format.
webmaster@1 1153 * @param $timezone
webmaster@1 1154 * Time zone offset in seconds; if omitted, the user's time zone is used.
webmaster@1 1155 * @param $langcode
webmaster@1 1156 * Optional language code to translate to a language other than what is used
webmaster@1 1157 * to display the page.
webmaster@1 1158 * @return
webmaster@1 1159 * A translated date string in the requested format.
webmaster@1 1160 */
webmaster@1 1161 function format_date($timestamp, $type = 'medium', $format = '', $timezone = NULL, $langcode = NULL) {
webmaster@1 1162 if (!isset($timezone)) {
webmaster@1 1163 global $user;
webmaster@1 1164 if (variable_get('configurable_timezones', 1) && $user->uid && strlen($user->timezone)) {
webmaster@1 1165 $timezone = $user->timezone;
webmaster@1 1166 }
webmaster@1 1167 else {
webmaster@1 1168 $timezone = variable_get('date_default_timezone', 0);
webmaster@1 1169 }
webmaster@1 1170 }
webmaster@1 1171
webmaster@1 1172 $timestamp += $timezone;
webmaster@1 1173
webmaster@1 1174 switch ($type) {
webmaster@1 1175 case 'small':
webmaster@1 1176 $format = variable_get('date_format_short', 'm/d/Y - H:i');
webmaster@1 1177 break;
webmaster@1 1178 case 'large':
webmaster@1 1179 $format = variable_get('date_format_long', 'l, F j, Y - H:i');
webmaster@1 1180 break;
webmaster@1 1181 case 'custom':
webmaster@1 1182 // No change to format.
webmaster@1 1183 break;
webmaster@1 1184 case 'medium':
webmaster@1 1185 default:
webmaster@1 1186 $format = variable_get('date_format_medium', 'D, m/d/Y - H:i');
webmaster@1 1187 }
webmaster@1 1188
webmaster@1 1189 $max = strlen($format);
webmaster@1 1190 $date = '';
webmaster@1 1191 for ($i = 0; $i < $max; $i++) {
webmaster@1 1192 $c = $format[$i];
webmaster@1 1193 if (strpos('AaDlM', $c) !== FALSE) {
webmaster@1 1194 $date .= t(gmdate($c, $timestamp), array(), $langcode);
webmaster@1 1195 }
webmaster@1 1196 else if ($c == 'F') {
webmaster@1 1197 // Special treatment for long month names: May is both an abbreviation
webmaster@1 1198 // and a full month name in English, but other languages have
webmaster@1 1199 // different abbreviations.
webmaster@1 1200 $date .= trim(t('!long-month-name '. gmdate($c, $timestamp), array('!long-month-name' => ''), $langcode));
webmaster@1 1201 }
webmaster@1 1202 else if (strpos('BdgGhHiIjLmnsStTUwWYyz', $c) !== FALSE) {
webmaster@1 1203 $date .= gmdate($c, $timestamp);
webmaster@1 1204 }
webmaster@1 1205 else if ($c == 'r') {
webmaster@1 1206 $date .= format_date($timestamp - $timezone, 'custom', 'D, d M Y H:i:s O', $timezone, $langcode);
webmaster@1 1207 }
webmaster@1 1208 else if ($c == 'O') {
webmaster@1 1209 $date .= sprintf('%s%02d%02d', ($timezone < 0 ? '-' : '+'), abs($timezone / 3600), abs($timezone % 3600) / 60);
webmaster@1 1210 }
webmaster@1 1211 else if ($c == 'Z') {
webmaster@1 1212 $date .= $timezone;
webmaster@1 1213 }
webmaster@1 1214 else if ($c == '\\') {
webmaster@1 1215 $date .= $format[++$i];
webmaster@1 1216 }
webmaster@1 1217 else {
webmaster@1 1218 $date .= $c;
webmaster@1 1219 }
webmaster@1 1220 }
webmaster@1 1221
webmaster@1 1222 return $date;
webmaster@1 1223 }
webmaster@1 1224
webmaster@1 1225 /**
webmaster@1 1226 * @} End of "defgroup format".
webmaster@1 1227 */
webmaster@1 1228
webmaster@1 1229 /**
webmaster@1 1230 * Generate a URL from a Drupal menu path. Will also pass-through existing URLs.
webmaster@1 1231 *
webmaster@1 1232 * @param $path
webmaster@1 1233 * The Drupal path being linked to, such as "admin/content/node", or an
webmaster@1 1234 * existing URL like "http://drupal.org/". The special path
webmaster@1 1235 * '<front>' may also be given and will generate the site's base URL.
webmaster@1 1236 * @param $options
webmaster@1 1237 * An associative array of additional options, with the following keys:
webmaster@7 1238 * - 'query'
webmaster@1 1239 * A query string to append to the link, or an array of query key/value
webmaster@1 1240 * properties.
webmaster@7 1241 * - 'fragment'
webmaster@1 1242 * A fragment identifier (or named anchor) to append to the link.
webmaster@1 1243 * Do not include the '#' character.
webmaster@7 1244 * - 'absolute' (default FALSE)
webmaster@1 1245 * Whether to force the output to be an absolute link (beginning with
webmaster@1 1246 * http:). Useful for links that will be displayed outside the site, such
webmaster@1 1247 * as in an RSS feed.
webmaster@7 1248 * - 'alias' (default FALSE)
webmaster@1 1249 * Whether the given path is an alias already.
webmaster@7 1250 * - 'external'
webmaster@1 1251 * Whether the given path is an external URL.
webmaster@7 1252 * - 'language'
webmaster@1 1253 * An optional language object. Used to build the URL to link to and
webmaster@1 1254 * look up the proper alias for the link.
webmaster@7 1255 * - 'base_url'
webmaster@1 1256 * Only used internally, to modify the base URL when a language dependent
webmaster@1 1257 * URL requires so.
webmaster@7 1258 * - 'prefix'
webmaster@1 1259 * Only used internally, to modify the path when a language dependent URL
webmaster@1 1260 * requires so.
webmaster@1 1261 * @return
webmaster@1 1262 * A string containing a URL to the given path.
webmaster@1 1263 *
webmaster@1 1264 * When creating links in modules, consider whether l() could be a better
webmaster@1 1265 * alternative than url().
webmaster@1 1266 */
webmaster@1 1267 function url($path = NULL, $options = array()) {
webmaster@1 1268 // Merge in defaults.
webmaster@1 1269 $options += array(
webmaster@1 1270 'fragment' => '',
webmaster@1 1271 'query' => '',
webmaster@1 1272 'absolute' => FALSE,
webmaster@1 1273 'alias' => FALSE,
webmaster@1 1274 'prefix' => ''
webmaster@1 1275 );
webmaster@1 1276 if (!isset($options['external'])) {
webmaster@1 1277 // Return an external link if $path contains an allowed absolute URL.
webmaster@1 1278 // Only call the slow filter_xss_bad_protocol if $path contains a ':' before
webmaster@1 1279 // any / ? or #.
webmaster@1 1280 $colonpos = strpos($path, ':');
webmaster@1 1281 $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && filter_xss_bad_protocol($path, FALSE) == check_plain($path));
webmaster@1 1282 }
webmaster@1 1283
webmaster@1 1284 // May need language dependent rewriting if language.inc is present.
webmaster@1 1285 if (function_exists('language_url_rewrite')) {
webmaster@1 1286 language_url_rewrite($path, $options);
webmaster@1 1287 }
webmaster@1 1288 if ($options['fragment']) {
webmaster@1 1289 $options['fragment'] = '#'. $options['fragment'];
webmaster@1 1290 }
webmaster@1 1291 if (is_array($options['query'])) {
webmaster@1 1292 $options['query'] = drupal_query_string_encode($options['query']);
webmaster@1 1293 }
webmaster@1 1294
webmaster@1 1295 if ($options['external']) {
webmaster@1 1296 // Split off the fragment.
webmaster@1 1297 if (strpos($path, '#') !== FALSE) {
webmaster@1 1298 list($path, $old_fragment) = explode('#', $path, 2);
webmaster@1 1299 if (isset($old_fragment) && !$options['fragment']) {
webmaster@1 1300 $options['fragment'] = '#'. $old_fragment;
webmaster@1 1301 }
webmaster@1 1302 }
webmaster@1 1303 // Append the query.
webmaster@1 1304 if ($options['query']) {
webmaster@1 1305 $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . $options['query'];
webmaster@1 1306 }
webmaster@1 1307 // Reassemble.
webmaster@1 1308 return $path . $options['fragment'];
webmaster@1 1309 }
webmaster@1 1310
webmaster@1 1311 global $base_url;
webmaster@1 1312 static $script;
webmaster@1 1313 static $clean_url;
webmaster@1 1314
webmaster@1 1315 if (!isset($script)) {
webmaster@1 1316 // On some web servers, such as IIS, we can't omit "index.php". So, we
webmaster@1 1317 // generate "index.php?q=foo" instead of "?q=foo" on anything that is not
webmaster@1 1318 // Apache.
webmaster@1 1319 $script = (strpos($_SERVER['SERVER_SOFTWARE'], 'Apache') === FALSE) ? 'index.php' : '';
webmaster@1 1320 }
webmaster@1 1321
webmaster@1 1322 // Cache the clean_url variable to improve performance.
webmaster@1 1323 if (!isset($clean_url)) {
webmaster@1 1324 $clean_url = (bool)variable_get('clean_url', '0');
webmaster@1 1325 }
webmaster@1 1326
webmaster@1 1327 if (!isset($options['base_url'])) {
webmaster@1 1328 // The base_url might be rewritten from the language rewrite in domain mode.
webmaster@1 1329 $options['base_url'] = $base_url;
webmaster@1 1330 }
webmaster@1 1331
webmaster@1 1332 // Preserve the original path before aliasing.
webmaster@1 1333 $original_path = $path;
webmaster@1 1334
webmaster@1 1335 // The special path '<front>' links to the default front page.
webmaster@1 1336 if ($path == '<front>') {
webmaster@1 1337 $path = '';
webmaster@1 1338 }
webmaster@1 1339 elseif (!empty($path) && !$options['alias']) {
webmaster@1 1340 $path = drupal_get_path_alias($path, isset($options['language']) ? $options['language']->language : '');
webmaster@1 1341 }
webmaster@1 1342
webmaster@1 1343 if (function_exists('custom_url_rewrite_outbound')) {
webmaster@1 1344 // Modules may alter outbound links by reference.
webmaster@1 1345 custom_url_rewrite_outbound($path, $options, $original_path);
webmaster@1 1346 }
webmaster@1 1347
webmaster@1 1348 $base = $options['absolute'] ? $options['base_url'] .'/' : base_path();
webmaster@1 1349 $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
webmaster@1 1350 $path = drupal_urlencode($prefix . $path);
webmaster@1 1351
webmaster@1 1352 if ($clean_url) {
webmaster@1 1353 // With Clean URLs.
webmaster@1 1354 if ($options['query']) {
webmaster@1 1355 return $base . $path .'?'. $options['query'] . $options['fragment'];
webmaster@1 1356 }
webmaster@1 1357 else {
webmaster@1 1358 return $base . $path . $options['fragment'];
webmaster@1 1359 }
webmaster@1 1360 }
webmaster@1 1361 else {
webmaster@1 1362 // Without Clean URLs.
webmaster@1 1363 $variables = array();
webmaster@1 1364 if (!empty($path)) {
webmaster@1 1365 $variables[] = 'q='. $path;
webmaster@1 1366 }
webmaster@1 1367 if (!empty($options['query'])) {
webmaster@1 1368 $variables[] = $options['query'];
webmaster@1 1369 }
webmaster@1 1370 if ($query = join('&', $variables)) {
webmaster@1 1371 return $base . $script .'?'. $query . $options['fragment'];
webmaster@1 1372 }
webmaster@1 1373 else {
webmaster@1 1374 return $base . $options['fragment'];
webmaster@1 1375 }
webmaster@1 1376 }
webmaster@1 1377 }
webmaster@1 1378
webmaster@1 1379 /**
webmaster@1 1380 * Format an attribute string to insert in a tag.
webmaster@1 1381 *
webmaster@1 1382 * @param $attributes
webmaster@1 1383 * An associative array of HTML attributes.
webmaster@1 1384 * @return
webmaster@1 1385 * An HTML string ready for insertion in a tag.
webmaster@1 1386 */
webmaster@1 1387 function drupal_attributes($attributes = array()) {
webmaster@1 1388 if (is_array($attributes)) {
webmaster@1 1389 $t = '';
webmaster@1 1390 foreach ($attributes as $key => $value) {
webmaster@1 1391 $t .= " $key=".'"'. check_plain($value) .'"';
webmaster@1 1392 }
webmaster@1 1393 return $t;
webmaster@1 1394 }
webmaster@1 1395 }
webmaster@1 1396
webmaster@1 1397 /**
webmaster@1 1398 * Format an internal Drupal link.
webmaster@1 1399 *
webmaster@1 1400 * This function correctly handles aliased paths, and allows themes to highlight
webmaster@1 1401 * links to the current page correctly, so all internal links output by modules
webmaster@1 1402 * should be generated by this function if possible.
webmaster@1 1403 *
webmaster@1 1404 * @param $text
webmaster@1 1405 * The text to be enclosed with the anchor tag.
webmaster@1 1406 * @param $path
webmaster@1 1407 * The Drupal path being linked to, such as "admin/content/node". Can be an
webmaster@1 1408 * external or internal URL.
webmaster@1 1409 * - If you provide the full URL, it will be considered an external URL.
webmaster@1 1410 * - If you provide only the path (e.g. "admin/content/node"), it is
webmaster@1 1411 * considered an internal link. In this case, it must be a system URL
webmaster@1 1412 * as the url() function will generate the alias.
webmaster@1 1413 * - If you provide '<front>', it generates a link to the site's
webmaster@1 1414 * base URL (again via the url() function).
webmaster@1 1415 * - If you provide a path, and 'alias' is set to TRUE (see below), it is
webmaster@1 1416 * used as is.
webmaster@1 1417 * @param $options
webmaster@1 1418 * An associative array of additional options, with the following keys:
webmaster@7 1419 * - 'attributes'
webmaster@1 1420 * An associative array of HTML attributes to apply to the anchor tag.
webmaster@7 1421 * - 'query'
webmaster@1 1422 * A query string to append to the link, or an array of query key/value
webmaster@1 1423 * properties.
webmaster@7 1424 * - 'fragment'
webmaster@1 1425 * A fragment identifier (named anchor) to append to the link.
webmaster@1 1426 * Do not include the '#' character.
webmaster@7 1427 * - 'absolute' (default FALSE)
webmaster@1 1428 * Whether to force the output to be an absolute link (beginning with
webmaster@1 1429 * http:). Useful for links that will be displayed outside the site, such
webmaster@1 1430 * as in an RSS feed.
webmaster@7 1431 * - 'html' (default FALSE)
webmaster@1 1432 * Whether the title is HTML, or just plain-text. For example for making
webmaster@1 1433 * an image a link, this must be set to TRUE, or else you will see the
webmaster@1 1434 * escaped HTML.
webmaster@7 1435 * - 'alias' (default FALSE)
webmaster@1 1436 * Whether the given path is an alias already.
webmaster@1 1437 * @return
webmaster@1 1438 * an HTML string containing a link to the given path.
webmaster@1 1439 */
webmaster@1 1440 function l($text, $path, $options = array()) {
webmaster@1 1441 // Merge in defaults.
webmaster@1 1442 $options += array(
webmaster@1 1443 'attributes' => array(),
webmaster@1 1444 'html' => FALSE,
webmaster@1 1445 );
webmaster@1 1446
webmaster@1 1447 // Append active class.
webmaster@1 1448 if ($path == $_GET['q'] || ($path == '<front>' && drupal_is_front_page())) {
webmaster@1 1449 if (isset($options['attributes']['class'])) {
webmaster@1 1450 $options['attributes']['class'] .= ' active';
webmaster@1 1451 }
webmaster@1 1452 else {
webmaster@1 1453 $options['attributes']['class'] = 'active';
webmaster@1 1454 }
webmaster@1 1455 }
webmaster@1 1456
webmaster@1 1457 // Remove all HTML and PHP tags from a tooltip. For best performance, we act only
webmaster@1 1458 // if a quick strpos() pre-check gave a suspicion (because strip_tags() is expensive).
webmaster@1 1459 if (isset($options['attributes']['title']) && strpos($options['attributes']['title'], '<') !== FALSE) {
webmaster@1 1460 $options['attributes']['title'] = strip_tags($options['attributes']['title']);
webmaster@1 1461 }
webmaster@1 1462
webmaster@1 1463 return '<a href="'. check_url(url($path, $options)) .'"'. drupal_attributes($options['attributes']) .'>'. ($options['html'] ? $text : check_plain($text)) .'</a>';
webmaster@1 1464 }
webmaster@1 1465
webmaster@1 1466 /**
webmaster@1 1467 * Perform end-of-request tasks.
webmaster@1 1468 *
webmaster@1 1469 * This function sets the page cache if appropriate, and allows modules to
webmaster@1 1470 * react to the closing of the page by calling hook_exit().
webmaster@1 1471 */
webmaster@1 1472 function drupal_page_footer() {
webmaster@1 1473 if (variable_get('cache', CACHE_DISABLED) != CACHE_DISABLED) {
webmaster@1 1474 page_set_cache();
webmaster@1 1475 }
webmaster@1 1476
webmaster@1 1477 module_invoke_all('exit');
webmaster@1 1478 }
webmaster@1 1479
webmaster@1 1480 /**
webmaster@1 1481 * Form an associative array from a linear array.
webmaster@1 1482 *
webmaster@1 1483 * This function walks through the provided array and constructs an associative
webmaster@1 1484 * array out of it. The keys of the resulting array will be the values of the
webmaster@1 1485 * input array. The values will be the same as the keys unless a function is
webmaster@1 1486 * specified, in which case the output of the function is used for the values
webmaster@1 1487 * instead.
webmaster@1 1488 *
webmaster@1 1489 * @param $array
webmaster@1 1490 * A linear array.
webmaster@1 1491 * @param $function
webmaster@1 1492 * A name of a function to apply to all values before output.
webmaster@1 1493 * @result
webmaster@1 1494 * An associative array.
webmaster@1 1495 */
webmaster@1 1496 function drupal_map_assoc($array, $function = NULL) {
webmaster@1 1497 if (!isset($function)) {
webmaster@1 1498 $result = array();
webmaster@1 1499 foreach ($array as $value) {
webmaster@1 1500 $result[$value] = $value;
webmaster@1 1501 }
webmaster@1 1502 return $result;
webmaster@1 1503 }
webmaster@1 1504 elseif (function_exists($function)) {
webmaster@1 1505 $result = array();
webmaster@1 1506 foreach ($array as $value) {
webmaster@1 1507 $result[$value] = $function($value);
webmaster@1 1508 }
webmaster@1 1509 return $result;
webmaster@1 1510 }
webmaster@1 1511 }
webmaster@1 1512
webmaster@1 1513 /**
webmaster@1 1514 * Evaluate a string of PHP code.
webmaster@1 1515 *
webmaster@1 1516 * This is a wrapper around PHP's eval(). It uses output buffering to capture both
webmaster@1 1517 * returned and printed text. Unlike eval(), we require code to be surrounded by
webmaster@1 1518 * <?php ?> tags; in other words, we evaluate the code as if it were a stand-alone
webmaster@1 1519 * PHP file.
webmaster@1 1520 *
webmaster@1 1521 * Using this wrapper also ensures that the PHP code which is evaluated can not
webmaster@1 1522 * overwrite any variables in the calling code, unlike a regular eval() call.
webmaster@1 1523 *
webmaster@1 1524 * @param $code
webmaster@1 1525 * The code to evaluate.
webmaster@1 1526 * @return
webmaster@1 1527 * A string containing the printed output of the code, followed by the returned
webmaster@1 1528 * output of the code.
webmaster@1 1529 */
webmaster@1 1530 function drupal_eval($code) {
webmaster@1 1531 global $theme_path, $theme_info, $conf;
webmaster@1 1532
webmaster@1 1533 // Store current theme path.
webmaster@1 1534 $old_theme_path = $theme_path;
webmaster@1 1535
webmaster@1 1536 // Restore theme_path to the theme, as long as drupal_eval() executes,
webmaster@1 1537 // so code evaluted will not see the caller module as the current theme.
webmaster@1 1538 // If theme info is not initialized get the path from theme_default.
webmaster@1 1539 if (!isset($theme_info)) {
webmaster@1 1540 $theme_path = drupal_get_path('theme', $conf['theme_default']);
webmaster@1 1541 }
webmaster@1 1542 else {
webmaster@1 1543 $theme_path = dirname($theme_info->filename);
webmaster@1 1544 }
webmaster@1 1545
webmaster@1 1546 ob_start();
webmaster@1 1547 print eval('?>'. $code);
webmaster@1 1548 $output = ob_get_contents();
webmaster@1 1549 ob_end_clean();
webmaster@1 1550
webmaster@1 1551 // Recover original theme path.
webmaster@1 1552 $theme_path = $old_theme_path;
webmaster@1 1553
webmaster@1 1554 return $output;
webmaster@1 1555 }
webmaster@1 1556
webmaster@1 1557 /**
webmaster@1 1558 * Returns the path to a system item (module, theme, etc.).
webmaster@1 1559 *
webmaster@1 1560 * @param $type
webmaster@1 1561 * The type of the item (i.e. theme, theme_engine, module).
webmaster@1 1562 * @param $name
webmaster@1 1563 * The name of the item for which the path is requested.
webmaster@1 1564 *
webmaster@1 1565 * @return
webmaster@1 1566 * The path to the requested item.
webmaster@1 1567 */
webmaster@1 1568 function drupal_get_path($type, $name) {
webmaster@1 1569 return dirname(drupal_get_filename($type, $name));
webmaster@1 1570 }
webmaster@1 1571
webmaster@1 1572 /**
webmaster@1 1573 * Returns the base URL path of the Drupal installation.
webmaster@1 1574 * At the very least, this will always default to /.
webmaster@1 1575 */
webmaster@1 1576 function base_path() {
webmaster@1 1577 return $GLOBALS['base_path'];
webmaster@1 1578 }
webmaster@1 1579
webmaster@1 1580 /**
webmaster@1 1581 * Provide a substitute clone() function for PHP4.
webmaster@1 1582 */
webmaster@1 1583 function drupal_clone($object) {
webmaster@1 1584 return version_compare(phpversion(), '5.0') < 0 ? $object : clone($object);
webmaster@1 1585 }
webmaster@1 1586
webmaster@1 1587 /**
webmaster@1 1588 * Add a <link> tag to the page's HEAD.
webmaster@1 1589 */
webmaster@1 1590 function drupal_add_link($attributes) {
webmaster@1 1591 drupal_set_html_head('<link'. drupal_attributes($attributes) ." />\n");
webmaster@1 1592 }
webmaster@1 1593
webmaster@1 1594 /**
webmaster@1 1595 * Adds a CSS file to the stylesheet queue.
webmaster@1 1596 *
webmaster@1 1597 * @param $path
webmaster@1 1598 * (optional) The path to the CSS file relative to the base_path(), e.g.,
webmaster@1 1599 * /modules/devel/devel.css.
webmaster@1 1600 *
webmaster@1 1601 * Modules should always prefix the names of their CSS files with the module
webmaster@1 1602 * name, for example: system-menus.css rather than simply menus.css. Themes
webmaster@1 1603 * can override module-supplied CSS files based on their filenames, and this
webmaster@1 1604 * prefixing helps prevent confusing name collisions for theme developers.
webmaster@3 1605 * See drupal_get_css where the overrides are performed.
webmaster@1 1606 *
webmaster@1 1607 * If the direction of the current language is right-to-left (Hebrew,
webmaster@1 1608 * Arabic, etc.), the function will also look for an RTL CSS file and append
webmaster@1 1609 * it to the list. The name of this file should have an '-rtl.css' suffix.
webmaster@1 1610 * For example a CSS file called 'name.css' will have a 'name-rtl.css'
webmaster@1 1611 * file added to the list, if exists in the same directory. This CSS file
webmaster@1 1612 * should contain overrides for properties which should be reversed or
webmaster@1 1613 * otherwise different in a right-to-left display.
webmaster@1 1614 * @param $type
webmaster@1 1615 * (optional) The type of stylesheet that is being added. Types are: module
webmaster@1 1616 * or theme.
webmaster@1 1617 * @param $media
webmaster@1 1618 * (optional) The media type for the stylesheet, e.g., all, print, screen.
webmaster@1 1619 * @param $preprocess
webmaster@1 1620 * (optional) Should this CSS file be aggregated and compressed if this
webmaster@1 1621 * feature has been turned on under the performance section?
webmaster@1 1622 *
webmaster@1 1623 * What does this actually mean?
webmaster@1 1624 * CSS preprocessing is the process of aggregating a bunch of separate CSS
webmaster@1 1625 * files into one file that is then compressed by removing all extraneous
webmaster@1 1626 * white space.
webmaster@1 1627 *
webmaster@1 1628 * The reason for merging the CSS files is outlined quite thoroughly here:
webmaster@1 1629 * http://www.die.net/musings/page_load_time/
webmaster@1 1630 * "Load fewer external objects. Due to request overhead, one bigger file
webmaster@1 1631 * just loads faster than two smaller ones half its size."
webmaster@1 1632 *
webmaster@1 1633 * However, you should *not* preprocess every file as this can lead to
webmaster@1 1634 * redundant caches. You should set $preprocess = FALSE when:
webmaster@1 1635 *
webmaster@1 1636 * - Your styles are only used rarely on the site. This could be a special
webmaster@1 1637 * admin page, the homepage, or a handful of pages that does not represent
webmaster@1 1638 * the majority of the pages on your site.
webmaster@1 1639 *
webmaster@1 1640 * Typical candidates for caching are for example styles for nodes across
webmaster@1 1641 * the site, or used in the theme.
webmaster@1 1642 * @return
webmaster@1 1643 * An array of CSS files.
webmaster@1 1644 */
webmaster@1 1645 function drupal_add_css($path = NULL, $type = 'module', $media = 'all', $preprocess = TRUE) {
webmaster@1 1646 static $css = array();
webmaster@1 1647 global $language;
webmaster@1 1648
webmaster@1 1649 // Create an array of CSS files for each media type first, since each type needs to be served
webmaster@1 1650 // to the browser differently.
webmaster@1 1651 if (isset($path)) {
webmaster@1 1652 // This check is necessary to ensure proper cascading of styles and is faster than an asort().
webmaster@1 1653 if (!isset($css[$media])) {
webmaster@1 1654 $css[$media] = array('module' => array(), 'theme' => array());
webmaster@1 1655 }
webmaster@1 1656 $css[$media][$type][$path] = $preprocess;
webmaster@1 1657
webmaster@1 1658 // If the current language is RTL, add the CSS file with RTL overrides.
webmaster@1 1659 if (defined('LANGUAGE_RTL') && $language->direction == LANGUAGE_RTL) {
webmaster@1 1660 $rtl_path = str_replace('.css', '-rtl.css', $path);
webmaster@1 1661 if (file_exists($rtl_path)) {
webmaster@1 1662 $css[$media][$type][$rtl_path] = $preprocess;
webmaster@1 1663 }
webmaster@1 1664 }
webmaster@1 1665 }
webmaster@1 1666
webmaster@1 1667 return $css;
webmaster@1 1668 }
webmaster@1 1669
webmaster@1 1670 /**
webmaster@1 1671 * Returns a themed representation of all stylesheets that should be attached to the page.
webmaster@1 1672 *
webmaster@3 1673 * It loads the CSS in order, with 'module' first, then 'theme' afterwards.
webmaster@3 1674 * This ensures proper cascading of styles so themes can easily override
webmaster@3 1675 * module styles through CSS selectors.
webmaster@3 1676 *
webmaster@3 1677 * Themes may replace module-defined CSS files by adding a stylesheet with the
webmaster@3 1678 * same filename. For example, themes/garland/system-menus.css would replace
webmaster@3 1679 * modules/system/system-menus.css. This allows themes to override complete
webmaster@3 1680 * CSS files, rather than specific selectors, when necessary.
webmaster@3 1681 *
webmaster@3 1682 * If the original CSS file is being overridden by a theme, the theme is
webmaster@3 1683 * responsible for supplying an accompanying RTL CSS file to replace the
webmaster@3 1684 * module's.
webmaster@1 1685 *
webmaster@1 1686 * @param $css
webmaster@1 1687 * (optional) An array of CSS files. If no array is provided, the default
webmaster@1 1688 * stylesheets array is used instead.
webmaster@1 1689 * @return
webmaster@1 1690 * A string of XHTML CSS tags.
webmaster@1 1691 */
webmaster@1 1692 function drupal_get_css($css = NULL) {
webmaster@1 1693 $output = '';
webmaster@1 1694 if (!isset($css)) {
webmaster@1 1695 $css = drupal_add_css();
webmaster@1 1696 }
webmaster@1 1697 $no_module_preprocess = '';
webmaster@1 1698 $no_theme_preprocess = '';
webmaster@1 1699
webmaster@1 1700 $preprocess_css = (variable_get('preprocess_css', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
webmaster@1 1701 $directory = file_directory_path();
webmaster@1 1702 $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
webmaster@1 1703
webmaster@1 1704 // A dummy query-string is added to filenames, to gain control over
webmaster@1 1705 // browser-caching. The string changes on every update or full cache
webmaster@1 1706 // flush, forcing browsers to load a new copy of the files, as the
webmaster@1 1707 // URL changed.
webmaster@1 1708 $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
webmaster@1 1709
webmaster@1 1710 foreach ($css as $media => $types) {
webmaster@1 1711 // If CSS preprocessing is off, we still need to output the styles.
webmaster@1 1712 // Additionally, go through any remaining styles if CSS preprocessing is on and output the non-cached ones.
webmaster@1 1713 foreach ($types as $type => $files) {
webmaster@3 1714 if ($type == 'module') {
webmaster@3 1715 // Setup theme overrides for module styles.
webmaster@3 1716 $theme_styles = array();
webmaster@3 1717 foreach (array_keys($css[$media]['theme']) as $theme_style) {
webmaster@3 1718 $theme_styles[] = basename($theme_style);
webmaster@3 1719 }
webmaster@3 1720 }
webmaster@1 1721 foreach ($types[$type] as $file => $preprocess) {
webmaster@3 1722 // If the theme supplies its own style using the name of the module style, skip its inclusion.
webmaster@3 1723 // This includes any RTL styles associated with its main LTR counterpart.
webmaster@3 1724 if ($type == 'module' && in_array(str_replace('-rtl.css', '.css', basename($file)), $theme_styles)) {
webmaster@7 1725 // Unset the file to prevent its inclusion when CSS aggregation is enabled.
webmaster@7 1726 unset($types[$type][$file]);
webmaster@3 1727 continue;
webmaster@3 1728 }
webmaster@7 1729 // Only include the stylesheet if it exists.
webmaster@7 1730 if (file_exists($file)) {
webmaster@7 1731 if (!$preprocess || !($is_writable && $preprocess_css)) {
webmaster@7 1732 // If a CSS file is not to be preprocessed and it's a module CSS file, it needs to *always* appear at the *top*,
webmaster@7 1733 // regardless of whether preprocessing is on or off.
webmaster@7 1734 if (!$preprocess && $type == 'module') {
webmaster@7 1735 $no_module_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
webmaster@7 1736 }
webmaster@7 1737 // If a CSS file is not to be preprocessed and it's a theme CSS file, it needs to *always* appear at the *bottom*,
webmaster@7 1738 // regardless of whether preprocessing is on or off.
webmaster@7 1739 else if (!$preprocess && $type == 'theme') {
webmaster@7 1740 $no_theme_preprocess .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
webmaster@7 1741 }
webmaster@7 1742 else {
webmaster@7 1743 $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $file . $query_string .'" />'."\n";
webmaster@7 1744 }
webmaster@1 1745 }
webmaster@1 1746 }
webmaster@1 1747 }
webmaster@1 1748 }
webmaster@1 1749
webmaster@1 1750 if ($is_writable && $preprocess_css) {
webmaster@1 1751 $filename = md5(serialize($types) . $query_string) .'.css';
webmaster@1 1752 $preprocess_file = drupal_build_css_cache($types, $filename);
webmaster@1 1753 $output .= '<link type="text/css" rel="stylesheet" media="'. $media .'" href="'. base_path() . $preprocess_file .'" />'."\n";
webmaster@1 1754 }
webmaster@1 1755 }
webmaster@1 1756
webmaster@1 1757 return $no_module_preprocess . $output . $no_theme_preprocess;
webmaster@1 1758 }
webmaster@1 1759
webmaster@1 1760 /**
webmaster@1 1761 * Aggregate and optimize CSS files, putting them in the files directory.
webmaster@1 1762 *
webmaster@1 1763 * @param $types
webmaster@1 1764 * An array of types of CSS files (e.g., screen, print) to aggregate and
webmaster@1 1765 * compress into one file.
webmaster@1 1766 * @param $filename
webmaster@1 1767 * The name of the aggregate CSS file.
webmaster@1 1768 * @return
webmaster@1 1769 * The name of the CSS file.
webmaster@1 1770 */
webmaster@1 1771 function drupal_build_css_cache($types, $filename) {
webmaster@1 1772 $data = '';
webmaster@1 1773
webmaster@1 1774 // Create the css/ within the files folder.
webmaster@1 1775 $csspath = file_create_path('css');
webmaster@1 1776 file_check_directory($csspath, FILE_CREATE_DIRECTORY);
webmaster@1 1777
webmaster@1 1778 if (!file_exists($csspath .'/'. $filename)) {
webmaster@1 1779 // Build aggregate CSS file.
webmaster@1 1780 foreach ($types as $type) {
webmaster@1 1781 foreach ($type as $file => $cache) {
webmaster@1 1782 if ($cache) {
webmaster@1 1783 $contents = drupal_load_stylesheet($file, TRUE);
webmaster@1 1784 // Return the path to where this CSS file originated from.
webmaster@1 1785 $base = base_path() . dirname($file) .'/';
webmaster@1 1786 _drupal_build_css_path(NULL, $base);
webmaster@1 1787 // Prefix all paths within this CSS file, ignoring external and absolute paths.
webmaster@1 1788 $data .= preg_replace_callback('/url\([\'"]?(?![a-z]+:|\/+)([^\'")]+)[\'"]?\)/i', '_drupal_build_css_path', $contents);
webmaster@1 1789 }
webmaster@1 1790 }
webmaster@1 1791 }
webmaster@1 1792
webmaster@1 1793 // Per the W3C specification at http://www.w3.org/TR/REC-CSS2/cascade.html#at-import,
webmaster@1 1794 // @import rules must proceed any other style, so we move those to the top.
webmaster@1 1795 $regexp = '/@import[^;]+;/i';
webmaster@1 1796 preg_match_all($regexp, $data, $matches);
webmaster@1 1797 $data = preg_replace($regexp, '', $data);
webmaster@1 1798 $data = implode('', $matches[0]) . $data;
webmaster@1 1799
webmaster@1 1800 // Create the CSS file.
webmaster@1 1801 file_save_data($data, $csspath .'/'. $filename, FILE_EXISTS_REPLACE);
webmaster@1 1802 }
webmaster@1 1803 return $csspath .'/'. $filename;
webmaster@1 1804 }
webmaster@1 1805
webmaster@1 1806 /**
webmaster@1 1807 * Helper function for drupal_build_css_cache().
webmaster@1 1808 *
webmaster@1 1809 * This function will prefix all paths within a CSS file.
webmaster@1 1810 */
webmaster@1 1811 function _drupal_build_css_path($matches, $base = NULL) {
webmaster@1 1812 static $_base;
webmaster@1 1813 // Store base path for preg_replace_callback.
webmaster@1 1814 if (isset($base)) {
webmaster@1 1815 $_base = $base;
webmaster@1 1816 }
webmaster@1 1817
webmaster@1 1818 // Prefix with base and remove '../' segments where possible.
webmaster@1 1819 $path = $_base . $matches[1];
webmaster@1 1820 $last = '';
webmaster@1 1821 while ($path != $last) {
webmaster@1 1822 $last = $path;
webmaster@1 1823 $path = preg_replace('`(^|/)(?!../)([^/]+)/../`', '$1', $path);
webmaster@1 1824 }
webmaster@1 1825 return 'url('. $path .')';
webmaster@1 1826 }
webmaster@1 1827
webmaster@1 1828 /**
webmaster@1 1829 * Loads the stylesheet and resolves all @import commands.
webmaster@1 1830 *
webmaster@1 1831 * Loads a stylesheet and replaces @import commands with the contents of the
webmaster@1 1832 * imported file. Use this instead of file_get_contents when processing
webmaster@1 1833 * stylesheets.
webmaster@1 1834 *
webmaster@1 1835 * The returned contents are compressed removing white space and comments only
webmaster@1 1836 * when CSS aggregation is enabled. This optimization will not apply for
webmaster@1 1837 * color.module enabled themes with CSS aggregation turned off.
webmaster@1 1838 *
webmaster@1 1839 * @param $file
webmaster@1 1840 * Name of the stylesheet to be processed.
webmaster@1 1841 * @param $optimize
webmaster@1 1842 * Defines if CSS contents should be compressed or not.
webmaster@1 1843 * @return
webmaster@1 1844 * Contents of the stylesheet including the imported stylesheets.
webmaster@1 1845 */
webmaster@1 1846 function drupal_load_stylesheet($file, $optimize = NULL) {
webmaster@1 1847 static $_optimize;
webmaster@1 1848 // Store optimization parameter for preg_replace_callback with nested @import loops.
webmaster@1 1849 if (isset($optimize)) {
webmaster@1 1850 $_optimize = $optimize;
webmaster@1 1851 }
webmaster@1 1852
webmaster@1 1853 $contents = '';
webmaster@1 1854 if (file_exists($file)) {
webmaster@1 1855 // Load the local CSS stylesheet.
webmaster@1 1856 $contents = file_get_contents($file);
webmaster@1 1857
webmaster@1 1858 // Change to the current stylesheet's directory.
webmaster@1 1859 $cwd = getcwd();
webmaster@1 1860 chdir(dirname($file));
webmaster@1 1861
webmaster@1 1862 // Replaces @import commands with the actual stylesheet content.
webmaster@1 1863 // This happens recursively but omits external files.
webmaster@1 1864 $contents = preg_replace_callback('/@import\s*(?:url\()?[\'"]?(?![a-z]+:)([^\'"\()]+)[\'"]?\)?;/', '_drupal_load_stylesheet', $contents);
webmaster@1 1865 // Remove multiple charset declarations for standards compliance (and fixing Safari problems).
webmaster@1 1866 $contents = preg_replace('/^@charset\s+[\'"](\S*)\b[\'"];/i', '', $contents);
webmaster@1 1867
webmaster@1 1868 if ($_optimize) {
webmaster@1 1869 // Perform some safe CSS optimizations.
webmaster@1 1870 $contents = preg_replace('<
webmaster@1 1871 \s*([@{}:;,]|\)\s|\s\()\s* | # Remove whitespace around separators, but keep space around parentheses.
webmaster@1 1872 /\*([^*\\\\]|\*(?!/))+\*/ | # Remove comments that are not CSS hacks.
webmaster@1 1873 [\n\r] # Remove line breaks.
webmaster@1 1874 >x', '\1', $contents);
webmaster@1 1875 }
webmaster@1 1876
webmaster@1 1877 // Change back directory.
webmaster@1 1878 chdir($cwd);
webmaster@1 1879 }
webmaster@1 1880
webmaster@1 1881 return $contents;
webmaster@1 1882 }
webmaster@1 1883
webmaster@1 1884 /**
webmaster@1 1885 * Loads stylesheets recursively and returns contents with corrected paths.
webmaster@1 1886 *
webmaster@1 1887 * This function is used for recursive loading of stylesheets and
webmaster@1 1888 * returns the stylesheet content with all url() paths corrected.
webmaster@1 1889 */
webmaster@1 1890 function _drupal_load_stylesheet($matches) {
webmaster@1 1891 $filename = $matches[1];
webmaster@1 1892 // Load the imported stylesheet and replace @import commands in there as well.
webmaster@1 1893 $file = drupal_load_stylesheet($filename);
webmaster@1 1894 // Alter all url() paths, but not external.
webmaster@1 1895 return preg_replace('/url\(([\'"]?)(?![a-z]+:)([^\'")]+)[\'"]?\)?;/i', 'url(\1'. dirname($filename) .'/', $file);
webmaster@1 1896 }
webmaster@1 1897
webmaster@1 1898 /**
webmaster@1 1899 * Delete all cached CSS files.
webmaster@1 1900 */
webmaster@1 1901 function drupal_clear_css_cache() {
webmaster@1 1902 file_scan_directory(file_create_path('css'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
webmaster@1 1903 }
webmaster@1 1904
webmaster@1 1905 /**
webmaster@1 1906 * Add a JavaScript file, setting or inline code to the page.
webmaster@1 1907 *
webmaster@1 1908 * The behavior of this function depends on the parameters it is called with.
webmaster@1 1909 * Generally, it handles the addition of JavaScript to the page, either as
webmaster@1 1910 * reference to an existing file or as inline code. The following actions can be
webmaster@1 1911 * performed using this function:
webmaster@1 1912 *
webmaster@1 1913 * - Add a file ('core', 'module' and 'theme'):
webmaster@1 1914 * Adds a reference to a JavaScript file to the page. JavaScript files
webmaster@1 1915 * are placed in a certain order, from 'core' first, to 'module' and finally
webmaster@1 1916 * 'theme' so that files, that are added later, can override previously added
webmaster@1 1917 * files with ease.
webmaster@1 1918 *
webmaster@1 1919 * - Add inline JavaScript code ('inline'):
webmaster@1 1920 * Executes a piece of JavaScript code on the current page by placing the code
webmaster@1 1921 * directly in the page. This can, for example, be useful to tell the user that
webmaster@1 1922 * a new message arrived, by opening a pop up, alert box etc.
webmaster@1 1923 *
webmaster@1 1924 * - Add settings ('setting'):
webmaster@1 1925 * Adds a setting to Drupal's global storage of JavaScript settings. Per-page
webmaster@1 1926 * settings are required by some modules to function properly. The settings
webmaster@1 1927 * will be accessible at Drupal.settings.
webmaster@1 1928 *
webmaster@1 1929 * @param $data
webmaster@1 1930 * (optional) If given, the value depends on the $type parameter:
webmaster@1 1931 * - 'core', 'module' or 'theme': Path to the file relative to base_path().
webmaster@1 1932 * - 'inline': The JavaScript code that should be placed in the given scope.
webmaster@1 1933 * - 'setting': An array with configuration options as associative array. The
webmaster@1 1934 * array is directly placed in Drupal.settings. You might want to wrap your
webmaster@1 1935 * actual configuration settings in another variable to prevent the pollution
webmaster@1 1936 * of the Drupal.settings namespace.
webmaster@1 1937 * @param $type
webmaster@1 1938 * (optional) The type of JavaScript that should be added to the page. Allowed
webmaster@1 1939 * values are 'core', 'module', 'theme', 'inline' and 'setting'. You
webmaster@1 1940 * can, however, specify any value. It is treated as a reference to a JavaScript
webmaster@1 1941 * file. Defaults to 'module'.
webmaster@1 1942 * @param $scope
webmaster@1 1943 * (optional) The location in which you want to place the script. Possible
webmaster@1 1944 * values are 'header' and 'footer' by default. If your theme implements
webmaster@1 1945 * different locations, however, you can also use these.
webmaster@1 1946 * @param $defer
webmaster@1 1947 * (optional) If set to TRUE, the defer attribute is set on the <script> tag.
webmaster@1 1948 * Defaults to FALSE. This parameter is not used with $type == 'setting'.
webmaster@1 1949 * @param $cache
webmaster@1 1950 * (optional) If set to FALSE, the JavaScript file is loaded anew on every page
webmaster@1 1951 * call, that means, it is not cached. Defaults to TRUE. Used only when $type
webmaster@1 1952 * references a JavaScript file.
webmaster@1 1953 * @param $preprocess
webmaster@1 1954 * (optional) Should this JS file be aggregated if this
webmaster@1 1955 * feature has been turned on under the performance section?
webmaster@1 1956 * @return
webmaster@1 1957 * If the first parameter is NULL, the JavaScript array that has been built so
webmaster@1 1958 * far for $scope is returned. If the first three parameters are NULL,
webmaster@1 1959 * an array with all scopes is returned.
webmaster@1 1960 */
webmaster@1 1961 function drupal_add_js($data = NULL, $type = 'module', $scope = 'header', $defer = FALSE, $cache = TRUE, $preprocess = TRUE) {
webmaster@1 1962 static $javascript = array();
webmaster@1 1963
webmaster@1 1964 if (isset($data)) {
webmaster@1 1965
webmaster@1 1966 // Add jquery.js and drupal.js, as well as the basePath setting, the
webmaster@1 1967 // first time a Javascript file is added.
webmaster@1 1968 if (empty($javascript)) {
webmaster@1 1969 $javascript['header'] = array(
webmaster@1 1970 'core' => array(
webmaster@1 1971 'misc/jquery.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
webmaster@1 1972 'misc/drupal.js' => array('cache' => TRUE, 'defer' => FALSE, 'preprocess' => TRUE),
webmaster@1 1973 ),
webmaster@1 1974 'module' => array(),
webmaster@1 1975 'theme' => array(),
webmaster@1 1976 'setting' => array(
webmaster@1 1977 array('basePath' => base_path()),
webmaster@1 1978 ),
webmaster@1 1979 'inline' => array(),
webmaster@1 1980 );
webmaster@1 1981 }
webmaster@1 1982
webmaster@1 1983 if (isset($scope) && !isset($javascript[$scope])) {
webmaster@1 1984 $javascript[$scope] = array('core' => array(), 'module' => array(), 'theme' => array(), 'setting' => array(), 'inline' => array());
webmaster@1 1985 }
webmaster@1 1986
webmaster@1 1987 if (isset($type) && isset($scope) && !isset($javascript[$scope][$type])) {
webmaster@1 1988 $javascript[$scope][$type] = array();
webmaster@1 1989 }
webmaster@1 1990
webmaster@1 1991 switch ($type) {
webmaster@1 1992 case 'setting':
webmaster@1 1993 $javascript[$scope][$type][] = $data;
webmaster@1 1994 break;
webmaster@1 1995 case 'inline':
webmaster@1 1996 $javascript[$scope][$type][] = array('code' => $data, 'defer' => $defer);
webmaster@1 1997 break;
webmaster@1 1998 default:
webmaster@1 1999 // If cache is FALSE, don't preprocess the JS file.
webmaster@1 2000 $javascript[$scope][$type][$data] = array('cache' => $cache, 'defer' => $defer, 'preprocess' => (!$cache ? FALSE : $preprocess));
webmaster@1 2001 }
webmaster@1 2002 }
webmaster@1 2003
webmaster@1 2004 if (isset($scope)) {
webmaster@1 2005
webmaster@1 2006 if (isset($javascript[$scope])) {
webmaster@1 2007 return $javascript[$scope];
webmaster@1 2008 }
webmaster@1 2009 else {
webmaster@1 2010 return array();
webmaster@1 2011 }
webmaster@1 2012 }
webmaster@1 2013 else {
webmaster@1 2014 return $javascript;
webmaster@1 2015 }
webmaster@1 2016 }
webmaster@1 2017
webmaster@1 2018 /**
webmaster@1 2019 * Returns a themed presentation of all JavaScript code for the current page.
webmaster@1 2020 *
webmaster@1 2021 * References to JavaScript files are placed in a certain order: first, all
webmaster@1 2022 * 'core' files, then all 'module' and finally all 'theme' JavaScript files
webmaster@1 2023 * are added to the page. Then, all settings are output, followed by 'inline'
webmaster@1 2024 * JavaScript code. If running update.php, all preprocessing is disabled.
webmaster@1 2025 *
webmaster@7 2026 * @param $scope
webmaster@1 2027 * (optional) The scope for which the JavaScript rules should be returned.
webmaster@1 2028 * Defaults to 'header'.
webmaster@7 2029 * @param $javascript
webmaster@1 2030 * (optional) An array with all JavaScript code. Defaults to the default
webmaster@1 2031 * JavaScript array for the given scope.
webmaster@1 2032 * @return
webmaster@1 2033 * All JavaScript code segments and includes for the scope as HTML tags.
webmaster@1 2034 */
webmaster@1 2035 function drupal_get_js($scope = 'header', $javascript = NULL) {
webmaster@1 2036 if ((!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') && function_exists('locale_update_js_files')) {
webmaster@1 2037 locale_update_js_files();
webmaster@1 2038 }
webmaster@1 2039
webmaster@1 2040 if (!isset($javascript)) {
webmaster@1 2041 $javascript = drupal_add_js(NULL, NULL, $scope);
webmaster@1 2042 }
webmaster@1 2043
webmaster@1 2044 if (empty($javascript)) {
webmaster@1 2045 return '';
webmaster@1 2046 }
webmaster@1 2047
webmaster@1 2048 $output = '';
webmaster@1 2049 $preprocessed = '';
webmaster@1 2050 $no_preprocess = array('core' => '', 'module' => '', 'theme' => '');
webmaster@1 2051 $files = array();
webmaster@1 2052 $preprocess_js = (variable_get('preprocess_js', FALSE) && (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update'));
webmaster@1 2053 $directory = file_directory_path();
webmaster@1 2054 $is_writable = is_dir($directory) && is_writable($directory) && (variable_get('file_downloads', FILE_DOWNLOADS_PUBLIC) == FILE_DOWNLOADS_PUBLIC);
webmaster@1 2055
webmaster@1 2056 // A dummy query-string is added to filenames, to gain control over
webmaster@1 2057 // browser-caching. The string changes on every update or full cache
webmaster@1 2058 // flush, forcing browsers to load a new copy of the files, as the
webmaster@1 2059 // URL changed. Files that should not be cached (see drupal_add_js())
webmaster@1 2060 // get time() as query-string instead, to enforce reload on every
webmaster@1 2061 // page request.
webmaster@1 2062 $query_string = '?'. substr(variable_get('css_js_query_string', '0'), 0, 1);
webmaster@1 2063
webmaster@11 2064 // For inline Javascript to validate as XHTML, all Javascript containing
webmaster@11 2065 // XHTML needs to be wrapped in CDATA. To make that backwards compatible
webmaster@11 2066 // with HTML 4, we need to comment out the CDATA-tag.
webmaster@11 2067 $embed_prefix = "\n<!--//--><![CDATA[//><!--\n";
webmaster@11 2068 $embed_suffix = "\n//--><!]]>\n";
webmaster@11 2069
webmaster@1 2070 foreach ($javascript as $type => $data) {
webmaster@1 2071
webmaster@1 2072 if (!$data) continue;
webmaster@1 2073
webmaster@1 2074 switch ($type) {
webmaster@1 2075 case 'setting':
webmaster@11 2076 $output .= '<script type="text/javascript">' . $embed_prefix . 'jQuery.extend(Drupal.settings, ' . drupal_to_js(call_user_func_array('array_merge_recursive', $data)) . ");" . $embed_suffix . "</script>\n";
webmaster@1 2077 break;
webmaster@1 2078 case 'inline':
webmaster@1 2079 foreach ($data as $info) {
webmaster@11 2080 $output .= '<script type="text/javascript"' . ($info['defer'] ? ' defer="defer"' : '') . '>' . $embed_prefix . $info['code'] . $embed_suffix . "</script>\n";
webmaster@1 2081 }
webmaster@1 2082 break;
webmaster@1 2083 default:
webmaster@1 2084 // If JS preprocessing is off, we still need to output the scripts.
webmaster@1 2085 // Additionally, go through any remaining scripts if JS preprocessing is on and output the non-cached ones.
webmaster@1 2086 foreach ($data as $path => $info) {
webmaster@1 2087 if (!$info['preprocess'] || !$is_writable || !$preprocess_js) {
webmaster@1 2088 $no_preprocess[$type] .= '<script type="text/javascript"'. ($info['defer'] ? ' defer="defer"' : '') .' src="'. base_path() . $path . ($info['cache'] ? $query_string : '?'. time()) ."\"></script>\n";
webmaster@1 2089 }
webmaster@1 2090 else {
webmaster@1 2091 $files[$path] = $info;
webmaster@1 2092 }
webmaster@1 2093 }
webmaster@1 2094 }
webmaster@1 2095 }
webmaster@1 2096
webmaster@1 2097 // Aggregate any remaining JS files that haven't already been output.
webmaster@1 2098 if ($is_writable && $preprocess_js && count($files) > 0) {
webmaster@1 2099 $filename = md5(serialize($files) . $query_string) .'.js';
webmaster@1 2100 $preprocess_file = drupal_build_js_cache($files, $filename);
webmaster@1 2101 $preprocessed .= '<script type="text/javascript" src="'. base_path() . $preprocess_file .'"></script>'."\n";
webmaster@1 2102 }
webmaster@1 2103
webmaster@1 2104 // Keep the order of JS files consistent as some are preprocessed and others are not.
webmaster@1 2105 // Make sure any inline or JS setting variables appear last after libraries have loaded.
webmaster@1 2106 $output = $preprocessed . implode('', $no_preprocess) . $output;
webmaster@1 2107
webmaster@1 2108 return $output;
webmaster@1 2109 }
webmaster@1 2110
webmaster@1 2111 /**
webmaster@1 2112 * Assist in adding the tableDrag JavaScript behavior to a themed table.
webmaster@1 2113 *
webmaster@1 2114 * Draggable tables should be used wherever an outline or list of sortable items
webmaster@1 2115 * needs to be arranged by an end-user. Draggable tables are very flexible and
webmaster@1 2116 * can manipulate the value of form elements placed within individual columns.
webmaster@1 2117 *
webmaster@1 2118 * To set up a table to use drag and drop in place of weight select-lists or
webmaster@1 2119 * in place of a form that contains parent relationships, the form must be
webmaster@1 2120 * themed into a table. The table must have an id attribute set. If using
webmaster@1 2121 * theme_table(), the id may be set as such:
webmaster@1 2122 * @code
webmaster@1 2123 * $output = theme('table', $header, $rows, array('id' => 'my-module-table'));
webmaster@1 2124 * return $output;
webmaster@1 2125 * @endcode
webmaster@1 2126 *
webmaster@1 2127 * In the theme function for the form, a special class must be added to each
webmaster@1 2128 * form element within the same column, "grouping" them together.
webmaster@1 2129 *
webmaster@1 2130 * In a situation where a single weight column is being sorted in the table, the
webmaster@1 2131 * classes could be added like this (in the theme function):
webmaster@1 2132 * @code
webmaster@1 2133 * $form['my_elements'][$delta]['weight']['#attributes']['class'] = "my-elements-weight";
webmaster@1 2134 * @endcode
webmaster@1 2135 *
webmaster@1 2136 * Each row of the table must also have a class of "draggable" in order to enable the
webmaster@1 2137 * drag handles:
webmaster@1 2138 * @code
webmaster@1 2139 * $row = array(...);
webmaster@1 2140 * $rows[] = array(
webmaster@1 2141 * 'data' => $row,
webmaster@1 2142 * 'class' => 'draggable',
webmaster@1 2143 * );
webmaster@1 2144 * @endcode
webmaster@1 2145 *
webmaster@1 2146 * When tree relationships are present, the two additional classes
webmaster@1 2147 * 'tabledrag-leaf' and 'tabledrag-root' can be used to refine the behavior:
webmaster@1 2148 * - Rows with the 'tabledrag-leaf' class cannot have child rows.
webmaster@1 2149 * - Rows with the 'tabledrag-root' class cannot be nested under a parent row.
webmaster@1 2150 *
webmaster@1 2151 * Calling drupal_add_tabledrag() would then be written as such:
webmaster@1 2152 * @code
webmaster@1 2153 * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
webmaster@1 2154 * @endcode
webmaster@1 2155 *
webmaster@1 2156 * In a more complex case where there are several groups in one column (such as
webmaster@1 2157 * the block regions on the admin/build/block page), a separate subgroup class
webmaster@1 2158 * must also be added to differentiate the groups.
webmaster@1 2159 * @code
webmaster@1 2160 * $form['my_elements'][$region][$delta]['weight']['#attributes']['class'] = "my-elements-weight my-elements-weight-". $region;
webmaster@1 2161 * @endcode
webmaster@1 2162 *
webmaster@1 2163 * $group is still 'my-element-weight', and the additional $subgroup variable
webmaster@1 2164 * will be passed in as 'my-elements-weight-'. $region. This also means that
webmaster@1 2165 * you'll need to call drupal_add_tabledrag() once for every region added.
webmaster@1 2166 *
webmaster@1 2167 * @code
webmaster@1 2168 * foreach ($regions as $region) {
webmaster@1 2169 * drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight', 'my-elements-weight-'. $region);
webmaster@1 2170 * }
webmaster@1 2171 * @endcode
webmaster@1 2172 *
webmaster@1 2173 * In a situation where tree relationships are present, adding multiple
webmaster@1 2174 * subgroups is not necessary, because the table will contain indentations that
webmaster@1 2175 * provide enough information about the sibling and parent relationships.
webmaster@1 2176 * See theme_menu_overview_form() for an example creating a table containing
webmaster@1 2177 * parent relationships.
webmaster@1 2178 *
webmaster@1 2179 * Please note that this function should be called from the theme layer, such as
webmaster@1 2180 * in a .tpl.php file, theme_ function, or in a template_preprocess function,
webmaster@1 2181 * not in a form declartion. Though the same JavaScript could be added to the
webmaster@1 2182 * page using drupal_add_js() directly, this function helps keep template files
webmaster@1 2183 * clean and readable. It also prevents tabledrag.js from being added twice
webmaster@1 2184 * accidentally.
webmaster@1 2185 *
webmaster@1 2186 * @param $table_id
webmaster@1 2187 * String containing the target table's id attribute. If the table does not
webmaster@1 2188 * have an id, one will need to be set, such as <table id="my-module-table">.
webmaster@1 2189 * @param $action
webmaster@1 2190 * String describing the action to be done on the form item. Either 'match'
webmaster@1 2191 * 'depth', or 'order'. Match is typically used for parent relationships.
webmaster@1 2192 * Order is typically used to set weights on other form elements with the same
webmaster@1 2193 * group. Depth updates the target element with the current indentation.
webmaster@1 2194 * @param $relationship
webmaster@1 2195 * String describing where the $action variable should be performed. Either
webmaster@1 2196 * 'parent', 'sibling', 'group', or 'self'. Parent will only look for fields
webmaster@1 2197 * up the tree. Sibling will look for fields in the same group in rows above
webmaster@1 2198 * and below it. Self affects the dragged row itself. Group affects the
webmaster@1 2199 * dragged row, plus any children below it (the entire dragged group).
webmaster@1 2200 * @param $group
webmaster@1 2201 * A class name applied on all related form elements for this action.
webmaster@1 2202 * @param $subgroup
webmaster@1 2203 * (optional) If the group has several subgroups within it, this string should
webmaster@1 2204 * contain the class name identifying fields in the same subgroup.
webmaster@1 2205 * @param $source
webmaster@1 2206 * (optional) If the $action is 'match', this string should contain the class
webmaster@1 2207 * name identifying what field will be used as the source value when matching
webmaster@1 2208 * the value in $subgroup.
webmaster@1 2209 * @param $hidden
webmaster@1 2210 * (optional) The column containing the field elements may be entirely hidden
webmaster@1 2211 * from view dynamically when the JavaScript is loaded. Set to FALSE if the
webmaster@1 2212 * column should not be hidden.
webmaster@1 2213 * @param $limit
webmaster@1 2214 * (optional) Limit the maximum amount of parenting in this table.
webmaster@1 2215 * @see block-admin-display-form.tpl.php
webmaster@1 2216 * @see theme_menu_overview_form()
webmaster@1 2217 */
webmaster@1 2218 function drupal_add_tabledrag($table_id, $action, $relationship, $group, $subgroup = NULL, $source = NULL, $hidden = TRUE, $limit = 0) {
webmaster@1 2219 static $js_added = FALSE;
webmaster@1 2220 if (!$js_added) {
webmaster@1 2221 drupal_add_js('misc/tabledrag.js', 'core');
webmaster@1 2222 $js_added = TRUE;
webmaster@1 2223 }
webmaster@1 2224
webmaster@1 2225 // If a subgroup or source isn't set, assume it is the same as the group.
webmaster@1 2226 $target = isset($subgroup) ? $subgroup : $group;
webmaster@1 2227 $source = isset($source) ? $source : $target;
webmaster@1 2228 $settings['tableDrag'][$table_id][$group][] = array(
webmaster@1 2229 'target' => $target,
webmaster@1 2230 'source' => $source,
webmaster@1 2231 'relationship' => $relationship,
webmaster@1 2232 'action' => $action,
webmaster@1 2233 'hidden' => $hidden,
webmaster@1 2234 'limit' => $limit,
webmaster@1 2235 );
webmaster@1 2236 drupal_add_js($settings, 'setting');
webmaster@1 2237 }
webmaster@1 2238
webmaster@1 2239 /**
webmaster@1 2240 * Aggregate JS files, putting them in the files directory.
webmaster@1 2241 *
webmaster@1 2242 * @param $files
webmaster@1 2243 * An array of JS files to aggregate and compress into one file.
webmaster@1 2244 * @param $filename
webmaster@1 2245 * The name of the aggregate JS file.
webmaster@1 2246 * @return
webmaster@1 2247 * The name of the JS file.
webmaster@1 2248 */
webmaster@1 2249 function drupal_build_js_cache($files, $filename) {
webmaster@1 2250 $contents = '';
webmaster@1 2251
webmaster@1 2252 // Create the js/ within the files folder.
webmaster@1 2253 $jspath = file_create_path('js');
webmaster@1 2254 file_check_directory($jspath, FILE_CREATE_DIRECTORY);
webmaster@1 2255
webmaster@1 2256 if (!file_exists($jspath .'/'. $filename)) {
webmaster@1 2257 // Build aggregate JS file.
webmaster@1 2258 foreach ($files as $path => $info) {
webmaster@1 2259 if ($info['preprocess']) {
webmaster@1 2260 // Append a ';' after each JS file to prevent them from running together.
webmaster@1 2261 $contents .= file_get_contents($path) .';';
webmaster@1 2262 }
webmaster@1 2263 }
webmaster@1 2264
webmaster@1 2265 // Create the JS file.
webmaster@1 2266 file_save_data($contents, $jspath .'/'. $filename, FILE_EXISTS_REPLACE);
webmaster@1 2267 }
webmaster@1 2268
webmaster@1 2269 return $jspath .'/'. $filename;
webmaster@1 2270 }
webmaster@1 2271
webmaster@1 2272 /**
webmaster@1 2273 * Delete all cached JS files.
webmaster@1 2274 */
webmaster@1 2275 function drupal_clear_js_cache() {
webmaster@1 2276 file_scan_directory(file_create_path('js'), '.*', array('.', '..', 'CVS'), 'file_delete', TRUE);
webmaster@1 2277 variable_set('javascript_parsed', array());
webmaster@1 2278 }
webmaster@1 2279
webmaster@1 2280 /**
webmaster@1 2281 * Converts a PHP variable into its Javascript equivalent.
webmaster@1 2282 *
webmaster@1 2283 * We use HTML-safe strings, i.e. with <, > and & escaped.
webmaster@1 2284 */
webmaster@1 2285 function drupal_to_js($var) {
webmaster@1 2286 switch (gettype($var)) {
webmaster@1 2287 case 'boolean':
webmaster@1 2288 return $var ? 'true' : 'false'; // Lowercase necessary!
webmaster@1 2289 case 'integer':
webmaster@1 2290 case 'double':
webmaster@1 2291 return $var;
webmaster@1 2292 case 'resource':
webmaster@1 2293 case 'string':
webmaster@1 2294 return '"'. str_replace(array("\r", "\n", "<", ">", "&"),
webmaster@1 2295 array('\r', '\n', '\x3c', '\x3e', '\x26'),
webmaster@1 2296 addslashes($var)) .'"';
webmaster@1 2297 case 'array':
webmaster@1 2298 // Arrays in JSON can't be associative. If the array is empty or if it
webmaster@1 2299 // has sequential whole number keys starting with 0, it's not associative
webmaster@1 2300 // so we can go ahead and convert it as an array.
webmaster@1 2301 if (empty ($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
webmaster@1 2302 $output = array();
webmaster@1 2303 foreach ($var as $v) {
webmaster@1 2304 $output[] = drupal_to_js($v);
webmaster@1 2305 }
webmaster@1 2306 return '[ '. implode(', ', $output) .' ]';
webmaster@1 2307 }
webmaster@1 2308 // Otherwise, fall through to convert the array as an object.
webmaster@1 2309 case 'object':
webmaster@1 2310 $output = array();
webmaster@1 2311 foreach ($var as $k => $v) {
webmaster@1 2312 $output[] = drupal_to_js(strval($k)) .': '. drupal_to_js($v);
webmaster@1 2313 }
webmaster@1 2314 return '{ '. implode(', ', $output) .' }';
webmaster@1 2315 default:
webmaster@1 2316 return 'null';
webmaster@1 2317 }
webmaster@1 2318 }
webmaster@1 2319
webmaster@1 2320 /**
webmaster@1 2321 * Return data in JSON format.
webmaster@1 2322 *
webmaster@1 2323 * This function should be used for JavaScript callback functions returning
webmaster@1 2324 * data in JSON format. It sets the header for JavaScript output.
webmaster@1 2325 *
webmaster@1 2326 * @param $var
webmaster@1 2327 * (optional) If set, the variable will be converted to JSON and output.
webmaster@1 2328 */
webmaster@1 2329 function drupal_json($var = NULL) {
webmaster@1 2330 // We are returning JavaScript, so tell the browser.
webmaster@1 2331 drupal_set_header('Content-Type: text/javascript; charset=utf-8');
webmaster@1 2332
webmaster@1 2333 if (isset($var)) {
webmaster@1 2334 echo drupal_to_js($var);
webmaster@1 2335 }
webmaster@1 2336 }
webmaster@1 2337
webmaster@1 2338 /**
webmaster@1 2339 * Wrapper around urlencode() which avoids Apache quirks.
webmaster@1 2340 *
webmaster@1 2341 * Should be used when placing arbitrary data in an URL. Note that Drupal paths
webmaster@1 2342 * are urlencoded() when passed through url() and do not require urlencoding()
webmaster@1 2343 * of individual components.
webmaster@1 2344 *
webmaster@1 2345 * Notes:
webmaster@1 2346 * - For esthetic reasons, we do not escape slashes. This also avoids a 'feature'
webmaster@1 2347 * in Apache where it 404s on any path containing '%2F'.
webmaster@1 2348 * - mod_rewrite unescapes %-encoded ampersands, hashes, and slashes when clean
webmaster@1 2349 * URLs are used, which are interpreted as delimiters by PHP. These
webmaster@1 2350 * characters are double escaped so PHP will still see the encoded version.
webmaster@1 2351 * - With clean URLs, Apache changes '//' to '/', so every second slash is
webmaster@1 2352 * double escaped.
webmaster@1 2353 *
webmaster@1 2354 * @param $text
webmaster@1 2355 * String to encode
webmaster@1 2356 */
webmaster@1 2357 function drupal_urlencode($text) {
webmaster@1 2358 if (variable_get('clean_url', '0')) {
webmaster@1 2359 return str_replace(array('%2F', '%26', '%23', '//'),
webmaster@1 2360 array('/', '%2526', '%2523', '/%252F'),
webmaster@1 2361 rawurlencode($text));
webmaster@1 2362 }
webmaster@1 2363 else {
webmaster@1 2364 return str_replace('%2F', '/', rawurlencode($text));
webmaster@1 2365 }
webmaster@1 2366 }
webmaster@1 2367
webmaster@1 2368 /**
webmaster@1 2369 * Ensure the private key variable used to generate tokens is set.
webmaster@1 2370 *
webmaster@1 2371 * @return
webmaster@1 2372 * The private key.
webmaster@1 2373 */
webmaster@1 2374 function drupal_get_private_key() {
webmaster@1 2375 if (!($key = variable_get('drupal_private_key', 0))) {
webmaster@1 2376 $key = md5(uniqid(mt_rand(), true)) . md5(uniqid(mt_rand(), true));
webmaster@1 2377 variable_set('drupal_private_key', $key);
webmaster@1 2378 }
webmaster@1 2379 return $key;
webmaster@1 2380 }
webmaster@1 2381
webmaster@1 2382 /**
webmaster@1 2383 * Generate a token based on $value, the current user session and private key.
webmaster@1 2384 *
webmaster@1 2385 * @param $value
webmaster@1 2386 * An additional value to base the token on.
webmaster@1 2387 */
webmaster@1 2388 function drupal_get_token($value = '') {
webmaster@1 2389 $private_key = drupal_get_private_key();
webmaster@1 2390 return md5(session_id() . $value . $private_key);
webmaster@1 2391 }
webmaster@1 2392
webmaster@1 2393 /**
webmaster@1 2394 * Validate a token based on $value, the current user session and private key.
webmaster@1 2395 *
webmaster@1 2396 * @param $token
webmaster@1 2397 * The token to be validated.
webmaster@1 2398 * @param $value
webmaster@1 2399 * An additional value to base the token on.
webmaster@1 2400 * @param $skip_anonymous
webmaster@1 2401 * Set to true to skip token validation for anonymous users.
webmaster@1 2402 * @return
webmaster@1 2403 * True for a valid token, false for an invalid token. When $skip_anonymous
webmaster@1 2404 * is true, the return value will always be true for anonymous users.
webmaster@1 2405 */
webmaster@1 2406 function drupal_valid_token($token, $value = '', $skip_anonymous = FALSE) {
webmaster@1 2407 global $user;
webmaster@1 2408 return (($skip_anonymous && $user->uid == 0) || ($token == md5(session_id() . $value . variable_get('drupal_private_key', ''))));
webmaster@1 2409 }
webmaster@1 2410
webmaster@1 2411 /**
webmaster@1 2412 * Performs one or more XML-RPC request(s).
webmaster@1 2413 *
webmaster@1 2414 * @param $url
webmaster@1 2415 * An absolute URL of the XML-RPC endpoint.
webmaster@1 2416 * Example:
webmaster@1 2417 * http://www.example.com/xmlrpc.php
webmaster@1 2418 * @param ...
webmaster@1 2419 * For one request:
webmaster@1 2420 * The method name followed by a variable number of arguments to the method.
webmaster@1 2421 * For multiple requests (system.multicall):
webmaster@1 2422 * An array of call arrays. Each call array follows the pattern of the single
webmaster@1 2423 * request: method name followed by the arguments to the method.
webmaster@1 2424 * @return
webmaster@1 2425 * For one request:
webmaster@1 2426 * Either the return value of the method on success, or FALSE.
webmaster@1 2427 * If FALSE is returned, see xmlrpc_errno() and xmlrpc_error_msg().
webmaster@1 2428 * For multiple requests:
webmaster@1 2429 * An array of results. Each result will either be the result
webmaster@1 2430 * returned by the method called, or an xmlrpc_error object if the call
webmaster@1 2431 * failed. See xmlrpc_error().
webmaster@1 2432 */
webmaster@1 2433 function xmlrpc($url) {
webmaster@1 2434 require_once './includes/xmlrpc.inc';
webmaster@1 2435 $args = func_get_args();
webmaster@1 2436 return call_user_func_array('_xmlrpc', $args);
webmaster@1 2437 }
webmaster@1 2438
webmaster@1 2439 function _drupal_bootstrap_full() {
webmaster@1 2440 static $called;
webmaster@1 2441
webmaster@1 2442 if ($called) {
webmaster@1 2443 return;
webmaster@1 2444 }
webmaster@1 2445 $called = 1;
webmaster@1 2446 require_once './includes/theme.inc';
webmaster@1 2447 require_once './includes/pager.inc';
webmaster@1 2448 require_once './includes/menu.inc';
webmaster@1 2449 require_once './includes/tablesort.inc';
webmaster@1 2450 require_once './includes/file.inc';
webmaster@1 2451 require_once './includes/unicode.inc';
webmaster@1 2452 require_once './includes/image.inc';
webmaster@1 2453 require_once './includes/form.inc';
webmaster@1 2454 require_once './includes/mail.inc';
webmaster@1 2455 require_once './includes/actions.inc';
webmaster@1 2456 // Set the Drupal custom error handler.
webmaster@1 2457 set_error_handler('drupal_error_handler');
webmaster@1 2458 // Emit the correct charset HTTP header.
webmaster@1 2459 drupal_set_header('Content-Type: text/html; charset=utf-8');
webmaster@1 2460 // Detect string handling method
webmaster@1 2461 unicode_check();
webmaster@1 2462 // Undo magic quotes
webmaster@1 2463 fix_gpc_magic();
webmaster@1 2464 // Load all enabled modules
webmaster@1 2465 module_load_all();
webmaster@1 2466 // Let all modules take action before menu system handles the request
webmaster@1 2467 // We do not want this while running update.php.
webmaster@1 2468 if (!defined('MAINTENANCE_MODE') || MAINTENANCE_MODE != 'update') {
webmaster@1 2469 module_invoke_all('init');
webmaster@1 2470 }
webmaster@1 2471 }
webmaster@1 2472
webmaster@1 2473 /**
webmaster@1 2474 * Store the current page in the cache.
webmaster@1 2475 *
webmaster@1 2476 * We try to store a gzipped version of the cache. This requires the
webmaster@1 2477 * PHP zlib extension (http://php.net/manual/en/ref.zlib.php).
webmaster@1 2478 * Presence of the extension is checked by testing for the function
webmaster@1 2479 * gzencode. There are two compression algorithms: gzip and deflate.
webmaster@1 2480 * The majority of all modern browsers support gzip or both of them.
webmaster@1 2481 * We thus only deal with the gzip variant and unzip the cache in case
webmaster@1 2482 * the browser does not accept gzip encoding.
webmaster@1 2483 *
webmaster@1 2484 * @see drupal_page_header
webmaster@1 2485 */
webmaster@1 2486 function page_set_cache() {
webmaster@1 2487 global $user, $base_root;
webmaster@1 2488
webmaster@1 2489 if (!$user->uid && $_SERVER['REQUEST_METHOD'] == 'GET' && page_get_cache(TRUE)) {
webmaster@1 2490 // This will fail in some cases, see page_get_cache() for the explanation.
webmaster@1 2491 if ($data = ob_get_contents()) {
webmaster@1 2492 $cache = TRUE;
webmaster@1 2493 if (variable_get('page_compression', TRUE) && function_exists('gzencode')) {
webmaster@1 2494 // We do not store the data in case the zlib mode is deflate.
webmaster@1 2495 // This should be rarely happening.
webmaster@1 2496 if (zlib_get_coding_type() == 'deflate') {
webmaster@1 2497 $cache = FALSE;
webmaster@1 2498 }
webmaster@1 2499 else if (zlib_get_coding_type() == FALSE) {
webmaster@1 2500 $data = gzencode($data, 9, FORCE_GZIP);
webmaster@1 2501 }
webmaster@1 2502 // The remaining case is 'gzip' which means the data is
webmaster@1 2503 // already compressed and nothing left to do but to store it.
webmaster@1 2504 }
webmaster@1 2505 ob_end_flush();
webmaster@1 2506 if ($cache && $data) {
webmaster@1 2507 cache_set($base_root . request_uri(), $data, 'cache_page', CACHE_TEMPORARY, drupal_get_headers());
webmaster@1 2508 }
webmaster@1 2509 }
webmaster@1 2510 }
webmaster@1 2511 }
webmaster@1 2512
webmaster@1 2513 /**
webmaster@1 2514 * Executes a cron run when called
webmaster@1 2515 * @return
webmaster@1 2516 * Returns TRUE if ran successfully
webmaster@1 2517 */
webmaster@1 2518 function drupal_cron_run() {
webmaster@1 2519 // If not in 'safe mode', increase the maximum execution time:
webmaster@1 2520 if (!ini_get('safe_mode')) {
webmaster@1 2521 set_time_limit(240);
webmaster@1 2522 }
webmaster@1 2523
webmaster@1 2524 // Fetch the cron semaphore
webmaster@1 2525 $semaphore = variable_get('cron_semaphore', FALSE);
webmaster@1 2526
webmaster@1 2527 if ($semaphore) {
webmaster@1 2528 if (time() - $semaphore > 3600) {
webmaster@1 2529 // Either cron has been running for more than an hour or the semaphore
webmaster@1 2530 // was not reset due to a database error.
webmaster@1 2531 watchdog('cron', 'Cron has been running for more than an hour and is most likely stuck.', array(), WATCHDOG_ERROR);
webmaster@1 2532
webmaster@1 2533 // Release cron semaphore
webmaster@1 2534 variable_del('cron_semaphore');
webmaster@1 2535 }
webmaster@1 2536 else {
webmaster@1 2537 // Cron is still running normally.
webmaster@1 2538 watchdog('cron', 'Attempting to re-run cron while it is already running.', array(), WATCHDOG_WARNING);
webmaster@1 2539 }
webmaster@1 2540 }
webmaster@1 2541 else {
webmaster@1 2542 // Register shutdown callback
webmaster@1 2543 register_shutdown_function('drupal_cron_cleanup');
webmaster@1 2544
webmaster@1 2545 // Lock cron semaphore
webmaster@1 2546 variable_set('cron_semaphore', time());
webmaster@1 2547
webmaster@1 2548 // Iterate through the modules calling their cron handlers (if any):
webmaster@1 2549 module_invoke_all('cron');
webmaster@1 2550
webmaster@1 2551 // Record cron time
webmaster@1 2552 variable_set('cron_last', time());
webmaster@1 2553 watchdog('cron', 'Cron run completed.', array(), WATCHDOG_NOTICE);
webmaster@1 2554
webmaster@1 2555 // Release cron semaphore
webmaster@1 2556 variable_del('cron_semaphore');
webmaster@1 2557
webmaster@1 2558 // Return TRUE so other functions can check if it did run successfully
webmaster@1 2559 return TRUE;
webmaster@1 2560 }
webmaster@1 2561 }
webmaster@1 2562
webmaster@1 2563 /**
webmaster@1 2564 * Shutdown function for cron cleanup.
webmaster@1 2565 */
webmaster@1 2566 function drupal_cron_cleanup() {
webmaster@1 2567 // See if the semaphore is still locked.
webmaster@1 2568 if (variable_get('cron_semaphore', FALSE)) {
webmaster@1 2569 watchdog('cron', 'Cron run exceeded the time limit and was aborted.', array(), WATCHDOG_WARNING);
webmaster@1 2570
webmaster@1 2571 // Release cron semaphore
webmaster@1 2572 variable_del('cron_semaphore');
webmaster@1 2573 }
webmaster@1 2574 }
webmaster@1 2575
webmaster@1 2576 /**
webmaster@1 2577 * Return an array of system file objects.
webmaster@1 2578 *
webmaster@1 2579 * Returns an array of file objects of the given type from the site-wide
webmaster@1 2580 * directory (i.e. modules/), the all-sites directory (i.e.
webmaster@1 2581 * sites/all/modules/), the profiles directory, and site-specific directory
webmaster@1 2582 * (i.e. sites/somesite/modules/). The returned array will be keyed using the
webmaster@1 2583 * key specified (name, basename, filename). Using name or basename will cause
webmaster@1 2584 * site-specific files to be prioritized over similar files in the default
webmaster@1 2585 * directories. That is, if a file with the same name appears in both the
webmaster@1 2586 * site-wide directory and site-specific directory, only the site-specific
webmaster@1 2587 * version will be included.
webmaster@1 2588 *
webmaster@1 2589 * @param $mask
webmaster@1 2590 * The regular expression of the files to find.
webmaster@1 2591 * @param $directory
webmaster@1 2592 * The subdirectory name in which the files are found. For example,
webmaster@1 2593 * 'modules' will search in both modules/ and
webmaster@1 2594 * sites/somesite/modules/.
webmaster@1 2595 * @param $key
webmaster@1 2596 * The key to be passed to file_scan_directory().
webmaster@1 2597 * @param $min_depth
webmaster@1 2598 * Minimum depth of directories to return files from.
webmaster@1 2599 *
webmaster@1 2600 * @return
webmaster@1 2601 * An array of file objects of the specified type.
webmaster@1 2602 */
webmaster@1 2603 function drupal_system_listing($mask, $directory, $key = 'name', $min_depth = 1) {
webmaster@1 2604 global $profile;
webmaster@1 2605 $config = conf_path();
webmaster@1 2606
webmaster@1 2607 // When this function is called during Drupal's initial installation process,
webmaster@1 2608 // the name of the profile that's about to be installed is stored in the global
webmaster@1 2609 // $profile variable. At all other times, the standard Drupal systems variable
webmaster@1 2610 // table contains the name of the current profile, and we can call variable_get()
webmaster@1 2611 // to determine what one is active.
webmaster@1 2612 if (!isset($profile)) {
webmaster@1 2613 $profile = variable_get('install_profile', 'default');
webmaster@1 2614 }
webmaster@1 2615 $searchdir = array($directory);
webmaster@1 2616 $files = array();
webmaster@1 2617
webmaster@1 2618 // Always search sites/all/* as well as the global directories
webmaster@1 2619 $searchdir[] = 'sites/all/'. $directory;
webmaster@1 2620
webmaster@1 2621 // The 'profiles' directory contains pristine collections of modules and
webmaster@1 2622 // themes as organized by a distribution. It is pristine in the same way
webmaster@1 2623 // that /modules is pristine for core; users should avoid changing anything
webmaster@1 2624 // there in favor of sites/all or sites/<domain> directories.
webmaster@1 2625 if (file_exists("profiles/$profile/$directory")) {
webmaster@1 2626 $searchdir[] = "profiles/$profile/$directory";
webmaster@1 2627 }
webmaster@1 2628
webmaster@1 2629 if (file_exists("$config/$directory")) {
webmaster@1 2630 $searchdir[] = "$config/$directory";
webmaster@1 2631 }
webmaster@1 2632
webmaster@1 2633 // Get current list of items
webmaster@1 2634 foreach ($searchdir as $dir) {
webmaster@1 2635 $files = array_merge($files, file_scan_directory($dir, $mask, array('.', '..', 'CVS'), 0, TRUE, $key, $min_depth));
webmaster@1 2636 }
webmaster@1 2637
webmaster@1 2638 return $files;
webmaster@1 2639 }
webmaster@1 2640
webmaster@1 2641
webmaster@1 2642 /**
webmaster@1 2643 * This dispatch function hands off structured Drupal arrays to type-specific
webmaster@1 2644 * *_alter implementations. It ensures a consistent interface for all altering
webmaster@1 2645 * operations.
webmaster@1 2646 *
webmaster@1 2647 * @param $type
webmaster@1 2648 * The data type of the structured array. 'form', 'links',
webmaster@1 2649 * 'node_content', and so on are several examples.
webmaster@1 2650 * @param $data
webmaster@1 2651 * The structured array to be altered.
webmaster@1 2652 * @param ...
webmaster@1 2653 * Any additional params will be passed on to the called
webmaster@1 2654 * hook_$type_alter functions.
webmaster@1 2655 */
webmaster@1 2656 function drupal_alter($type, &$data) {
webmaster@1 2657 // PHP's func_get_args() always returns copies of params, not references, so
webmaster@1 2658 // drupal_alter() can only manipulate data that comes in via the required first
webmaster@1 2659 // param. For the edge case functions that must pass in an arbitrary number of
webmaster@1 2660 // alterable parameters (hook_form_alter() being the best example), an array of
webmaster@1 2661 // those params can be placed in the __drupal_alter_by_ref key of the $data
webmaster@1 2662 // array. This is somewhat ugly, but is an unavoidable consequence of a flexible
webmaster@1 2663 // drupal_alter() function, and the limitations of func_get_args().
webmaster@1 2664 // @todo: Remove this in Drupal 7.
webmaster@1 2665 if (is_array($data) && isset($data['__drupal_alter_by_ref'])) {
webmaster@1 2666 $by_ref_parameters = $data['__drupal_alter_by_ref'];
webmaster@1 2667 unset($data['__drupal_alter_by_ref']);
webmaster@1 2668 }
webmaster@1 2669
webmaster@1 2670 // Hang onto a reference to the data array so that it isn't blown away later.
webmaster@1 2671 // Also, merge in any parameters that need to be passed by reference.
webmaster@1 2672 $args = array(&$data);
webmaster@1 2673 if (isset($by_ref_parameters)) {
webmaster@1 2674 $args = array_merge($args, $by_ref_parameters);
webmaster@1 2675 }
webmaster@1 2676
webmaster@1 2677 // Now, use func_get_args() to pull in any additional parameters passed into
webmaster@1 2678 // the drupal_alter() call.
webmaster@1 2679 $additional_args = func_get_args();
webmaster@1 2680 array_shift($additional_args);
webmaster@1 2681 array_shift($additional_args);
webmaster@1 2682 $args = array_merge($args, $additional_args);
webmaster@1 2683
webmaster@1 2684 foreach (module_implements($type .'_alter') as $module) {
webmaster@1 2685 $function = $module .'_'. $type .'_alter';
webmaster@1 2686 call_user_func_array($function, $args);
webmaster@1 2687 }
webmaster@1 2688 }
webmaster@1 2689
webmaster@1 2690
webmaster@1 2691 /**
webmaster@1 2692 * Renders HTML given a structured array tree.
webmaster@1 2693 *
webmaster@1 2694 * Recursively iterates over each of the array elements, generating HTML code.
webmaster@1 2695 * This function is usually called from within a another function, like
webmaster@1 2696 * drupal_get_form() or node_view().
webmaster@1 2697 *
webmaster@1 2698 * @param $elements
webmaster@1 2699 * The structured array describing the data to be rendered.
webmaster@1 2700 * @return
webmaster@1 2701 * The rendered HTML.
webmaster@1 2702 */
webmaster@1 2703 function drupal_render(&$elements) {
webmaster@1 2704 if (!isset($elements) || (isset($elements['#access']) && !$elements['#access'])) {
webmaster@1 2705 return NULL;
webmaster@1 2706 }
webmaster@1 2707
webmaster@1 2708 // If the default values for this element haven't been loaded yet, populate
webmaster@1 2709 // them.
webmaster@1 2710 if (!isset($elements['#defaults_loaded']) || !$elements['#defaults_loaded']) {
webmaster@1 2711 if ((!empty($elements['#type'])) && ($info = _element_info($elements['#type']))) {
webmaster@1 2712 $elements += $info;
webmaster@1 2713 }
webmaster@1 2714 }
webmaster@1 2715
webmaster@1 2716 // Make any final changes to the element before it is rendered. This means
webmaster@1 2717 // that the $element or the children can be altered or corrected before the
webmaster@1 2718 // element is rendered into the final text.
webmaster@1 2719 if (isset($elements['#pre_render'])) {
webmaster@1 2720 foreach ($elements['#pre_render'] as $function) {
webmaster@1 2721 if (function_exists($function)) {
webmaster@1 2722 $elements = $function($elements);
webmaster@1 2723 }
webmaster@1 2724 }
webmaster@1 2725 }
webmaster@1 2726
webmaster@1 2727 $content = '';
webmaster@1 2728 // Either the elements did not go through form_builder or one of the children
webmaster@1 2729 // has a #weight.
webmaster@1 2730 if (!isset($elements['#sorted'])) {
webmaster@1 2731 uasort($elements, "element_sort");
webmaster@1 2732 }
webmaster@1 2733 $elements += array('#title' => NULL, '#description' => NULL);
webmaster@1 2734 if (!isset($elements['#children'])) {
webmaster@1 2735 $children = element_children($elements);
webmaster@7 2736 // Render all the children that use a theme function.
webmaster@1 2737 if (isset($elements['#theme']) && empty($elements['#theme_used'])) {
webmaster@1 2738 $elements['#theme_used'] = TRUE;
webmaster@1 2739
webmaster@1 2740 $previous = array();
webmaster@1 2741 foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
webmaster@1 2742 $previous[$key] = isset($elements[$key]) ? $elements[$key] : NULL;
webmaster@1 2743 }
webmaster@1 2744 // If we rendered a single element, then we will skip the renderer.
webmaster@1 2745 if (empty($children)) {
webmaster@1 2746 $elements['#printed'] = TRUE;
webmaster@1 2747 }
webmaster@1 2748 else {
webmaster@1 2749 $elements['#value'] = '';
webmaster@1 2750 }
webmaster@1 2751 $elements['#type'] = 'markup';
webmaster@1 2752
webmaster@1 2753 unset($elements['#prefix'], $elements['#suffix']);
webmaster@1 2754 $content = theme($elements['#theme'], $elements);
webmaster@1 2755
webmaster@1 2756 foreach (array('#value', '#type', '#prefix', '#suffix') as $key) {
webmaster@1 2757 $elements[$key] = isset($previous[$key]) ? $previous[$key] : NULL;
webmaster@1 2758 }
webmaster@1 2759 }
webmaster@7 2760 // Render each of the children using drupal_render and concatenate them.
webmaster@1 2761 if (!isset($content) || $content === '') {
webmaster@1 2762 foreach ($children as $key) {
webmaster@1 2763 $content .= drupal_render($elements[$key]);
webmaster@1 2764 }
webmaster@1 2765 }
webmaster@1 2766 }
webmaster@1 2767 if (isset($content) && $content !== '') {
webmaster@1 2768 $elements['#children'] = $content;
webmaster@1 2769 }
webmaster@1 2770
webmaster@1 2771 // Until now, we rendered the children, here we render the element itself
webmaster@1 2772 if (!isset($elements['#printed'])) {
webmaster@1 2773 $content = theme(!empty($elements['#type']) ? $elements['#type'] : 'markup', $elements);
webmaster@1 2774 $elements['#printed'] = TRUE;
webmaster@1 2775 }
webmaster@1 2776
webmaster@1 2777 if (isset($content) && $content !== '') {
webmaster@1 2778 // Filter the outputted content and make any last changes before the
webmaster@1 2779 // content is sent to the browser. The changes are made on $content
webmaster@1 2780 // which allows the output'ed text to be filtered.
webmaster@1 2781 if (isset($elements['#post_render'])) {
webmaster@1 2782 foreach ($elements['#post_render'] as $function) {
webmaster@1 2783 if (function_exists($function)) {
webmaster@1 2784 $content = $function($content, $elements);
webmaster@1 2785 }
webmaster@1 2786 }
webmaster@1 2787 }
webmaster@1 2788 $prefix = isset($elements['#prefix']) ? $elements['#prefix'] : '';
webmaster@1 2789 $suffix = isset($elements['#suffix']) ? $elements['#suffix'] : '';
webmaster@1 2790 return $prefix . $content . $suffix;
webmaster@1 2791 }
webmaster@1 2792 }
webmaster@1 2793
webmaster@1 2794 /**
webmaster@1 2795 * Function used by uasort to sort structured arrays by weight.
webmaster@1 2796 */
webmaster@1 2797 function element_sort($a, $b) {
webmaster@1 2798 $a_weight = (is_array($a) && isset($a['#weight'])) ? $a['#weight'] : 0;
webmaster@1 2799 $b_weight = (is_array($b) && isset($b['#weight'])) ? $b['#weight'] : 0;
webmaster@1 2800 if ($a_weight == $b_weight) {
webmaster@1 2801 return 0;
webmaster@1 2802 }
webmaster@1 2803 return ($a_weight < $b_weight) ? -1 : 1;
webmaster@1 2804 }
webmaster@1 2805
webmaster@1 2806 /**
webmaster@1 2807 * Check if the key is a property.
webmaster@1 2808 */
webmaster@1 2809 function element_property($key) {
webmaster@1 2810 return $key[0] == '#';
webmaster@1 2811 }
webmaster@1 2812
webmaster@1 2813 /**
webmaster@1 2814 * Get properties of a structured array element. Properties begin with '#'.
webmaster@1 2815 */
webmaster@1 2816 function element_properties($element) {
webmaster@1 2817 return array_filter(array_keys((array) $element), 'element_property');
webmaster@1 2818 }
webmaster@1 2819
webmaster@1 2820 /**
webmaster@1 2821 * Check if the key is a child.
webmaster@1 2822 */
webmaster@1 2823 function element_child($key) {
webmaster@1 2824 return !isset($key[0]) || $key[0] != '#';
webmaster@1 2825 }
webmaster@1 2826
webmaster@1 2827 /**
webmaster@1 2828 * Get keys of a structured array tree element that are not properties (i.e., do not begin with '#').
webmaster@1 2829 */
webmaster@1 2830 function element_children($element) {
webmaster@1 2831 return array_filter(array_keys((array) $element), 'element_child');
webmaster@1 2832 }
webmaster@1 2833
webmaster@1 2834 /**
webmaster@1 2835 * Provide theme registration for themes across .inc files.
webmaster@1 2836 */
webmaster@1 2837 function drupal_common_theme() {
webmaster@1 2838 return array(
webmaster@1 2839 // theme.inc
webmaster@1 2840 'placeholder' => array(
webmaster@1 2841 'arguments' => array('text' => NULL)
webmaster@1 2842 ),
webmaster@1 2843 'page' => array(
webmaster@1 2844 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
webmaster@1 2845 'template' => 'page',
webmaster@1 2846 ),
webmaster@1 2847 'maintenance_page' => array(
webmaster@1 2848 'arguments' => array('content' => NULL, 'show_blocks' => TRUE, 'show_messages' => TRUE),
webmaster@1 2849 'template' => 'maintenance-page',
webmaster@1 2850 ),
webmaster@1 2851 'update_page' => array(
webmaster@1 2852 'arguments' => array('content' => NULL, 'show_messages' => TRUE),
webmaster@1 2853 ),
webmaster@1 2854 'install_page' => array(
webmaster@1 2855 'arguments' => array('content' => NULL),
webmaster@1 2856 ),
webmaster@1 2857 'task_list' => array(
webmaster@1 2858 'arguments' => array('items' => NULL, 'active' => NULL),
webmaster@1 2859 ),
webmaster@1 2860 'status_messages' => array(
webmaster@1 2861 'arguments' => array('display' => NULL),
webmaster@1 2862 ),
webmaster@1 2863 'links' => array(
webmaster@1 2864 'arguments' => array('links' => NULL, 'attributes' => array('class' => 'links')),
webmaster@1 2865 ),
webmaster@1 2866 'image' => array(
webmaster@1 2867 'arguments' => array('path' => NULL, 'alt' => '', 'title' => '', 'attributes' => NULL, 'getsize' => TRUE),
webmaster@1 2868 ),
webmaster@1 2869 'breadcrumb' => array(
webmaster@1 2870 'arguments' => array('breadcrumb' => NULL),
webmaster@1 2871 ),
webmaster@1 2872 'help' => array(
webmaster@1 2873 'arguments' => array(),
webmaster@1 2874 ),
webmaster@1 2875 'submenu' => array(
webmaster@1 2876 'arguments' => array('links' => NULL),
webmaster@1 2877 ),
webmaster@1 2878 'table' => array(
webmaster@1 2879 'arguments' => array('header' => NULL, 'rows' => NULL, 'attributes' => array(), 'caption' => NULL),
webmaster@1 2880 ),
webmaster@1 2881 'table_select_header_cell' => array(
webmaster@1 2882 'arguments' => array(),
webmaster@1 2883 ),
webmaster@1 2884 'tablesort_indicator' => array(
webmaster@1 2885 'arguments' => array('style' => NULL),
webmaster@1 2886 ),
webmaster@1 2887 'box' => array(
webmaster@1 2888 'arguments' => array('title' => NULL, 'content' => NULL, 'region' => 'main'),
webmaster@1 2889 'template' => 'box',
webmaster@1 2890 ),
webmaster@1 2891 'block' => array(
webmaster@1 2892 'arguments' => array('block' => NULL),
webmaster@1 2893 'template' => 'block',
webmaster@1 2894 ),
webmaster@1 2895 'mark' => array(
webmaster@1 2896 'arguments' => array('type' => MARK_NEW),
webmaster@1 2897 ),
webmaster@1 2898 'item_list' => array(
webmaster@1 2899 'arguments' => array('items' => array(), 'title' => NULL, 'type' => 'ul', 'attributes' => NULL),
webmaster@1 2900 ),
webmaster@1 2901 'more_help_link' => array(
webmaster@1 2902 'arguments' => array('url' => NULL),
webmaster@1 2903 ),
webmaster@1 2904 'xml_icon' => array(
webmaster@1 2905 'arguments' => array('url' => NULL),
webmaster@1 2906 ),
webmaster@1 2907 'feed_icon' => array(
webmaster@1 2908 'arguments' => array('url' => NULL, 'title' => NULL),
webmaster@1 2909 ),
webmaster@1 2910 'more_link' => array(
webmaster@1 2911 'arguments' => array('url' => NULL, 'title' => NULL)
webmaster@1 2912 ),
webmaster@1 2913 'closure' => array(
webmaster@1 2914 'arguments' => array('main' => 0),
webmaster@1 2915 ),
webmaster@1 2916 'blocks' => array(
webmaster@1 2917 'arguments' => array('region' => NULL),
webmaster@1 2918 ),
webmaster@1 2919 'username' => array(
webmaster@1 2920 'arguments' => array('object' => NULL),
webmaster@1 2921 ),
webmaster@1 2922 'progress_bar' => array(
webmaster@1 2923 'arguments' => array('percent' => NULL, 'message' => NULL),
webmaster@1 2924 ),
webmaster@1 2925 'indentation' => array(
webmaster@1 2926 'arguments' => array('size' => 1),
webmaster@1 2927 ),
webmaster@1 2928 // from pager.inc
webmaster@1 2929 'pager' => array(
webmaster@1 2930 'arguments' => array('tags' => array(), 'limit' => 10, 'element' => 0, 'parameters' => array()),
webmaster@1 2931 ),
webmaster@1 2932 'pager_first' => array(
webmaster@1 2933 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
webmaster@1 2934 ),
webmaster@1 2935 'pager_previous' => array(
webmaster@1 2936 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
webmaster@1 2937 ),
webmaster@1 2938 'pager_next' => array(
webmaster@1 2939 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'interval' => 1, 'parameters' => array()),
webmaster@1 2940 ),
webmaster@1 2941 'pager_last' => array(
webmaster@1 2942 'arguments' => array('text' => NULL, 'limit' => NULL, 'element' => 0, 'parameters' => array()),
webmaster@1 2943 ),
webmaster@1 2944 'pager_link' => array(
webmaster@1 2945 'arguments' => array('text' => NULL, 'page_new' => NULL, 'element' => NULL, 'parameters' => array(), 'attributes' => array()),
webmaster@1 2946 ),
webmaster@1 2947 // from locale.inc
webmaster@1 2948 'locale_admin_manage_screen' => array(
webmaster@1 2949 'arguments' => array('form' => NULL),
webmaster@1 2950 ),
webmaster@1 2951 // from menu.inc
webmaster@1 2952 'menu_item_link' => array(
webmaster@1 2953 'arguments' => array('item' => NULL),
webmaster@1 2954 ),
webmaster@1 2955 'menu_tree' => array(
webmaster@1 2956 'arguments' => array('tree' => NULL),
webmaster@1 2957 ),
webmaster@1 2958 'menu_item' => array(
webmaster@1 2959 'arguments' => array('link' => NULL, 'has_children' => NULL, 'menu' => ''),
webmaster@1 2960 ),
webmaster@1 2961 'menu_local_task' => array(
webmaster@1 2962 'arguments' => array('link' => NULL, 'active' => FALSE),
webmaster@1 2963 ),
webmaster@1 2964 'menu_local_tasks' => array(
webmaster@1 2965 'arguments' => array(),
webmaster@1 2966 ),
webmaster@1 2967 // from form.inc
webmaster@1 2968 'select' => array(
webmaster@1 2969 'arguments' => array('element' => NULL),
webmaster@1 2970 ),
webmaster@1 2971 'fieldset' => array(
webmaster@1 2972 'arguments' => array('element' => NULL),
webmaster@1 2973 ),
webmaster@1 2974 'radio' => array(
webmaster@1 2975 'arguments' => array('element' => NULL),
webmaster@1 2976 ),
webmaster@1 2977 'radios' => array(
webmaster@1 2978 'arguments' => array('element' => NULL),
webmaster@1 2979 ),
webmaster@1 2980 'password_confirm' => array(
webmaster@1 2981 'arguments' => array('element' => NULL),
webmaster@1 2982 ),
webmaster@1 2983 'date' => array(
webmaster@1 2984 'arguments' => array('element' => NULL),
webmaster@1 2985 ),
webmaster@1 2986 'item' => array(
webmaster@1 2987 'arguments' => array('element' => NULL),
webmaster@1 2988 ),
webmaster@1 2989 'checkbox' => array(
webmaster@1 2990 'arguments' => array('element' => NULL),
webmaster@1 2991 ),
webmaster@1 2992 'checkboxes' => array(
webmaster@1 2993 'arguments' => array('element' => NULL),
webmaster@1 2994 ),
webmaster@1 2995 'submit' => array(
webmaster@1 2996 'arguments' => array('element' => NULL),
webmaster@1 2997 ),
webmaster@1 2998 'button' => array(
webmaster@1 2999 'arguments' => array('element' => NULL),
webmaster@1 3000 ),
webmaster@1 3001 'image_button' => array(
webmaster@1 3002 'arguments' => array('element' => NULL),
webmaster@1 3003 ),
webmaster@1 3004 'hidden' => array(
webmaster@1 3005 'arguments' => array('element' => NULL),
webmaster@1 3006 ),
webmaster@1 3007 'token' => array(
webmaster@1 3008 'arguments' => array('element' => NULL),
webmaster@1 3009 ),
webmaster@1 3010 'textfield' => array(
webmaster@1 3011 'arguments' => array('element' => NULL),
webmaster@1 3012 ),
webmaster@1 3013 'form' => array(
webmaster@1 3014 'arguments' => array('element' => NULL),
webmaster@1 3015 ),
webmaster@1 3016 'textarea' => array(
webmaster@1 3017 'arguments' => array('element' => NULL),
webmaster@1 3018 ),
webmaster@1 3019 'markup' => array(
webmaster@1 3020 'arguments' => array('element' => NULL),
webmaster@1 3021 ),
webmaster@1 3022 'password' => array(
webmaster@1 3023 'arguments' => array('element' => NULL),
webmaster@1 3024 ),
webmaster@1 3025 'file' => array(
webmaster@1 3026 'arguments' => array('element' => NULL),
webmaster@1 3027 ),
webmaster@1 3028 'form_element' => array(
webmaster@1 3029 'arguments' => array('element' => NULL, 'value' => NULL),
webmaster@1 3030 ),
webmaster@1 3031 );
webmaster@1 3032 }
webmaster@1 3033
webmaster@1 3034 /**
webmaster@1 3035 * @ingroup schemaapi
webmaster@1 3036 * @{
webmaster@1 3037 */
webmaster@1 3038
webmaster@1 3039 /**
webmaster@1 3040 * Get the schema definition of a table, or the whole database schema.
webmaster@1 3041 *
webmaster@1 3042 * The returned schema will include any modifications made by any
webmaster@1 3043 * module that implements hook_schema_alter().
webmaster@1 3044 *
webmaster@1 3045 * @param $table
webmaster@1 3046 * The name of the table. If not given, the schema of all tables is returned.
webmaster@1 3047 * @param $rebuild
webmaster@1 3048 * If true, the schema will be rebuilt instead of retrieved from the cache.
webmaster@1 3049 */
webmaster@1 3050 function drupal_get_schema($table = NULL, $rebuild = FALSE) {
webmaster@1 3051 static $schema = array();
webmaster@1 3052
webmaster@1 3053 if (empty($schema) || $rebuild) {
webmaster@1 3054 // Try to load the schema from cache.
webmaster@1 3055 if (!$rebuild && $cached = cache_get('schema')) {
webmaster@1 3056 $schema = $cached->data;
webmaster@1 3057 }
webmaster@1 3058 // Otherwise, rebuild the schema cache.
webmaster@1 3059 else {
webmaster@1 3060 $schema = array();
webmaster@1 3061 // Load the .install files to get hook_schema.
webmaster@1 3062 module_load_all_includes('install');
webmaster@1 3063
webmaster@1 3064 // Invoke hook_schema for all modules.
webmaster@1 3065 foreach (module_implements('schema') as $module) {
webmaster@1 3066 $current = module_invoke($module, 'schema');
webmaster@1 3067 _drupal_initialize_schema($module, $current);
webmaster@1 3068 $schema = array_merge($schema, $current);
webmaster@1 3069 }
webmaster@1 3070
webmaster@1 3071 drupal_alter('schema', $schema);
webmaster@1 3072 cache_set('schema', $schema);
webmaster@1 3073 }
webmaster@1 3074 }
webmaster@1 3075
webmaster@1 3076 if (!isset($table)) {
webmaster@1 3077 return $schema;
webmaster@1 3078 }
webmaster@1 3079 elseif (isset($schema[$table])) {
webmaster@1 3080 return $schema[$table];
webmaster@1 3081 }
webmaster@1 3082 else {
webmaster@1 3083 return FALSE;
webmaster@1 3084 }
webmaster@1 3085 }
webmaster@1 3086
webmaster@1 3087 /**
webmaster@1 3088 * Create all tables that a module defines in its hook_schema().
webmaster@1 3089 *
webmaster@1 3090 * Note: This function does not pass the module's schema through
webmaster@1 3091 * hook_schema_alter(). The module's tables will be created exactly as the
webmaster@1 3092 * module defines them.
webmaster@1 3093 *
webmaster@1 3094 * @param $module
webmaster@1 3095 * The module for which the tables will be created.
webmaster@1 3096 * @return
webmaster@1 3097 * An array of arrays with the following key/value pairs:
webmaster@7 3098 * - success: a boolean indicating whether the query succeeded.
webmaster@7 3099 * - query: the SQL query(s) executed, passed through check_plain().
webmaster@1 3100 */
webmaster@1 3101 function drupal_install_schema($module) {
webmaster@1 3102 $schema = drupal_get_schema_unprocessed($module);
webmaster@1 3103 _drupal_initialize_schema($module, $schema);
webmaster@1 3104
webmaster@1 3105 $ret = array();
webmaster@1 3106 foreach ($schema as $name => $table) {
webmaster@1 3107 db_create_table($ret, $name, $table);
webmaster@1 3108 }
webmaster@1 3109 return $ret;
webmaster@1 3110 }
webmaster@1 3111
webmaster@1 3112 /**
webmaster@1 3113 * Remove all tables that a module defines in its hook_schema().
webmaster@1 3114 *
webmaster@1 3115 * Note: This function does not pass the module's schema through
webmaster@1 3116 * hook_schema_alter(). The module's tables will be created exactly as the
webmaster@1 3117 * module defines them.
webmaster@1 3118 *
webmaster@1 3119 * @param $module
webmaster@1 3120 * The module for which the tables will be removed.
webmaster@1 3121 * @return
webmaster@1 3122 * An array of arrays with the following key/value pairs:
webmaster@7 3123 * - success: a boolean indicating whether the query succeeded.
webmaster@7 3124 * - query: the SQL query(s) executed, passed through check_plain().
webmaster@1 3125 */
webmaster@1 3126 function drupal_uninstall_schema($module) {
webmaster@1 3127 $schema = drupal_get_schema_unprocessed($module);
webmaster@1 3128 _drupal_initialize_schema($module, $schema);
webmaster@1 3129
webmaster@1 3130 $ret = array();
webmaster@1 3131 foreach ($schema as $table) {
webmaster@1 3132 db_drop_table($ret, $table['name']);
webmaster@1 3133 }
webmaster@1 3134 return $ret;
webmaster@1 3135 }
webmaster@1 3136
webmaster@1 3137 /**
webmaster@1 3138 * Returns the unprocessed and unaltered version of a module's schema.
webmaster@1 3139 *
webmaster@1 3140 * Use this function only if you explicitly need the original
webmaster@1 3141 * specification of a schema, as it was defined in a module's
webmaster@1 3142 * hook_schema(). No additional default values will be set,
webmaster@1 3143 * hook_schema_alter() is not invoked and these unprocessed
webmaster@1 3144 * definitions won't be cached.
webmaster@1 3145 *
webmaster@1 3146 * This function can be used to retrieve a schema specification in
webmaster@1 3147 * hook_schema(), so it allows you to derive your tables from existing
webmaster@1 3148 * specifications.
webmaster@1 3149 *
webmaster@1 3150 * It is also used by drupal_install_schema() and
webmaster@1 3151 * drupal_uninstall_schema() to ensure that a module's tables are
webmaster@1 3152 * created exactly as specified without any changes introduced by a
webmaster@1 3153 * module that implements hook_schema_alter().
webmaster@1 3154 *
webmaster@1 3155 * @param $module
webmaster@1 3156 * The module to which the table belongs.
webmaster@1 3157 * @param $table
webmaster@1 3158 * The name of the table. If not given, the module's complete schema
webmaster@1 3159 * is returned.
webmaster@1 3160 */
webmaster@1 3161 function drupal_get_schema_unprocessed($module, $table = NULL) {
webmaster@1 3162 // Load the .install file to get hook_schema.
webmaster@1 3163 module_load_include('install', $module);
webmaster@1 3164 $schema = module_invoke($module, 'schema');
webmaster@1 3165
webmaster@1 3166 if (!is_null($table) && isset($schema[$table])) {
webmaster@1 3167 return $schema[$table];
webmaster@1 3168 }
webmaster@1 3169 else {
webmaster@1 3170 return $schema;
webmaster@1 3171 }
webmaster@1 3172 }
webmaster@1 3173
webmaster@1 3174 /**
webmaster@1 3175 * Fill in required default values for table definitions returned by hook_schema().
webmaster@1 3176 *
webmaster@1 3177 * @param $module
webmaster@1 3178 * The module for which hook_schema() was invoked.
webmaster@1 3179 * @param $schema
webmaster@1 3180 * The schema definition array as it was returned by the module's
webmaster@1 3181 * hook_schema().
webmaster@1 3182 */
webmaster@1 3183 function _drupal_initialize_schema($module, &$schema) {
webmaster@1 3184 // Set the name and module key for all tables.
webmaster@1 3185 foreach ($schema as $name => $table) {
webmaster@1 3186 if (empty($table['module'])) {
webmaster@1 3187 $schema[$name]['module'] = $module;
webmaster@1 3188 }
webmaster@1 3189 if (!isset($table['name'])) {
webmaster@1 3190 $schema[$name]['name'] = $name;
webmaster@1 3191 }
webmaster@1 3192 }
webmaster@1 3193 }
webmaster@1 3194
webmaster@1 3195 /**
webmaster@1 3196 * Retrieve a list of fields from a table schema. The list is suitable for use in a SQL query.
webmaster@1 3197 *
webmaster@1 3198 * @param $table
webmaster@1 3199 * The name of the table from which to retrieve fields.
webmaster@1 3200 * @param
webmaster@1 3201 * An optional prefix to to all fields.
webmaster@1 3202 *
webmaster@1 3203 * @return An array of fields.
webmaster@1 3204 **/
webmaster@1 3205 function drupal_schema_fields_sql($table, $prefix = NULL) {
webmaster@1 3206 $schema = drupal_get_schema($table);
webmaster@1 3207 $fields = array_keys($schema['fields']);
webmaster@1 3208 if ($prefix) {
webmaster@1 3209 $columns = array();
webmaster@1 3210 foreach ($fields as $field) {
webmaster@1 3211 $columns[] = "$prefix.$field";
webmaster@1 3212 }
webmaster@1 3213 return $columns;
webmaster@1 3214 }
webmaster@1 3215 else {
webmaster@1 3216 return $fields;
webmaster@1 3217 }
webmaster@1 3218 }
webmaster@1 3219
webmaster@1 3220 /**
webmaster@1 3221 * Save a record to the database based upon the schema.
webmaster@1 3222 *
webmaster@1 3223 * Default values are filled in for missing items, and 'serial' (auto increment)
webmaster@1 3224 * types are filled in with IDs.
webmaster@1 3225 *
webmaster@1 3226 * @param $table
webmaster@1 3227 * The name of the table; this must exist in schema API.
webmaster@1 3228 * @param $object
webmaster@1 3229 * The object to write. This is a reference, as defaults according to
webmaster@1 3230 * the schema may be filled in on the object, as well as ID on the serial
webmaster@1 3231 * type(s). Both array an object types may be passed.
webmaster@1 3232 * @param $update
webmaster@1 3233 * If this is an update, specify the primary keys' field names. It is the
webmaster@1 3234 * caller's responsibility to know if a record for this object already
webmaster@1 3235 * exists in the database. If there is only 1 key, you may pass a simple string.
webmaster@1 3236 * @return
webmaster@1 3237 * Failure to write a record will return FALSE. Otherwise SAVED_NEW or
webmaster@1 3238 * SAVED_UPDATED is returned depending on the operation performed. The
webmaster@1 3239 * $object parameter contains values for any serial fields defined by
webmaster@1 3240 * the $table. For example, $object->nid will be populated after inserting
webmaster@1 3241 * a new node.
webmaster@1 3242 */
webmaster@1 3243 function drupal_write_record($table, &$object, $update = array()) {
webmaster@1 3244 // Standardize $update to an array.
webmaster@1 3245 if (is_string($update)) {
webmaster@1 3246 $update = array($update);
webmaster@1 3247 }
webmaster@1 3248
webmaster@7 3249 $schema = drupal_get_schema($table);
webmaster@7 3250 if (empty($schema)) {
webmaster@7 3251 return FALSE;
webmaster@7 3252 }
webmaster@9 3253
webmaster@1 3254 // Convert to an object if needed.
webmaster@1 3255 if (is_array($object)) {
webmaster@1 3256 $object = (object) $object;
webmaster@1 3257 $array = TRUE;
webmaster@1 3258 }
webmaster@1 3259 else {
webmaster@1 3260 $array = FALSE;
webmaster@1 3261 }
webmaster@1 3262
webmaster@1 3263 $fields = $defs = $values = $serials = $placeholders = array();
webmaster@1 3264
webmaster@1 3265 // Go through our schema, build SQL, and when inserting, fill in defaults for
webmaster@1 3266 // fields that are not set.
webmaster@1 3267 foreach ($schema['fields'] as $field => $info) {
webmaster@1 3268 // Special case -- skip serial types if we are updating.
webmaster@1 3269 if ($info['type'] == 'serial' && count($update)) {
webmaster@1 3270 continue;
webmaster@1 3271 }
webmaster@1 3272
webmaster@1 3273 // For inserts, populate defaults from Schema if not already provided
webmaster@1 3274 if (!isset($object->$field) && !count($update) && isset($info['default'])) {
webmaster@1 3275 $object->$field = $info['default'];
webmaster@1 3276 }
webmaster@1 3277
webmaster@1 3278 // Track serial fields so we can helpfully populate them after the query.
webmaster@1 3279 if ($info['type'] == 'serial') {
webmaster@1 3280 $serials[] = $field;
webmaster@1 3281 // Ignore values for serials when inserting data. Unsupported.
webmaster@1 3282 unset($object->$field);
webmaster@1 3283 }
webmaster@1 3284
webmaster@1 3285 // Build arrays for the fields, placeholders, and values in our query.
webmaster@1 3286 if (isset($object->$field)) {
webmaster@1 3287 $fields[] = $field;
webmaster@1 3288 $placeholders[] = db_type_placeholder($info['type']);
webmaster@1 3289
webmaster@1 3290 if (empty($info['serialize'])) {
webmaster@1 3291 $values[] = $object->$field;
webmaster@1 3292 }
webmaster@1 3293 else {
webmaster@1 3294 $values[] = serialize($object->$field);
webmaster@1 3295 }
webmaster@1 3296 }
webmaster@1 3297 }
webmaster@1 3298
webmaster@1 3299 // Build the SQL.
webmaster@1 3300 $query = '';
webmaster@1 3301 if (!count($update)) {
webmaster@1 3302 $query = "INSERT INTO {". $table ."} (". implode(', ', $fields) .') VALUES ('. implode(', ', $placeholders) .')';
webmaster@1 3303 $return = SAVED_NEW;
webmaster@1 3304 }
webmaster@1 3305 else {
webmaster@1 3306 $query = '';
webmaster@1 3307 foreach ($fields as $id => $field) {
webmaster@1 3308 if ($query) {
webmaster@1 3309 $query .= ', ';
webmaster@1 3310 }
webmaster@1 3311 $query .= $field .' = '. $placeholders[$id];
webmaster@1 3312 }
webmaster@1 3313
webmaster@1 3314 foreach ($update as $key){
webmaster@1 3315 $conditions[] = "$key = ". db_type_placeholder($schema['fields'][$key]['type']);
webmaster@1 3316 $values[] = $object->$key;
webmaster@1 3317 }
webmaster@1 3318
webmaster@1 3319 $query = "UPDATE {". $table ."} SET $query WHERE ". implode(' AND ', $conditions);
webmaster@1 3320 $return = SAVED_UPDATED;
webmaster@1 3321 }
webmaster@1 3322
webmaster@1 3323 // Execute the SQL.
webmaster@1 3324 if (db_query($query, $values)) {
webmaster@1 3325 if ($serials) {
webmaster@1 3326 // Get last insert ids and fill them in.
webmaster@1 3327 foreach ($serials as $field) {
webmaster@1 3328 $object->$field = db_last_insert_id($table, $field);
webmaster@1 3329 }
webmaster@1 3330 }
webmaster@1 3331 }
webmaster@7 3332 else {
webmaster@7 3333 $return = FALSE;
webmaster@7 3334 }
webmaster@7 3335
webmaster@7 3336 // If we began with an array, convert back so we don't surprise the caller.
webmaster@7 3337 if ($array) {
webmaster@7 3338 $object = (array) $object;
webmaster@7 3339 }
webmaster@7 3340
webmaster@7 3341 return $return;
webmaster@1 3342 }
webmaster@1 3343
webmaster@1 3344 /**
webmaster@1 3345 * @} End of "ingroup schemaapi".
webmaster@1 3346 */
webmaster@1 3347
webmaster@1 3348 /**
webmaster@1 3349 * Parse Drupal info file format.
webmaster@1 3350 *
webmaster@1 3351 * Files should use an ini-like format to specify values.
webmaster@1 3352 * White-space generally doesn't matter, except inside values.
webmaster@1 3353 * e.g.
webmaster@1 3354 *
webmaster@1 3355 * @verbatim
webmaster@1 3356 * key = value
webmaster@1 3357 * key = "value"
webmaster@1 3358 * key = 'value'
webmaster@1 3359 * key = "multi-line
webmaster@1 3360 *
webmaster@1 3361 * value"
webmaster@1 3362 * key = 'multi-line
webmaster@1 3363 *
webmaster@1 3364 * value'
webmaster@1 3365 * key
webmaster@1 3366 * =
webmaster@1 3367 * 'value'
webmaster@1 3368 * @endverbatim
webmaster@1 3369 *
webmaster@1 3370 * Arrays are created using a GET-like syntax:
webmaster@1 3371 *
webmaster@1 3372 * @verbatim
webmaster@1 3373 * key[] = "numeric array"
webmaster@1 3374 * key[index] = "associative array"
webmaster@1 3375 * key[index][] = "nested numeric array"
webmaster@1 3376 * key[index][index] = "nested associative array"
webmaster@1 3377 * @endverbatim
webmaster@1 3378 *
webmaster@1 3379 * PHP constants are substituted in, but only when used as the entire value:
webmaster@1 3380 *
webmaster@1 3381 * Comments should start with a semi-colon at the beginning of a line.
webmaster@1 3382 *
webmaster@1 3383 * This function is NOT for placing arbitrary module-specific settings. Use
webmaster@1 3384 * variable_get() and variable_set() for that.
webmaster@1 3385 *
webmaster@1 3386 * Information stored in the module.info file:
webmaster@1 3387 * - name: The real name of the module for display purposes.
webmaster@1 3388 * - description: A brief description of the module.
webmaster@1 3389 * - dependencies: An array of shortnames of other modules this module depends on.
webmaster@1 3390 * - package: The name of the package of modules this module belongs to.
webmaster@1 3391 *
webmaster@1 3392 * Example of .info file:
webmaster@1 3393 * @verbatim
webmaster@1 3394 * name = Forum
webmaster@1 3395 * description = Enables threaded discussions about general topics.
webmaster@1 3396 * dependencies[] = taxonomy
webmaster@1 3397 * dependencies[] = comment
webmaster@1 3398 * package = Core - optional
webmaster@1 3399 * version = VERSION
webmaster@1 3400 * @endverbatim
webmaster@1 3401 *
webmaster@1 3402 * @param $filename
webmaster@1 3403 * The file we are parsing. Accepts file with relative or absolute path.
webmaster@1 3404 * @return
webmaster@1 3405 * The info array.
webmaster@1 3406 */
webmaster@1 3407 function drupal_parse_info_file($filename) {
webmaster@1 3408 $info = array();
webmaster@1 3409
webmaster@1 3410 if (!file_exists($filename)) {
webmaster@1 3411 return $info;
webmaster@1 3412 }
webmaster@1 3413
webmaster@1 3414 $data = file_get_contents($filename);
webmaster@1 3415 if (preg_match_all('
webmaster@1 3416 @^\s* # Start at the beginning of a line, ignoring leading whitespace
webmaster@1 3417 ((?:
webmaster@1 3418 [^=;\[\]]| # Key names cannot contain equal signs, semi-colons or square brackets,
webmaster@1 3419 \[[^\[\]]*\] # unless they are balanced and not nested
webmaster@1 3420 )+?)
webmaster@1 3421 \s*=\s* # Key/value pairs are separated by equal signs (ignoring white-space)
webmaster@1 3422 (?:
webmaster@1 3423 ("(?:[^"]|(?<=\\\\)")*")| # Double-quoted string, which may contain slash-escaped quotes/slashes
webmaster@1 3424 (\'(?:[^\']|(?<=\\\\)\')*\')| # Single-quoted string, which may contain slash-escaped quotes/slashes
webmaster@1 3425 ([^\r\n]*?) # Non-quoted string
webmaster@1 3426 )\s*$ # Stop at the next end of a line, ignoring trailing whitespace
webmaster@1 3427 @msx', $data, $matches, PREG_SET_ORDER)) {
webmaster@1 3428 foreach ($matches as $match) {
webmaster@1 3429 // Fetch the key and value string
webmaster@1 3430 $i = 0;
webmaster@1 3431 foreach (array('key', 'value1', 'value2', 'value3') as $var) {
webmaster@1 3432 $$var = isset($match[++$i]) ? $match[$i] : '';
webmaster@1 3433 }
webmaster@1 3434 $value = stripslashes(substr($value1, 1, -1)) . stripslashes(substr($value2, 1, -1)) . $value3;
webmaster@1 3435
webmaster@1 3436 // Parse array syntax
webmaster@1 3437 $keys = preg_split('/\]?\[/', rtrim($key, ']'));
webmaster@1 3438 $last = array_pop($keys);
webmaster@1 3439 $parent = &$info;
webmaster@1 3440
webmaster@1 3441 // Create nested arrays
webmaster@1 3442 foreach ($keys as $key) {
webmaster@1 3443 if ($key == '') {
webmaster@1 3444 $key = count($parent);
webmaster@1 3445 }
webmaster@1 3446 if (!isset($parent[$key]) || !is_array($parent[$key])) {
webmaster@1 3447 $parent[$key] = array();
webmaster@1 3448 }
webmaster@1 3449 $parent = &$parent[$key];
webmaster@1 3450 }
webmaster@1 3451
webmaster@1 3452 // Handle PHP constants
webmaster@1 3453 if (defined($value)) {
webmaster@1 3454 $value = constant($value);
webmaster@1 3455 }
webmaster@1 3456
webmaster@1 3457 // Insert actual value
webmaster@1 3458 if ($last == '') {
webmaster@1 3459 $last = count($parent);
webmaster@1 3460 }
webmaster@1 3461 $parent[$last] = $value;
webmaster@1 3462 }
webmaster@1 3463 }
webmaster@1 3464
webmaster@1 3465 return $info;
webmaster@1 3466 }
webmaster@1 3467
webmaster@1 3468 /**
webmaster@1 3469 * @return
webmaster@1 3470 * Array of the possible severity levels for log messages.
webmaster@1 3471 *
webmaster@1 3472 * @see watchdog
webmaster@1 3473 */
webmaster@1 3474 function watchdog_severity_levels() {
webmaster@1 3475 return array(
webmaster@1 3476 WATCHDOG_EMERG => t('emergency'),
webmaster@1 3477 WATCHDOG_ALERT => t('alert'),
webmaster@1 3478 WATCHDOG_CRITICAL => t('critical'),
webmaster@1 3479 WATCHDOG_ERROR => t('error'),
webmaster@1 3480 WATCHDOG_WARNING => t('warning'),
webmaster@1 3481 WATCHDOG_NOTICE => t('notice'),
webmaster@1 3482 WATCHDOG_INFO => t('info'),
webmaster@1 3483 WATCHDOG_DEBUG => t('debug'),
webmaster@1 3484 );
webmaster@1 3485 }
webmaster@1 3486
webmaster@1 3487
webmaster@1 3488 /**
webmaster@1 3489 * Explode a string of given tags into an array.
webmaster@1 3490 */
webmaster@1 3491 function drupal_explode_tags($tags) {
webmaster@1 3492 // This regexp allows the following types of user input:
webmaster@1 3493 // this, "somecompany, llc", "and ""this"" w,o.rks", foo bar
webmaster@1 3494 $regexp = '%(?:^|,\ *)("(?>[^"]*)(?>""[^"]* )*"|(?: [^",]*))%x';
webmaster@1 3495 preg_match_all($regexp, $tags, $matches);
webmaster@1 3496 $typed_tags = array_unique($matches[1]);
webmaster@1 3497
webmaster@1 3498 $tags = array();
webmaster@1 3499 foreach ($typed_tags as $tag) {
webmaster@1 3500 // If a user has escaped a term (to demonstrate that it is a group,
webmaster@1 3501 // or includes a comma or quote character), we remove the escape
webmaster@1 3502 // formatting so to save the term into the database as the user intends.
webmaster@1 3503 $tag = trim(str_replace('""', '"', preg_replace('/^"(.*)"$/', '\1', $tag)));
webmaster@1 3504 if ($tag != "") {
webmaster@1 3505 $tags[] = $tag;
webmaster@1 3506 }
webmaster@1 3507 }
webmaster@1 3508
webmaster@1 3509 return $tags;
webmaster@1 3510 }
webmaster@1 3511
webmaster@1 3512 /**
webmaster@1 3513 * Implode an array of tags into a string.
webmaster@1 3514 */
webmaster@1 3515 function drupal_implode_tags($tags) {
webmaster@1 3516 $encoded_tags = array();
webmaster@1 3517 foreach ($tags as $tag) {
webmaster@1 3518 // Commas and quotes in tag names are special cases, so encode them.
webmaster@1 3519 if (strpos($tag, ',') !== FALSE || strpos($tag, '"') !== FALSE) {
webmaster@1 3520 $tag = '"'. str_replace('"', '""', $tag) .'"';
webmaster@1 3521 }
webmaster@1 3522
webmaster@1 3523 $encoded_tags[] = $tag;
webmaster@1 3524 }
webmaster@1 3525 return implode(', ', $encoded_tags);
webmaster@1 3526 }
webmaster@1 3527
webmaster@1 3528 /**
webmaster@1 3529 * Flush all cached data on the site.
webmaster@1 3530 *
webmaster@1 3531 * Empties cache tables, rebuilds the menu cache and theme registries, and
webmaster@7 3532 * invokes a hook so that other modules' cache data can be cleared as well.
webmaster@1 3533 */
webmaster@1 3534 function drupal_flush_all_caches() {
webmaster@1 3535 // Change query-strings on css/js files to enforce reload for all users.
webmaster@1 3536 _drupal_flush_css_js();
webmaster@1 3537
webmaster@1 3538 drupal_clear_css_cache();
webmaster@1 3539 drupal_clear_js_cache();
webmaster@7 3540 system_theme_data();
webmaster@1 3541 drupal_rebuild_theme_registry();
webmaster@1 3542 menu_rebuild();
webmaster@1 3543 node_types_rebuild();
webmaster@1 3544 // Don't clear cache_form - in-progress form submissions may break.
webmaster@1 3545 // Ordered so clearing the page cache will always be the last action.
webmaster@1 3546 $core = array('cache', 'cache_block', 'cache_filter', 'cache_page');
webmaster@1 3547 $cache_tables = array_merge(module_invoke_all('flush_caches'), $core);
webmaster@1 3548 foreach ($cache_tables as $table) {
webmaster@1 3549 cache_clear_all('*', $table, TRUE);
webmaster@1 3550 }
webmaster@1 3551 }
webmaster@1 3552
webmaster@1 3553 /**
webmaster@1 3554 * Helper function to change query-strings on css/js files.
webmaster@1 3555 *
webmaster@1 3556 * Changes the character added to all css/js files as dummy query-string,
webmaster@1 3557 * so that all browsers are forced to reload fresh files. We keep
webmaster@1 3558 * 20 characters history (FIFO) to avoid repeats, but only the first
webmaster@1 3559 * (newest) character is actually used on urls, to keep them short.
webmaster@1 3560 * This is also called from update.php.
webmaster@1 3561 */
webmaster@1 3562 function _drupal_flush_css_js() {
webmaster@1 3563 $string_history = variable_get('css_js_query_string', '00000000000000000000');
webmaster@1 3564 $new_character = $string_history[0];
webmaster@1 3565 $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
webmaster@1 3566 while (strpos($string_history, $new_character) !== FALSE) {
webmaster@1 3567 $new_character = $characters[mt_rand(0, strlen($characters) - 1)];
webmaster@1 3568 }
webmaster@1 3569 variable_set('css_js_query_string', $new_character . substr($string_history, 0, 19));
webmaster@1 3570 }