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