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