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