1
0
mirror of https://github.com/processwire/processwire.git synced 2025-08-09 16:26:59 +02:00

phpdoc improvements to WireFileTools, FunctionsWireAPI, FunctionsAPI and Functions files.

This commit is contained in:
Ryan Cramer
2019-01-18 11:50:22 -05:00
parent 97adac20ed
commit 7bbb97e6e4
4 changed files with 737 additions and 277 deletions

View File

@@ -8,23 +8,47 @@
* ProcessWire 3.x, Copyright 2016 by Ryan Cramer * ProcessWire 3.x, Copyright 2016 by Ryan Cramer
* https://processwire.com * https://processwire.com
* *
* #pw-summary-arrays These shortcuts for creating WireArray types are available in ProcessWire 3.0.123 and newer.
* #pw-summary-files These file system functions are procedural versions of some of those provided by the `$files` API variable.
*
*/ */
/** /**
* Return a ProcessWire API variable, or NULL if it doesn't exist * Return an API variable, or return current ProcessWire instance if given no arguments
* *
* And the wire() function is the recommended way to access the API when included from other PHP scripts. * - Call `wire()` with no arguments returns the current ProcessWire instance.
* Like the fuel() function, except that ommitting $name returns the current ProcessWire instance rather than the fuel. * - Call `wire('var')` to return the API variable represented by 'var', or null if not present.
* The distinction may not matter in most cases. * - Call `wire('all')` or `wire('*')` to return an iterable object of all API variables.
* - Call `wire($object)` to attach $object to the current instance ($object must be Wire-derived object).
* *
* @param string $name If omitted, returns a Fuel object with references to all the fuel. * #pw-group-common
* @return null|ProcessWire|Wire|Session|Page|Pages|Modules|User|Users|Roles|Permissions|Templates|Fields|Fieldtypes|Sanitizer|Config|Notices|WireDatabasePDO|WireHooks|WireDateTime|WireFileTools|WireMailTools|WireInput|string|mixed * #pw-group-Functions-API
*
* @param string $name If omitted, returns current ProcessWire instance.
* @return null|ProcessWire|Wire|Session|Page|Pages|Modules|User|Users|Roles|Permissions|Templates|Fields|Fieldtypes|Sanitizer|Config|Notices|WireDatabasePDO|WireHooks|WireDateTime|WireFileTools|WireMailTools|WireInput|string|mixed Requested API variable or null if it does not exist
* *
*/ */
function wire($name = 'wire') { function wire($name = 'wire') {
return ProcessWire::getCurrentInstance()->wire($name); return ProcessWire::getCurrentInstance()->wire($name);
} }
/**
* Get or set the current ProcessWire instance
*
* #pw-group-common
*
* @param ProcessWire|Wire|null $wire To set specify ProcessWire instance or any Wire-derived object in it, or omit to get current instance.
* @return ProcessWire
* @since 3.0.125
*
*/
function wireInstance(Wire $wire = null) {
if($wire === null) return ProcessWire::getCurrentInstance();
if(!$wire instanceof ProcessWire) $wire = $wire->wire();
ProcessWire::setCurrentInstance($wire);
return $wire;
}
/** /**
* Return all Fuel, or specified ProcessWire API variable, or NULL if it doesn't exist. * Return all Fuel, or specified ProcessWire API variable, or NULL if it doesn't exist.
* *
@@ -32,6 +56,8 @@ function wire($name = 'wire') {
* When a $name is specified, this function is identical to the wire() function. * When a $name is specified, this function is identical to the wire() function.
* Both functions exist more for consistent naming depending on usage. * Both functions exist more for consistent naming depending on usage.
* *
* #pw-internal
*
* @deprecated * @deprecated
* @param string $name If omitted, returns a Fuel object with references to all the fuel. * @param string $name If omitted, returns a Fuel object with references to all the fuel.
* @return mixed Fuel value if available, NULL if not. * @return mixed Fuel value if available, NULL if not.
@@ -49,6 +75,8 @@ function fuel($name = '') {
* *
* Watch out when using this function with strings that have a <textarea>, you may want to have it use \r newlines, at least temporarily. * Watch out when using this function with strings that have a <textarea>, you may want to have it use \r newlines, at least temporarily.
* *
* #pw-internal
*
* @param string $str String that needs the tabs * @param string $str String that needs the tabs
* @param int $numTabs Number of tabs to insert per line (note any existing tabs are left as-is, so indentation is retained) * @param int $numTabs Number of tabs to insert per line (note any existing tabs are left as-is, so indentation is retained)
* @param string $str The provided string but with tabs inserted * @param string $str The provided string but with tabs inserted
@@ -72,6 +100,8 @@ endif;
* *
* Use json_encode() instead if you don't want any empty values removed. * Use json_encode() instead if you don't want any empty values removed.
* *
* #pw-internal
*
* @param array $data Array to be encoded to JSON * @param array $data Array to be encoded to JSON
* @param bool|array $allowEmpty Should empty values be allowed in the encoded data? * @param bool|array $allowEmpty Should empty values be allowed in the encoded data?
* - Specify false to exclude all empty values (this is the default if not specified). * - Specify false to exclude all empty values (this is the default if not specified).
@@ -95,13 +125,14 @@ function wireEncodeJSON(array $data, $allowEmpty = false, $beautify = false) {
return json_encode($data, $flags); return json_encode($data, $flags);
} }
/** /**
* Decode JSON to array * Decode JSON to array
* *
* Uses json_decode and works the same way except that arrays are forced. * Uses json_decode and works the same way except that arrays are forced.
* This is the counterpart to the wireEncodeJSON() function. * This is the counterpart to the wireEncodeJSON() function.
* *
* #pw-internal
*
* @param string $json A JSON encoded string * @param string $json A JSON encoded string
* @return array * @return array
* *
@@ -115,6 +146,8 @@ function wireDecodeJSON($json) {
/** /**
* Minimize an array to remove empty values * Minimize an array to remove empty values
* *
* #pw-internal
*
* @param array $data Array to reduce * @param array $data Array to reduce
* @param bool|array $allowEmpty Should empty values be allowed in the encoded data? * @param bool|array $allowEmpty Should empty values be allowed in the encoded data?
* - Specify false to exclude all empty values (this is the default if not specified). * - Specify false to exclude all empty values (this is the default if not specified).
@@ -123,6 +156,7 @@ function wireDecodeJSON($json) {
* - Specify the digit 0 to retain values that are 0, but not other types of empty values. * - Specify the digit 0 to retain values that are 0, but not other types of empty values.
* @param bool $convert Perform type conversions where appropriate: i.e. convert digit-only string to integer * @param bool $convert Perform type conversions where appropriate: i.e. convert digit-only string to integer
* @return array * @return array
* @deprecated Use $sanitizer->minArray() instead
* *
*/ */
function wireMinArray(array $data, $allowEmpty = false, $convert = false) { function wireMinArray(array $data, $allowEmpty = false, $convert = false) {
@@ -131,15 +165,19 @@ function wireMinArray(array $data, $allowEmpty = false, $convert = false) {
return $sanitizer->minArray($data, $allowEmpty, $convert); return $sanitizer->minArray($data, $allowEmpty, $convert);
} }
/** /**
* Create a directory that is writable to ProcessWire and uses the $config chmod settings * Create a directory (optionally recursively) that is writable to ProcessWire and uses the $config chmod settings
*
* This is procedural version of the `$files->mkdir()` method.
*
* #pw-group-files
* *
* @param string $path * @param string $path
* @param bool $recursive If set to true, all directories will be created as needed to reach the end. * @param bool $recursive If set to true, all directories will be created as needed to reach the end.
* @param string $chmod Optional mode to set directory to (default: $config->chmodDir), format must be a string i.e. "0755" * @param string $chmod Optional mode to set directory to (default: $config->chmodDir), format must be a string i.e. "0755"
* If omitted, then ProcessWire's $config->chmodDir setting is used instead. * If omitted, then ProcessWires $config->chmodDir setting is used instead.
* @return bool * @return bool
* @see WireFileTools::mkdir()
* *
*/ */
function wireMkdir($path, $recursive = false, $chmod = null) { function wireMkdir($path, $recursive = false, $chmod = null) {
@@ -149,11 +187,16 @@ function wireMkdir($path, $recursive = false, $chmod = null) {
} }
/** /**
* Remove a directory * Remove a directory (optionally recursively)
*
* This is procedural version of the `$files->rmdir()` method. See that method for more options.
*
* #pw-group-files
* *
* @param string $path * @param string $path
* @param bool $recursive If set to true, all files and directories in $path will be recursively removed as well. * @param bool $recursive If set to true, all files and directories in $path will be recursively removed as well.
* @return bool * @return bool
* @see WireFileTools::rmdir()
* *
*/ */
function wireRmdir($path, $recursive = false) { function wireRmdir($path, $recursive = false) {
@@ -163,7 +206,13 @@ function wireRmdir($path, $recursive = false) {
} }
/** /**
* Change the mode of a file or directory, consistent with PW's chmodFile/chmodDir settings * Change the mode of a file or directory (optionally recursive)
*
* If no `$chmod` mode argument is specified the `$config->chmodFile` or $config->chmodDir` settings will be used.
*
* This is procedural version of the `$files->chmod()` method.
*
* #pw-group-files
* *
* @param string $path May be a directory or a filename * @param string $path May be a directory or a filename
* @param bool $recursive If set to true, all files and directories in $path will be recursively set as well. * @param bool $recursive If set to true, all files and directories in $path will be recursively set as well.
@@ -171,6 +220,7 @@ function wireRmdir($path, $recursive = false) {
* you may override it by specifying it here. Ignored otherwise. Format should be a string, like "0755". * you may override it by specifying it here. Ignored otherwise. Format should be a string, like "0755".
* @return bool Returns true if all changes were successful, or false if at least one chmod failed. * @return bool Returns true if all changes were successful, or false if at least one chmod failed.
* @throws WireException when it receives incorrect chmod format * @throws WireException when it receives incorrect chmod format
* @see WireFileTools::chmod()
* *
*/ */
function wireChmod($path, $recursive = false, $chmod = null) { function wireChmod($path, $recursive = false, $chmod = null) {
@@ -180,17 +230,20 @@ function wireChmod($path, $recursive = false, $chmod = null) {
} }
/** /**
* Copy all files in directory $src to directory $dst * Copy all files recursively from one directory to another
* *
* The default behavior is to also copy directories recursively. * This is procedural version of the `$files->copy()` method.
*
* #pw-group-files
* *
* @param string $src Path to copy files from * @param string $src Path to copy files from
* @param string $dst Path to copy files to. Directory is created if it doesn't already exist. * @param string $dst Path to copy files to. Directory is created if it doesnt already exist.
* @param bool|array Array of options: * @param bool|array Array of options:
* - recursive (boolean): Whether to copy directories within recursively. (default=true) * - `recursive` (bool): Whether to copy directories within recursively. (default=true)
* - allowEmptyDirs (boolean): Copy directories even if they are empty? (default=true) * - `allowEmptyDirs` (bool): Copy directories even if they are empty? (default=true)
* - If a boolean is specified for $options, it is assumed to be the 'recursive' option. * - If a boolean is specified for $options, it is assumed to be the 'recursive' option.
* @return bool True on success, false on failure. * @return bool True on success, false on failure.
* @see WireFileTools::copy()
* *
*/ */
function wireCopy($src, $dst, $options = array()) { function wireCopy($src, $dst, $options = array()) {
@@ -202,10 +255,15 @@ function wireCopy($src, $dst, $options = array()) {
/** /**
* Unzips the given ZIP file to the destination directory * Unzips the given ZIP file to the destination directory
* *
* This is procedural version of the `$files->unzip()` method. See that method for more details.
*
* #pw-group-files
*
* @param string $file ZIP file to extract * @param string $file ZIP file to extract
* @param string $dst Directory where files should be unzipped into. Directory is created if it doesn't exist. * @param string $dst Directory where files should be unzipped into. Directory is created if it doesnt exist.
* @return array Returns an array of filenames (excluding $dst) that were unzipped. * @return array Returns an array of filenames (excluding $dst) that were unzipped.
* @throws WireException All error conditions result in WireException being thrown. * @throws WireException All error conditions result in WireException being thrown.
* @see WireFileTools::unzip()
* *
*/ */
function wireUnzipFile($file, $dst) { function wireUnzipFile($file, $dst) {
@@ -215,22 +273,27 @@ function wireUnzipFile($file, $dst) {
} }
/** /**
* Creates a ZIP file * Create a ZIP file from given files
*
* This is procedural version of the `$files->zip()` method. See that method for all options.
*
* #pw-group-files
* *
* @param string $zipfile Full path and filename to create or update (i.e. /path/to/myfile.zip) * @param string $zipfile Full path and filename to create or update (i.e. /path/to/myfile.zip)
* @param array|string $files Array of files to add (full path and filename), or directory (string) to add. * @param array|string $files Array of files to add (full path and filename), or directory (string) to add.
* If given a directory, it will recursively add everything in that directory. * If given a directory, it will recursively add everything in that directory.
* @param array $options Associative array of: * @param array $options Options modify default behavior:
* - allowHidden (boolean or array): allow hidden files? May be boolean, or array of hidden files (basenames) you allow. (default=false) * - `allowHidden` (bool|array): allow hidden files? May be boolean, or array of hidden files (basenames) you allow. (default=false)
* Note that if you actually specify a hidden file in your $files argument, then that overrides this. * Note that if you actually specify a hidden file in your $files argument, then that overrides this.
* - allowEmptyDirs (boolean): allow empty directories in the ZIP file? (default=true) * - `allowEmptyDirs` (bool): allow empty directories in the ZIP file? (default=true)
* - overwrite (boolean): Replaces ZIP file if already present (rather than adding to it) (default=false) * - `overwrite` (bool): Replaces ZIP file if already present (rather than adding to it) (default=false)
* - exclude (array): Files or directories to exclude * - `exclude` (array): Files or directories to exclude
* - dir (string): Directory name to prepend to added files in the ZIP * - `dir` (string): Directory name to prepend to added files in the ZIP
* @return array Returns associative array of: * @return array Returns associative array of:
* - files => array(all files that were added), * - `files` (array): all files that were added
* - errors => array(files that failed to add, if any) * - `errors` (array): files that failed to add, if any
* @throws WireException Original ZIP file creation error conditions result in WireException being thrown. * @throws WireException Original ZIP file creation error conditions result in WireException being thrown.
* @see WireFileTools::zip()
* *
*/ */
function wireZipFile($zipfile, $files, array $options = array()) { function wireZipFile($zipfile, $files, array $options = array()) {
@@ -242,43 +305,52 @@ function wireZipFile($zipfile, $files, array $options = array()) {
/** /**
* Send the contents of the given filename via http * Send the contents of the given filename via http
* *
* This function utilizes the $content->fileContentTypes to match file extension * This function utilizes the `$config->fileContentTypes` to match file extension
* to content type headers and force-download state. * to content type headers and force-download state.
* *
* This function throws a WireException if the file can't be sent for some reason. * This function throws a WireException if the file cant be sent for some reason.
* *
* @param string $filename Filename to send * This is procedural version of the `$files->send()` method. See that method for all options.
* @param array $options Options that you may pass in, see $_options in function for details. *
* @param array $headers Headers that are sent, see $_headers in function for details. * #pw-group-files
* To remove a header completely, make its value NULL and it won't be sent. *
* @param string $filename Full path and filename to send
* @param array $options Optional options that you may pass in (see `WireHttp::sendFile()` for details)
* @param array $headers Optional headers that are sent (see `WireHttp::sendFile()` for details)
* @throws WireException * @throws WireException
* @see WireHttp::sendFile(), WireFileTools::send()
* *
*/ */
function wireSendFile($filename, array $options = array(), array $headers = array()) { function wireSendFile($filename, array $options = array(), array $headers = array()) {
$http = new WireHttp(); /** @var WireFileTools $fileTools */
$http->sendFile($filename, $options, $headers); $files = wire('files');
$files->send($filename, $options, $headers);
} }
/** /**
* Given a unix timestamp (or date string), returns a formatted string indicating the time relative to now * Given a unix timestamp (or date string), returns a formatted string indicating the time relative to now
* *
* Example: 1 day ago, 30 seconds ago, etc. * Examples: 1 day ago, 30 seconds ago”, “just now”, etc.
*
* This is the procedural version of `$datetime->relativeTimeStr()`.
* *
* Based upon: http://www.php.net/manual/en/function.time.php#89415 * Based upon: http://www.php.net/manual/en/function.time.php#89415
* *
* #pw-group-strings
*
* @param int|string $ts Unix timestamp or date string * @param int|string $ts Unix timestamp or date string
* @param bool|int|array $abbreviate Whether to use abbreviations for shorter strings. * @param bool|int|array $abbreviate Whether to use abbreviations for shorter strings.
* Specify boolean TRUE for abbreviations (abbreviated where common, not always different from non-abbreviated) * - Specify boolean TRUE for abbreviations (abbreviated where common, not always different from non-abbreviated)
* Specify integer 1 for extra short abbreviations (all terms abbreviated into shortest possible string) * - Specify integer 1 for extra short abbreviations (all terms abbreviated into shortest possible string)
* Specify boolean FALSE or omit for no abbreviations. * - Specify boolean FALSE or omit for no abbreviations.
* Specify associative array of key=value pairs of terms to use for abbreviations. The possible keys are: * - Specify associative array of key=value pairs of terms to use for abbreviations. The possible keys are:
* just now, ago, from now, never * just now, ago, from now, never, second, minute, hour, day, week, month, year, decade, seconds, minutes,
* second, minute, hour, day, week, month, year, decade * hours, days, weeks, months, years, decades
* seconds, minutes, hours, days, weeks, months, years, decades * @param bool $useTense Whether to append a tense like “ago” or “from now”,
* @param bool $useTense Whether to append a tense like "ago" or "from now",
* May be ok to disable in situations where all times are assumed in future or past. * May be ok to disable in situations where all times are assumed in future or past.
* In abbreviate=1 (shortest) mode, this removes the leading "+" or "-" from the string. * In abbreviate=1 (shortest) mode, this removes the leading "+" or "-" from the string.
* @return string * @return string
* @see WireDateTime::relativeTimeStr()
* *
*/ */
function wireRelativeTimeStr($ts, $abbreviate = false, $useTense = true) { function wireRelativeTimeStr($ts, $abbreviate = false, $useTense = true) {
@@ -289,81 +361,85 @@ function wireRelativeTimeStr($ts, $abbreviate = false, $useTense = true) {
/** /**
* Send an email or retrieve the mailer object * Send an email or get a WireMail object to populate before send
* *
* Note 1: The order of arguments is different from PHP's mail() function. * - Please note that the order of arguments is different from PHPs mail() function.
* Note 2: If no arguments are specified it simply returns a WireMail object (see #4 below). * - If no arguments are specified it simply returns a WireMail object (see #4 below).
* - This is a procedural version of functions provided by the `$mail` API variable (see that for more options).
* - This function will attempt to use an installed module that extends WireMail.
* - If no other WireMail module is installed, the default `WireMail` (which uses PHP mail) will be used instead.
* *
* This function will attempt to use an installed module that extends WireMail. * ~~~~~~
* If no module is installed, WireMail (which uses PHP mail) will be used instead. * // Default usage:
* wireMail($to, $from, $subject, $body, $options);
* *
* This function can be called in these ways: * // Specify body and/or bodyHTML in $options array (perhaps with other options):
* $options = [ 'body' => $body, 'bodyHTML' => $bodyHTML ];
* wireMail($to, $from, $subject, $options);
* *
* 1. Default usage: * // Specify both $body and $bodyHTML as arguments, but no $options:
* wireMail($to, $from, $subject, $body, $bodyHTML);
* *
* wireMail($to, $from, $subject, $body, $options); * // Specify a blank call to wireMail() to get the WireMail sending object. This can
* * // be either WireMail() or a class descending from it. If a WireMail descending
* * // module is installed, it will be returned rather than WireMail():
* 2. Specify body and/or bodyHTML in $options array (perhaps with other options): * $mail = wireMail();
* * $mail->to('user@domain.com')->from('you@company.com');
* wireMail($to, $from, $subject, $options); * $mail->subject('Mail Subject')->body('Mail Body Text')->bodyHTML('Body HTML');
* * $numSent = $mail->send();
*
* 3. Specify both $body and $bodyHTML as arguments, but no $options:
*
* wireMail($to, $from, $subject, $body, $bodyHTML);
*
*
* 4. Specify a blank call to wireMail() to get the WireMail sending object. This can
* be either WireMail() or a class descending from it. If a WireMail descending
* module is installed, it will be returned rather than WireMail():
*
* $mail = wireMail();
* $mail->to('user@domain.com')->from('you@company.com');
* $mail->subject('Mail Subject')->body('Mail Body Text')->bodyHTML('Body HTML');
* $numSent = $mail->send();
* *
* #pw-group-common
* *
* @param string|array $to Email address TO. For multiple, specify CSV string or array. * @param string|array $to Email address TO. For multiple, specify CSV string or array.
* @param string $from Email address FROM. This may be an email address, or a combined name and email address. * @param string $from Email address FROM. This may be an email address, or a combined name and email address.
* Example of combined name and email: Karen Cramer <karen@processwire.com> * Example of combined name and email: `Karen Cramer <karen@processwire.com>`
* @param string $subject Email subject * @param string $subject Email subject
* @param string|array $body Email body or omit to move straight to $options * @param string|array $body Email body or omit to move straight to $options array
* @param array|string $options Array of options OR the $bodyHTML string. Array $options are: * @param array|string $options Array of options OR the $bodyHTML string. Array $options are:
* body: string * - `bodyHTML` (string): Email body as HTML.
* bodyHTML: string * - `body` (string): Email body as plain text. This is created automatically if you only provide $bodyHTML.
* headers: associative array of header name => header value * - `headers` (array): Associative array of ['header name' => 'header value']
* Any additional options will be sent along to the WireMail module or class, in tact. * - Any additional options you provide will be sent along to the WireMail module or class, in tact.
* @return int|WireMail Returns number of messages sent or WireMail object if no arguments specified. * @return int|WireMail Returns number of messages sent or WireMail object if no arguments specified.
* *
*/ */
function wireMail($to = '', $from = '', $subject = '', $body = '', $options = array()) { function wireMail($to = '', $from = '', $subject = '', $body = '', $options = array()) {
/** @var WireMail $mail */ /** @var WireMailTools $mail */
$mail = wire('mail'); $mail = wire('mail');
return $mail->send($to, $from, $subject, $body, $options); return $mail->send($to, $from, $subject, $body, $options);
} }
/** /**
* Given a string $str and values $vars, replace tags in the string with the values * Given a string ($str) and values ($vars), replace “{tags}” in the string with the values
* *
* The $vars may also be an object, in which case values will be pulled as properties of the object. * - The `$vars` should be an associative array of `[ 'tag' => 'value' ]`.
* - The `$vars` may also be an object, in which case values will be pulled as properties of the object.
* *
* By default, tags are specified in the format: {first_name} where first_name is the name of the * By default, tags are specified in the format: {first_name} where first_name is the name of the
* variable to pull from $vars, '{' is the opening tag character, and '}' is the closing tag char. * variable to pull from $vars, `{` is the opening tag character, and `}` is the closing tag char.
* *
* The tag parser can also handle subfields and OR tags, if $vars is an object that supports that. * The tag parser can also handle subfields and OR tags, if `$vars` is an object that supports that.
* For instance {products.title} is a subfield, and {first_name|title|name} is an OR tag. * For instance `{products.title}` is a subfield, and `{first_name|title|name}` is an OR tag.
*
* ~~~~~
* $vars = [ 'foo' => 'FOO!', 'bar' => 'BAR!' ];
* $str = 'This is a test: {foo}, and this is another test: {bar}';
* echo wirePopulateStringTags($str, $vars);
* // outputs: This is a test: FOO!, and this is another test: BAR!
* ~~~~~
*
* #pw-group-strings
* *
* @param string $str The string to operate on (where the {tags} might be found) * @param string $str The string to operate on (where the {tags} might be found)
* @param WireData|object|array Object or associative array to pull replacement values from. * @param WireData|object|array $vars Object or associative array to pull replacement values from.
* @param array $options Array of optional changes to default behavior, including: * @param array $options Array of optional changes to default behavior, including:
* - tagOpen: The required opening tag character(s), default is '{' * - `tagOpen` (string): The required opening tag character(s), default is '{'
* - tagClose: The optional closing tag character(s), default is '}' * - `tagClose` (string): The optional closing tag character(s), default is '}'
* - recursive: If replacement value contains tags, populate those too? Default=false. * - `recursive` (bool): If replacement value contains tags, populate those too? (default=false)
* - removeNullTags: If a tag resolves to a NULL, remove it? If false, tag will remain. Default=true. * - `removeNullTags` (bool): If a tag resolves to a NULL, remove it? If false, tag will remain. (default=true)
* - entityEncode: Entity encode the values pulled from $vars? Default=false. * - `entityEncode` (bool): Entity encode the values pulled from $vars? (default=false)
* - entityDecode: Entity decode the values pulled from $vars? Default=false. * - `entityDecode` (bool): Entity decode the values pulled from $vars? (default=false)
* @return string String with tags populated. * @return string String with tags populated.
* *
*/ */
@@ -446,12 +522,24 @@ function wirePopulateStringTags($str, $vars, array $options = array()) {
/** /**
* Return a new temporary directory/path ready to use for files * Return a new temporary directory/path ready to use for files
* *
* @param object|string $name Provide the object that needs the temp dir, or name your own string * - The directory will be automatically removed after a set period of time (default=120s).
* @param array|int $options Options array: * - This is a procedural version of the `$files->tempDir()` method.
* - maxAge: Maximum age of temp dir files in seconds (default=120) *
* - basePath: Base path where temp dirs should be created. Omit to use default (recommended). * ~~~~~
* Note: if you specify an integer for $options, then $maxAge is assumed. * $td = wireTempDir('hello-world');
* @return WireTempDir * $path = (string) $td; // or use $td->get();
* file_put_contents($path . 'some-file.txt', 'Hello world');
* ~~~~~
*
* #pw-group-files
*
* @param Object|string $name Provide the object that needs the temp dir, or name your own string
* @param array|int $options Options array to modify default behavior:
* - `maxAge` (integer): Maximum age of temp dir files in seconds (default=120)
* - `basePath` (string): Base path where temp dirs should be created. Omit to use default (recommended).
* - Note: if you specify an integer for $options, then 'maxAge' is assumed.
* @return WireTempDir If you typecast return value to a string, it is the temp dir path (with trailing slash).
* @see WireFileTools::tempDir(), WireTempDir
* *
*/ */
function wireTempDir($name, $options = array()) { function wireTempDir($name, $options = array()) {
@@ -463,26 +551,33 @@ function wireTempDir($name, $options = array()) {
/** /**
* Given a filename, render it as a ProcessWire template file * Given a filename, render it as a ProcessWire template file
* *
* This is a shortcut to using the TemplateFile class. * This is a shortcut to using the `TemplateFile` class, as well as the procedural version of `$files->render()`.
* *
* File is assumed relative to /site/templates/ (or a directory within there) unless you specify a full path. * File is assumed relative to `/site/templates/` (or a directory within there) unless you specify a full path.
* If you specify a full path, it will accept files in or below site/templates/, site/modules/, wire/modules/. * If you specify a full path, it will accept files in or below any of the following:
* *
* Note this function returns the output for you to output wherever you want (delayed output). * - /site/templates/
* For direct output, use the wireInclude() function instead. * - /site/modules/
* - /wire/modules/
*
* Note this function returns the output to you, so that you can send the output wherever you want (delayed output).
* For direct output, use the `wireIncludeFile()` or `$files->include()` function instead.
*
* #pw-group-files
* *
* @param string $filename Assumed relative to /site/templates/ unless you provide a full path name with the filename. * @param string $filename Assumed relative to /site/templates/ unless you provide a full path name with the filename.
* If you provide a path, it must resolve somewhere in site/templates/, site/modules/ or wire/modules/. * If you provide a path, it must resolve somewhere in site/templates/, site/modules/ or wire/modules/.
* @param array $vars Optional associative array of variables to send to template file. * @param array $vars Optional associative array of variables to send to template file.
* Please note that all template files automatically receive all API variables already (you don't have to provide them) * Please note that all template files automatically receive all API variables already (you don't have to provide them).
* @param array $options Associative array of options to modify behavior: * @param array $options Associative array of options to modify behavior:
* - defaultPath: Path where files are assumed to be when only filename or relative filename is specified (default=/site/templates/) * - `defaultPath` (string): Path where files are assumed to be when only filename or relative filename is specified (default=/site/templates/)
* - autoExtension: Extension to assume when no ext in filename, make blank for no auto assumption (default=php) * - `autoExtension` (string): Extension to assume when no ext in filename, make blank for no auto assumption (default=php)
* - allowedPaths: Array of paths that are allowed (default is templates, core modules and site modules) * - `allowedPaths` (array): Array of paths that are allowed (default is templates, core modules and site modules)
* - allowDotDot: Allow use of ".." in paths? (default=false) * - `allowDotDot` (bool): Allow use of ".." in paths? (default=false)
* - throwExceptions: Throw exceptions when fatal error occurs? (default=true) * - `throwExceptions` (bool): Throw exceptions when fatal error occurs? (default=true)
* @return string|bool Rendered template file or boolean false on fatal error (and throwExceptions disabled) * @return string|bool Rendered template file or boolean false on fatal error (and throwExceptions disabled)
* @throws WireException if template file doesn't exist * @throws WireException if template file doesnt exist
* @see wireIncludeFile(), WireFileTools::render(), WireFileTools::include()
* *
*/ */
function wireRenderFile($filename, array $vars = array(), array $options = array()) { function wireRenderFile($filename, array $vars = array(), array $options = array()) {
@@ -493,53 +588,67 @@ function wireRenderFile($filename, array $vars = array(), array $options = array
/** /**
* Include a PHP file passing it all API variables and optionally your own specified variables * Include a PHP file passing it all API variables and optionally your own specified variables
* This is the procedural version of the `$files->include()` method.
*
* This is the same as PHPs `include()` function except for the following:
* *
* This is the same as PHP's include() function except for the following:
* - It receives all API variables and optionally your custom variables * - It receives all API variables and optionally your custom variables
* - If your filename is not absolute, it doesn't look in PHP's include path, only in the current dir. * - If your filename is not absolute, it doesnt look in PHPs include path, only in the current dir.
* - It only allows including files that are part of the PW installation: templates, core modules or site modules * - It only allows including files that are part of the PW installation: templates, core modules or site modules
* - It will assume a ".php" extension if filename has no extension. * - It will assume a .php extension if filename has no extension.
* *
* Note this function produced direct output. To retrieve output as a return value, use the * Note this function produces direct output. To retrieve output as a return value, use the
* `wireRenderFile()` function instead. * `wireRenderFile()` or `$files->render()` function instead.
* *
* @param $filename * #pw-group-files
*
* @param string $filename Filename to include
* @param array $vars Optional variables you want to hand to the include (associative array) * @param array $vars Optional variables you want to hand to the include (associative array)
* @param array $options Array of options to modify behavior: * @param array $options Array of options to modify behavior:
* - func: Function to use: include, include_once, require or require_once (default=include) * - `func` (string): Function to use: include, include_once, require or require_once (default=include)
* - autoExtension: Extension to assume when no ext in filename, make blank for no auto assumption (default=php) * - `autoExtension` (string): Extension to assume when no ext in filename, make blank for no auto assumption (default=php)
* - allowedPaths: Array of paths include files are allowed from. Note current dir is always allowed. * - `allowedPaths` (array): Array of start paths include files are allowed from. Note current dir is always allowed.
* @return bool Returns true * @return bool Always returns true
* @throws WireException if file doesn't exist or is not allowed * @throws WireException if file doesnt exist or is not allowed
* @see wireRenderFile(), WireFileTools::include(), WireFileTools::render()
*
* *
*/ */
function wireIncludeFile($filename, array $vars = array(), array $options = array()) { function wireIncludeFile($filename, array $vars = array(), array $options = array()) {
/** @var WireFileTools $files */ /** @var WireFileTools $files */
$files = wire('files'); $files = wire('files');
return $files->include($filename, $vars, $options); return $files->___include($filename, $vars, $options);
} }
/** /**
* Format a date, using PHP date(), strftime() or other special strings (see arguments). * Format a date, using PHP date(), strftime() or other special strings (see arguments).
* *
* This is designed to work the same wa as PHP's date() but be able to accept any common format * This is designed to work the same wa as PHPs `date()` but be able to accept any common format
* used in ProcessWire. This is helpful in reducing code in places where you might have logic * used in ProcessWire. This is helpful in reducing code in places where you might have logic
* determining when to use date(), strftime(), or wireRelativeTimeStr(). * determining when to use `date()`, `strftime()`, or `wireRelativeTimeStr()`.
* *
* @param string|int $format Use one of the following: * This is the procedural version of the `$datetime->date()` method.
* - PHP date() format *
* - PHP strftime() format (detected by presence of a '%' somewhere in it) * ~~~~~
* - 'relative': for a relative date/time string. * echo wireDate('Y-m-d H:i:s'); // Outputs: 2019-01-20 06:48:11
* - 'relative-': for a relative date/time string with no tense. * echo wireDate('relative', '2019-01-20 06:00'); // Outputs: 48 minutes ago
* - 'rel': for an abbreviated relative date/time string. * ~~~~~
* - 'rel-': for an abbreviated relative date/time string with no tense. *
* - 'r': for an extra-abbreviated relative date/time string. * #pw-group-strings
* - 'r-': for an extra-abbreviated relative date/time string with no tense. * #pw-group-common
* - 'ts': makes it return a unix timestamp *
* - '': blank string makes it use the system date format ($config->dateFormat) * @param string|int $format Use any PHP date() or strftime() format, or one of the following:
* - `relative` for a relative date/time string.
* - `relative-` for a relative date/time string with no tense.
* - `rel` for an abbreviated relative date/time string.
* - `rel-` for an abbreviated relative date/time string with no tense.
* - `r` for an extra-abbreviated relative date/time string.
* - `r-` for an extra-abbreviated relative date/time string with no tense.
* - `ts` makes it return a unix timestamp.
* - Specify blank string to make it use the system date format ($config->dateFormat) .
* - If given an integer and no second argument specified, it is assumed to be the second ($ts) argument. * - If given an integer and no second argument specified, it is assumed to be the second ($ts) argument.
* @param int|string|null $ts Optionally specify the date/time stamp or strtotime() compatible string. * @param int|string|null $ts Optionally specify the date/time stamp or strtotime() compatible string. If not specified, current time is used.
* If not specified, current time is used.
* @return string|bool Formatted date/time, or boolean false on failure * @return string|bool Formatted date/time, or boolean false on failure
* *
*/ */
@@ -551,9 +660,16 @@ function wireDate($format = '', $ts = null) {
/** /**
* Render markup for an icon * Render markup for a system icon
* *
* Icon and class can be specified with or without the fa- prefix. * It is NOT necessary to specify an icon prefix like “fa-” with the icon name.
*
* ~~~~~
* // Outputs: "<i class='fa fa-home'></i>"
* echo wireIconMarkup('home');
* ~~~~~
*
* #pw-group-markup
* *
* @param string $icon Icon name (currently a font-awesome icon name, but support for more in future) * @param string $icon Icon name (currently a font-awesome icon name, but support for more in future)
* @param string $class Additional attributes for class (example: "fw" for fixed width) * @param string $class Additional attributes for class (example: "fw" for fixed width)
@@ -583,8 +699,16 @@ function wireIconMarkup($icon, $class = '') {
/** /**
* Get the markup or class name for an icon that can represent the given filename * Get the markup or class name for an icon that can represent the given filename
* *
* @param string $filename Can be any type of filename (with or without path) * ~~~~~
* @param string|bool $class Additional class attributes (optional). * // Outputs: "<i class='fa fa-pdf-o'></i>"
* echo wireIconMarkupFile('file.pdf');
* ~~~~~
*
* #pw-group-markup
* #pw-group-files
*
* @param string $filename Can be any type of filename (with or without path).
* @param string|bool $class Additional class attributes, i.e. "fw" for fixed-width (optional).
* Or specify boolean TRUE to get just the icon class name (no markup). * Or specify boolean TRUE to get just the icon class name (no markup).
* @return string * @return string
* *
@@ -625,12 +749,15 @@ function wireIconMarkupFile($filename, $class = '') {
} }
/** /**
* Given a quantity of bytes, return a more readable size string * Given a quantity of bytes (int), return readable string that refers to quantity in bytes, kB, MB, GB, etc.
*
* #pw-group-strings
* *
* @param int $bytes Quantity in bytes * @param int $bytes Quantity in bytes
* @param bool|int|array $small Make returned string as small as possible (default=false), * @param bool|int|array $small Make returned string as small as possible? (default=false)
* …or specify integer 1 for $small option but with space between number and unit label. * - `true` (bool): Yes, make returned string as small as possible.
* …or optionally specify $options argument here. * - `1` (int): Same as `true` but with space between number and unit label.
* - Or optionally specify the $options argument here if you do not need the $small argument.
* @param array|int $options Options to modify default behavior, or if an integer then `decimals` option is assumed: * @param array|int $options Options to modify default behavior, or if an integer then `decimals` option is assumed:
* - `decimals` (int): Number of decimals to use in returned value (default=0). * - `decimals` (int): Number of decimals to use in returned value (default=0).
* - `decimal_point` (string|null): Decimal point character, or null to detect from locale (default=null). * - `decimal_point` (string|null): Decimal point character, or null to detect from locale (default=null).
@@ -720,13 +847,17 @@ function wireBytesStr($bytes, $small = false, $options = array()) {
} }
/** /**
* Normalize a class name with or without namespace * Normalize a class name with or without namespace, or get namespace of class
* *
* Can also be used in an equivalent way to PHP's get_class() function. * Default behavior is to return class name without namespace.
* *
* @param string|object $className * #pw-group-class-helpers
*
* @param string|object $className Class name or object instance
* @param bool|int|string $withNamespace Should return value include namespace? (default=false) * @param bool|int|string $withNamespace Should return value include namespace? (default=false)
* or specify integer 1 to return only namespace (i.e. "ProcessWire", no leading or trailing backslashes) * - `false` (bool): Return only class name without namespace (default).
* - `true` (bool): Yes include namespace in returned value.
* - `1` (int): Return only namespace (i.e. “ProcessWire”, with no leading or trailing backslashes)
* @return string|null Returns string or NULL if namespace-only requested and unable to determine * @return string|null Returns string or NULL if namespace-only requested and unable to determine
* *
*/ */
@@ -758,7 +889,13 @@ function wireClassName($className, $withNamespace = false) {
} }
/** /**
* ProcessWire namespace aware version of PHP's class_exists() function * Does the given class name exist?
*
* ProcessWire namespace aware version of PHPs class_exists() function
*
* If given a class name that does not include a namespace, the `\ProcessWire` namespace is assumed.
*
* #pw-group-class-helpers
* *
* @param string $className * @param string $className
* @param bool $autoload * @param bool $autoload
@@ -771,7 +908,13 @@ function wireClassExists($className, $autoload = true) {
} }
/** /**
* ProcessWire namespace aware version of PHP's method_exists() function * Does the given class have the given method?
*
* ProcessWire namespace aware version of PHPs method_exists() function
*
* If given a class name that does not include a namespace, the `\ProcessWire` namespace is assumed.
*
* #pw-group-class-helpers
* *
* @param string $className * @param string $className
* @param string $method * @param string $method
@@ -784,7 +927,12 @@ function wireMethodExists($className, $method) {
} }
/** /**
* ProcessWire namespace aware version of PHP's class_implements() function * Get an array of all the interfaces that the given class implements
*
* - ProcessWire namespace aware version of PHPs class_implements() function.
* - Return value has array keys as class name with namespace and array values as class name without namespace.
*
* #pw-group-class-helpers
* *
* @param string|object $className * @param string|object $className
* @param bool $autoload * @param bool $autoload
@@ -811,11 +959,15 @@ function wireClassImplements($className, $autoload = true) {
} }
/** /**
* ProcessWire namespace aware version of PHP's class_parents() function * Return array of all parent classes for given class/object
*
* ProcessWire namespace aware version of PHPs class_parents() function
* *
* Returns associative array where array keys are full namespaced class name, and * Returns associative array where array keys are full namespaced class name, and
* values are the non-namespaced classname. * values are the non-namespaced classname.
* *
* #pw-group-class-helpers
*
* @param string|object $className * @param string|object $className
* @param bool $autoload * @param bool $autoload
* @return array * @return array
@@ -847,13 +999,15 @@ function wireClassParents($className, $autoload = true) {
* array of interfaces, or mixed array of interfaces and class names. Previous versions did * array of interfaces, or mixed array of interfaces and class names. Previous versions did
* not support interfaces unless the $instance argument was an object. * not support interfaces unless the $instance argument was an object.
* *
* #pw-group-class-helpers
*
* @param object|string $instance Object instance to test (or string of its class name). * @param object|string $instance Object instance to test (or string of its class name).
* @param string|array $className Class/interface name or array of class/interface names to test against. * @param string|array $className Class/interface name or array of class/interface names to test against.
* @param bool $autoload * @param bool $autoload Allow PHP to autoload the class? (default=true)
* @return bool|string Returns one of the following: * @return bool|string Returns one of the following:
* - boolean false if not an instance (whether $className argument is string or array). * - `false` (bool): if not an instance (whether $className argument is string or array).
* - boolean true if given a single $className (string) and $instance is an instance of it. * - `true` (bool): if given a single $className (string) and $instance is an instance of it.
* - string of first matching class/interface name if $className was an array of classes to test. * - `ClassName` (string): first matching class/interface name if $className was an array of classes to test.
* *
*/ */
function wireInstanceOf($instance, $className, $autoload = true) { function wireInstanceOf($instance, $className, $autoload = true) {
@@ -917,7 +1071,11 @@ function wireInstanceOf($instance, $className, $autoload = true) {
} }
/** /**
* ProcessWire namespace aware version of PHP's is_callable() function * Is the given $var callable as a function?
*
* ProcessWire namespace aware version of PHPs is_callable() function
*
* #pw-group-class-helpers
* *
* @param string|callable $var * @param string|callable $var
* @param bool $syntaxOnly * @param bool $syntaxOnly
@@ -934,10 +1092,13 @@ function wireIsCallable($var, $syntaxOnly = false, &$callableName = '') {
* Return the count of item(s) present in the given value * Return the count of item(s) present in the given value
* *
* Duplicates behavior of PHP count() function prior to PHP 7.2, which states: * Duplicates behavior of PHP count() function prior to PHP 7.2, which states:
* Returns the number of elements in $value. When the parameter is neither an array nor an *
* > Returns the number of elements in $value. When the parameter is neither an array nor an
* object with implemented Countable interface, 1 will be returned. There is one exception, * object with implemented Countable interface, 1 will be returned. There is one exception,
* if $value is NULL, 0 will be returned. * if $value is NULL, 0 will be returned.
* *
* #pw-group-common
*
* @param mixed $value * @param mixed $value
* @return int * @return int
* *
@@ -952,6 +1113,12 @@ function wireCount($value) {
/** /**
* Get or set an output region (primarily for front-end output usage) * Get or set an output region (primarily for front-end output usage)
* *
* This function is an convenience for storing markup that ultimately gets output in a _main.php file
* (or whatever file `$config->appendTemplateFile` is set to). It is an alternative to passing variables
* between included files and provides an interface for setting, appending, prepending and ultimately
* getting markup (or other strings) for output. Its designed for use the the “Delayed Output” strategy,
* though does not necessarily require it.
*
* ~~~~~ * ~~~~~
* // define a region * // define a region
* region('content', '<p>this is some content</p>'); * region('content', '<p>this is some content</p>');
@@ -975,6 +1142,8 @@ function wireCount($value) {
* region('*', ''); * region('*', '');
* ~~~~~ * ~~~~~
* *
* #pw-internal
*
* @param string $key Name of region to get or set. * @param string $key Name of region to get or set.
* - Specify "*" to retrieve all defined regions in an array. * - Specify "*" to retrieve all defined regions in an array.
* - Prepend a "+" to the region name to have it prepend your given value to any existing value. * - Prepend a "+" to the region name to have it prepend your given value to any existing value.
@@ -1034,8 +1203,20 @@ function wireRegion($key, $value = null) {
/** /**
* Create new WireArray, add given $items to it, and return it * Create new WireArray, add given $items to it, and return it
* *
* @param array|WireArray $items * This is the same as creating a `new WireArray()` and then adding items to it with separate `add()` calls,
* except that this function enables you to do it all in one shot.
*
* ~~~~~~
* $a = WireArray(); // create empty WireArray
* $a = WireArray('foo'); // create WireArray with one "foo" string
* $a = WireArray(['foo', 'bar', 'baz']); // create WireArray with 3 strings
* ~~~~~~
*
* #pw-group-arrays
*
* @param array|WireArray|mixed $items
* @return WireArray * @return WireArray
* @since 3.0.123
* *
*/ */
function WireArray($items = array()) { function WireArray($items = array()) {
@@ -1045,8 +1226,20 @@ function WireArray($items = array()) {
/** /**
* Create new PageArray, add given $items (pages) to it, and return it * Create new PageArray, add given $items (pages) to it, and return it
* *
* This is the same as creating a `new PageArray()` and then adding items to it with separate `add()` calls,
* except that this function enables you to do it all in one shot.
*
* ~~~~~
* $a = PageArray(); // create empty PageArray
* $a = PageArray($page); // create PageArray with one page
* $a = PageArray([ $page1, $page2, $page3 ]); // create PageArray with multiple items
* ~~~~~
*
* #pw-group-arrays
*
* @param array|PageArray $items * @param array|PageArray $items
* @return WireArray * @return PageArray
* @since 3.0.123
* *
*/ */
function PageArray($items = array()) { function PageArray($items = array()) {

View File

@@ -3,26 +3,36 @@
/** /**
* ProcessWire functions API maps function names to common API variables * ProcessWire functions API maps function names to common API variables
* *
* #pw-summary-Functions-API =
* Provides an alternative to the API variables by providing functions of the same * Provides an alternative to the API variables by providing functions of the same
* name, with these benefits: * name, with these benefits:
* *
* - They are always in scope * - They are always in scope whether inside a function or outside of it.
* - Makes life simpler in an IDE that recognizes phpdoc, as it can more easily * - They are self documenting with your IDE, unlike API $variables.
* recognize the types an return values. * - They cannot be accidentally overwritten the way variables can be.
* - They provider greater contrast between what are API-calls and variables.
* - In some cases it makes for shorter API calls. * - In some cases it makes for shorter API calls.
* - Some of the functions provide arguments for useful shortcuts.
* *
* The primary drawback is that the function calls are not mapped to a specific * These functions always refer to the current ProcessWire instance, so are intended
* instance, so in a multi-instance environment it's possible these function calls * primarily for front-end usage in template files (not for modules).
* may not be referring to the correct ProcessWire instance. For this reason, we
* think these functions are primarily useful for front-end/website usages, and
* not as useful for back-end and module development.
* *
* Note: This file is only used if $config->useFunctionsAPI == true; * If these functions are not working for you, you can enable them by setting
* `$config->useFunctionsAPI=true;` in your /site/config.php file.
*
* Regardless of whether the Functions API is enabled or not, you can also access
* any of these functions by prefixing the word `wire` to them and using the format
* `wireFunction()` i.e. `wirePages()`, `wireUser()`, etc.
* Or, if you do not
* #pw-summary-Functions-API
* *
*/ */
/** /**
* Access the $pages API variable as a function * Retrieve or save pages ($pages API variable as a function)
*
* Accessing `pages()` is exactly the same as accessing `$pages`. Though there are a couple of optional
* shortcuts available by providing an argument to this function.
* *
* ~~~~ * ~~~~
* // A call with no arguments returns the $pages API variable * // A call with no arguments returns the $pages API variable
@@ -39,12 +49,15 @@
* $page = pages("page-name"); * $page = pages("page-name");
* ~~~~ * ~~~~
* *
* @param string|array $selector Specify one of the following: * #pw-group-Functions-API
*
* @param string|array|int $selector Specify one of the following:
* - Nothing, makes it return the $pages API variable. * - Nothing, makes it return the $pages API variable.
* - Selector (string) to find matching pages, makes function return PageArray - equivalent to $pages->find("selector"); * - Selector (string) to find matching pages, makes function return PageArray - equivalent to $pages->find("selector");
* - Page ID (int) to return a single matching Page - equivalent to $pages->get(123); * - Page ID (int) to return a single matching Page - equivalent to $pages->get(123);
* - Page name (string) to return a single page having the given name - equivalent to $pages->get("name"); * - Page name (string) to return a single page having the given name - equivalent to $pages->get("name");
* @return Pages|PageArray|Page|NullPage * @return Pages|PageArray|Page|NullPage
* @see Pages
* *
*/ */
function pages($selector = '') { function pages($selector = '') {
@@ -52,19 +65,35 @@ function pages($selector = '') {
} }
/** /**
* Access the $page API variable as a function * Returns the current Page being viewed ($page API variable as a function)
*
* This function behaves the same as the `$page` API variable, though does support optional
* arguments as shortcuts for getting from the page or setting values to it.
* *
* ~~~~ * ~~~~
* $page = page(); // Simply get $page API var * $page = page(); // Simply get $page API var
* $body = page()->body; // Get body field value *
* $body = page('body'); // Same as above * // Get the “body” field
* $headline = page('headline|title'); // Get headline or title * $body = page()->body; // direct syntax
* page('headline', 'Setting headline value'); // Set headline * $body = page()->get('body'); // regular syntax
* $body = page('body'); // shortcut syntax
*
* // Get the “headline” field or fallback to “title
* $headline = page()->get('headline|title'); // regular syntax
* $headline = page('headline|title'); // shortcut syntax
*
* // Set the “headline” field
* page()->headline = 'My headline'; // direct syntax
* page()->set('headline', 'My headline'); // regular syntax
* page('headline', 'My headline'); // shortcut syntax
* ~~~~ * ~~~~
* *
* #pw-group-Functions-API
*
* @param string $key Optional property to get or set * @param string $key Optional property to get or set
* @param null $value Optional value to set * @param null $value Optional value to set
* @return Page|mixed * @return Page|mixed
* @see Page
* *
*/ */
function page($key = '', $value = null) { function page($key = '', $value = null) {
@@ -72,19 +101,25 @@ function page($key = '', $value = null) {
} }
/** /**
* Access the $config API variable as a function * Access a ProcessWire configuration setting ($config API variable as a function)
*
* This function behaves the same as the `$config` API variable, though does support
* optional shortcut arguments for getting/setting values.
* *
* ~~~~~ * ~~~~~
* $config = config(); // Simply get $config API var * $config = config(); // Simply get $config API var
* $debug = config()->debug; // Get value of debug * $debug = config()->debug; // Get value of debug
* $debug = config('debug'); // Same as above * $debug = config('debug'); // Same as above, shortcut syntax
* config()->debug = true; // Set value of debug * config()->debug = true; // Set value of debug
* config('debug', true); // Same as above * config('debug', true); // Same as above, shortcut syntax
* ~~~~~ * ~~~~~
* *
* #pw-group-Functions-API
*
* @param string $key * @param string $key
* @param null $value * @param null $value
* @return Config|mixed * @return Config|mixed
* @see Config
* *
*/ */
function config($key = '', $value = null) { function config($key = '', $value = null) {
@@ -92,7 +127,10 @@ function config($key = '', $value = null) {
} }
/** /**
* Access the $modules API variable as a function * Get a module, get module information, and much more ($modules API variable as a function)
*
* This function behaves the same as the `$modules` API variable, though does support
* an optional shortcut argument for getting a module.
* *
* ~~~~~ * ~~~~~
* $modules = modules(); // Simply get $modules API var * $modules = modules(); // Simply get $modules API var
@@ -100,8 +138,11 @@ function config($key = '', $value = null) {
* $module = modules('ModuleName'); // Shortcut to get a module * $module = modules('ModuleName'); // Shortcut to get a module
* ~~~~~ * ~~~~~
* *
* #pw-group-Functions-API
*
* @param string $name Optionally retrieve the given module name * @param string $name Optionally retrieve the given module name
* @return Modules|Module|ConfigurableModule|null * @return Modules|Module|ConfigurableModule|null
* @see Modules
* *
*/ */
function modules($name = '') { function modules($name = '') {
@@ -109,11 +150,17 @@ function modules($name = '') {
} }
/** /**
* Access the $user API variable as a function * Get the currently logged in user ($user API variable as a function)
*
* This function behaves the same as the `$user` API variable, though does support
* optional shortcut arguments for getting or setting values.
*
* #pw-group-Functions-API
* *
* @param string $key Optional property to get or set * @param string $key Optional property to get or set
* @param null $value Optional value to set * @param null $value Optional value to set
* @return User|mixed * @return User|mixed
* @see User
* *
*/ */
function user($key = '', $value = null) { function user($key = '', $value = null) {
@@ -121,13 +168,28 @@ function user($key = '', $value = null) {
} }
/** /**
* Access the $users API variable as a function * Get, find or save users ($users API variable as a function)
* *
* See the pages() function for full usage details. * This function behaves the same as the `$users` API variable, though does support
* an optional shortcut argument for getting a single user or finding multiple users.
* *
* @param string|array $selector Optional selector to send to find() or get() * ~~~~~~
* // Get a single user (regular and shortcut syntax)
* $u = users()->get('karen');
* $u = users('karen');
*
* // Find multiple users (regular and shortcut syntax)
* $us = users()->find('roles.name=editor');
* $us = users('roles.name=editor');
* ~~~~~~
*
* #pw-group-Functions-API
*
* @param string|array|int $selector Optional selector to send to find() or get()
* - Specify user name or ID to get and return that User
* - Specify a selector string to find all users matching selector (PageArray)
* @return Users|PageArray|User|mixed * @return Users|PageArray|User|mixed
* @see pages() * @see pages(), Users
* *
*/ */
function users($selector = '') { function users($selector = '') {
@@ -135,11 +197,29 @@ function users($selector = '') {
} }
/** /**
* Access the $session API variable as a function * Get or set values in the current user session ($session API variable as a function)
*
* This function behaves the same as the `$session` API variable, though does support
* optional shortcut arguments for getting or setting values.
*
* ~~~~~
* // Get a value from the session
* $foo = session()->foo; // direct syntax
* $foo = session()->get('foo'); // regular syntax
* $foo = session('foo'); // shortcut syntax
*
* // Set a value to the session
* session()->foo = 'bar'; // direct syntax
* session()->set('foo', 'bar'); // regular syntax
* session('foo', 'bar'); // shortcut syntax
* ~~~~~
*
* #pw-group-Functions-API
* *
* @param string $key Optional property to get or set * @param string $key Optional property to get or set
* @param null $value Optional value to set * @param null $value Optional value to set
* @return Session|mixed * @return Session|null|string|array|int|float
* @see Session
* *
*/ */
function session($key = '', $value = null) { function session($key = '', $value = null) {
@@ -147,10 +227,21 @@ function session($key = '', $value = null) {
} }
/** /**
* Access the $fields API variable as a function * Get or save fields independent of templates ($fields API variable as as function)
*
* This function behaves the same as the `$fields` API variable, though does support
* an optional shortcut argument for getting a single field.
*
* ~~~~~
* $field = fields()->get('title'); // regular syntax
* $field = fields('title'); // shortcut syntax
* ~~~~~
*
* #pw-group-Functions-API
* *
* @param string $name Optional field name to retrieve * @param string $name Optional field name to retrieve
* @return Fields|Field|null * @return Fields|Field|null
* @see Fields
* *
*/ */
function fields($name = '') { function fields($name = '') {
@@ -158,10 +249,21 @@ function fields($name = '') {
} }
/** /**
* Access the $templates API variable as a function * Get or save templates ($templates API variable as a function)
*
* This function behaves the same as the `$templates` API variable, though does support
* an optional shortcut argument for getting a single template.
*
* ~~~~~~
* $t = templates()->get('basic-page'); // regular syntax
* $t = templates('basic-page'); // shortcut syntax
* ~~~~~~
*
* #pw-group-Functions-API
* *
* @param string $name Optional template to retrieve * @param string $name Optional template to retrieve
* @return Templates|Template|null * @return Templates|Template|null
* @see Templates
* *
*/ */
function templates($name = '') { function templates($name = '') {
@@ -169,9 +271,12 @@ function templates($name = '') {
} }
/** /**
* Access the $database API variable as a function * Create and execute PDO database queries ($database API variable as a function)
*
* #pw-group-Functions-API
* *
* @return WireDatabasePDO * @return WireDatabasePDO
* @see WireDatabasePDO
* *
*/ */
function database() { function database() {
@@ -179,12 +284,28 @@ function database() {
} }
/** /**
* Access the $permissions API varaible as a function * Get, find or save permissions ($permissions API variable as a function)
* *
* See the pages() function for usage details. * Accessing `permissions()` is exactly the same as accessing `$permissions`. Though there are a couple of optional
* shortcuts available by providing an argument to this function.
* *
* @param string $selector * ~~~~~
* // Get a permission
* $p = permissions()->get('page-edit'); // regular syntax
* $p = permissions('page-edit'); // shortcut syntax
*
* // Find permissions
* $ps = permissions()->find('name^=page'); // regular syntax
* $ps = permissions('name^=page'); // shortcut syntax
* ~~~~~
*
* #pw-group-Functions-API
*
* @param string|int $selector
* - Specify permission name or ID to retrieve that Permission (Permission)
* - Specify a selector string to return all permissions matching selector (PageArray)
* @return Permissions|Permission|PageArray|null|NullPage * @return Permissions|Permission|PageArray|null|NullPage
* @see Permissions
* *
*/ */
function permissions($selector = '') { function permissions($selector = '') {
@@ -192,12 +313,18 @@ function permissions($selector = '') {
} }
/** /**
* Access the $roles API varaible as a function * Get, find or save roles ($roles API variable as a function)
* *
* See the pages() function for usage details. * Accessing `roles()` is exactly the same as accessing `$roles`. Though there are a couple of optional
* shortcuts available by providing an argument to this function.
* *
* @param string $selector * #pw-group-Functions-API
*
* @param string|int $selector
* - Specify name or ID of role to get (Role object)
* - Specify selector string matching roles to find (PageArray object)
* @return Roles|Role|PageArray|null|NullPage * @return Roles|Role|PageArray|null|NullPage
* @see Roles
* *
*/ */
function roles($selector = '') { function roles($selector = '') {
@@ -205,17 +332,21 @@ function roles($selector = '') {
} }
/** /**
* Access the $sanitizer API variable as a function * Sanitize variables and related string functions ($sanitizer API variable as a function)
*
* This behaves the same as the `$sanitizer` API variable but supports arguments as optional shortcuts.
* *
* ~~~~~ * ~~~~~
* // Example usages * $clean = sanitizer()->pageName($dirty); // regular syntax
* $clean = sanitizer()->pageName($dirty); * $clean = sanitizer('pageName', $dirty); // shortcut syntax
* $clean = sanitizer('pageName', $dirty); // same as above
* ~~~~~ * ~~~~~
* *
* #pw-group-Functions-API
*
* @param string $name Optionally enter a sanitizer function name * @param string $name Optionally enter a sanitizer function name
* @param string $value If $name populated, enter the value to sanitize * @param string $value If $name populated, enter the value to sanitize
* @return Sanitizer|string|int|array|null|mixed * @return Sanitizer|string|int|array|null|mixed
* @see Sanitizer
* *
*/ */
function sanitizer($name = '', $value = '') { function sanitizer($name = '', $value = '') {
@@ -223,18 +354,23 @@ function sanitizer($name = '', $value = '') {
} }
/** /**
* Access the $datetime API variable as a function * Access date and time related tools ($datetime API variable as a function)
*
* This behaves the same as the `$datetime` API variable except that you can optionally provide
* arguments as a shortcut to the `$datetime->formatDate()` method.
* *
* ~~~~~ * ~~~~~
* // Example usages
* $str = datetime()->relativeTimeStr('2016-10-10'); * $str = datetime()->relativeTimeStr('2016-10-10');
* $str = datetime('Y-m-d'); * $str = datetime('Y-m-d'); // shortcut to formatDate method
* $str = datetime('Y-m-d', time()); * $str = datetime('Y-m-d', time()); // shortcut to formatDate method
* ~~~~~ * ~~~~~
* *
* #pw-group-Functions-API
*
* @param string $format Optional date format * @param string $format Optional date format
* @param string|int $value Optional date to format * @param string|int $value Optional date to format
* @return WireDateTime|string|int * @return WireDateTime|string|int
* @see WireDateTime
* *
*/ */
function datetime($format = '', $value = '') { function datetime($format = '', $value = '') {
@@ -242,9 +378,14 @@ function datetime($format = '', $value = '') {
} }
/** /**
* Access the $files API variable as a function * Access tools for working on the file system ($files API variable as a function)
*
* This behaves identically to the `$files` API variable and as no optional arguments.
*
* #pw-group-Functions-API
* *
* @return WireFileTools * @return WireFileTools
* @see WireFileTools
* *
*/ */
function files() { function files() {
@@ -252,16 +393,21 @@ function files() {
} }
/** /**
* Access the $cache API variable as a function * Get and save caches ($cache API variable as a function)
* *
* If called with no arguments it returns the $cache API variable. * This behaves the same as the $cache API variable but does support arguments as a
* If called with arguments, it can be used the same as `WireCache::get()`. * shortcut for the `$cache->get()` method.
*
* - If called with no arguments it returns the $cache API variable.
* - If called with arguments, it can be used the same as `WireCache::get()`.
*
* #pw-group-Functions-API
* *
* @param string $name * @param string $name
* @param callable|int|string|null $expire * @param callable|int|string|null $expire
* @param callable|int|string|null $func * @param callable|int|string|null $func
* @return WireCache|string|array|PageArray|null * @return WireCache|string|array|PageArray|null
* @see WireCache::get() * @see WireCache, WireCache::get()
* *
*/ */
function cache($name = '', $expire = null, $func = null) { function cache($name = '', $expire = null, $func = null) {
@@ -269,19 +415,22 @@ function cache($name = '', $expire = null, $func = null) {
} }
/** /**
* Access the $languages API variable as a function * Access all installed languages in multi-language environment ($languages API variable as a function)
* *
* Returns the $languages API variable, or a Language object if given a language name. * Returns the `$languages` API variable, or a `Language` object if given a language name or ID.
* *
* ~~~~ * ~~~~
* // Examples
* $languages = languages(); // Languages if active, null if not * $languages = languages(); // Languages if active, null if not
* $en = languages()->getDefault(); * $en = languages()->getDefault(); // Get default language
* $de = languages('de'); * $de = languages()->get('de'); // Get another language
* $de = languages('de'); // Get another language (shorcut syntax)
* ~~~~ * ~~~~
* *
* #pw-group-Functions-API
*
* @param string|int $name Optional Language name or ID for language to retrieve * @param string|int $name Optional Language name or ID for language to retrieve
* @return Languages|Language|NullPage|null * @return Languages|Language|NullPage|null
* @see Languages, Languages::get(), Language
* *
*/ */
function languages($name = '') { function languages($name = '') {
@@ -289,29 +438,44 @@ function languages($name = '') {
} }
/** /**
* Access the $input API variable as a function * Access GET, POST or COOKIE input variables and more ($input API variable as a function)
* *
* - Default behavior is to return the $input API var. * - Default behavior with no arguments is to return the `$input` API variable.
* - If given just a $type (like "get" or "post"), it will return a WireInputData object for that type. * - If given just a `$type` argument (like get or post), it will return a `WireInputData` object for that type.
* - If given a $type and $key it will return the input variable. * - If given a `$type` and `$key` arguments, it will return the value, or null if not present.
* - If all arguments given, the returned value will also be run through the given sanitizer. * - If `$sanitizer` argument given, the returned value will also be run through the given sanitizer.
* - If the `$sanitizer` argument is an array, the returned input value must be within the given list, or null if not (3.0.125+).
* - If `$fallback` argument given, it will return the fallback value if input value was not present or not valid (3.0.125+).
* - See the `WireInput::get()` method for all options.
* *
* ~~~~~ * ~~~~~
* // Examples * // Can be used the same way as the $input API variable
* // In examples below the “post” can also be “get” or “cookie”
* $input = input(); // Returns $input API var (WireInput) * $input = input(); // Returns $input API var (WireInput)
* $post = input('post'); // Returns $input->post (WireInputData) * $post = input()->post(); // Returns $input->post (WireInputData instance)
* $value = input('get', 'sort'); // Returns $input->get('sort'); * $foo = input()->post('foo'); // Returns POST variable “foo”
* $value = input('get', 'sort', 'fieldName'); // Returns $input->get('sort') run through $sanitizer->fieldName(). * $bar = input()->post('bar', 'text'); // Returns “bar” after text sanitizer (3.0.125+)
* $s = input()->post('s', ['foo', 'bar', 'baz']); // POST var “s” must match given list (3.0.125+)
*
* // You can also move the arguments all to the function call if you prefer:
* $s = input('get', 'sort'); // Returns GET var “sort”
* $s = input('get', 'sort', 'fieldName'); // Returns “sort” after “fieldName” sanitizer
* $s = input('get', 'sort', ['title', 'created']); // Require sort to be one in given array (3.0.125+)
* $s = input('get', 'sort', ['title', 'created'], 'title'); // Same as above, fallback to 'title' (3.0.125+)
* ~~~~~ * ~~~~~
* *
* #pw-group-Functions-API
*
* @param string $type Optionally indicate "get", "post", "cookie" or "whitelist" * @param string $type Optionally indicate "get", "post", "cookie" or "whitelist"
* @param string $key If getting a value, specify name of property containing value * @param string $key If getting a value, specify name of input property containing value
* @param string $sanitizer Optionally specify sanitizer name to run value through * @param string $sanitizer Optionally specify sanitizer name to run value through, or in 3.0.125+ may also be an array of allowed values.
* @return WireInput|WireInputData array|string|int|null * @param string|int|null $fallback Value to fallback to if input not present or invalid
* @return WireInput|WireInputData|array|string|int|null
* @see WireInput
* *
*/ */
function input($type = '', $key = '', $sanitizer = '') { function input($type = '', $key = '', $sanitizer = null, $fallback = null) {
return wireInput($type, $key, $sanitizer); return wireInput($type, $key, $sanitizer, $fallback);
} }
/** /**
@@ -319,6 +483,8 @@ function input($type = '', $key = '', $sanitizer = '') {
* *
* This is the same as the input() function except that the $type "get" is already implied. * This is the same as the input() function except that the $type "get" is already implied.
* *
* #pw-internal
*
* @param string $key * @param string $key
* @param string $sanitizer * @param string $sanitizer
* @return WireInputData|string|int|array|null * @return WireInputData|string|int|array|null
@@ -333,6 +499,8 @@ function inputGet($key = '', $sanitizer = '') {
* *
* This is the same as the input() function except that the $type "post" is already implied. * This is the same as the input() function except that the $type "post" is already implied.
* *
* #pw-internal
*
* @param string $key * @param string $key
* @param string $sanitizer * @param string $sanitizer
* @return WireInputData|string|int|array|null * @return WireInputData|string|int|array|null
@@ -347,6 +515,8 @@ function inputPost($key = '', $sanitizer = '') {
* *
* This is the same as the input() function except that the $type "cookie" is already implied. * This is the same as the input() function except that the $type "cookie" is already implied.
* *
* #pw-internal
*
* @param string $key * @param string $key
* @param string $sanitizer * @param string $sanitizer
* @return WireInputData|string|int|array|null * @return WireInputData|string|int|array|null
@@ -357,10 +527,21 @@ function inputCookie($key = '', $sanitizer = '') {
} }
/** /**
* Function that returns a $config->urls->[name] value o * Get one of any named system URLs (shortcut to the $config API variable “urls” property)
*
* URLs always have a trailing slash.
*
* ~~~~~
* // you can use either syntax below, where “templates” can be the name for any system URL
* $url = urls()->templates;
* $url = urls('templates');
* ~~~~~
*
* #pw-group-Functions-API
* *
* @param string $key * @param string $key
* @return null|Paths|string * @return null|Paths|string
* @see Config::urls()
* *
*/ */
function urls($key = '') { function urls($key = '') {
@@ -368,10 +549,21 @@ function urls($key = '') {
} }
/** /**
* Function that returns a $config->paths->[name] value o * Get one of any named server disk paths (shortcut to the $config API variable “paths” property)
*
* Paths always have a trailing slash.
*
* ~~~~~
* // you can use either syntax below, where “templates” can be the name for any system URL
* $path = paths()->templates;
* $path = paths('templates');
* ~~~~~
*
* #pw-group-Functions-API
* *
* @param string $key * @param string $key
* @return null|Paths|string * @return null|Paths|string
* @see Config::paths()
* *
*/ */
function paths($key = '') { function paths($key = '') {
@@ -381,6 +573,8 @@ function paths($key = '') {
/** /**
* Start or stop a profiler event or return WireProfilerInterface instance * Start or stop a profiler event or return WireProfilerInterface instance
* *
* #pw-internal
*
* @param string|array|object|null $name Name of event to start or event to stop * @param string|array|object|null $name Name of event to start or event to stop
* @param null|object|string $source If starting an event, optional source of event (object) * @param null|object|string $source If starting an event, optional source of event (object)
* @param array $data Optional extra data as associative array * @param array $data Optional extra data as associative array
@@ -392,7 +586,18 @@ function profiler($name = null, $source = null, $data = array()) {
} }
/** /**
* Get or set a region for front-end output * Get or set an output region (primarily for front-end output usage)
*
* This function is an convenience for storing markup that ultimately gets output in a _main.php file
* (or whatever file `$config->appendTemplateFile` is set to). It is an alternative to passing variables
* between included files and provides an interface for setting, appending, prepending and ultimately
* getting markup (or other strings) for output. Its designed for use the the “Delayed Output” strategy,
* though does not necessarily require it.
*
* This function can also be accessed as `wireRegion()`, and that function is always available
* regardless of whether the Functions API is enabled or not.
*
* *Note: unlike other functions in the Functions API, this function is not related to API variables.*
* *
* ~~~~~ * ~~~~~
* // define a region * // define a region
@@ -415,13 +620,16 @@ function profiler($name = null, $source = null, $data = array()) {
* *
* // clear all regions * // clear all regions
* region('*', ''); * region('*', '');
*
* ~~~~~ * ~~~~~
* *
* #pw-group-Functions-API
*
* @param string $key Name of region to get or set. * @param string $key Name of region to get or set.
* - Specify "*" to retrieve all defined regions in an array. * - Specify "*" to retrieve all defined regions in an array.
* - Prepend a "+" to the region name to have it prepend your given value to any existing value. * - Prepend a "+" to the region name to have it prepend your given value to any existing value.
* - Append a "+" to the region name to have it append your given value to any existing value. * - Append a "+" to the region name to have it append your given value to any existing value.
* - Prepend a "++" to region name to make future calls without "+" automatically prepend.
* - Append a "++" to region name to make future calls without "+" to automatically append.
* @param null|string $value If setting a region, the text that you want to set. * @param null|string $value If setting a region, the text that you want to set.
* @return string|null|bool|array Returns string of text when getting a region, NULL if region not set, or TRUE if setting region. * @return string|null|bool|array Returns string of text when getting a region, NULL if region not set, or TRUE if setting region.
* *
@@ -439,6 +647,8 @@ function region($key = '', $value = null) {
* ProcessWire. It is also preferable to using a variable (or variables) because it is always * ProcessWire. It is also preferable to using a variable (or variables) because it is always
* in scope and accessible anywhere in your template files, even within existing functions. * in scope and accessible anywhere in your template files, even within existing functions.
* *
* *Note: unlike other functions in the Functions API, this function is not related to API variables.*
*
* ~~~~~ * ~~~~~
* // set a setting named “foo” to value “bar” * // set a setting named “foo” to value “bar”
* setting('foo', 'bar'); * setting('foo', 'bar');
@@ -460,17 +670,14 @@ function region($key = '', $value = null) {
* setting(false, 'foo'); * setting(false, 'foo');
* ~~~~~ * ~~~~~
* *
* #pw-group-Functions-API
*
* @param string|array $name Setting name, or array to set multiple * @param string|array $name Setting name, or array to set multiple
* @param string|int|array|float|mixed $value Value to set, or omit if getting value of $name (default=null) * @param string|int|array|float|mixed $value Value to set, or omit if getting value of $name (default=null)
* @return array|string|int|bool|mixed|null * @return array|string|int|bool|mixed|null
* *
*/ */
function setting($name = '', $value = null) { function setting($name = '', $value = null) {
static $settings = []; return wireSetting($name, $value);
if($name === '') return $settings;
if(is_array($name)) return $settings = array_merge($settings, $name);
if($name === false) { unset($settings[(string) $value]); return null; }
if($value !== null) $settings[$name] = $value;
return isset($settings[$name]) ? $settings[$name] : null;
} }

View File

@@ -374,26 +374,30 @@ function wireLanguages($name = '') {
* *
* ~~~~~ * ~~~~~
* // Examples * // Examples
* $input = input(); // Returns $input API var (WireInput) * $input = wireInput(); // Returns $input API var (WireInput)
* $post = input('post'); // Returns $input->post (WireInputData) * $post = wireInput('post'); // Returns $input->post (WireInputData)
* $value = input('get', 'sort'); // Returns $input->get('sort'); * $post = wireInput()->post(); // Same as above
* $value = input('get', 'sort', 'fieldName'); // Returns $input->get('sort') run through $sanitizer->fieldName(). * $value = wireInput('get', 'sort'); // Returns $input->get('sort');
* $value = wireInput('get', 'sort', 'fieldName'); // Returns $input->get('sort') run through $sanitizer->fieldName().
* $value = wireInput('get', 'sort', 'fieldName', 'title'); // Same as above but fallback to 'title' if no sort is present (3.0.125)
* $value = wireInput('get', 'sort', ['title', 'created', 'likes'], 'title'); // Require value to be one given or fallback to 'title' (3.0.125+)
* $value = wireInput()->get('sort', ['title', 'created', 'likes'], 'title'); // Same as above (3.0.125)
* ~~~~~ * ~~~~~
* *
* @param string $type Optionally indicate "get", "post", "cookie" or "whitelist" * @param string $type Optionally indicate "get", "post", "cookie" or "whitelist"
* @param string $key If getting a value, specify name of property containing value * @param string $key If getting a value, specify name of property containing value
* @param string $sanitizer Optionally specify sanitizer name to run value through * @param string $sanitizer Optionally specify sanitizer name to run value through, or array containing whitelist of allowed values (3.0.125).
* @return WireInput|WireInputData array|string|int|null * @param mixed $fallback Fallback value to return rather than null if value not present or does not validate (3.0.125+)
* @return WireInput|WireInputData|array|string|int|null
* *
*/ */
function wireInput($type = '', $key = '', $sanitizer = '') { function wireInput($type = '', $key = '', $sanitizer = null, $fallback = null) {
/** @var WireInput $input */ /** @var WireInput $input */
$input = wire('input'); $input = wire('input');
if(!strlen($type)) return $input; if(!strlen($type)) return $input;
$type = strtolower($type); $type = strtolower($type);
if(!strlen($key)) return $input->$type; if(!strlen($key)) return $input->$type;
$value = $input->$type($key); $value = $input->$type($key, $sanitizer, $fallback);
if(strlen($sanitizer)) $value = wireSanitizer($sanitizer, $value);
return $value; return $value;
} }
@@ -402,13 +406,14 @@ function wireInput($type = '', $key = '', $sanitizer = '') {
* *
* This is the same as the input() function except that the $type "get" is already implied. * This is the same as the input() function except that the $type "get" is already implied.
* *
* @param string $key * @param string $key Name of input variable to get
* @param string $sanitizer * @param string $sanitizer Optionally specify sanitizer name to run value through, or array containing whitelist of allowed values (3.0.125+).
* @param mixed $fallback Fallback value to return rather than null if value not present or does not validate (3.0.125+)
* @return WireInputData|string|int|array|null * @return WireInputData|string|int|array|null
* *
*/ */
function wireInputGet($key = '', $sanitizer = '') { function wireInputGet($key = '', $sanitizer = null, $fallback = null) {
return wireInput('get', $key, $sanitizer); return wireInput('get', $key, $sanitizer, $fallback);
} }
/** /**
@@ -416,13 +421,14 @@ function wireInputGet($key = '', $sanitizer = '') {
* *
* This is the same as the input() function except that the $type "post" is already implied. * This is the same as the input() function except that the $type "post" is already implied.
* *
* @param string $key * @param string $key Name of input variable to get
* @param string $sanitizer * @param string $sanitizer Optionally specify sanitizer name to run value through, or array containing whitelist of allowed values (3.0.125).
* @param mixed $fallback Fallback value to return rather than null if value not present or does not validate (3.0.125+)
* @return WireInputData|string|int|array|null * @return WireInputData|string|int|array|null
* *
*/ */
function wireInputPost($key = '', $sanitizer = '') { function wireInputPost($key = '', $sanitizer = null, $fallback = null) {
return wireInput('post', $key, $sanitizer); return wireInput('post', $key, $sanitizer, $fallback);
} }
/** /**
@@ -430,13 +436,14 @@ function wireInputPost($key = '', $sanitizer = '') {
* *
* This is the same as the input() function except that the $type "cookie" is already implied. * This is the same as the input() function except that the $type "cookie" is already implied.
* *
* @param string $key * @param string $key Name of input variable to get
* @param string $sanitizer * @param string $sanitizer Optionally specify sanitizer name to run value through, or array containing whitelist of allowed values (3.0.125+).
* @param mixed $fallback Fallback value to return rather than null if value not present or does not validate (3.0.125+)
* @return WireInputData|string|int|array|null * @return WireInputData|string|int|array|null
* *
*/ */
function wireInputCookie($key = '', $sanitizer = '') { function wireInputCookie($key = '', $sanitizer = null, $fallback = null) {
return wireInput('cookie', $key, $sanitizer); return wireInput('cookie', $key, $sanitizer, $fallback);
} }
/** /**
@@ -504,6 +511,50 @@ function wirePaths($key = '') {
return wire('config')->paths($key); return wire('config')->paths($key);
} }
/**
* Get or set a runtime site setting
*
* This is a simple helper function for maintaining runtime settings in a site profile.
* It simply sets and gets settings that you define. It is preferable to using ProcessWires
* `$config` or `config()` API var/function because it is not used to store anything else for
* ProcessWire. It is also preferable to using a variable (or variables) because it is always
* in scope and accessible anywhere in your template files, even within existing functions.
*
* ~~~~~
* // set a setting named “foo” to value “bar”
* setting('foo', 'bar');
*
* // get a setting named “foo”
* $value = setting('foo');
*
* // set or replace multiple settings
* setting([
* 'foo' => 'value',
* 'bar' => 123,
* 'baz' => [ 'foo', 'bar', 'baz' ]
* ]);
*
* // get all settings in associative array
* $a = setting();
*
* // to unset a setting
* setting(false, 'foo');
* ~~~~~
*
* @param string|array $name Setting name, or array to set multiple
* @param string|int|array|float|mixed $value Value to set, or omit if getting value of $name (default=null)
* @return array|string|int|bool|mixed|null
*
*/
function wireSetting($name = '', $value = null) {
static $settings = array();
if($name === '') return $settings;
if(is_array($name)) return $settings = array_merge($settings, $name);
if($name === false) { unset($settings[(string) $value]); return null; }
if($value !== null) $settings[$name] = $value;
return isset($settings[$name]) ? $settings[$name] : null;
}
/** /**
* Return array of functions available from the functions API * Return array of functions available from the functions API
* *
@@ -534,7 +585,7 @@ function _wireFunctionsAPI() {
'region' => 'wireRegion', 'region' => 'wireRegion',
'roles' => 'wireRoles', 'roles' => 'wireRoles',
'sanitizer' => 'wireSanitizer', 'sanitizer' => 'wireSanitizer',
'setting' => '', // no implemented 'setting' => 'wireSetting',
'session' => 'wireSession', 'session' => 'wireSession',
'templates' => 'wireTemplates', 'templates' => 'wireTemplates',
'urls' => 'wireUrls', 'urls' => 'wireUrls',

View File

@@ -499,14 +499,23 @@ class WireFileTools extends Wire {
/** /**
* Return a new temporary directory/path ready to use for files * Return a new temporary directory/path ready to use for files
* *
* The directory will be automatically removed after a set period of time (default=120s)
*
* #pw-advanced * #pw-advanced
* *
* ~~~~~
* $td = $files->tempDir('hello-world');
* $path = (string) $td; // or use $td->get();
* file_put_contents($path . 'some-file.txt', 'Hello world');
* ~~~~~
*
* @param Object|string $name Provide the object that needs the temp dir, or name your own string * @param Object|string $name Provide the object that needs the temp dir, or name your own string
* @param array|int $options Options array to modify default behavior: * @param array|int $options Options array to modify default behavior:
* - `maxAge` (integer): Maximum age of temp dir files in seconds (default=120) * - `maxAge` (integer): Maximum age of temp dir files in seconds (default=120)
* - `basePath` (string): Base path where temp dirs should be created. Omit to use default (recommended). * - `basePath` (string): Base path where temp dirs should be created. Omit to use default (recommended).
* - Note: if you specify an integer for $options, then 'maxAge' is assumed. * - Note: if you specify an integer for $options, then 'maxAge' is assumed.
* @return WireTempDir * @return WireTempDir If you typecast return value to a string, it is the temp dir path (with trailing slash).
* @see WireTempDir
* *
*/ */
public function tempDir($name, $options = array()) { public function tempDir($name, $options = array()) {
@@ -929,12 +938,12 @@ class WireFileTools extends Wire {
/** /**
* Include a PHP file passing it all API variables and optionally your own specified variables * Include a PHP file passing it all API variables and optionally your own specified variables
* *
* This is the same as PHP's `include()` function except for the following: * This is the same as PHPs `include()` function except for the following:
* *
* - It receives all API variables and optionally your custom variables * - It receives all API variables and optionally your custom variables
* - If your filename is not absolute, it doesn't look in PHP's include path, only in the current dir. * - If your filename is not absolute, it doesnt look in PHPs include path, only in the current dir.
* - It only allows including files that are part of the PW installation: templates, core modules or site modules * - It only allows including files that are part of the PW installation: templates, core modules or site modules
* - It will assume a ".php" extension if filename has no extension. * - It will assume a .php extension if filename has no extension.
* *
* Note this function produces direct output. To retrieve output as a return value, use the * Note this function produces direct output. To retrieve output as a return value, use the
* `$files->render()` function instead. * `$files->render()` function instead.
@@ -948,7 +957,7 @@ class WireFileTools extends Wire {
* - `autoExtension` (string): Extension to assume when no ext in filename, make blank for no auto assumption (default=php) * - `autoExtension` (string): Extension to assume when no ext in filename, make blank for no auto assumption (default=php)
* - `allowedPaths` (array): Array of start paths include files are allowed from. Note current dir is always allowed. * - `allowedPaths` (array): Array of start paths include files are allowed from. Note current dir is always allowed.
* @return bool Always returns true * @return bool Always returns true
* @throws WireException if file doesn't exist or is not allowed * @throws WireException if file doesnt exist or is not allowed
* *
*/ */
function ___include($filename, array $vars = array(), array $options = array()) { function ___include($filename, array $vars = array(), array $options = array()) {