This file was ported from Drupal's includes/common.inc
License:
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to:
The Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301,
USA
Author:
Brendon Crawford
Copyright:
2008 Brendon Crawford
Contact:
message144 at users dot sourceforge dot net
_fix_gpc_magic_files(item,
key)
Helper function to strip slashes from FILES skipping over the tmp_name keys
since PHP generates single backslashes for file paths on Windows systems.
format_date(timestamp,
type='medium',
format='',
timezone=None,
langcode=None)
Format a date with the given configured format or a custom format string.
drupal_add_js(data=None,
type_='plugin',
scope='php.header',
defer=False,
cache=True,
preprocess=True)
Add a JavaScript file, setting or inline code to the page.
drupal_add_tabledrag(table_id,
action,
relationship,
group,
subgroup=None,
source=None,
hidden=True,
limit=0)
Assist in adding the tableDrag JavaScript behavior to a themed table.
Set an HTTP response php.header for the current page.
Note: When sending a Content-Type php.header, always
include a 'charset' type,
too. This is necessary to avoid security bugs (e.g. UTF-7 XSS).
Prepare a destination query string for use in combination
with drupal_goto().
Used to direct the user back to the referring page after completing a form.
By default the current URL is returned. If a destination exists in the
previous request, that destination is returned. As such, a destination can
persist across multiple pages.
Send the user to a different Drupal page.
This issues an on-site HTTP redirect. The function makes sure the redirected
URL is formatted correctly.
Usually the redirected URL is constructed from this function's input
parameters. However you may override that behavior by setting a
destination in either the php.REQUEST-array (i.e. by using
the query string of an URI) or the php.REQUEST['edit']-array (i.e. by
using a hidden form field). This is used to direct the user back to
the proper page after completing a form. For example, after editing
a post on the 'admin/content/node'-page or after having logged on using the
'user login'-block in a sidebar. The function drupal_get_destination()
can be used to help set the destination URL.
Drupal will ensure that messages set by drupal_set_message() and other
session data are written to the database before the user is redirected.
This function ends the request; use it rather than a print theme('page')
statement in your menu callback.
Parameters:
path - A Drupal path or a full URL.
query - A query string component, if any.
fragment - A destination fragment identifier (named anchor).
http_response_code - Valid values for an actual "goto" as per RFC 2616 section 10.3 are:
- 301 Moved Permanently (the recommended value for most redirects)
- 302 Found (default in Drupal and PHP, sometimes used for spamming search
engines)
- 303 See Other
- 304 Not Modified
- 305 Use Proxy
- 307 Temporary Redirect (alternative to "503 Site Down for Maintenance")
Note: Other values are defined by RFC 2616, but are rarely used and poorly
supported.
Perform an HTTP request.
This is a flexible and powerful HTTP client implementation.
Correctly handles
php.GET, php.POST, PUT or any other HTTP requests. Handles redirects.
Parameters:
url - A string containing a fully qualified URI.
headers - An array containing an HTTP php.header : value pair.
method - A string defining the HTTP request to use.
data - A string containing data to include in the request.
retry - An integer representing how many times to retry the request in case of a
redirect.
Returns:
An object containing the HTTP request headers, response code, headers,
data and redirect status.
Note:
DRUPY:
This function has been modified to use urllib2.
Although it does not act exactly as before, it is
still good enough to get the job done.
Return object should look like this:
result:
Str error
Int code
Str request
Dict headers
Int redirect_code
Str redirect_url
Helper function to strip slashes from FILES skipping over the tmp_name keys
since PHP generates single backslashes for file paths on Windows systems.
tmp_name does not have backslashes added see
http://php.net/manual/en/features.file-upload.php#42280
Translate strings to the page language or a given language.
All human-readable text that will be displayed somewhere
within a page should
be run through the t() function.
Examples:
Parameters:
string - A string containing the English string to translate.
args - An associative array of replacements to make after translation. Incidences
of any key in this array are replaced with the corresponding value.
Based on the first character of the key, the value
is escaped and/or themed:
- !variable: inserted as is
- @variable: escape plain text to HTML (check_plain)
- %variable: escape text and theme as a placeholder for user-submitted
content (check_plain + theme_placeholder)
langcode - Optional language code to translate to a language other than what is used
to display the page.
Verify the syntax of the given URL.
This function should only be used on actual URLs. It should not be used for
Drupal menu paths, which can contain arbitrary characters.
Parameters:
url - The URL to verify.
absolute - Whether the URL is absolute (beginning with a scheme such as "http:").
Check if the current visitor (hostname/IP) is allowed to
proceed with the specified event.
The user is allowed to proceed if he did not trigger the
specified event more than threshold times per hour.
Parameters:
name - The name of the event.
number - The maximum number of the specified event per hour (per visitor).
Returns:
True if the user did not exceed the hourly threshold. False otherwise.
array - An array where each item represent an element and is either a:
- (key : value) pair (value)
- Associative array with fields:
- 'key': element name
- 'value': element contents
- 'attributes': associative array of element attributes
In both cases, 'value' can be a simple string, or it can be another array
with the same format as array itself for nesting.
Format a string containing a count of items.
This function ensures that the string is pluralized correctly. Since t() is
called by this function, make sure not to pass already-localized strings to
it.
For example:
Parameters:
count - The item count to display.
singular - The string for the singular case. Please make sure it is clear this is
singular, to ease translation (e.g. use "1 new comment"
instead of "1 new").
Do not use @count in the singular string.
plural - The string for the plural case. Please make sure it is clear
this is plural,
to ease translation. Use @count in place of the item count, as in "@count
new comments".
args - An associative array of replacements to make after translation. Incidences
of any key in this array are replaced with the corresponding value.
Based on the first character of the key, the value is
escaped and/or themed:
- !variable: inserted as is
- @variable: escape plain text to HTML (check_plain)
- %variable: escape text and theme as a placeholder for user-submitted
content (check_plain + theme_placeholder)
Note that you do not need to include @count in this array.
This replacement is done automatically for the plural case.
langcode - Optional language code to translate to a language other than
what is used to display the page.
Format a date with the given configured format or a custom format string.
Drupal allows administrators to select formatting strings for 'small',
'medium' and 'large' date formats. This function can handle these formats,
as well as any custom format.
Parameters:
timestamp - The exact date to format, as a UNIX timestamp.
type - The format to use. Can be "small", "medium" or "large"
for the preconfigured
date formats. If "custom" is specified, then format is required as well.
format - A PHP date format string as required by date(). A backslash should be used
before a character to avoid interpreting the character as part of a date
format.
timezone - Time zone offset in seconds; if omitted, the user's time zone is used.
langcode - Optional language code to translate to a language other than what is used
to display the page.
Generate a URL from a Drupal menu path.
Will also pass-through existing URLs.
Parameters:
path - The Drupal path being linked to, such as "admin/content/node", or an
existing URL like "http://drupal.org/". The special path
'' may also be given and will generate the site's base URL.
options - An associative array of additional options, with the following keys:
'query'
A query string to append to the link, or an array of query key/value
properties.
'fragment'
A fragment identifier (or named anchor) to append to the link.
Do not include the '#' character.
'absolute' (default False)
Whether to force the output to be an absolute link (beginning with
http:). Useful for links that will be displayed outside the site, such
as in an RSS feed.
'alias' (default False)
Whether the given path is an alias already.
'external'
Whether the given path is an external URL.
'language'
An optional language object. Used to build the URL to link to and
look up the proper alias for the link.
'base_url'
Only used internally, to modify the base URL when a language dependent
URL requires so.
'prefix'
Only used internally, to modify the path when a language dependent URL
requires so.
Returns:
A string containing a URL to the given path.
When creating links in plugins, consider whether l() could be a better
alternative than url().
Format an internal Drupal link.
This function correctly handles aliased paths, and allows
themes to highlight
links to the current page correctly, so all internal links output by plugins
should be generated by this function if possible.
Parameters:
text - The text to be enclosed with the anchor tag.
path - The Drupal path being linked to, such as "admin/content/node". Can be an
external or internal URL.
- If you provide the full URL, it will be considered an external URL.
- If you provide only the path (e.g. "admin/content/node"), it is
considered an internal link. In this case, it must be a system URL
as the url() function will generate the alias.
- If you provide '', it generates a link to the site's
base URL (again via the url() function).
- If you provide a path, and 'alias' is set to True (see below), it is
used as is.
options - An associative array of additional options, with the following keys:
'attributes'
An associative array of HTML attributes to apply to the anchor tag.
'query'
A query string to append to the link, or an array of query key/value
properties.
'fragment'
A fragment identifier (named anchor) to append to the link.
Do not include the '#' character.
'absolute' (default False)
Whether to force the output to be an absolute link (beginning with
http:). Useful for links that will be displayed outside the site, such
as in an RSS feed.
'html' (default False)
Whether the title is HTML, or just plain-text. For example for making
an image a link, this must be set to True, or else you will see the
escaped HTML.
'alias' (default False)
Whether the given path is an alias already.
Returns:
an HTML string containing a link to the given path.
Perform end-of-request tasks.
This function sets the page cache if appropriate, and allows plugins to
react to the closing of the page by calling hook_exit().
Form an associative array from a linear array.
This function walks through the provided array and constructs an associative
array out of it. The keys of the resulting array will be the values of the
input array. The values will be the same as the keys unless a function is
specified, in which case the output of the function is used for the values
instead.
Parameters:
array - A linear array.
function - A name of a function to apply to all values before output.
Evaluate a string of PHP code.
This is a wrapper around PHP's eval(). It uses output
buffering to capture both
returned and printed text. Unlike eval(), we require code to
be surrounded by
tags; in other words, we evaluate the code as if it
were a stand-alone
PHP file.
Using this wrapper also ensures that the PHP code which is
evaluated can not
overwrite any variables in the calling code, unlike a regular eval() call.
Parameters:
code - The code to evaluate.
Returns:
A string containing the printed output of the code,
followed by the returned
output of the code.
path - (optional) The path to the CSS file relative to the base_path(), e.g.,
/plugins/devel/devel.css.
Modules should always prefix the names of their CSS files with the plugin
name, for example: system-menus.css rather than simply menus.css. Themes
can override plugin-supplied CSS files based on their filenames, and this
prefixing helps prevent confusing name collisions for theme developers.
See drupal_get_css where the overrides are performed.
If the direction of the current language is right-to-left (Hebrew,
Arabic, etc.), the function will also look for an RTL CSS file and append
it to the list. The name of this file should have an '-rtl.css' suffix.
For example a CSS file called 'name.css' will have a 'name-rtl.css'
file added to the list, if exists in the same directory. This CSS file
should contain overrides for properties which should be reversed or
otherwise different in a right-to-left display.
type - (optional) The type of stylesheet that is being added. Types are: plugin
or theme.
media - (optional) The media type for the stylesheet, e.g., all, print, screen.
preprocess - (optional) Should this CSS file be aggregated and compressed if this
feature has been turned on under the performance section?
What does this actually mean?
CSS preprocessing is the process of aggregating a bunch of separate CSS
files into one file that is then compressed by removing all extraneous
white space.
The reason for merging the CSS files is outlined quite thoroughly here:
http://www.die.net/musings/page_load_time/
"Load fewer external objects. Due to request overhead, one bigger file
just loads faster than two smaller ones half its size."
However, you should *not* preprocess every file as this can lead to
redundant caches. You should set preprocess = False when:
- Your styles are only used rarely on the site. This could be a special
admin page, the homepage, or a handful of pages that
does not represent
the majority of the pages on your site.
Typical candidates for caching are for example styles for nodes across
the site, or used in the theme.
Returns a themed representation of all stylesheets that
should be attached to the page.
It loads the CSS in order, with 'plugin' first, then 'theme' afterwards.
This ensures proper cascading of styles so themes can easily override
plugin styles through CSS selectors.
Themes may replace plugin-defined CSS files by adding a stylesheet with the
same filename. For example, themes/garland/system-menus.css would replace
plugins/system/system-menus.css. This allows themes to override complete
CSS files, rather than specific selectors, when necessary.
If the original CSS file is being overridden by a theme, the theme is
responsible for supplying an accompanying RTL CSS file to replace the
plugin's.
Parameters:
css - (optional) An array of CSS files. If no array is provided, the default
stylesheets array is used instead.
Loads the stylesheet and resolves all @import commands.
Loads a stylesheet and replaces @import commands with the contents of the
imported file. Use this instead of file_get_contents when processing
stylesheets.
The returned contents are compressed removing white space and comments only
when CSS aggregation is enabled. This optimization will not apply for
color.plugin enabled themes with CSS aggregation turned off.
Parameters:
file - Name of the stylesheet to be processed.
optimize - Defines if CSS contents should be compressed or not.
Returns:
Contents of the stylesheet including the imported stylesheets.
Loads stylesheets recursively and returns contents with corrected paths.
This function is used for recursive loading of stylesheets and
returns the stylesheet content with all url() paths corrected.
Add a JavaScript file, setting or inline code to the page.
The behavior of this function depends on the parameters it is called with.
Generally, it handles the addition of JavaScript to the page, either as
reference to an existing file or as inline code.
The following actions can be
performed using this function:
- Add a file ('core', 'plugin' and 'theme'):
Adds a reference to a JavaScript file to the page. JavaScript files
are placed in a certain order, from 'core' first, to 'plugin' and finally
'theme' so that files, that are added later, can override previously added
files with ease.
- Add inline JavaScript code ('inline'):
Executes a piece of JavaScript code on the current page by
placing the code
directly in the page. This can, for example, be useful
to tell the user that
a new message arrived, by opening a pop up, alert box etc.
- Add settings ('setting'):
Adds a setting to Drupal's global storage of JavaScript settings. Per-page
settings are required by some plugins to function properly. The settings
will be accessible at Drupal.settings.
Parameters:
data - (optional) If given, the value depends on the type parameter:
- 'core', 'plugin' or 'theme': Path to the file relative to base_path().
- 'inline': The JavaScript code that should be placed in the given scope.
- 'setting': An array with configuration options as associative array. The
array is directly placed in Drupal.settings.
You might want to wrap your
actual configuration settings in another variable to
prevent the pollution
of the Drupal.settings namespace.
type - (optional) The type of JavaScript that should be added to
the page. Allowed
values are 'core', 'plugin', 'theme', 'inline' and 'setting'. You
can, however, specify any value. It is treated as a reference
to a JavaScript
file. Defaults to 'plugin'.
scope - (optional) The location in which you want to place the script. Possible
values are 'php.header' and 'footer' by default. If your theme implements
different locations, however, you can also use these.
defer - (optional) If set to True, the defer attribute is set on the