code
stringlengths 2.5k
150k
| kind
stringclasses 1
value |
---|---|
php session_destroy session\_destroy
================
(PHP 4, PHP 5, PHP 7, PHP 8)
session\_destroy — Destroys all data registered to a session
### Description
```
session_destroy(): bool
```
**session\_destroy()** destroys all of the data associated with the current session. It does not unset any of the global variables associated with the session, or unset the session cookie. To use the session variables again, [session\_start()](function.session-start) has to be called.
> **Note**: You do not have to call **session\_destroy()** from usual code. Cleanup $\_SESSION array rather than destroying session data.
>
>
In order to kill the session altogether, the session ID must also be unset. If a cookie is used to propagate the session ID (default behavior), then the session cookie must be deleted. [setcookie()](function.setcookie) may be used for that.
When [session.use\_strict\_mode](https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode) is enabled. You do not have to remove obsolete session ID cookie because session module will not accept session ID cookie when there is no data associated to the session ID and set new session ID cookie. Enabling [session.use\_strict\_mode](https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode) is recommended for all sites.
**Warning** Immediate session deletion may cause unwanted results. When there is concurrent requests, other connections may see sudden session data loss. e.g. Requests from JavaScript and/or requests from URL links.
Although current session module does not accept empty session ID cookie, but immediate session deletion may result in empty session ID cookie due to client(browser) side race condition. This will result that the client creates many session ID needlessly.
To avoid these, you must set deletion time-stamp to $\_SESSION and reject access while later. Or make sure your application does not have concurrent requests. This applies to [session\_regenerate\_id()](function.session-regenerate-id) also.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Destroying a session with [$\_SESSION](reserved.variables.session)**
```
<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();
// Unset all of the session variables.
$_SESSION = array();
// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
$params = session_get_cookie_params();
setcookie(session_name(), '', time() - 42000,
$params["path"], $params["domain"],
$params["secure"], $params["httponly"]
);
}
// Finally, destroy the session.
session_destroy();
?>
```
### Notes
>
> **Note**:
>
>
> Only use [session\_unset()](function.session-unset) for older deprecated code that does not use [$\_SESSION](reserved.variables.session).
>
>
### See Also
* [session.use\_strict\_mode](https://www.php.net/manual/en/session.configuration.php#ini.session.use-strict-mode)
* [session\_reset()](function.session-reset) - Re-initialize session array with original values
* [session\_regenerate\_id()](function.session-regenerate-id) - Update the current session id with a newly generated one
* [unset()](function.unset) - Unset a given variable
* [setcookie()](function.setcookie) - Send a cookie
php V8JsException::getJsSourceLine V8JsException::getJsSourceLine
==============================
(PECL v8js >= 0.1.0)
V8JsException::getJsSourceLine — The getJsSourceLine purpose
### Description
```
final public V8JsException::getJsSourceLine(): string
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php usort usort
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
usort — Sort an array by values using a user-defined comparison function
### Description
```
usort(array &$array, callable $callback): bool
```
Sorts `array` in place by values using a user-supplied comparison function to determine the order.
>
> **Note**:
>
>
> If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
>
>
> **Note**: This function assigns new keys to the elements in `array`. It will remove any existing keys that may have been assigned, rather than just reordering the keys.
>
>
### Parameters
`array`
The input array.
`callback`
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
```
callback(mixed $a, mixed $b): int
```
### Return Values
Always returns **`true`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | If `callback` expects a parameter to be passed by reference, this function will now emit an **`E_WARNING`**. |
### Examples
**Example #1 **usort()** example**
```
<?php
function cmp($a, $b)
{
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>
```
The above example will output:
```
0: 1
1: 2
2: 3
3: 5
4: 6
```
The spaceship operator may be used to simplify the internal comparison even further.
```
<?php
function cmp($a, $b)
{
return $a <=> $b;
}
$a = array(3, 2, 5, 6, 1);
usort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>
```
>
> **Note**:
>
>
> Obviously in this trivial case the [sort()](function.sort) function would be more appropriate.
>
>
**Example #2 **usort()** example using multi-dimensional array**
```
<?php
function cmp($a, $b)
{
return strcmp($a["fruit"], $b["fruit"]);
}
$fruits[0]["fruit"] = "lemons";
$fruits[1]["fruit"] = "apples";
$fruits[2]["fruit"] = "grapes";
usort($fruits, "cmp");
foreach ($fruits as $key => $value) {
echo "\$fruits[$key]: " . $value["fruit"] . "\n";
}
?>
```
When sorting a multi-dimensional array, $a and $b contain references to the first index of the array.
The above example will output:
```
$fruits[0]: apples
$fruits[1]: grapes
$fruits[2]: lemons
```
**Example #3 **usort()** example using a member function of an object**
```
<?php
class TestObj {
private string $name;
function __construct($name)
{
$this->name = $name;
}
/* This is the static comparing function: */
static function cmp_obj($a, $b)
{
return strtolower($a->name) <=> strtolower($b->name);
}
}
$a[] = new TestObj("c");
$a[] = new TestObj("b");
$a[] = new TestObj("d");
usort($a, [TestObj::class, "cmp_obj"]);
foreach ($a as $item) {
echo $item->name . "\n";
}
?>
```
The above example will output:
```
b
c
d
```
**Example #4 **usort()** example using a [closure](functions.anonymous) to sort a multi-dimensional array**
```
<?php
$array[0] = array('key_a' => 'z', 'key_b' => 'c');
$array[1] = array('key_a' => 'x', 'key_b' => 'b');
$array[2] = array('key_a' => 'y', 'key_b' => 'a');
function build_sorter($key) {
return function ($a, $b) use ($key) {
return strnatcmp($a[$key], $b[$key]);
};
}
usort($array, build_sorter('key_b'));
foreach ($array as $item) {
echo $item['key_a'] . ', ' . $item['key_b'] . "\n";
}
?>
```
The above example will output:
```
y, a
x, b
z, c
```
**Example #5 **usort()** example using the spaceship operator**
The spaceship operator allows for straightforward comparison of compound values across multiple axes. The following example will sort `$people` by last name, then by first name if the last name matches.
```
<?php
$people[0] = ['first' => 'Adam', 'last' => 'West'];
$people[1] = ['first' => 'Alec', 'last' => 'Baldwin'];
$people[2] = ['first' => 'Adam', 'last' => 'Baldwin'];
function sorter(array $a, array $b) {
return [$a['last'], $a['first']] <=> [$b['last'], $b['first']];
}
usort($people, 'sorter');
foreach ($people as $person) {
print $person['last'] . ', ' . $person['first'] . PHP_EOL;
}
?>
```
The above example will output:
```
Baldwin, Adam
Baldwin, Alec
West, Adam
```
### See Also
* [uasort()](function.uasort) - Sort an array with a user-defined comparison function and maintain index association
* [uksort()](function.uksort) - Sort an array by keys using a user-defined comparison function
* The [comparison of array sorting functions](https://www.php.net/manual/en/array.sorting.php)
php Imagick::setImageProfile Imagick::setImageProfile
========================
(PECL imagick 2, PECL imagick 3)
Imagick::setImageProfile — Adds a named profile to the Imagick object
### Description
```
public Imagick::setImageProfile(string $name, string $profile): bool
```
Adds a named profile to the Imagick object. If a profile with the same name already exists, it is replaced. This method differs from the Imagick::ProfileImage() method in that it does not apply any CMS color profiles.
### Parameters
`name`
`profile`
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
php EventBase::getFeatures EventBase::getFeatures
======================
(PECL event >= 1.2.6-beta)
EventBase::getFeatures — Returns bitmask of features supported
### Description
```
public EventBase::getFeatures(): int
```
Returns bitmask of features supported.
### Parameters
This function has no parameters.
### Return Values
Returns integer representing a bitmask of supported features. See [EventConfig::FEATURE\_\* constants](class.eventconfig#eventconfig.constants) .
### Examples
**Example #1 **EventBase::getFeatures()** example**
```
<?php
// Avoiding "select" method
$cfg = new EventConfig();
if ($cfg->avoidMethod("select")) {
echo "'select' method avoided\n";
}
$base = new EventBase($cfg);
echo "Features:\n";
$features = $base->getFeatures();
($features & EventConfig::FEATURE_ET) and print("ET - edge-triggered IO\n");
($features & EventConfig::FEATURE_O1) and print("O1 - O(1) operation for adding/deletting events\n");
($features & EventConfig::FEATURE_FDS) and print("FDS - arbitrary file descriptor types, and not just sockets\n");
?>
```
### See Also
* [EventBase::getMethod()](eventbase.getmethod) - Returns event method in use
* [EventConfig](class.eventconfig)
php The Yaf_Exception_LoadFailed_Module class
The Yaf\_Exception\_LoadFailed\_Module class
============================================
Introduction
------------
(Yaf >=1.0.0)
Class synopsis
--------------
class **Yaf\_Exception\_LoadFailed\_Module** extends [Yaf\_Exception\_LoadFailed](class.yaf-exception-loadfailed) { /\* Properties \*/ /\* Methods \*/ /\* Inherited methods \*/
```
public Yaf_Exception::getPrevious(): void
```
}
php Gmagick::readimageblob Gmagick::readimageblob
======================
(PECL gmagick >= Unknown)
Gmagick::readimageblob — Reads image from a binary string
### Description
```
public Gmagick::readimageblob(string $imageContents, string $filename = ?): Gmagick
```
Reads image from a binary string.
### Parameters
`imageContents`
Content of image.
`filename`
The image filename.
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php mysqli::release_savepoint mysqli::release\_savepoint
==========================
mysqli\_release\_savepoint
==========================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
mysqli::release\_savepoint -- mysqli\_release\_savepoint — Removes the named savepoint from the set of savepoints of the current transaction
### Description
Object-oriented style
```
public mysqli::release_savepoint(string $name): bool
```
Procedural style:
```
mysqli_release_savepoint(mysqli $mysql, string $name): bool
```
This function is identical to executing `$mysqli->query("RELEASE SAVEPOINT `$name`");`. This function does not trigger commit or rollback.
### Parameters
`mysql`
Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init)
`name`
The identifier of the savepoint.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [mysqli\_savepoint()](mysqli.savepoint) - Set a named transaction savepoint
php Ds\Sequence::contains Ds\Sequence::contains
=====================
(PECL ds >= 1.0.0)
Ds\Sequence::contains — Determines if the sequence contains given values
### Description
```
abstract public Ds\Sequence::contains(mixed ...$values): bool
```
Determines if the sequence contains all values.
### Parameters
`values`
Values to check.
### Return Values
**`false`** if any of the provided `values` are not in the sequence, **`true`** otherwise.
### Examples
**Example #1 **Ds\Sequence::contains()** example**
```
<?php
$sequence = new \Ds\Vector(['a', 'b', 'c', 1, 2, 3]);
var_dump($sequence->contains('a')); // true
var_dump($sequence->contains('a', 'b')); // true
var_dump($sequence->contains('c', 'd')); // false
var_dump($sequence->contains(...['c', 'b', 'a'])); // true
// Always strict
var_dump($sequence->contains(1)); // true
var_dump($sequence->contains('1')); // false
var_dump($sequece->contains(...[])); // true
?>
```
The above example will output something similar to:
```
bool(true)
bool(true)
bool(false)
bool(true)
bool(true)
bool(false)
bool(true)
```
php UConverter::setSourceEncoding UConverter::setSourceEncoding
=============================
(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)
UConverter::setSourceEncoding — Set the source encoding
### Description
```
public UConverter::setSourceEncoding(string $encoding): bool
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`encoding`
### Return Values
php stream_filter_prepend stream\_filter\_prepend
=======================
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
stream\_filter\_prepend — Attach a filter to a stream
### Description
```
stream_filter_prepend(
resource $stream,
string $filtername,
int $read_write = ?,
mixed $params = ?
): resource
```
Adds `filtername` to the list of filters attached to `stream`.
### Parameters
`stream`
The target stream.
`filtername`
The filter name.
`read_write`
By default, **stream\_filter\_prepend()** will attach the filter to the `read filter chain` if the file was opened for reading (i.e. File Mode: `r`, and/or `+`). The filter will also be attached to the `write filter chain` if the file was opened for writing (i.e. File Mode: `w`, `a`, and/or `+`). **`STREAM_FILTER_READ`**, **`STREAM_FILTER_WRITE`**, and/or **`STREAM_FILTER_ALL`** can also be passed to the `read_write` parameter to override this behavior. See [stream\_filter\_append()](function.stream-filter-append) for an example of using this parameter.
`params`
This filter will be added with the specified `params` to the *beginning* of the list and will therefore be called first during stream operations. To add a filter to the end of the list, use [stream\_filter\_append()](function.stream-filter-append).
### Return Values
Returns a resource on success or **`false`** on failure. The resource can be used to refer to this filter instance during a call to [stream\_filter\_remove()](function.stream-filter-remove).
**`false`** is returned if `stream` is not a resource or if `filtername` cannot be located.
### Notes
> **Note**: **When using custom (user) filters**
> [stream\_filter\_register()](function.stream-filter-register) must be called first in order to register the desired user filter to `filtername`.
>
>
> **Note**: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is prepended to a stream, data in the internal buffers, which has already been processed through other filters will *not* be reprocessed through the new filter at that time. This differs from the behavior of [stream\_filter\_append()](function.stream-filter-append).
>
>
> **Note**: When a filter is added for read and write, two instances of the filter are created. **stream\_filter\_prepend()** must be called twice with **`STREAM_FILTER_READ`** and **`STREAM_FILTER_WRITE`** to get both filter resources.
>
>
### See Also
* [stream\_filter\_register()](function.stream-filter-register) - Register a user defined stream filter
* [stream\_filter\_append()](function.stream-filter-append) - Attach a filter to a stream
php SQLite3::exec SQLite3::exec
=============
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3::exec — Executes a result-less query against a given database
### Description
```
public SQLite3::exec(string $query): bool
```
Executes a result-less query against a given database.
> **Note**: SQLite3 may need to create [» temporary files](https://sqlite.org/tempfiles.html) during the execution of queries, so the respective directories may have to be writable.
>
>
### Parameters
`query`
The SQL query to execute (typically an INSERT, UPDATE, or DELETE query).
### Return Values
Returns **`true`** if the query succeeded, **`false`** on failure.
### Examples
**Example #1 **SQLite3::exec()** example**
```
<?php
$db = new SQLite3('mysqlitedb.db');
$db->exec('CREATE TABLE bar (bar TEXT)');
?>
```
php SVM::crossvalidate SVM::crossvalidate
==================
(PECL svm >= 0.1.0)
SVM::crossvalidate — Test training params on subsets of the training data
### Description
```
public svm::crossvalidate(array $problem, int $number_of_folds): float
```
Crossvalidate can be used to test the effectiveness of the current parameter set on a subset of the training data. Given a problem set and a n "folds", it separates the problem set into n subsets, and the repeatedly trains on one subset and tests on another. While the accuracy will generally be lower than a SVM trained on the enter data set, the accuracy score returned should be relatively useful, so it can be used to test different training parameters.
### Parameters
`problem`
The problem data. This can either be in the form of an array, the URL of an SVMLight formatted file, or a stream to an opened SVMLight formatted datasource.
`number_of_folds`
The number of sets the data should be divided into and cross tested. A higher number means smaller training sets and less reliability. 5 is a good number to start with.
### Return Values
The correct percentage, expressed as a floating point number from 0-1. In the case of NU\_SVC or EPSILON\_SVR kernels the mean squared error will returned instead.
### See Also
* [SVM::train()](svm.train) - Create a SVMModel based on training data
php stats_harmonic_mean stats\_harmonic\_mean
=====================
(PECL stats >= 1.0.0)
stats\_harmonic\_mean — Returns the harmonic mean of an array of values
### Description
```
stats_harmonic_mean(array $a): number
```
Returns the harmonic mean of the values in `a`.
### Parameters
`a`
The input array
### Return Values
Returns the harmonic mean of the values in `a`, or **`false`** if `a` is empty or is not an array.
| programming_docs |
php posix_setsid posix\_setsid
=============
(PHP 4, PHP 5, PHP 7, PHP 8)
posix\_setsid — Make the current process a session leader
### Description
```
posix_setsid(): int
```
Make the current process a session leader.
### Parameters
This function has no parameters.
### Return Values
Returns the session id, or -1 on errors.
### See Also
* The POSIX.1 and the setsid(2) manual page on the POSIX system for more information on process groups and job control.
php SolrQuery::getHighlightFragsize SolrQuery::getHighlightFragsize
===============================
(PECL solr >= 0.9.2)
SolrQuery::getHighlightFragsize — Returns the number of characters of fragments to consider for highlighting
### Description
```
public SolrQuery::getHighlightFragsize(string $field_override = ?): int
```
Returns the number of characters of fragments to consider for highlighting. Zero implies no fragmenting. The entire field should be used.
### Parameters
`field_override`
The name of the field
### Return Values
Returns an integer on success or **`null`** if not set.
php Imagick::getImageDepth Imagick::getImageDepth
======================
(PECL imagick 2, PECL imagick 3)
Imagick::getImageDepth — Gets the image depth
### Description
```
public Imagick::getImageDepth(): int
```
Gets the image depth.
### Parameters
This function has no parameters.
### Return Values
The image depth.
php SolrQuery::getHighlightRegexPattern SolrQuery::getHighlightRegexPattern
===================================
(PECL solr >= 0.9.2)
SolrQuery::getHighlightRegexPattern — Returns the regular expression for fragmenting
### Description
```
public SolrQuery::getHighlightRegexPattern(): string
```
Returns the regular expression used for fragmenting
### Parameters
This function has no parameters.
### Return Values
Returns a string on success and **`null`** if not set.
php ParentIterator::rewind ParentIterator::rewind
======================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
ParentIterator::rewind — Rewind the iterator
### Description
```
public ParentIterator::rewind(): void
```
Rewinds the iterator.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php gmp_neg gmp\_neg
========
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
gmp\_neg — Negate number
### Description
```
gmp_neg(GMP|int|string $num): GMP
```
Returns the negative value of a number.
### Parameters
`num`
A [GMP](class.gmp) object, an int or a numeric string.
### Return Values
Returns -`num`, as a GMP number.
### Examples
**Example #1 **gmp\_neg()** example**
```
<?php
$neg1 = gmp_neg("1");
echo gmp_strval($neg1) . "\n";
$neg2 = gmp_neg("-1");
echo gmp_strval($neg2) . "\n";
?>
```
The above example will output:
```
-1
1
```
php ZipArchive::open ZipArchive::open
================
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)
ZipArchive::open — Open a ZIP file archive
### Description
```
public ZipArchive::open(string $filename, int $flags = 0): bool|int
```
Opens a new or existing zip archive for reading, writing or modifying.
Since libzip 1.6.0, a empty file is not a valid archive any longer.
### Parameters
`filename`
The file name of the ZIP archive to open.
`flags`
The mode to use to open the archive.
* **`[ZipArchive::OVERWRITE](https://www.php.net/manual/en/zip.constants.php#ziparchive.constants.overwrite)`**
* **`[ZipArchive::CREATE](https://www.php.net/manual/en/zip.constants.php#ziparchive.constants.create)`**
* **`[ZipArchive::RDONLY](https://www.php.net/manual/en/zip.constants.php#ziparchive.constants.rdonly)`**
* **`[ZipArchive::EXCL](https://www.php.net/manual/en/zip.constants.php#ziparchive.constants.excl)`**
* **`[ZipArchive::CHECKCONS](https://www.php.net/manual/en/zip.constants.php#ziparchive.constants.checkcons)`**
### Return Values
Returns **`true`** on success, **`false`** or one of the following error codes on error:
**`ZipArchive::ER_EXISTS`**
File already exists. **`ZipArchive::ER_INCONS`**
Zip archive inconsistent. **`ZipArchive::ER_INVAL`**
Invalid argument. **`ZipArchive::ER_MEMORY`**
Malloc failure. **`ZipArchive::ER_NOENT`**
No such file. **`ZipArchive::ER_NOZIP`**
Not a zip archive. **`ZipArchive::ER_OPEN`**
Can't open file. **`ZipArchive::ER_READ`**
Read error. **`ZipArchive::ER_SEEK`**
Seek error. ### Examples
**Example #1 Open and extract**
```
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
echo 'ok';
$zip->extractTo('test');
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>
```
**Example #2 Create an archive**
```
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('test.txt', 'file content goes here');
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
```
**Example #3 Create an temporary archive**
```
<?php
$name = tempnam(sys_get_temp_dir(), "FOO");
$zip = new ZipArchive;
$res = $zip->open($name, ZipArchive::OVERWRITE); /* truncate as empty file is not valid */
if ($res === TRUE) {
$zip->addFile('data.txt', 'entryname.txt');
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
```
php runkit7_object_id runkit7\_object\_id
===================
(PECL runkit7 >= Unknown)
runkit7\_object\_id — Return the integer object handle for given object
### Description
```
runkit7_object_id(object $obj): int
```
This function is equivalent to [spl\_object\_id()](function.spl-object-id).
This function returns a unique identifier for the object. The object id is unique for the lifetime of the object. Once the object is destroyed, its id may be reused for other objects. This behavior is similar to [spl\_object\_hash()](function.spl-object-hash).
### Parameters
`obj`
Any object.
### Return Values
An integer identifier that is unique for each currently existing object and is always the same for each object.
### Notes
>
> **Note**:
>
>
> When an object is destroyed, its id may be reused for other objects.
>
>
### See Also
* [spl\_object\_id()](function.spl-object-id) - Return the integer object handle for given object
php Imagick::setResolution Imagick::setResolution
======================
(PECL imagick 2, PECL imagick 3)
Imagick::setResolution — Sets the image resolution
### Description
```
public Imagick::setResolution(float $x_resolution, float $y_resolution): bool
```
Sets the image resolution.
### Parameters
`x_resolution`
The horizontal resolution.
`y_resolution`
The vertical resolution.
### Return Values
Returns **`true`** on success.
### Notes
**Imagick::setResolution()** must be called before loading or creating an image.
### See Also
* [Imagick::setImageResolution()](imagick.setimageresolution) - Sets the image resolution
* [Imagick::getImageResolution()](imagick.getimageresolution) - Gets the image X and Y resolution
php GearmanClient::addTaskBackground GearmanClient::addTaskBackground
================================
(PECL gearman >= 0.5.0)
GearmanClient::addTaskBackground — Add a background task to be run in parallel
### Description
```
public GearmanClient::addTaskBackground(
string $function_name,
string $workload,
mixed &$context = ?,
string $unique = ?
): GearmanTask
```
Adds a background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call [GearmanClient::runTasks()](gearmanclient.runtasks) to perform the work.
### Parameters
`function_name`
A registered function the worker is to execute
`workload`
Serialized data to be processed
`context`
Application context to associate with a task
`unique`
A unique ID used to identify a particular task
### Return Values
A [GearmanTask](class.gearmantask) object or **`false`** if the task could not be added.
### Examples
**Example #1 Two tasks, one background and one not**
This example illustrates the difference between running a background task and a normal task. The client adds two tasks to execute the same function, but one is added with **addTaskBackground()**. A callback is set so that progress of the job can be tracked. A simple worker with an artificial delay reports on the job progress and the client picks this up through the callback. Two workers are run for this example. Note that the background task does not show in the client output.
```
<?php
# The client script
# create our gearman client
$gmc= new GearmanClient();
# add the default job server
$gmc->addServer();
# set a couple of callbacks so we can track progress
$gmc->setCompleteCallback("reverse_complete");
$gmc->setStatusCallback("reverse_status");
# add a task for the "reverse" function
$task= $gmc->addTask("reverse", "Hello World!", null, "1");
# add another task, but this one to run in the background
$task= $gmc->addTaskBackground("reverse", "!dlroW olleH", null, "2");
if (! $gmc->runTasks())
{
echo "ERROR " . $gmc->error() . "\n";
exit;
}
echo "DONE\n";
function reverse_status($task)
{
echo "STATUS: " . $task->unique() . ", " . $task->jobHandle() . " - " . $task->taskNumerator() .
"/" . $task->taskDenominator() . "\n";
}
function reverse_complete($task)
{
echo "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";
}
?>
```
```
<?php
# The worker script
echo "Starting\n";
# Create our worker object.
$gmworker= new GearmanWorker();
# Add default server (localhost).
$gmworker->addServer();
# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");
print "Waiting for job...\n";
while($gmworker->work())
{
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}
function reverse_fn($job)
{
echo "Received job: " . $job->handle() . "\n";
$workload = $job->workload();
$workload_size = $job->workloadSize();
echo "Workload: $workload ($workload_size)\n";
# This status loop is not needed, just showing how it works
for ($x= 0; $x < $workload_size; $x++)
{
echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
$job->sendStatus($x+1, $workload_size);
$job->sendData(substr($workload, $x, 1));
sleep(1);
}
$result= strrev($workload);
echo "Result: $result\n";
# Return what we want to send back to the client.
return $result;
}
?>
```
Worker output for two workers running:
```
Received job: H:foo.local:65
Workload: !dlroW olleH (12)
1/12 complete
Received job: H:foo.local:66
Workload: Hello World! (12)
Sending status: 1/12 complete
Sending status: 2/12 complete
Sending status: 2/12 complete
Sending status: 3/12 complete
Sending status: 3/12 complete
Sending status: 4/12 complete
Sending status: 4/12 complete
Sending status: 5/12 complete
Sending status: 5/12 complete
Sending status: 6/12 complete
Sending status: 6/12 complete
Sending status: 7/12 complete
Sending status: 7/12 complete
Sending status: 8/12 complete
Sending status: 8/12 complete
Sending status: 9/12 complete
Sending status: 9/12 complete
Sending status: 10/12 complete
Sending status: 10/12 complete
Sending status: 11/12 complete
Sending status: 11/12 complete
Sending status: 12/12 complete
Sending status: 12/12 complete
Result: !dlroW olleH
Result: Hello World!
```
Client output:
```
STATUS: 1, H:foo.local:66 - 1/12
STATUS: 1, H:foo.local:66 - 2/12
STATUS: 1, H:foo.local:66 - 3/12
STATUS: 1, H:foo.local:66 - 4/12
STATUS: 1, H:foo.local:66 - 5/12
STATUS: 1, H:foo.local:66 - 6/12
STATUS: 1, H:foo.local:66 - 7/12
STATUS: 1, H:foo.local:66 - 8/12
STATUS: 1, H:foo.local:66 - 9/12
STATUS: 1, H:foo.local:66 - 10/12
STATUS: 1, H:foo.local:66 - 11/12
STATUS: 1, H:foo.local:66 - 12/12
COMPLETE: 1, !dlroW olleH
DONE
```
### See Also
* [GearmanClient::addTask()](gearmanclient.addtask) - Add a task to be run in parallel
* [GearmanClient::addTaskHigh()](gearmanclient.addtaskhigh) - Add a high priority task to run in parallel
* [GearmanClient::addTaskLow()](gearmanclient.addtasklow) - Add a low priority task to run in parallel
* [GearmanClient::addTaskHighBackground()](gearmanclient.addtaskhighbackground) - Add a high priority background task to be run in parallel
* [GearmanClient::addTaskLowBackground()](gearmanclient.addtasklowbackground) - Add a low priority background task to be run in parallel
* [GearmanClient::runTasks()](gearmanclient.runtasks) - Run a list of tasks in parallel
php xdiff_string_bdiff_size xdiff\_string\_bdiff\_size
==========================
(PECL xdiff >= 1.5.0)
xdiff\_string\_bdiff\_size — Read a size of file created by applying a binary diff
### Description
```
xdiff_string_bdiff_size(string $patch): int
```
Returns a size of a result file that would be created after applying binary `patch` to the original file.
### Parameters
`patch`
The binary patch created by [xdiff\_string\_bdiff()](function.xdiff-string-bdiff) or [xdiff\_string\_rabdiff()](function.xdiff-string-rabdiff) function.
### Return Values
Returns the size of file that would be created.
### Examples
**Example #1 **xdiff\_string\_bdiff\_size()** example**
The following code applies reads a size of file that would be created after applying a binary diff.
```
<?php
$binary_patch = file_get_contents('file.bdiff');
$length = xdiff_string_bdiff_size($binary_patch);
echo "Resulting file will be $length bytes long";
?>
```
### See Also
* [xdiff\_string\_bdiff()](function.xdiff-string-bdiff) - Make binary diff of two strings
* [xdiff\_string\_rabdiff()](function.xdiff-string-rabdiff) - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm
* [xdiff\_string\_bpatch()](function.xdiff-string-bpatch) - Patch a string with a binary diff
php GearmanTask::unique GearmanTask::unique
===================
(PECL gearman >= 0.6.0)
GearmanTask::unique — Get the unique identifier for a task
### Description
```
public GearmanTask::unique(): string
```
Returns the unique identifier for this task. This is assigned by the [GearmanClient](class.gearmanclient), as opposed to the job handle which is set by the Gearman job server.
### Parameters
This function has no parameters.
### Return Values
The unique identifier, or **`false`** if no identifier is assigned.
### See Also
* [GearmanClient::do()](gearmanclient.do) - Run a single task and return a result [deprecated]
* [GearmanClient::addTask()](gearmanclient.addtask) - Add a task to be run in parallel
php uksort uksort
======
(PHP 4, PHP 5, PHP 7, PHP 8)
uksort — Sort an array by keys using a user-defined comparison function
### Description
```
uksort(array &$array, callable $callback): bool
```
Sorts `array` in place by keys using a user-supplied comparison function to determine the order.
>
> **Note**:
>
>
> If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
>
>
>
> **Note**:
>
>
> Resets array's internal pointer to the first element.
>
>
### Parameters
`array`
The input array.
`callback`
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
```
callback(mixed $a, mixed $b): int
```
### Return Values
Always returns **`true`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | If `callback` expects a parameter to be passed by reference, this function will now emit an **`E_WARNING`**. |
### Examples
**Example #1 **uksort()** example**
```
<?php
function cmp($a, $b)
{
$a = preg_replace('@^(a|an|the) @', '', $a);
$b = preg_replace('@^(a|an|the) @', '', $b);
return strcasecmp($a, $b);
}
$a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4);
uksort($a, "cmp");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
?>
```
The above example will output:
```
an apple: 3
a banana: 4
the Earth: 2
John: 1
```
### See Also
* [usort()](function.usort) - Sort an array by values using a user-defined comparison function
* [uasort()](function.uasort) - Sort an array with a user-defined comparison function and maintain index association
* The [comparison of array sorting functions](https://www.php.net/manual/en/array.sorting.php)
php GmagickDraw::rectangle GmagickDraw::rectangle
======================
(PECL gmagick >= Unknown)
GmagickDraw::rectangle — Draws a rectangle
### Description
```
public GmagickDraw::rectangle(
float $x1,
float $y1,
float $x2,
float $y2
): GmagickDraw
```
Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings.
### Parameters
`x1`
x ordinate of first coordinate
`y1`
y ordinate of first coordinate
`x2`
x ordinate of second coordinate
`y2`
y ordinate of second coordinate
### Return Values
The [GmagickDraw](class.gmagickdraw) object.
php SolrQuery::addGroupField SolrQuery::addGroupField
========================
(PECL solr >= 2.2.0)
SolrQuery::addGroupField — Add a field to be used to group results
### Description
```
public SolrQuery::addGroupField(string $value): SolrQuery
```
The name of the field by which to group results. The field must be single-valued, and either be indexed or a field type that has a value source and works in a function query, such as ExternalFileField. It must also be a string-based field, such as StrField or TextField Uses group.field parameter
### Parameters
`value`
The name of the field.
### Return Values
Returns an instance of [SolrQuery](class.solrquery).
### See Also
* [SolrQuery::setGroup()](solrquery.setgroup) - Enable/Disable result grouping (group parameter)
* [SolrQuery::addGroupFunction()](solrquery.addgroupfunction) - Allows grouping results based on the unique values of a function query (group.func parameter)
* [SolrQuery::addGroupQuery()](solrquery.addgroupquery) - Allows grouping of documents that match the given query
* [SolrQuery::addGroupSortField()](solrquery.addgroupsortfield) - Add a group sort field (group.sort parameter)
* [SolrQuery::setGroupFacet()](solrquery.setgroupfacet) - Sets group.facet parameter
* [SolrQuery::setGroupOffset()](solrquery.setgroupoffset) - Sets the group.offset parameter
* [SolrQuery::setGroupLimit()](solrquery.setgrouplimit) - Specifies the number of results to return for each group. The server default value is 1
* [SolrQuery::setGroupMain()](solrquery.setgroupmain) - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
* [SolrQuery::setGroupNGroups()](solrquery.setgroupngroups) - If true, Solr includes the number of groups that have matched the query in the results
* [SolrQuery::setGroupTruncate()](solrquery.setgrouptruncate) - If true, facet counts are based on the most relevant document of each group matching the query
* [SolrQuery::setGroupFormat()](solrquery.setgroupformat) - Sets the group format, result structure (group.format parameter)
* [SolrQuery::setGroupCachePercent()](solrquery.setgroupcachepercent) - Enables caching for result grouping
| programming_docs |
php The DOMException class
The DOMException class
======================
Introduction
------------
(PHP 5, PHP 7, PHP 8)
DOM operations raise exceptions under particular circumstances, i.e., when an operation is impossible to perform for logical reasons.
See also [Exceptions](language.exceptions).
Class synopsis
--------------
final class **DOMException** extends [Exception](class.exception) { /\* Properties \*/ public int [$code](class.domexception#domexception.props.code); /\* Inherited properties \*/
protected string [$message](class.exception#exception.props.message) = "";
private string [$string](class.exception#exception.props.string) = "";
protected int [$code](class.exception#exception.props.code);
protected string [$file](class.exception#exception.props.file) = "";
protected int [$line](class.exception#exception.props.line);
private array [$trace](class.exception#exception.props.trace) = [];
private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/
```
final public Exception::getMessage(): string
```
```
final public Exception::getPrevious(): ?Throwable
```
```
final public Exception::getCode(): int
```
```
final public Exception::getFile(): string
```
```
final public Exception::getLine(): int
```
```
final public Exception::getTrace(): array
```
```
final public Exception::getTraceAsString(): string
```
```
public Exception::__toString(): string
```
```
private Exception::__clone(): void
```
} Properties
----------
code An integer indicating the type of error generated
php EvTimer::set EvTimer::set
============
(PECL ev >= 0.2.0)
EvTimer::set — Configures the watcher
### Description
```
public EvTimer::set( float $after , float $repeat ): void
```
Configures the watcher
### Parameters
`after` Configures the timer to trigger after `after` seconds.
`repeat` If repeat is **`0.0`** , then it will automatically be stopped once the timeout is reached. If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.
### Return Values
No value is returned.
php imagelayereffect imagelayereffect
================
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
imagelayereffect — Set the alpha blending flag to use layering effects
### Description
```
imagelayereffect(GdImage $image, int $effect): bool
```
Set the alpha blending flag to use layering effects.
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`effect`
One of the following constants:
**`IMG_EFFECT_REPLACE`**
Use pixel replacement (equivalent of passing **`true`** to [imagealphablending()](function.imagealphablending)) **`IMG_EFFECT_ALPHABLEND`**
Use normal pixel blending (equivalent of passing **`false`** to [imagealphablending()](function.imagealphablending)) **`IMG_EFFECT_NORMAL`**
Same as **`IMG_EFFECT_ALPHABLEND`**. **`IMG_EFFECT_OVERLAY`**
Overlay has the effect that black background pixels will remain black, white background pixels will remain white, but grey background pixels will take the colour of the foreground pixel. **`IMG_EFFECT_MULTIPLY`**
Overlays with a multiply effect. ### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
| 7.2.0 | Added **`IMG_EFFECT_MULTIPLY`** (requires system libgd >= 2.1.1 or the bundled libgd). |
### Examples
**Example #1 **imagelayereffect()** example**
```
<?php
// Setup an image
$im = imagecreatetruecolor(100, 100);
// Set a background
imagefilledrectangle($im, 0, 0, 100, 100, imagecolorallocate($im, 220, 220, 220));
// Apply the overlay alpha blending flag
imagelayereffect($im, IMG_EFFECT_OVERLAY);
// Draw two grey ellipses
imagefilledellipse($im, 50, 50, 40, 40, imagecolorallocate($im, 100, 255, 100));
imagefilledellipse($im, 50, 50, 50, 80, imagecolorallocate($im, 100, 100, 255));
imagefilledellipse($im, 50, 50, 80, 50, imagecolorallocate($im, 255, 100, 100));
// Output
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
```
The above example will output something similar to:
php Fiber::throw Fiber::throw
============
(PHP 8 >= 8.1.0)
Fiber::throw — Resumes execution of the fiber with an exception
### Description
```
public Fiber::throw(Throwable $exception): mixed
```
Resumes the fiber by throwing the given exception from the current [Fiber::suspend()](fiber.suspend) call.
If the fiber is not suspended when this method is called, a [FiberError](class.fibererror) will be thrown.
### Parameters
`exception`
The exception to throw into the fiber from the current [Fiber::suspend()](fiber.suspend) call.
### Return Values
The value provided to the next call to [Fiber::suspend()](fiber.suspend) or **`null`** if the fiber returns. If the fiber throws an exception before suspending, it will be thrown from the call to this method.
php ZipArchive::getStream ZipArchive::getStream
=====================
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)
ZipArchive::getStream — Get a file handler to the entry defined by its name (read only)
### Description
```
public ZipArchive::getStream(string $name): resource|false
```
Get a file handler to the entry defined by its name. For now, it only supports read operations.
### Parameters
`name`
The name of the entry to use.
### Return Values
Returns a file pointer (resource) on success or **`false`** on failure.
### Examples
**Example #1 Get the entry contents with [fread()](function.fread) and store it**
```
<?php
$contents = '';
$z = new ZipArchive();
if ($z->open('test.zip')) {
$fp = $z->getStream('test');
if(!$fp) exit("failed\n");
while (!feof($fp)) {
$contents .= fread($fp, 2);
}
fclose($fp);
file_put_contents('t',$contents);
echo "done.\n";
}
?>
```
**Example #2 Same as the previous example but with [fopen()](function.fopen) and the zip stream wrapper**
```
<?php
$contents = '';
$fp = fopen('zip://' . dirname(__FILE__) . '/test.zip#test', 'r');
if (!$fp) {
exit("cannot open\n");
}
while (!feof($fp)) {
$contents .= fread($fp, 2);
}
echo "$contents\n";
fclose($fp);
echo "done.\n";
?>
```
**Example #3 Stream wrapper and image, can be used with the xml function as well**
```
<?php
$im = imagecreatefromgif('zip://' . dirname(__FILE__) . '/test_im.zip#pear_item.gif');
imagepng($im, 'a.png');
?>
```
### See Also
* [ZipArchive::getStreamIndex()](ziparchive.getstreamindex) - Get a file handler to the entry defined by its index (read only)
* [ZipArchive::getStreamName()](ziparchive.getstreamname) - Get a file handler to the entry defined by its name (read only)
* [Compression Streams](https://www.php.net/manual/en/wrappers.compression.php)
php sqlsrv_fetch_array sqlsrv\_fetch\_array
====================
(No version information available, might only be in Git)
sqlsrv\_fetch\_array — Returns a row as an array
### Description
```
sqlsrv_fetch_array(
resource $stmt,
int $fetchType = ?,
int $row = ?,
int $offset = ?
): array
```
Returns the next available row of data as an associative array, a numeric array, or both (the default).
### Parameters
`stmt`
A statement resource returned by sqlsrv\_query or sqlsrv\_prepare.
`fetchType`
A predefined constant specifying the type of array to return. Possible values are **`SQLSRV_FETCH_ASSOC`**, **`SQLSRV_FETCH_NUMERIC`**, and **`SQLSRV_FETCH_BOTH`** (the default).
A fetch type of SQLSRV\_FETCH\_ASSOC should not be used when consuming a result set with multiple columns of the same name.
`row`
Specifies the row to access in a result set that uses a scrollable cursor. Possible values are **`SQLSRV_SCROLL_NEXT`**, **`SQLSRV_SCROLL_PRIOR`**, **`SQLSRV_SCROLL_FIRST`**, **`SQLSRV_SCROLL_LAST`**, **`SQLSRV_SCROLL_ABSOLUTE`** and, **`SQLSRV_SCROLL_RELATIVE`** (the default). When this parameter is specified, the `fetchType` must be explicitly defined.
`offset`
Specifies the row to be accessed if the row parameter is set to **`SQLSRV_SCROLL_ABSOLUTE`** or **`SQLSRV_SCROLL_RELATIVE`**. Note that the first row in a result set has index 0.
### Return Values
Returns an array on success, **`null`** if there are no more rows to return, and **`false`** if an error occurs.
### Examples
**Example #1 Retrieving an associative array.**
```
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['LastName'].", ".$row['FirstName']."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
```
**Example #2 Retrieving a numeric array.**
```
<?php
$serverName = "serverName\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT FirstName, LastName FROM SomeTable";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
echo $row[0].", ".$row[1]."<br />";
}
sqlsrv_free_stmt( $stmt);
?>
```
### Notes
Not specifying the `fetchType` or explicitly using the **`SQLSRV_FETCH_TYPE`** constant in the examples above will return an array that has both associative and numeric keys.
If more than one column is returned with the same name, the last column will take precedence. To avoid field name collisions, use aliases.
If a column with no name is returned, the associative key for the array element will be an empty string ("").
### See Also
* [sqlsrv\_connect()](function.sqlsrv-connect) - Opens a connection to a Microsoft SQL Server database
* [sqlsrv\_query()](function.sqlsrv-query) - Prepares and executes a query
* [sqlsrv\_errors()](function.sqlsrv-errors) - Returns error and warning information about the last SQLSRV operation performed
* [sqlsrv\_fetch()](function.sqlsrv-fetch) - Makes the next row in a result set available for reading
php Gmagick::levelimage Gmagick::levelimage
===================
(PECL gmagick >= Unknown)
Gmagick::levelimage — Adjusts the levels of an image
### Description
```
public Gmagick::levelimage(
float $blackPoint,
float $gamma,
float $whitePoint,
int $channel = Gmagick::CHANNEL_DEFAULT
): mixed
```
Adjusts the levels of an image by scaling the colors falling between specified white and black points to the full available quantum range. The parameters provided represent the black, mid, and white points. The black point specifies the darkest color in the image. Colors darker than the black point are set to zero. Mid point specifies a gamma correction to apply to the image. White point specifies the lightest color in the image. Colors brighter than the white point are set to the maximum quantum value.
### Parameters
`blackPoint`
The image black point.
`gamma`
The gamma value.
`whitePoint`
The image white point.
`channel`
Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of [channel constants](https://www.php.net/manual/en/gmagick.constants.php#gmagick.constants.channel).
### Return Values
[Gmagick](class.gmagick) object with image leveled.
### Errors/Exceptions
Throws an **GmagickException** on error.
php MessageFormatter::formatMessage MessageFormatter::formatMessage
===============================
msgfmt\_format\_message
=======================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
MessageFormatter::formatMessage -- msgfmt\_format\_message — Quick format message
### Description
Object-oriented style
```
public static MessageFormatter::formatMessage(string $locale, string $pattern, array $values): string|false
```
Procedural style
```
msgfmt_format_message(string $locale, string $pattern, array $values): string|false
```
Quick formatting function that formats the string without having to explicitly create the formatter object. Use this function when the format operation is done only once and does not need any parameters or state to be kept or when wanting to customize the output by providing additional context to ICU directly.
### Parameters
`locale`
The locale to use for formatting locale-dependent parts
`pattern`
The pattern string to insert things into. The pattern uses an 'apostrophe-friendly' syntax; see [» Quoting/Escaping](https://unicode-org.github.io/icu/userguide/format_parse/messages/#quotingescaping) for details.
`values`
The array of values to insert into the format string
### Return Values
The formatted pattern string or **`false`** if an error occurred
### Examples
**Example #1 **msgfmt\_format\_message()** example**
```
<?php
echo msgfmt_format_message("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo msgfmt_format_message("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
?>
```
**Example #2 OO example**
```
<?php
echo MessageFormatter::formatMessage("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree\n", array(4560, 123, 4560/123));
echo MessageFormatter::formatMessage("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum\n", array(4560, 123, 4560/123));
?>
```
The above example will output:
```
4,560 monkeys on 123 trees make 37.073 monkeys per tree
4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum
```
**Example #3 Instructing ICU to format currency with common and with narrow currency symbol**
Requires ICU ≥ 67.
```
<?php
echo msgfmt_format_message("cs_CZ", "{0, number, :: currency/CAD}", array(123.45));
echo msgfmt_format_message("cs_CZ", "{0, number, :: currency/CAD unit-width-narrow}", array(123.45));
```
The above example will output:
```
123,45 CA$
123,45 $
```
### See Also
* [msgfmt\_create()](messageformatter.create) - Constructs a new Message Formatter
* [msgfmt\_parse()](messageformatter.parse) - Parse input string according to pattern
* [msgfmt\_get\_error\_code()](messageformatter.geterrorcode) - Get the error code from last operation
* [msgfmt\_get\_error\_message()](messageformatter.geterrormessage) - Get the error text from the last operation
php gmp_kronecker gmp\_kronecker
==============
(PHP 7 >= 7.3.0, PHP 8)
gmp\_kronecker — Kronecker symbol
### Description
```
gmp_kronecker(GMP|int|string $num1, GMP|int|string $num2): int
```
This function computes the Kronecker symbol of `num1` and `num2`.
### Parameters
`num1`
A [GMP](class.gmp) object, an int or a numeric string.
`num2`
A [GMP](class.gmp) object, an int or a numeric string.
### Return Values
Returns the Kronecker symbol of `num1` and `num2`
### See Also
* [gmp\_jacobi()](function.gmp-jacobi) - Jacobi symbol
* [gmp\_legendre()](function.gmp-legendre) - Legendre symbol
php socket_set_nonblock socket\_set\_nonblock
=====================
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket\_set\_nonblock — Sets nonblocking mode for file descriptor fd
### Description
```
socket_set_nonblock(Socket $socket): bool
```
The **socket\_set\_nonblock()** function sets the **`O_NONBLOCK`** flag on the socket specified by the `socket` parameter.
When an operation (e.g. receive, send, connect, accept, ...) is performed on a non-blocking socket, the script will not pause its execution until it receives a signal or it can perform the operation. Rather, if the operation would result in a block, the called function will fail.
### Parameters
`socket`
A [Socket](class.socket) instance created with [socket\_create()](function.socket-create) or [socket\_accept()](function.socket-accept).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. |
### Examples
**Example #1 **socket\_set\_nonblock()** example**
```
<?php
$socket = socket_create_listen(1223);
socket_set_nonblock($socket);
socket_accept($socket);
?>
```
This example creates a listening socket on all interfaces on port 1223 and sets the socket to **`O_NONBLOCK`** mode. [socket\_accept()](function.socket-accept) will immediately fail unless there is a pending connection exactly at this moment.
### See Also
* [socket\_set\_block()](function.socket-set-block) - Sets blocking mode on a socket
* [socket\_set\_option()](function.socket-set-option) - Sets socket options for the socket
* [stream\_set\_blocking()](function.stream-set-blocking) - Set blocking/non-blocking mode on a stream
php Imagick::getImageBorderColor Imagick::getImageBorderColor
============================
(PECL imagick 2, PECL imagick 3)
Imagick::getImageBorderColor — Returns the image border color
### Description
```
public Imagick::getImageBorderColor(): ImagickPixel
```
Returns the image border color.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
php None Namespaces and dynamic language features
----------------------------------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
PHP's implementation of namespaces is influenced by its dynamic nature as a programming language. Thus, to convert code like the following example into namespaced code:
**Example #1 Dynamically accessing elements**
example1.php:
```
<?php
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "global";
$a = 'classname';
$obj = new $a; // prints classname::__construct
$b = 'funcname';
$b(); // prints funcname
echo constant('constname'), "\n"; // prints global
?>
```
One must use the fully qualified name (class name with namespace prefix). Note that because there is no difference between a qualified and a fully qualified Name inside a dynamic class name, function name, or constant name, the leading backslash is not necessary. **Example #2 Dynamically accessing namespaced elements**
```
<?php
namespace namespacename;
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "namespaced";
/* note that if using double quotes, "\\namespacename\\classname" must be used */
$a = '\namespacename\classname';
$obj = new $a; // prints namespacename\classname::__construct
$a = 'namespacename\classname';
$obj = new $a; // also prints namespacename\classname::__construct
$b = 'namespacename\funcname';
$b(); // prints namespacename\funcname
$b = '\namespacename\funcname';
$b(); // also prints namespacename\funcname
echo constant('\namespacename\constname'), "\n"; // prints namespaced
echo constant('namespacename\constname'), "\n"; // also prints namespaced
?>
```
Be sure to read the [note about escaping namespace names in strings](language.namespaces.faq#language.namespaces.faq.quote).
| programming_docs |
php EvLoop::timer EvLoop::timer
=============
(PECL ev >= 0.2.0)
EvLoop::timer — Creates EvTimer watcher object associated with the current event loop instance
### Description
```
final public EvLoop::timer(
float $after ,
float $repeat ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): EvTimer
```
Creates EvTimer watcher object associated with the current event loop instance
### Parameters
All parameters have the same meaning as for [EvTimer::\_\_construct()](evtimer.construct)
### Return Values
Returns EvTimer object on success
### See Also
* [EvTimer::\_\_construct()](evtimer.construct) - Constructs an EvTimer watcher object
php Yaf_Dispatcher::setDefaultAction Yaf\_Dispatcher::setDefaultAction
=================================
(Yaf >=1.0.0)
Yaf\_Dispatcher::setDefaultAction — Change default action name
### Description
```
public Yaf_Dispatcher::setDefaultAction(string $action): Yaf_Dispatcher
```
### Parameters
`action`
### Return Values
php mcrypt_enc_get_supported_key_sizes mcrypt\_enc\_get\_supported\_key\_sizes
=======================================
(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)
mcrypt\_enc\_get\_supported\_key\_sizes — Returns an array with the supported keysizes of the opened algorithm
**Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged.
### Description
```
mcrypt_enc_get_supported_key_sizes(resource $td): array
```
Gets the supported key sizes of the opened algorithm.
### Parameters
`td`
The encryption descriptor.
### Return Values
Returns an array with the key sizes supported by the algorithm specified by the encryption descriptor. If it returns an empty array then all key sizes between 1 and [mcrypt\_enc\_get\_key\_size()](function.mcrypt-enc-get-key-size) are supported by the algorithm.
### Examples
**Example #1 **mcrypt\_enc\_get\_supported\_key\_sizes()** example**
```
<?php
$td = mcrypt_module_open('rijndael-256', '', 'ecb', '');
var_dump(mcrypt_enc_get_supported_key_sizes($td));
?>
```
The above example will output:
```
array(3) {
[0]=>
int(16)
[1]=>
int(24)
[2]=>
int(32)
}
```
php PDOStatement::debugDumpParams PDOStatement::debugDumpParams
=============================
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)
PDOStatement::debugDumpParams — Dump an SQL prepared command
### Description
```
public PDOStatement::debugDumpParams(): ?bool
```
Dumps the information contained by a prepared statement directly on the output. It will provide the `SQL` query in use, the number of parameters used (`Params`), the list of parameters with their key name or position, their name, their position in the query (if this is supported by the PDO driver, otherwise, it will be -1), type (`param_type`) as an integer, and a boolean value `is_param`.
This is a debug function, which dumps the data directly to the normal output.
**Tip**As with anything that outputs its result directly to the browser, the [output-control functions](https://www.php.net/manual/en/book.outcontrol.php) can be used to capture the output of this function, and save it in a string (for example).
This will only dump the parameters in the statement at the moment of the dump. Extra parameters are not stored in the statement, and not displayed.
### Parameters
This function has no parameters.
### Return Values
Returns **`null`**, or **`false`** in case of an error.
### Changelog
| Version | Description |
| --- | --- |
| 7.2.0 | **PDOStatement::debugDumpParams()** now returns the SQL sent to the database, including the full, raw query (including the replaced placeholders with their bounded values). Note, that this will only be available if emulated prepared statements are turned on. |
### Examples
**Example #1 **PDOStatement::debugDumpParams()** example with named parameters**
```
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories, PDO::PARAM_INT);
$sth->bindValue(':colour', $colour, PDO::PARAM_STR, 12);
$sth->execute();
$sth->debugDumpParams();
?>
```
The above example will output:
```
SQL: [96] SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour
Params: 2
Key: Name: [9] :calories
paramno=-1
name=[9] ":calories"
is_param=1
param_type=1
Key: Name: [7] :colour
paramno=-1
name=[7] ":colour"
is_param=1
param_type=2
```
**Example #2 **PDOStatement::debugDumpParams()** example with unnamed parameters**
```
<?php
/* Execute a prepared statement by binding PHP variables */
$calories = 150;
$colour = 'red';
$name = 'apple';
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindValue(2, $colour, PDO::PARAM_STR);
$sth->execute();
$sth->debugDumpParams();
?>
```
The above example will output:
```
SQL: [82] SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?
Params: 2
Key: Position #0:
paramno=0
name=[0] ""
is_param=1
param_type=1
Key: Position #1:
paramno=1
name=[0] ""
is_param=1
param_type=2
```
### See Also
* [PDO::prepare()](pdo.prepare) - Prepares a statement for execution and returns a statement object
* [PDOStatement::bindParam()](pdostatement.bindparam) - Binds a parameter to the specified variable name
* [PDOStatement::bindValue()](pdostatement.bindvalue) - Binds a value to a parameter
php Ds\Pair::copy Ds\Pair::copy
=============
(No version information available, might only be in Git)
Ds\Pair::copy — Returns a shallow copy of the pair
### Description
```
public Ds\Pair::copy(): Ds\Pair
```
Returns a shallow copy of the pair.
### Parameters
This function has no parameters.
### Return Values
Returns a shallow copy of the pair.
### Examples
**Example #1 **Ds\Pair::copy()** example**
```
<?php
$a = new \Ds\Pair("a", 1);
$b = $a->copy();
$a->key = "x";
print_r($a);
print_r($b);
?>
```
The above example will output something similar to:
```
Ds\Pair Object
(
[key] => x
[value] => 1
)
Ds\Pair Object
(
[key] => a
[value] => 1
)
```
php enchant_dict_store_replacement enchant\_dict\_store\_replacement
=================================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )
enchant\_dict\_store\_replacement — Add a correction for a word
### Description
```
enchant_dict_store_replacement(EnchantDictionary $dictionary, string $misspelled, string $correct): void
```
Add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list.
### Parameters
`dictionary`
An Enchant dictionary returned by [enchant\_broker\_request\_dict()](function.enchant-broker-request-dict) or [enchant\_broker\_request\_pwl\_dict()](function.enchant-broker-request-pwl-dict).
`misspelled`
The work to fix
`correct`
The correct word
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `dictionary` expects an [EnchantDictionary](class.enchantdictionary) instance now; previoulsy, a [resource](language.types.resource) was expected. |
php Parle\RLexer::insertMacro Parle\RLexer::insertMacro
=========================
(PECL parle >= 0.5.1)
Parle\RLexer::insertMacro — Insert regex macro
### Description
```
public Parle\RLexer::insertMacro(string $name, string $regex): void
```
Insert a regex macro, that can be later used as a shortcut and included in other regular expressions.
### Parameters
`name`
Name of the macros.
`regex`
Regular expression.
### Return Values
No value is returned.
php mysqli_stmt::$insert_id mysqli\_stmt::$insert\_id
=========================
mysqli\_stmt\_insert\_id
========================
(PHP 5, PHP 7, PHP 8)
mysqli\_stmt::$insert\_id -- mysqli\_stmt\_insert\_id — Get the ID generated from the previous INSERT operation
### Description
Object-oriented style
int|string [$mysqli\_stmt->insert\_id](mysqli-stmt.insert-id); Procedural style
```
mysqli_stmt_insert_id(mysqli_stmt $statement): int|string
```
**Warning**This function is currently not documented; only its argument list is available.
php EventHttpRequest::addHeader EventHttpRequest::addHeader
===========================
(PECL event >= 1.4.0-beta)
EventHttpRequest::addHeader — Adds an HTTP header to the headers of the request
### Description
```
public EventHttpRequest::addHeader( string $key , string $value , int $type ): bool
```
Adds an HTTP header to the headers of the request.
### Parameters
`key` Header name.
`value` Header value.
`type` One of [`EventHttpRequest::*_HEADER` constants](class.eventhttprequest#eventhttprequest.constants) .
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [EventHttpRequest::removeHeader()](eventhttprequest.removeheader) - Removes an HTTP header from the headers of the request
php SolrResponse::getResponse SolrResponse::getResponse
=========================
(PECL solr >= 0.9.2)
SolrResponse::getResponse — Returns a SolrObject representing the XML response from the server
### Description
```
public SolrResponse::getResponse(): SolrObject
```
Returns a SolrObject representing the XML response from the server.
### Parameters
This function has no parameters.
### Return Values
Returns a SolrObject representing the XML response from the server
php SolrDocument::offsetUnset SolrDocument::offsetUnset
=========================
(PECL solr >= 0.9.2)
SolrDocument::offsetUnset — Removes a field
### Description
```
public SolrDocument::offsetUnset(string $fieldName): void
```
Removes a field from the document.
### Parameters
`fieldName`
The name of the field.
### Return Values
No return value.
php bzflush bzflush
=======
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
bzflush — Do nothing
### Description
```
bzflush(resource $bz): bool
```
This function is supposed to force a write of all buffered bzip2 data for the file pointer `bz`, but is implemented as null function in libbz2, and as such does nothing.
### Parameters
`bz`
The file pointer. It must be valid and must point to a file successfully opened by [bzopen()](function.bzopen).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [bzread()](function.bzread) - Binary safe bzip2 file read
* [bzwrite()](function.bzwrite) - Binary safe bzip2 file write
php fnmatch fnmatch
=======
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
fnmatch — Match filename against a pattern
### Description
```
fnmatch(string $pattern, string $filename, int $flags = 0): bool
```
**fnmatch()** checks if the passed `filename` would match the given shell wildcard `pattern`.
### Parameters
`pattern`
The shell wildcard pattern.
`filename`
The tested string. This function is especially useful for filenames, but may also be used on regular strings.
The average user may be used to shell patterns or at least in their simplest form to `'?'` and `'*'` wildcards so using **fnmatch()** instead of [preg\_match()](function.preg-match) for frontend search expression input may be way more convenient for non-programming users.
`flags`
The value of `flags` can be any combination of the following flags, joined with the [binary OR (|) operator](language.operators.bitwise).
**A list of possible flags for **fnmatch()**** | `Flag` | Description |
| --- | --- |
| **`FNM_NOESCAPE`** | Disable backslash escaping. |
| **`FNM_PATHNAME`** | Slash in string only matches slash in the given pattern. |
| **`FNM_PERIOD`** | Leading period in string must be exactly matched by period in the given pattern. |
| **`FNM_CASEFOLD`** | Caseless match. Part of the GNU extension. |
### Return Values
Returns **`true`** if there is a match, **`false`** otherwise.
### Examples
**Example #1 Checking a color name against a shell wildcard pattern**
```
<?php
if (fnmatch("*gr[ae]y", $color)) {
echo "some form of gray ...";
}
?>
```
### Notes
**Warning** For now, this function is not available on non-POSIX compliant systems except Windows.
### See Also
* [glob()](function.glob) - Find pathnames matching a pattern
* [preg\_match()](function.preg-match) - Perform a regular expression match
* [sscanf()](function.sscanf) - Parses input from a string according to a format
* [printf()](function.printf) - Output a formatted string
* [sprintf()](function.sprintf) - Return a formatted string
php ReflectionClass::getDocComment ReflectionClass::getDocComment
==============================
(PHP 5, PHP 7, PHP 8)
ReflectionClass::getDocComment — Gets doc comments
### Description
```
public ReflectionClass::getDocComment(): string|false
```
Gets doc comments from a class. Doc comments start with `/**`, followed by whitespace. If there are multiple doc comments above the class definition, the one closest to the class will be taken.
### Parameters
This function has no parameters.
### Return Values
The doc comment if it exists, otherwise **`false`**.
### Examples
**Example #1 **ReflectionClass::getDocComment()** example**
```
<?php
/**
* A test class
*
* @param foo bar
* @return baz
*/
class TestClass { }
$rc = new ReflectionClass('TestClass');
var_dump($rc->getDocComment());
?>
```
The above example will output:
```
string(61) "/**
* A test class
*
* @param foo bar
* @return baz
*/"
```
### See Also
* [ReflectionClass::getName()](reflectionclass.getname) - Gets class name
php SplFileObject::ftruncate SplFileObject::ftruncate
========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
SplFileObject::ftruncate — Truncates the file to a given length
### Description
```
public SplFileObject::ftruncate(int $size): bool
```
Truncates the file to `size` bytes.
### Parameters
`size`
The size to truncate to.
>
> **Note**:
>
>
> If `size` is larger than the file it is extended with null bytes.
>
> If `size` is smaller than the file, the extra data will be lost.
>
>
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **SplFileObject::ftruncate()** example**
```
<?php
// Create file containing "Hello World!"
$file = new SplFileObject("/tmp/ftruncate", "w+");
$file->fwrite("Hello World!");
// Truncate to 5 bytes
$file->ftruncate(5);
// Rewind and read data
$file->rewind();
echo $file->fgets();
?>
```
The above example will output something similar to:
```
Hello
```
### See Also
* [ftruncate()](function.ftruncate) - Truncates a file to a given length
php None Unsetting References
--------------------
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:
```
<?php
$a = 1;
$b =& $a;
unset($a);
?>
```
won't unset $b, just $a. Again, it might be useful to think about this as analogous to the Unix **unlink** call.
php ldap_rename ldap\_rename
============
(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)
ldap\_rename — Modify the name of an entry
### Description
```
ldap_rename(
LDAP\Connection $ldap,
string $dn,
string $new_rdn,
string $new_parent,
bool $delete_old_rdn,
?array $controls = null
): bool
```
The entry specified by `dn` is renamed/moved.
### Parameters
`ldap`
An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect).
`dn`
The distinguished name of an LDAP entity.
`new_rdn`
The new RDN.
`new_parent`
The new parent/superior entry.
`delete_old_rdn`
If **`true`** the old RDN value(s) is removed, else the old RDN value(s) is retained as non-distinguished values of the entry.
`controls`
Array of [LDAP Controls](https://www.php.net/manual/en/ldap.controls.php) to send with the request.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. |
| 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. |
| 7.3.0 | Support for `controls` added |
### Notes
>
> **Note**:
>
>
> This function currently only works with LDAPv3. You may have to use [ldap\_set\_option()](function.ldap-set-option) prior to binding to use LDAPv3. This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x.
>
>
### See Also
* [ldap\_rename\_ext()](function.ldap-rename-ext) - Modify the name of an entry
* [ldap\_modify()](function.ldap-modify) - Alias of ldap\_mod\_replace
php SyncSharedMemory::write SyncSharedMemory::write
=======================
(PECL sync >= 1.1.0)
SyncSharedMemory::write — Copy data to named shared memory
### Description
```
public SyncSharedMemory::write(string $string = ?, int $start = 0)
```
Copies data to named shared memory.
### Parameters
`string`
The data to write to shared memory.
>
> **Note**:
>
>
> If the size of the data exceeds the size of the shared memory, the number of bytes written returned will be less than the length of the input.
>
>
`start`
The start/offset, in bytes, to begin writing.
>
> **Note**:
>
>
> If the value is negative, the starting position will begin at the specified number of bytes from the end of the shared memory segment.
>
>
### Return Values
An integer containing the number of bytes written to shared memory.
### Examples
**Example #1 **SyncSharedMemory::write()** example**
```
<?php
// You will probably need to protect shared memory with other synchronization objects.
// Shared memory goes away when the last reference to it disappears.
$mem = new SyncSharedMemory("AppReportName", 1024);
if ($mem->first())
{
// Do first time initialization work here.
}
$result = $mem->write("report.txt");
var_dump($result);
$result = $mem->write("report.txt", -3);
var_dump($result);
?>
```
The above example will output something similar to:
```
int(10)
int(3)
```
### See Also
* [SyncSharedMemory::\_\_construct()](syncsharedmemory.construct) - Constructs a new SyncSharedMemory object
* [SyncSharedMemory::first()](syncsharedmemory.first) - Check to see if the object is the first instance system-wide of named shared memory
* **SyncSharedMemory::write()**
* [SyncSharedMemory::read()](syncsharedmemory.read) - Copy data from named shared memory
php The RarArchive class
The RarArchive class
====================
Introduction
------------
(PECL rar >= 2.0.0)
This class represents a RAR archive, which may be formed by several volumes (parts) and which contains a number of RAR entries (i.e., files, directories and other special objects such as symbolic links).
Objects of this class can be traversed, yielding the entries stored in the respective RAR archive. Those entries can also be obtained through [RarArchive::getEntry()](rararchive.getentry) and [RarArchive::getEntries()](rararchive.getentries).
Class synopsis
--------------
final class **RarArchive** implements [Traversable](class.traversable) { /\* Methods \*/
```
public close(): bool
```
```
public getComment(): string
```
```
public getEntries(): array|false
```
```
public getEntry(string $entryname): RarEntry|false
```
```
public isBroken(): bool
```
```
public isSolid(): bool
```
```
public static open(string $filename, string $password = NULL, callable $volume_callback = NULL): RarArchive|false
```
```
public setAllowBroken(bool $allow_broken): bool
```
```
public __toString(): string
```
} Table of Contents
-----------------
* [RarArchive::close](rararchive.close) — Close RAR archive and free all resources
* [RarArchive::getComment](rararchive.getcomment) — Get comment text from the RAR archive
* [RarArchive::getEntries](rararchive.getentries) — Get full list of entries from the RAR archive
* [RarArchive::getEntry](rararchive.getentry) — Get entry object from the RAR archive
* [RarArchive::isBroken](rararchive.isbroken) — Test whether an archive is broken (incomplete)
* [RarArchive::isSolid](rararchive.issolid) — Check whether the RAR archive is solid
* [RarArchive::open](rararchive.open) — Open RAR archive
* [RarArchive::setAllowBroken](rararchive.setallowbroken) — Whether opening broken archives is allowed
* [RarArchive::\_\_toString](rararchive.tostring) — Get text representation
| programming_docs |
php InternalIterator::key InternalIterator::key
=====================
(PHP 8)
InternalIterator::key — Return the key of the current element
### Description
```
public InternalIterator::key(): mixed
```
Returns the key of the current element.
### Parameters
This function has no parameters.
### Return Values
Returns the key of the current element.
php GearmanClient::setClientCallback GearmanClient::setClientCallback
================================
(PECL gearman <= 0.5.0)
GearmanClient::setClientCallback — Callback function when there is a data packet for a task (deprecated)
### Description
```
public GearmanClient::setClientCallback(callable $callback): void
```
Sets the callback function for accepting data packets for a task. The callback function should take a single argument, a [GearmanTask](class.gearmantask) object.
>
> **Note**:
>
>
> This method has been replaced by [GearmanClient::setDataCallback()](gearmanclient.setdatacallback) in the 0.6.0 release of the Gearman extension.
>
>
### Parameters
`callback`
A function or method to call
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [GearmanClient::setCompleteCallback()](gearmanclient.setcompletecallback) - Set a function to be called on task completion
* [GearmanClient::setCreatedCallback()](gearmanclient.setcreatedcallback) - Set a callback for when a task is queued
* [GearmanClient::setDataCallback()](gearmanclient.setdatacallback) - Callback function when there is a data packet for a task
* [GearmanClient::setExceptionCallback()](gearmanclient.setexceptioncallback) - Set a callback for worker exceptions
* [GearmanClient::setFailCallback()](gearmanclient.setfailcallback) - Set callback for job failure
* [GearmanClient::setStatusCallback()](gearmanclient.setstatuscallback) - Set a callback for collecting task status
* [GearmanClient::setWarningCallback()](gearmanclient.setwarningcallback) - Set a callback for worker warnings
* [GearmanClient::setWorkloadCallback()](gearmanclient.setworkloadcallback) - Set a callback for accepting incremental data updates
php SolrQuery::getHighlightRegexSlop SolrQuery::getHighlightRegexSlop
================================
(PECL solr >= 0.9.2)
SolrQuery::getHighlightRegexSlop — Returns the deviation factor from the ideal fragment size
### Description
```
public SolrQuery::getHighlightRegexSlop(): float
```
Returns the factor by which the regex fragmenter can deviate from the ideal fragment size to accommodate the regular expression
### Parameters
This function has no parameters.
### Return Values
Returns a float on success and **`null`** if not set.
php file_exists file\_exists
============
(PHP 4, PHP 5, PHP 7, PHP 8)
file\_exists — Checks whether a file or directory exists
### Description
```
file_exists(string $filename): bool
```
Checks whether a file or directory exists.
### Parameters
`filename`
Path to the file or directory.
On windows, use //computername/share/filename or \\computername\share\filename to check files on network shares.
### Return Values
Returns **`true`** if the file or directory specified by `filename` exists; **`false`** otherwise.
>
> **Note**:
>
>
> This function will return **`false`** for symlinks pointing to non-existing files.
>
>
>
> **Note**:
>
>
> The check is done using the real UID/GID instead of the effective one.
>
>
> **Note**: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
>
>
### Errors/Exceptions
Upon failure, an **`E_WARNING`** is emitted.
### Examples
**Example #1 Testing whether a file exists**
```
<?php
$filename = '/path/to/foo.txt';
if (file_exists($filename)) {
echo "The file $filename exists";
} else {
echo "The file $filename does not exist";
}
?>
```
### Notes
> **Note**: The results of this function are cached. See [clearstatcache()](function.clearstatcache) for more details.
>
>
**Tip**As of PHP 5.0.0, this function can also be used with *some* URL wrappers. Refer to [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality.
### See Also
* [is\_readable()](function.is-readable) - Tells whether a file exists and is readable
* [is\_writable()](function.is-writable) - Tells whether the filename is writable
* [is\_file()](function.is-file) - Tells whether the filename is a regular file
* [file()](function.file) - Reads entire file into an array
* [SplFileInfo](class.splfileinfo)
php odbc_columnprivileges odbc\_columnprivileges
======================
(PHP 4, PHP 5, PHP 7, PHP 8)
odbc\_columnprivileges — Lists columns and associated privileges for the given table
### Description
```
odbc_columnprivileges(
resource $odbc,
?string $catalog,
string $schema,
string $table,
string $column
): resource|false
```
Lists columns and associated privileges for the given table.
### Parameters
`odbc`
The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details.
`catalog`
The catalog ('qualifier' in ODBC 2 parlance).
`schema`
The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.
`table`
The table name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.
`column`
The column name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.
### Return Values
Returns an ODBC result identifier or **`false`** on failure. This result identifier can be used to fetch a list of columns and associated privileges.
The result set has the following columns:
* `TABLE_CAT`
* `TABLE_SCHEM`
* `TABLE_NAME`
* `COLUMN_NAME`
* `GRANTOR`
* `GRANTEE`
* `PRIVILEGE`
* `IS_GRANTABLE`
Drivers can report additional columns. The result set is ordered by `TABLE_CAT`, `TABLE_SCHEM`, `TABLE_NAME`, `COLUMN_NAME` and `PRIVILEGE`.
### Examples
**Example #1 List Privileges for a Column**
```
<?php
$conn = odbc_connect($dsn, $user, $pass);
$privileges = odbc_columnprivileges($conn, 'TutorialDB', 'dbo', 'test', 'id');
while (($row = odbc_fetch_array($privileges))) {
print_r($row);
break; // further rows omitted for brevity
}
?>
```
The above example will output something similar to:
```
Array
(
[TABLE_CAT] => TutorialDB
[TABLE_SCHEM] => dbo
[TABLE_NAME] => test
[COLUMN_NAME] => id
[GRANTOR] => dbo
[GRANTEE] => dbo
[PRIVILEGE] => INSERT
[IS_GRANTABLE] => YES
)
```
php ob_start ob\_start
=========
(PHP 4, PHP 5, PHP 7, PHP 8)
ob\_start — Turn on output buffering
### Description
```
ob_start(callable $callback = null, int $chunk_size = 0, int $flags = PHP_OUTPUT_HANDLER_STDFLAGS): bool
```
This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.
The contents of this internal buffer may be copied into a string variable using [ob\_get\_contents()](function.ob-get-contents). To output what is stored in the internal buffer, use [ob\_end\_flush()](function.ob-end-flush). Alternatively, [ob\_end\_clean()](function.ob-end-clean) will silently discard the buffer contents.
**Warning** Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. `chdir(dirname($_SERVER['SCRIPT_FILENAME']))` in the callback function.
Output buffers are stackable, that is, you may call **ob\_start()** while another **ob\_start()** is active. Just make sure that you call [ob\_end\_flush()](function.ob-end-flush) the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.
If output buffering is still active when the script ends, PHP outputs the contents automatically.
### Parameters
`callback`
An optional `callback` function may be specified. This function takes a string as a parameter and should return a string. The function will be called when the output buffer is flushed (sent) or cleaned (with [ob\_flush()](function.ob-flush), [ob\_clean()](function.ob-clean) or similar function) or when the output buffer is flushed to the browser at the end of the request. When `callback` is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the `callback` is not a callable function, this function will return **`false`**. This is the callback signature:
```
handler(string $buffer, int $phase = ?): string
```
`buffer`
Contents of the output buffer. `phase`
Bitmask of [**`PHP_OUTPUT_HANDLER_*`** constants](https://www.php.net/manual/en/outcontrol.constants.php). If `callback` returns **`false`** original input is sent to the browser.
The `callback` parameter may be bypassed by passing a **`null`** value.
[ob\_end\_clean()](function.ob-end-clean), [ob\_end\_flush()](function.ob-end-flush), [ob\_clean()](function.ob-clean), [ob\_flush()](function.ob-flush) and **ob\_start()** may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like `print_r($expression, true)` or `highlight_file($filename, true)` from a callback function.
>
> **Note**:
>
>
> [ob\_gzhandler()](function.ob-gzhandler) function exists to facilitate sending gz-encoded data to web browsers that support compressed web pages. [ob\_gzhandler()](function.ob-gzhandler) determines what type of content encoding the browser will accept and will return its output accordingly.
>
>
`chunk_size`
If the optional parameter `chunk_size` is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceed `chunk_size`. The default value `0` means that the output function will only be called when the output buffer is closed.
`flags`
The `flags` parameter is a bitmask that controls the operations that can be performed on the output buffer. The default is to allow output buffers to be cleaned, flushed and removed, which can be set explicitly via **`PHP_OUTPUT_HANDLER_CLEANABLE`** | **`PHP_OUTPUT_HANDLER_FLUSHABLE`** | **`PHP_OUTPUT_HANDLER_REMOVABLE`**, or **`PHP_OUTPUT_HANDLER_STDFLAGS`** as shorthand.
Each flag controls access to a set of functions, as described below:
| Constant | Functions |
| --- | --- |
| **`PHP_OUTPUT_HANDLER_CLEANABLE`** | [ob\_clean()](function.ob-clean), [ob\_end\_clean()](function.ob-end-clean), and [ob\_get\_clean()](function.ob-get-clean). |
| **`PHP_OUTPUT_HANDLER_FLUSHABLE`** | [ob\_end\_flush()](function.ob-end-flush), [ob\_flush()](function.ob-flush), and [ob\_get\_flush()](function.ob-get-flush). |
| **`PHP_OUTPUT_HANDLER_REMOVABLE`** | [ob\_end\_clean()](function.ob-end-clean), [ob\_end\_flush()](function.ob-end-flush), and [ob\_get\_flush()](function.ob-get-flush). |
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 User defined callback function example**
```
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php
ob_end_flush();
?>
```
The above example will output:
```
<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>
```
**Example #2 Creating an unerasable output buffer**
```
<?php
ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^ PHP_OUTPUT_HANDLER_REMOVABLE);
?>
```
### See Also
* [ob\_get\_contents()](function.ob-get-contents) - Return the contents of the output buffer
* [ob\_end\_clean()](function.ob-end-clean) - Clean (erase) the output buffer and turn off output buffering
* [ob\_end\_flush()](function.ob-end-flush) - Flush (send) the output buffer and turn off output buffering
* [ob\_implicit\_flush()](function.ob-implicit-flush) - Turn implicit flush on/off
* [ob\_gzhandler()](function.ob-gzhandler) - ob\_start callback function to gzip output buffer
* [ob\_iconv\_handler()](function.ob-iconv-handler) - Convert character encoding as output buffer handler
* [mb\_output\_handler()](function.mb-output-handler) - Callback function converts character encoding in output buffer
* [ob\_tidyhandler()](function.ob-tidyhandler) - ob\_start callback function to repair the buffer
php Memcached::isPristine Memcached::isPristine
=====================
(PECL memcached >= 2.0.0)
Memcached::isPristine — Check if the instance was recently created
### Description
```
public Memcached::isPristine(): bool
```
**Memcached::isPristine()** checks if the Memcache instance was recently created.
### Parameters
This function has no parameters.
### Return Values
Returns the true if instance is recently created, false otherwise.
### See Also
* [Memcached::isPersistent()](memcached.ispersistent) - Check if a persitent connection to memcache is being used
php Ev::backend Ev::backend
===========
(PECL ev >= 0.2.0)
Ev::backend — Returns an integer describing the backend used by libev
### Description
```
final public static Ev::backend(): int
```
Returns an integer describing the backend used by *libev* . See [Backend flags](class.ev#ev.constants.watcher-backends)
### Parameters
This function has no parameters.
### Return Values
Returns an integer(bit mask) describing the backend used by *libev* .
### See Also
* [EvEmbed](class.evembed)
* [Ev::embeddableBackends()](ev.embeddablebackends) - Returns the set of backends that are embeddable in other event loops
* [Ev::recommendedBackends()](ev.recommendedbackends) - Returns a bit mask of recommended backends for current platform
* [Ev::supportedBackends()](ev.supportedbackends) - Returns the set of backends supported by current libev configuration
* [Backend flags](class.ev#ev.constants.watcher-backends)
php enchant_broker_request_pwl_dict enchant\_broker\_request\_pwl\_dict
===================================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )
enchant\_broker\_request\_pwl\_dict — Creates a dictionary using a PWL file
### Description
```
enchant_broker_request_pwl_dict(EnchantBroker $broker, string $filename): EnchantDictionary|false
```
Creates a dictionary using a PWL file. A PWL file is personal word file one word per line.
### Parameters
`broker`
An Enchant broker returned by [enchant\_broker\_init()](function.enchant-broker-init).
`filename`
Path to the PWL file. If there is no such file, a new one will be created if possible.
### Return Values
Returns a dictionary resource on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `broker` expects an [EnchantBroker](class.enchantbroker) instance now; previoulsy, a [resource](language.types.resource) was expected. |
| 8.0.0 | On success, this function returns an [EnchantDictionary](class.enchantdictionary) instance now; previoulsy, a [resource](language.types.resource) was retured. |
### See Also
* [enchant\_dict\_describe()](function.enchant-dict-describe) - Describes an individual dictionary
* [enchant\_broker\_dict\_exists()](function.enchant-broker-dict-exists) - Whether a dictionary exists or not. Using non-empty tag
* [enchant\_broker\_free\_dict()](function.enchant-broker-free-dict) - Free a dictionary resource
php runkit7_function_rename runkit7\_function\_rename
=========================
(PECL runkit7 >= Unknown)
runkit7\_function\_rename — Change a function's name
### Description
```
runkit7_function_rename(string $source_name, string $target_name): bool
```
> **Note**: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the `runkit.internal_override` setting in php.ini.
>
>
### Parameters
`source_name`
Current function name
`target_name`
New function name
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [runkit7\_function\_add()](function.runkit7-function-add) - Add a new function, similar to create\_function
* [runkit7\_function\_copy()](function.runkit7-function-copy) - Copy a function to a new function name
* [runkit7\_function\_redefine()](function.runkit7-function-redefine) - Replace a function definition with a new implementation
* [runkit7\_function\_remove()](function.runkit7-function-remove) - Remove a function definition
php idn_to_utf8 idn\_to\_utf8
=============
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.2, PECL idn >= 0.1)
idn\_to\_utf8 — Convert domain name from IDNA ASCII to Unicode
### Description
Procedural style
```
idn_to_utf8(
string $domain,
int $flags = IDNA_DEFAULT,
int $variant = INTL_IDNA_VARIANT_UTS46,
array &$idna_info = null
): string|false
```
This function converts a Unicode domain name from an IDNA ASCII-compatible format to plain Unicode, encoded in UTF-8.
### Parameters
`domain`
Domain to convert in an IDNA ASCII-compatible format.
`flags`
Conversion options - combination of IDNA\_\* constants (except IDNA\_ERROR\_\* constants).
`variant`
Either **`INTL_IDNA_VARIANT_2003`** (deprecated as of PHP 7.2.0) for IDNA 2003 or **`INTL_IDNA_VARIANT_UTS46`** (only available as of ICU 4.6) for UTS #46.
`idna_info`
This parameter can be used only if **`INTL_IDNA_VARIANT_UTS46`** was used for `variant`. In that case, it will be filled with an array with the keys `'result'`, the possibly illegal result of the transformation, `'isTransitionalDifferent'`, a boolean indicating whether the usage of the transitional mechanisms of UTS #46 either has or would have changed the result and `'errors'`, which is an int representing a bitset of the error constants IDNA\_ERROR\_\*.
### Return Values
The domain name in Unicode, encoded in UTF-8, or **`false`** on failure
### Changelog
| Version | Description |
| --- | --- |
| 7.4.0 | The default value of `variant` is now **`INTL_IDNA_VARIANT_UTS46`** instead of the deprecated **`INTL_IDNA_VARIANT_2003`**. |
| 7.2.0 | **`INTL_IDNA_VARIANT_2003`** has been deprecated; use **`INTL_IDNA_VARIANT_UTS46`** instead. |
### Examples
**Example #1 **idn\_to\_utf8()** example**
```
<?php
echo idn_to_utf8('xn--tst-qla.de');
?>
```
The above example will output:
```
täst.de
```
### See Also
* [idn\_to\_ascii()](function.idn-to-ascii) - Convert domain name to IDNA ASCII form
php SplFileInfo::setInfoClass SplFileInfo::setInfoClass
=========================
(PHP 5 >= 5.1.2, PHP 7, PHP 8)
SplFileInfo::setInfoClass — Sets the class used with [SplFileInfo::getFileInfo()](splfileinfo.getfileinfo) and [SplFileInfo::getPathInfo()](splfileinfo.getpathinfo)
### Description
```
public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void
```
Use this method to set a custom class which will be used when [SplFileInfo::getFileInfo()](splfileinfo.getfileinfo) and [SplFileInfo::getPathInfo()](splfileinfo.getpathinfo) are called. The class name passed to this method must be [SplFileInfo](class.splfileinfo) or a class derived from [SplFileInfo](class.splfileinfo).
### Parameters
`class`
The class name to use when [SplFileInfo::getFileInfo()](splfileinfo.getfileinfo) and [SplFileInfo::getPathInfo()](splfileinfo.getpathinfo) are called.
### Return Values
No value is returned.
### Examples
**Example #1 [SplFileInfo::setFileClass()](splfileinfo.setfileclass) example**
```
<?php
// Define a class which extends SplFileInfo
class MyFoo extends SplFileInfo {}
$info = new SplFileInfo('foo');
// Set the class name to use
$info->setInfoClass('MyFoo');
var_dump($info->getFileInfo());
?>
```
The above example will output something similar to:
```
object(MyFoo)#2 (0) { }
```
### See Also
* [SplFileInfo::getFileInfo()](splfileinfo.getfileinfo) - Gets an SplFileInfo object for the file
| programming_docs |
php The Map class
The Map class
=============
Introduction
------------
(No version information available, might only be in Git)
A Map is a sequential collection of key-value pairs, almost identical to an array used in a similar context. Keys can be any type, but must be unique. Values are replaced if added to the map using the same key.
Strengths
---------
* Keys and values can be any type, including objects.
* Supports array syntax (square brackets).
* Insertion order is preserved.
* Performance and memory efficiency is very similar to an array.
* Automatically frees allocated memory when its size drops low enough.
Weaknesses
----------
* Can’t be converted to an array when objects are used as keys.
Class synopsis
--------------
class **Ds\Map** implements **Ds\Collection**, [ArrayAccess](class.arrayaccess) { /\* Constants \*/ const int [MIN\_CAPACITY](class.ds-map#ds-map.constants.min-capacity) = 16; /\* Methods \*/
```
public allocate(int $capacity): void
```
```
public apply(callable $callback): void
```
```
public capacity(): int
```
```
public clear(): void
```
```
public copy(): Ds\Map
```
```
public diff(Ds\Map $map): Ds\Map
```
```
public filter(callable $callback = ?): Ds\Map
```
```
public first(): Ds\Pair
```
```
public get(mixed $key, mixed $default = ?): mixed
```
```
public hasKey(mixed $key): bool
```
```
public hasValue(mixed $value): bool
```
```
public intersect(Ds\Map $map): Ds\Map
```
```
public isEmpty(): bool
```
```
public keys(): Ds\Set
```
```
public ksort(callable $comparator = ?): void
```
```
public ksorted(callable $comparator = ?): Ds\Map
```
```
public last(): Ds\Pair
```
```
public map(callable $callback): Ds\Map
```
```
public merge(mixed $values): Ds\Map
```
```
public pairs(): Ds\Sequence
```
```
public put(mixed $key, mixed $value): void
```
```
public putAll(mixed $pairs): void
```
```
public reduce(callable $callback, mixed $initial = ?): mixed
```
```
public remove(mixed $key, mixed $default = ?): mixed
```
```
public reverse(): void
```
```
public reversed(): Ds\Map
```
```
public skip(int $position): Ds\Pair
```
```
public slice(int $index, int $length = ?): Ds\Map
```
```
public sort(callable $comparator = ?): void
```
```
public sorted(callable $comparator = ?): Ds\Map
```
```
public sum(): int|float
```
```
public toArray(): array
```
```
public union(Ds\Map $map): Ds\Map
```
```
public values(): Ds\Sequence
```
```
public xor(Ds\Map $map): Ds\Map
```
} Predefined Constants
--------------------
**`Ds\Map::MIN_CAPACITY`** Changelog
---------
| Version | Description |
| --- | --- |
| PECL ds 1.3.0 | The class now implements [ArrayAccess](class.arrayaccess). |
Table of Contents
-----------------
* [Ds\Map::allocate](ds-map.allocate) — Allocates enough memory for a required capacity
* [Ds\Map::apply](ds-map.apply) — Updates all values by applying a callback function to each value
* [Ds\Map::capacity](ds-map.capacity) — Returns the current capacity
* [Ds\Map::clear](ds-map.clear) — Removes all values
* [Ds\Map::\_\_construct](ds-map.construct) — Creates a new instance
* [Ds\Map::copy](ds-map.copy) — Returns a shallow copy of the map
* [Ds\Map::count](ds-map.count) — Returns the number of values in the map
* [Ds\Map::diff](ds-map.diff) — Creates a new map using keys that aren't in another map
* [Ds\Map::filter](ds-map.filter) — Creates a new map using a callable to determine which pairs to include
* [Ds\Map::first](ds-map.first) — Returns the first pair in the map
* [Ds\Map::get](ds-map.get) — Returns the value for a given key
* [Ds\Map::hasKey](ds-map.haskey) — Determines whether the map contains a given key
* [Ds\Map::hasValue](ds-map.hasvalue) — Determines whether the map contains a given value
* [Ds\Map::intersect](ds-map.intersect) — Creates a new map by intersecting keys with another map
* [Ds\Map::isEmpty](ds-map.isempty) — Returns whether the map is empty
* [Ds\Map::jsonSerialize](ds-map.jsonserialize) — Returns a representation that can be converted to JSON
* [Ds\Map::keys](ds-map.keys) — Returns a set of the map's keys
* [Ds\Map::ksort](ds-map.ksort) — Sorts the map in-place by key
* [Ds\Map::ksorted](ds-map.ksorted) — Returns a copy, sorted by key
* [Ds\Map::last](ds-map.last) — Returns the last pair of the map
* [Ds\Map::map](ds-map.map) — Returns the result of applying a callback to each value
* [Ds\Map::merge](ds-map.merge) — Returns the result of adding all given associations
* [Ds\Map::pairs](ds-map.pairs) — Returns a sequence containing all the pairs of the map
* [Ds\Map::put](ds-map.put) — Associates a key with a value
* [Ds\Map::putAll](ds-map.putall) — Associates all key-value pairs of a traversable object or array
* [Ds\Map::reduce](ds-map.reduce) — Reduces the map to a single value using a callback function
* [Ds\Map::remove](ds-map.remove) — Removes and returns a value by key
* [Ds\Map::reverse](ds-map.reverse) — Reverses the map in-place
* [Ds\Map::reversed](ds-map.reversed) — Returns a reversed copy
* [Ds\Map::skip](ds-map.skip) — Returns the pair at a given positional index
* [Ds\Map::slice](ds-map.slice) — Returns a subset of the map defined by a starting index and length
* [Ds\Map::sort](ds-map.sort) — Sorts the map in-place by value
* [Ds\Map::sorted](ds-map.sorted) — Returns a copy, sorted by value
* [Ds\Map::sum](ds-map.sum) — Returns the sum of all values in the map
* [Ds\Map::toArray](ds-map.toarray) — Converts the map to an array
* [Ds\Map::union](ds-map.union) — Creates a new map using values from the current instance and another map
* [Ds\Map::values](ds-map.values) — Returns a sequence of the map's values
* [Ds\Map::xor](ds-map.xor) — Creates a new map using keys of either the current instance or of another map, but not of both
php mb_strtolower mb\_strtolower
==============
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
mb\_strtolower — Make a string lowercase
### Description
```
mb_strtolower(string $string, ?string $encoding = null): string
```
Returns `string` with all alphabetic characters converted to lowercase.
### Parameters
`string`
The string being lowercased.
`encoding`
The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used.
### Return Values
`string` with all alphabetic characters converted to lowercase.
### Examples
**Example #1 **mb\_strtolower()** example**
```
<?php
$str = "Mary Had A Little Lamb and She LOVED It So";
$str = mb_strtolower($str);
echo $str; // Prints mary had a little lamb and she loved it so
?>
```
**Example #2 **mb\_strtolower()** example with non-Latin UTF-8 text**
```
<?php
$str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός";
$str = mb_strtolower($str, 'UTF-8');
echo $str; // Prints τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός
?>
```
### Notes
By contrast to [strtolower()](function.strtolower), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä).
For more information about the Unicode properties, please see [» http://www.unicode.org/reports/tr21/](http://www.unicode.org/reports/tr21/).
### See Also
* [mb\_strtoupper()](function.mb-strtoupper) - Make a string uppercase
* [mb\_convert\_case()](function.mb-convert-case) - Perform case folding on a string
* [strtolower()](function.strtolower) - Make a string lowercase
php Yaf_Application::execute Yaf\_Application::execute
=========================
(Yaf >=1.0.0)
Yaf\_Application::execute — Execute a callback
### Description
```
public Yaf_Application::execute(callable $entry, string ...$args): void
```
This method is typically used to run Yaf\_Application in a crontab work. Make the crontab work can also use the autoloader and Bootstrap mechanism.
### Parameters
`entry`
a valid callback
`args`
parameters will pass to the callback
### Return Values
### Examples
**Example #1 **Yaf\_Application::execute()**example**
```
<?php
function main($argc, $argv) {
}
$config = array(
"application" => array(
"directory" => realpath(dirname(__FILE__)) . "/application",
),
);
/** Yaf_Application */
$application = new Yaf_Application($config);
$application->execute("main", $argc, $argv);
?>
```
The above example will output something similar to:
php ZipArchive::getFromIndex ZipArchive::getFromIndex
========================
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0)
ZipArchive::getFromIndex — Returns the entry contents using its index
### Description
```
public ZipArchive::getFromIndex(int $index, int $len = 0, int $flags = 0): string|false
```
Returns the entry contents using its index.
### Parameters
`index`
Index of the entry
`len`
The length to be read from the entry. If `0`, then the entire entry is read.
`flags`
The flags to use to open the archive. the following values may be ORed to it.
* **`ZipArchive::FL_UNCHANGED`**
* **`ZipArchive::FL_COMPRESSED`**
### Return Values
Returns the contents of the entry on success or **`false`** on failure.
### Examples
**Example #1 Get the file contents**
```
<?php
$zip = new ZipArchive;
if ($zip->open('test.zip') === TRUE) {
echo $zip->getFromIndex(2);
$zip->close();
} else {
echo 'failed';
}
?>
```
### See Also
* [ZipArchive::getFromName()](ziparchive.getfromname) - Returns the entry contents using its name
php mcrypt_enc_get_iv_size mcrypt\_enc\_get\_iv\_size
==========================
(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)
mcrypt\_enc\_get\_iv\_size — Returns the size of the IV of the opened algorithm
**Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged.
### Description
```
mcrypt_enc_get_iv_size(resource $td): int
```
This function returns the size of the IV of the algorithm specified by the encryption descriptor in bytes. An IV is used in cbc, cfb and ofb modes, and in some algorithms in stream mode.
### Parameters
`td`
The encryption descriptor.
### Return Values
Returns the size of the IV, or 0 if the IV is ignored by the algorithm.
php DOMXPath::registerPhpFunctions DOMXPath::registerPhpFunctions
==============================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
DOMXPath::registerPhpFunctions — Register PHP functions as XPath functions
### Description
```
public DOMXPath::registerPhpFunctions(string|array|null $restrict = null): void
```
This method enables the ability to use PHP functions within XPath expressions.
### Parameters
`restrict`
Use this parameter to only allow certain functions to be called from XPath.
This parameter can be either a string (a function name) or an array of function names.
### Return Values
No value is returned.
### Examples
The following examples use book.xml which contains the following:
**Example #1 book.xml**
```
<?xml version="1.0" encoding="UTF-8"?>
<books>
<book>
<title>PHP Basics</title>
<author>Jim Smith</author>
<author>Jane Smith</author>
</book>
<book>
<title>PHP Secrets</title>
<author>Jenny Smythe</author>
</book>
<book>
<title>XML basics</title>
<author>Joe Black</author>
</book>
</books>
```
**Example #2 **DOMXPath::registerPHPFunctions()** with `php:functionString`**
```
<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");
// Register PHP functions (no restrictions)
$xpath->registerPHPFunctions();
// Call substr function on the book title
$nodes = $xpath->query('//book[php:functionString("substr", title, 0, 3) = "PHP"]');
echo "Found {$nodes->length} books starting with 'PHP':\n";
foreach ($nodes as $node) {
$title = $node->getElementsByTagName("title")->item(0)->nodeValue;
$author = $node->getElementsByTagName("author")->item(0)->nodeValue;
echo "$title by $author\n";
}
?>
```
The above example will output something similar to:
```
Found 2 books starting with 'PHP':
PHP Basics by Jim Smith
PHP Secrets by Jenny Smythe
```
**Example #3 **DOMXPath::registerPHPFunctions()** with `php:function`**
```
<?php
$doc = new DOMDocument;
$doc->load('book.xml');
$xpath = new DOMXPath($doc);
// Register the php: namespace (required)
$xpath->registerNamespace("php", "http://php.net/xpath");
// Register PHP functions (has_multiple only)
$xpath->registerPHPFunctions("has_multiple");
function has_multiple($nodes) {
// Return true if more than one author
return count($nodes) > 1;
}
// Filter books with multiple authors
$books = $xpath->query('//book[php:function("has_multiple", author)]');
echo "Books with multiple authors:\n";
foreach ($books as $book) {
echo $book->getElementsByTagName("title")->item(0)->nodeValue . "\n";
}
?>
```
The above example will output something similar to:
```
Books with multiple authors:
PHP Basics
```
### See Also
* [DOMXPath::registerNamespace()](domxpath.registernamespace) - Registers the namespace with the DOMXPath object
* [DOMXPath::query()](domxpath.query) - Evaluates the given XPath expression
* [DOMXPath::evaluate()](domxpath.evaluate) - Evaluates the given XPath expression and returns a typed result if possible
php mcrypt_get_block_size mcrypt\_get\_block\_size
========================
(PHP 4, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)
mcrypt\_get\_block\_size — Gets the block size of the specified cipher
**Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged.
### Description
```
mcrypt_get_block_size(int $cipher): int|false
```
```
mcrypt_get_block_size(string $cipher, string $mode): int|false
```
The first prototype is when linked against libmcrypt 2.2.x, the second when linked against libmcrypt 2.4.x or 2.5.x.
**mcrypt\_get\_block\_size()** is used to get the size of a block of the specified `cipher` (in combination with an encryption mode).
It is more useful to use the [mcrypt\_enc\_get\_block\_size()](function.mcrypt-enc-get-block-size) function as this uses the resource returned by [mcrypt\_module\_open()](function.mcrypt-module-open).
### Parameters
`cipher`
One of the **`MCRYPT_ciphername`** constants, or the name of the algorithm as string.
`mode`
One of the **`MCRYPT_MODE_modename`** constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
### Return Values
Returns the algorithm block size in bytes or **`false`** on failure.
### Examples
**Example #1 **mcrypt\_get\_block\_size()** example**
This example shows how to use this function when linked against libmcrypt 2.4.x and 2.5.x.
```
<?php
echo mcrypt_get_block_size('tripledes', 'ecb'); // 8
?>
```
### See Also
* [mcrypt\_get\_key\_size()](function.mcrypt-get-key-size) - Gets the key size of the specified cipher
* [mcrypt\_enc\_get\_block\_size()](function.mcrypt-enc-get-block-size) - Returns the blocksize of the opened algorithm
* [mcrypt\_encrypt()](function.mcrypt-encrypt) - Encrypts plaintext with given parameters
php SolrClient::getByIds SolrClient::getByIds
====================
(PECL solr >= 2.2.0)
SolrClient::getByIds — Get Documents by their Ids. Utilizes Solr Realtime Get (RTG)
### Description
```
public SolrClient::getByIds(array $ids): SolrQueryResponse
```
Get Documents by their Ids. Utilizes Solr Realtime Get (RTG).
### Parameters
`ids`
Document ids
### Return Values
[SolrQueryResponse](class.solrqueryresponse)
### Examples
**Example #1 **SolrClient::getByIds()** example**
```
<?php
include "bootstrap.php";
$options = array
(
'hostname' => SOLR_SERVER_HOSTNAME,
'login' => SOLR_SERVER_USERNAME,
'password' => SOLR_SERVER_PASSWORD,
'port' => SOLR_SERVER_PORT,
'path' => SOLR_SERVER_PATH
);
$client = new SolrClient($options);
$response = $client->getByIds(['GB18030TEST', '6H500F0']);
print_r($response->getResponse());
?>
```
The above example will output something similar to:
```
SolrObject Object
(
[response] => SolrObject Object
(
[numFound] => 2
[start] => 0
[docs] => Array
(
[0] => SolrObject Object
(
[id] => GB18030TEST
[name] => Array
(
[0] => Test with some GB18030 encoded characters
)
[features] => Array
(
[0] => No accents here
[1] => 这是一个功能
[2] => This is a feature (translated)
[3] => 这份文件是很有光泽
[4] => This document is very shiny (translated)
)
[price] => Array
(
[0] => 0
)
[inStock] => Array
(
[0] => 1
)
[_version_] => 1510294336239042560
)
[1] => SolrObject Object
(
[id] => 6H500F0
[name] => Array
(
[0] => Maxtor DiamondMax 11 - hard drive - 500 GB - SATA-300
)
[manu] => Array
(
[0] => Maxtor Corp.
)
[manu_id_s] => maxtor
[cat] => Array
(
[0] => electronics
[1] => hard drive
)
[features] => Array
(
[0] => SATA 3.0Gb/s, NCQ
[1] => 8.5ms seek
[2] => 16MB cache
)
[price] => Array
(
[0] => 350
)
[popularity] => Array
(
[0] => 6
)
[inStock] => Array
(
[0] => 1
)
[store] => Array
(
[0] => 45.17614,-93.87341
)
[manufacturedate_dt] => 2006-02-13T15:26:37Z
[_version_] => 1510294336449806336
)
)
)
)
```
### See Also
* [SolrClient::getById()](solrclient.getbyid) - Get Document By Id. Utilizes Solr Realtime Get (RTG)
php Imagick::decipherImage Imagick::decipherImage
======================
(PECL imagick 2 >= 2.3.0, PECL imagick 3)
Imagick::decipherImage — Deciphers an image
### Description
```
public Imagick::decipherImage(string $passphrase): bool
```
Deciphers image that has been enciphered before. The image must be enciphered using [Imagick::encipherImage()](imagick.encipherimage). This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer.
### Parameters
`passphrase`
The passphrase
### Return Values
Returns **`true`** on success.
### See Also
* [Imagick::encipherImage()](imagick.encipherimage) - Enciphers an image
| programming_docs |
php Componere\Patch::getClosures Componere\Patch::getClosures
============================
(Componere 2 >= 2.1.0)
Componere\Patch::getClosures — Get Closures
### Description
```
public Componere\Patch::getClosures(): array
```
Shall return an array of Closures
### Return Values
Shall return all methods as an array of Closure objects bound to the correct scope and object
php Imagick::readImage Imagick::readImage
==================
(PECL imagick 2, PECL imagick 3)
Imagick::readImage — Reads image from filename
### Description
```
public Imagick::readImage(string $filename): bool
```
Reads image from filename
### Parameters
`filename`
### Return Values
Returns **`true`** on success.
php mysqli_stmt::$affected_rows mysqli\_stmt::$affected\_rows
=============================
mysqli\_stmt\_affected\_rows
============================
(PHP 5, PHP 7, PHP 8)
mysqli\_stmt::$affected\_rows -- mysqli\_stmt\_affected\_rows — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
### Description
Object-oriented style
int|string [$mysqli\_stmt->affected\_rows](mysqli-stmt.affected-rows); Procedural style
```
mysqli_stmt_affected_rows(mysqli_stmt $statement): int|string
```
Returns the number of rows affected by `INSERT`, `UPDATE`, or `DELETE` query. Works like [mysqli\_stmt\_num\_rows()](mysqli-stmt.num-rows) for `SELECT` statements.
### Parameters
`statement`
Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init).
### Return Values
An integer greater than zero indicates the number of rows affected or retrieved. Zero indicates that no records were updated for an `UPDATE` statement, no rows matched the `WHERE` clause in the query or that no query has yet been executed. `-1` indicates that the query returned an error or that, for a `SELECT` query, **mysqli\_stmt\_affected\_rows()** was called prior to calling [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result).
>
> **Note**:
>
>
> If the number of affected rows is greater than maximum PHP int value, the number of affected rows will be returned as a string value.
>
>
### Examples
**Example #1 **mysqli\_stmt\_affected\_rows()** example**
Object-oriented style
```
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* create temp table */
$mysqli->query("CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
$stmt = $mysqli->prepare($query);
/* Bind variable for placeholder */
$code = 'A%';
$stmt->bind_param("s", $code);
/* execute statement */
$stmt->execute();
printf("Rows inserted: %d\n", $stmt->affected_rows);
```
Procedural style
```
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* create temp table */
mysqli_query($link, "CREATE TEMPORARY TABLE myCountry LIKE Country");
$query = "INSERT INTO myCountry SELECT * FROM Country WHERE Code LIKE ?";
/* prepare statement */
$stmt = mysqli_prepare($link, $query);
/* Bind variable for placeholder */
$code = 'A%';
mysqli_stmt_bind_param($stmt, "s", $code);
/* execute statement */
mysqli_stmt_execute($stmt);
printf("Rows inserted: %d\n", mysqli_stmt_affected_rows($stmt));
```
The above examples will output:
```
Rows inserted: 17
```
### See Also
* [mysqli\_stmt\_num\_rows()](mysqli-stmt.num-rows) - Returns the number of rows fetched from the server
* [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result) - Stores a result set in an internal buffer
php Imagick::extentImage Imagick::extentImage
====================
(PECL imagick 2, PECL imagick 3)
Imagick::extentImage — Set image size
### Description
```
public Imagick::extentImage(
int $width,
int $height,
int $x,
int $y
): bool
```
Comfortability method for setting image size. The method sets the image size and allows setting x,y coordinates where the new area begins. This method is available if Imagick has been compiled against ImageMagick version 6.3.1 or newer.
**Caution** Prior to ImageMagick 6.5.7-8 (1623), $x was positive when shifting to the left and negative when shifting to the right, and $y was positive when shifting an image up and negative when shifting an image down. Somewhere betwen ImageMagick 6.3.7 (1591) and ImageMagick 6.5.7-8 (1623), the axes of $x and $y were flipped, so that $x was negative when shifting to the left and positive when shifting to the right, and $y was negative when shifting an image up and positive when shifting an image down. Somewhere between ImageMagick 6.5.7-8 (1623) and ImageMagick 6.6.9-7 (1641), the axes of $x and $y were flipped back to pre-ImageMagick 6.5.7-8 (1623) functionality.
### Parameters
`width`
The new width
`height`
The new height
`x`
X position for the new size
`y`
Y position for the new size
### Return Values
Returns **`true`** on success.
### See Also
* [Imagick::resizeImage()](imagick.resizeimage) - Scales an image
* [Imagick::thumbnailImage()](imagick.thumbnailimage) - Changes the size of an image
* [Imagick::cropImage()](imagick.cropimage) - Extracts a region of the image
php Yar_Concurrent_Client::reset Yar\_Concurrent\_Client::reset
==============================
(PECL yar >= 1.2.4)
Yar\_Concurrent\_Client::reset — Clean all registered calls
### Description
```
public static Yar_Concurrent_Client::reset(): bool
```
Clean all registered calls
### Parameters
### Return Values
### Examples
**Example #1 **Yar\_Concurrent\_Client::reset()** example**
The above example will output something similar to:
### See Also
* [Yar\_Concurrent\_Client::call()](yar-concurrent-client.call) - Register a concurrent call
* [Yar\_Concurrent\_Client::loop()](yar-concurrent-client.loop) - Send all calls
* [Yar\_Server::\_\_construct()](yar-server.construct) - Register a server
* [Yar\_Server::handle()](yar-server.handle) - Start RPC Server
php SolrQuery::setExplainOther SolrQuery::setExplainOther
==========================
(PECL solr >= 0.9.2)
SolrQuery::setExplainOther — Sets the explainOther common query parameter
### Description
```
public SolrQuery::setExplainOther(string $query): SolrQuery
```
Sets the explainOther common query parameter
### Parameters
`query`
The Lucene query to identify a set of documents
### Return Values
Returns the current SolrQuery object, if the return value is used.
php openssl_cipher_key_length openssl\_cipher\_key\_length
============================
(PHP 8 >= 8.2.0)
openssl\_cipher\_key\_length — Gets the cipher key length
### Description
```
openssl_cipher_key_length(string $cipher_algo): int|false
```
Gets the cipher key length.
### Parameters
`cipher_algo`
The cipher method, see [openssl\_get\_cipher\_methods()](function.openssl-get-cipher-methods) for a list of potential values.
### Return Values
Returns the cipher length on success, or **`false`** on failure.
### Errors/Exceptions
Emits an **`E_WARNING`** level error when the cipher algorithm is unknown.
### Examples
**Example #1 **openssl\_cipher\_key\_length()** example**
```
<?php
$method = 'AES-128-CBC';
var_dump(openssl_cipher_key_length($method));
?>
```
The above example will output something similar to:
```
int(16)
```
php The Yaf_Exception_LoadFailed_View class
The Yaf\_Exception\_LoadFailed\_View class
==========================================
Introduction
------------
(Yaf >=1.0.0)
Class synopsis
--------------
class **Yaf\_Exception\_LoadFailed\_View** extends [Yaf\_Exception\_LoadFailed](class.yaf-exception-loadfailed) { /\* Properties \*/ /\* Methods \*/ /\* Inherited methods \*/
```
public Yaf_Exception::getPrevious(): void
```
}
php EventBuffer::pullup EventBuffer::pullup
===================
(PECL event >= 1.2.6-beta)
EventBuffer::pullup — Linearizes data within buffer and returns it's contents as a string
### Description
```
public EventBuffer::pullup( int $size ): string
```
"Linearizes" the first `size` bytes of the buffer, copying or moving them as needed to ensure that they are all contiguous and occupying the same chunk of memory. If size is negative, the function linearizes the entire buffer.
**Warning** Calling **EventBuffer::pullup()** with a large size can be quite slow, since it potentially needs to copy the entire buffer's contents.
### Parameters
`size` The number of bytes required to be contiguous within the buffer.
### Return Values
If `size` is greater than the number of bytes in the buffer, the function returns **`null`**. Otherwise, **EventBuffer::pullup()** returns string.
### See Also
* [EventBuffer::copyout()](eventbuffer.copyout) - Copies out specified number of bytes from the front of the buffer
* [EventBuffer::drain()](eventbuffer.drain) - Removes specified number of bytes from the front of the buffer without copying it anywhere
* [EventBuffer::read()](eventbuffer.read) - Read data from an evbuffer and drain the bytes read
* [EventBuffer::readLine()](eventbuffer.readline) - Extracts a line from the front of the buffer
* [EventBuffer::appendFrom()](eventbuffer.appendfrom) - Moves the specified number of bytes from a source buffer to the end of the current buffer
php SolrQuery::setHighlight SolrQuery::setHighlight
=======================
(PECL solr >= 0.9.2)
SolrQuery::setHighlight — Enables or disables highlighting
### Description
```
public SolrQuery::setHighlight(bool $flag): SolrQuery
```
Setting it to **`true`** enables highlighted snippets to be generated in the query response.
Setting it to **`false`** disables highlighting
### Parameters
`flag`
Enable or disable highlighting
### Return Values
Returns the current SolrQuery object, if the return value is used.
php json_encode json\_encode
============
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0)
json\_encode — Returns the JSON representation of a value
### Description
```
json_encode(mixed $value, int $flags = 0, int $depth = 512): string|false
```
Returns a string containing the JSON representation of the supplied `value`. If the parameter is an array or object, it will be serialized recursively.
If a value to be serialized is an object, then by default only publicly visible properties will be included. Alternatively, a class may implement [JsonSerializable](class.jsonserializable) to control how its values are serialized to JSON.
The encoding is affected by the supplied `flags` and additionally the encoding of float values depends on the value of [serialize\_precision](https://www.php.net/manual/en/ini.core.php#ini.serialize-precision).
### Parameters
`value`
The `value` being encoded. Can be any type except a [resource](language.types.resource).
All string data must be UTF-8 encoded.
>
> **Note**:
>
>
> PHP implements a superset of JSON as specified in the original [» RFC 7159](http://www.faqs.org/rfcs/rfc7159).
>
>
`flags`
Bitmask consisting of **`JSON_FORCE_OBJECT`**, **`JSON_HEX_QUOT`**, **`JSON_HEX_TAG`**, **`JSON_HEX_AMP`**, **`JSON_HEX_APOS`**, **`JSON_INVALID_UTF8_IGNORE`**, **`JSON_INVALID_UTF8_SUBSTITUTE`**, **`JSON_NUMERIC_CHECK`**, **`JSON_PARTIAL_OUTPUT_ON_ERROR`**, **`JSON_PRESERVE_ZERO_FRACTION`**, **`JSON_PRETTY_PRINT`**, **`JSON_UNESCAPED_LINE_TERMINATORS`**, **`JSON_UNESCAPED_SLASHES`**, **`JSON_UNESCAPED_UNICODE`**, **`JSON_THROW_ON_ERROR`**. The behaviour of these constants is described on the [JSON constants](https://www.php.net/manual/en/json.constants.php) page.
`depth`
Set the maximum depth. Must be greater than zero.
### Return Values
Returns a JSON encoded string on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 7.3.0 | **`JSON_THROW_ON_ERROR`** `flags` was added. |
| 7.2.0 | **`JSON_INVALID_UTF8_IGNORE`**, and **`JSON_INVALID_UTF8_SUBSTITUTE`** `flags` were added. |
| 7.1.0 | **`JSON_UNESCAPED_LINE_TERMINATORS`** `flags` was added. |
| 7.1.0 | [serialize\_precision](https://www.php.net/manual/en/ini.core.php#ini.serialize-precision) is used instead of [precision](https://www.php.net/manual/en/ini.core.php#ini.precision) when encoding float values. |
### Examples
**Example #1 A **json\_encode()** example**
```
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
```
The above example will output:
```
{"a":1,"b":2,"c":3,"d":4,"e":5}
```
**Example #2 A **json\_encode()** example showing some flags in use**
```
<?php
$a = array('<foo>',"'bar'",'"baz"','&blong&', "\xc3\xa9");
echo "Normal: ", json_encode($a), "\n";
echo "Tags: ", json_encode($a, JSON_HEX_TAG), "\n";
echo "Apos: ", json_encode($a, JSON_HEX_APOS), "\n";
echo "Quot: ", json_encode($a, JSON_HEX_QUOT), "\n";
echo "Amp: ", json_encode($a, JSON_HEX_AMP), "\n";
echo "Unicode: ", json_encode($a, JSON_UNESCAPED_UNICODE), "\n";
echo "All: ", json_encode($a, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE), "\n\n";
$b = array();
echo "Empty array output as array: ", json_encode($b), "\n";
echo "Empty array output as object: ", json_encode($b, JSON_FORCE_OBJECT), "\n\n";
$c = array(array(1,2,3));
echo "Non-associative array output as array: ", json_encode($c), "\n";
echo "Non-associative array output as object: ", json_encode($c, JSON_FORCE_OBJECT), "\n\n";
$d = array('foo' => 'bar', 'baz' => 'long');
echo "Associative array always output as object: ", json_encode($d), "\n";
echo "Associative array always output as object: ", json_encode($d, JSON_FORCE_OBJECT), "\n\n";
?>
```
The above example will output:
```
Normal: ["<foo>","'bar'","\"baz\"","&blong&","\u00e9"]
Tags: ["\u003Cfoo\u003E","'bar'","\"baz\"","&blong&","\u00e9"]
Apos: ["<foo>","\u0027bar\u0027","\"baz\"","&blong&","\u00e9"]
Quot: ["<foo>","'bar'","\u0022baz\u0022","&blong&","\u00e9"]
Amp: ["<foo>","'bar'","\"baz\"","\u0026blong\u0026","\u00e9"]
Unicode: ["<foo>","'bar'","\"baz\"","&blong&","é"]
All: ["\u003Cfoo\u003E","\u0027bar\u0027","\u0022baz\u0022","\u0026blong\u0026","é"]
Empty array output as array: []
Empty array output as object: {}
Non-associative array output as array: [[1,2,3]]
Non-associative array output as object: {"0":{"0":1,"1":2,"2":3}}
Associative array always output as object: {"foo":"bar","baz":"long"}
Associative array always output as object: {"foo":"bar","baz":"long"}
```
**Example #3 JSON\_NUMERIC\_CHECK option example**
```
<?php
echo "Strings representing numbers automatically turned into numbers".PHP_EOL;
$numbers = array('+123123', '-123123', '1.2e3', '0.00001');
var_dump(
$numbers,
json_encode($numbers, JSON_NUMERIC_CHECK)
);
echo "Strings containing improperly formatted numbers".PHP_EOL;
$strings = array('+a33123456789', 'a123');
var_dump(
$strings,
json_encode($strings, JSON_NUMERIC_CHECK)
);
?>
```
The above example will output something similar to:
```
Strings representing numbers automatically turned into numbers
array(4) {
[0]=>
string(7) "+123123"
[1]=>
string(7) "-123123"
[2]=>
string(5) "1.2e3"
[3]=>
string(7) "0.00001"
}
string(28) "[123123,-123123,1200,1.0e-5]"
Strings containing improperly formatted numbers
array(2) {
[0]=>
string(13) "+a33123456789"
[1]=>
string(4) "a123"
}
string(24) "["+a33123456789","a123"]"
```
**Example #4 Sequential versus non-sequential array example**
```
<?php
echo "Sequential array".PHP_EOL;
$sequential = array("foo", "bar", "baz", "blong");
var_dump(
$sequential,
json_encode($sequential)
);
echo PHP_EOL."Non-sequential array".PHP_EOL;
$nonsequential = array(1=>"foo", 2=>"bar", 3=>"baz", 4=>"blong");
var_dump(
$nonsequential,
json_encode($nonsequential)
);
echo PHP_EOL."Sequential array with one key unset".PHP_EOL;
unset($sequential[1]);
var_dump(
$sequential,
json_encode($sequential)
);
?>
```
The above example will output:
```
Sequential array
array(4) {
[0]=>
string(3) "foo"
[1]=>
string(3) "bar"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
string(27) "["foo","bar","baz","blong"]"
Non-sequential array
array(4) {
[1]=>
string(3) "foo"
[2]=>
string(3) "bar"
[3]=>
string(3) "baz"
[4]=>
string(5) "blong"
}
string(43) "{"1":"foo","2":"bar","3":"baz","4":"blong"}"
Sequential array with one key unset
array(3) {
[0]=>
string(3) "foo"
[2]=>
string(3) "baz"
[3]=>
string(5) "blong"
}
string(33) "{"0":"foo","2":"baz","3":"blong"}"
```
**Example #5 **`JSON_PRESERVE_ZERO_FRACTION`** option example**
```
<?php
var_dump(json_encode(12.0, JSON_PRESERVE_ZERO_FRACTION));
var_dump(json_encode(12.0));
?>
```
The above example will output:
```
string(4) "12.0"
string(2) "12"
```
### Notes
>
> **Note**:
>
>
> In the event of a failure to encode, [json\_last\_error()](function.json-last-error) can be used to determine the exact nature of the error.
>
>
>
> **Note**:
>
>
> When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.
>
>
>
> **Note**:
>
>
> Like the reference JSON encoder, **json\_encode()** will generate JSON that is a simple value (that is, neither an object nor an array) if given a string, int, float or bool as an input `value`. While most decoders will accept these values as valid JSON, some may not, as the specification is ambiguous on this point.
>
> To summarise, always test that your JSON decoder can handle the output you generate from **json\_encode()**.
>
>
### See Also
* [JsonSerializable](class.jsonserializable)
* [json\_decode()](function.json-decode) - Decodes a JSON string
* [json\_last\_error()](function.json-last-error) - Returns the last error occurred
* [serialize()](function.serialize) - Generates a storable representation of a value
php Imagick::negateImage Imagick::negateImage
====================
(PECL imagick 2, PECL imagick 3)
Imagick::negateImage — Negates the colors in the reference image
### Description
```
public Imagick::negateImage(bool $gray, int $channel = Imagick::CHANNEL_DEFAULT): bool
```
Negates the colors in the reference image. The Grayscale option means that only grayscale values within the image are negated.
### Parameters
`gray`
Whether to only negate grayscale pixels within the image.
`channel`
Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel).
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
### Examples
**Example #1 **Imagick::negateImage()****
```
<?php
function negateImage($imagePath, $grayOnly, $channel) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->negateImage($grayOnly, $channel);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>
```
php GearmanWorker::setTimeout GearmanWorker::setTimeout
=========================
(PECL gearman >= 0.6.0)
GearmanWorker::setTimeout — Set socket I/O activity timeout
### Description
```
public GearmanWorker::setTimeout(int $timeout): bool
```
Sets the interval of time to wait for socket I/O activity.
### Parameters
`timeout`
An interval of time in milliseconds. A negative value indicates an infinite timeout.
### Return Values
Always returns **`true`**.
### Examples
**Example #1 A simple worker with a 5 second timeout**
```
<?php
echo "Starting\n";
# Create our worker object.
$gmworker= new GearmanWorker();
# Add default server (localhost).
$gmworker->addServer();
# Register function "reverse" with the server.
$gmworker->addFunction("reverse", "reverse_fn");
# Set the timeout to 5 seconds
$gmworker->setTimeout(5000);
echo "Waiting for job...\n";
while(@$gmworker->work() || $gmworker->returnCode() == GEARMAN_TIMEOUT)
{
if ($gmworker->returnCode() == GEARMAN_TIMEOUT)
{
# Normally one would want to do something useful here ...
echo "Timeout. Waiting for next job...\n";
continue;
}
if ($gmworker->returnCode() != GEARMAN_SUCCESS)
{
echo "return_code: " . $gmworker->returnCode() . "\n";
break;
}
}
echo "Done\n";
function reverse_fn($job)
{
return strrev($job->workload());
}
?>
```
Running the worker with no submitted jobs will generate output that looks like the following:
```
Starting
Waiting for job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...
Timeout. Waiting for next job...
```
### See Also
* [GearmanWorker::timeout()](gearmanworker.timeout) - Get socket I/O activity timeout
| programming_docs |
php The SessionUpdateTimestampHandlerInterface interface
The SessionUpdateTimestampHandlerInterface interface
====================================================
Introduction
------------
(PHP 7, PHP 8)
**SessionUpdateTimestampHandlerInterface** is an interface which defines optional methods for creating a custom session handler. In order to pass a custom session handler to [session\_set\_save\_handler()](function.session-set-save-handler) using its OOP invocation, the class can implement this interface.
Note that the callback methods of classes implementing this interface are designed to be called internally by PHP and are not meant to be called from user-space code.
Class synopsis
--------------
interface **SessionUpdateTimestampHandlerInterface** { /\* Methods \*/
```
public updateTimestamp(string $id, string $data): bool
```
```
public validateId(string $id): bool
```
} Table of Contents
-----------------
* [SessionUpdateTimestampHandlerInterface::updateTimestamp](sessionupdatetimestamphandlerinterface.updatetimestamp) — Update timestamp
* [SessionUpdateTimestampHandlerInterface::validateId](sessionupdatetimestamphandlerinterface.validateid) — Validate ID
php hex2bin hex2bin
=======
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
hex2bin — Decodes a hexadecimally encoded binary string
### Description
```
hex2bin(string $string): string|false
```
Decodes a hexadecimally encoded binary string.
**Caution** This function does *NOT* convert a hexadecimal number to a binary number. This can be done using the [base\_convert()](function.base-convert) function.
### Parameters
`string`
Hexadecimal representation of data.
### Return Values
Returns the binary representation of the given data or **`false`** on failure.
### Errors/Exceptions
If the hexadecimal input string is of odd length or invalid hexadecimal string an **`E_WARNING`** level error is thrown.
### Examples
**Example #1 **hex2bin()** example**
```
<?php
$hex = hex2bin("6578616d706c65206865782064617461");
var_dump($hex);
?>
```
The above example will output something similar to:
```
string(16) "example hex data"
```
### See Also
* [bin2hex()](function.bin2hex) - Convert binary data into hexadecimal representation
* [unpack()](function.unpack) - Unpack data from binary string
php SolrInputDocument::getChildDocumentsCount SolrInputDocument::getChildDocumentsCount
=========================================
(PECL solr >= 2.3.0)
SolrInputDocument::getChildDocumentsCount — Returns the number of child documents
### Description
```
public SolrInputDocument::getChildDocumentsCount(): int
```
Returns the number of child documents
### Parameters
This function has no parameters.
### Return Values
### See Also
* [SolrInputDocument::addChildDocument()](solrinputdocument.addchilddocument) - Adds a child document for block indexing
* [SolrInputDocument::addChildDocuments()](solrinputdocument.addchilddocuments) - Adds an array of child documents
* [SolrInputDocument::hasChildDocuments()](solrinputdocument.haschilddocuments) - Returns true if the document has any child documents
* [SolrInputDocument::getChildDocuments()](solrinputdocument.getchilddocuments) - Returns an array of child documents (SolrInputDocument)
php Imagick::getPackageName Imagick::getPackageName
=======================
(PECL imagick 2, PECL imagick 3)
Imagick::getPackageName — Returns the ImageMagick package name
### Description
```
public static Imagick::getPackageName(): string
```
Returns the ImageMagick package name.
### Parameters
This function has no parameters.
### Return Values
Returns the ImageMagick package name as a string.
### Errors/Exceptions
Throws ImagickException on error.
php stream_context_get_params stream\_context\_get\_params
============================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
stream\_context\_get\_params — Retrieves parameters from a context
### Description
```
stream_context_get_params(resource $context): array
```
Retrieves parameter and options information from the stream or context.
### Parameters
`context`
A stream resource or a [context](https://www.php.net/manual/en/context.php) resource
### Return Values
Returns an associate array containing all context options and parameters.
### Examples
**Example #1 **stream\_context\_get\_params()** example**
Basic usage example
```
<?php
$ctx = stream_context_create();
$params = array("notification" => "stream_notification_callback");
stream_context_set_params($ctx, $params);
var_dump(stream_context_get_params($ctx));
?>
```
The above example will output something similar to:
```
array(2) {
["notification"]=>
string(28) "stream_notification_callback"
["options"]=>
array(0) {
}
}
```
### See Also
* [stream\_context\_set\_option()](function.stream-context-set-option) - Sets an option for a stream/wrapper/context
* [stream\_context\_set\_params()](function.stream-context-set-params) - Set parameters for a stream/wrapper/context
php mysqli_stmt::$errno mysqli\_stmt::$errno
====================
mysqli\_stmt\_errno
===================
(PHP 5, PHP 7, PHP 8)
mysqli\_stmt::$errno -- mysqli\_stmt\_errno — Returns the error code for the most recent statement call
### Description
Object-oriented style
int [$mysqli\_stmt->errno](mysqli-stmt.errno); Procedural style
```
mysqli_stmt_errno(mysqli_stmt $statement): int
```
Returns the error code for the most recently invoked statement function that can succeed or fail.
### Parameters
`statement`
Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init).
### Return Values
An error code value. Zero means no error occurred.
### Examples
**Example #1 Object-oriented style**
```
<?php
/* Open a connection */
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$mysqli->query("CREATE TABLE myCountry LIKE Country");
$mysqli->query("INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = $mysqli->prepare($query)) {
/* drop table */
$mysqli->query("DROP TABLE myCountry");
/* execute query */
$stmt->execute();
printf("Error: %d.\n", $stmt->errno);
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
```
**Example #2 Procedural style**
```
<?php
/* Open a connection */
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
mysqli_query($link, "CREATE TABLE myCountry LIKE Country");
mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country");
$query = "SELECT Name, Code FROM myCountry ORDER BY Name";
if ($stmt = mysqli_prepare($link, $query)) {
/* drop table */
mysqli_query($link, "DROP TABLE myCountry");
/* execute query */
mysqli_stmt_execute($stmt);
printf("Error: %d.\n", mysqli_stmt_errno($stmt));
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($link);
?>
```
The above examples will output:
```
Error: 1146.
```
### See Also
* [mysqli\_stmt\_error()](mysqli-stmt.error) - Returns a string description for last statement error
* [mysqli\_stmt\_sqlstate()](mysqli-stmt.sqlstate) - Returns SQLSTATE error from previous statement operation
php ZookeeperConfig::get ZookeeperConfig::get
====================
(PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0)
ZookeeperConfig::get — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously
### Description
```
public ZookeeperConfig::get(callable $watcher_cb = null, array &$stat = null): string
```
### Parameters
`watcher_cb`
If nonzero, a watch will be set at the server to notify the client if the node changes.
`stat`
If not NULL, will hold the value of stat for the path on return.
### Return Values
Returns the configuration string on success, and false on failure.
### Errors/Exceptions
This method emits [ZookeeperException](class.zookeeperexception) and it's derivatives when parameters count or types are wrong or fail to get configuration.
### Examples
**Example #1 **ZookeeperConfig::get()** example**
Get configuration.
```
<?php
$zk = new Zookeeper();
$zk->connect('localhost:2181');
$zk->addAuth('digest', 'timandes:timandes');
$zkConfig = $zk->getConfig();
$r = $zkConfig->get();
if ($r)
echo $r;
else
echo 'ERR';
?>
```
The above example will output:
```
server.1=localhost:2888:3888:participant;0.0.0.0:2181
version=0xca01e881a2
```
### See Also
* [ZookeeperConfig::set()](zookeeperconfig.set) - Change ZK cluster ensemble membership and roles of ensemble peers
* [ZookeeperConfig::add()](zookeeperconfig.add) - Add servers to the ensemble
* [ZookeeperConfig::remove()](zookeeperconfig.remove) - Remove servers from the ensemble
* [ZookeeperException](class.zookeeperexception)
php SolrCollapseFunction::setMax SolrCollapseFunction::setMax
============================
(PECL solr >= 2.2.0)
SolrCollapseFunction::setMax — Selects the group heads by the max value of a numeric field or function query
### Description
```
public SolrCollapseFunction::setMax(string $max): SolrCollapseFunction
```
Selects the group heads by the max value of a numeric field or function query.
### Parameters
`max`
### Return Values
[SolrCollapseFunction](class.solrcollapsefunction)
### Examples
**Example #1 **SolrCollapseFunction::setMax()** example**
```
<?php
$func = new SolrCollapseFunction('field_name');
$func->setMax('sum(cscore(),field(some_field))');
$query = new SolrQuery('*:*');
$query->collapse($func);
?>
```
php Yaf_Request_Abstract::getControllerName Yaf\_Request\_Abstract::getControllerName
=========================================
(Yaf >=1.0.0)
Yaf\_Request\_Abstract::getControllerName — The getControllerName purpose
### Description
```
public Yaf_Request_Abstract::getControllerName(): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php output_add_rewrite_var output\_add\_rewrite\_var
=========================
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
output\_add\_rewrite\_var — Add URL rewriter values
### Description
```
output_add_rewrite_var(string $name, string $value): bool
```
This function adds another name/value pair to the URL rewrite mechanism. The name and value will be added to URLs (as GET parameter) and forms (as hidden input fields) the same way as the session ID when transparent URL rewriting is enabled with [session.use\_trans\_sid](https://www.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid).
This function's behaviour is controlled by the [url\_rewriter.tags](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.tags) and [url\_rewriter.hosts](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.hosts) php.ini parameters.
Note that this function can be successfully called at most once per request.
> **Note**: Calling this function will implicitly start output buffering if it is not active already.
>
>
### Parameters
`name`
The variable name.
`value`
The variable value.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 7.1.0 | Before PHP 7.1.0, rewrite vars set by **output\_add\_rewrite\_var()** use the same Session module trans sid output buffer. Since PHP 7.1.0, dedicated output buffer is used, [url\_rewriter.tags](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.tags) is used solely for output functions, [url\_rewriter.hosts](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.tags) is added. |
### Examples
**Example #1 **output\_add\_rewrite\_var()** example**
```
<?php
output_add_rewrite_var('var', 'value');
// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';
// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';
print_r(ob_list_handlers());
?>
```
The above example will output:
```
<a href="file.php?var=value">link</a>
<a href="http://example.com">link2</a>
<form action="script.php" method="post">
<input type="hidden" name="var" value="value" />
<input type="text" name="var2" />
</form>
Array
(
[0] => URL-Rewriter
)
```
### See Also
* [output\_reset\_rewrite\_vars()](function.output-reset-rewrite-vars) - Reset URL rewriter values
* [ob\_flush()](function.ob-flush) - Flush (send) the output buffer
* [ob\_list\_handlers()](function.ob-list-handlers) - List all output handlers in use
* [url\_rewriter.tags](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.tags)
* [url\_rewriter.hosts](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.hosts)
* [session.trans\_sid\_tags](https://www.php.net/manual/en/session.configuration.php#ini.session.trans-sid-tags)
* [session.trans\_sid\_hosts](https://www.php.net/manual/en/session.configuration.php#ini.session.trans-sid-hosts)
php Yaf_Controller_Abstract::getView Yaf\_Controller\_Abstract::getView
==================================
(Yaf >=1.0.0)
Yaf\_Controller\_Abstract::getView — Retrieve the view engine
### Description
```
public Yaf_Controller_Abstract::getView(): Yaf_View_Interface
```
retrieve view engine
### Parameters
This function has no parameters.
### Return Values
php fbird_name_result fbird\_name\_result
===================
(PHP 5, PHP 7 < 7.4.0)
fbird\_name\_result — Alias of [ibase\_name\_result()](function.ibase-name-result)
### Description
This function is an alias of: [ibase\_name\_result()](function.ibase-name-result).
### See Also
* [fbird\_prepare()](function.fbird-prepare) - Alias of ibase\_prepare
* [fbird\_execute()](function.fbird-execute) - Alias of ibase\_execute
php DOMNamedNodeMap::getNamedItemNS DOMNamedNodeMap::getNamedItemNS
===============================
(PHP 5, PHP 7, PHP 8)
DOMNamedNodeMap::getNamedItemNS — Retrieves a node specified by local name and namespace URI
### Description
```
public DOMNamedNodeMap::getNamedItemNS(?string $namespace, string $localName): ?DOMNode
```
Retrieves a node specified by `localName` and `namespace`.
### Parameters
`namespace`
The namespace URI of the node to retrieve.
`localName`
The local name of the node to retrieve.
### Return Values
A node (of any type) with the specified local name and namespace URI, or **`null`** if no node is found.
### See Also
* [DOMNamedNodeMap::getNamedItem()](domnamednodemap.getnameditem) - Retrieves a node specified by name
php ftp_alloc ftp\_alloc
==========
(PHP 5, PHP 7, PHP 8)
ftp\_alloc — Allocates space for a file to be uploaded
### Description
```
ftp_alloc(FTP\Connection $ftp, int $size, string &$response = null): bool
```
Sends an `ALLO` command to the remote FTP server to allocate space for a file to be uploaded.
>
> **Note**:
>
>
> Many FTP servers do not support this command. These servers may return a failure code (**`false`**) indicating the command is not supported or a success code (**`true`**) to indicate that pre-allocation is not necessary and the client should continue as though the operation were successful. Because of this, it may be best to reserve this function for servers which explicitly require preallocation.
>
>
### Parameters
`ftp`
An [FTP\Connection](class.ftp-connection) instance.
`size`
The number of bytes to allocate.
`response`
A textual representation of the servers response will be returned by reference in `response` if a variable is provided.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **ftp\_alloc()** example**
```
<?php
$file = "/home/user/myfile";
// connect to the server
$ftp = ftp_connect('ftp.example.com');
$login_result = ftp_login($ftp, 'anonymous', '[email protected]');
if (ftp_alloc($ftp, filesize($file), $result)) {
echo "Space successfully allocated on server. Sending $file.\n";
ftp_put($ftp, '/incoming/myfile', $file, FTP_BINARY);
} else {
echo "Unable to allocate space on server. Server said: $result\n";
}
ftp_close($ftp);
?>
```
### See Also
* [ftp\_put()](function.ftp-put) - Uploads a file to the FTP server
* [ftp\_fput()](function.ftp-fput) - Uploads from an open file to the FTP server
php Ds\Deque::sorted Ds\Deque::sorted
================
(PECL ds >= 1.0.0)
Ds\Deque::sorted — Returns a sorted copy
### Description
```
public Ds\Deque::sorted(callable $comparator = ?): Ds\Deque
```
Returns a sorted copy, using an optional `comparator` function.
### Parameters
`comparator`
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
```
callback(mixed $a, mixed $b): int
```
**Caution** Returning *non-integer* values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal.
### Return Values
Returns a sorted copy of the deque.
### Examples
**Example #1 **Ds\Deque::sorted()** example**
```
<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);
print_r($deque->sorted());
?>
```
The above example will output something similar to:
```
Ds\Deque Object
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
```
**Example #2 **Ds\Deque::sorted()** example using a comparator**
```
<?php
$deque = new \Ds\Deque([4, 5, 1, 3, 2]);
$sorted = $deque->sorted(function($a, $b) {
return $b <=> $a;
});
print_r($sorted);
?>
```
The above example will output something similar to:
```
Ds\Deque Object
(
[0] => 5
[1] => 4
[2] => 3
[3] => 2
[4] => 1
)
```
php SplFixedArray::setSize SplFixedArray::setSize
======================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplFixedArray::setSize — Change the size of an array
### Description
```
public SplFixedArray::setSize(int $size): bool
```
Change the size of an array to the new size of `size`. If `size` is less than the current array size, any values after the new size will be discarded. If `size` is greater than the current array size, the array will be padded with **`null`** values.
### Parameters
`size`
The new array size. This should be a value between `0` and **`PHP_INT_MAX`**.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Errors/Exceptions
Throws [InvalidArgumentException](class.invalidargumentexception) when `size` is less than zero.
Raises **`E_WARNING`** when `size` cannot be used as a number.
### Examples
**Example #1 **SplFixedArray::setSize()** example**
```
<?php
$array = new SplFixedArray(5);
echo $array->getSize()."\n";
$array->setSize(10);
echo $array->getSize()."\n";
?>
```
The above example will output:
```
5
10
```
| programming_docs |
php The DOMEntityReference class
The DOMEntityReference class
============================
Class synopsis
--------------
(PHP 5, PHP 7, PHP 8)
class **DOMEntityReference** extends [DOMNode](class.domnode) { /\* Inherited properties \*/ public readonly string [$nodeName](class.domnode#domnode.props.nodename);
public ?string [$nodeValue](class.domnode#domnode.props.nodevalue);
public readonly int [$nodeType](class.domnode#domnode.props.nodetype);
public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode);
public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes);
public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild);
public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild);
public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling);
public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling);
public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes);
public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument);
public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri);
public string [$prefix](class.domnode#domnode.props.prefix);
public readonly ?string [$localName](class.domnode#domnode.props.localname);
public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri);
public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domentityreference.construct)(string `$name`) /\* Inherited methods \*/
```
public DOMNode::appendChild(DOMNode $node): DOMNode|false
```
```
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
```
```
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
```
```
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
```
```
public DOMNode::getLineNo(): int
```
```
public DOMNode::getNodePath(): ?string
```
```
public DOMNode::hasAttributes(): bool
```
```
public DOMNode::hasChildNodes(): bool
```
```
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
```
```
public DOMNode::isDefaultNamespace(string $namespace): bool
```
```
public DOMNode::isSameNode(DOMNode $otherNode): bool
```
```
public DOMNode::isSupported(string $feature, string $version): bool
```
```
public DOMNode::lookupNamespaceUri(string $prefix): string
```
```
public DOMNode::lookupPrefix(string $namespace): ?string
```
```
public DOMNode::normalize(): void
```
```
public DOMNode::removeChild(DOMNode $child): DOMNode|false
```
```
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
```
} Table of Contents
-----------------
* [DOMEntityReference::\_\_construct](domentityreference.construct) — Creates a new DOMEntityReference object
php DOMNamedNodeMap::count DOMNamedNodeMap::count
======================
(PHP 7 >= 7.2.0, PHP 8)
DOMNamedNodeMap::count — Get number of nodes in the map
### Description
```
public DOMNamedNodeMap::count(): int
```
Gets the number of nodes in the map.
### Parameters
This function has no parameters.
### Return Values
Returns the number of nodes in the map, which is identical to the [length](class.domnamednodemap#domnamednodemap.props.length) property.
php DOMChildNode::replaceWith DOMChildNode::replaceWith
=========================
(PHP 8)
DOMChildNode::replaceWith — Replaces the node with new nodes
### Description
```
public DOMChildNode::replaceWith(DOMNode|string ...$nodes): void
```
Replaces the node with new `nodes`. A combination of [DOMChildNode::remove()](domchildnode.remove) and **DOMChildNode::append()**.
### Parameters
`nodes`
The replacement nodes.
### Return Values
No value is returned.
### See Also
* [DOMChildNode::after()](domchildnode.after) - Adds nodes after the node
* [DOMChildNode::before()](domchildnode.before) - Adds nodes before the node
* [DOMChildNode::remove()](domchildnode.remove) - Removes the node
* [DOMNode::replaceChild()](domnode.replacechild) - Replaces a child
php ReflectionExtension::__construct ReflectionExtension::\_\_construct
==================================
(PHP 5, PHP 7, PHP 8)
ReflectionExtension::\_\_construct — Constructs a ReflectionExtension
### Description
public **ReflectionExtension::\_\_construct**(string `$name`) Construct a [ReflectionExtension](class.reflectionextension) object.
### Parameters
`name`
Name of the extension.
### Examples
**Example #1 [ReflectionExtension](class.reflectionextension) example**
```
<?php
$ext = new ReflectionExtension('Reflection');
printf('Extension: %s (version: %s)', $ext->getName(), $ext->getVersion());
?>
```
The above example will output something similar to:
```
Extension: Reflection (version: $Revision$)
```
### See Also
* [ReflectionExtension::info()](reflectionextension.info) - Print extension info
* [Constructors](language.oop5.decon#language.oop5.decon.constructor)
php The Yaf_Route_Rewrite class
The Yaf\_Route\_Rewrite class
=============================
Introduction
------------
(Yaf >=1.0.0)
For usage, please see the example section of [Yaf\_Route\_Rewrite::\_\_construct()](yaf-route-rewrite.construct)
Class synopsis
--------------
class **Yaf\_Route\_Rewrite** extends [Yaf\_Route\_Interface](class.yaf-route-interface) implements [Yaf\_Route\_Interface](class.yaf-route-interface) { /\* Properties \*/ protected [$\_route](class.yaf-route-rewrite#yaf-route-rewrite.props.route);
protected [$\_default](class.yaf-route-rewrite#yaf-route-rewrite.props.default);
protected [$\_verify](class.yaf-route-rewrite#yaf-route-rewrite.props.verify); /\* Methods \*/ public [\_\_construct](yaf-route-rewrite.construct)(string `$match`, array `$route`, array `$verify` = ?)
```
public assemble(array $info, array $query = ?): string
```
```
public route(Yaf_Request_Abstract $request): bool
```
/\* Inherited methods \*/
```
abstract public Yaf_Route_Interface::assemble(array $info, array $query = ?): string
```
```
abstract public Yaf_Route_Interface::route(Yaf_Request_Abstract $request): bool
```
} Properties
----------
\_route \_default \_verify Table of Contents
-----------------
* [Yaf\_Route\_Rewrite::assemble](yaf-route-rewrite.assemble) — Assemble a url
* [Yaf\_Route\_Rewrite::\_\_construct](yaf-route-rewrite.construct) — Yaf\_Route\_Rewrite constructor
* [Yaf\_Route\_Rewrite::route](yaf-route-rewrite.route) — The route purpose
php The mysqli_stmt class
The mysqli\_stmt class
======================
Introduction
------------
(PHP 5, PHP 7, PHP 8)
Represents a prepared statement.
Class synopsis
--------------
class **mysqli\_stmt** { /\* Properties \*/ public readonly int|string [$affected\_rows](mysqli-stmt.affected-rows);
public readonly int|string [$insert\_id](mysqli-stmt.insert-id);
public readonly int|string [$num\_rows](mysqli-stmt.num-rows);
public readonly int [$param\_count](mysqli-stmt.param-count);
public readonly int [$field\_count](mysqli-stmt.field-count);
public readonly int [$errno](mysqli-stmt.errno);
public readonly string [$error](mysqli-stmt.error);
public readonly array [$error\_list](mysqli-stmt.error-list);
public readonly string [$sqlstate](mysqli-stmt.sqlstate);
public int [$id](class.mysqli-stmt#mysqli-stmt.props.id); /\* Methods \*/ public [\_\_construct](mysqli-stmt.construct)([mysqli](class.mysqli) `$mysql`, ?string `$query` = **`null`**)
```
public attr_get(int $attribute): int
```
```
public attr_set(int $attribute, int $value): bool
```
```
public bind_param(string $types, mixed &$var, mixed &...$vars): bool
```
```
public bind_result(mixed &$var, mixed &...$vars): bool
```
```
public close(): bool
```
```
public data_seek(int $offset): void
```
```
public execute(?array $params = null): bool
```
```
public fetch(): ?bool
```
```
public free_result(): void
```
```
public get_result(): mysqli_result|false
```
```
public get_warnings(): mysqli_warning|false
```
```
public more_results(): bool
```
```
public next_result(): bool
```
```
public num_rows(): int|string
```
```
public prepare(string $query): bool
```
```
public reset(): bool
```
```
public result_metadata(): mysqli_result|false
```
```
public send_long_data(int $param_num, string $data): bool
```
```
public store_result(): bool
```
} Properties
----------
id Stores the statement ID.
Table of Contents
-----------------
* [mysqli\_stmt::$affected\_rows](mysqli-stmt.affected-rows) — Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed
* [mysqli\_stmt::attr\_get](mysqli-stmt.attr-get) — Used to get the current value of a statement attribute
* [mysqli\_stmt::attr\_set](mysqli-stmt.attr-set) — Used to modify the behavior of a prepared statement
* [mysqli\_stmt::bind\_param](mysqli-stmt.bind-param) — Binds variables to a prepared statement as parameters
* [mysqli\_stmt::bind\_result](mysqli-stmt.bind-result) — Binds variables to a prepared statement for result storage
* [mysqli\_stmt::close](mysqli-stmt.close) — Closes a prepared statement
* [mysqli\_stmt::\_\_construct](mysqli-stmt.construct) — Constructs a new mysqli\_stmt object
* [mysqli\_stmt::data\_seek](mysqli-stmt.data-seek) — Seeks to an arbitrary row in statement result set
* [mysqli\_stmt::$errno](mysqli-stmt.errno) — Returns the error code for the most recent statement call
* [mysqli\_stmt::$error\_list](mysqli-stmt.error-list) — Returns a list of errors from the last statement executed
* [mysqli\_stmt::$error](mysqli-stmt.error) — Returns a string description for last statement error
* [mysqli\_stmt::execute](mysqli-stmt.execute) — Executes a prepared statement
* [mysqli\_stmt::fetch](mysqli-stmt.fetch) — Fetch results from a prepared statement into the bound variables
* [mysqli\_stmt::$field\_count](mysqli-stmt.field-count) — Returns the number of columns in the given statement
* [mysqli\_stmt::free\_result](mysqli-stmt.free-result) — Frees stored result memory for the given statement handle
* [mysqli\_stmt::get\_result](mysqli-stmt.get-result) — Gets a result set from a prepared statement as a mysqli\_result object
* [mysqli\_stmt::get\_warnings](mysqli-stmt.get-warnings) — Get result of SHOW WARNINGS
* [mysqli\_stmt::$insert\_id](mysqli-stmt.insert-id) — Get the ID generated from the previous INSERT operation
* [mysqli\_stmt::more\_results](mysqli-stmt.more-results) — Check if there are more query results from a multiple query
* [mysqli\_stmt::next\_result](mysqli-stmt.next-result) — Reads the next result from a multiple query
* [mysqli\_stmt::$num\_rows](mysqli-stmt.num-rows) — Returns the number of rows fetched from the server
* [mysqli\_stmt::$param\_count](mysqli-stmt.param-count) — Returns the number of parameters for the given statement
* [mysqli\_stmt::prepare](mysqli-stmt.prepare) — Prepares an SQL statement for execution
* [mysqli\_stmt::reset](mysqli-stmt.reset) — Resets a prepared statement
* [mysqli\_stmt::result\_metadata](mysqli-stmt.result-metadata) — Returns result set metadata from a prepared statement
* [mysqli\_stmt::send\_long\_data](mysqli-stmt.send-long-data) — Send data in blocks
* [mysqli\_stmt::$sqlstate](mysqli-stmt.sqlstate) — Returns SQLSTATE error from previous statement operation
* [mysqli\_stmt::store\_result](mysqli-stmt.store-result) — Stores a result set in an internal buffer
php GearmanTask::recvData GearmanTask::recvData
=====================
(PECL gearman >= 0.5.0)
GearmanTask::recvData — Read work or result data into a buffer for a task
### Description
```
public GearmanTask::recvData(int $data_len): array
```
**Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
### Parameters
`data_len`
Length of data to be read.
### Return Values
An array whose first element is the length of data read and the second is the data buffer. Returns **`false`** if the read failed.
### See Also
* [GearmanTask::sendData()](gearmantask.senddata) - Send data for a task (deprecated)
php PharData::isWritable PharData::isWritable
====================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)
PharData::isWritable — Returns true if the tar/zip archive can be modified
### Description
```
public PharData::isWritable(): bool
```
This method returns **`true`** if the tar/zip archive on disk is not read-only. Unlike [Phar::isWritable()](phar.iswritable), data-only tar/zip archives can be modified even if `phar.readonly` is set to `1`.
### Parameters
No parameters.
### Return Values
Returns **`true`** if the tar/zip archive can be modified
### See Also
* [Phar::canWrite()](phar.canwrite) - Returns whether phar extension supports writing and creating phars
* [Phar::isWritable()](phar.iswritable) - Returns true if the phar archive can be modified
php DOMDocument::normalizeDocument DOMDocument::normalizeDocument
==============================
(PHP 5, PHP 7, PHP 8)
DOMDocument::normalizeDocument — Normalizes the document
### Description
```
public DOMDocument::normalizeDocument(): void
```
This method acts as if you saved and then loaded the document, putting the document in a "normal" form.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
### See Also
* [» The DOM Specification](http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-normalizeDocument)
* [DOMNode::normalize()](domnode.normalize) - Normalizes the node
php None match
-----
(PHP 8)
The `match` expression branches evaluation based on an identity check of a value. Similarly to a `switch` statement, a `match` expression has a subject expression that is compared against multiple alternatives. Unlike `switch`, it will evaluate to a value much like ternary expressions. Unlike `switch`, the comparison is an identity check (`===`) rather than a weak equality check (`==`). Match expressions are available as of PHP 8.0.0.
**Example #1 Structure of a `match` expression**
```
<?php
$return_value = match (subject_expression) {
single_conditional_expression => return_expression,
conditional_expression1, conditional_expression2 => return_expression,
};
?>
```
**Example #2 Basic `match` usage**
```
<?php
$food = 'cake';
$return_value = match ($food) {
'apple' => 'This food is an apple',
'bar' => 'This food is a bar',
'cake' => 'This food is a cake',
};
var_dump($return_value);
?>
```
The above example will output:
```
string(19) "This food is a cake"
```
> **Note**: The result of a `match` expression does not need to be used.
>
>
> **Note**: A `match` expression *must* be terminated by a semicolon `;`.
>
>
The `match` expression is similar to a `switch` statement but has some key differences:
* A `match` arm compares values strictly (`===`) instead of loosely as the switch statement does.
* A `match` expression returns a value.
* `match` arms do not fall-through to later cases the way `switch` statements do.
* A `match` expression must be exhaustive.
As `switch` statements, `match` expressions are executed match arm by match arm. In the beginning, no code is executed. The conditional expressions are only evaluated if all previous conditional expressions failed to match the subject expression. Only the return expression corresponding to the matching conditional expression will be evaluated. For example:
```
<?php
$result = match ($x) {
foo() => ...,
$this->bar() => ..., // $this->bar() isn't called if foo() === $x
$this->baz => beep(), // beep() isn't called unless $x === $this->baz
// etc.
};
?>
```
`match` expression arms may contain multiple expressions separated by a comma. That is a logical OR, and is a short-hand for multiple match arms with the same right-hand side.
```
<?php
$result = match ($x) {
// This match arm:
$a, $b, $c => 5,
// Is equivalent to these three match arms:
$a => 5,
$b => 5,
$c => 5,
};
?>
```
A special case is the `default` pattern. This pattern matches anything that wasn't previously matched. For example:
```
<?php
$expressionResult = match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
default => baz(),
};
?>
```
> **Note**: Multiple default patterns will raise a **`E_FATAL_ERROR`** error.
>
>
A `match` expression must be exhaustive. If the subject expression is not handled by any match arm an [UnhandledMatchError](class.unhandledmatcherror) is thrown.
**Example #3 Example of an unhandled match expression**
```
<?php
$condition = 5;
try {
match ($condition) {
1, 2 => foo(),
3, 4 => bar(),
};
} catch (\UnhandledMatchError $e) {
var_dump($e);
}
?>
```
The above example will output:
```
object(UnhandledMatchError)#1 (7) {
["message":protected]=>
string(33) "Unhandled match value of type int"
["string":"Error":private]=>
string(0) ""
["code":protected]=>
int(0)
["file":protected]=>
string(9) "/in/ICgGK"
["line":protected]=>
int(6)
["trace":"Error":private]=>
array(0) {
}
["previous":"Error":private]=>
NULL
}
```
### Using match expressions to handle non identity checks
It is possible to use a `match` expression to handle non-identity conditional cases by using `true` as the subject expression.
**Example #4 Using a generalized match expressions to branch on integer ranges**
```
<?php
$age = 23;
$result = match (true) {
$age >= 65 => 'senior',
$age >= 25 => 'adult',
$age >= 18 => 'young adult',
default => 'kid',
};
var_dump($result);
?>
```
The above example will output:
```
string(11) "young adult"
```
**Example #5 Using a generalized match expressions to branch on string content**
```
<?php
$text = 'Bienvenue chez nous';
$result = match (true) {
str_contains($text, 'Welcome') || str_contains($text, 'Hello') => 'en',
str_contains($text, 'Bienvenue') || str_contains($text, 'Bonjour') => 'fr',
// ...
};
var_dump($result);
?>
```
The above example will output:
```
string(2) "fr"
```
php Ds\Collection::toArray Ds\Collection::toArray
======================
(PECL ds >= 1.0.0)
Ds\Collection::toArray — Converts the collection to an array
### Description
```
abstract public Ds\Collection::toArray(): array
```
Converts the collection to an array.
>
> **Note**:
>
>
> Casting to an array is not supported yet.
>
>
### Parameters
This function has no parameters.
### Return Values
An array containing all the values in the same order as the collection.
### Examples
**Example #1 **Ds\Collection::toArray()** example**
```
<?php
$collection = new \Ds\Vector([1, 2, 3]);
var_dump($collection->toArray());
?>
```
The above example will output something similar to:
```
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
```
php ftp_nb_get ftp\_nb\_get
============
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
ftp\_nb\_get — Retrieves a file from the FTP server and writes it to a local file (non-blocking)
### Description
```
ftp_nb_get(
FTP\Connection $ftp,
string $local_filename,
string $remote_filename,
int $mode = FTP_BINARY,
int $offset = 0
): int
```
**ftp\_nb\_get()** retrieves a remote file from the FTP server, and saves it into a local file.
The difference between this function and [ftp\_get()](function.ftp-get) is that this function retrieves the file asynchronously, so your program can perform other operations while the file is being downloaded.
### Parameters
`ftp`
An [FTP\Connection](class.ftp-connection) instance.
`local_filename`
The local file path (will be overwritten if the file already exists).
`remote_filename`
The remote file path.
`mode`
The transfer mode. Must be either **`FTP_ASCII`** or **`FTP_BINARY`**.
`offset`
The position in the remote file to start downloading from.
### Return Values
Returns **`FTP_FAILED`** or **`FTP_FINISHED`** or **`FTP_MOREDATA`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. |
| 7.3.0 | The `mode` parameter is now optional. Formerly it has been mandatory. |
### Examples
**Example #1 **ftp\_nb\_get()** example**
```
<?php
// Initiate the download
$ret = ftp_nb_get($ftp, "test", "README", FTP_BINARY);
while ($ret == FTP_MOREDATA) {
// Do whatever you want
echo ".";
// Continue downloading...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "There was an error downloading the file...";
exit(1);
}
?>
```
**Example #2 Resuming a download with **ftp\_nb\_get()****
```
<?php
// Initiate
$ret = ftp_nb_get($ftp, "test", "README", FTP_BINARY,
filesize("test"));
// OR: $ret = ftp_nb_get($ftp, "test", "README",
// FTP_BINARY, FTP_AUTORESUME);
while ($ret == FTP_MOREDATA) {
// Do whatever you want
echo ".";
// Continue downloading...
$ret = ftp_nb_continue($ftp);
}
if ($ret != FTP_FINISHED) {
echo "There was an error downloading the file...";
exit(1);
}
?>
```
**Example #3 Resuming a download at position 100 to a new file with **ftp\_nb\_get()****
```
<?php
// Disable Autoseek
ftp_set_option($ftp, FTP_AUTOSEEK, false);
// Initiate
$ret = ftp_nb_get($ftp, "newfile", "README", FTP_BINARY, 100);
while ($ret == FTP_MOREDATA) {
/* ... */
// Continue downloading...
$ret = ftp_nb_continue($ftp);
}
?>
```
In the example above, newfile is 100 bytes smaller than README on the FTP server because we started reading at offset 100. If we didn't disable **`FTP_AUTOSEEK`**, the first 100 bytes of newfile would be `'\0'`.
### See Also
* [ftp\_nb\_fget()](function.ftp-nb-fget) - Retrieves a file from the FTP server and writes it to an open file (non-blocking)
* [ftp\_nb\_continue()](function.ftp-nb-continue) - Continues retrieving/sending a file (non-blocking)
* [ftp\_fget()](function.ftp-fget) - Downloads a file from the FTP server and saves to an open file
* [ftp\_get()](function.ftp-get) - Downloads a file from the FTP server
| programming_docs |
php ReflectionGenerator::getExecutingGenerator ReflectionGenerator::getExecutingGenerator
==========================================
(PHP 7, PHP 8)
ReflectionGenerator::getExecutingGenerator — Gets the executing [Generator](class.generator) object
### Description
```
public ReflectionGenerator::getExecutingGenerator(): Generator
```
Get the executing [Generator](class.generator) object
### Parameters
This function has no parameters.
### Return Values
Returns the currently executing [Generator](class.generator) object.
### Examples
**Example #1 **ReflectionGenerator::getExecutingGenerator()** example**
```
<?php
class GenExample
{
public function gen()
{
yield 1;
}
}
$gen = (new GenExample)->gen();
$reflectionGen = new ReflectionGenerator($gen);
$gen2 = $reflectionGen->getExecutingGenerator();
var_dump($gen2 === $gen);
var_dump($gen2->current());
```
The above example will output something similar to:
```
bool(true)
int(1);
```
### See Also
* [ReflectionGenerator::getExecutingLine()](reflectiongenerator.getexecutingline) - Gets the currently executing line of the generator
* [ReflectionGenerator::getExecutingFile()](reflectiongenerator.getexecutingfile) - Gets the file name of the currently executing generator
php OAuth::setVersion OAuth::setVersion
=================
(PECL OAuth >= 0.99.1)
OAuth::setVersion — Set the OAuth version
### Description
```
public OAuth::setVersion(string $version): bool
```
Sets the OAuth version for subsequent requests
### Parameters
`version`
OAuth version, default value is always "1.0"
### Return Values
Returns **`true`** on success or **`false`** on failure.
php IntlRuleBasedBreakIterator::getRules IntlRuleBasedBreakIterator::getRules
====================================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
IntlRuleBasedBreakIterator::getRules — Get the rule set used to create this object
### Description
```
public IntlRuleBasedBreakIterator::getRules(): string|false
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php fclose fclose
======
(PHP 4, PHP 5, PHP 7, PHP 8)
fclose — Closes an open file pointer
### Description
```
fclose(resource $stream): bool
```
The file pointed to by `stream` is closed.
### Parameters
`stream`
The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 A simple **fclose()** example**
```
<?php
$handle = fopen('somefile.txt', 'r');
fclose($handle);
?>
```
### See Also
* [fopen()](function.fopen) - Opens file or URL
* [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection
php DateTimeImmutable::add DateTimeImmutable::add
======================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
DateTimeImmutable::add — Returns a new object, with added amount of days, months, years, hours, minutes and seconds
### Description
```
public DateTimeImmutable::add(DateInterval $interval): DateTimeImmutable
```
Creates a new [DateTimeImmutable](class.datetimeimmutable) object, and adds the specified [DateInterval](class.dateinterval) object to this, to represent the new value.
### Parameters
`interval` A [DateInterval](class.dateinterval) object
### Return Values
Returns a new [DateTimeImmutable](class.datetimeimmutable) object with the modified data.
### Examples
**Example #1 **DateTimeImmutable::add()** example**
Object-oriented style
```
<?php
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('P10D'));
echo $newDate->format('Y-m-d') . "\n";
?>
```
**Example #2 Further **DateTimeImmutable::add()** examples**
```
<?php
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('PT10H30S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
$date = new DateTimeImmutable('2000-01-01');
$newDate = $date->add(new DateInterval('P7Y5M4DT4H3M2S'));
echo $newDate->format('Y-m-d H:i:s') . "\n";
?>
```
The above example will output:
```
2000-01-01 10:00:30
2007-06-05 04:03:02
```
**Example #3 Beware when adding months**
```
<?php
$date = new DateTimeImmutable('2000-12-31');
$interval = new DateInterval('P1M');
$newDate1 = $date->add($interval);
echo $newDate1->format('Y-m-d') . "\n";
$newDate2 = $newDate1->add($interval);
echo $newDate2->format('Y-m-d') . "\n";
?>
```
The above example will output:
```
2001-01-31
2001-03-03
```
### See Also
* [DateTimeImmutable::sub()](datetimeimmutable.sub) - Subtracts an amount of days, months, years, hours, minutes and seconds
* [DateTimeImmutable::diff()](datetime.diff) - Returns the difference between two DateTime objects
* [DateTimeImmutable::modify()](datetimeimmutable.modify) - Creates a new object with modified timestamp
php Imagick::setImageArtifact Imagick::setImageArtifact
=========================
(PECL imagick 3)
Imagick::setImageArtifact — Set image artifact
### Description
```
public Imagick::setImageArtifact(string $artifact, string $value): bool
```
Associates an artifact with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.
### Parameters
`artifact`
The name of the artifact
`value`
The value of the artifact
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
### Examples
**Example #1 **Imagick::setImageArtifact()****
```
<?php
function setImageArtifact() {
$src1 = new \Imagick(realpath("./images/artifact/source1.png"));
$src2 = new \Imagick(realpath("./images/artifact/source2.png"));
$src2->setImageVirtualPixelMethod(\Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$src2->setImageArtifact('compose:args', "1,0,-0.5,0.5");
$src1->compositeImage($src2, Imagick::COMPOSITE_MATHEMATICS, 0, 0);
$src1->setImageFormat('png');
header("Content-Type: image/png");
echo $src1->getImagesBlob();
}
?>
```
### See Also
* [Imagick::getImageArtifact()](imagick.getimageartifact) - Get image artifact
* [Imagick::deleteImageArtifact()](imagick.deleteimageartifact) - Delete image artifact
php imap_mime_header_decode imap\_mime\_header\_decode
==========================
(PHP 4, PHP 5, PHP 7, PHP 8)
imap\_mime\_header\_decode — Decode MIME header elements
### Description
```
imap_mime_header_decode(string $string): array|false
```
Decodes MIME message header extensions that are non ASCII text (see [» RFC2047](http://www.faqs.org/rfcs/rfc2047)).
### Parameters
`string`
The MIME text
### Return Values
The decoded elements are returned in an array of objects, where each object has two properties, `charset` and `text`.
If the element hasn't been encoded, and in other words is in plain US-ASCII, the `charset` property of that element is set to `default`.
The function returns **`false`** on failure.
### Examples
**Example #1 **imap\_mime\_header\_decode()** example**
```
<?php
$text = "=?ISO-8859-1?Q?Keld_J=F8rn_Simonsen?= <[email protected]>";
$elements = imap_mime_header_decode($text);
for ($i=0; $i<count($elements); $i++) {
echo "Charset: {$elements[$i]->charset}\n";
echo "Text: {$elements[$i]->text}\n\n";
}
?>
```
The above example will output:
```
Charset: ISO-8859-1
Text: Keld Jørn Simonsen
Charset: default
Text: <[email protected]>
```
In the above example we would have two elements, whereas the first element had previously been encoded with ISO-8859-1, and the second element would be plain US-ASCII.
### See Also
* [imap\_utf8()](function.imap-utf8) - Converts MIME-encoded text to UTF-8
php stream_bucket_append stream\_bucket\_append
======================
(PHP 5, PHP 7, PHP 8)
stream\_bucket\_append — Append bucket to brigade
### Description
```
stream_bucket_append(resource $brigade, object $bucket): void
```
**Warning**This function is currently not documented; only its argument list is available.
php Imagick::getQuantumRange Imagick::getQuantumRange
========================
(PECL imagick 2, PECL imagick 3)
Imagick::getQuantumRange — Returns the Imagick quantum range
### Description
```
public static Imagick::getQuantumRange(): array
```
Returns the quantum range for the Imagick instance.
### Parameters
This function has no parameters.
### Return Values
Returns an associative array containing the quantum range as an int (`"quantumRangeLong"`) and as a string (`"quantumRangeString"`).
### Errors/Exceptions
Throws ImagickException on error.
php pg_result_error_field pg\_result\_error\_field
========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
pg\_result\_error\_field — Returns an individual field of an error report
### Description
```
pg_result_error_field(PgSql\Result $result, int $field_code): string|false|null
```
**pg\_result\_error\_field()** returns one of the detailed error message fields associated with `result` instance. It is only available against a PostgreSQL 7.4 or above server. The error field is specified by the `field_code`.
Because [pg\_query()](function.pg-query) and [pg\_query\_params()](function.pg-query-params) return **`false`** if the query fails, you must use [pg\_send\_query()](function.pg-send-query) and [pg\_get\_result()](function.pg-get-result) to get the result handle.
If you need to get additional error information from failed [pg\_query()](function.pg-query) queries, use [pg\_set\_error\_verbosity()](function.pg-set-error-verbosity) and [pg\_last\_error()](function.pg-last-error) and then parse the result.
### Parameters
`result`
An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others).
`field_code`
Possible `field_code` values are: **`PGSQL_DIAG_SEVERITY`**, **`PGSQL_DIAG_SQLSTATE`**, **`PGSQL_DIAG_MESSAGE_PRIMARY`**, **`PGSQL_DIAG_MESSAGE_DETAIL`**, **`PGSQL_DIAG_MESSAGE_HINT`**, **`PGSQL_DIAG_STATEMENT_POSITION`**, **`PGSQL_DIAG_INTERNAL_POSITION`** (PostgreSQL 8.0+ only), **`PGSQL_DIAG_INTERNAL_QUERY`** (PostgreSQL 8.0+ only), **`PGSQL_DIAG_CONTEXT`**, **`PGSQL_DIAG_SOURCE_FILE`**, **`PGSQL_DIAG_SOURCE_LINE`** or **`PGSQL_DIAG_SOURCE_FUNCTION`**.
### Return Values
A string containing the contents of the error field, **`null`** if the field does not exist or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **pg\_result\_error\_field()** example**
```
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
$res1 = pg_get_result($dbconn);
echo pg_result_error_field($res1, PGSQL_DIAG_SQLSTATE);
?>
```
### See Also
* [pg\_result\_error()](function.pg-result-error) - Get error message associated with result
php PharData::compress PharData::compress
==================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)
PharData::compress — Compresses the entire tar/zip archive using Gzip or Bzip2 compression
### Description
```
public PharData::compress(int $compression, ?string $extension = null): ?PharData
```
For tar archives, this method compresses the entire archive using gzip compression or bzip2 compression. The resulting file can be processed with the gunzip command/bunzip command, or accessed directly and transparently with the Phar extension.
For zip archives, this method fails with an exception. The [zlib](https://www.php.net/manual/en/ref.zlib.php) extension must be enabled to compress with gzip compression, the [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extension must be enabled in order to compress with bzip2 compression.
In addition, this method automatically renames the archive, appending `.gz`, `.bz2` or removing the extension if passed `Phar::NONE` to remove compression. Alternatively, a file extension may be specified with the second parameter.
### Parameters
`compression`
Compression must be one of `Phar::GZ`, `Phar::BZ2` to add compression, or `Phar::NONE` to remove compression.
`extension`
By default, the extension is `.tar.gz` or `.tar.bz2` for compressing a tar, and `.tar` for decompressing.
### Return Values
A [PharData](class.phardata) object is returned on success, or **`null`** on failure.
### Errors/Exceptions
Throws [BadMethodCallException](class.badmethodcallexception) if the [zlib](https://www.php.net/manual/en/ref.zlib.php) extension is not available, or the [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extension is not enabled.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `extension` is now nullable. |
### Examples
**Example #1 A **PharData::compress()** example**
```
<?php
$p = new PharData('/path/to/my.tar');
$p['myfile.txt'] = 'hi';
$p['myfile2.txt'] = 'hi';
$p1 = $p->compress(Phar::GZ); // copies to /path/to/my.tar.gz
$p2 = $p->compress(Phar::BZ2); // copies to /path/to/my.tar.bz2
$p3 = $p2->compress(Phar::NONE); // exception: /path/to/my.tar already exists
?>
```
### See Also
* [Phar::compress()](phar.compress) - Compresses the entire Phar archive using Gzip or Bzip2 compression
php QuickHashStringIntHash::get QuickHashStringIntHash::get
===========================
(No version information available, might only be in Git)
QuickHashStringIntHash::get — This method retrieves a value from the hash by its key
### Description
```
public QuickHashStringIntHash::get(string $key): mixed
```
This method retrieves a value from the hash by its key.
### Parameters
`key`
The key of the entry to retrieve.
### Return Values
The value if the key exists, or **`null`** if the key wasn't part of the hash.
### Examples
**Example #1 **QuickHashStringIntHash::get()** example**
```
<?php
$hash = new QuickHashStringIntHash( 8 );
var_dump( $hash->get( "one" ) );
var_dump( $hash->add( "two", 2 ) );
var_dump( $hash->get( "two" ) );
?>
```
The above example will output something similar to:
```
bool(false)
bool(true)
int(2)
```
php IntlChar::charDirection IntlChar::charDirection
=======================
(PHP 7, PHP 8)
IntlChar::charDirection — Get bidirectional category value for a code point
### Description
```
public static IntlChar::charDirection(int|string $codepoint): ?int
```
Returns the bidirectional category value for the code point, which is used in the [» Unicode bidirectional algorithm (UAX #9)](http://www.unicode.org/reports/tr9/).
>
> **Note**:
>
>
> Some unassigned code points have bidi values of R or AL because they are in blocks that are reserved for Right-To-Left scripts.
>
>
### Parameters
`codepoint`
The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)
### Return Values
The bidirectional category value; one of the following constants:
* **`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT`**
* **`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT`**
* **`IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER`**
* **`IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR`**
* **`IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_TERMINATOR`**
* **`IntlChar::CHAR_DIRECTION_ARABIC_NUMBER`**
* **`IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR`**
* **`IntlChar::CHAR_DIRECTION_BLOCK_SEPARATOR`**
* **`IntlChar::CHAR_DIRECTION_SEGMENT_SEPARATOR`**
* **`IntlChar::CHAR_DIRECTION_WHITE_SPACE_NEUTRAL`**
* **`IntlChar::CHAR_DIRECTION_OTHER_NEUTRAL`**
* **`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_EMBEDDING`**
* **`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_OVERRIDE`**
* **`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ARABIC`**
* **`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_EMBEDDING`**
* **`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_OVERRIDE`**
* **`IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_FORMAT`**
* **`IntlChar::CHAR_DIRECTION_DIR_NON_SPACING_MARK`**
* **`IntlChar::CHAR_DIRECTION_BOUNDARY_NEUTRAL`**
* **`IntlChar::CHAR_DIRECTION_FIRST_STRONG_ISOLATE`**
* **`IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT_ISOLATE`**
* **`IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT_ISOLATE`**
* **`IntlChar::CHAR_DIRECTION_POP_DIRECTIONAL_ISOLATE`**
* **`IntlChar::CHAR_DIRECTION_CHAR_DIRECTION_COUNT`**
Returns **`null`** on failure. ### Examples
**Example #1 Testing different code points**
```
<?php
var_dump(IntlChar::charDirection("A") === IntlChar::CHAR_DIRECTION_LEFT_TO_RIGHT);
var_dump(IntlChar::charDirection("\u{05E9}") === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT);
var_dump(IntlChar::charDirection("+") === IntlChar::CHAR_DIRECTION_EUROPEAN_NUMBER_SEPARATOR);
var_dump(IntlChar::charDirection(".") === IntlChar::CHAR_DIRECTION_COMMON_NUMBER_SEPARATOR);
?>
```
The above example will output:
```
bool(true)
bool(true)
bool(true)
bool(true)
```
php stats_cdf_normal stats\_cdf\_normal
==================
(PECL stats >= 1.0.0)
stats\_cdf\_normal — Calculates any one parameter of the normal distribution given values for the others
### Description
```
stats_cdf_normal(
float $par1,
float $par2,
float $par3,
int $which
): float
```
Returns the cumulative distribution function, its inverse, or one of its parameters, of the normal distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.
The following table lists the return value and parameters by `which`. CDF, x, mu, and sigma denotes cumulative distribution function, the value of the random variable, the mean and the standard deviation of the normal distribution, respectively.
**Return value and parameters**| `which` | Return value | `par1` | `par2` | `par3` |
| --- | --- | --- | --- | --- |
| 1 | CDF | x | mu | sigma |
| 2 | x | CDF | mu | sigma |
| 3 | mu | x | CDF | sigma |
| 4 | sigma | x | CDF | mu |
### Parameters
`par1`
The first parameter
`par2`
The second parameter
`par3`
The third parameter
`which`
The flag to determine what to be calculated
### Return Values
Returns CDF, x, mu, or sigma, determined by `which`.
php pg_get_notify pg\_get\_notify
===============
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
pg\_get\_notify — Gets SQL NOTIFY message
### Description
```
pg_get_notify(PgSql\Connection $connection, int $mode = PGSQL_ASSOC): array|false
```
**pg\_get\_notify()** gets notifications generated by a `NOTIFY` SQL command. To receive notifications, the `LISTEN` SQL command must be issued.
### Parameters
`connection`
An [PgSql\Connection](class.pgsql-connection) instance.
`mode`
An optional parameter that controls how the returned array is indexed. `mode` is a constant and can take the following values: **`PGSQL_ASSOC`**, **`PGSQL_NUM`** and **`PGSQL_BOTH`**. Using **`PGSQL_NUM`**, the function will return an array with numerical indices, using **`PGSQL_ASSOC`** it will return only associative indices while **`PGSQL_BOTH`** will return both numerical and associative indices.
### Return Values
An array containing the `NOTIFY` message name and backend PID. If supported by the server, the array also contains the server version and the payload. Otherwise if no `NOTIFY` is waiting, then **`false`** is returned.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 PostgreSQL NOTIFY message**
```
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
// Listen 'author_updated' message from other processes
pg_query($conn, 'LISTEN author_updated;');
$notify = pg_get_notify($conn);
if (!$notify) {
echo "No messages\n";
} else {
print_r($notify);
}
?>
```
### See Also
* [pg\_get\_pid()](function.pg-get-pid) - Gets the backend's process ID
| programming_docs |
php IteratorIterator::__construct IteratorIterator::\_\_construct
===============================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
IteratorIterator::\_\_construct — Create an iterator from anything that is traversable
### Description
public **IteratorIterator::\_\_construct**([Traversable](class.traversable) `$iterator`, ?string `$class` = **`null`**) Creates an iterator from anything that is traversable.
### Parameters
`iterator`
The traversable iterator.
### See Also
* [Traversable](class.traversable)
php stats_cdf_chisquare stats\_cdf\_chisquare
=====================
(PECL stats >= 1.0.0)
stats\_cdf\_chisquare — Calculates any one parameter of the chi-square distribution given values for the others
### Description
```
stats_cdf_chisquare(float $par1, float $par2, int $which): float
```
Returns the cumulative distribution function, its inverse, or one of its parameters, of the chi-square distribution. The kind of the return value and parameters (`par1` and `par2`) are determined by `which`.
The following table lists the return value and parameters by `which`. CDF, x, and k denotes cumulative distribution function, the value of the random variable, and the degree of freedom of the chi-square distribution, respectively.
**Return value and parameters**| `which` | Return value | `par1` | `par2` |
| --- | --- | --- | --- |
| 1 | CDF | x | k |
| 2 | x | CDF | k |
| 3 | k | x | CDF |
### Parameters
`par1`
The first parameter
`par2`
The second parameter
`which`
The flag to determine what to be calculated
### Return Values
Returns CDF, x, or k, determined by `which`.
php geoip_setup_custom_directory geoip\_setup\_custom\_directory
===============================
(PECL geoip >= 1.1.0)
geoip\_setup\_custom\_directory — Set a custom directory for the GeoIP database
### Description
```
geoip_setup_custom_directory(string $path): void
```
The **geoip\_setup\_custom\_directory()** function will change the default directory of the GeoIP database. This is equivalent to changing [geoip.custom\_directory](https://www.php.net/manual/en/geoip.configuration.php#ini.geoip.custom-directory).
### Parameters
`path`
The full path of where the GeoIP database is on disk.
### Return Values
No value is returned.
### Examples
**Example #1 A **geoip\_setup\_custom\_directory()** example**
This will change the GeoIP default database path.
```
<?php
geoip_setup_custom_directory('/some/other/path');
print geoip_db_filename(GEOIP_COUNTRY_EDITION);
?>
```
The above example will output:
```
/some/other/path/GeoIP.dat
```
php Yaf_Request_Http::getRaw Yaf\_Request\_Http::getRaw
==========================
(Yaf >=3.0.7)
Yaf\_Request\_Http::getRaw — Retrieve Raw request body
### Description
```
public Yaf_Request_Http::getRaw(): mixed
```
Retrieve Raw request body
### Parameters
This function has no parameters.
### Return Values
Return string on success, FALSE on failure.
### See Also
* [Yaf\_Request\_Http::get()](yaf-request-http.get) - Retrieve variable from client
* [Yaf\_Request\_Http::getPost()](yaf-request-http.getpost) - Retrieve POST variable
* [Yaf\_Request\_Http::getCookie()](yaf-request-http.getcookie) - Retrieve Cookie variable
* [Yaf\_Request\_Http::getQuery()](yaf-request-http.getquery) - Fetch a query parameter
* [Yaf\_Request\_Abstract::getServer()](yaf-request-abstract.getserver) - Retrieve SERVER variable
* [Yaf\_Request\_Abstract::getParam()](yaf-request-abstract.getparam) - Retrieve calling parameter
php Yaf_Route_Supervar::route Yaf\_Route\_Supervar::route
===========================
(Yaf >=1.0.0)
Yaf\_Route\_Supervar::route — The route purpose
### Description
```
public Yaf_Route_Supervar::route(Yaf_Request_Abstract $request): bool
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`request`
### Return Values
If there is a key(which was defined in [Yaf\_Route\_Supervar::\_\_construct()](yaf-route-supervar.construct)) in $\_GET, return **`true`**. otherwise return **`false`**.
php Imagick::montageImage Imagick::montageImage
=====================
(PECL imagick 2, PECL imagick 3)
Imagick::montageImage — Creates a composite image
### Description
```
public Imagick::montageImage(
ImagickDraw $draw,
string $tile_geometry,
string $thumbnail_geometry,
int $mode,
string $frame
): Imagick
```
Creates a composite image by combining several separate images. The images are tiled on the composite image with the name of the image optionally appearing just below the individual tile.
### Parameters
`draw`
The font name, size, and color are obtained from this object.
`tile_geometry`
The number of tiles per row and page (e.g. 6x4+0+0).
`thumbnail_geometry`
Preferred image size and border size of each thumbnail (e.g. 120x120+4+3).
`mode`
Thumbnail framing mode, see [Montage Mode constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.montagemode).
`frame`
Surround the image with an ornamental border (e.g. 15x15+3+3). The frame color is that of the thumbnail's matte color.
### Return Values
Creates a composite image and returns it as a new [Imagick](class.imagick) object.
php SplFixedArray::toArray SplFixedArray::toArray
======================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplFixedArray::toArray — Returns a PHP array from the fixed array
### Description
```
public SplFixedArray::toArray(): array
```
Returns a PHP array from the fixed array.
### Parameters
This function has no parameters.
### Return Values
Returns a PHP array, similar to the fixed array.
### Examples
**Example #1 **SplFixedArray::toArray()** example**
```
<?php
$fa = new SplFixedArray(3);
$fa[0] = 0;
$fa[2] = 2;
var_dump($fa->toArray());
?>
```
The above example will output:
```
array(3) {
[0]=>
int(0)
[1]=>
NULL
[2]=>
int(2)
}
```
php wincache_ucache_dec wincache\_ucache\_dec
=====================
(PECL wincache >= 1.1.0)
wincache\_ucache\_dec — Decrements the value associated with the key
### Description
```
wincache_ucache_dec(string $key, int $dec_by = 1, bool &$success = ?): mixed
```
Decrements the value associated with the `key` by 1 or as specified by `dec_by`.
### Parameters
`key`
The `key` that was used to store the variable in the cache. `key` is case sensitive.
`dec_by`
The value by which the variable associated with the `key` will get decremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the `key` should be of type `long`, otherwise the function fails and returns **`false`**.
`success`
Will be set to **`true`** on success and **`false`** on failure.
### Return Values
Returns the decremented value on success and **`false`** on failure.
### Examples
**Example #1 Using **wincache\_ucache\_dec()****
```
<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_dec('counter', 2923, $success));
var_dump($success);
?>
```
The above example will output:
```
int(2922)
bool(true)
```
### See Also
* [wincache\_ucache\_inc()](function.wincache-ucache-inc) - Increments the value associated with the key
* [wincache\_ucache\_cas()](function.wincache-ucache-cas) - Compares the variable with old value and assigns new value to it
php XMLWriter::startElementNs XMLWriter::startElementNs
=========================
xmlwriter\_start\_element\_ns
=============================
(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0)
XMLWriter::startElementNs -- xmlwriter\_start\_element\_ns — Create start namespaced element tag
### Description
Object-oriented style
```
public XMLWriter::startElementNs(?string $prefix, string $name, ?string $namespace): bool
```
Procedural style
```
xmlwriter_start_element_ns(
XMLWriter $writer,
?string $prefix,
string $name,
?string $namespace
): bool
```
Starts a namespaced element.
### Parameters
`writer`
Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory).
`prefix`
The namespace prefix. If `prefix` is **`null`**, the namespace will be omitted.
`name`
The element name.
`namespace`
The namespace URI. If `namespace` is **`null`**, the namespace declaration will be omitted.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. |
### See Also
* [XMLWriter::endElement()](xmlwriter.endelement) - End current element
* [XMLWriter::writeElementNs()](xmlwriter.writeelementns) - Write full namespaced element tag
php array_shift array\_shift
============
(PHP 4, PHP 5, PHP 7, PHP 8)
array\_shift — Shift an element off the beginning of array
### Description
```
array_shift(array &$array): mixed
```
**array\_shift()** shifts the first value of the `array` off and returns it, shortening the `array` by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be affected.
> **Note**: This function will [reset()](function.reset) the array pointer of the input array after use.
>
>
### Parameters
`array`
The input array.
### Return Values
Returns the shifted value, or **`null`** if `array` is empty or is not an array.
### Examples
**Example #1 **array\_shift()** example**
```
<?php
$stack = array("orange", "banana", "apple", "raspberry");
$fruit = array_shift($stack);
print_r($stack);
?>
```
The above example will output:
```
Array
(
[0] => banana
[1] => apple
[2] => raspberry
)
```
and `orange` will be assigned to $fruit.
### See Also
* [array\_unshift()](function.array-unshift) - Prepend one or more elements to the beginning of an array
* [array\_push()](function.array-push) - Push one or more elements onto the end of array
* [array\_pop()](function.array-pop) - Pop the element off the end of array
php pspell_add_to_personal pspell\_add\_to\_personal
=========================
(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)
pspell\_add\_to\_personal — Add the word to a personal wordlist
### Description
```
pspell_add_to_personal(PSpell\Dictionary $dictionary, string $word): bool
```
**pspell\_add\_to\_personal()** adds a word to the personal wordlist. If you used [pspell\_new\_config()](function.pspell-new-config) with [pspell\_config\_personal()](function.pspell-config-personal) to open the dictionary, you can save the wordlist later with [pspell\_save\_wordlist()](function.pspell-save-wordlist).
### Parameters
`dictionary`
An [PSpell\Dictionary](class.pspell-dictionary) instance.
`word`
The added word.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `dictionary` parameter expects an [PSpell\Dictionary](class.pspell-dictionary) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **pspell\_add\_to\_personal()****
```
<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);
pspell_add_to_personal($pspell, "Vlad");
pspell_save_wordlist($pspell);
?>
```
### Notes
>
> **Note**:
>
>
> This function will not work unless you have pspell .11.2 and aspell .32.5 or later.
>
>
php RarArchive::open RarArchive::open
================
rar\_open
=========
(PECL rar >= 2.0.0)
RarArchive::open -- rar\_open — Open RAR archive
### Description
Object-oriented style (method):
```
public static RarArchive::open(string $filename, string $password = NULL, callable $volume_callback = NULL): RarArchive|false
```
Procedural style:
```
rar_open(string $filename, string $password = NULL, callable $volume_callback = NULL): RarArchive|false
```
Open specified RAR archive and return [RarArchive](class.rararchive) instance representing it.
>
> **Note**:
>
>
> If opening a multi-volume archive, the path of the first volume should be passed as the first parameter. Otherwise, not all files will be shown. This is by design.
>
>
### Parameters
`filename`
Path to the Rar archive.
`password`
A plain password, if needed to decrypt the headers. It will also be used by default if encrypted files are found. Note that the files may have different passwords in respect to the headers and among them.
`volume_callback`
A function that receives one parameter – the path of the volume that was not found – and returns a string with the correct path for such volume or **`null`** if such volume does not exist or is not known. The programmer should ensure the passed function doesn't cause loops as this function is called repeatedly if the path returned in a previous call did not correspond to the needed volume. Specifying this parameter omits the notice that would otherwise be emitted whenever a volume is not found; an implementation that only returns **`null`** can therefore be used to merely omit such notices.
**Warning** Prior to version 2.0.0, this function would not handle relative paths correctly. Use [realpath()](function.realpath) as a workaround.
### Return Values
Returns the requested [RarArchive](class.rararchive) instance or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| PECL rar 3.0.0 | `volume_callback` was added. |
### Examples
**Example #1 Object-oriented style**
```
<?php
$rar_arch = RarArchive::open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
die("Failed opening file");
$entries = $rar_arch->getEntries();
if ($entries === FALSE)
die("Failed fetching entries");
echo "Found " . count($entries) . " files.\n";
if (empty($entries))
die("No valid entries found.");
$stream = reset($entries)->getStream();
if ($stream === FALSE)
die("Failed opening first file");
$rar_arch->close();
echo "Content of first one follows:\n";
echo stream_get_contents($stream);
fclose($stream);
?>
```
The above example will output something similar to:
```
Found 2 files.
Content of first one follows:
Encrypted file 1 contents.
```
**Example #2 Procedural style**
```
<?php
$rar_arch = rar_open('encrypted_headers.rar', 'samplepassword');
if ($rar_arch === FALSE)
die("Failed opening file");
$entries = rar_list($rar_arch);
if ($entries === FALSE)
die("Failed fetching entries");
echo "Found " . count($entries) . " files.\n";
if (empty($entries))
die("No valid entries found.");
$stream = reset($entries)->getStream();
if ($stream === FALSE)
die("Failed opening first file");
rar_close($rar_arch);
echo "Content of first one follows:\n";
echo stream_get_contents($stream);
fclose($stream);
?>
```
**Example #3 Volume Callback**
```
<?php
/* In this example, there's a volume named multi_broken.part1.rar
* whose next volume is named multi.part2.rar */
function resolve($vol) {
if (preg_match('/_broken/', $vol))
return str_replace('_broken', '', $vol);
else
return null;
}
$rar_file1 = rar_open(dirname(__FILE__).'/multi_broken.part1.rar', null, 'resolve');
$entry = $rar_file1->getEntry('file2.txt');
$entry->extract(null, dirname(__FILE__) . "/temp_file2.txt");
?>
```
### See Also
* [`rar://` wrapper](https://www.php.net/manual/en/wrappers.rar.php)
php IntlDateFormatter::parse IntlDateFormatter::parse
========================
datefmt\_parse
==============
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
IntlDateFormatter::parse -- datefmt\_parse — Parse string to a timestamp value
### Description
Object-oriented style
```
public IntlDateFormatter::parse(string $string, int &$offset = null): int|float|false
```
Procedural style
```
datefmt_parse(IntlDateFormatter $formatter, string $string, int &$offset = null): int|float|false
```
Converts `string` to an incremental time value, starting at `offset` and consuming as much of the input value as possible.
### Parameters
`formatter`
The formatter resource
`string`
string to convert to a time
`offset`
Position at which to start the parsing in `string` (zero-based). If no error occurs before `string` is consumed, `offset` will contain -1 otherwise it will contain the position at which parsing ended (and the error occurred). This variable will contain the end position if the parse fails. If `offset` > `strlen($string)`, the parse fails immediately.
### Return Values
Timestamp of parsed value, or **`false`** if value cannot be parsed.
### Examples
**Example #1 OO example**
```
<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . $fmt->parse('Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = new IntlDateFormatter(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
?>
```
**Example #2 **datefmt\_parse()** example**
```
<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'First parsed output is ' . datefmt_parse($fmt, 'Wednesday, December 20, 1989 4:00:00 PM PT');
$fmt = datefmt_create(
'de-DE',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
echo 'Second parsed output is ' . datefmt_parse($fmt, 'Mittwoch, 20. Dezember 1989 16:00 Uhr GMT-08:00');
?>
```
The above example will output:
```
First parsed output is 630201600
Second parsed output is 630201600
```
### See Also
* [datefmt\_create()](intldateformatter.create) - Create a date formatter
* [datefmt\_format()](intldateformatter.format) - Format the date/time value as a string
* [datefmt\_localtime()](intldateformatter.localtime) - Parse string to a field-based time value
* [datefmt\_get\_error\_code()](intldateformatter.geterrorcode) - Get the error code from last operation
* [datefmt\_get\_error\_message()](intldateformatter.geterrormessage) - Get the error text from the last operation
php curl_share_close curl\_share\_close
==================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
curl\_share\_close — Close a cURL share handle
### Description
```
curl_share_close(CurlShareHandle $share_handle): void
```
>
> **Note**:
>
>
> This function has no effect. Prior to PHP 8.0.0, this function was used to close the resource.
>
>
Closes a cURL share handle and frees all resources.
### Parameters
`share_handle` A cURL share handle returned by [curl\_share\_init()](function.curl-share-init).
### Return Values
No value is returned.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `share_handle` expects a [CurlShareHandle](class.curlsharehandle) instance now; previously, a resource was expected. |
### Examples
**Example #1 [curl\_share\_setopt()](function.curl-share-setopt) example**
This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.
```
<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);
// Execute the first cURL handle
curl_exec($ch1);
// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);
// Execute the second cURL handle
// all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);
// Close the cURL share handle
curl_share_close($sh);
// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>
```
### See Also
* [curl\_share\_init()](function.curl-share-init) - Initialize a cURL share handle
| programming_docs |
php Gmagick::getimagewhitepoint Gmagick::getimagewhitepoint
===========================
(PECL gmagick >= Unknown)
Gmagick::getimagewhitepoint — Returns the chromaticity white point
### Description
```
public Gmagick::getimagewhitepoint(): array
```
Returns the chromaticity white point as an associative array with the keys "x" and "y".
### Parameters
This function has no parameters.
### Return Values
Returns the chromaticity white point as an associative array with the keys "x" and "y".
### Errors/Exceptions
Throws an **GmagickException** on error.
php imagecolorat imagecolorat
============
(PHP 4, PHP 5, PHP 7, PHP 8)
imagecolorat — Get the index of the color of a pixel
### Description
```
imagecolorat(GdImage $image, int $x, int $y): int|false
```
Returns the index of the color of the pixel at the specified location in the image specified by `image`.
If the image is a truecolor image, this function returns the RGB value of that pixel as integer. Use bitshifting and masking to access the distinct red, green and blue component values:
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`x`
x-coordinate of the point.
`y`
y-coordinate of the point.
### Return Values
Returns the index of the color or **`false`** on failure.
**Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
### Examples
**Example #1 Access distinct RGB values**
```
<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
var_dump($r, $g, $b);
?>
```
The above example will output something similar to:
```
int(119)
int(123)
int(180)
```
**Example #2 Human-readable RGB values using [imagecolorsforindex()](function.imagecolorsforindex)**
```
<?php
$im = imagecreatefrompng("php.png");
$rgb = imagecolorat($im, 10, 15);
$colors = imagecolorsforindex($im, $rgb);
var_dump($colors);
?>
```
The above example will output something similar to:
```
array(4) {
["red"]=>
int(119)
["green"]=>
int(123)
["blue"]=>
int(180)
["alpha"]=>
int(127)
}
```
### See Also
* [imagecolorset()](function.imagecolorset) - Set the color for the specified palette index
* [imagecolorsforindex()](function.imagecolorsforindex) - Get the colors for an index
* [imagesetpixel()](function.imagesetpixel) - Set a single pixel
php ImagickDraw::point ImagickDraw::point
==================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::point — Draws a point
### Description
```
public ImagickDraw::point(float $x, float $y): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Draws a point using the current stroke color and stroke thickness at the specified coordinates.
### Parameters
`x`
point's x coordinate
`y`
point's y coordinate
### Return Values
No value is returned.
### Examples
**Example #1 **ImagickDraw::point()** example**
```
<?php
function point($fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setFillColor($fillColor);
for ($x = 0; $x < 10000; $x++) {
$draw->point(rand(0, 500), rand(0, 500));
}
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>
```
php Thread::join Thread::join
============
(PECL pthreads >= 2.0.0)
Thread::join — Synchronization
### Description
```
public Thread::join(): bool
```
Causes the calling context to wait for the referenced Thread to finish executing
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Join with the referenced Thread**
```
<?php
class My extends Thread {
public function run() {
/* ... */
}
}
$my = new My();
$my->start();
/* ... */
var_dump($my->join());
/* ... */
?>
```
The above example will output:
```
bool(true)
```
php Imagick::setImageDepth Imagick::setImageDepth
======================
(PECL imagick 2, PECL imagick 3)
Imagick::setImageDepth — Sets the image depth
### Description
```
public Imagick::setImageDepth(int $depth): bool
```
Sets the image depth.
### Parameters
`depth`
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
php date_offset_get date\_offset\_get
=================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
date\_offset\_get — Alias of [DateTime::getOffset()](datetime.getoffset)
### Description
This function is an alias of: [DateTime::getOffset()](datetime.getoffset)
php GmagickDraw::gettextencoding GmagickDraw::gettextencoding
============================
(PECL gmagick >= Unknown)
GmagickDraw::gettextencoding — Returns the code set used for text annotations
### Description
```
public GmagickDraw::gettextencoding(): mixed
```
Returns a string which specifies the code set used for text annotations.
### Parameters
This function has no parameters.
### Return Values
Returns a string specifying the code set or **`false`** if text encoding is not set.
php Gmagick::setimageresolution Gmagick::setimageresolution
===========================
(PECL gmagick >= Unknown)
Gmagick::setimageresolution — Sets the image resolution
### Description
```
public Gmagick::setimageresolution(float $xResolution, float $yResolution): Gmagick
```
Sets the image resolution.
### Parameters
`xResolution`
The image x resolution.
`yResolution`
The image y resolution.
### Return Values
The Gmagick object on success.
### Errors/Exceptions
Throws an **GmagickException** on error.
php IntlCalendar::getActualMaximum IntlCalendar::getActualMaximum
==============================
(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)
IntlCalendar::getActualMaximum — The maximum value for a field, considering the objectʼs current time
### Description
Object-oriented style
```
public IntlCalendar::getActualMaximum(int $field): int|false
```
Procedural style
```
intlcal_get_actual_maximum(IntlCalendar $calendar, int $field): int|false
```
Returns a fieldʼs relative maximum value around the current time. The exact semantics vary by field, but in the general case this is the value that would be obtained if one would set the field value into the [smallest relative maximum](intlcalendar.getleastmaximum) for the field and would increment it until reaching the [global maximum](intlcalendar.getmaximum) or the field value wraps around, in which the value returned would be the global maximum or the value before the wrapping, respectively.
For instance, in the gregorian calendar, the actual maximum value for the [day of month](class.intlcalendar#intlcalendar.constants.field-day-of-month) would vary between `28` and `31`, depending on the month and year of the current time.
### Parameters
`calendar`
An [IntlCalendar](class.intlcalendar) instance.
`field`
One of the [IntlCalendar](class.intlcalendar) date/time [field constants](class.intlcalendar#intlcalendar.constants). These are integer values between `0` and **`IntlCalendar::FIELD_COUNT`**.
### Return Values
An int representing the maximum value in the units associated with the given `field` or **`false`** on failure.
### Examples
**Example #1 **IntlCalendar::getActualMaximum()****
```
<?php
ini_set('date.timezone', 'Europe/Lisbon');
$cal = IntlCalendar::fromDateTime('2013-02-15');
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //28
$cal->add(IntlCalendar::FIELD_EXTENDED_YEAR, -1);
var_dump($cal->getActualMaximum(IntlCalendar::FIELD_DAY_OF_MONTH)); //29
```
The above example will output:
```
int(28)
int(29)
```
### See Also
* [IntlCalendar::getMaximum()](intlcalendar.getmaximum) - Get the global maximum value for a field
* [IntlCalendar::getLeastMaximum()](intlcalendar.getleastmaximum) - Get the smallest local maximum for a field
* [IntlCalendar::getActualMinimum()](intlcalendar.getactualminimum) - The minimum value for a field, considering the objectʼs current time
php SimpleXMLElement::addAttribute SimpleXMLElement::addAttribute
==============================
(PHP 5 >= 5.1.3, PHP 7, PHP 8)
SimpleXMLElement::addAttribute — Adds an attribute to the SimpleXML element
### Description
```
public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
```
Adds an attribute to the SimpleXML element.
### Parameters
`qualifiedName`
The name of the attribute to add.
`value`
The value of the attribute.
`namespace`
If specified, the namespace to which the attribute belongs.
### Return Values
No value is returned.
### Examples
>
> **Note**:
>
>
> Listed examples may include `example.php`, which refers to the XML string found in the first example of the [basic usage](https://www.php.net/manual/en/simplexml.examples-basic.php) guide.
>
>
**Example #1 Add attributes and children to a SimpleXML element**
```
<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);
$sxe->addAttribute('type', 'documentary');
$movie = $sxe->addChild('movie');
$movie->addChild('title', 'PHP2: More Parser Stories');
$movie->addChild('plot', 'This is all about the people who make it work.');
$characters = $movie->addChild('characters');
$character = $characters->addChild('character');
$character->addChild('name', 'Mr. Parser');
$character->addChild('actor', 'John Doe');
$rating = $movie->addChild('rating', '5');
$rating->addAttribute('type', 'stars');
echo $sxe->asXML();
?>
```
The above example will output something similar to:
```
<?xml version="1.0" standalone="yes"?>
<movies type="documentary">
<movie>
<title>PHP: Behind the Parser</title>
<characters>
<character>
<name>Ms. Coder</name>
<actor>Onlivia Actora</actor>
</character>
<character>
<name>Mr. Coder</name>
<actor>El ActÓr</actor>
</character>
</characters>
<plot>
So, this language. It's like, a programming language. Or is it a
scripting language? All is revealed in this thrilling horror spoof
of a documentary.
</plot>
<great-lines>
<line>PHP solves all my web problems</line>
</great-lines>
<rating type="thumbs">7</rating>
<rating type="stars">5</rating>
</movie>
<movie>
<title>PHP2: More Parser Stories</title>
<plot>This is all about the people who make it work.</plot>
<characters>
<character>
<name>Mr. Parser</name>
<actor>John Doe</actor>
</character>
</characters>
<rating type="stars">5</rating>
</movie>
</movies>
```
### See Also
* [SimpleXMLElement::addChild()](simplexmlelement.addchild) - Adds a child element to the XML node
* [Basic SimpleXML usage](https://www.php.net/manual/en/simplexml.examples-basic.php)
php Parle\RLexer::pushState Parle\RLexer::pushState
=======================
(PECL parle >= 0.5.1)
Parle\RLexer::pushState — Push a new start state
### Description
```
public Parle\RLexer::pushState(string $state): int
```
This lexer type can have more than one state machine. This allows you to lex different tokens depending on context, thus allowing simple parsing to take place. Once a state pushed, it can be used with a suitable [Parle\RLexer::push()](parle-rlexer.push) signature variant.
### Parameters
`state`
Name of the state.
### Return Values
php fbird_num_fields fbird\_num\_fields
==================
(PHP 5, PHP 7 < 7.4.0)
fbird\_num\_fields — Alias of [ibase\_num\_fields()](function.ibase-num-fields)
### Description
This function is an alias of: [ibase\_num\_fields()](function.ibase-num-fields).
### See Also
* [fbird\_field\_info()](function.fbird-field-info) - Alias of ibase\_field\_info
php Ds\Pair::__construct Ds\Pair::\_\_construct
======================
(PECL ds >= 1.0.0)
Ds\Pair::\_\_construct — Creates a new instance
### Description
public **Ds\Pair::\_\_construct**([mixed](language.types.declarations#language.types.declarations.mixed) `$key` = ?, [mixed](language.types.declarations#language.types.declarations.mixed) `$value` = ?) Creates a new instance using a given `key` and `value`.
### Parameters
`key`
The key.
`value`
The value.
php Imagick::getImageProperty Imagick::getImageProperty
=========================
(PECL imagick 2, PECL imagick 3)
Imagick::getImageProperty — Returns the named image property
### Description
```
public Imagick::getImageProperty(string $name): string
```
Returns the named image property. This method is available if Imagick has been compiled against ImageMagick version 6.3.2 or newer.
### Parameters
`name`
name of the property (for example Exif:DateTime)
### Return Values
Returns a string containing the image property, false if a property with the given name does not exist.
### Examples
**Example #1 Using **Imagick::getImageProperty()**:**
Setting and getting image property
```
<?php
$image = new Imagick();
$image->newImage(300, 200, "black");
$image->setImageProperty('Exif:Make', 'Imagick');
echo $image->getImageProperty('Exif:Make');
?>
```
### See Also
* [Imagick::setImageProperty()](imagick.setimageproperty) - Sets an image property
php Imagick::getNumberImages Imagick::getNumberImages
========================
(PECL imagick 2, PECL imagick 3)
Imagick::getNumberImages — Returns the number of images in the object
### Description
```
public Imagick::getNumberImages(): int
```
Returns the number of images associated with Imagick object.
### Parameters
This function has no parameters.
### Return Values
Returns the number of images associated with Imagick object.
### Errors/Exceptions
Throws ImagickException on error.
php streamWrapper::stream_cast streamWrapper::stream\_cast
===========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
streamWrapper::stream\_cast — Retrieve the underlaying resource
### Description
```
public streamWrapper::stream_cast(int $cast_as): resource
```
This method is called in response to [stream\_select()](function.stream-select).
### Parameters
`cast_as`
Can be **`STREAM_CAST_FOR_SELECT`** when [stream\_select()](function.stream-select) is calling **stream\_cast()** or **`STREAM_CAST_AS_STREAM`** when **stream\_cast()** is called for other uses.
### Return Values
Should return the underlying stream resource used by the wrapper, or **`false`**.
### See Also
* [stream\_select()](function.stream-select) - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
php The Parle\LexerException class
The Parle\LexerException class
==============================
Introduction
------------
(PECL parle >= 0.5.1)
Class synopsis
--------------
class **Parle\LexerException** extends [Exception](class.exception) implements [Throwable](class.throwable) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = "";
private string [$string](class.exception#exception.props.string) = "";
protected int [$code](class.exception#exception.props.code);
protected string [$file](class.exception#exception.props.file) = "";
protected int [$line](class.exception#exception.props.line);
private array [$trace](class.exception#exception.props.trace) = [];
private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Methods \*/ /\* Inherited methods \*/
```
final public Exception::getMessage(): string
```
```
final public Exception::getPrevious(): ?Throwable
```
```
final public Exception::getCode(): int
```
```
final public Exception::getFile(): string
```
```
final public Exception::getLine(): int
```
```
final public Exception::getTrace(): array
```
```
final public Exception::getTraceAsString(): string
```
```
public Exception::__toString(): string
```
```
private Exception::__clone(): void
```
}
php The CurlHandle class
The CurlHandle class
====================
Introduction
------------
(PHP 8)
A fully opaque class which replaces `curl` resources as of PHP 8.0.0.
Class synopsis
--------------
final class **CurlHandle** { }
php Yaf_View_Interface::display Yaf\_View\_Interface::display
=============================
(Yaf >=1.0.0)
Yaf\_View\_Interface::display — Render and output a template
### Description
```
abstract public Yaf_View_Interface::display(string $tpl, array $tpl_vars = ?): bool
```
Render a template and output the result immediately.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`tpl`
`tpl_vars`
### Return Values
php VarnishAdmin::connect VarnishAdmin::connect
=====================
(PECL varnish >= 0.3)
VarnishAdmin::connect — Connect to a varnish instance administration interface
### Description
```
public VarnishAdmin::connect(): bool
```
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
php The DOMCharacterData class
The DOMCharacterData class
==========================
Introduction
------------
(PHP 5, PHP 7, PHP 8)
Represents nodes with character data. No nodes directly correspond to this class, but other nodes do inherit from it.
Class synopsis
--------------
class **DOMCharacterData** extends [DOMNode](class.domnode) implements [DOMChildNode](class.domchildnode) { /\* Properties \*/ public string [$data](class.domcharacterdata#domcharacterdata.props.data);
public readonly int [$length](class.domcharacterdata#domcharacterdata.props.length);
public readonly ?[DOMElement](class.domelement) [$previousElementSibling](class.domcharacterdata#domcharacterdata.props.previouselementsibling);
public readonly ?[DOMElement](class.domelement) [$nextElementSibling](class.domcharacterdata#domcharacterdata.props.nextelementsibling); /\* Inherited properties \*/
public readonly string [$nodeName](class.domnode#domnode.props.nodename);
public ?string [$nodeValue](class.domnode#domnode.props.nodevalue);
public readonly int [$nodeType](class.domnode#domnode.props.nodetype);
public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode);
public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes);
public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild);
public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild);
public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling);
public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling);
public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes);
public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument);
public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri);
public string [$prefix](class.domnode#domnode.props.prefix);
public readonly ?string [$localName](class.domnode#domnode.props.localname);
public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri);
public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/
```
public appendData(string $data): bool
```
```
public deleteData(int $offset, int $count): bool
```
```
public insertData(int $offset, string $data): bool
```
```
public replaceData(int $offset, int $count, string $data): bool
```
```
public substringData(int $offset, int $count): string|false
```
/\* Inherited methods \*/
```
public DOMNode::appendChild(DOMNode $node): DOMNode|false
```
```
public DOMNode::C14N(
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): string|false
```
```
public DOMNode::C14NFile(
string $uri,
bool $exclusive = false,
bool $withComments = false,
?array $xpath = null,
?array $nsPrefixes = null
): int|false
```
```
public DOMNode::cloneNode(bool $deep = false): DOMNode|false
```
```
public DOMNode::getLineNo(): int
```
```
public DOMNode::getNodePath(): ?string
```
```
public DOMNode::hasAttributes(): bool
```
```
public DOMNode::hasChildNodes(): bool
```
```
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
```
```
public DOMNode::isDefaultNamespace(string $namespace): bool
```
```
public DOMNode::isSameNode(DOMNode $otherNode): bool
```
```
public DOMNode::isSupported(string $feature, string $version): bool
```
```
public DOMNode::lookupNamespaceUri(string $prefix): string
```
```
public DOMNode::lookupPrefix(string $namespace): ?string
```
```
public DOMNode::normalize(): void
```
```
public DOMNode::removeChild(DOMNode $child): DOMNode|false
```
```
public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false
```
} Properties
----------
data The contents of the node.
length The length of the contents.
nextElementSibling The next sibling element or **`null`**.
previousElementSibling The previous sibling element or **`null`**.
Changelog
---------
| Version | Description |
| --- | --- |
| 8.0.0 | The nextElementSibling and previousElementSibling properties have been added. |
| 8.0.0 | **DOMCharacterData** implements [DOMChildNode](class.domchildnode) now. |
See Also
--------
* [» W3C specification of CharacterData](http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-FF21A306)
Table of Contents
-----------------
* [DOMCharacterData::appendData](domcharacterdata.appenddata) — Append the string to the end of the character data of the node
* [DOMCharacterData::deleteData](domcharacterdata.deletedata) — Remove a range of characters from the node
* [DOMCharacterData::insertData](domcharacterdata.insertdata) — Insert a string at the specified 16-bit unit offset
* [DOMCharacterData::replaceData](domcharacterdata.replacedata) — Replace a substring within the DOMCharacterData node
* [DOMCharacterData::substringData](domcharacterdata.substringdata) — Extracts a range of data from the node
| programming_docs |
php IntlChar::isJavaSpaceChar IntlChar::isJavaSpaceChar
=========================
(PHP 7, PHP 8)
IntlChar::isJavaSpaceChar — Check if code point is a space character according to Java
### Description
```
public static IntlChar::isJavaSpaceChar(int|string $codepoint): ?bool
```
Determine if the specified code point is a space character according to Java.
**`true`** for characters with general categories "Z" (separators), which does not include control codes (e.g., TAB or Line Feed).
### Parameters
`codepoint`
The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)
### Return Values
Returns **`true`** if `codepoint` is a space character according to Java, **`false`** if not. Returns **`null`** on failure.
### Examples
**Example #1 Testing different code points**
```
<?php
var_dump(IntlChar::isJavaSpaceChar("A"));
var_dump(IntlChar::isJavaSpaceChar(" "));
var_dump(IntlChar::isJavaSpaceChar("\n"));
var_dump(IntlChar::isJavaSpaceChar("\t"));
var_dump(IntlChar::isJavaSpaceChar("\u{00A0}"));
?>
```
The above example will output:
```
bool(false)
bool(true)
bool(false)
bool(false)
bool(true)
```
### See Also
* [IntlChar::isspace()](intlchar.isspace) - Check if code point is a space character
* [IntlChar::isWhitespace()](intlchar.iswhitespace) - Check if code point is a whitespace character according to ICU
* [IntlChar::isUWhiteSpace()](intlchar.isuwhitespace) - Check if code point has the White\_Space Unicode property
php stats_stat_paired_t stats\_stat\_paired\_t
======================
(PECL stats >= 1.0.0)
stats\_stat\_paired\_t — Returns the t-value of the dependent t-test for paired samples
### Description
```
stats_stat_paired_t(array $arr1, array $arr2): float
```
Returns the t-value of the dependent t-test for paired samples `arr1` and `arr2`.
### Parameters
`arr1`
The first samples
`arr2`
The second samples
### Return Values
Returns the t-value, or **`false`** if failure.
php sodium_crypto_aead_aes256gcm_is_available sodium\_crypto\_aead\_aes256gcm\_is\_available
==============================================
(PHP 7 >= 7.2.0, PHP 8)
sodium\_crypto\_aead\_aes256gcm\_is\_available — Check if hardware supports AES256-GCM
### Description
```
sodium_crypto_aead_aes256gcm_is_available(): bool
```
The return value of this function depends on whether or not the hardware supports hardware-accelerated AES.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if it is safe to encrypt with AES-256-GCM, and **`false`** otherwise.
php PharData::decompress PharData::decompress
====================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)
PharData::decompress — Decompresses the entire Phar archive
### Description
```
public PharData::decompress(?string $extension = null): ?PharData
```
For tar-based archives, this method decompresses the entire archive.
For Zip-based archives, this method fails with an exception. The [zlib](https://www.php.net/manual/en/ref.zlib.php) extension must be enabled to decompress an archive compressed with gzip compression, and the [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extension must be enabled in order to decompress an archive compressed with bzip2 compression.
In addition, this method automatically renames the file extension of the archive, `.tar` by default. Alternatively, a file extension may be specified with the `extension` parameter.
### Parameters
`extension`
For decompressing, the default file extension is `.tar`. Use this parameter to specify another file extension. Be aware that only executable archives can contain `.phar` in their filename.
### Return Values
A [PharData](class.phardata) object is returned on success, or **`null`** on failure.
### Errors/Exceptions
Throws [BadMethodCallException](class.badmethodcallexception) if the [zlib](https://www.php.net/manual/en/ref.zlib.php) extension is not available, or the [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extension is not enabled.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `extension` is now nullable. |
### Examples
**Example #1 A **PharData::decompress()** example**
```
<?php
$p = new PharData('/path/to/my.tar.gz');
$p->decompress(); // creates /path/to/my.tar
?>
```
### See Also
* [PharFileInfo::getCompressedSize()](pharfileinfo.getcompressedsize) - Returns the actual size of the file (with compression) inside the Phar archive
* [PharFileInfo::isCompressed()](pharfileinfo.iscompressed) - Returns whether the entry is compressed
* [PharFileInfo::compress()](pharfileinfo.compress) - Compresses the current Phar entry with either zlib or bzip2 compression
* [PharFileInfo::decompress()](pharfileinfo.decompress) - Decompresses the current Phar entry within the phar
* [PharData::compress()](phardata.compress) - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
* [Phar::canCompress()](phar.cancompress) - Returns whether phar extension supports compression using either zlib or bzip2
* [Phar::isCompressed()](phar.iscompressed) - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on)
* [PharData::compress()](phardata.compress) - Compresses the entire tar/zip archive using Gzip or Bzip2 compression
* [Phar::getSupportedCompression()](phar.getsupportedcompression) - Return array of supported compression algorithms
* [PharData::compressFiles()](phardata.compressfiles) - Compresses all files in the current tar/zip archive
* [PharData::decompressFiles()](phardata.decompressfiles) - Decompresses all files in the current zip archive
php Ds\Map::reduce Ds\Map::reduce
==============
(PECL ds >= 1.0.0)
Ds\Map::reduce — Reduces the map to a single value using a callback function
### Description
```
public Ds\Map::reduce(callable $callback, mixed $initial = ?): mixed
```
Reduces the map to a single value using a callback function.
### Parameters
`callback`
```
callback(mixed $carry, mixed $key, mixed $value): mixed
```
`carry`
The return value of the previous callback, or `initial` if it's the first iteration.
`key`
The key of the current iteration.
`value`
The value of the current iteration.
`initial`
The initial value of the carry value. Can be **`null`**.
### Return Values
The return value of the final callback.
### Examples
**Example #1 **Ds\Map::reduce()** with initial value example**
```
<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
$callback = function($carry, $key, $value) {
return $carry * $value;
};
var_dump($map->reduce($callback, 5));
// Iterations:
//
// $carry = $initial = 5
//
// $carry = $carry * 1 = 5
// $carry = $carry * 2 = 10
// $carry = $carry * 3 = 30
?>
```
The above example will output something similar to:
```
int(30)
```
**Example #2 **Ds\Map::reduce()** without an initial value example**
```
<?php
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map->reduce(function($carry, $key, $value) {
return $carry + $value + 5;
}));
// Iterations:
//
// $carry = $initial = null
//
// $carry = $carry + 1 + 5 = 6
// $carry = $carry + 2 + 5 = 13
// $carry = $carry + 3 + 5 = 21
?>
```
The above example will output something similar to:
```
int(21)
```
php ImagickDraw::getClipRule ImagickDraw::getClipRule
========================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::getClipRule — Returns the current polygon fill rule
### Description
```
public ImagickDraw::getClipRule(): int
```
**Warning**This function is currently not documented; only its argument list is available.
Returns the current polygon fill rule to be used by the clipping path.
### Return Values
Returns a [FILLRULE](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.fillrule) constant (`imagick::FILLRULE_*`).
php EventBuffer::readFrom EventBuffer::readFrom
=====================
(PECL event >= 1.7.0)
EventBuffer::readFrom — Read data from a file onto the end of the buffer
### Description
```
public EventBuffer::read( mixed $fd , int $howmuch ): int
```
Read data from the file specified by `fd` onto the end of the buffer.
### Parameters
`fd` Socket resource, stream, or numeric file descriptor.
`howmuch` Maxmimum number of bytes to read.
### Return Values
Returns the number of bytes read, or **`false`** on failure.
### See Also
* [EventBuffer::copyout()](eventbuffer.copyout) - Copies out specified number of bytes from the front of the buffer
* [EventBuffer::drain()](eventbuffer.drain) - Removes specified number of bytes from the front of the buffer without copying it anywhere
* [EventBuffer::pullup()](eventbuffer.pullup) - Linearizes data within buffer and returns it's contents as a string
* [EventBuffer::readLine()](eventbuffer.readline) - Extracts a line from the front of the buffer
* [EventBuffer::appendFrom()](eventbuffer.appendfrom) - Moves the specified number of bytes from a source buffer to the end of the current buffer
php ImagickDraw::popClipPath ImagickDraw::popClipPath
========================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::popClipPath — Terminates a clip path definition
### Description
```
public ImagickDraw::popClipPath(): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Terminates a clip path definition.
### Return Values
No value is returned.
php GearmanTask::functionName GearmanTask::functionName
=========================
(PECL gearman >= 0.6.0)
GearmanTask::functionName — Get associated function name
### Description
```
public GearmanTask::functionName(): string
```
Returns the name of the function this task is associated with, i.e., the function the Gearman worker calls.
### Parameters
This function has no parameters.
### Return Values
A function name.
php svn_fs_props_changed svn\_fs\_props\_changed
=======================
(PECL svn >= 0.2.0)
svn\_fs\_props\_changed — Return true if props are different, false otherwise
### Description
```
svn_fs_props_changed(
resource $root1,
string $path1,
resource $root2,
string $path2
): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Return true if props are different, false otherwise
### Notes
**Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
php ReflectionFunctionAbstract::isClosure ReflectionFunctionAbstract::isClosure
=====================================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
ReflectionFunctionAbstract::isClosure — Checks if closure
### Description
```
public ReflectionFunctionAbstract::isClosure(): bool
```
Checks whether the reflected function is a [Closure](class.closure).
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if the function is a [Closure](class.closure), otherwise **`false`**.
### Examples
**Example #1 **ReflectionFunctionAbstract::isClosure()** example**
```
<?php
// Non-closure
$function1 = 'str_replace';
$reflection1 = new ReflectionFunction($function1);
var_dump($reflection1->isClosure());
// Closure
$function2 = function () {};
$reflection2 = new ReflectionFunction($function2);
var_dump($reflection2->isClosure());
?>
```
The above example will output:
```
bool(false)
bool(true)
```
### See Also
* [ReflectionFunctionAbstract::isGenerator()](reflectionfunctionabstract.isgenerator) - Returns whether this function is a generator
php mysqli::escape_string mysqli::escape\_string
======================
mysqli\_escape\_string
======================
(PHP 5, PHP 7, PHP 8)
mysqli::escape\_string -- mysqli\_escape\_string — Alias of [mysqli\_real\_escape\_string()](mysqli.real-escape-string)
### Description
This function is an alias of: [mysqli\_real\_escape\_string()](mysqli.real-escape-string).
php FiberError::__construct FiberError::\_\_construct
=========================
(PHP 8 >= 8.1.0)
FiberError::\_\_construct — Constructor to disallow direct instantiation
### Description
public **FiberError::\_\_construct**() ### Parameters
This function has no parameters.
### Errors/Exceptions
Throws an [Error](class.error) exception when called.
php Yaf_Controller_Abstract::__construct Yaf\_Controller\_Abstract::\_\_construct
========================================
(Yaf >=1.0.0)
Yaf\_Controller\_Abstract::\_\_construct — Yaf\_Controller\_Abstract constructor
### Description
final private **Yaf\_Controller\_Abstract::\_\_construct**() **Yaf\_Controller\_Abstract::\_\_construct()** is final, which means it can not be overridden. You may want to see [Yaf\_Controller\_Abstract::init()](yaf-controller-abstract.init) instead.
### Parameters
This function has no parameters.
### Return Values
### See Also
* [Yaf\_Controller\_Abstract::init()](yaf-controller-abstract.init) - Controller initializer
php Stomp::begin Stomp::begin
============
stomp\_begin
============
(PECL stomp >= 0.1.0)
Stomp::begin -- stomp\_begin — Starts a transaction
### Description
Object-oriented style (method):
```
public Stomp::begin(string $transaction_id, array $headers = ?): bool
```
Procedural style:
```
stomp_begin(resource $link, string $transaction_id, array $headers = ?): bool
```
Starts a transaction.
### Parameters
`link`
Procedural style only: The stomp link identifier returned by [stomp\_connect()](stomp.construct).
`transaction_id`
The transaction id.
`headers`
Associative array containing the additional headers (example: receipt).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
See [stomp\_commit()](stomp.commit) or [stomp\_abort()](stomp.abort).
### Notes
**Tip**Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached.
php gmp_com gmp\_com
========
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
gmp\_com — Calculates one's complement
### Description
```
gmp_com(GMP|int|string $num): GMP
```
Returns the one's complement of `num`.
### Parameters
`num`
A [GMP](class.gmp) object, an int or a numeric string.
### Return Values
Returns the one's complement of `num`, as a GMP number.
### Examples
**Example #1 **gmp\_com()** example**
```
<?php
$com = gmp_com("1234");
echo gmp_strval($com) . "\n";
?>
```
The above example will output:
```
-1235
```
php md5 md5
===
(PHP 4, PHP 5, PHP 7, PHP 8)
md5 — Calculate the md5 hash of a string
**Warning** It is not recommended to use this function to secure passwords, due to the fast nature of this hashing algorithm. See the [Password Hashing FAQ](https://www.php.net/manual/en/faq.passwords.php#faq.passwords.fasthash) for details and best practices.
### Description
```
md5(string $string, bool $binary = false): string
```
Calculates the MD5 hash of `string` using the [» RSA Data Security, Inc. MD5 Message-Digest Algorithm](http://www.faqs.org/rfcs/rfc1321), and returns that hash.
### Parameters
`string`
The string.
`binary`
If the optional `binary` is set to **`true`**, then the md5 digest is instead returned in raw binary format with a length of 16.
### Return Values
Returns the hash as a 32-character hexadecimal number.
### Examples
**Example #1 A **md5()** example**
```
<?php
$str = 'apple';
if (md5($str) === '1f3870be274f6c49b3e31a0c6728957f') {
echo "Would you like a green or red apple?";
}
?>
```
### See Also
* [md5\_file()](function.md5-file) - Calculates the md5 hash of a given file
* [sha1\_file()](function.sha1-file) - Calculate the sha1 hash of a file
* [crc32()](function.crc32) - Calculates the crc32 polynomial of a string
* [sha1()](function.sha1) - Calculate the sha1 hash of a string
* [hash()](function.hash) - Generate a hash value (message digest)
* [crypt()](function.crypt) - One-way string hashing
* [password\_hash()](function.password-hash) - Creates a password hash
php strrchr strrchr
=======
(PHP 4, PHP 5, PHP 7, PHP 8)
strrchr — Find the last occurrence of a character in a string
### Description
```
strrchr(string $haystack, string $needle): string|false
```
This function returns the portion of `haystack` which starts at the last occurrence of `needle` and goes until the end of `haystack`.
### Parameters
`haystack`
The string to search in
`needle`
If `needle` contains more than one character, only the first is used. This behavior is different from that of [strstr()](function.strstr).
Prior to PHP 8.0.0, if `needle` is not a string, it is converted to an integer and applied as the ordinal value of a character. This behavior is deprecated as of PHP 7.3.0, and relying on it is highly discouraged. Depending on the intended behavior, the `needle` should either be explicitly cast to string, or an explicit call to [chr()](function.chr) should be performed.
### Return Values
This function returns the portion of string, or **`false`** if `needle` is not found.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | Passing an int as `needle` is no longer supported. |
| 7.3.0 | Passing an int as `needle` has been deprecated. |
### Examples
**Example #1 **strrchr()** example**
```
<?php
// get last directory in $PATH
$dir = substr(strrchr($PATH, ":"), 1);
// get everything after last newline
$text = "Line 1\nLine 2\nLine 3";
$last = substr(strrchr($text, 10), 1 );
?>
```
### Notes
> **Note**: This function is binary-safe.
>
>
### See Also
* [strstr()](function.strstr) - Find the first occurrence of a string
* [strrpos()](function.strrpos) - Find the position of the last occurrence of a substring in a string
php RecursiveIteratorIterator::nextElement RecursiveIteratorIterator::nextElement
======================================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
RecursiveIteratorIterator::nextElement — Next element
### Description
```
public RecursiveIteratorIterator::nextElement(): void
```
Called when the next element is available.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php MultipleIterator::current MultipleIterator::current
=========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
MultipleIterator::current — Gets the registered iterator instances
### Description
```
public MultipleIterator::current(): array
```
Get the registered iterator instances current() result.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
An array containing the current values of each attached iterator.
### Errors/Exceptions
A [RuntimeException](class.runtimeexception) if the iterator is invalid (as of PHP 8.1.0), or mode **`MIT_NEED_ALL`** is set and at least one attached iterator is not valid. Or an **IllegalValueException** if a key is **`null`** and **`MIT_KEYS_ASSOC`** is set.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | A [RuntimeException](class.runtimeexception) is now thrown if **MultipleIterator::current()** is called on an invalid iterator. Previously, **`false`** was returned. |
### See Also
* [MultipleIterator::valid()](multipleiterator.valid) - Checks the validity of sub iterators
| programming_docs |
php The GMP class
The GMP class
=============
Introduction
------------
(PHP 5 >= 5.6.0, PHP 7, PHP 8)
A GMP number. These objects support overloaded [arithmetic](language.operators.arithmetic), [bitwise](language.operators.bitwise) and [comparison](language.operators.comparison) operators.
>
> **Note**:
>
>
> No object-oriented interface is provided to manipulate **GMP** objects. Please use the [procedural GMP API](https://www.php.net/manual/en/book.gmp.php).
>
>
class **GMP** { /\* Methods \*/
```
public __serialize(): array
```
```
public __unserialize(array $data): void
```
} Table of Contents
-----------------
* [GMP::\_\_serialize](gmp.serialize) — Serializes the GMP object
* [GMP::\_\_unserialize](gmp.unserialize) — Deserializes the data parameter into a GMP object
php Memcached::prepend Memcached::prepend
==================
(PECL memcached >= 0.1.0)
Memcached::prepend — Prepend data to an existing item
### Description
```
public Memcached::prepend(string $key, string $value): bool
```
**Memcached::prepend()** prepends the given `value` string to the value of an existing item. The reason that `value` is forced to be a string is that prepending mixed types is not well-defined.
>
> **Note**:
>
>
> If the **`Memcached::OPT_COMPRESSION`** is enabled, the operation will fail and a warning will be issued, because prepending compressed data to a value that is potentially already compressed is not possible.
>
>
### Parameters
`key`
The key of the item to prepend the data to.
`value`
The string to prepend.
### Return Values
Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTSTORED`** if the key does not exist.
### Examples
**Example #1 **Memcached::prepend()** example**
```
<?php
$m = new Memcached();
$m->addServer('localhost', 11211);
$m->setOption(Memcached::OPT_COMPRESSION, false);
$m->set('foo', 'abc');
$m->prepend('foo', 'def');
var_dump($m->get('foo'));
?>
```
The above example will output:
```
string(6) "defabc"
```
### See Also
* [Memcached::prependByKey()](memcached.prependbykey) - Prepend data to an existing item on a specific server
* [Memcached::append()](memcached.append) - Append data to an existing item
php ssh2_sftp_unlink ssh2\_sftp\_unlink
==================
(PECL ssh2 >= 0.9.0)
ssh2\_sftp\_unlink — Delete a file
### Description
```
ssh2_sftp_unlink(resource $sftp, string $filename): bool
```
Deletes a file on the remote filesystem.
### Parameters
`sftp`
An SSH2 SFTP resource opened by [ssh2\_sftp()](function.ssh2-sftp).
`filename`
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Deleting a file**
```
<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
ssh2_sftp_unlink($sftp, '/home/username/stale_file');
?>
```
### See Also
* [unlink()](function.unlink) - Deletes a file
php IntlBreakIterator::__construct IntlBreakIterator::\_\_construct
================================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
IntlBreakIterator::\_\_construct — Private constructor for disallowing instantiation
### Description
private **IntlBreakIterator::\_\_construct**()
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php SolrQuery::getHighlightSnippets SolrQuery::getHighlightSnippets
===============================
(PECL solr >= 0.9.2)
SolrQuery::getHighlightSnippets — Returns the maximum number of highlighted snippets to generate per field
### Description
```
public SolrQuery::getHighlightSnippets(string $field_override = ?): int
```
Returns the maximum number of highlighted snippets to generate per field. Accepts an optional field override
### Parameters
`field_override`
The name of the field
### Return Values
Returns an integer on success and **`null`** if not set.
php NumberFormatter::getSymbol NumberFormatter::getSymbol
==========================
numfmt\_get\_symbol
===================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
NumberFormatter::getSymbol -- numfmt\_get\_symbol — Get a symbol value
### Description
Object-oriented style
```
public NumberFormatter::getSymbol(int $symbol): string|false
```
Procedural style
```
numfmt_get_symbol(NumberFormatter $formatter, int $symbol): string|false
```
Get a symbol associated with the formatter. The formatter uses symbols to represent the special locale-dependent characters in a number, for example the percent sign. This API is not supported for rule-based formatters.
### Parameters
`formatter`
[NumberFormatter](class.numberformatter) object.
`symbol`
Symbol specifier, one of the [format symbol](class.numberformatter#intl.numberformatter-constants.unumberformatsymbol) constants.
### Return Values
The symbol string or **`false`** on error.
### Examples
**Example #1 **numfmt\_get\_symbol()** example**
```
<?php
$fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
numfmt_set_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".numfmt_get_symbol($fmt, NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo numfmt_format($fmt, 1234567.891234567890000)."\n";
?>
```
**Example #2 OO example**
```
<?php
$fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL );
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
$fmt->setSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL, "*");
echo "Sep: ".$fmt->getSymbol(NumberFormatter::GROUPING_SEPARATOR_SYMBOL)."\n";
echo $fmt->format(1234567.891234567890000)."\n";
?>
```
The above example will output:
```
Sep: .
1.234.567,891
Sep: *
1*234*567,891
```
### See Also
* [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code
* [numfmt\_set\_symbol()](numberformatter.setsymbol) - Set a symbol value
php SplFixedArray::rewind SplFixedArray::rewind
=====================
(PHP 5 >= 5.3.0, PHP 7)
SplFixedArray::rewind — Rewind iterator back to the start
### Description
```
public SplFixedArray::rewind(): void
```
Rewinds the iterator to the beginning.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php SQLite3::open SQLite3::open
=============
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3::open — Opens an SQLite database
### Description
```
public SQLite3::open(string $filename, int $flags = SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE, string $encryptionKey = ""): void
```
Opens an SQLite 3 Database. If the build includes encryption, then it will attempt to use the key.
### Parameters
`filename`
Path to the SQLite database, or `:memory:` to use in-memory database.
`flags`
Optional flags used to determine how to open the SQLite database. By default, open uses `SQLITE3_OPEN_READWRITE | SQLITE3_OPEN_CREATE`.
* `SQLITE3_OPEN_READONLY`: Open the database for reading only.
* `SQLITE3_OPEN_READWRITE`: Open the database for reading and writing.
* `SQLITE3_OPEN_CREATE`: Create the database if it does not exist.
`encryptionKey`
An optional encryption key used when encrypting and decrypting an SQLite database. If the SQLite encryption module is not installed, this parameter will have no effect.
### Return Values
No value is returned.
### Examples
**Example #1 **SQLite3::open()** example**
```
<?php
/**
* Simple example of extending the SQLite3 class and changing the __construct
* parameters, then using the open method to initialize the DB.
*/
class MyDB extends SQLite3
{
function __construct()
{
$this->open('mysqlitedb.db');
}
}
$db = new MyDB();
$db->exec('CREATE TABLE foo (bar STRING)');
$db->exec("INSERT INTO foo (bar) VALUES ('This is a test')");
$result = $db->query('SELECT bar FROM foo');
var_dump($result->fetchArray());
?>
```
php ReflectionParameter::getPosition ReflectionParameter::getPosition
================================
(PHP 5 >= 5.1.3, PHP 7, PHP 8)
ReflectionParameter::getPosition — Gets parameter position
### Description
```
public ReflectionParameter::getPosition(): int
```
Gets the position of the parameter.
### Parameters
This function has no parameters.
### Return Values
The position of the parameter, left to right, starting at position #0.
### See Also
* [ReflectionParameter::getName()](reflectionparameter.getname) - Gets parameter name
php SplFileObject::getChildren SplFileObject::getChildren
==========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
SplFileObject::getChildren — No purpose
### Description
```
public SplFileObject::getChildren(): null
```
An [SplFileObject](class.splfileobject) does not have children so this method returns **`null`**.
### Parameters
This function has no parameters.
### Return Values
Returns **`null`**.
### See Also
* [RecursiveIterator::getChildren()](recursiveiterator.getchildren) - Returns an iterator for the current entry
php SplPriorityQueue::key SplPriorityQueue::key
=====================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplPriorityQueue::key — Return current node index
### Description
```
public SplPriorityQueue::key(): int
```
This function returns the current node index
### Parameters
This function has no parameters.
### Return Values
The current node index.
php SolrQuery::setMltMaxNumQueryTerms SolrQuery::setMltMaxNumQueryTerms
=================================
(PECL solr >= 0.9.2)
SolrQuery::setMltMaxNumQueryTerms — Sets the maximum number of query terms included
### Description
```
public SolrQuery::setMltMaxNumQueryTerms(int $value): SolrQuery
```
Sets the maximum number of query terms that will be included in any generated query.
### Parameters
`value`
The maximum number of query terms that will be included in any generated query
### Return Values
Returns the current SolrQuery object, if the return value is used.
php Parle\RLexer::advance Parle\RLexer::advance
=====================
(PECL parle >= 0.5.1)
Parle\RLexer::advance — Process next lexer rule
### Description
```
public Parle\RLexer::advance(): void
```
Processes the next rule and prepares the resulting token data.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php OAuth::getLastResponseHeaders OAuth::getLastResponseHeaders
=============================
(No version information available, might only be in Git)
OAuth::getLastResponseHeaders — Get headers for last response
### Description
```
public OAuth::getLastResponseHeaders(): string|false
```
Get headers for last response.
### Parameters
This function has no parameters.
### Return Values
A string containing the last response's headers or **`false`** on failure
php Event::free Event::free
===========
(PECL event >= 1.2.6-beta)
Event::free — Make event non-pending and free resources allocated for this event
### Description
```
public Event::free(): void
```
Removes event from the list of events monitored by libevent, and free resources allocated for the event.
**Warning** The **Event::free()** method currently doesn't destruct the object itself. To destruct the object completely call [unset()](function.unset) , or assign **`null`**.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
### See Also
* [Event::\_\_construct()](event.construct) - Constructs Event object
php Phar::convertToExecutable Phar::convertToExecutable
=========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)
Phar::convertToExecutable — Convert a phar archive to another executable phar archive file format
### Description
```
public Phar::convertToExecutable(?int $format = null, ?int $compression = null, ?string $extension = null): ?Phar
```
>
> **Note**:
>
>
> This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown.
>
>
>
This method is used to convert a phar archive to another file format. For instance, it can be used to create a tar-based executable phar archive from a zip-based executable phar archive, or from an executable phar archive in the phar file format. In addition, it can be used to apply whole-archive compression to a tar or phar-based archive.
If no changes are specified, this method throws a [BadMethodCallException](class.badmethodcallexception).
If successful, the method creates a new archive on disk and returns a [Phar](class.phar) object. The old archive is not removed from disk, and should be done manually after the process has finished.
### Parameters
`format`
This should be one of `Phar::PHAR`, `Phar::TAR`, or `Phar::ZIP`. If set to **`null`**, the existing file format will be preserved.
`compression`
This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression.
`extension`
This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain `.phar` in their file extension in order to be processed as a phar archive.
If converting to a phar-based archive, the default extensions are `.phar`, `.phar.gz`, or `.phar.bz2` depending on the specified compression. For tar-based phar archives, the default extensions are `.phar.tar`, `.phar.tar.gz`, and `.phar.tar.bz2`. For zip-based phar archives, the default extension is `.phar.zip`.
### Return Values
The method returns a [Phar](class.phar) object on success, or **`null`** on failure.
### Errors/Exceptions
This method throws [BadMethodCallException](class.badmethodcallexception) when unable to compress, an unknown compression method has been specified, the requested archive is buffering with [Phar::startBuffering()](phar.startbuffering) and has not concluded with [Phar::stopBuffering()](phar.stopbuffering), an [UnexpectedValueException](class.unexpectedvalueexception) if write support is disabled, and a [PharException](class.pharexception) if any problems are encountered during the phar creation process.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `format`, `compression`, and `localName` are now nullable. |
### Examples
**Example #1 A **Phar::convertToExecutable()** example**
Using Phar::convertToExecutable():
```
<?php
try {
$tarphar = new Phar('myphar.phar.tar');
// convert it to the phar file format
// note that myphar.phar.tar is *not* unlinked
$phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
// creates myphar.phar.tgz
$compressed = $phar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>
```
### See Also
* [Phar::convertToData()](phar.converttodata) - Convert a phar archive to a non-executable tar or zip file
* [PharData::convertToExecutable()](phardata.converttoexecutable) - Convert a non-executable tar/zip archive to an executable phar archive
* [PharData::convertToData()](phardata.converttodata) - Convert a phar archive to a non-executable tar or zip file
php imagettfbbox imagettfbbox
============
(PHP 4, PHP 5, PHP 7, PHP 8)
imagettfbbox — Give the bounding box of a text using TrueType fonts
### Description
```
imagettfbbox(
float $size,
float $angle,
string $font_filename,
string $string,
array $options = []
): array|false
```
This function calculates and returns the bounding box in pixels for a TrueType text.
>
> **Note**:
>
>
> Prior to PHP 8.0.0, [imageftbbox()](function.imageftbbox) was an extended variant of **imagettfbbox()** which additionally supported the `extrainfo`. As of PHP 8.0.0, **imagettfbbox()** is an alias of [imageftbbox()](function.imageftbbox).
>
>
### Parameters
`size`
The font size in points.
`angle`
Angle in degrees in which `string` will be measured.
`fontfile`
The path to the TrueType font you wish to use.
Depending on which version of the GD library PHP is using, *when `fontfile` does not begin with a leading `/` then `.ttf` will be appended* to the filename and the library will attempt to search for that filename along a library-defined font path.
When using versions of the GD library lower than 2.0.18, a `space` character, rather than a semicolon, was used as the 'path separator' for different font files. Unintentional use of this feature will result in the warning message: `Warning: Could not find/open font`. For these affected versions, the only solution is moving the font to a path which does not contain spaces.
In many cases where a font resides in the same directory as the script using it the following trick will alleviate any include problems.
```
<?php
// Set the environment variable for GD
putenv('GDFONTPATH=' . realpath('.'));
// Name the font to be used (note the lack of the .ttf extension)
$font = 'SomeFont';
?>
```
>
> **Note**:
>
>
> Note that [open\_basedir](https://www.php.net/manual/en/ini.core.php#ini.open-basedir) does *not* apply to `fontfile`.
>
>
`string`
The string to be measured.
### Return Values
**imagettfbbox()** returns an array with 8 elements representing four points making the bounding box of the text on success and **`false`** on error.
| key | contents |
| --- | --- |
| 0 | lower left corner, X position |
| 1 | lower left corner, Y position |
| 2 | lower right corner, X position |
| 3 | lower right corner, Y position |
| 4 | upper right corner, X position |
| 5 | upper right corner, Y position |
| 6 | upper left corner, X position |
| 7 | upper left corner, Y position |
The points are relative to the *text* regardless of the `angle`, so "upper left" means in the top left-hand corner seeing the text horizontally.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | The `options` has been added. |
### Examples
**Example #1 **imagettfbbox()** example**
```
<?php
// Create a 300x150 image
$im = imagecreatetruecolor(300, 150);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
// Set the background to be white
imagefilledrectangle($im, 0, 0, 299, 299, $white);
// Path to our font file
$font = './arial.ttf';
// First we create our bounding box for the first text
$bbox = imagettfbbox(10, 45, $font, 'Powered by PHP ' . phpversion());
// This is our cordinates for X and Y
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 25;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;
// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'Powered by PHP ' . phpversion());
// Create the next bounding box for the second text
$bbox = imagettfbbox(10, 45, $font, 'and Zend Engine ' . zend_version());
// Set the cordinates so its next to the first text
$x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) + 10;
$y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5;
// Write it
imagettftext($im, 10, 45, $x, $y, $black, $font, 'and Zend Engine ' . zend_version());
// Output to browser
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
?>
```
### Notes
> **Note**: This function is only available if PHP is compiled with freetype support (**--with-freetype-dir=DIR**)
>
>
### See Also
* [imagettftext()](function.imagettftext) - Write text to the image using TrueType fonts
* [imageftbbox()](function.imageftbbox) - Give the bounding box of a text using fonts via freetype2
| programming_docs |
php XMLReader::moveToFirstAttribute XMLReader::moveToFirstAttribute
===============================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
XMLReader::moveToFirstAttribute — Position cursor on the first Attribute
### Description
```
public XMLReader::moveToFirstAttribute(): bool
```
Moves cursor to the first Attribute.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [XMLReader::moveToElement()](xmlreader.movetoelement) - Position cursor on the parent Element of current Attribute
* [XMLReader::moveToAttribute()](xmlreader.movetoattribute) - Move cursor to a named attribute
* [XMLReader::moveToAttributeNo()](xmlreader.movetoattributeno) - Move cursor to an attribute by index
* [XMLReader::moveToAttributeNs()](xmlreader.movetoattributens) - Move cursor to a named attribute
* [XMLReader::moveToNextAttribute()](xmlreader.movetonextattribute) - Position cursor on the next Attribute
php Ds\Set::remove Ds\Set::remove
==============
(PECL ds >= 1.0.0)
Ds\Set::remove — Removes all given values from the set
### Description
```
public Ds\Set::remove(mixed ...$values): void
```
Removes all given `values` from the set, ignoring any that are not in the set.
### Parameters
`values`
The values to remove.
### Return Values
No value is returned.
### Examples
**Example #1 **Ds\Set::remove()** example**
```
<?php
$set = new \Ds\Set([1, 2, 3, 4, 5]);
$set->remove(1); // Remove 1
$set->remove(1, 2); // Can't find 1, but remove 2
$set->remove(...[3, 4]); // Remove 3 and 4
var_dump($set);
?>
```
The above example will output something similar to:
```
object(Ds\Set)#1 (1) {
[0]=>
int(5)
}
```
php gzuncompress gzuncompress
============
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
gzuncompress — Uncompress a compressed string
### Description
```
gzuncompress(string $data, int $max_length = 0): string|false
```
This function uncompress a compressed string.
### Parameters
`data`
The data compressed by [gzcompress()](function.gzcompress).
`max_length`
The maximum length of data to decode.
### Return Values
The original uncompressed data or **`false`** on error.
The function will return an error if the uncompressed data is more than 32768 times the length of the compressed input `data` or more than the optional parameter `max_length`.
### Examples
**Example #1 **gzuncompress()** example**
```
<?php
$compressed = gzcompress('Compress me', 9);
$uncompressed = gzuncompress($compressed);
echo $uncompressed;
?>
```
### See Also
* [gzcompress()](function.gzcompress) - Compress a string
* [gzinflate()](function.gzinflate) - Inflate a deflated string
* [gzdeflate()](function.gzdeflate) - Deflate a string
* [gzencode()](function.gzencode) - Create a gzip compressed string
php VarnishAdmin::__construct VarnishAdmin::\_\_construct
===========================
(PECL varnish >= 0.3)
VarnishAdmin::\_\_construct — VarnishAdmin constructor
### Description
```
public VarnishAdmin::__construct(array $args = ?)
```
### Parameters
`args`
Configuration arguments. The possible keys are:
```
VARNISH_CONFIG_IDENT - local varnish instance ident
VARNISH_CONFIG_HOST - varnish instance ip
VARNISH_CONFIG_PORT - varnish instance port
VARNISH_CONFIG_SECRET - varnish instance secret
VARNISH_CONFIG_TIMEOUT - connection read timeout
VARNISH_CONFIG_COMPAT - varnish major version compatibility
```
### Return Values
### Examples
**Example #1 **VarnishAdmin::\_\_construct()** example**
```
<?php
$args = array(
VARNISH_CONFIG_HOST => "::1",
VARNISH_CONFIG_PORT => 6082,
VARNISH_CONFIG_SECRET => "5174826b-8595-4958-aa7a-0609632ad7ca",
VARNISH_CONFIG_TIMEOUT => 300,
);
$va = new VarnishAdmin($args);
?>
```
php EventBufferEvent::getDnsErrorString EventBufferEvent::getDnsErrorString
===================================
(PECL event >= 1.2.6-beta)
EventBufferEvent::getDnsErrorString — Returns string describing the last failed DNS lookup attempt
### Description
```
public EventBufferEvent::getDnsErrorString(): string
```
Returns string describing the last failed DNS lookup attempt made by [EventBufferEvent::connectHost()](eventbufferevent.connecthost) , or an empty string, if there is no DNS error detected.
### Parameters
This function has no parameters.
### Return Values
Returns a string describing DNS lookup error, or an empty string for no error.
### See Also
* [EventBufferEvent::connectHost()](eventbufferevent.connecthost) - Connects to a hostname with optionally asyncronous DNS resolving
php Collator::getErrorCode Collator::getErrorCode
======================
collator\_get\_error\_code
==========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
Collator::getErrorCode -- collator\_get\_error\_code — Get collator's last error code
### Description
Object-oriented style
```
public Collator::getErrorCode(): int|false
```
Procedural style
```
collator_get_error_code(Collator $object): int|false
```
### Parameters
`object`
[Collator](class.collator) object.
### Return Values
Error code returned by the last Collator API function call, or **`false`** on failure.
### Examples
**Example #1 **collator\_get\_error\_code()** example**
```
<?php
$coll = collator_create( 'en_US' );
if( collator_get_attribute( $coll, Collator::FRENCH_COLLATION ) === false )
handle_error( collator_get_error_code() );
?>
```
### See Also
* [collator\_get\_error\_message()](collator.geterrormessage) - Get text for collator's last error code
php bcmul bcmul
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
bcmul — Multiply two arbitrary precision numbers
### Description
```
bcmul(string $num1, string $num2, ?int $scale = null): string
```
Multiply the `num1` by the `num2`.
### Parameters
`num1`
The left operand, as a string.
`num2`
The right operand, as a string.
`scale`
This optional parameter is used to set the number of digits after the decimal place in the result. If omitted, it will default to the scale set globally with the [bcscale()](function.bcscale) function, or fallback to `0` if this has not been set.
### Return Values
Returns the result as a string.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `scale` is now nullable. |
| 7.3.0 | **bcmul()** now returns numbers with the requested scale. Formerly, the returned numbers may have omitted trailing decimal zeroes. |
### Examples
**Example #1 **bcmul()** example**
```
<?php
echo bcmul('1.34747474747', '35', 3); // 47.161
echo bcmul('2', '4'); // 8
?>
```
### Notes
>
> **Note**:
>
>
> Before PHP 7.3.0 **bcmul()** may return a result with fewer digits after the decimal point than the `scale` parameter would indicate. This only occurs when the result doesn't require all of the precision allowed by the `scale`. For example:
>
>
> **Example #2 **bcmul()** scale example**
>
>
> ```
> <?php
> echo bcmul('5', '2', 2); // prints "10", not "10.00"
> ?>
> ```
>
### See Also
* [bcdiv()](function.bcdiv) - Divide two arbitrary precision numbers
php cal_days_in_month cal\_days\_in\_month
====================
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
cal\_days\_in\_month — Return the number of days in a month for a given year and calendar
### Description
```
cal_days_in_month(int $calendar, int $month, int $year): int
```
This function will return the number of days in the `month` of `year` for the specified `calendar`.
### Parameters
`calendar`
Calendar to use for calculation
`month`
Month in the selected calendar
`year`
Year in the selected calendar
### Return Values
The length in days of the selected month in the given calendar
### Examples
**Example #1 **cal\_days\_in\_month()** example**
```
<?php
$number = cal_days_in_month(CAL_GREGORIAN, 8, 2003); // 31
echo "There were {$number} days in August 2003";
?>
```
php openssl_encrypt openssl\_encrypt
================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
openssl\_encrypt — Encrypts data
### Description
```
openssl_encrypt(
string $data,
string $cipher_algo,
string $passphrase,
int $options = 0,
string $iv = "",
string &$tag = null,
string $aad = "",
int $tag_length = 16
): string|false
```
Encrypts given data with given method and key, returns a raw or base64 encoded string
### Parameters
`data`
The plaintext message data to be encrypted.
`cipher_algo`
The cipher method. For a list of available cipher methods, use [openssl\_get\_cipher\_methods()](function.openssl-get-cipher-methods).
`passphrase`
The passphrase. If the passphrase is shorter than expected, it is silently padded with `NUL` characters; if the passphrase is longer than expected, it is silently truncated.
`options`
`options` is a bitwise disjunction of the flags **`OPENSSL_RAW_DATA`** and **`OPENSSL_ZERO_PADDING`**.
`iv`
A non-NULL Initialization Vector.
`tag`
The authentication tag passed by reference when using AEAD cipher mode (GCM or CCM).
`aad`
Additional authenticated data.
`tag_length`
The length of the authentication `tag`. Its value can be between 4 and 16 for GCM mode.
### Return Values
Returns the encrypted string on success or **`false`** on failure.
### Errors/Exceptions
Emits an **`E_WARNING`** level error if an unknown cipher algorithm is passed in via the `cipher_algo` parameter.
Emits an **`E_WARNING`** level error if an empty value is passed in via the `iv` parameter.
### Changelog
| Version | Description |
| --- | --- |
| 7.1.0 | The `tag`, `aad` and `tag_length` parameters were added. |
### Examples
**Example #1 AES Authenticated Encryption in GCM mode example for PHP 7.1+**
```
<?php
//$key should have been previously generated in a cryptographically safe way, like openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$cipher = "aes-128-gcm";
if (in_array($cipher, openssl_get_cipher_methods()))
{
$ivlen = openssl_cipher_iv_length($cipher);
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext = openssl_encrypt($plaintext, $cipher, $key, $options=0, $iv, $tag);
//store $cipher, $iv, and $tag for decryption later
$original_plaintext = openssl_decrypt($ciphertext, $cipher, $key, $options=0, $iv, $tag);
echo $original_plaintext."\n";
}
?>
```
**Example #2 AES Authenticated Encryption example prior to PHP 7.1**
```
<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))// timing attack safe comparison
{
echo $original_plaintext."\n";
}
?>
```
### See Also
* [openssl\_decrypt()](function.openssl-decrypt) - Decrypts data
php MessageFormatter::getErrorMessage MessageFormatter::getErrorMessage
=================================
msgfmt\_get\_error\_message
===========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
MessageFormatter::getErrorMessage -- msgfmt\_get\_error\_message — Get the error text from the last operation
### Description
Object-oriented style
```
public MessageFormatter::getErrorMessage(): string
```
Procedural style
```
msgfmt_get_error_message(MessageFormatter $formatter): string
```
Get the error text from the last operation.
### Parameters
`formatter`
The message formatter
### Return Values
Description of the last error.
### Examples
**Example #1 **msgfmt\_get\_error\_message()** example**
```
<?php
$fmt = msgfmt_create("en_US", "{0, number} monkeys on {1, number} trees");
$str = msgfmt_format($fmt, array());
if(!$str) {
echo "ERROR: ".msgfmt_get_error_message($fmt) . " (" . msgfmt_get_error_code($fmt) . ")\n";
}
?>
```
**Example #2 OO example**
```
<?php
$fmt = new MessageFormatter("en_US", "{0, number} monkeys on {1, number} trees");
$str = $fmt->format(array());
if(!$str) {
echo "ERROR: ".$fmt->getErrorMessage() . " (" . $fmt->getErrorCode() . ")\n";
}
?>
```
The above example will output:
```
ERROR: msgfmt_format: not enough parameters: U_ILLEGAL_ARGUMENT_ERROR (1)
```
### See Also
* [msgfmt\_get\_error\_code()](messageformatter.geterrorcode) - Get the error code from last operation
* [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code
* [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure
php jdtounix jdtounix
========
(PHP 4, PHP 5, PHP 7, PHP 8)
jdtounix — Convert Julian Day to Unix timestamp
### Description
```
jdtounix(int $julian_day): int
```
This function will return a Unix timestamp corresponding to the Julian Day given in `julian_day`. The time returned is UTC.
### Parameters
`julian_day`
A julian day number between `2440588` and `106751993607888` on 64bit systems, or between `2440588` and `2465443` on 32bit systems.
### Return Values
The unix timestamp for the start (midnight, not noon) of the given Julian day
### Errors/Exceptions
If `julian_day` is outside of the allowed range, a [ValueError](class.valueerror) is thrown.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | This function no longer returns **`false`** on failure, but raises a [ValueError](class.valueerror) instead. |
| 7.3.24, 7.4.12 | The upper limit of `julian_day` has been extended. Previously, it was `2465342` regardless of the architecture. |
### See Also
* [unixtojd()](function.unixtojd) - Convert Unix timestamp to Julian Day
php Yaf_Loader::getLocalNamespace Yaf\_Loader::getLocalNamespace
==============================
(Yaf >=1.0.0)
Yaf\_Loader::getLocalNamespace — The getLocalNamespace purpose
### Description
```
public Yaf_Loader::getLocalNamespace(): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php Imagick::deleteImageArtifact Imagick::deleteImageArtifact
============================
(PECL imagick 3)
Imagick::deleteImageArtifact — Delete image artifact
### Description
```
public Imagick::deleteImageArtifact(string $artifact): bool
```
Deletes an artifact associated with the image. The difference between image properties and image artifacts is that properties are public and artifacts are private. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.
### Parameters
`artifact`
The name of the artifact to delete
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
### See Also
* [Imagick::setImageArtifact()](imagick.setimageartifact) - Set image artifact
* [Imagick::getImageArtifact()](imagick.getimageartifact) - Get image artifact
php ZipArchive::statName ZipArchive::statName
====================
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0)
ZipArchive::statName — Get the details of an entry defined by its name
### Description
```
public ZipArchive::statName(string $name, int $flags = 0): array|false
```
The function obtains information about the entry defined by its name.
### Parameters
`name`
Name of the entry
`flags`
The flags argument specifies how the name lookup should be done. Also, **`ZipArchive::FL_UNCHANGED`** may be ORed to it to request information about the original file in the archive, ignoring any changes made.
* **`ZipArchive::FL_NOCASE`**
* **`ZipArchive::FL_NODIR`**
* **`ZipArchive::FL_UNCHANGED`**
### Return Values
Returns an array containing the entry details or **`false`** on failure.
### Examples
**Example #1 Dump the stat info of an entry**
```
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip');
if ($res === TRUE) {
print_r($zip->statName('foobar/baz'));
$zip->close();
} else {
echo 'failed, code:' . $res;
}
?>
```
The above example will output something similar to:
```
Array
(
[name] => foobar/baz
[index] => 3
[crc] => 499465816
[size] => 27
[mtime] => 1123164748
[comp_size] => 24
[comp_method] => 8
)
```
php Ds\Set::get Ds\Set::get
===========
(PECL ds >= 1.0.0)
Ds\Set::get — Returns the value at a given index
### Description
```
public Ds\Set::get(int $index): mixed
```
Returns the value at a given index.
### Parameters
`index`
The index to access, starting at 0.
### Return Values
The value at the requested index.
### Errors/Exceptions
[OutOfRangeException](class.outofrangeexception) if the index is not valid.
### Examples
**Example #1 **Ds\Set::get()** example**
```
<?php
$set = new \Ds\Set(["a", "b", "c"]);
var_dump($set->get(0));
var_dump($set->get(1));
var_dump($set->get(2));
?>
```
The above example will output something similar to:
```
string(1) "a"
string(1) "b"
string(1) "c"
```
**Example #2 **Ds\Set::get()** example using array syntax**
```
<?php
$set = new \Ds\Set(["a", "b", "c"]);
var_dump($set[0]);
var_dump($set[1]);
var_dump($set[2]);
?>
```
The above example will output something similar to:
```
string(1) "a"
string(1) "b"
string(1) "c"
```
php tmpfile tmpfile
=======
(PHP 4, PHP 5, PHP 7, PHP 8)
tmpfile — Creates a temporary file
### Description
```
tmpfile(): resource|false
```
Creates a temporary file with a unique name in read-write (w+) mode and returns a file handle.
The file is automatically removed when closed (for example, by calling [fclose()](function.fclose), or when there are no remaining references to the file handle returned by **tmpfile()**), or when the script ends.
**Caution** If the script terminates unexpectedly, the temporary file may not be deleted.
### Parameters
This function has no parameters.
### Return Values
Returns a file handle, similar to the one returned by [fopen()](function.fopen), for the new file or **`false`** on failure.
### Examples
**Example #1 **tmpfile()** example**
```
<?php
$temp = tmpfile();
fwrite($temp, "writing to tempfile");
fseek($temp, 0);
echo fread($temp, 1024);
fclose($temp); // this removes the file
?>
```
The above example will output:
```
writing to tempfile
```
### See Also
* [tempnam()](function.tempnam) - Create file with unique file name
* [sys\_get\_temp\_dir()](function.sys-get-temp-dir) - Returns directory path used for temporary files
php EvEmbed::sweep EvEmbed::sweep
==============
(PECL ev >= 0.2.0)
EvEmbed::sweep — Make a single, non-blocking sweep over the embedded loop
### Description
```
public EvEmbed::sweep(): void
```
Make a single, non-blocking sweep over the embedded loop. Works similarly to the following, but in the most appropriate way for embedded loops:
```
<?php
$other->start(Ev::RUN_NOWAIT);
?>
```
### Parameters
This function has no parameters.
### Return Values
No value is returned.
### See Also
* [EvWatcher::start()](evwatcher.start) - Starts the watcher
| programming_docs |
php ob_end_clean ob\_end\_clean
==============
(PHP 4, PHP 5, PHP 7, PHP 8)
ob\_end\_clean — Clean (erase) the output buffer and turn off output buffering
### Description
```
ob_end_clean(): bool
```
This function discards the contents of the topmost output buffer and turns off this output buffering. If you want to further process the buffer's contents you have to call [ob\_get\_contents()](function.ob-get-contents) before **ob\_end\_clean()** as the buffer contents are discarded when **ob\_end\_clean()** is called.
The output buffer must be started by [ob\_start()](function.ob-start) with [PHP\_OUTPUT\_HANDLER\_CLEANABLE](https://www.php.net/manual/en/outcontrol.constants.php#constant.php-output-handler-cleanable) and [PHP\_OUTPUT\_HANDLER\_REMOVABLE](https://www.php.net/manual/en/outcontrol.constants.php#constant.php-output-handler-removable) flags. Otherwise **ob\_end\_clean()** will not work.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).
### Errors/Exceptions
If the function fails it generates an **`E_NOTICE`**.
### Examples
The following example shows an easy way to get rid of all output buffers:
**Example #1 **ob\_end\_clean()** example**
```
<?php
ob_start();
echo 'Text that won\'t get displayed.';
ob_end_clean();
?>
```
### See Also
* [ob\_start()](function.ob-start) - Turn on output buffering
* [ob\_get\_contents()](function.ob-get-contents) - Return the contents of the output buffer
* [ob\_flush()](function.ob-flush) - Flush (send) the output buffer
php wddx_serialize_value wddx\_serialize\_value
======================
(PHP 4, PHP 5, PHP 7)
wddx\_serialize\_value — Serialize a single value into a WDDX packet
**Warning**This function was *REMOVED* in PHP 7.4.0.
### Description
```
wddx_serialize_value(mixed $var, string $comment = ?): string
```
Creates a WDDX packet from a single given value.
### Parameters
`var`
The value to be serialized
`comment`
An optional comment string that appears in the packet header.
### Return Values
Returns the WDDX packet, or **`false`** on error.
php Ds\Set::isEmpty Ds\Set::isEmpty
===============
(PECL ds >= 1.0.0)
Ds\Set::isEmpty — Returns whether the set is empty
### Description
```
public Ds\Set::isEmpty(): bool
```
Returns whether the set is empty.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if the set is empty, **`false`** otherwise.
### Examples
**Example #1 **Ds\Set::isEmpty()** example**
```
<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set();
var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>
```
The above example will output something similar to:
```
bool(false)
bool(true)
```
php pg_field_prtlen pg\_field\_prtlen
=================
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
pg\_field\_prtlen — Returns the printed length
### Description
```
pg_field_prtlen(PgSql\Result $result, int $row_number, mixed $field_name_or_number): int
```
```
pg_field_prtlen(PgSql\Result $result, mixed $field_name_or_number): int
```
**pg\_field\_prtlen()** returns the actual printed length (number of characters) of a specific value in a PostgreSQL `result`. Row numbering starts at 0. This function will return **`false`** on an error.
`field_name_or_number` can be passed either as an int or as a string. If it is passed as an int, PHP recognises it as the field number, otherwise as field name.
See the example given at the [pg\_field\_name()](function.pg-field-name) page.
>
> **Note**:
>
>
> This function used to be called **pg\_fieldprtlen()**.
>
>
### Parameters
`result`
An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others).
`row`
Row number in result. Rows are numbered from 0 upwards. If omitted, current row is fetched.
### Return Values
The field printed length.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 Getting information about fields**
```
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
$res = pg_query($dbconn, "select * from authors where author = 'Orwell'");
$i = pg_num_fields($res);
for ($j = 0; $j < $i; $j++) {
echo "column $j\n";
$fieldname = pg_field_name($res, $j);
echo "fieldname: $fieldname\n";
echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";
echo "storage length: " . pg_field_size($res, $j) . " bytes\n";
echo "field type: " . pg_field_type($res, $j) . " \n\n";
}
?>
```
The above example will output:
```
column 0
fieldname: author
printed length: 6 characters
storage length: -1 bytes
field type: varchar
column 1
fieldname: year
printed length: 4 characters
storage length: 2 bytes
field type: int2
column 2
fieldname: title
printed length: 24 characters
storage length: -1 bytes
field type: varchar
```
### See Also
* [pg\_field\_size()](function.pg-field-size) - Returns the internal storage size of the named field
php Imagick::blackThresholdImage Imagick::blackThresholdImage
============================
(PECL imagick 2, PECL imagick 3)
Imagick::blackThresholdImage — Forces all pixels below the threshold into black
### Description
```
public Imagick::blackThresholdImage(mixed $threshold): bool
```
Is like Imagick::thresholdImage() but forces all pixels below the threshold into black while leaving all pixels above the threshold unchanged.
### Parameters
`threshold`
The threshold below which everything turns black
### Return Values
Returns **`true`** on success.
### Changelog
| Version | Description |
| --- | --- |
| PECL imagick 2.1.0 | Now allows a string representing the color as a parameter. Previous versions allow only an ImagickPixel object. |
### Examples
**Example #1 **Imagick::blackThresholdImage()****
```
<?php
function blackThresholdImage($imagePath, $thresholdColor) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->blackthresholdimage($thresholdColor);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>
```
php SolrQuery::setMlt SolrQuery::setMlt
=================
(PECL solr >= 0.9.2)
SolrQuery::setMlt — Enables or disables moreLikeThis
### Description
```
public SolrQuery::setMlt(bool $flag): SolrQuery
```
Enables or disables moreLikeThis
### Parameters
`flag`
**`true`** enables it and **`false`** turns it off.
### Return Values
Returns the current SolrQuery object, if the return value is used.
php mcrypt_encrypt mcrypt\_encrypt
===============
(PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0)
mcrypt\_encrypt — Encrypts plaintext with given parameters
**Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged.
### Description
```
mcrypt_encrypt(
string $cipher,
string $key,
string $data,
string $mode,
string $iv = ?
): string|false
```
Encrypts the data and returns it.
### Parameters
`cipher`
One of the **`MCRYPT_ciphername`** constants, or the name of the algorithm as string.
`key`
The key with which the data will be encrypted. If the provided key size is not supported by the cipher, the function will emit a warning and return **`false`**
`data`
The data that will be encrypted with the given `cipher` and `mode`. If the size of the data is not n \* blocksize, the data will be padded with '`\0`'.
The returned crypttext can be larger than the size of the data that was given by `data`.
`mode`
One of the **`MCRYPT_MODE_modename`** constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream".
`iv`
Used for the initialization in CBC, CFB, OFB modes, and in some algorithms in STREAM mode. If the provided IV size is not supported by the chaining mode or no IV was provided, but the chaining mode requires one, the function will emit a warning and return **`false`**.
### Return Values
Returns the encrypted data as a string or **`false`** on failure.
### Examples
**Example #1 **mcrypt\_encrypt()** Example**
```
<?php
# --- ENCRYPTION ---
# the key should be random binary, use scrypt, bcrypt or PBKDF2 to
# convert a string into a key
# key is specified using hexadecimal
$key = pack('H*', "bcb04b7e103a0cd8b54763051cef08bc55abe029fdebae5e1d417e2ffb2a00a3");
# show key size use either 16, 24 or 32 byte keys for AES-128, 192
# and 256 respectively
$key_size = strlen($key);
echo "Key size: " . $key_size . "\n";
$plaintext = "This string was AES-256 / CBC / ZeroBytePadding encrypted.";
# create a random IV to use with CBC encoding
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
# creates a cipher text compatible with AES (Rijndael block size = 128)
# to keep the text confidential
# only suitable for encoded input that never ends with value 00h
# (because of default zero padding)
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key,
$plaintext, MCRYPT_MODE_CBC, $iv);
# prepend the IV for it to be available for decryption
$ciphertext = $iv . $ciphertext;
# encode the resulting cipher text so it can be represented by a string
$ciphertext_base64 = base64_encode($ciphertext);
echo $ciphertext_base64 . "\n";
# === WARNING ===
# Resulting cipher text has no integrity or authenticity added
# and is not protected against padding oracle attacks.
# --- DECRYPTION ---
$ciphertext_dec = base64_decode($ciphertext_base64);
# retrieves the IV, iv_size should be created using mcrypt_get_iv_size()
$iv_dec = substr($ciphertext_dec, 0, $iv_size);
# retrieves the cipher text (everything except the $iv_size in the front)
$ciphertext_dec = substr($ciphertext_dec, $iv_size);
# may remove 00h valued characters from end of plain text
$plaintext_dec = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key,
$ciphertext_dec, MCRYPT_MODE_CBC, $iv_dec);
echo $plaintext_dec . "\n";
?>
```
The above example will output:
```
Key size: 32
ENJW8mS2KaJoNB5E5CoSAAu0xARgsR1bdzFWpEn+poYw45q+73az5kYi4j+0haevext1dGrcW8Qi59txfCBV8BBj3bzRP3dFCp3CPQSJ8eU=
This string was AES-256 / CBC / ZeroBytePadding encrypted.
```
### See Also
* [mcrypt\_decrypt()](function.mcrypt-decrypt) - Decrypts crypttext with given parameters
* [mcrypt\_module\_open()](function.mcrypt-module-open) - Opens the module of the algorithm and the mode to be used
php The RecursiveFilterIterator class
The RecursiveFilterIterator class
=================================
Introduction
------------
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
This abstract iterator filters out unwanted values for a [RecursiveIterator](class.recursiveiterator). This class should be extended to implement custom filters. The **RecursiveFilterIterator::accept()** must be implemented in the subclass.
Class synopsis
--------------
abstract class **RecursiveFilterIterator** extends [FilterIterator](class.filteriterator) implements [RecursiveIterator](class.recursiveiterator) { /\* Methods \*/ public [\_\_construct](recursivefilteriterator.construct)([RecursiveIterator](class.recursiveiterator) `$iterator`)
```
public getChildren(): ?RecursiveFilterIterator
```
```
public hasChildren(): bool
```
/\* Inherited methods \*/
```
public FilterIterator::accept(): bool
```
```
public FilterIterator::current(): mixed
```
```
public FilterIterator::getInnerIterator(): Iterator
```
```
public FilterIterator::key(): mixed
```
```
public FilterIterator::next(): void
```
```
public FilterIterator::rewind(): void
```
```
public FilterIterator::valid(): bool
```
```
public IteratorIterator::current(): mixed
```
```
public IteratorIterator::getInnerIterator(): ?Iterator
```
```
public IteratorIterator::key(): mixed
```
```
public IteratorIterator::next(): void
```
```
public IteratorIterator::rewind(): void
```
```
public IteratorIterator::valid(): bool
```
} Table of Contents
-----------------
* [RecursiveFilterIterator::\_\_construct](recursivefilteriterator.construct) — Create a RecursiveFilterIterator from a RecursiveIterator
* [RecursiveFilterIterator::getChildren](recursivefilteriterator.getchildren) — Return the inner iterator's children contained in a RecursiveFilterIterator
* [RecursiveFilterIterator::hasChildren](recursivefilteriterator.haschildren) — Check whether the inner iterator's current element has children
php SQLite3Stmt::execute SQLite3Stmt::execute
====================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3Stmt::execute — Executes a prepared statement and returns a result set object
### Description
```
public SQLite3Stmt::execute(): SQLite3Result|false
```
Executes a prepared statement and returns a result set object.
**Caution** Result set objects retrieved by calling this method on the same statement object are not independent, but rather share the same underlying structure. Therefore it is recommended to call [SQLite3Result::finalize()](sqlite3result.finalize), before calling **SQLite3Stmt::execute()** on the same statement object again.
### Parameters
This function has no parameters.
### Return Values
Returns an [SQLite3Result](class.sqlite3result) object on successful execution of the prepared statement, **`false`** on failure.
### See Also
* [SQLite3::prepare()](sqlite3.prepare) - Prepares an SQL statement for execution
* [SQLite3Stmt::bindValue()](sqlite3stmt.bindvalue) - Binds the value of a parameter to a statement variable
* [SQLite3Stmt::bindParam()](sqlite3stmt.bindparam) - Binds a parameter to a statement variable
php socket_recv socket\_recv
============
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket\_recv — Receives data from a connected socket
### Description
```
socket_recv(
Socket $socket,
?string &$data,
int $length,
int $flags
): int|false
```
The **socket\_recv()** function receives `length` bytes of data in `data` from `socket`. **socket\_recv()** can be used to gather data from connected sockets. Additionally, one or more flags can be specified to modify the behaviour of the function.
`data` is passed by reference, so it must be specified as a variable in the argument list. Data read from `socket` by **socket\_recv()** will be returned in `data`.
### Parameters
`socket`
The `socket` must be a [Socket](class.socket) instance previously created by socket\_create().
`data`
The data received will be fetched to the variable specified with `data`. If an error occurs, if the connection is reset, or if no data is available, `data` will be set to **`null`**.
`length`
Up to `length` bytes will be fetched from remote host.
`flags`
The value of `flags` can be any combination of the following flags, joined with the binary OR (`|`) operator.
**Possible values for `flags`**| Flag | Description |
| --- | --- |
| **`MSG_OOB`** | Process out-of-band data. |
| **`MSG_PEEK`** | Receive data from the beginning of the receive queue without removing it from the queue. |
| **`MSG_WAITALL`** | Block until at least `length` are received. However, if a signal is caught or the remote host disconnects, the function may return less data. |
| **`MSG_DONTWAIT`** | With this flag set, the function returns even if it would normally have blocked. |
### Return Values
**socket\_recv()** returns the number of bytes received, or **`false`** if there was an error. The actual error code can be retrieved by calling [socket\_last\_error()](function.socket-last-error). This error code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual explanation of the error.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. |
### Examples
**Example #1 **socket\_recv()** example**
This example is a simple rewrite of the first example from [Examples](https://www.php.net/manual/en/sockets.examples.php) to use **socket\_recv()**.
```
<?php
error_reporting(E_ALL);
echo "<h2>TCP/IP Connection</h2>\n";
/* Get the port for the WWW service. */
$service_port = getservbyname('www', 'tcp');
/* Get the IP address for the target host. */
$address = gethostbyname('www.example.com');
/* Create a TCP/IP socket. */
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
} else {
echo "OK.\n";
}
echo "Attempting to connect to '$address' on port '$service_port'...";
$result = socket_connect($socket, $address, $service_port);
if ($result === false) {
echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
} else {
echo "OK.\n";
}
$in = "HEAD / HTTP/1.1\r\n";
$in .= "Host: www.example.com\r\n";
$in .= "Connection: Close\r\n\r\n";
$out = '';
echo "Sending HTTP HEAD request...";
socket_write($socket, $in, strlen($in));
echo "OK.\n";
echo "Reading response:\n\n";
$buf = 'This is my buffer.';
if (false !== ($bytes = socket_recv($socket, $buf, 2048, MSG_WAITALL))) {
echo "Read $bytes bytes from socket_recv(). Closing socket...";
} else {
echo "socket_recv() failed; reason: " . socket_strerror(socket_last_error($socket)) . "\n";
}
socket_close($socket);
echo $buf . "\n";
echo "OK.\n\n";
?>
```
The above example will produce something like:
```
<h2>TCP/IP Connection</h2>
OK.
Attempting to connect to '208.77.188.166' on port '80'...OK.
Sending HTTP HEAD request...OK.
Reading response:
Read 123 bytes from socket_recv(). Closing socket...HTTP/1.1 200 OK
Date: Mon, 14 Sep 2009 08:56:36 GMT
Server: Apache/2.2.3 (Red Hat)
Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
ETag: "b80f4-1b6-80bfd280"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8
OK.
```
php Event::getSupportedMethods Event::getSupportedMethods
==========================
(PECL event >= 1.2.6-beta)
Event::getSupportedMethods — Returns array with of the names of the methods supported in this version of Libevent
### Description
```
public static Event::getSupportedMethods(): array
```
Returns array with of the names of the methods(backends) supported in this version of Libevent.
### Parameters
This function has no parameters.
### Return Values
Returns array.
### See Also
* [EventConfig](class.eventconfig)
php disk_free_space disk\_free\_space
=================
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
disk\_free\_space — Returns available space on filesystem or disk partition
### Description
```
disk_free_space(string $directory): float|false
```
Given a string containing a directory, this function will return the number of bytes available on the corresponding filesystem or disk partition.
### Parameters
`directory`
A directory of the filesystem or disk partition.
>
> **Note**:
>
>
> Given a file name instead of a directory, the behaviour of the function is unspecified and may differ between operating systems and PHP versions.
>
>
### Return Values
Returns the number of available bytes as a float or **`false`** on failure.
### Examples
**Example #1 **disk\_free\_space()** example**
```
<?php
// $df contains the number of bytes available on "/"
$df = disk_free_space("/");
// On Windows:
$df_c = disk_free_space("C:");
$df_d = disk_free_space("D:");
?>
```
### Notes
> **Note**: This function will not work on [remote files](https://www.php.net/manual/en/features.remote-files.php) as the file to be examined must be accessible via the server's filesystem.
>
>
### See Also
* [disk\_total\_space()](function.disk-total-space) - Returns the total size of a filesystem or disk partition
| programming_docs |
php Yaf_Request_Http::getQuery Yaf\_Request\_Http::getQuery
============================
(Yaf >=1.0.0)
Yaf\_Request\_Http::getQuery — Fetch a query parameter
### Description
```
public Yaf_Request_Http::getQuery(string $name, string $default = ?): mixed
```
Retrieve GET variable
### Parameters
`name`
the variable name
`default`
if this parameter is provide, this will be returned if the variable can not be found
### Return Values
### See Also
* [Yaf\_Request\_Http::get()](yaf-request-http.get) - Retrieve variable from client
* [Yaf\_Request\_Http::getPost()](yaf-request-http.getpost) - Retrieve POST variable
* [Yaf\_Request\_Http::getCookie()](yaf-request-http.getcookie) - Retrieve Cookie variable
* [Yaf\_Request\_Http::getRaw()](yaf-request-http.getraw) - Retrieve Raw request body
* [Yaf\_Request\_Abstract::getServer()](yaf-request-abstract.getserver) - Retrieve SERVER variable
* [Yaf\_Request\_Abstract::getParam()](yaf-request-abstract.getparam) - Retrieve calling parameter
php socket_select socket\_select
==============
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket\_select — Runs the select() system call on the given arrays of sockets with a specified timeout
### Description
```
socket_select(
?array &$read,
?array &$write,
?array &$except,
?int $seconds,
int $microseconds = 0
): int|false
```
**socket\_select()** accepts arrays of sockets and waits for them to change status. Those coming with BSD sockets background will recognize that those socket arrays are in fact the so-called file descriptor sets. Three independent arrays of sockets are watched.
### Parameters
`read`
The sockets listed in the `read` array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a socket is also ready on end-of-file, in which case a [socket\_read()](function.socket-read) will return a zero length string).
`write`
The sockets listed in the `write` array will be watched to see if a write will not block.
`except`
The sockets listed in the `except` array will be watched for exceptions.
`seconds`
The `seconds` and `microseconds` together form the `timeout` parameter. The `timeout` is an upper bound on the amount of time elapsed before **socket\_select()** return. `seconds` may be zero , causing **socket\_select()** to return immediately. This is useful for polling. If `seconds` is **`null`** (no timeout), **socket\_select()** can block indefinitely.
`microseconds`
**Warning** On exit, the arrays are modified to indicate which socket actually changed status.
You do not need to pass every array to **socket\_select()**. You can leave it out and use an empty array or **`null`** instead. Also do not forget that those arrays are passed *by reference* and will be modified after **socket\_select()** returns.
>
> **Note**:
>
>
> Due a limitation in the current Zend Engine it is not possible to pass a constant modifier like **`null`** directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:
>
>
> **Example #1 Using **`null`** with **socket\_select()****
>
>
> ```
> <?php
> $e = NULL;
> socket_select($r, $w, $e, 0);
> ?>
> ```
>
### Return Values
On success **socket\_select()** returns the number of sockets contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens.On error **`false`** is returned. The error code can be retrieved with [socket\_last\_error()](function.socket-last-error).
>
> **Note**:
>
>
> Be sure to use the `===` operator when checking for an error. Since the **socket\_select()** may return 0 the comparison with `==` would evaluate to **`true`**:
>
>
> **Example #2 Understanding **socket\_select()**'s result**
>
>
> ```
> <?php
> $e = NULL;
> if (false === socket_select($r, $w, $e, 0)) {
> echo "socket_select() failed, reason: " .
> socket_strerror(socket_last_error()) . "\n";
> }
> ?>
> ```
>
### Examples
**Example #3 **socket\_select()** example**
```
<?php
/* Prepare the read array */
$read = array($socket1, $socket2);
$write = NULL;
$except = NULL;
$num_changed_sockets = socket_select($read, $write, $except, 0);
if ($num_changed_sockets === false) {
/* Error handling */
} else if ($num_changed_sockets > 0) {
/* At least at one of the sockets something interesting happened */
}
?>
```
### Notes
>
> **Note**:
>
>
> Be aware that some socket implementations need to be handled very carefully. A few basic rules:
>
>
> * You should always try to use **socket\_select()** without timeout. Your program should have nothing to do if there is no data available. Code that depends on timeouts is not usually portable and difficult to debug.
> * No socket must be added to any set if you do not intend to check its result after the **socket\_select()** call, and respond appropriately. After **socket\_select()** returns, all sockets in all arrays must be checked. Any socket that is available for writing must be written to, and any socket available for reading must be read from.
> * If you read/write to a socket returns in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.
> * It's common to most socket implementations that the only exception caught with the `except` array is out-of-bound data received on a socket.
>
>
### See Also
* [socket\_read()](function.socket-read) - Reads a maximum of length bytes from a socket
* [socket\_write()](function.socket-write) - Write to a socket
* [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket
* [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error
php IteratorIterator::current IteratorIterator::current
=========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
IteratorIterator::current — Get the current value
### Description
```
public IteratorIterator::current(): mixed
```
Get the value of the current element.
### Parameters
This function has no parameters.
### Return Values
The value of the current element.
### See Also
* [IteratorIterator::key()](iteratoriterator.key) - Get the key of the current element
php SplFileInfo::isWritable SplFileInfo::isWritable
=======================
(PHP 5 >= 5.1.2, PHP 7, PHP 8)
SplFileInfo::isWritable — Tells if the entry is writable
### Description
```
public SplFileInfo::isWritable(): bool
```
Checks if the current entry is writable.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if writable, **`false`** otherwise;
php ngettext ngettext
========
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
ngettext — Plural version of gettext
### Description
```
ngettext(string $singular, string $plural, int $count): string
```
The plural version of [gettext()](function.gettext). Some languages have more than one form for plural messages dependent on the count.
### Parameters
`singular`
The singular message ID.
`plural`
The plural message ID.
`count`
The number (e.g. item count) to determine the translation for the respective grammatical number.
### Return Values
Returns correct plural form of message identified by `singular` and `plural` for count `count`.
### Examples
**Example #1 **ngettext()** example**
```
<?php
setlocale(LC_ALL, 'cs_CZ');
printf(ngettext("%d window", "%d windows", 1), 1); // 1 okno
printf(ngettext("%d window", "%d windows", 2), 2); // 2 okna
printf(ngettext("%d window", "%d windows", 5), 5); // 5 oken
?>
```
php ReflectionFunctionAbstract::isDeprecated ReflectionFunctionAbstract::isDeprecated
========================================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
ReflectionFunctionAbstract::isDeprecated — Checks if deprecated
### Description
```
public ReflectionFunctionAbstract::isDeprecated(): bool
```
Checks whether the function is deprecated.
### Parameters
This function has no parameters.
### Return Values
**`true`** if it's deprecated, otherwise **`false`**
### Examples
**Example #1 **ReflectionFunctionAbstract::isDeprecated()** example**
```
<?php
$rf = new ReflectionFunction('ereg');
var_dump($rf->isDeprecated());
?>
```
The above example will output:
```
bool(true)
```
### See Also
* [ReflectionFunctionAbstract::getDocComment()](reflectionfunctionabstract.getdoccomment) - Gets doc comment
php Gmagick::setimageformat Gmagick::setimageformat
=======================
(PECL gmagick >= Unknown)
Gmagick::setimageformat — Sets the format of a particular image
### Description
```
public Gmagick::setimageformat(string $imageFormat): Gmagick
```
Sets the format of a particular image in a sequence.
### Parameters
`imageFormat`
The image format.
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php ImagickDraw::pathClose ImagickDraw::pathClose
======================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::pathClose — Adds a path element to the current path
### Description
```
public ImagickDraw::pathClose(): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Adds a path element to the current path which closes the current subpath by drawing a straight line from the current point to the current subpath's most recent starting point (usually, the most recent moveto point).
### Return Values
No value is returned.
php IntlChar::getBlockCode IntlChar::getBlockCode
======================
(PHP 7, PHP 8)
IntlChar::getBlockCode — Get the Unicode allocation block containing a code point
### Description
```
public static IntlChar::getBlockCode(int|string $codepoint): ?int
```
Returns the Unicode allocation block that contains the character.
### Parameters
`codepoint`
The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)
### Return Values
Returns the block value for `codepoint`. See the `IntlChar::BLOCK_CODE_*` constants for possible return values. Returns **`null`** on failure.
### Examples
**Example #1 Testing different code points**
```
<?php
var_dump(IntlChar::getBlockCode("A") === IntlChar::BLOCK_CODE_BASIC_LATIN);
var_dump(IntlChar::getBlockCode("Φ") === IntlChar::BLOCK_CODE_GREEK);
var_dump(IntlChar::getBlockCode("\u{2603}") === IntlChar::BLOCK_CODE_MISCELLANEOUS_SYMBOLS);
?>
```
The above example will output:
```
bool(true)
bool(true)
bool(true)
```
php log10 log10
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
log10 — Base-10 logarithm
### Description
```
log10(float $num): float
```
Returns the base-10 logarithm of `num`.
### Parameters
`num`
The argument to process
### Return Values
The base-10 logarithm of `num`
### See Also
* [log()](function.log) - Natural logarithm
php stats_dens_beta stats\_dens\_beta
=================
(PECL stats >= 1.0.0)
stats\_dens\_beta — Probability density function of the beta distribution
### Description
```
stats_dens_beta(float $x, float $a, float $b): float
```
Returns the probability density at `x`, where the random variable follows the beta distribution of which the shape parameters are `a` and `b`.
### Parameters
`x`
The value at which the probability density is calculated
`a`
The shape parameter of the distribution
`b`
The shape parameter of the distribution
### Return Values
The probability density at `x` or **`false`** for failure.
php read_exif_data read\_exif\_data
================
(PHP 4 >= 4.0.1, PHP 5, PHP 7)
read\_exif\_data — Alias of [exif\_read\_data()](function.exif-read-data)
**Warning**This alias was *DEPRECATED* in PHP 7.2.0, and *REMOVED* as of PHP 8.0.0.
### Description
This function is an alias of: [exif\_read\_data()](function.exif-read-data).
### Changelog
| Version | Description |
| --- | --- |
| 7.2.0 | This function alias was deprecated. |
php RecursiveCachingIterator::getChildren RecursiveCachingIterator::getChildren
=====================================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
RecursiveCachingIterator::getChildren — Return the inner iterator's children as a RecursiveCachingIterator
### Description
```
public RecursiveCachingIterator::getChildren(): ?RecursiveCachingIterator
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
The inner iterator's children, as a RecursiveCachingIterator; or **`null`** if there is no children.
php sapi_windows_cp_get sapi\_windows\_cp\_get
======================
(PHP 7 >= 7.1.0, PHP 8)
sapi\_windows\_cp\_get — Get current codepage
### Description
```
sapi_windows_cp_get(string $kind = ""): int
```
Gets the current codepage.
### Parameters
`kind`
The kind of operating system codepage to get, either `'ansi'` or `'oem'`. Any other value refers to the current codepage of the process.
### Return Values
If `kind` is `'ansi'`, the current ANSI code page of the operating system is returned. If `kind` is `'oem'`, the current OEM code page of the operating system is returned. Otherwise, the current codepage of the process is returned.
### See Also
* [sapi\_windows\_cp\_set()](function.sapi-windows-cp-set) - Set process codepage
php mailparse_msg_extract_part mailparse\_msg\_extract\_part
=============================
(PECL mailparse >= 0.9.0)
mailparse\_msg\_extract\_part — Extracts/decodes a message section
### Description
```
mailparse_msg_extract_part(resource $mimemail, string $msgbody, callable $callbackfunc = ?): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`mimemail`
A valid `MIME` resource.
`msgbody`
`callbackfunc`
### Return Values
No value is returned.
### See Also
* [mailparse\_msg\_extract\_part\_file()](function.mailparse-msg-extract-part-file) - Extracts/decodes a message section
* [mailparse\_msg\_extract\_whole\_part\_file()](function.mailparse-msg-extract-whole-part-file) - Extracts a message section including headers without decoding the transfer encoding
php setlocale setlocale
=========
(PHP 4, PHP 5, PHP 7, PHP 8)
setlocale — Set locale information
### Description
```
setlocale(int $category, string $locales, string ...$rest): string|false
```
Alternative signature (not supported with named arguments):
```
setlocale(int $category, array $locale_array): string|false
```
Sets locale information.
**Warning** The locale information is maintained per process, not per thread. If you are running PHP on a multithreaded server API , you may experience sudden changes in locale settings while a script is running, though the script itself never called **setlocale()**. This happens due to other scripts running in different threads of the same process at the same time, changing the process-wide locale using **setlocale()**. On Windows, locale information is maintained per thread as of PHP 7.0.5.
### Parameters
`category`
`category` is a named constant specifying the category of the functions affected by the locale setting:
* **`LC_ALL`** for all of the below
* **`LC_COLLATE`** for string comparison, see [strcoll()](function.strcoll)
* **`LC_CTYPE`** for character classification and conversion, for example [ctype\_alpha()](function.ctype-alpha)
* **`LC_MONETARY`** for [localeconv()](function.localeconv)
* **`LC_NUMERIC`** for decimal separator (See also [localeconv()](function.localeconv))
* **`LC_TIME`** for date and time formatting with [strftime()](function.strftime)
* **`LC_MESSAGES`** for system responses (available if PHP was compiled with `libintl`)
`locales`
If `locales` is the empty string `""`, the locale names will be set from the values of environment variables with the same names as the above categories, or from "LANG".
If `locales` is `"0"`, the locale setting is not affected, only the current setting is returned.
If `locales` is followed by additional parameters then each parameter is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.
`rest`
Optional string parameters to try as locale settings until success.
`locale_array`
Each array element is tried to be set as new locale until success. This is useful if a locale is known under different names on different systems or for providing a fallback for a possibly not available locale.
>
> **Note**:
>
>
> On Windows, setlocale(LC\_ALL, '') sets the locale names from the system's regional/language settings (accessible via Control Panel).
>
>
### Return Values
Returns the new current locale, or **`false`** if the locale functionality is not implemented on your platform, the specified locale does not exist or the category name is invalid.
An invalid category name also causes a warning message. Category/locale names can be found in [» RFC 1766](http://www.faqs.org/rfcs/rfc1766) and [» ISO 639](http://www.loc.gov/standards/iso639-2/php/code_list.php). Different systems have different naming schemes for locales.
>
> **Note**:
>
>
> The return value of **setlocale()** depends on the system that PHP is running. It returns exactly what the system `setlocale` function returns.
>
>
### Examples
**Example #1 **setlocale()** Examples**
```
<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nl_NL');
/* Output: vrijdag 22 december 1978 */
echo strftime("%A %e %B %Y", mktime(0, 0, 0, 12, 22, 1978));
/* try different possible locale names for german */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'de', 'ge');
echo "Preferred locale for german on this system is '$loc_de'";
?>
```
**Example #2 **setlocale()** Examples for Windows**
```
<?php
/* Set locale to Dutch */
setlocale(LC_ALL, 'nld_nld');
/* Output: vrijdag 22 december 1978 */
echo strftime("%A %d %B %Y", mktime(0, 0, 0, 12, 22, 1978));
/* try different possible locale names for german */
$loc_de = setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo "Preferred locale for german on this system is '$loc_de'";
?>
```
### Notes
**Tip** Windows users will find useful information about `locales` strings at Microsoft's MSDN website. Supported language strings can be found in the [» language strings documentation](http://msdn.microsoft.com/en-us/library/39cwe7zf%28v=vs.90%29.aspx) and supported country/region strings in the [» country/region strings documentation](http://msdn.microsoft.com/en-us/library/cdax410z%28v=vs.90%29.aspx).
php Componere\Patch::__construct Componere\Patch::\_\_construct
==============================
(Componere 2 >= 2.1.0)
Componere\Patch::\_\_construct — Patch Construction
### Description
public **Componere\Patch::\_\_construct**(object `$instance`)
public **Componere\Patch::\_\_construct**(object `$instance`, array `$interfaces`) ### Parameters
`instance`
The target for this Patch
`interfaces`
A case insensitive array of class names
### Exceptions
**Warning** Shall throw [RuntimeException](class.runtimeexception) if a class in `interfaces` cannot be found
**Warning** Shall throw [RuntimeException](class.runtimeexception) if an class in `interfaces` is not an interface
| programming_docs |
php The IteratorIterator class
The IteratorIterator class
==========================
Introduction
------------
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
This iterator wrapper allows the conversion of anything that is [Traversable](class.traversable) into an Iterator. It is important to understand that most classes that do not implement Iterators have reasons as most likely they do not allow the full Iterator feature set. If so, techniques should be provided to prevent misuse, otherwise expect exceptions or fatal errors.
Class synopsis
--------------
class **IteratorIterator** implements [OuterIterator](class.outeriterator) { /\* Methods \*/ public [\_\_construct](iteratoriterator.construct)([Traversable](class.traversable) `$iterator`, ?string `$class` = **`null`**)
```
public current(): mixed
```
```
public getInnerIterator(): ?Iterator
```
```
public key(): mixed
```
```
public next(): void
```
```
public rewind(): void
```
```
public valid(): bool
```
} Notes
-----
>
> **Note**:
>
>
> This class permits access to methods of the inner iterator via the \_\_call magic method.
>
>
Table of Contents
-----------------
* [IteratorIterator::\_\_construct](iteratoriterator.construct) — Create an iterator from anything that is traversable
* [IteratorIterator::current](iteratoriterator.current) — Get the current value
* [IteratorIterator::getInnerIterator](iteratoriterator.getinneriterator) — Get the inner iterator
* [IteratorIterator::key](iteratoriterator.key) — Get the key of the current element
* [IteratorIterator::next](iteratoriterator.next) — Forward to the next element
* [IteratorIterator::rewind](iteratoriterator.rewind) — Rewind to the first element
* [IteratorIterator::valid](iteratoriterator.valid) — Checks if the iterator is valid
php Imagick::sigmoidalContrastImage Imagick::sigmoidalContrastImage
===============================
(PECL imagick 2, PECL imagick 3)
Imagick::sigmoidalContrastImage — Adjusts the contrast of an image
### Description
```
public Imagick::sigmoidalContrastImage(
bool $sharpen,
float $alpha,
float $beta,
int $channel = Imagick::CHANNEL_DEFAULT
): bool
```
Adjusts the contrast of an image with a non-linear sigmoidal contrast algorithm. Increase the contrast of the image using a sigmoidal transfer function without saturating highlights or shadows. Contrast indicates how much to increase the contrast (0 is none; 3 is typical; 20 is pushing it); mid-point indicates where midtones fall in the resultant image (0 is white; 50 is middle-gray; 100 is black). Set sharpen to **`true`** to increase the image contrast otherwise the contrast is reduced.
See also [» ImageMagick v6 Examples - Image Transformations — Sigmoidal Non-linearity Contrast](http://www.imagemagick.org/Usage/color_mods/#sigmoidal)
### Parameters
`sharpen`
If true increase the contrast, if false decrease the contrast.
`alpha`
The amount of contrast to apply. 1 is very little, 5 is a significant amount, 20 is extreme.
`beta`
Where the midpoint of the gradient will be. This value should be in the range 0 to 1 - mutliplied by the quantum value for ImageMagick.
`channel`
Which color channels the contrast will be applied to.
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
### Examples
**Example #1 Create a gradient image using **Imagick::sigmoidalContrastImage()** suitable for blending two images together smoothly, with the blending defined by $contrast and $the midpoint**
```
<?php
function generateBlendImage($width, $height, $contrast = 10, $midpoint = 0.5) {
$imagick = new Imagick();
$imagick->newPseudoImage($width, $height, 'gradient:black-white');
$quanta = $imagick->getQuantumRange();
$imagick->sigmoidalContrastImage(true, $contrast, $midpoint * $quanta["quantumRangeLong"]);
return $imagick;
}
?>
```
php sqlsrv_fetch sqlsrv\_fetch
=============
(No version information available, might only be in Git)
sqlsrv\_fetch — Makes the next row in a result set available for reading
### Description
```
sqlsrv_fetch(resource $stmt, int $row = ?, int $offset = ?): mixed
```
Makes the next row in a result set available for reading. Use [sqlsrv\_get\_field()](function.sqlsrv-get-field) to read the fields of the row.
### Parameters
`stmt`
A statement resource created by executing [sqlsrv\_query()](function.sqlsrv-query) or [sqlsrv\_execute()](function.sqlsrv-execute).
`row`
The row to be accessed. This parameter can only be used if the specified statement was prepared with a scrollable cursor. In that case, this parameter can take on one of the following values:
* SQLSRV\_SCROLL\_NEXT
* SQLSRV\_SCROLL\_PRIOR
* SQLSRV\_SCROLL\_FIRST
* SQLSRV\_SCROLL\_LAST
* SQLSRV\_SCROLL\_ABSOLUTE
* SQLSRV\_SCROLL\_RELATIVE
`offset`
Specifies the row to be accessed if the row parameter is set to **`SQLSRV_SCROLL_ABSOLUTE`** or **`SQLSRV_SCROLL_RELATIVE`**. Note that the first row in a result set has index 0.
### Return Values
Returns **`true`** if the next row of a result set was successfully retrieved, **`false`** if an error occurs, and **`null`** if there are no more rows in the result set.
### Examples
**Example #1 **sqlsrv\_fetch()** example**
The following example demonstrates how to retrieve a row with **sqlsrv\_fetch()** and get the row fields with [sqlsrv\_get\_field()](function.sqlsrv-get-field).
```
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "SELECT Name, Comment
FROM Table_1
WHERE ReviewID=1";
$stmt = sqlsrv_query( $conn, $sql);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
// Make the first (and in this case, only) row of the result set available for reading.
if( sqlsrv_fetch( $stmt ) === false) {
die( print_r( sqlsrv_errors(), true));
}
// Get the row fields. Field indices start at 0 and must be retrieved in order.
// Retrieving row fields by name is not supported by sqlsrv_get_field.
$name = sqlsrv_get_field( $stmt, 0);
echo "$name: ";
$comment = sqlsrv_get_field( $stmt, 1);
echo $comment;
?>
```
### See Also
* [sqlsrv\_get\_field()](function.sqlsrv-get-field) - Gets field data from the currently selected row
* [sqlsrv\_fetch\_array()](function.sqlsrv-fetch-array) - Returns a row as an array
* [sqlsrv\_fetch\_object()](function.sqlsrv-fetch-object) - Retrieves the next row of data in a result set as an object
php str_rot13 str\_rot13
==========
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
str\_rot13 — Perform the rot13 transform on a string
### Description
```
str_rot13(string $string): string
```
Performs the ROT13 encoding on the `string` argument and returns the resulting string.
The ROT13 encoding simply shifts every letter by 13 places in the alphabet while leaving non-alpha characters untouched. Encoding and decoding are done by the same function, passing an encoded string as argument will return the original version.
### Parameters
`string`
The input string.
### Return Values
Returns the ROT13 version of the given string.
### Examples
**Example #1 **str\_rot13()** example**
```
<?php
echo str_rot13('PHP 4.3.0'); // CUC 4.3.0
?>
```
php Ds\Sequence::push Ds\Sequence::push
=================
(PECL ds >= 1.0.0)
Ds\Sequence::push — Adds values to the end of the sequence
### Description
```
abstract public Ds\Sequence::push(mixed ...$values): void
```
Adds values to the end of the sequence.
### Parameters
`values`
The values to add.
### Return Values
No value is returned.
### Examples
**Example #1 **Ds\Sequence::push()** example**
```
<?php
$sequence = new \Ds\Vector();
$sequence->push("a");
$sequence->push("b");
$sequence->push("c", "d");
$sequence->push(...["e", "f"]);
print_r($sequence);
?>
```
The above example will output something similar to:
```
Ds\Vector Object
(
[0] => a
[1] => b
[2] => c
[3] => d
[4] => e
[5] => f
)
```
php SolrQuery::addExpandSortField SolrQuery::addExpandSortField
=============================
(PECL solr >= 2.2.0)
SolrQuery::addExpandSortField — Orders the documents within the expanded groups (expand.sort parameter)
### Description
```
public SolrQuery::addExpandSortField(string $field, string $order = ?): SolrQuery
```
Orders the documents within the expanded groups (expand.sort parameter).
### Parameters
`field`
field name
`order`
Order ASC/DESC, utilizes SolrQuery::ORDER\_\* constants.
Default: SolrQuery::ORDER\_DESC
### Return Values
[SolrQuery](class.solrquery)
### See Also
* [SolrQuery::setExpand()](solrquery.setexpand) - Enables/Disables the Expand Component
* [SolrQuery::removeExpandSortField()](solrquery.removeexpandsortfield) - Removes an expand sort field from the expand.sort parameter
* [SolrQuery::setExpandRows()](solrquery.setexpandrows) - Sets the number of rows to display in each group (expand.rows). Server Default 5
* [SolrQuery::setExpandQuery()](solrquery.setexpandquery) - Sets the expand.q parameter
* [SolrQuery::addExpandFilterQuery()](solrquery.addexpandfilterquery) - Overrides main filter query, determines which documents to include in the main group
* [SolrQuery::removeExpandFilterQuery()](solrquery.removeexpandfilterquery) - Removes an expand filter query
php pspell_add_to_session pspell\_add\_to\_session
========================
(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)
pspell\_add\_to\_session — Add the word to the wordlist in the current session
### Description
```
pspell_add_to_session(PSpell\Dictionary $dictionary, string $word): bool
```
**pspell\_add\_to\_session()** adds a word to the wordlist associated with the current session. It is very similar to [pspell\_add\_to\_personal()](function.pspell-add-to-personal)
### Parameters
`dictionary`
An [PSpell\Dictionary](class.pspell-dictionary) instance.
`word`
The added word.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `dictionary` parameter expects an [PSpell\Dictionary](class.pspell-dictionary) instance now; previously, a [resource](language.types.resource) was expected. |
php ssdeep_fuzzy_compare ssdeep\_fuzzy\_compare
======================
(PECL ssdeep >= 1.0.0)
ssdeep\_fuzzy\_compare — Calculates the match score between two fuzzy hash signatures
### Description
```
ssdeep_fuzzy_compare(string $signature1, string $signature2): int
```
Calculates the match score between `signature1` and `signature2` using [» context-triggered piecewise hashing](http://dfrws.org/2006/proceedings/12-Kornblum.pdf), and returns the match score.
### Parameters
`signature1`
The first fuzzy hash signature string.
`signature2`
The second fuzzy hash signature string.
### Return Values
Returns an integer from 0 to 100 on success, **`false`** otherwise.
php openssl_verify openssl\_verify
===============
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
openssl\_verify — Verify signature
### Description
```
openssl_verify(
string $data,
string $signature,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key,
string|int $algorithm = OPENSSL_ALGO_SHA1
): int|false
```
**openssl\_verify()** verifies that the `signature` is correct for the specified `data` using the public key associated with `public_key`. This must be the public key corresponding to the private key used for signing.
### Parameters
`data`
The string of data used to generate the signature previously
`signature`
A raw binary string, generated by [openssl\_sign()](function.openssl-sign) or similar means
`public_key`
[OpenSSLAsymmetricKey](class.opensslasymmetrickey) - a key, returned by [openssl\_get\_publickey()](function.openssl-get-publickey)
string - a PEM formatted key, example, "-----BEGIN PUBLIC KEY----- MIIBCgK..."
`algorithm`
int - one of these [Signature Algorithms](https://www.php.net/manual/en/openssl.signature-algos.php).
string - a valid string returned by [openssl\_get\_md\_methods()](function.openssl-get-md-methods) example, "sha1WithRSAEncryption" or "sha512".
### Return Values
Returns 1 if the signature is correct, 0 if it is incorrect, and -1 or **`false`** on error.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `public_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) or [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` or `OpenSSL X.509` was accepted. |
### Examples
**Example #1 **openssl\_verify()** example**
```
<?php
// $data and $signature are assumed to contain the data and the signature
// fetch public key from certificate and ready it
$pubkeyid = openssl_pkey_get_public("file://src/openssl-0.9.6/demos/sign/cert.pem");
// state whether signature is okay or not
$ok = openssl_verify($data, $signature, $pubkeyid);
if ($ok == 1) {
echo "good";
} elseif ($ok == 0) {
echo "bad";
} else {
echo "ugly, error checking signature";
}
// free the key from memory
openssl_free_key($pubkeyid);
?>
```
**Example #2 **openssl\_verify()** example**
```
<?php
//data you want to sign
$data = 'my data';
//create new private and public key
$private_key_res = openssl_pkey_new(array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
));
$details = openssl_pkey_get_details($private_key_res);
$public_key_res = openssl_pkey_get_public($details['key']);
//create signature
openssl_sign($data, $signature, $private_key_res, "sha256WithRSAEncryption");
//verify signature
$ok = openssl_verify($data, $signature, $public_key_res, OPENSSL_ALGO_SHA256);
if ($ok == 1) {
echo "valid";
} elseif ($ok == 0) {
echo "invalid";
} else {
echo "error: ".openssl_error_string();
}
?>
```
### See Also
* [openssl\_sign()](function.openssl-sign) - Generate signature
php GearmanWorker::addFunction GearmanWorker::addFunction
==========================
(PECL gearman >= 0.5.0)
GearmanWorker::addFunction — Register and add callback function
### Description
```
public GearmanWorker::addFunction(
string $function_name,
callable $function,
mixed &$context = ?,
int $timeout = ?
): bool
```
Registers a function name with the job server and specifies a callback corresponding to that function. Optionally specify extra application context data to be used when the callback is called and a timeout.
### Parameters
`function_name`
The name of a function to register with the job server
`function`
A callback that gets called when a job for the registered function name is submitted
`context`
A reference to arbitrary application context data that can be modified by the worker function
`timeout`
An interval of time in seconds
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Simple worker making use of extra application context data**
```
<?php
# get a gearman worker
$worker= new GearmanWorker();
# add the default server (localhost)
$worker->addServer();
# define a variable to hold application data
$count= 0;
# add the "reverse" function
$worker->addFunction("reverse", "reverse_cb", $count);
# start the worker
while ($worker->work());
function reverse_cb($job, &$count)
{
$count++;
return "$count: " . strrev($job->workload());
}
?>
```
Running a client that submits two jobs for the reverse function would have output similar to the following:
```
1: olleh
2: dlrow
```
### See Also
* [GearmanClient::do()](gearmanclient.do) - Run a single task and return a result [deprecated]
php imageloadfont imageloadfont
=============
(PHP 4, PHP 5, PHP 7, PHP 8)
imageloadfont — Load a new font
### Description
```
imageloadfont(string $filename): GdFont|false
```
**imageloadfont()** loads a user-defined bitmap and returns its identifier.
### Parameters
`filename`
The font file format is currently binary and architecture dependent. This means you should generate the font files on the same type of CPU as the machine you are running PHP on.
**Font file format**| byte position | C data type | description |
| --- | --- | --- |
| byte 0-3 | int | number of characters in the font |
| byte 4-7 | int | value of first character in the font (often 32 for space) |
| byte 8-11 | int | pixel width of each character |
| byte 12-15 | int | pixel height of each character |
| byte 16- | char | array with character data, one byte per pixel in each character, for a total of (nchars\*width\*height) bytes. |
### Return Values
Returns an [GdFont](class.gdfont) instance, or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | Returns an [GdFont](class.gdfont) instance now; previously, an int was returned. |
### Examples
**Example #1 **imageloadfont()** usage example**
```
<?php
// Create a new image instance
$im = imagecreatetruecolor(50, 20);
$black = imagecolorallocate($im, 0, 0, 0);
$white = imagecolorallocate($im, 255, 255, 255);
// Make the background white
imagefilledrectangle($im, 0, 0, 49, 19, $white);
// Load the gd font and write 'Hello'
$font = imageloadfont('./04b.gdf');
imagestring($im, $font, 0, 0, 'Hello', $black);
// Output to browser
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
?>
```
### See Also
* [imagefontwidth()](function.imagefontwidth) - Get font width
* [imagefontheight()](function.imagefontheight) - Get font height
php exit exit
====
(PHP 4, PHP 5, PHP 7, PHP 8)
exit — Output a message and terminate the current script
### Description
```
exit(string $status = ?): void
```
```
exit(int $status): void
```
Terminates execution of the script. [Shutdown functions](function.register-shutdown-function) and [object destructors](language.oop5.decon#language.oop5.decon.destructor) will always be executed even if `exit` is called.
`exit` is a language construct and it can be called without parentheses if no `status` is passed.
### Parameters
`status`
If `status` is a string, this function prints the `status` just before exiting.
If `status` is an int, that value will be used as the exit status and not printed. Exit statuses should be in the range 0 to 254, the exit status 255 is reserved by PHP and shall not be used. The status 0 is used to terminate the program successfully.
### Return Values
No value is returned.
### Examples
**Example #1 `exit` example**
```
<?php
$filename = '/path/to/data-file';
$file = fopen($filename, 'r')
or exit("unable to open file ($filename)");
?>
```
**Example #2 `exit` status example**
```
<?php
//exit program normally
exit;
exit();
exit(0);
//exit with an error code
exit(1);
exit(0376); //octal
?>
```
**Example #3 Shutdown functions and destructors run regardless**
```
<?php
class Foo
{
public function __destruct()
{
echo 'Destruct: ' . __METHOD__ . '()' . PHP_EOL;
}
}
function shutdown()
{
echo 'Shutdown: ' . __FUNCTION__ . '()' . PHP_EOL;
}
$foo = new Foo();
register_shutdown_function('shutdown');
exit();
echo 'This will not be output.';
?>
```
The above example will output:
```
Shutdown: shutdown()
Destruct: Foo::__destruct()
```
### Notes
> **Note**: Because this is a language construct and not a function, it cannot be called using [variable functions](functions.variable-functions), or [named arguments](functions.arguments#functions.named-arguments).
>
>
>
> **Note**:
>
>
> This language construct is equivalent to [die()](function.die).
>
>
### See Also
* [register\_shutdown\_function()](function.register-shutdown-function) - Register a function for execution on shutdown
| programming_docs |
php IntlDateFormatter::formatObject IntlDateFormatter::formatObject
===============================
datefmt\_format\_object
=======================
(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL intl >= 3.0.0)
IntlDateFormatter::formatObject -- datefmt\_format\_object — Formats an object
### Description
Object-oriented style
```
public static IntlDateFormatter::formatObject(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false
```
Procedural style
```
datefmt_format_object(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false
```
This function allows formatting an [IntlCalendar](class.intlcalendar) or [DateTime](class.datetime) object without first explicitly creating a [IntlDateFormatter](class.intldateformatter) object.
The temporary [IntlDateFormatter](class.intldateformatter) that will be created will take the timezone from the passed in object. The timezone database bundled with PHP will not be used – ICU's will be used instead. The timezone identifier used in [DateTime](class.datetime) objects must therefore also exist in ICU's database.
### Parameters
`datetime`
An object of type [IntlCalendar](class.intlcalendar) or [DateTime](class.datetime). The timezone information in the object will be used.
`format`
How to format the date/time. This can either be an array with two elements (first the date style, then the time style, these being one of the constants **`IntlDateFormatter::NONE`**, **`IntlDateFormatter::SHORT`**, **`IntlDateFormatter::MEDIUM`**, **`IntlDateFormatter::LONG`**, **`IntlDateFormatter::FULL`**), an int with the value of one of these constants (in which case it will be used both for the time and the date) or a string with the format described in [» the ICU documentation](https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax). If **`null`**, the default style will be used.
`locale`
The locale to use, or **`null`** to use the [default one](https://www.php.net/manual/en/intl.configuration.php#ini.intl.default-locale).
### Return Values
A string with result or **`false`** on failure.
### Examples
**Example #1 **IntlDateFormatter::formatObject()** examples**
```
<?php
/* default timezone is irrelevant; timezone taken from the object */
ini_set('date.timezone', 'UTC');
/* default locale is taken from this ini setting */
ini_set('intl.default_locale', 'fr_FR');
$cal = IntlCalendar::fromDateTime("2013-06-06 17:05:06 Europe/Dublin");
echo "default:\n\t",
IntlDateFormatter::formatObject($cal),
"\n";
echo "long \$format (full):\n\t",
IntlDateFormatter::formatObject($cal, IntlDateFormatter::FULL),
"\n";
echo "array \$format (none, full):\n\t",
IntlDateFormatter::formatObject($cal, array(
IntlDateFormatter::NONE,
IntlDateFormatter::FULL)),
"\n";
echo "string \$format (d 'of' MMMM y):\n\t",
IntlDateFormatter::formatObject($cal, "d 'of' MMMM y", 'en_US'),
"\n";
echo "with DateTime:\n\t",
IntlDateFormatter::formatObject(
new DateTime("2013-09-09 09:09:09 Europe/Madrid"),
IntlDateFormatter::FULL,
'es_ES'),
"\n";
```
The above example will output:
```
default:
6 juin 2013 17:05:06
long $format (full):
jeudi 6 juin 2013 17:05:06 heure d’été irlandaise
array $format (none, full):
17:05:06 heure d’été irlandaise
string $format (d 'of' MMMM y):
6 of June 2013
with DateTime:
lunes, 9 de septiembre de 2013 09:09:09 Hora de verano de Europa central
```
php socket_last_error socket\_last\_error
===================
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket\_last\_error — Returns the last error on the socket
### Description
```
socket_last_error(?Socket $socket = null): int
```
If a [Socket](class.socket) instance is passed to this function, the last error which occurred on this particular socket is returned. If `socket` is **`null`**, the error code of the last failed socket function is returned. The latter is particularly helpful for functions like [socket\_create()](function.socket-create) which don't return a socket on failure and [socket\_select()](function.socket-select) which can fail for reasons not directly tied to a particular socket. The error code is suitable to be fed to [socket\_strerror()](function.socket-strerror) which returns a string describing the given error code.
If no error had occurred, or the error had been cleared with [socket\_clear\_error()](function.socket-clear-error), the function returns `0`.
### Parameters
`socket`
A [Socket](class.socket) instance created with [socket\_create()](function.socket-create).
### Return Values
This function returns a socket error code.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. |
| 8.0.0 | `socket` is nullable now. |
### Examples
**Example #1 **socket\_last\_error()** example**
```
<?php
$socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Couldn't create socket: [$errorcode] $errormsg");
}
?>
```
### Notes
>
> **Note**:
>
>
> **socket\_last\_error()** does not clear the error code, use [socket\_clear\_error()](function.socket-clear-error) for this purpose.
>
>
php SplPriorityQueue::insert SplPriorityQueue::insert
========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplPriorityQueue::insert — Inserts an element in the queue by sifting it up
### Description
```
public SplPriorityQueue::insert(mixed $value, mixed $priority): bool
```
Insert `value` with the priority `priority` in the queue.
### Parameters
`value`
The value to insert.
`priority`
The associated priority.
### Return Values
Returns **`true`**.
php Yaf_Config_Ini::__set Yaf\_Config\_Ini::\_\_set
=========================
(Yaf >=1.0.0)
Yaf\_Config\_Ini::\_\_set — The \_\_set purpose
### Description
```
public Yaf_Config_Ini::__set(string $name, mixed $value): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`name`
`value`
### Return Values
php The HashContext class
The HashContext class
=====================
Introduction
------------
(PHP 7 >= 7.2.0, PHP 8)
Class synopsis
--------------
final class **HashContext** { /\* Methods \*/ private [\_\_construct](hashcontext.construct)()
```
public __serialize(): array
```
```
public __unserialize(array $data): void
```
} Table of Contents
-----------------
* [HashContext::\_\_construct](hashcontext.construct) — Private constructor to disallow direct instantiation
* [HashContext::\_\_serialize](hashcontext.serialize) — Serializes the HashContext object
* [HashContext::\_\_unserialize](hashcontext.unserialize) — Deserializes the data parameter into a HashContext object
php Event::setTimer Event::setTimer
===============
(PECL event >= 1.2.6-beta)
Event::setTimer — Re-configures timer event
### Description
```
public Event::setTimer( EventBase $base , callable $cb , mixed $arg = ?): bool
```
Re-configures timer event. Note, this function doesn't invoke obsolete libevent's `event_set` . It calls `event_assign` instead.
### Parameters
`base` The event base to associate with.
`cb` The timer event callback. See [Event callbacks](https://www.php.net/manual/en/event.callbacks.php) .
`arg` Custom data. If specified, it will be passed to the callback when event triggers.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [Event::\_\_construct()](event.construct) - Constructs Event object
* [Event::timer()](event.timer) - Constructs timer event object
php IntlChar::getUnicodeVersion IntlChar::getUnicodeVersion
===========================
(PHP 7, PHP 8)
IntlChar::getUnicodeVersion — Get the Unicode version
### Description
```
public static IntlChar::getUnicodeVersion(): array
```
Gets the Unicode version information.
The version array is filled in with the version information for the Unicode standard that is currently used by ICU. For example, Unicode version 3.1.1 is represented as an array with the values `[3, 1, 1, 0]`.
### Parameters
This function has no parameters.
### Return Values
An array containing the Unicode version number.
### Examples
**Example #1 Testing different properties**
```
<?php
var_dump(IntlChar::getUnicodeVersion());
?>
```
The above example will output:
```
array(4) {
[0]=>
int(7)
[1]=>
int(0)
[2]=>
int(0)
[3]=>
int(0)
}
```
### See Also
* [IntlChar::charAge()](intlchar.charage) - Get the "age" of the code point
php The IntlDateFormatter class
The IntlDateFormatter class
===========================
Introduction
------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
Date Formatter is a concrete class that enables locale-dependent formatting/parsing of dates using pattern strings and/or canned patterns.
This class represents the ICU date formatting functionality. It allows users to display dates in a localized format or to parse strings into PHP date values using pattern strings and/or canned patterns.
Class synopsis
--------------
class **IntlDateFormatter** { /\* Methods \*/ public [\_\_construct](intldateformatter.create)(
?string `$locale`,
int `$dateType` = IntlDateFormatter::FULL,
int `$timeType` = IntlDateFormatter::FULL,
[IntlTimeZone](class.intltimezone)|[DateTimeZone](class.datetimezone)|string|null `$timezone` = **`null`**,
[IntlCalendar](class.intlcalendar)|int|null `$calendar` = **`null`**,
?string `$pattern` = **`null`**
)
```
public static create(
?string $locale,
int $dateType = IntlDateFormatter::FULL,
int $timeType = IntlDateFormatter::FULL,
IntlTimeZone|DateTimeZone|string|null $timezone = null,
IntlCalendar|int|null $calendar = null,
?string $pattern = null
): ?IntlDateFormatter
```
```
public format(IntlCalendar|DateTimeInterface|array|string|int|float $datetime): string|false
```
```
public static formatObject(IntlCalendar|DateTimeInterface $datetime, array|int|string|null $format = null, ?string $locale = null): string|false
```
```
public getCalendar(): int|false
```
```
public getDateType(): int|false
```
```
public getErrorCode(): int
```
```
public getErrorMessage(): string
```
```
public getLocale(int $type = ULOC_ACTUAL_LOCALE): string|false
```
```
public getPattern(): string|false
```
```
public getTimeType(): int|false
```
```
public getTimeZoneId(): string|false
```
```
public getCalendarObject(): IntlCalendar|false|null
```
```
public getTimeZone(): IntlTimeZone|false
```
```
public isLenient(): bool
```
```
public localtime(string $string, int &$offset = null): array|false
```
```
public parse(string $string, int &$offset = null): int|float|false
```
```
public setCalendar(IntlCalendar|int|null $calendar): bool
```
```
public setLenient(bool $lenient): void
```
```
public setPattern(string $pattern): bool
```
```
public setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): ?bool
```
} See Also
--------
* [» ICU Date formatter](http://www.icu-project.org/apiref/icu4c/udat_8h.html#details)
* [» ICU Date formats](https://unicode-org.github.io/icu/userguide/format_parse/datetime/#datetime-format-syntax)
Predefined Constants
--------------------
These constants are used to specify different formats in the constructor for DateType and TimeType.
**`IntlDateFormatter::NONE`** (int) Do not include this element **`IntlDateFormatter::FULL`** (int) Completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST) **`IntlDateFormatter::LONG`** (int) Long style (January 12, 1952 or 3:30:32pm) **`IntlDateFormatter::MEDIUM`** (int) Medium style (Jan 12, 1952) **`IntlDateFormatter::SHORT`** (int) Most abbreviated style, only essential data (12/13/52 or 3:30pm) **`IntlDateFormatter::RELATIVE_FULL`** (int) The same as **`IntlDateFormatter::FULL`**, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only. **`IntlDateFormatter::RELATIVE_LONG`** (int) The same as **`IntlDateFormatter::LONG`**, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only. **`IntlDateFormatter::RELATIVE_MEDIUM`** (int) The same as **`IntlDateFormatter::MEDIUM`**, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only. **`IntlDateFormatter::RELATIVE_SHORT`** (int) The same as **`IntlDateFormatter::SHORT`**, but yesterday, today, and tomorrow show as `yesterday`, `today`, and `tomorrow`, respectively. Available as of PHP 8.0.0, for `dateType` only. The following int constants are used to specify the calendar. These calendars are all based directly on the Gregorian calendar. Non-Gregorian calendars need to be specified in locale. Examples might include locale="hi@calendar=BUDDHIST".
**`IntlDateFormatter::TRADITIONAL`** (int) Non-Gregorian Calendar **`IntlDateFormatter::GREGORIAN`** (int) Gregorian Calendar Table of Contents
-----------------
* [IntlDateFormatter::create](intldateformatter.create) — Create a date formatter
* [IntlDateFormatter::format](intldateformatter.format) — Format the date/time value as a string
* [IntlDateFormatter::formatObject](intldateformatter.formatobject) — Formats an object
* [IntlDateFormatter::getCalendar](intldateformatter.getcalendar) — Get the calendar type used for the IntlDateFormatter
* [IntlDateFormatter::getDateType](intldateformatter.getdatetype) — Get the datetype used for the IntlDateFormatter
* [IntlDateFormatter::getErrorCode](intldateformatter.geterrorcode) — Get the error code from last operation
* [IntlDateFormatter::getErrorMessage](intldateformatter.geterrormessage) — Get the error text from the last operation
* [IntlDateFormatter::getLocale](intldateformatter.getlocale) — Get the locale used by formatter
* [IntlDateFormatter::getPattern](intldateformatter.getpattern) — Get the pattern used for the IntlDateFormatter
* [IntlDateFormatter::getTimeType](intldateformatter.gettimetype) — Get the timetype used for the IntlDateFormatter
* [IntlDateFormatter::getTimeZoneId](intldateformatter.gettimezoneid) — Get the timezone-id used for the IntlDateFormatter
* [IntlDateFormatter::getCalendarObject](intldateformatter.getcalendarobject) — Get copy of formatterʼs calendar object
* [IntlDateFormatter::getTimeZone](intldateformatter.gettimezone) — Get formatterʼs timezone
* [IntlDateFormatter::isLenient](intldateformatter.islenient) — Get the lenient used for the IntlDateFormatter
* [IntlDateFormatter::localtime](intldateformatter.localtime) — Parse string to a field-based time value
* [IntlDateFormatter::parse](intldateformatter.parse) — Parse string to a timestamp value
* [IntlDateFormatter::setCalendar](intldateformatter.setcalendar) — Sets the calendar type used by the formatter
* [IntlDateFormatter::setLenient](intldateformatter.setlenient) — Set the leniency of the parser
* [IntlDateFormatter::setPattern](intldateformatter.setpattern) — Set the pattern used for the IntlDateFormatter
* [IntlDateFormatter::setTimeZone](intldateformatter.settimezone) — Sets formatterʼs timezone
php is_scalar is\_scalar
==========
(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)
is\_scalar — Finds whether a variable is a scalar
### Description
```
is_scalar(mixed $value): bool
```
Finds whether the given variable is a scalar.
Scalar variables are those containing an int, float, string or bool. Types array, object, resource and null are not scalar.
>
> **Note**:
>
>
> **is\_scalar()** does not consider resource type values to be scalar as resources are abstract datatypes which are currently based on integers. This implementation detail should not be relied upon, as it may change.
>
>
>
> **Note**:
>
>
> **is\_scalar()** does not consider NULL to be scalar.
>
>
### Parameters
`value`
The variable being evaluated.
### Return Values
Returns **`true`** if `value` is a scalar, **`false`** otherwise.
### Examples
**Example #1 **is\_scalar()** example**
```
<?php
function show_var($var)
{
if (is_scalar($var)) {
echo $var;
} else {
var_dump($var);
}
}
$pi = 3.1416;
$proteins = array("hemoglobin", "cytochrome c oxidase", "ferredoxin");
show_var($pi);
show_var($proteins)
?>
```
The above example will output:
```
3.1416
array(3) {
[0]=>
string(10) "hemoglobin"
[1]=>
string(20) "cytochrome c oxidase"
[2]=>
string(10) "ferredoxin"
}
```
### See Also
* [is\_float()](function.is-float) - Finds whether the type of a variable is float
* [is\_int()](function.is-int) - Find whether the type of a variable is integer
* [is\_numeric()](function.is-numeric) - Finds whether a variable is a number or a numeric string
* [is\_real()](function.is-real) - Alias of is\_float
* [is\_string()](function.is-string) - Find whether the type of a variable is string
* [is\_bool()](function.is-bool) - Finds out whether a variable is a boolean
* [is\_object()](function.is-object) - Finds whether a variable is an object
* [is\_array()](function.is-array) - Finds whether a variable is an array
php DOMElement::removeAttributeNode DOMElement::removeAttributeNode
===============================
(PHP 5, PHP 7, PHP 8)
DOMElement::removeAttributeNode — Removes attribute
### Description
```
public DOMElement::removeAttributeNode(DOMAttr $attr): DOMAttr|false
```
Removes attribute `attr` from the element.
### Parameters
`attr`
The attribute node.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Errors/Exceptions
**`DOM_NO_MODIFICATION_ALLOWED_ERR`**
Raised if the node is readonly.
**`DOM_NOT_FOUND_ERROR`**
Raised if `attr` is not an attribute of the element.
### See Also
* [DOMElement::hasAttribute()](domelement.hasattribute) - Checks to see if attribute exists
* [DOMElement::getAttributeNode()](domelement.getattributenode) - Returns attribute node
* [DOMElement::setAttributeNode()](domelement.setattributenode) - Adds new attribute node to element
php XMLWriter::endComment XMLWriter::endComment
=====================
xmlwriter\_end\_comment
=======================
(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0)
XMLWriter::endComment -- xmlwriter\_end\_comment — Create end comment
### Description
Object-oriented style
```
public XMLWriter::endComment(): bool
```
Procedural style
```
xmlwriter_end_comment(XMLWriter $writer): bool
```
Ends the current comment.
### Parameters
`writer`
Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. |
### See Also
* [XMLWriter::startComment()](xmlwriter.startcomment) - Create start comment
* [XMLWriter::writeComment()](xmlwriter.writecomment) - Write full comment tag
| programming_docs |
php Yaf_Request_Abstract::isGet Yaf\_Request\_Abstract::isGet
=============================
(Yaf >=1.0.0)
Yaf\_Request\_Abstract::isGet — Determine if request is GET request
### Description
```
public Yaf_Request_Abstract::isGet(): bool
```
### Parameters
This function has no parameters.
### Return Values
boolean
### See Also
* [Yaf\_Request\_Abstract::isHead()](yaf-request-abstract.ishead) - Determine if request is HEAD request
* [Yaf\_Request\_Abstract::isCli()](yaf-request-abstract.iscli) - Determine if request is CLI request
* [Yaf\_Request\_Abstract::isPost()](yaf-request-abstract.ispost) - Determine if request is POST request
* [Yaf\_Request\_Abstract::isPut()](yaf-request-abstract.isput) - Determine if request is PUT request
* [Yaf\_Request\_Abstract::isOptions()](yaf-request-abstract.isoptions) - Determine if request is OPTIONS request
* [Yaf\_Request\_Abstract::isXmlHTTPRequest()](yaf-request-abstract.isxmlhttprequest) - Determine if request is AJAX request
php sleep sleep
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
sleep — Delay execution
### Description
```
sleep(int $seconds): int
```
Delays the program execution for the given number of `seconds`.
>
> **Note**:
>
>
> In order to delay program execution for a fraction of a second, use [usleep()](function.usleep) as the **sleep()** function expects an int. For example, `sleep(0.25)` will pause program execution for `0` seconds.
>
>
### Parameters
`seconds`
Halt time in seconds (must be greater than or equal to `0`).
### Return Values
Returns zero on success.
If the call was interrupted by a signal, **sleep()** returns a non-zero value. On Windows, this value will always be `192` (the value of the **`WAIT_IO_COMPLETION`** constant within the Windows API). On other platforms, the return value will be the number of seconds left to sleep.
### Errors/Exceptions
If the specified number of `seconds` is negative, this function will throw a [ValueError](class.valueerror).
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | The function throws a [ValueError](class.valueerror) on negative `seconds`; previously, an **`E_WARNING`** was raised instead, and the function returned **`false`**. |
### Examples
**Example #1 **sleep()** example**
```
<?php
// current time
echo date('h:i:s') . "\n";
// sleep for 10 seconds
sleep(10);
// wake up !
echo date('h:i:s') . "\n";
?>
```
This example will output (after 10 seconds)
```
05:31:23
05:31:33
```
### See Also
* [usleep()](function.usleep) - Delay execution in microseconds
* [time\_nanosleep()](function.time-nanosleep) - Delay for a number of seconds and nanoseconds
* [time\_sleep\_until()](function.time-sleep-until) - Make the script sleep until the specified time
* [set\_time\_limit()](function.set-time-limit) - Limits the maximum execution time
php eio_fchmod eio\_fchmod
===========
(PECL eio >= 0.0.1dev)
eio\_fchmod — Change file permissions
### Description
```
eio_fchmod(
mixed $fd,
int $mode,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource
```
**eio\_fchmod()** changes permissions for the file specified by `fd` file descriptor.
### Parameters
`fd`
Stream, Socket resource, or numeric file descriptor, e.g. returned by [eio\_open()](function.eio-open).
`mode`
The new permissions. E.g. 0644.
`pri`
The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**.
`callback`
`callback` function is called when the request is done. It should match the following prototype:
```
void callback(mixed $data, int $result[, resource $req]);
```
`data`
is custom data passed to the request.
`result`
request-specific result value; basically, the value returned by corresponding system call.
`req`
is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error)
`data`
Arbitrary variable passed to `callback`.
### Return Values
**eio\_fchmod()** returns request resource on success, or **`false`** on failure.
### See Also
* [eio\_fchown()](function.eio-fchown) - Change file ownership
php ZipArchive::count ZipArchive::count
=================
(PHP 7 >= 7.2.0, PHP 8, PECL zip >= 1.15.0)
ZipArchive::count — Counts the number of files in the archive
### Description
```
public ZipArchive::count(): int
```
### Parameters
This function has no parameters.
### Return Values
Returns the number of files in the archive.
php exif_thumbnail exif\_thumbnail
===============
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
exif\_thumbnail — Retrieve the embedded thumbnail of an image
### Description
```
exif_thumbnail(
resource|string $file,
int &$width = null,
int &$height = null,
int &$image_type = null
): string|false
```
**exif\_thumbnail()** reads the embedded thumbnail of an image.
If you want to deliver thumbnails through this function, you should send the mimetype information using the [header()](function.header) function.
It is possible that **exif\_thumbnail()** cannot create an image but can determine its size. In this case, the return value is **`false`** but `width` and `height` are set.
### Parameters
`file`
The location of the image file. This can either be a path to the file or a stream resource.
`width`
The return width of the returned thumbnail.
`height`
The returned height of the returned thumbnail.
`image_type`
The returned image type of the returned thumbnail. This is either TIFF or JPEG.
### Return Values
Returns the embedded thumbnail, or **`false`** if the image contains no thumbnail.
### Changelog
| Version | Description |
| --- | --- |
| 7.2.0 | The `file` parameter now supports both local files and stream resources. |
### Examples
**Example #1 **exif\_thumbnail()** example**
```
<?php
$image = exif_thumbnail('/path/to/image.jpg', $width, $height, $type);
if ($image!==false) {
header('Content-type: ' .image_type_to_mime_type($type));
echo $image;
exit;
} else {
// no thumbnail available, handle the error here
echo 'No thumbnail available';
}
?>
```
### Notes
>
> **Note**:
>
>
> If the `file` is used to pass a stream to this function, then the stream must be seekable. Note that the file pointer position is not changed after this function returns.
>
>
### See Also
* [exif\_read\_data()](function.exif-read-data) - Reads the EXIF headers from an image file
* [image\_type\_to\_mime\_type()](function.image-type-to-mime-type) - Get Mime-Type for image-type returned by getimagesize, exif\_read\_data, exif\_thumbnail, exif\_imagetype
php getmxrr getmxrr
=======
(PHP 4, PHP 5, PHP 7, PHP 8)
getmxrr — Get MX records corresponding to a given Internet host name
### Description
```
getmxrr(string $hostname, array &$hosts, array &$weights = null): bool
```
Searches DNS for MX records corresponding to `hostname`.
### Parameters
`hostname`
The Internet host name.
`hosts`
A list of the MX records found is placed into the array `hosts`.
`weights`
If the `weights` array is given, it will be filled with the weight information gathered.
### Return Values
Returns **`true`** if any records are found; returns **`false`** if no records were found or if an error occurred.
### Notes
>
> **Note**:
>
>
> This function should not be used for the purposes of address verification. Only the mailexchangers found in DNS are returned, however, according to [» RFC 2821](http://www.faqs.org/rfcs/rfc2821) when no mail exchangers are listed, `hostname` itself should be used as the only mail exchanger with a priority of `0`.
>
>
>
> **Note**:
>
>
> For compatibility with Windows before this was implemented, then try the [» PEAR](https://pear.php.net/) class [» Net\_DNS](https://pear.php.net/package/Net_DNS).
>
>
### See Also
* [checkdnsrr()](function.checkdnsrr) - Check DNS records corresponding to a given Internet host name or IP address
* [dns\_get\_record()](function.dns-get-record) - Fetch DNS Resource Records associated with a hostname
* [gethostbyname()](function.gethostbyname) - Get the IPv4 address corresponding to a given Internet host name
* [gethostbynamel()](function.gethostbynamel) - Get a list of IPv4 addresses corresponding to a given Internet host name
* [gethostbyaddr()](function.gethostbyaddr) - Get the Internet host name corresponding to a given IP address
* the `named(8)` manual page
php imap_headerinfo imap\_headerinfo
================
(PHP 4, PHP 5, PHP 7, PHP 8)
imap\_headerinfo — Read the header of the message
### Description
```
imap_headerinfo(
IMAP\Connection $imap,
int $message_num,
int $from_length = 0,
int $subject_length = 0
): stdClass|false
```
Gets information about the given message number by reading its headers.
### Parameters
`imap`
An [IMAP\Connection](class.imap-connection) instance.
`message_num`
The message number
`from_length`
Number of characters for the `fetchfrom` property. Must be greater than or equal to zero.
`subject_length`
Number of characters for the `fetchsubject` property Must be greater than or equal to zero.
`defaulthost`
### Return Values
Returns **`false`** on error or, if successful, the information in an object with following properties:
* toaddress - full to: line, up to 1024 characters
* to - an array of objects from the To: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
* fromaddress - full from: line, up to 1024 characters
* from - an array of objects from the From: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
* ccaddress - full cc: line, up to 1024 characters
* cc - an array of objects from the Cc: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
* bccaddress - full bcc: line, up to 1024 characters
* bcc - an array of objects from the Bcc: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
* reply\_toaddress - full Reply-To: line, up to 1024 characters
* reply\_to - an array of objects from the Reply-To: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
* senderaddress - full sender: line, up to 1024 characters
* sender - an array of objects from the Sender: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
* return\_pathaddress - full Return-Path: line, up to 1024 characters
* return\_path - an array of objects from the Return-Path: line, with the following properties: `personal`, `adl`, `mailbox`, and `host`
* remail -
* date - The message date as found in its headers
* Date - Same as date
* subject - The message subject
* Subject - Same as subject
* in\_reply\_to -
* message\_id -
* newsgroups -
* followup\_to -
* references -
* Recent - `R` if recent and seen, `N` if recent and not seen, ' ' if not recent.
* Unseen - `U` if not seen AND not recent, ' ' if seen OR not seen and recent
* Flagged - `F` if flagged, ' ' if not flagged
* Answered - `A` if answered, ' ' if unanswered
* Deleted - `D` if deleted, ' ' if not deleted
* Draft - `X` if draft, ' ' if not draft
* Msgno - The message number
* MailDate -
* Size - The message size
* udate - mail message date in Unix time
* fetchfrom - from line formatted to fit `from_length` characters
* fetchsubject - subject line formatted to fit `subject_length` characters
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. |
| 8.0.0 | The unused `defaulthost` parameter has been removed. |
### See Also
* [imap\_fetch\_overview()](function.imap-fetch-overview) - Read an overview of the information in the headers of the given message
php Gmagick::readimagefile Gmagick::readimagefile
======================
(PECL gmagick >= Unknown)
Gmagick::readimagefile — The readimagefile purpose
### Description
```
public Gmagick::readimagefile(resource $fp, string $filename = ?): Gmagick
```
Reads an image or image sequence from an open file descriptor.
### Parameters
`fp`
The file descriptor.
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php The SplMinHeap class
The SplMinHeap class
====================
Introduction
------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
The SplMinHeap class provides the main functionalities of a heap, keeping the minimum on the top.
Class synopsis
--------------
class **SplMinHeap** extends [SplHeap](class.splheap) { /\* Methods \*/
```
protected compare(mixed $value1, mixed $value2): int
```
/\* Inherited methods \*/
```
protected SplHeap::compare(mixed $value1, mixed $value2): int
```
```
public SplHeap::count(): int
```
```
public SplHeap::current(): mixed
```
```
public SplHeap::extract(): mixed
```
```
public SplHeap::insert(mixed $value): bool
```
```
public SplHeap::isCorrupted(): bool
```
```
public SplHeap::isEmpty(): bool
```
```
public SplHeap::key(): int
```
```
public SplHeap::next(): void
```
```
public SplHeap::recoverFromCorruption(): bool
```
```
public SplHeap::rewind(): void
```
```
public SplHeap::top(): mixed
```
```
public SplHeap::valid(): bool
```
} Table of Contents
-----------------
* [SplMinHeap::compare](splminheap.compare) — Compare elements in order to place them correctly in the heap while sifting up
php fdf_error fdf\_error
==========
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)
fdf\_error — Return error description for FDF error code
### Description
```
fdf_error(int $error_code = -1): string
```
Gets a textual description for the FDF error code given in `error_code`.
### Parameters
`error_code`
An error code obtained with [fdf\_errno()](function.fdf-errno). If not provided, this function uses the internal error code set by the last operation.
### Return Values
Returns the error message as a string, or the string `no error` if nothing went wrong.
### See Also
* [fdf\_errno()](function.fdf-errno) - Return error code for last fdf operation
php snmp_set_quick_print snmp\_set\_quick\_print
=======================
(PHP 4, PHP 5, PHP 7, PHP 8)
snmp\_set\_quick\_print — Set the value of `enable` within the NET-SNMP library
### Description
```
snmp_set_quick_print(bool $enable): bool
```
Sets the value of `enable` within the NET-SNMP library. When this is set (1), the SNMP library will return 'quick printed' values. This means that just the value will be printed. When `enable` is not enabled (default) the NET-SNMP library prints extra information including the type of the value (i.e. IpAddress or OID). Additionally, if quick\_print is not enabled, the library prints additional hex values for all strings of three characters or less.
By default the NET-SNMP library returns verbose values, quick\_print is used to return only the value.
Currently strings are still returned with extra quotes, this will be corrected in a later release.
### Parameters
`enable`
### Return Values
Always returns **`true`**.
### Examples
Setting quick\_print is often used when using the information returned rather than displaying it.
**Example #1 Using **snmp\_set\_quick\_print()****
```
<?php
snmp_set_quick_print(0);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
snmp_set_quick_print(1);
$a = snmpget("127.0.0.1", "public", ".1.3.6.1.2.1.2.2.1.9.1");
echo "$a\n";
?>
```
The above example will output something similar to:
```
'Timeticks: (0) 0:00:00.00'
'0:00:00.00'
```
### See Also
* [snmp\_get\_quick\_print()](function.snmp-get-quick-print) - Fetches the current value of the NET-SNMP library's quick\_print setting
php DateTime::setISODate DateTime::setISODate
====================
date\_isodate\_set
==================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
DateTime::setISODate -- date\_isodate\_set — Sets the ISO date
### Description
Object-oriented style
```
public DateTime::setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime
```
Procedural style
```
date_isodate_set(
DateTime $object,
int $year,
int $week,
int $dayOfWeek = 1
): DateTime
```
Set a date according to the ISO 8601 standard - using weeks and day offsets rather than specific dates.
Like [DateTimeImmutable::setISODate()](datetimeimmutable.setisodate) but works with [DateTime](class.datetime).
The procedural version takes the [DateTime](class.datetime) object as its first argument.
### Parameters
`object`
Procedural style only: A [DateTime](class.datetime) object returned by [date\_create()](function.date-create). The function modifies this object.
`year`
Year of the date.
`week`
Week of the date.
`dayOfWeek`
Offset from the first day of the week.
### Return Values
Returns the modified [DateTime](class.datetime) object for method chaining.
### See Also
* [DateTimeImmutable::setISODate()](datetimeimmutable.setisodate) - Sets the ISO date
php msg_queue_exists msg\_queue\_exists
==================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
msg\_queue\_exists — Check whether a message queue exists
### Description
```
msg_queue_exists(int $key): bool
```
Checks whether the message queue `key` exists.
### Parameters
`key`
Queue key.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [msg\_remove\_queue()](function.msg-remove-queue) - Destroy a message queue
* [msg\_receive()](function.msg-receive) - Receive a message from a message queue
* [msg\_stat\_queue()](function.msg-stat-queue) - Returns information from the message queue data structure
php DateInterval::format DateInterval::format
====================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
DateInterval::format — Formats the interval
### Description
```
public DateInterval::format(string $format): string
```
Formats the interval.
### Parameters
`format`
**The following characters are recognized in the `format` parameter string. Each format character must be prefixed by a percent sign (`%`).** | `format` character | Description | Example values |
| --- | --- | --- |
| `%` | Literal `%` | `%` |
| `Y` | Years, numeric, at least 2 digits with leading 0 | `01`, `03` |
| `y` | Years, numeric | `1`, `3` |
| `M` | Months, numeric, at least 2 digits with leading 0 | `01`, `03`, `12` |
| `m` | Months, numeric | `1`, `3`, `12` |
| `D` | Days, numeric, at least 2 digits with leading 0 | `01`, `03`, `31` |
| `d` | Days, numeric | `1`, `3`, `31` |
| `a` | Total number of days as a result of a [DateTime::diff()](datetime.diff) or `(unknown)` otherwise | `4`, `18`, `8123` |
| `H` | Hours, numeric, at least 2 digits with leading 0 | `01`, `03`, `23` |
| `h` | Hours, numeric | `1`, `3`, `23` |
| `I` | Minutes, numeric, at least 2 digits with leading 0 | `01`, `03`, `59` |
| `i` | Minutes, numeric | `1`, `3`, `59` |
| `S` | Seconds, numeric, at least 2 digits with leading 0 | `01`, `03`, `57` |
| `s` | Seconds, numeric | `1`, `3`, `57` |
| `F` | Microseconds, numeric, at least 6 digits with leading 0 | `007701`, `052738`, `428291` |
| `f` | Microseconds, numeric | `7701`, `52738`, `428291` |
| `R` | Sign "`-`" when negative, "`+`" when positive | `-`, `+` |
| `r` | Sign "`-`" when negative, empty when positive | `-`,
|
### Return Values
Returns the formatted interval.
### Changelog
| Version | Description |
| --- | --- |
| 7.2.12 | The `F` and `f` format will now always be positive. |
| 7.1.0 | The `F` and `f` format characters were added. |
### Examples
**Example #1 [DateInterval](class.dateinterval) example**
```
<?php
$interval = new DateInterval('P2Y4DT6H8M');
echo $interval->format('%d days');
?>
```
The above example will output:
```
4 days
```
**Example #2 [DateInterval](class.dateinterval) and carry over points**
```
<?php
$interval = new DateInterval('P32D');
echo $interval->format('%d days');
?>
```
The above example will output:
```
32 days
```
**Example #3 [DateInterval](class.dateinterval) and [DateTime::diff()](datetime.diff) with the %a and %d modifiers**
```
<?php
$january = new DateTime('2010-01-01');
$february = new DateTime('2010-02-01');
$interval = $february->diff($january);
// %a will output the total number of days.
echo $interval->format('%a total days')."\n";
// While %d will only output the number of days not already covered by the
// month.
echo $interval->format('%m month, %d days');
?>
```
The above example will output:
```
31 total days
1 month, 0 days
```
### Notes
>
> **Note**:
>
>
> The **DateInterval::format()** method does not recalculate carry over points in time strings nor in date segments. This is expected because it is not possible to overflow values like `"32 days"` which could be interpreted as anything from `"1 month and 4 days"` to `"1 month and 1 day"`.
>
>
### See Also
* [DateTime::diff()](datetime.diff) - Returns the difference between two DateTime objects
| programming_docs |
php html_entity_decode html\_entity\_decode
====================
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
html\_entity\_decode — Convert HTML entities to their corresponding characters
### Description
```
html_entity_decode(string $string, int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, ?string $encoding = null): string
```
**html\_entity\_decode()** is the opposite of [htmlentities()](function.htmlentities) in that it converts HTML entities in the `string` to their corresponding characters.
More precisely, this function decodes all the entities (including all numeric entities) that a) are necessarily valid for the chosen document type — i.e., for XML, this function does not decode named entities that might be defined in some DTD — and b) whose character or characters are in the coded character set associated with the chosen encoding and are permitted in the chosen document type. All other entities are left as is.
### Parameters
`string`
The input string.
`flags`
A bitmask of one or more of the following flags, which specify how to handle quotes and which document type to use. The default is `ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401`.
**Available `flags` constants**| Constant Name | Description |
| --- | --- |
| **`ENT_COMPAT`** | Will convert double-quotes and leave single-quotes alone. |
| **`ENT_QUOTES`** | Will convert both double and single quotes. |
| **`ENT_NOQUOTES`** | Will leave both double and single quotes unconverted. |
| **`ENT_SUBSTITUTE`** | Replace invalid code unit sequences with a Unicode Replacement Character U+FFFD (UTF-8) or � (otherwise) instead of returning an empty string. |
| **`ENT_HTML401`** | Handle code as HTML 4.01. |
| **`ENT_XML1`** | Handle code as XML 1. |
| **`ENT_XHTML`** | Handle code as XHTML. |
| **`ENT_HTML5`** | Handle code as HTML 5. |
`encoding`
An optional argument defining the encoding used when converting characters.
If omitted, `encoding` defaults to the value of the [default\_charset](https://www.php.net/manual/en/ini.core.php#ini.default-charset) configuration option.
Although this argument is technically optional, you are highly encouraged to specify the correct value for your code if the [default\_charset](https://www.php.net/manual/en/ini.core.php#ini.default-charset) configuration option may be set incorrectly for the given input.
The following character sets are supported:
**Supported charsets**| Charset | Aliases | Description |
| --- | --- | --- |
| ISO-8859-1 | ISO8859-1 | Western European, Latin-1. |
| ISO-8859-5 | ISO8859-5 | Little used cyrillic charset (Latin/Cyrillic). |
| ISO-8859-15 | ISO8859-15 | Western European, Latin-9. Adds the Euro sign, French and Finnish letters missing in Latin-1 (ISO-8859-1). |
| UTF-8 | | ASCII compatible multi-byte 8-bit Unicode. |
| cp866 | ibm866, 866 | DOS-specific Cyrillic charset. |
| cp1251 | Windows-1251, win-1251, 1251 | Windows-specific Cyrillic charset. |
| cp1252 | Windows-1252, 1252 | Windows specific charset for Western European. |
| KOI8-R | koi8-ru, koi8r | Russian. |
| BIG5 | 950 | Traditional Chinese, mainly used in Taiwan. |
| GB2312 | 936 | Simplified Chinese, national standard character set. |
| BIG5-HKSCS | | Big5 with Hong Kong extensions, Traditional Chinese. |
| Shift\_JIS | SJIS, SJIS-win, cp932, 932 | Japanese |
| EUC-JP | EUCJP, eucJP-win | Japanese |
| MacRoman | | Charset that was used by Mac OS. |
| `''` | | An empty string activates detection from script encoding (Zend multibyte), [default\_charset](https://www.php.net/manual/en/ini.core.php#ini.default-charset) and current locale (see [nl\_langinfo()](function.nl-langinfo) and [setlocale()](function.setlocale)), in this order. Not recommended. |
> **Note**: Any other character sets are not recognized. The default encoding will be used instead and a warning will be emitted.
>
>
### Return Values
Returns the decoded string.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | `flags` changed from **`ENT_COMPAT`** to **`ENT_QUOTES`** | **`ENT_SUBSTITUTE`** | **`ENT_HTML401`**. |
| 8.0.0 | `encoding` is nullable now. |
### Examples
**Example #1 Decoding HTML entities**
```
<?php
$orig = "I'll \"walk\" the <b>dog</b> now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk" the <b>dog</b> now
echo $b; // I'll "walk" the <b>dog</b> now
?>
```
### Notes
>
> **Note**:
>
>
> You might wonder why trim(html\_entity\_decode(' ')); doesn't reduce the string to an empty string, that's because the ' ' entity is not ASCII code 32 (which is stripped by [trim()](function.trim)) but ASCII code 160 (0xa0) in the default ISO 8859-1 encoding.
>
>
### See Also
* [htmlentities()](function.htmlentities) - Convert all applicable characters to HTML entities
* [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities
* [get\_html\_translation\_table()](function.get-html-translation-table) - Returns the translation table used by htmlspecialchars and htmlentities
* [urldecode()](function.urldecode) - Decodes URL-encoded string
php stats_rand_gen_funiform stats\_rand\_gen\_funiform
==========================
(PECL stats >= 1.0.0)
stats\_rand\_gen\_funiform — Generates uniform float between low (exclusive) and high (exclusive)
### Description
```
stats_rand_gen_funiform(float $low, float $high): float
```
Returns a random deviate from the uniform distribution from `low` to `high`.
### Parameters
`low`
The lower bound (inclusive)
`high`
The upper bound (exclusive)
### Return Values
A random deviate
php Gmagick::setimagescene Gmagick::setimagescene
======================
(PECL gmagick >= Unknown)
Gmagick::setimagescene — Sets the image scene
### Description
```
public Gmagick::setimagescene(int $scene): Gmagick
```
Sets the image scene.
### Parameters
`scene`
The image scene number.
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php socket_addrinfo_bind socket\_addrinfo\_bind
======================
(PHP 7 >= 7.2.0, PHP 8)
socket\_addrinfo\_bind — Create and bind to a socket from a given addrinfo
### Description
```
socket_addrinfo_bind(AddressInfo $address): Socket|false
```
Create a [Socket](class.socket) instance, and bind it to the provided [AddressInfo](class.addressinfo). The return value of this function may be used with [socket\_listen()](function.socket-listen).
### Parameters
`address`
[AddressInfo](class.addressinfo) instance created from [socket\_addrinfo\_lookup()](function.socket-addrinfo-lookup).
### Return Values
Returns a [Socket](class.socket) instance on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | On success, this function returns a [Socket](class.socket) instance now; previously, a resource was returned. |
| 8.0.0 | `address` is an [AddressInfo](class.addressinfo) instance now; previously, it was a resource. |
### See Also
* [socket\_addrinfo\_connect()](function.socket-addrinfo-connect) - Create and connect to a socket from a given addrinfo
* [socket\_addrinfo\_explain()](function.socket-addrinfo-explain) - Get information about addrinfo
* [socket\_addrinfo\_lookup()](function.socket-addrinfo-lookup) - Get array with contents of getaddrinfo about the given hostname
* [socket\_listen()](function.socket-listen) - Listens for a connection on a socket
php ImagickDraw::setFillOpacity ImagickDraw::setFillOpacity
===========================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::setFillOpacity — Sets the opacity to use when drawing using the fill color or fill texture
### Description
```
public ImagickDraw::setFillOpacity(float $fillOpacity): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Sets the opacity to use when drawing using the fill color or fill texture. Fully opaque is 1.0.
### Parameters
`fillOpacity`
the fill opacity
### Return Values
No value is returned.
### Examples
**Example #1 **ImagickDraw::setFillOpacity()****
```
<?php
function setFillOpacity($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeOpacity(1);
$draw->setStrokeWidth(2);
$draw->rectangle(100, 200, 200, 300);
$draw->setFillOpacity(0.4);
$draw->rectangle(300, 200, 400, 300);
$imagick = new \Imagick();
$imagick->newImage(500, 500, $backgroundColor);
$imagick->setImageFormat("png");
$imagick->drawImage($draw);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>
```
php ibase_restore ibase\_restore
==============
(PHP 5, PHP 7 < 7.4.0)
ibase\_restore — Initiates a restore task in the service manager and returns immediately
### Description
```
ibase_restore(
resource $service_handle,
string $source_file,
string $dest_db,
int $options = 0,
bool $verbose = false
): mixed
```
This function passes the arguments to the (remote) database server. There it starts a new restore process. Therefore you won't get any responses.
### Parameters
`service_handle`
A previously opened connection to the database server.
`source_file`
The absolute path on the server where the backup file is located.
`dest_db`
The path to create the new database on the server. You can also use database alias.
`options`
Additional options to pass to the database server for restore. The `options` parameter can be a combination of the following constants: **`IBASE_RES_DEACTIVATE_IDX`**, **`IBASE_RES_NO_SHADOW`**, **`IBASE_RES_NO_VALIDITY`**, **`IBASE_RES_ONE_AT_A_TIME`**, **`IBASE_RES_REPLACE`**, **`IBASE_RES_CREATE`**, **`IBASE_RES_USE_ALL_SPACE`**, **`IBASE_PRP_PAGE_BUFFERS`**, **`IBASE_PRP_SWEEP_INTERVAL`**, **`IBASE_RES_CREATE`**. Read the section about [Predefined Constants](https://www.php.net/manual/en/ibase.constants.php) for further information.
`verbose`
Since the restore process is done on the database server, you don't have any chance to get its output. This argument is useless.
### Return Values
Returns **`true`** on success or **`false`** on failure.
Since the restore process is done on the (remote) server, this function just passes the arguments to it. While the arguments are legal, you won't get **`false`**.
### Examples
**Example #1 **ibase\_restore()** example**
```
<?php
// Attach to database server by ip address and port
$service = ibase_service_attach ('10.1.11.200/3050', 'sysdba', 'masterkey');
// Start the restore process on database server
// Restore employee backup to the new emps.fdb database
// Don't use any special arguments
ibase_restore($service, '/srv/backup/employees.fbk', '/srv/firebird/emps.fdb');
// Free the attached connection
ibase_service_detach ($service);
?>
```
**Example #2 **ibase\_restore()** example with arguments**
```
<?php
// Attach to database server by name and default port
$service = ibase_service_attach ('fb-server.contoso.local', 'sysdba', 'masterkey');
// Start the restore process on database server
// Restore to employee database using alias.
// Restore without indixes. Replace existing database.
ibase_restore($service, '/srv/backup/employees.fbk', 'employees.fdb', IBASE_RES_DEACTIVATE_IDX | IBASE_RES_REPLACE);
// Free the attached connection
ibase_service_detach ($service);
?>
```
### See Also
* [ibase\_backup()](function.ibase-backup) - Initiates a backup task in the service manager and returns immediately
php SplPriorityQueue::current SplPriorityQueue::current
=========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplPriorityQueue::current — Return current node pointed by the iterator
### Description
```
public SplPriorityQueue::current(): mixed
```
Get the current datastructure node.
### Parameters
This function has no parameters.
### Return Values
The value or priority (or both) of the current node, depending on the extract flag.
php mysqli::next_result mysqli::next\_result
====================
mysqli\_next\_result
====================
(PHP 5, PHP 7, PHP 8)
mysqli::next\_result -- mysqli\_next\_result — Prepare next result from multi\_query
### Description
Object-oriented style
```
public mysqli::next_result(): bool
```
Procedural style
```
mysqli_next_result(mysqli $mysql): bool
```
Prepares next result set from a previous call to [mysqli\_multi\_query()](mysqli.multi-query) which can be retrieved by [mysqli\_store\_result()](mysqli.store-result) or [mysqli\_use\_result()](mysqli.use-result).
### Parameters
`mysql`
Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init)
### Return Values
Returns **`true`** on success or **`false`** on failure. Also returns **`false`** if the next statement resulted in an error, unlike [mysqli\_more\_results()](mysqli.more-results).
### Examples
See [mysqli\_multi\_query()](mysqli.multi-query).
### See Also
* [mysqli\_multi\_query()](mysqli.multi-query) - Performs one or more queries on the database
* [mysqli\_more\_results()](mysqli.more-results) - Check if there are any more query results from a multi query
* [mysqli\_store\_result()](mysqli.store-result) - Transfers a result set from the last query
* [mysqli\_use\_result()](mysqli.use-result) - Initiate a result set retrieval
php Collator::setStrength Collator::setStrength
=====================
collator\_set\_strength
=======================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
Collator::setStrength -- collator\_set\_strength — Set collation strength
### Description
Object-oriented style
```
public Collator::setStrength(int $strength): bool
```
Procedural style
```
collator_set_strength(Collator $object, int $strength): bool
```
The [» ICU](http://www.icu-project.org/) Collation Service supports many levels of comparison (named "Levels", but also known as "Strengths"). Having these categories enables ICU to sort strings precisely according to local conventions. However, by allowing the levels to be selectively employed, searching for a string in text can be performed with various matching conditions.
1. *Primary Level*: Typically, this is used to denote differences between base characters (for example, "a" < "b"). It is the strongest difference. For example, dictionaries are divided into different sections by base character. This is also called the `level 1` strength.
2. *Secondary Level*: Accents in the characters are considered secondary differences (for example, "as" < "às" < "at"). Other differences between letters can also be considered secondary differences, depending on the language. A secondary difference is ignored when there is a primary difference anywhere in the strings. This is also called the `level 2` strength.
>
> **Note**:
>
>
> Note: In some languages (such as Danish), certain accented letters are considered to be separate base characters. In most languages, however, an accented letter only has a secondary difference from the unaccented version of that letter.
>
>
3. *Tertiary Level*: Upper and lower case differences in characters are distinguished at the tertiary level (for example, "ao" < "Ao" < "aò"). In addition, a variant of a letter differs from the base form on the tertiary level (such as "A" and " "). Another example is the difference between large and small Kana. A tertiary difference is ignored when there is a primary or secondary difference anywhere in the strings. This is also called the `level 3` strength.
4. *Quaternary Level*: When punctuation is ignored (see Ignoring Punctuations ) at levels 1-3, an additional level can be used to distinguish words with and without punctuation (for example, "ab" < "a-b" < "aB"). This difference is ignored when there is a primary, secondary or tertiary difference. This is also known as the `level 4` strength. The quaternary level should only be used if ignoring punctuation is required or when processing Japanese text (see Hiragana processing).
5. *Identical Level*: When all other levels are equal, the identical level is used as a tiebreaker. The Unicode code point values of the NFD form of each string are compared at this level, just in case there is no difference at levels 1-4. For example, Hebrew cantillation marks are only distinguished at this level. This level should be used sparingly, as only code point values differences between two strings is an extremely rare occurrence. Using this level substantially decreases the performance for both incremental comparison and sort key generation (as well as increasing the sort key length). It is also known as `level 5` strength.
For example, people may choose to ignore accents or ignore accents and case when searching for text. Almost all characters are distinguished by the first three levels, and in most locales the default value is thus Tertiary. However, if Alternate is set to be Shifted, then the Quaternary strength can be used to break ties among whitespace, punctuation, and symbols that would otherwise be ignored. If very fine distinctions among characters are required, then the Identical strength can be used (for example, Identical Strength distinguishes between the Mathematical Bold Small A and the Mathematical Italic Small A.). However, using levels higher than Tertiary the Identical strength result in significantly longer sort keys, and slower string comparison performance for equal strings.
### Parameters
`object`
[Collator](class.collator) object.
`strength`
Strength to set.
Possible values are:
* **`Collator::PRIMARY`**
* **`Collator::SECONDARY`**
* **`Collator::TERTIARY`**
* **`Collator::QUATERNARY`**
* **`Collator::IDENTICAL`**
* **`Collator::DEFAULT_STRENGTH`**
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **collator\_set\_strength()** example**
```
<?php
$arr = array( 'aò', 'Ao', 'ao' );
$coll = collator_create( 'en_US' );
// Sort array using default strength.
collator_sort( $coll, $arr );
var_export( $arr );
// Sort array using primary strength.
collator_set_strength( $coll, Collator::PRIMARY );
collator_sort( $coll, $arr );
var_export( $arr );
?>
```
The above example will output:
```
array (
0 => 'ao',
1 => 'Ao',
2 => 'aò',
)
array (
0 => 'aò',
1 => 'Ao',
2 => 'ao',
)
```
### See Also
* [[Collator](class.collator) constants](class.collator#intl.collator-constants)
* [collator\_get\_strength()](collator.getstrength) - Get current collation strength
php IntlDateFormatter::localtime IntlDateFormatter::localtime
============================
datefmt\_localtime
==================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
IntlDateFormatter::localtime -- datefmt\_localtime — Parse string to a field-based time value
### Description
Object-oriented style
```
public IntlDateFormatter::localtime(string $string, int &$offset = null): array|false
```
Procedural style
```
datefmt_localtime(IntlDateFormatter $formatter, string $string, int &$offset = null): array|false
```
Converts string $value to a field-based time value ( an array of various fields), starting at $parse\_pos and consuming as much of the input value as possible.
### Parameters
`formatter`
The formatter resource
`string`
string to convert to a time
`offset`
Position at which to start the parsing in $value (zero-based). If no error occurs before $value is consumed, $parse\_pos will contain -1 otherwise it will contain the position at which parsing ended . If $parse\_pos > strlen($value), the parse fails immediately.
### Return Values
Localtime compatible array of integers : contains 24 hour clock value in tm\_hour field, or **`false`** on failure.
### Examples
**Example #1 **datefmt\_localtime()** example**
```
<?php
$fmt = datefmt_create(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$arr = datefmt_localtime($fmt, 'Wednesday, December 31, 1969 4:00:00 PM PT', 0);
echo 'First parsed output is ';
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>
```
**Example #2 OO example**
```
<?php
$fmt = new IntlDateFormatter(
'en_US',
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'America/Los_Angeles',
IntlDateFormatter::GREGORIAN
);
$arr = $fmt->localtime('Wednesday, December 31, 1969 4:00:00 PM PT', 0);
echo 'First parsed output is ';
if ($arr) {
foreach ($arr as $key => $value) {
echo "$key : $value , ";
}
}
?>
```
The above example will output:
```
First parsed output is tm_sec : 0 , tm_min : 0 , tm_hour : 16 , tm_year : 1969 ,
tm_mday : 31 , tm_wday : 4 , tm_yday : 365 , tm_mon : 11 , tm_isdst : 0 ,
```
### See Also
* [datefmt\_create()](intldateformatter.create) - Create a date formatter
* [datefmt\_format()](intldateformatter.format) - Format the date/time value as a string
* [datefmt\_parse()](intldateformatter.parse) - Parse string to a timestamp value
* [datefmt\_get\_error\_code()](intldateformatter.geterrorcode) - Get the error code from last operation
* [datefmt\_get\_error\_message()](intldateformatter.geterrormessage) - Get the error text from the last operation
| programming_docs |
php inflate_get_read_len inflate\_get\_read\_len
=======================
(PHP 7 >= 7.2.0, PHP 8)
inflate\_get\_read\_len — Get number of bytes read so far
### Description
```
inflate_get_read_len(InflateContext $context): int
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`context`
### Return Values
Returns number of bytes read so far or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `context` expects an [InflateContext](class.inflatecontext) instance now; previously, a resource was expected. |
php VarnishAdmin::setHost VarnishAdmin::setHost
=====================
(PECL varnish >= 0.8)
VarnishAdmin::setHost — Set the class host configuration param
### Description
```
public VarnishAdmin::setHost(string $host): void
```
### Parameters
`host`
Connection host configuration parameter.
### Return Values
php The EvStat class
The EvStat class
================
Introduction
------------
(PECL ev >= 0.2.0)
**EvStat** monitors a file system path for attribute changes. It calls *stat()* on that path in regular intervals(or when the OS signals it changed) and sees if it changed compared to the last time, invoking the callback if it did.
The path does not need to exist: changing from "path exists" to "path does not exist" is a status change like any other. The condition "path does not exist" is signified by the **`'nlink'`** item being 0(returned by [EvStat::attr()](evstat.attr) method).
The path must not end in a slash or contain special components such as **`'.'`** or **`..`** . The path should be absolute: if it is relative and the working directory changes, then the behaviour is undefined.
Since there is no portable change notification interface available, the portable implementation simply calls *stat()* regularly on the path to see if it changed somehow. For this case a recommended polling interval can be specified. If one specifies a polling interval of **`0.0`** (highly recommended) then a suitable, unspecified default value will be used(which could be expected to be around 5 seconds, although this might change dynamically). *libev* will also impose a minimum interval which is currently around **`0.1`** , but that’s usually overkill.
This watcher type is not meant for massive numbers of **EvStat** watchers, as even with OS-supported change notifications, this can be resource-intensive.
Class synopsis
--------------
class **EvStat** extends [EvWatcher](class.evwatcher) { /\* Properties \*/ public [$path](class.evstat#evstat.props.path);
public [$interval](class.evstat#evstat.props.interval); /\* Inherited properties \*/
public [$is\_active](class.evwatcher#evwatcher.props.is-active);
public [$data](class.evwatcher#evwatcher.props.data);
public [$is\_pending](class.evwatcher#evwatcher.props.is-pending);
public [$priority](class.evwatcher#evwatcher.props.priority); /\* Methods \*/ public [\_\_construct](evstat.construct)(
string `$path` ,
float `$interval` ,
[callable](language.types.callable) `$callback` ,
[mixed](language.types.declarations#language.types.declarations.mixed) `$data` = **`null`** ,
int `$priority` = 0
)
```
public attr(): array
```
```
final public static createStopped(
string $path ,
float $interval ,
callable $callback ,
mixed $data = null ,
int $priority = 0
): void
```
```
public prev(): void
```
```
public set( string $path , float $interval ): void
```
```
public stat(): bool
```
/\* Inherited methods \*/
```
public EvWatcher::clear(): int
```
```
public EvWatcher::feed( int $revents ): void
```
```
public EvWatcher::getLoop(): EvLoop
```
```
public EvWatcher::invoke( int $revents ): void
```
```
public EvWatcher::keepalive( bool $value = ?): bool
```
```
public EvWatcher::setCallback( callable $callback ): void
```
```
public EvWatcher::start(): void
```
```
public EvWatcher::stop(): void
```
} Properties
----------
interval *Readonly* . Hint on how quickly a change is expected to be detected and should normally be specified as **`0.0`** to let *libev* choose a suitable value.
path *Readonly* . The path to wait for status changes on.
Table of Contents
-----------------
* [EvStat::attr](evstat.attr) — Returns the values most recently detected by Ev
* [EvStat::\_\_construct](evstat.construct) — Constructs EvStat watcher object
* [EvStat::createStopped](evstat.createstopped) — Create a stopped EvStat watcher object
* [EvStat::prev](evstat.prev) — Returns the previous set of values returned by EvStat::attr
* [EvStat::set](evstat.set) — Configures the watcher
* [EvStat::stat](evstat.stat) — Initiates the stat call
php The RecursiveTreeIterator class
The RecursiveTreeIterator class
===============================
Introduction
------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Allows iterating over a [RecursiveIterator](class.recursiveiterator) to generate an ASCII graphic tree.
Class synopsis
--------------
class **RecursiveTreeIterator** extends [RecursiveIteratorIterator](class.recursiveiteratoriterator) { /\* Inherited constants \*/ public const int [RecursiveIteratorIterator::LEAVES\_ONLY](class.recursiveiteratoriterator#recursiveiteratoriterator.constants.leaves-only);
public const int [RecursiveIteratorIterator::SELF\_FIRST](class.recursiveiteratoriterator#recursiveiteratoriterator.constants.self-first);
public const int [RecursiveIteratorIterator::CHILD\_FIRST](class.recursiveiteratoriterator#recursiveiteratoriterator.constants.child-first);
public const int [RecursiveIteratorIterator::CATCH\_GET\_CHILD](class.recursiveiteratoriterator#recursiveiteratoriterator.constants.catch-get-child); /\* Constants \*/
public const int [BYPASS\_CURRENT](class.recursivetreeiterator#recursivetreeiterator.constants.bypass-current);
public const int [BYPASS\_KEY](class.recursivetreeiterator#recursivetreeiterator.constants.bypass-key);
public const int [PREFIX\_LEFT](class.recursivetreeiterator#recursivetreeiterator.constants.prefix-left);
public const int [PREFIX\_MID\_HAS\_NEXT](class.recursivetreeiterator#recursivetreeiterator.constants.prefix-mid-has-next) = 1;
public const int [PREFIX\_MID\_LAST](class.recursivetreeiterator#recursivetreeiterator.constants.prefix-mid-last) = 2;
public const int [PREFIX\_END\_HAS\_NEXT](class.recursivetreeiterator#recursivetreeiterator.constants.prefix-end-has-next) = 3;
public const int [PREFIX\_END\_LAST](class.recursivetreeiterator#recursivetreeiterator.constants.prefix-end-last) = 4;
public const int [PREFIX\_RIGHT](class.recursivetreeiterator#recursivetreeiterator.constants.prefix-right) = 5; /\* Methods \*/ public [\_\_construct](recursivetreeiterator.construct)(
[RecursiveIterator](class.recursiveiterator)|[IteratorAggregate](class.iteratoraggregate) `$iterator`,
int `$flags` = RecursiveTreeIterator::BYPASS\_KEY,
int `$cachingIteratorFlags` = CachingIterator::CATCH\_GET\_CHILD,
int `$mode` = RecursiveTreeIterator::SELF\_FIRST
)
```
public beginChildren(): void
```
```
public beginIteration(): RecursiveIterator
```
```
public callGetChildren(): RecursiveIterator
```
```
public callHasChildren(): bool
```
```
public current(): mixed
```
```
public endChildren(): void
```
```
public endIteration(): void
```
```
public getEntry(): string
```
```
public getPostfix(): string
```
```
public getPrefix(): string
```
```
public key(): mixed
```
```
public next(): void
```
```
public nextElement(): void
```
```
public rewind(): void
```
```
public setPostfix(string $postfix): void
```
```
public setPrefixPart(int $part, string $value): void
```
```
public valid(): bool
```
/\* Inherited methods \*/
```
public RecursiveIteratorIterator::beginChildren(): void
```
```
public RecursiveIteratorIterator::beginIteration(): void
```
```
public RecursiveIteratorIterator::callGetChildren(): ?RecursiveIterator
```
```
public RecursiveIteratorIterator::callHasChildren(): bool
```
```
public RecursiveIteratorIterator::current(): mixed
```
```
public RecursiveIteratorIterator::endChildren(): void
```
```
public RecursiveIteratorIterator::endIteration(): void
```
```
public RecursiveIteratorIterator::getDepth(): int
```
```
public RecursiveIteratorIterator::getInnerIterator(): RecursiveIterator
```
```
public RecursiveIteratorIterator::getMaxDepth(): int|false
```
```
public RecursiveIteratorIterator::getSubIterator(?int $level = null): ?RecursiveIterator
```
```
public RecursiveIteratorIterator::key(): mixed
```
```
public RecursiveIteratorIterator::next(): void
```
```
public RecursiveIteratorIterator::nextElement(): void
```
```
public RecursiveIteratorIterator::rewind(): void
```
```
public RecursiveIteratorIterator::setMaxDepth(int $maxDepth = -1): void
```
```
public RecursiveIteratorIterator::valid(): bool
```
} Predefined Constants
--------------------
**`RecursiveTreeIterator::BYPASS_CURRENT`** **`RecursiveTreeIterator::BYPASS_KEY`** **`RecursiveTreeIterator::PREFIX_LEFT`** **`RecursiveTreeIterator::PREFIX_MID_HAS_NEXT`** **`RecursiveTreeIterator::PREFIX_MID_LAST`** **`RecursiveTreeIterator::PREFIX_END_HAS_NEXT`** **`RecursiveTreeIterator::PREFIX_END_LAST`** **`RecursiveTreeIterator::PREFIX_RIGHT`** Table of Contents
-----------------
* [RecursiveTreeIterator::beginChildren](recursivetreeiterator.beginchildren) — Begin children
* [RecursiveTreeIterator::beginIteration](recursivetreeiterator.beginiteration) — Begin iteration
* [RecursiveTreeIterator::callGetChildren](recursivetreeiterator.callgetchildren) — Get children
* [RecursiveTreeIterator::callHasChildren](recursivetreeiterator.callhaschildren) — Has children
* [RecursiveTreeIterator::\_\_construct](recursivetreeiterator.construct) — Construct a RecursiveTreeIterator
* [RecursiveTreeIterator::current](recursivetreeiterator.current) — Get current element
* [RecursiveTreeIterator::endChildren](recursivetreeiterator.endchildren) — End children
* [RecursiveTreeIterator::endIteration](recursivetreeiterator.enditeration) — End iteration
* [RecursiveTreeIterator::getEntry](recursivetreeiterator.getentry) — Get current entry
* [RecursiveTreeIterator::getPostfix](recursivetreeiterator.getpostfix) — Get the postfix
* [RecursiveTreeIterator::getPrefix](recursivetreeiterator.getprefix) — Get the prefix
* [RecursiveTreeIterator::key](recursivetreeiterator.key) — Get the key of the current element
* [RecursiveTreeIterator::next](recursivetreeiterator.next) — Move to next element
* [RecursiveTreeIterator::nextElement](recursivetreeiterator.nextelement) — Next element
* [RecursiveTreeIterator::rewind](recursivetreeiterator.rewind) — Rewind iterator
* [RecursiveTreeIterator::setPostfix](recursivetreeiterator.setpostfix) — Set postfix
* [RecursiveTreeIterator::setPrefixPart](recursivetreeiterator.setprefixpart) — Set a part of the prefix
* [RecursiveTreeIterator::valid](recursivetreeiterator.valid) — Check validity
php OAuth::enableSSLChecks OAuth::enableSSLChecks
======================
(PECL OAuth >= 0.99.5)
OAuth::enableSSLChecks — Turn on SSL checks
### Description
```
public OAuth::enableSSLChecks(): bool
```
Turns on the usual SSL peer certificate and host checks (enabled by default). Alternatively, the `sslChecks` member can be set to a non-**`false`** value to turn SSL checks off.
### Parameters
This function has no parameters.
### Return Values
**`true`**
### Changelog
| Version | Description |
| --- | --- |
| PECL oauth 0.99.8 | The `sslChecks` member was added |
### See Also
* [OAuth::disableSSLChecks()](oauth.disablesslchecks) - Turn off SSL checks
php is_resource is\_resource
============
(PHP 4, PHP 5, PHP 7, PHP 8)
is\_resource — Finds whether a variable is a resource
### Description
```
is_resource(mixed $value): bool
```
Finds whether the given variable is a resource.
### Parameters
`value`
The variable being evaluated.
### Return Values
Returns **`true`** if `value` is a resource, **`false`** otherwise.
### Examples
**Example #1 **is\_resource()** example**
```
<?php
$handle = fopen("php://stdout", "w");
if (is_resource($handle)) {
echo '$handle is a resource';
}
?>
```
The above example will output:
```
$handle is a resource
```
### Notes
>
> **Note**:
>
>
> **is\_resource()** is not a strict type-checking method: it will return **`false`** if `value` is a resource variable that has been closed.
>
>
### See Also
* [The resource-type documentation](language.types.resource)
* [get\_resource\_type()](function.get-resource-type) - Returns the resource type
php openssl_pkcs12_export_to_file openssl\_pkcs12\_export\_to\_file
=================================
(PHP 5 >= 5.2.2, PHP 7, PHP 8)
openssl\_pkcs12\_export\_to\_file — Exports a PKCS#12 Compatible Certificate Store File
### Description
```
openssl_pkcs12_export_to_file(
OpenSSLCertificate|string $certificate,
string $output_filename,
OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key,
string $passphrase,
array $options = []
): bool
```
**openssl\_pkcs12\_export\_to\_file()** stores `certificate` into a file named by `output_filename` in a PKCS#12 file format.
### Parameters
`x509`
See [Key/Certificate parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values.
`output_filename`
Path to the output file.
`private_key`
Private key component of PKCS#12 file. See [Public/Private Key parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values.
`passphrase`
Encryption password for unlocking the PKCS#12 file.
`options`
Optional array, other keys will be ignored.
| Key | Description |
| --- | --- |
| `"extracerts"` | array of extra certificates or a single certificate to be included in the PKCS#12 file. |
| `"friendlyname"` | string to be used for the supplied certificate and key |
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509 CSR` was accepted. |
| 8.0.0 | `private_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) or [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` or `OpenSSL X.509` was accepted. |
php Ds\PriorityQueue::capacity Ds\PriorityQueue::capacity
==========================
(PECL ds >= 1.0.0)
Ds\PriorityQueue::capacity — Returns the current capacity
### Description
```
public Ds\PriorityQueue::capacity(): int
```
Returns the current capacity.
### Parameters
This function has no parameters.
### Return Values
The current capacity.
### Examples
**Example #1 **Ds\PriorityQueue::capacity()** example**
```
<?php
$queue = new \Ds\PriorityQueue();
var_dump($queue->capacity());
?>
```
The above example will output something similar to:
```
int(8)
```
php wincache_scache_info wincache\_scache\_info
======================
(PECL wincache >= 1.1.0)
wincache\_scache\_info — Retrieves information about files cached in the session cache
### Description
```
wincache_scache_info(bool $summaryonly = false): array|false
```
Retrieves information about session cache content and its usage.
### Parameters
`summaryonly`
Controls whether the returned array will contain information about individual cache entries along with the session cache summary.
### Return Values
Array of meta data about session cache or **`false`** on failure
The array returned by this function contains the following elements:
* `total_cache_uptime` - total time in seconds that the session cache has been active
* `total_item_count` - total number of elements that are currently in the session cache
* `is_local_cache` - true is the cache metadata is for a local cache instance, false if the metadata is for the global cache
* `total_hit_count` - number of times the data has been served from the cache
* `total_miss_count` - number of times the data has not been found in the cache
* `scache_entries` - an array that contains the information about all the cached items:
+ `key_name` - name of the key which is used to store the data
+ `value_type` - type of value stored by the key
+ `use_time` - time in seconds since the file has been accessed in the opcode cache
+ `last_check` - time in seconds since the file has been checked for modifications
+ `ttl_seconds` - time remaining for the data to live in the cache, 0 meaning infinite
+ `age_seconds` - time elapsed from the time data has been added in the cache
+ `hitcount` - number of times data has been served from the cache
### Examples
**Example #1 A **wincache\_scache\_info()** example**
```
<pre>
<?php
print_r(wincache_scache_info());
?>
</pre>
```
The above example will output:
```
Array
(
[total_cache_uptime] => 17357
[total_file_count] => 121
[total_hit_count] => 36562
[total_miss_count] => 201
[scache_entries] => Array
(
[1] => Array
(
[file_name] => c:\inetpub\wwwroot\checkcache.php
[add_time] => 17356
[use_time] => 7
[last_check] => 10
[hit_count] => 454
[function_count] => 0
[class_count] => 1
)
[2] => Array (...iterates for each cached file)
)
)
```
### See Also
* [wincache\_fcache\_fileinfo()](function.wincache-fcache-fileinfo) - Retrieves information about files cached in the file cache
* [wincache\_fcache\_meminfo()](function.wincache-fcache-meminfo) - Retrieves information about file cache memory usage
* [wincache\_ocache\_meminfo()](function.wincache-ocache-meminfo) - Retrieves information about opcode cache memory usage
* [wincache\_rplist\_fileinfo()](function.wincache-rplist-fileinfo) - Retrieves information about resolve file path cache
* [wincache\_rplist\_meminfo()](function.wincache-rplist-meminfo) - Retrieves information about memory usage by the resolve file path cache
* [wincache\_refresh\_if\_changed()](function.wincache-refresh-if-changed) - Refreshes the cache entries for the cached files
* [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage
* [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache
* [wincache\_scache\_meminfo()](function.wincache-scache-meminfo) - Retrieves information about session cache memory usage
php RecursiveFilterIterator::getChildren RecursiveFilterIterator::getChildren
====================================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
RecursiveFilterIterator::getChildren — Return the inner iterator's children contained in a RecursiveFilterIterator
### Description
```
public RecursiveFilterIterator::getChildren(): ?RecursiveFilterIterator
```
Return the inner iterator's children contained in a [RecursiveFilterIterator](class.recursivefilteriterator).
### Parameters
This function has no parameters.
### Return Values
Returns a [RecursiveFilterIterator](class.recursivefilteriterator) containing the inner iterator's children.
### See Also
* [RecursiveFilterIterator::hasChildren()](recursivefilteriterator.haschildren) - Check whether the inner iterator's current element has children
* [RecursiveIterator::getChildren()](recursiveiterator.getchildren) - Returns an iterator for the current entry
| programming_docs |
php Yaf_Loader::isLocalName Yaf\_Loader::isLocalName
========================
(Yaf >=1.0.0)
Yaf\_Loader::isLocalName — The isLocalName purpose
### Description
```
public Yaf_Loader::isLocalName(): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php Ds\Vector::last Ds\Vector::last
===============
(PECL ds >= 1.0.0)
Ds\Vector::last — Returns the last value
### Description
```
public Ds\Vector::last(): mixed
```
Returns the last value in the vector.
### Parameters
This function has no parameters.
### Return Values
The last value in the vector.
### Errors/Exceptions
[UnderflowException](class.underflowexception) if empty.
### Examples
**Example #1 **Ds\Vector::last()** example**
```
<?php
$vector = new \Ds\Vector([1, 2, 3]);
var_dump($vector->last());
?>
```
The above example will output something similar to:
```
int(3)
```
php Yaf_Loader::registerNamespace Yaf\_Loader::registerNamespace
==============================
(Yaf >=3.2.0)
Yaf\_Loader::registerNamespace — Register namespace with searching path
### Description
```
public Yaf_Loader::registerNamespace(string|array $namespaces, string $path = ?): bool
```
Register a namespace with searching path, [Yaf\_Loader](class.yaf-loader) searchs classes under this namespace in path, the one is also could be configureded via [application.library.directory.namespace](https://www.php.net/manual/en/yaf.appconfig.php#configuration.yaf.library.namespace)(in application.ini);
>
> **Note**:
>
>
> Yaf still think underline as folder separator.
>
>
### Parameters
`namespace`
a string of namespace, or a array of namespaces with paths.
`path`
a string of path, it is better to use abosolute path here for performance
### Return Values
bool
### Examples
**Example #1 **Yaf\_Loader::registerNamespace()**example**
```
<?php
$loader = Yaf_Loader::getInstance();
$loader->registerNamespace("\Vendor\PHP", "/var/lib/php");
$loader->registerNamespace(array(
"\Vendor\ASP" => "/var/lib/asp",
"\Vendor\JSP" => "/usr/lib/vendor/",
));
$loader->autoload("\Vendor\PHP\Dummy"); //load '/var/lib/php/Dummy.php'
$loader->autoload("\Vendor\PHP\Foo_Bar"); //load '/var/lib/php/Foo/Bar.php'
$loader->autoload("\Vendor\JSP\Dummy"); //load '/usr/lib/vendor/Dummy.php'
?>
```
php ReflectionClassConstant::getValue ReflectionClassConstant::getValue
=================================
(PHP 7 >= 7.1.0, PHP 8)
ReflectionClassConstant::getValue — Gets value
### Description
```
public ReflectionClassConstant::getValue(): mixed
```
Gets the class constant's value.
### Parameters
This function has no parameters.
### Return Values
The value of the class constant.
php Throwable::__toString Throwable::\_\_toString
=======================
(PHP 7, PHP 8)
Throwable::\_\_toString — Gets a string representation of the thrown object
### Description
```
public Throwable::__toString(): string
```
### Parameters
This function has no parameters.
### Return Values
Returns the string representation of the thrown object.
### See Also
* [Exception::\_\_toString()](exception.tostring) - String representation of the exception
php The DateTimeImmutable class
The DateTimeImmutable class
===========================
Introduction
------------
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
Representation of date and time.
This class behaves the same as [DateTime](class.datetime) except new objects are returned when modification methods such as [DateTime::modify()](datetime.modify) are called.
Class synopsis
--------------
class **DateTimeImmutable** implements [DateTimeInterface](class.datetimeinterface) { /\* Inherited constants \*/ public const string [DateTimeInterface::ATOM](class.datetimeinterface#datetimeinterface.constants.atom) = "Y-m-d\\TH:i:sP";
public const string [DateTimeInterface::COOKIE](class.datetimeinterface#datetimeinterface.constants.cookie) = "l, d-M-Y H:i:s T";
public const string [DateTimeInterface::ISO8601](class.datetimeinterface#datetimeinterface.constants.iso8601) = "Y-m-d\\TH:i:sO";
public const string [DateTimeInterface::ISO8601\_EXPANDED](class.datetimeinterface#datetimeinterface.constants.iso8601-expanded) = "X-m-d\\TH:i:sP";
public const string [DateTimeInterface::RFC822](class.datetimeinterface#datetimeinterface.constants.rfc822) = "D, d M y H:i:s O";
public const string [DateTimeInterface::RFC850](class.datetimeinterface#datetimeinterface.constants.rfc850) = "l, d-M-y H:i:s T";
public const string [DateTimeInterface::RFC1036](class.datetimeinterface#datetimeinterface.constants.rfc1036) = "D, d M y H:i:s O";
public const string [DateTimeInterface::RFC1123](class.datetimeinterface#datetimeinterface.constants.rfc1123) = "D, d M Y H:i:s O";
public const string [DateTimeInterface::RFC7231](class.datetimeinterface#datetimeinterface.constants.rfc7231) = "D, d M Y H:i:s \\G\\M\\T";
public const string [DateTimeInterface::RFC2822](class.datetimeinterface#datetimeinterface.constants.rfc2822) = "D, d M Y H:i:s O";
public const string [DateTimeInterface::RFC3339](class.datetimeinterface#datetimeinterface.constants.rfc3339) = "Y-m-d\\TH:i:sP";
public const string [DateTimeInterface::RFC3339\_EXTENDED](class.datetimeinterface#datetimeinterface.constants.rfc3339-extended) = "Y-m-d\\TH:i:s.vP";
public const string [DateTimeInterface::RSS](class.datetimeinterface#datetimeinterface.constants.rss) = "D, d M Y H:i:s O";
public const string [DateTimeInterface::W3C](class.datetimeinterface#datetimeinterface.constants.w3c) = "Y-m-d\\TH:i:sP"; /\* Methods \*/ public [\_\_construct](datetimeimmutable.construct)(string `$datetime` = "now", ?[DateTimeZone](class.datetimezone) `$timezone` = **`null`**)
```
public add(DateInterval $interval): DateTimeImmutable
```
```
public static createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false
```
```
public static createFromInterface(DateTimeInterface $object): DateTimeImmutable
```
```
public static createFromMutable(DateTime $object): static
```
```
public static getLastErrors(): array|false
```
```
public modify(string $modifier): DateTimeImmutable|false
```
```
public static __set_state(array $array): DateTimeImmutable
```
```
public setDate(int $year, int $month, int $day): DateTimeImmutable
```
```
public setISODate(int $year, int $week, int $dayOfWeek = 1): DateTimeImmutable
```
```
public setTime(
int $hour,
int $minute,
int $second = 0,
int $microsecond = 0
): DateTimeImmutable
```
```
public setTimestamp(int $timestamp): DateTimeImmutable
```
```
public setTimezone(DateTimeZone $timezone): DateTimeImmutable
```
```
public sub(DateInterval $interval): DateTimeImmutable
```
```
public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval
```
```
public format(string $format): string
```
```
public getOffset(): int
```
```
public getTimestamp(): int
```
```
public getTimezone(): DateTimeZone|false
```
```
public __wakeup(): void
```
} Changelog
---------
| Version | Description |
| --- | --- |
| 7.1.0 | The **DateTimeImmutable** constructor now includes the current microseconds in the constructed value. Before this, it would always initialise the microseconds to `0`. |
Table of Contents
-----------------
* [DateTimeImmutable::add](datetimeimmutable.add) — Returns a new object, with added amount of days, months, years, hours, minutes and seconds
* [DateTimeImmutable::\_\_construct](datetimeimmutable.construct) — Returns new DateTimeImmutable object
* [DateTimeImmutable::createFromFormat](datetimeimmutable.createfromformat) — Parses a time string according to a specified format
* [DateTimeImmutable::createFromInterface](datetimeimmutable.createfrominterface) — Returns new DateTimeImmutable object encapsulating the given DateTimeInterface object
* [DateTimeImmutable::createFromMutable](datetimeimmutable.createfrommutable) — Returns new DateTimeImmutable instance encapsulating the given DateTime object
* [DateTimeImmutable::getLastErrors](datetimeimmutable.getlasterrors) — Returns the warnings and errors
* [DateTimeImmutable::modify](datetimeimmutable.modify) — Creates a new object with modified timestamp
* [DateTimeImmutable::\_\_set\_state](datetimeimmutable.set-state) — The \_\_set\_state handler
* [DateTimeImmutable::setDate](datetimeimmutable.setdate) — Sets the date
* [DateTimeImmutable::setISODate](datetimeimmutable.setisodate) — Sets the ISO date
* [DateTimeImmutable::setTime](datetimeimmutable.settime) — Sets the time
* [DateTimeImmutable::setTimestamp](datetimeimmutable.settimestamp) — Sets the date and time based on a Unix timestamp
* [DateTimeImmutable::setTimezone](datetimeimmutable.settimezone) — Sets the time zone
* [DateTimeImmutable::sub](datetimeimmutable.sub) — Subtracts an amount of days, months, years, hours, minutes and seconds
php str_getcsv str\_getcsv
===========
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
str\_getcsv — Parse a CSV string into an array
### Description
```
str_getcsv(
string $string,
string $separator = ",",
string $enclosure = "\"",
string $escape = "\\"
): array
```
Parses a string input for fields in CSV format and returns an array containing the fields read.
>
> **Note**:
>
>
> The locale settings are taken into account by this function. If `LC_CTYPE` is e.g. `en_US.UTF-8`, strings in one-byte encodings may be read wrongly by this function.
>
>
### Parameters
`string`
The string to parse.
`separator`
Set the field delimiter (one single-byte character only).
`enclosure`
Set the field enclosure character (one single-byte character only).
`escape`
Set the escape character (at most one single-byte character). Defaults as a backslash (`\`) An empty string (`""`) disables the proprietary escape mechanism.
> **Note**: Usually an `enclosure` character is escaped inside a field by doubling it; however, the `escape` character can be used as an alternative. So for the default parameter values `""` and `\"` have the same meaning. Other than allowing to escape the `enclosure` character the `escape` character has no special meaning; it isn't even meant to escape itself.
>
>
### Return Values
Returns an indexed array containing the fields read.
### Changelog
| Version | Description |
| --- | --- |
| 7.4.0 | The `escape` parameter now interprets an empty string as signal to disable the proprietary escape mechanism. Formerly, an empty string was treated like the default parameter value. |
### Examples
**Example #1 **str\_getcsv()** example**
```
<?php
$string = 'PHP,Java,Python,Kotlin,Swift';
$data = str_getcsv($string);
var_dump($data);
?>
```
The above example will output:
```
array(5) {
[0]=>
string(3) "PHP"
[1]=>
string(4) "Java"
[2]=>
string(6) "Python"
[3]=>
string(6) "Kotlin"
[4]=>
string(5) "Swift"
}
```
### See Also
* [fgetcsv()](function.fgetcsv) - Gets line from file pointer and parse for CSV fields
php The SplObserver interface
The SplObserver interface
=========================
Introduction
------------
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
The **SplObserver** interface is used alongside [SplSubject](class.splsubject) to implement the Observer Design Pattern.
Interface synopsis
------------------
interface **SplObserver** { /\* Methods \*/
```
public update(SplSubject $subject): void
```
} Table of Contents
-----------------
* [SplObserver::update](splobserver.update) — Receive update from subject
php imap_deletemailbox imap\_deletemailbox
===================
(PHP 4, PHP 5, PHP 7, PHP 8)
imap\_deletemailbox — Delete a mailbox
### Description
```
imap_deletemailbox(IMAP\Connection $imap, string $mailbox): bool
```
Deletes the specified `mailbox`.
### Parameters
`imap`
An [IMAP\Connection](class.imap-connection) instance.
`mailbox`
The mailbox name, see [imap\_open()](function.imap-open) for more information
**Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. |
### See Also
* [imap\_createmailbox()](function.imap-createmailbox) - Create a new mailbox
* [imap\_renamemailbox()](function.imap-renamemailbox) - Rename an old mailbox to new mailbox
* [imap\_open()](function.imap-open) - Open an IMAP stream to a mailbox for the format of `mbox`
php is_float is\_float
=========
(PHP 4, PHP 5, PHP 7, PHP 8)
is\_float — Finds whether the type of a variable is float
### Description
```
is_float(mixed $value): bool
```
Finds whether the type of the given variable is float.
>
> **Note**:
>
>
> To test if a variable is a number or a numeric string (such as form input, which is always a string), you must use [is\_numeric()](function.is-numeric).
>
>
### Parameters
`value`
The variable being evaluated.
### Return Values
Returns **`true`** if `value` is a float, **`false`** otherwise.
### Examples
**Example #1 **is\_float()** example**
```
var_dump(is_float(27.25));
var_dump(is_float('abc'));
var_dump(is_float(23));
var_dump(is_float(23.5));
var_dump(is_float(1e7)); //Scientific Notation
var_dump(is_float(true));
?>
```
The above example will output:
```
bool(true)
bool(false)
bool(false)
bool(true)
bool(true)
bool(false)
```
### See Also
* [is\_bool()](function.is-bool) - Finds out whether a variable is a boolean
* [is\_int()](function.is-int) - Find whether the type of a variable is integer
* [is\_numeric()](function.is-numeric) - Finds whether a variable is a number or a numeric string
* [is\_string()](function.is-string) - Find whether the type of a variable is string
* [is\_array()](function.is-array) - Finds whether a variable is an array
* [is\_object()](function.is-object) - Finds whether a variable is an object
php Imagick::trimImage Imagick::trimImage
==================
(PECL imagick 2, PECL imagick 3)
Imagick::trimImage — Remove edges from the image
### Description
```
public Imagick::trimImage(float $fuzz): bool
```
Remove edges that are the background color from the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.
### Parameters
`fuzz`
By default target must match a particular pixel color exactly. However, in many cases two colors may differ by a small amount. The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. This parameter represents the variation on the quantum range.
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
### Examples
**Example #1 Using **Imagick::trimImage()**:**
Trim an image, then display to the browser.
```
<?php
/* Create the object and read the image in */
$im = new Imagick("image.jpg");
/* Trim the image. */
$im->trimImage(0);
/* Ouput the image */
header("Content-Type: image/" . $im->getImageFormat());
echo $im;
?>
```
### See Also
* [Imagick::getQuantumDepth()](imagick.getquantumdepth) - Gets the quantum depth
* [Imagick::getQuantumRange()](imagick.getquantumrange) - Returns the Imagick quantum range
* [imagecropauto()](function.imagecropauto) - Crop an image automatically using one of the available modes
php array_values array\_values
=============
(PHP 4, PHP 5, PHP 7, PHP 8)
array\_values — Return all the values of an array
### Description
```
array_values(array $array): array
```
**array\_values()** returns all the values from the `array` and indexes the array numerically.
### Parameters
`array`
The array.
### Return Values
Returns an indexed array of values.
### Examples
**Example #1 **array\_values()** example**
```
<?php
$array = array("size" => "XL", "color" => "gold");
print_r(array_values($array));
?>
```
The above example will output:
```
Array
(
[0] => XL
[1] => gold
)
```
### See Also
* [array\_keys()](function.array-keys) - Return all the keys or a subset of the keys of an array
* [array\_combine()](function.array-combine) - Creates an array by using one array for keys and another for its values
php EventHttp::addServerAlias EventHttp::addServerAlias
=========================
(PECL event >= 1.4.0-beta)
EventHttp::addServerAlias — Adds a server alias to the HTTP server object
### Description
```
public EventHttp::addServerAlias( string $alias ): bool
```
Adds a server alias to the HTTP server object.
### Parameters
`alias` The alias to add.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **EventHttp::addServerAlias()** example**
```
<?php
$base = new EventBase();
$http = new EventHttp($base);
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!$http->bind("127.0.0.1", 8088)) {
exit("bind(1) failed\n");
};
if (!$http->addServerAlias("local.net")) {
exit("Failed to add server alias\n");
}
$http->setCallback("/about", function($req) {
echo "URI: ", $req->getUri(), PHP_EOL;
$req->sendReply(200, "OK");
});
$base->dispatch();
?>
```
### See Also
* [EventHttp::removeServerAlias()](eventhttp.removeserveralias) - Removes server alias
php mysqli_stmt::__construct mysqli\_stmt::\_\_construct
===========================
(PHP 5, PHP 7, PHP 8)
mysqli\_stmt::\_\_construct — Constructs a new [mysqli\_stmt](class.mysqli-stmt) object
### Description
public **mysqli\_stmt::\_\_construct**([mysqli](class.mysqli) `$mysql`, ?string `$query` = **`null`**) This method constructs a new [mysqli\_stmt](class.mysqli-stmt) object.
### Parameters
`link`
A valid [mysqli](class.mysqli) object.
`query`
The query, as a string. If this parameter is **`null`**, then the constructor behaves identically to [mysqli\_stmt\_init()](mysqli.stmt-init), otherwise it behaves as per [mysqli\_prepare()](mysqli.prepare).
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `query` is now nullable. |
### See Also
* [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution
* [mysqli\_stmt\_init()](mysqli.stmt-init) - Initializes a statement and returns an object for use with mysqli\_stmt\_prepare
php session_name session\_name
=============
(PHP 4, PHP 5, PHP 7, PHP 8)
session\_name — Get and/or set the current session name
### Description
```
session_name(?string $name = null): string|false
```
**session\_name()** returns the name of the current session. If `name` is given, **session\_name()** will update the session name and return the *old* session name.
If a new session `name` is supplied, **session\_name()** modifies the HTTP cookie (and output content when `session.transid` is enabled). Once the HTTP cookie is sent, **session\_name()** raises error. **session\_name()** must be called before [session\_start()](function.session-start) for the session to work properly.
The session name is reset to the default value stored in `session.name` at request startup time. Thus, you need to call **session\_name()** for every request (and before [session\_start()](function.session-start) is called).
### Parameters
`name`
The session name references the name of the session, which is used in cookies and URLs (e.g. `PHPSESSID`). It should contain only alphanumeric characters; it should be short and descriptive (i.e. for users with enabled cookie warnings). If `name` is specified and not **`null`**, the name of the current session is changed to its value.
**Warning** The session name can't consist of digits only, at least one letter must be present. Otherwise a new session id is generated every time.
### Return Values
Returns the name of the current session. If `name` is given and function updates the session name, name of the *old* session is returned, or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `name` is nullable now. |
| 7.2.0 | **session\_name()** checks session status, previously it only checked cookie status. Therefore, older **session\_name()** allows to call **session\_name()** after [session\_start()](function.session-start) which may crash PHP and may result in misbehaviors. |
### Examples
**Example #1 **session\_name()** example**
```
<?php
/* set the session name to WebsiteID */
$previous_name = session_name("WebsiteID");
echo "The previous session name was $previous_name<br />";
?>
```
### See Also
* The [session.name](https://www.php.net/manual/en/session.configuration.php#ini.session.name) configuration directive
| programming_docs |
php SolrQuery::getSortFields SolrQuery::getSortFields
========================
(PECL solr >= 0.9.2)
SolrQuery::getSortFields — Returns all the sort fields
### Description
```
public SolrQuery::getSortFields(): array
```
Returns all the sort fields
### Parameters
This function has no parameters.
### Return Values
Returns an array on success and **`null`** if none of the parameters was set.
php DOMCharacterData::substringData DOMCharacterData::substringData
===============================
(PHP 5, PHP 7, PHP 8)
DOMCharacterData::substringData — Extracts a range of data from the node
### Description
```
public DOMCharacterData::substringData(int $offset, int $count): string|false
```
Returns the specified substring.
### Parameters
`offset`
Start offset of substring to extract.
`count`
The number of characters to extract.
### Return Values
The specified substring. If the sum of `offset` and `count` exceeds the length, then all 16-bit units to the end of the data are returned.
### Errors/Exceptions
**`DOM_INDEX_SIZE_ERR`**
Raised if `offset` is negative or greater than the number of 16-bit units in data, or if `count` is negative.
### See Also
* [DOMCharacterData::appendData()](domcharacterdata.appenddata) - Append the string to the end of the character data of the node
* [DOMCharacterData::deleteData()](domcharacterdata.deletedata) - Remove a range of characters from the node
* [DOMCharacterData::insertData()](domcharacterdata.insertdata) - Insert a string at the specified 16-bit unit offset
* [DOMCharacterData::replaceData()](domcharacterdata.replacedata) - Replace a substring within the DOMCharacterData node
php Imagick::colorMatrixImage Imagick::colorMatrixImage
=========================
(PECL imagick 3 >= 3.3.0)
Imagick::colorMatrixImage — Description
### Description
```
public Imagick::colorMatrixImage(array $color_matrix = Imagick::CHANNEL_DEFAULT): bool
```
Apply color transformation to an image. The method permits saturation changes, hue rotation, luminance to alpha, and various other effects. Although variable-sized transformation matrices can be used, typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA (or RGBA with offsets). The matrix is similar to those used by Adobe Flash except offsets are in column 6 rather than 5 (in support of CMYKA images) and offsets are normalized (divide Flash offset by 255)
### Parameters
`color_matrix`
### Return Values
Returns **`true`** on success.
### Examples
**Example #1 **Imagick::colorMatrixImage()****
```
<?php
function colorMatrixImage($imagePath, $colorMatrix) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setImageOpacity(1);
//A color matrix should look like:
// $colorMatrix = [
// 1.5, 0.0, 0.0, 0.0, 0.0, -0.157,
// 0.0, 1.0, 0.5, 0.0, 0.0, -0.157,
// 0.0, 0.0, 1.5, 0.0, 0.0, -0.157,
// 0.0, 0.0, 0.0, 1.0, 0.0, 0.0,
// 0.0, 0.0, 0.0, 0.0, 1.0, 0.0,
// 0.0, 0.0, 0.0, 0.0, 0.0, 1.0
// ];
$background = new \Imagick();
$background->newPseudoImage($imagick->getImageWidth(), $imagick->getImageHeight(), "pattern:checkerboard");
$background->setImageFormat('png');
$imagick->setImageFormat('png');
$imagick->colorMatrixImage($colorMatrix);
$background->compositeImage($imagick, \Imagick::COMPOSITE_ATOP, 0, 0);
header("Content-Type: image/png");
echo $background->getImageBlob();
}
?>
```
php rtrim rtrim
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
rtrim — Strip whitespace (or other characters) from the end of a string
### Description
```
rtrim(string $string, string $characters = " \n\r\t\v\x00"): string
```
This function returns a string with whitespace (or other characters) stripped from the end of `string`.
Without the second parameter, **rtrim()** will strip these characters:
* " " (ASCII `32` (`0x20`)), an ordinary space.
* "\t" (ASCII `9` (`0x09`)), a tab.
* "\n" (ASCII `10` (`0x0A`)), a new line (line feed).
* "\r" (ASCII `13` (`0x0D`)), a carriage return.
* "\0" (ASCII `0` (`0x00`)), the `NULL`-byte.
* "\v" (ASCII `11` (`0x0B`)), a vertical tab.
### Parameters
`string`
The input string.
`characters`
You can also specify the characters you want to strip, by means of the `characters` parameter. Simply list all characters that you want to be stripped. With `..` you can specify a range of characters.
### Return Values
Returns the modified string.
### Examples
**Example #1 Usage example of **rtrim()****
```
<?php
$text = "\t\tThese are a few words :) ... ";
$binary = "\x09Example string\x0A";
$hello = "Hello World";
var_dump($text, $binary, $hello);
print "\n";
$trimmed = rtrim($text);
var_dump($trimmed);
$trimmed = rtrim($text, " \t.");
var_dump($trimmed);
$trimmed = rtrim($hello, "Hdle");
var_dump($trimmed);
// trim the ASCII control characters at the end of $binary
// (from 0 to 31 inclusive)
$clean = rtrim($binary, "\x00..\x1F");
var_dump($clean);
?>
```
The above example will output:
```
string(32) " These are a few words :) ... "
string(16) " Example string
"
string(11) "Hello World"
string(30) " These are a few words :) ..."
string(26) " These are a few words :)"
string(9) "Hello Wor"
string(15) " Example string"
```
### See Also
* [trim()](function.trim) - Strip whitespace (or other characters) from the beginning and end of a string
* [ltrim()](function.ltrim) - Strip whitespace (or other characters) from the beginning of a string
php PDO::getAvailableDrivers PDO::getAvailableDrivers
========================
pdo\_drivers
============
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 1.0.3)
PDO::getAvailableDrivers -- pdo\_drivers — Return an array of available PDO drivers
### Description
```
public static PDO::getAvailableDrivers(): array
```
```
pdo_drivers(): array
```
This function returns all currently available PDO drivers which can be used in `DSN` parameter of [PDO::\_\_construct()](pdo.construct).
### Parameters
This function has no parameters.
### Return Values
**PDO::getAvailableDrivers()** returns an array of PDO driver names. If no drivers are available, it returns an empty array.
### Examples
**Example #1 A **PDO::getAvailableDrivers()** example**
```
<?php
print_r(PDO::getAvailableDrivers());
?>
```
The above example will output something similar to:
```
Array
(
[0] => mysql
[1] => sqlite
)
```
php EventBase::dispatch EventBase::dispatch
===================
(PECL event >= 1.2.6-beta)
EventBase::dispatch — Dispatch pending events
### Description
```
public EventBase::dispatch(): void
```
Wait for events to become active, and run their callbacks. The same as [EventBase::loop()](eventbase.loop) with no flags set.
**Warning** Do *NOT* destroy the [EventBase](class.eventbase) object as long as resources of the associated `Event` objects are not released. Otherwise, it will lead to unpredictable results!
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [EventBase::loop()](eventbase.loop) - Dispatch pending events
php SQLite3::version SQLite3::version
================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3::version — Returns the SQLite3 library version as a string constant and as a number
### Description
```
public static SQLite3::version(): array
```
Returns the SQLite3 library version as a string constant and as a number.
### Parameters
This function has no parameters.
### Return Values
Returns an associative array with the keys "versionString" and "versionNumber".
### Examples
**Example #1 **SQLite3::version()** example**
```
<?php
print_r(SQLite3::version());
?>
```
The above example will output something similar to:
```
Array
(
[versionString] => 3.5.9
[versionNumber] => 3005009
)
```
php ImagickDraw::setStrokeDashOffset ImagickDraw::setStrokeDashOffset
================================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::setStrokeDashOffset — Specifies the offset into the dash pattern to start the dash
### Description
```
public ImagickDraw::setStrokeDashOffset(float $dash_offset): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Specifies the offset into the dash pattern to start the dash.
### Parameters
`dash_offset`
dash offset
### Return Values
No value is returned.
### Examples
**Example #1 **ImagickDraw::setStrokeDashOffset()** example**
```
<?php
function setStrokeDashOffset($strokeColor, $fillColor, $backgroundColor) {
$draw = new \ImagickDraw();
$draw->setStrokeColor($strokeColor);
$draw->setFillColor($fillColor);
$draw->setStrokeWidth(4);
$draw->setStrokeDashArray([20, 20]);
$draw->setStrokeDashOffset(0);
$draw->rectangle(100, 50, 225, 175);
//Start the dash effect halfway through the solid portion
$draw->setStrokeDashOffset(10);
$draw->rectangle(275, 50, 400, 175);
//Start the dash effect on the space portion
$draw->setStrokeDashOffset(20);
$draw->rectangle(100, 200, 225, 350);
$draw->setStrokeDashOffset(5);
$draw->rectangle(275, 200, 400, 350);
$image = new \Imagick();
$image->newImage(500, 400, $backgroundColor);
$image->setImageFormat("png");
$image->drawImage($draw);
header("Content-Type: image/png");
echo $image->getImageBlob();
}
?>
```
php The Lua class
The Lua class
=============
Introduction
------------
(PECL lua >=0.9.0)
Class synopsis
--------------
class **Lua** { /\* Constants \*/ const string [LUA\_VERSION](class.lua#lua.constants.lua-version) = Lua 5.1.4; /\* Methods \*/
```
public assign(string $name, string $value): mixed
```
```
public call(callable $lua_func, array $args = ?, int $use_self = 0): mixed
```
```
public __call(callable $lua_func, array $args = ?, int $use_self = 0): mixed
```
```
public __construct(string $lua_script_file = NULL)
```
```
public eval(string $statements): mixed
```
```
public getVersion(): string
```
```
public include(string $file): mixed
```
```
public registerCallback(string $name, callable $function): mixed
```
} Predefined Constants
--------------------
**`Lua::LUA_VERSION`** Table of Contents
-----------------
* [Lua::assign](lua.assign) — Assign a PHP variable to Lua
* [Lua::call](lua.call) — Call Lua functions
* [Lua::\_\_construct](lua.construct) — Lua constructor
* [Lua::eval](lua.eval) — Evaluate a string as Lua code
* [Lua::getVersion](lua.getversion) — The getversion purpose
* [Lua::include](lua.include) — Parse a Lua script file
* [Lua::registerCallback](lua.registercallback) — Register a PHP function to Lua
php imagejpeg imagejpeg
=========
(PHP 4, PHP 5, PHP 7, PHP 8)
imagejpeg — Output image to browser or file
### Description
```
imagejpeg(GdImage $image, resource|string|null $file = null, int $quality = -1): bool
```
**imagejpeg()** creates a JPEG file from the given `image`.
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`file`
The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or **`null`**, the raw image stream will be output directly.
`quality`
`quality` is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file). The default (`-1`) uses the default IJG quality value (about 75).
### Return Values
Returns **`true`** on success or **`false`** on failure.
**Caution**However, if libgd fails to output the image, this function returns **`true`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
### Examples
**Example #1 Outputting a JPEG image to the browser**
```
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Output the image
imagejpeg($im);
// Free up memory
imagedestroy($im);
?>
```
The above example will output something similar to:
**Example #2 Saving a JPEG image to a file**
```
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image as 'simpletext.jpg'
imagejpeg($im, 'simpletext.jpg');
// Free up memory
imagedestroy($im);
?>
```
**Example #3 Outputting the image at 75% quality to the browser**
```
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set the content type header - in this case image/jpeg
header('Content-Type: image/jpeg');
// Skip the to parameter using NULL, then set the quality to 75%
imagejpeg($im, NULL, 75);
// Free up memory
imagedestroy($im);
?>
```
### Notes
>
> **Note**:
>
>
> If you want to output Progressive JPEGs, you need to set interlacing on with [imageinterlace()](function.imageinterlace).
>
>
### See Also
* [imagepng()](function.imagepng) - Output a PNG image to either the browser or a file
* [imagegif()](function.imagegif) - Output image to browser or file
* [imagewbmp()](function.imagewbmp) - Output image to browser or file
* [imageinterlace()](function.imageinterlace) - Enable or disable interlace
* [imagetypes()](function.imagetypes) - Return the image types supported by this PHP build
php Yaf_Plugin_Abstract::preResponse Yaf\_Plugin\_Abstract::preResponse
==================================
(Yaf >=1.0.0)
Yaf\_Plugin\_Abstract::preResponse — The preResponse purpose
### Description
```
public Yaf_Plugin_Abstract::preResponse(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`request`
`response`
### Return Values
php ImagickDraw::render ImagickDraw::render
===================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::render — Renders all preceding drawing commands onto the image
### Description
```
public ImagickDraw::render(): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Renders all preceding drawing commands onto the image.
### Return Values
Returns **`true`** on success or **`false`** on failure.
php connection_aborted connection\_aborted
===================
(PHP 4, PHP 5, PHP 7, PHP 8)
connection\_aborted — Check whether client disconnected
### Description
```
connection_aborted(): int
```
Checks whether the client disconnected.
### Parameters
This function has no parameters.
### Return Values
Returns 1 if client disconnected, 0 otherwise.
### See Also
* [connection\_status()](function.connection-status) - Returns connection status bitfield
* [ignore\_user\_abort()](function.ignore-user-abort) - Set whether a client disconnect should abort script execution
* [Connection Handling](https://www.php.net/manual/en/features.connection-handling.php) for a complete description of connection handling in PHP.
php SQLite3::lastErrorCode SQLite3::lastErrorCode
======================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3::lastErrorCode — Returns the numeric result code of the most recent failed SQLite request
### Description
```
public SQLite3::lastErrorCode(): int
```
Returns the numeric result code of the most recent failed SQLite request.
### Parameters
This function has no parameters.
### Return Values
Returns an integer value representing the numeric result code of the most recent failed SQLite request.
php Ds\PriorityQueue::push Ds\PriorityQueue::push
======================
(PECL ds >= 1.0.0)
Ds\PriorityQueue::push — Pushes values into the queue
### Description
```
public Ds\PriorityQueue::push(mixed $value, int $priority): void
```
Pushes a `value` with a given `priority` into the queue.
### Parameters
`value`
The value to push into the queue.
`priority`
The priority associated with the value.
### Return Values
No value is returned.
### Examples
**Example #1 **Ds\PriorityQueue::push()** example**
```
<?php
$queue = new \Ds\PriorityQueue();
$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);
print_r($queue->pop());
print_r($queue->pop());
print_r($queue->pop());
?>
```
The above example will output something similar to:
```
string(1) "b"
string(1) "c"
string(1) "a"
```
php ftp_ssl_connect ftp\_ssl\_connect
=================
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
ftp\_ssl\_connect — Opens a Secure SSL-FTP connection
### Description
```
ftp_ssl_connect(string $hostname, int $port = 21, int $timeout = 90): FTP\Connection|false
```
**ftp\_ssl\_connect()** opens an *explicit* SSL-FTP connection to the specified `hostname`. That implies that **ftp\_ssl\_connect()** will succeed even if the server is not configured for SSL-FTP, or its certificate is invalid. Only when [ftp\_login()](function.ftp-login) is called, the client will send the appropriate AUTH FTP command, so [ftp\_login()](function.ftp-login) will fail in the mentioned cases.
>
> **Note**: **Why this function may not exist**
>
>
>
> Before PHP 7.0.0, **ftp\_ssl\_connect()** was only available if both the ftp module and the [OpenSSL](https://www.php.net/manual/en/ref.openssl.php) support have been built statically into php; this means that on Windows this function had been undefined in the official PHP builds. To have this function available on Windows, it had been necessary to compile own PHP binaries.
>
>
>
> **Note**:
>
>
> **ftp\_ssl\_connect()** is not intended for use with sFTP. To use sFTP with PHP, please see [ssh2\_sftp()](function.ssh2-sftp).
>
>
### Parameters
`hostname`
The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with `ftp://`.
`port`
This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.
`timeout`
This parameter specifies the timeout for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with [ftp\_set\_option()](function.ftp-set-option) and [ftp\_get\_option()](function.ftp-get-option).
### Return Values
Returns an [FTP\Connection](class.ftp-connection) instance on success, or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | Returns an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was returned. |
### Examples
**Example #1 **ftp\_ssl\_connect()** example**
```
<?php
// set up basic ssl connection
$ftp = ftp_ssl_connect($ftp_server);
// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);
if (!$login_result) {
// PHP will already have raised an E_WARNING level message in this case
die("can't login");
}
echo ftp_pwd($ftp);
// close the ssl connection
ftp_close($ftp);
?>
```
### See Also
* [ftp\_connect()](function.ftp-connect) - Opens an FTP connection
| programming_docs |
php tidyNode::isHtml tidyNode::isHtml
================
(PHP 5, PHP 7, PHP 8)
tidyNode::isHtml — Checks if a node is an element node
### Description
```
public tidyNode::isHtml(): bool
```
Tells if the node is an element node, but not the root node of the document.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if the node is an element node, but not the root node of the document, **`false`** otherwise.
### Changelog
| Version | Description |
| --- | --- |
| 7.3.24, 7.4.12 | This function has been fixed to have reasonable behavior. Previously, almost any node was reported as being an HTML node. |
### Examples
**Example #1 Extract HTML code from a mixed HTML document**
```
<?php
$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>
<?php
// PHP code
echo 'hello world!';
?>
<%
/* ASP code */
response.write("Hello World!")
%>
<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;
$tidy = tidy_parse_string($html);
$num = 0;
get_nodes($tidy->html());
function get_nodes($node) {
// check if the current node is of requested type
if($node->isHtml()) {
echo "\n\n# html node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}
// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}
?>
```
The above example will output:
```
# html node #1
<html>
<head>
<?php echo '<title>title</title>'; ?><#
/* JSTE code */
alert('Hello World');
#>
<title></title>
</head>
<body>
<?php
// PHP code
echo 'hello world!';
?><%
/* ASP code */
response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>
</html>
# html node #2
<head>
<?php echo '<title>title</title>'; ?><#
/* JSTE code */
alert('Hello World');
#>
<title></title>
</head>
# html node #3
<title></title>
# html node #4
<body>
<?php
// PHP code
echo 'hello world!';
?><%
/* ASP code */
response.write("Hello World!")
%><!-- Comments -->
Hello WorldOutside HTML
</body>
```
php VarnishAdmin::clearPanic VarnishAdmin::clearPanic
========================
(PECL varnish >= 0.4)
VarnishAdmin::clearPanic — Clear varnish instance panic messages
### Description
```
public VarnishAdmin::clearPanic(): int
```
### Parameters
This function has no parameters.
### Return Values
Returns the varnish command status.
php SessionHandlerInterface::read SessionHandlerInterface::read
=============================
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
SessionHandlerInterface::read — Read session data
### Description
```
public SessionHandlerInterface::read(string $id): string|false
```
Reads the session data from the session storage, and returns the results. Called right after the session starts or when [session\_start()](function.session-start) is called. Please note that before this method is called [SessionHandlerInterface::open()](sessionhandlerinterface.open) is invoked.
This method is called by PHP itself when the session is started. This method should retrieve the session data from storage by the session ID provided. The string returned by this method must be in the same serialized format as when originally passed to the [SessionHandlerInterface::write()](sessionhandlerinterface.write) If the record was not found, return **`false`**.
The data returned by this method will be decoded internally by PHP using the unserialization method specified in [session.serialize\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.serialize-handler). The resulting data will be used to populate the [$\_SESSION](reserved.variables.session) superglobal.
Note that the serialization scheme is not the same as [unserialize()](function.unserialize) and can be accessed by [session\_decode()](function.session-decode).
### Parameters
`id`
The session id.
### Return Values
Returns an encoded string of the read data. If nothing was read, it must return **`false`**. Note this value is returned internally to PHP for processing.
### See Also
* The [session.serialize\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.serialize-handler) configuration directive.
php yaml_parse_file yaml\_parse\_file
=================
(PECL yaml >= 0.4.0)
yaml\_parse\_file — Parse a YAML stream from a file
### Description
```
yaml_parse_file(
string $filename,
int $pos = 0,
int &$ndocs = ?,
array $callbacks = null
): mixed
```
Convert all or part of a YAML document stream read from a file to a PHP variable.
### Parameters
`filename`
Path to the file.
`pos`
Document to extract from stream (`-1` for all documents, `0` for first document, ...).
`ndocs`
If `ndocs` is provided, then it is filled with the number of documents found in stream.
`callbacks`
Content handlers for YAML nodes. Associative array of YAML tag => [callable](language.types.callable) mappings. See [parse callbacks](https://www.php.net/manual/en/yaml.callbacks.parse.php) for more details.
### Return Values
Returns the value encoded in `input` in appropriate PHP type or **`false`** on failure. If `pos` is `-1` an array will be returned with one entry for each document found in the stream.
### Notes
**Warning** Processing untrusted user input with **yaml\_parse\_file()** is dangerous if the use of [unserialize()](function.unserialize) is enabled for nodes using the `!php/object` tag. This behavior can be disabled by using the `yaml.decode_php` ini setting.
### See Also
* [yaml\_parse()](function.yaml-parse) - Parse a YAML stream
* [yaml\_parse\_url()](function.yaml-parse-url) - Parse a Yaml stream from a URL
* [yaml\_emit()](function.yaml-emit) - Returns the YAML representation of a value
php eio_readlink eio\_readlink
=============
(PECL eio >= 0.0.1dev)
eio\_readlink — Read value of a symbolic link
### Description
```
eio_readlink(
string $path,
int $pri,
callable $callback,
mixed $data = NULL
): resource
```
### Parameters
`path`
Source symbolic link path
`pri`
The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**.
`callback`
`callback` function is called when the request is done. It should match the following prototype:
```
void callback(mixed $data, int $result[, resource $req]);
```
`data`
is custom data passed to the request.
`result`
request-specific result value; basically, the value returned by corresponding system call.
`req`
is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error)
`data`
Arbitrary variable passed to `callback`.
### Return Values
**eio\_readlink()** returns request resource on success, or **`false`** on failure.
### Examples
**Example #1 **eio\_readlink()** example**
```
<?php
$filename = dirname(__FILE__)."/symlink.dat";
touch($filename);
$link = dirname(__FILE__)."/symlink.link";
$hardlink = dirname(__FILE__)."/hardlink.link";
function my_hardlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && !is_link($data));
@unlink($data);
eio_symlink($filename, $link, EIO_PRI_DEFAULT, "my_symlink_cb", $link);
}
function my_symlink_cb($data, $result) {
global $link, $filename;
var_dump(file_exists($data) && is_link($data));
if (!eio_readlink($data, EIO_PRI_DEFAULT, "my_readlink_cb", NULL)) {
@unlink($link);
@unlink($filename);
}
}
function my_readlink_cb($data, $result) {
global $filename, $link;
var_dump($result);
@unlink($link);
@unlink($filename);
}
eio_link($filename, $hardlink, EIO_PRI_DEFAULT, "my_hardlink_cb", $hardlink);
eio_event_loop();
?>
```
The above example will output something similar to:
```
bool(true)
bool(true)
string(16) "/tmp/symlink.dat"
```
### See Also
* [eio\_symlink()](function.eio-symlink) - Create a symbolic link
php Fiber::isTerminated Fiber::isTerminated
===================
(PHP 8 >= 8.1.0)
Fiber::isTerminated — Determines if the fiber has terminated
### Description
```
public Fiber::isTerminated(): bool
```
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** only after the fiber has terminated, either by returning or throwing an exception; otherwise **`false`** is returned.
php None Examples
--------
**Example #1 Basic limited values**
```
<?php
enum SortOrder
{
case Asc;
case Desc;
}
function query($fields, $filter, SortOrder $order = SortOrder::Asc) { ... }
?>
```
The `query()` function can now proceed safe in the knowledge that `$order` is guaranteed to be either `SortOrder::Asc` or `SortOrder::Desc`. Any other value would have resulted in a [TypeError](class.typeerror), so no further error checking or testing is needed.
**Example #2 Advanced exclusive values**
```
<?php
enum UserStatus: string
{
case Pending = 'P';
case Active = 'A';
case Suspended = 'S';
case CanceledByUser = 'C';
public function label(): string
{
return match($this) {
static::Pending => 'Pending',
static::Active => 'Active',
static::Suspended => 'Suspended',
static::CanceledByUser => 'Canceled by user',
};
}
}
?>
```
In this example, a user's status may be one of, and exclusively, `UserStatus::Pending`, `UserStatus::Active`, `UserStatus::Suspended`, or `UserStatus::CanceledByUser`. A function can type a parameter against `UserStatus` and then only accept those four values, period.
All four values have a `label()` method, which returns a human-readable string. That string is independent of the "machine name" scalar equivalent string, which can be used in, for example, a database field or an HTML select box.
```
<?php
foreach (UserStatus::cases() as $case) {
printf('<option value="%s">%s</option>\n', $case->value, $case->label());
}
?>
```
php imagewebp imagewebp
=========
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
imagewebp — Output a WebP image to browser or file
### Description
```
imagewebp(GdImage $image, resource|string|null $file = null, int $quality = -1): bool
```
Outputs or saves a WebP version of the given `image`.
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`file`
The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or **`null`**, the raw image stream will be output directly.
`quality`
`quality` ranges from 0 (worst quality, smaller file) to 100 (best quality, biggest file).
### Return Values
Returns **`true`** on success or **`false`** on failure.
**Caution**However, if libgd fails to output the image, this function returns **`true`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
### Examples
**Example #1 Saving an WebP file**
```
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'WebP with PHP', $text_color);
// Save the image
imagewebp($im, 'php.webp');
// Free up memory
imagedestroy($im);
?>
```
php The ReflectionType class
The ReflectionType class
========================
Introduction
------------
(PHP 7, PHP 8)
The **ReflectionType** class reports information about a function's parameter/return type or a class's property type. The Reflection extension declares the following subtypes:
* [ReflectionNamedType](class.reflectionnamedtype) (as of PHP 7.1.0)
* [ReflectionUnionType](class.reflectionuniontype) (as of PHP 8.0.0)
* [ReflectionIntersectionType](class.reflectionintersectiontype) (as of PHP 8.1.0)
Class synopsis
--------------
abstract class **ReflectionType** implements [Stringable](class.stringable) { /\* Methods \*/
```
public allowsNull(): bool
```
```
public __toString(): string
```
} Changelog
---------
| Version | Description |
| --- | --- |
| 8.0.0 | **ReflectionType** has become abstract and **ReflectionType::isBuiltin()** has been moved to [ReflectionNamedType::isBuiltin()](reflectionnamedtype.isbuiltin). |
Table of Contents
-----------------
* [ReflectionType::allowsNull](reflectiontype.allowsnull) — Checks if null is allowed
* [ReflectionType::\_\_toString](reflectiontype.tostring) — To string
php The OpenSSLCertificate class
The OpenSSLCertificate class
============================
Introduction
------------
(PHP 8)
A fully opaque class which replaces `OpenSSL X.509` resources as of PHP 8.0.0.
Class synopsis
--------------
final class **OpenSSLCertificate** { }
php gmp_root gmp\_root
=========
(PHP 5 >= 5.6.0, PHP 7, PHP 8)
gmp\_root — Take the integer part of nth root
### Description
```
gmp_root(GMP|int|string $num, int $nth): GMP
```
Takes the `nth` root of `num` and returns the integer component of the result.
### Parameters
`num`
A [GMP](class.gmp) object, an int or a numeric string.
`nth`
The positive root to take of `num`.
### Return Values
The integer component of the resultant root, as a GMP number.
php VarnishAdmin::stop VarnishAdmin::stop
==================
(PECL varnish >= 0.3)
VarnishAdmin::stop — Stop varnish worker process
### Description
```
public VarnishAdmin::stop(): int
```
### Parameters
This function has no parameters.
### Return Values
Returns the varnish command status.
php token_name token\_name
===========
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
token\_name — Get the symbolic name of a given PHP token
### Description
```
token_name(int $id): string
```
**token\_name()** gets the symbolic name for a PHP `id` value.
### Parameters
`id`
The token value.
### Return Values
The symbolic name of the given `id`.
### Examples
**Example #1 **token\_name()** example**
```
<?php
// 260 is the token value for the T_EVAL token
echo token_name(260); // -> "T_EVAL"
// a token constant maps to its own name
echo token_name(T_FUNCTION); // -> "T_FUNCTION"
?>
```
### See Also
* [List of Parser Tokens](https://www.php.net/manual/en/tokens.php)
* [PhpToken::getTokenName()](phptoken.gettokenname) - Returns the name of the token.
php SQLite3Stmt::close SQLite3Stmt::close
==================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3Stmt::close — Closes the prepared statement
### Description
```
public SQLite3Stmt::close(): bool
```
Closes the prepared statement.
> **Note**: Note that all [SQLite3Result](class.sqlite3result)s that have been retrieved by executing this statement will be invalidated when the statement is closed.
>
>
### Parameters
This function has no parameters.
### Return Values
Returns **`true`**
php ReflectionFunction::getClosure ReflectionFunction::getClosure
==============================
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
ReflectionFunction::getClosure — Returns a dynamically created closure for the function
### Description
```
public ReflectionFunction::getClosure(): Closure
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
Returns [Closure](class.closure). Returns **`null`** in case of an error.
php streamWrapper::__construct streamWrapper::\_\_construct
============================
(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)
streamWrapper::\_\_construct — Constructs a new stream wrapper
### Description
public **streamWrapper::\_\_construct**() Called when opening the stream wrapper, right before [streamWrapper::stream\_open()](streamwrapper.stream-open).
### Parameters
This function has no parameters.
php GearmanClient::setWorkloadCallback GearmanClient::setWorkloadCallback
==================================
(PECL gearman >= 0.5.0)
GearmanClient::setWorkloadCallback — Set a callback for accepting incremental data updates
### Description
```
public GearmanClient::setWorkloadCallback(callable $callback): bool
```
Sets a function to be called when a worker needs to send back data prior to job completion. A worker can do this when it needs to send updates, send partial results, or flush data during long running jobs. The callback should accept a single argument, a [GearmanTask](class.gearmantask) object.
### Parameters
`callback`
A function to call
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [GearmanClient::setDataCallback()](gearmanclient.setdatacallback) - Callback function when there is a data packet for a task
* [GearmanClient::setCompleteCallback()](gearmanclient.setcompletecallback) - Set a function to be called on task completion
* [GearmanClient::setCreatedCallback()](gearmanclient.setcreatedcallback) - Set a callback for when a task is queued
* [GearmanClient::setExceptionCallback()](gearmanclient.setexceptioncallback) - Set a callback for worker exceptions
* [GearmanClient::setFailCallback()](gearmanclient.setfailcallback) - Set callback for job failure
* [GearmanClient::setStatusCallback()](gearmanclient.setstatuscallback) - Set a callback for collecting task status
* [GearmanClient::setWarningCallback()](gearmanclient.setwarningcallback) - Set a callback for worker warnings
php DOMNode::insertBefore DOMNode::insertBefore
=====================
(PHP 5, PHP 7, PHP 8)
DOMNode::insertBefore — Adds a new child before a reference node
### Description
```
public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false
```
This function inserts a new node right before the reference node. If you plan to do further modifications on the appended child you must use the returned node.
When using an existing node it will be moved.
### Parameters
`node`
The new node.
`child`
The reference node. If not supplied, `node` is appended to the children.
### Return Values
The inserted node.
### Errors/Exceptions
**`DOM_NO_MODIFICATION_ALLOWED_ERR`**
Raised if this node is readonly or if the previous parent of the node being inserted is readonly.
**`DOM_HIERARCHY_REQUEST_ERR`**
Raised if this node is of a type that does not allow children of the type of the `node` node, or if the node to append is one of this node's ancestors or this node itself.
**`DOM_WRONG_DOCUMENT_ERR`**
Raised if `node` was created from a different document than the one that created this node.
**`DOM_NOT_FOUND`**
Raised if `child` is not a child of this node.
### See Also
* [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children
php pack pack
====
(PHP 4, PHP 5, PHP 7, PHP 8)
pack — Pack data into binary string
### Description
```
pack(string $format, mixed ...$values): string
```
Pack given arguments into a binary string according to `format`.
The idea for this function was taken from Perl and all formatting codes work the same as in Perl. However, there are some formatting codes that are missing such as Perl's "u" format code.
Note that the distinction between signed and unsigned values only affects the function [unpack()](function.unpack), where as function **pack()** gives the same result for signed and unsigned format codes.
### Parameters
`format`
The `format` string consists of format codes followed by an optional repeater argument. The repeater argument can be either an integer value or `*` for repeating to the end of the input data. For a, A, h, H the repeat count specifies how many characters of one data argument are taken, for @ it is the absolute position where to put the next data, for everything else the repeat count specifies how many data arguments are consumed and packed into the resulting binary string.
Currently implemented formats are:
****pack()** format characters**| Code | Description |
| --- | --- |
| a | NUL-padded string |
| A | SPACE-padded string |
| h | Hex string, low nibble first |
| H | Hex string, high nibble first |
| c | signed char |
| C | unsigned char |
| s | signed short (always 16 bit, machine byte order) |
| S | unsigned short (always 16 bit, machine byte order) |
| n | unsigned short (always 16 bit, big endian byte order) |
| v | unsigned short (always 16 bit, little endian byte order) |
| i | signed integer (machine dependent size and byte order) |
| I | unsigned integer (machine dependent size and byte order) |
| l | signed long (always 32 bit, machine byte order) |
| L | unsigned long (always 32 bit, machine byte order) |
| N | unsigned long (always 32 bit, big endian byte order) |
| V | unsigned long (always 32 bit, little endian byte order) |
| q | signed long long (always 64 bit, machine byte order) |
| Q | unsigned long long (always 64 bit, machine byte order) |
| J | unsigned long long (always 64 bit, big endian byte order) |
| P | unsigned long long (always 64 bit, little endian byte order) |
| f | float (machine dependent size and representation) |
| g | float (machine dependent size, little endian byte order) |
| G | float (machine dependent size, big endian byte order) |
| d | double (machine dependent size and representation) |
| e | double (machine dependent size, little endian byte order) |
| E | double (machine dependent size, big endian byte order) |
| x | NUL byte |
| X | Back up one byte |
| Z | NUL-padded string |
| @ | NUL-fill to absolute position |
`values`
### Return Values
Returns a binary string containing data, or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | This function no longer returns **`false`** on failure. |
| 7.2.0 | float and double types supports both Big Endian and Little Endian. |
| 7.0.15,7.1.1 | The "e", "E", "g" and "G" codes were added to enable byte order support for float and double. |
### Examples
**Example #1 **pack()** example**
```
<?php
$binarydata = pack("nvc*", 0x1234, 0x5678, 65, 66);
?>
```
The resulting binary string will be 6 bytes long and contain the byte sequence 0x12, 0x34, 0x78, 0x56, 0x41, 0x42.
### Notes
**Caution** Note that PHP internally stores int values as signed values of a machine-dependent size (C type `long`). Integer literals and operations that yield numbers outside the bounds of the int type will be stored as float. When packing these floats as integers, they are first cast into the integer type. This may or may not result in the desired byte pattern.
The most relevant case is when packing unsigned numbers that would be representable with the int type if it were unsigned. In systems where the int type has a 32-bit size, the cast usually results in the same byte pattern as if the int were unsigned (although this relies on implementation-defined unsigned to signed conversions, as per the C standard). In systems where the int type has 64-bit size, the float most likely does not have a mantissa large enough to hold the value without loss of precision. If those systems also have a native 64-bit C `int` type (most UNIX-like systems don't), the only way to use the `I` pack format in the upper range is to create int negative values with the same byte representation as the desired unsigned value.
### See Also
* [unpack()](function.unpack) - Unpack data from binary string
| programming_docs |
php mysqli_get_links_stats mysqli\_get\_links\_stats
=========================
(PHP 5 >= 5.6.0, PHP 7, PHP 8)
mysqli\_get\_links\_stats — Return information about open and cached links
### Description
```
mysqli_get_links_stats(): array
```
**mysqli\_get\_links\_stats()** returns information about open and cached MySQL links.
### Parameters
This function has no parameters.
### Return Values
**mysqli\_get\_links\_stats()** returns an associative array with three elements, keyed as follows:
`total`
An int indicating the total number of open links in any state.
`active_plinks`
An int representing the number of active persistent connections.
`cached_plinks`
An int representing the number of inactive persistent connections.
php Yaf_View_Simple::__set Yaf\_View\_Simple::\_\_set
==========================
(Yaf >=1.0.0)
Yaf\_View\_Simple::\_\_set — Set value to engine
### Description
```
public Yaf_View_Simple::__set(string $name, mixed $value): void
```
This is a alternative and easier way to [Yaf\_View\_Simple::assign()](yaf-view-simple.assign).
### Parameters
`name`
A string value name.
`value`
Mixed value.
### Return Values
### Examples
**Example #1 **Yaf\_View\_Simple::\_\_set()**example**
```
<?php
class IndexController extends Yaf_Controller_Abstract {
public function indexAction() {
$this->getView()->foo = "bar"; // same as assign("foo", "bar");
}
}
?>
```
### See Also
* [Yaf\_View\_Simple::assignRef()](yaf-view-simple.assignref) - The assignRef purpose
* [Yaf\_View\_Interface::assign()](yaf-view-interface.assign) - Assign value to View engine
php RecursiveFilterIterator::__construct RecursiveFilterIterator::\_\_construct
======================================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
RecursiveFilterIterator::\_\_construct — Create a RecursiveFilterIterator from a RecursiveIterator
### Description
public **RecursiveFilterIterator::\_\_construct**([RecursiveIterator](class.recursiveiterator) `$iterator`) Create a [RecursiveFilterIterator](class.recursivefilteriterator) from a [RecursiveIterator](class.recursiveiterator).
### Parameters
`iterator`
The [RecursiveIterator](class.recursiveiterator) to be filtered.
### Examples
**Example #1 Basic **RecursiveFilterIterator()** example**
```
<?php
class TestsOnlyFilter extends RecursiveFilterIterator {
public function accept() {
// Accept the current item if we can recurse into it
// or it is a value starting with "test"
return $this->hasChildren() || (strpos($this->current(), "test") !== FALSE);
}
}
$array = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter = new TestsOnlyFilter($iterator);
foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
echo $value . "\n";
}
?>
```
The above example will output something similar to:
```
test1
test3
test4
test5
```
**Example #2 **RecursiveFilterIterator()** example**
```
<?php
class StartsWithFilter extends RecursiveFilterIterator {
protected $word;
public function __construct(RecursiveIterator $rit, $word) {
$this->word = $word;
parent::__construct($rit);
}
public function accept() {
return $this->hasChildren() OR strpos($this->current(), $this->word) === 0;
}
public function getChildren() {
return new self($this->getInnerIterator()->getChildren(), $this->word);
}
}
$array = array("test1", array("taste2", "test3", "test4"), "test5");
$iterator = new RecursiveArrayIterator($array);
$filter = new StartsWithFilter($iterator, "test");
foreach(new RecursiveIteratorIterator($filter) as $key => $value)
{
echo $value . "\n";
}
?>
```
The above example will output something similar to:
```
test1
test3
test4
test5
```
### See Also
* [RecursiveFilterIterator::getChildren()](recursivefilteriterator.getchildren) - Return the inner iterator's children contained in a RecursiveFilterIterator
* [RecursiveFilterIterator::hasChildren()](recursivefilteriterator.haschildren) - Check whether the inner iterator's current element has children
* [FilterIterator::accept()](filteriterator.accept) - Check whether the current element of the iterator is acceptable
php Gmagick::getimagescene Gmagick::getimagescene
======================
(PECL gmagick >= Unknown)
Gmagick::getimagescene — Gets the image scene
### Description
```
public Gmagick::getimagescene(): int
```
Gets the image scene.
### Parameters
This function has no parameters.
### Return Values
Returns the image scene.
### Errors/Exceptions
Throws an **GmagickException** on error.
php recode_file recode\_file
============
(PHP 4, PHP 5, PHP 7 < 7.4.0)
recode\_file — Recode from file to file according to recode request
### Description
```
recode_file(string $request, resource $input, resource $output): bool
```
Recode the file referenced by file handle `input` into the file referenced by file handle `output` according to the recode `request`.
### Parameters
`request`
The desired recode request type
`input`
A local file handle resource for the `input`
`output`
A local file handle resource for the `output`
### Return Values
Returns **`false`**, if unable to comply, **`true`** otherwise.
### Examples
**Example #1 Basic **recode\_file()** example**
```
<?php
$input = fopen('input.txt', 'r');
$output = fopen('output.txt', 'w');
recode_file("us..flat", $input, $output);
?>
```
### Notes
This function does not currently process file handles referencing remote files (URLs). Both file handles must refer to local files.
### See Also
* [fopen()](function.fopen) - Opens file or URL
php IntlCalendar::getWeekendTransition IntlCalendar::getWeekendTransition
==================================
(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)
IntlCalendar::getWeekendTransition — Get time of the day at which weekend begins or ends
### Description
Object-oriented style
```
public IntlCalendar::getWeekendTransition(int $dayOfWeek): int|false
```
Procedural style
```
intlcal_get_weekend_transition(IntlCalendar $calendar, int $dayOfWeek): int|false
```
Returns the number of milliseconds after midnight at which the weekend begins or ends.
This is only applicable for days of the week for which [IntlCalendar::getDayOfWeekType()](intlcalendar.getdayofweektype) returns either **`IntlCalendar::DOW_TYPE_WEEKEND_OFFSET`** or **`IntlCalendar::DOW_TYPE_WEEKEND_CEASE`**. Calling this function for other days of the week is an error condition.
This function requires ICU 4.4 or later.
### Parameters
`calendar`
An [IntlCalendar](class.intlcalendar) instance.
`dayOfWeek`
One of the constants **`IntlCalendar::DOW_SUNDAY`**, **`IntlCalendar::DOW_MONDAY`**, …, **`IntlCalendar::DOW_SATURDAY`**.
### Return Values
The number of milliseconds into the day at which the weekend begins or ends or **`false`** on failure.
### Examples
See example on [IntlCalendar::getDayOfWeekType()](intlcalendar.getdayofweektype).
php pspell_check pspell\_check
=============
(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)
pspell\_check — Check a word
### Description
```
pspell_check(PSpell\Dictionary $dictionary, string $word): bool
```
**pspell\_check()** checks the spelling of a word.
### Parameters
`dictionary`
An [PSpell\Dictionary](class.pspell-dictionary) instance.
`word`
The tested word.
### Return Values
Returns **`true`** if the spelling is correct, **`false`** if not.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `dictionary` parameter expects an [PSpell\Dictionary](class.pspell-dictionary) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **pspell\_check()** Example**
```
<?php
$pspell = pspell_new("en");
if (pspell_check($pspell, "testt")) {
echo "This is a valid spelling";
} else {
echo "Sorry, wrong spelling";
}
?>
```
php ldap_exop_whoami ldap\_exop\_whoami
==================
(PHP 7 >= 7.2.0, PHP 8)
ldap\_exop\_whoami — WHOAMI extended operation helper
### Description
```
ldap_exop_whoami(LDAP\Connection $ldap): string|false
```
Performs a WHOAMI extended operation and returns the data.
### Parameters
`ldap`
An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect).
### Return Values
The data returned by the server, or **`false`** on error.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. |
### See Also
* [ldap\_exop()](function.ldap-exop) - Performs an extended operation
php Phar::getAlias Phar::getAlias
==============
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.1)
Phar::getAlias — Get the alias for Phar
### Description
```
public Phar::getAlias(): ?string
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
Returns the alias or **`null`** if there's no alias.
php The Yar_Client_Exception class
The Yar\_Client\_Exception class
================================
Introduction
------------
(No version information available, might only be in Git)
Class synopsis
--------------
class **Yar\_Client\_Exception** extends [Exception](class.exception) { /\* Properties \*/ /\* Methods \*/
```
public getType(): string
```
/\* Inherited methods \*/
```
final public Exception::getMessage(): string
```
```
final public Exception::getPrevious(): ?Throwable
```
```
final public Exception::getCode(): int
```
```
final public Exception::getFile(): string
```
```
final public Exception::getLine(): int
```
```
final public Exception::getTrace(): array
```
```
final public Exception::getTraceAsString(): string
```
```
public Exception::__toString(): string
```
```
private Exception::__clone(): void
```
} Properties
----------
message code file line Table of Contents
-----------------
* [Yar\_Client\_Exception::getType](yar-client-exception.gettype) — Retrieve exception's type
php Exception::getMessage Exception::getMessage
=====================
(PHP 5, PHP 7, PHP 8)
Exception::getMessage — Gets the Exception message
### Description
```
final public Exception::getMessage(): string
```
Returns the Exception message.
### Parameters
This function has no parameters.
### Return Values
Returns the Exception message as a string.
### Examples
**Example #1 **Exception::getMessage()** example**
```
<?php
try {
throw new Exception("Some error message");
} catch(Exception $e) {
echo $e->getMessage();
}
?>
```
The above example will output something similar to:
```
Some error message
```
### See Also
* [Throwable::getMessage()](throwable.getmessage) - Gets the message
php SplHeap::compare SplHeap::compare
================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplHeap::compare — Compare elements in order to place them correctly in the heap while sifting up
### Description
```
protected SplHeap::compare(mixed $value1, mixed $value2): int
```
Compare `value1` with `value2`.
**Warning** Throwing exceptions in **SplHeap::compare()** can corrupt the Heap and place it in a blocked state. You can unblock it by calling [SplHeap::recoverFromCorruption()](splheap.recoverfromcorruption). However, some elements might not be placed correctly and it may hence break the heap-property.
### Parameters
`value1`
The value of the first node being compared.
`value2`
The value of the second node being compared.
### Return Values
Result of the comparison, positive integer if `value1` is greater than `value2`, 0 if they are equal, negative integer otherwise.
>
> **Note**:
>
>
> Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position.
>
>
php RarException::isUsingExceptions RarException::isUsingExceptions
===============================
(PECL rar >= 2.0.0)
RarException::isUsingExceptions — Check whether error handling with exceptions is in use
### Description
```
public static RarException::isUsingExceptions(): bool
```
Checks whether the RAR functions will emit warnings and return error values or whether they will throw exceptions in most of the circumstances (does not include some programmatic errors such as passing the wrong type of arguments).
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if exceptions are being used, **`false`** otherwise.
### Examples
**Example #1 **RarException::isUsingExceptions()** example**
```
<?php
//The default is not to use exceptions
var_dump(RarException::isUsingExceptions());
?>
```
The above example will output something similar to:
```
bool(false)
```
### See Also
* [RarException::setUsingExceptions()](rarexception.setusingexceptions) - Activate and deactivate error handling with exceptions
php shm_remove shm\_remove
===========
(PHP 4, PHP 5, PHP 7, PHP 8)
shm\_remove — Removes shared memory from Unix systems
### Description
```
shm_remove(SysvSharedMemory $shm): bool
```
**shm\_remove()** removes the shared memory `shm`. All data will be destroyed.
### Parameters
`shm`
A shared memory segment obtained from [shm\_attach()](function.shm-attach).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `shm` expects a [SysvSharedMemory](class.sysvsharedmemory) instance now; previously, a resource was expected. |
### See Also
* [shm\_remove\_var()](function.shm-remove-var) - Removes a variable from shared memory
php OAuthProvider::checkOAuthRequest OAuthProvider::checkOAuthRequest
================================
(PECL OAuth >= 1.0.0)
OAuthProvider::checkOAuthRequest — Check an oauth request
### Description
```
public OAuthProvider::checkOAuthRequest(string $uri = ?, string $method = ?): void
```
Checks an OAuth request.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`uri`
The optional URI, or endpoint.
`method`
The HTTP method. Optionally pass in one of the **`OAUTH_HTTP_METHOD_*`** [OAuth constants](https://www.php.net/manual/en/oauth.constants.php).
### Return Values
No value is returned.
### Errors/Exceptions
Emits an **`E_ERROR`** level error if the HTTP method cannot be detected.
### See Also
* [OAuthProvider::reportProblem()](oauthprovider.reportproblem) - Report a problem
php phpdbg_get_executable phpdbg\_get\_executable
=======================
(PHP 7, PHP 8)
phpdbg\_get\_executable —
### Description
```
phpdbg_get_executable(array $options = []): array
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`options`
### Return Values
php Ev::stop Ev::stop
========
(PECL ev >= 0.2.0)
Ev::stop — Stops the default event loop
### Description
```
final public static Ev::stop( int $how = ?): void
```
Stops the default event loop
### Parameters
`how` One of *Ev::BREAK\_\** [constants](class.ev#ev.constants.break-flags) .
### Return Values
No value is returned.
### See Also
* [Ev::run()](ev.run) - Begin checking for events and calling callbacks for the default loop
php DOMDocument::save DOMDocument::save
=================
(PHP 5, PHP 7, PHP 8)
DOMDocument::save — Dumps the internal XML tree back into a file
### Description
```
public DOMDocument::save(string $filename, int $options = 0): int|false
```
Creates an XML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below.
### Parameters
`filename`
The path to the saved XML document.
`options`
Additional Options. Currently only [LIBXML\_NOEMPTYTAG](https://www.php.net/manual/en/libxml.constants.php) is supported.
### Return Values
Returns the number of bytes written or **`false`** if an error occurred.
### Examples
**Example #1 Saving a DOM tree into a file**
```
<?php
$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;
$root = $doc->createElement('book');
$root = $doc->appendChild($root);
$title = $doc->createElement('title');
$title = $root->appendChild($title);
$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);
echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes
?>
```
### See Also
* [DOMDocument::saveXML()](domdocument.savexml) - Dumps the internal XML tree back into a string
* [DOMDocument::load()](domdocument.load) - Load XML from a file
* [DOMDocument::loadXML()](domdocument.loadxml) - Load XML from a string
php ftp_connect ftp\_connect
============
(PHP 4, PHP 5, PHP 7, PHP 8)
ftp\_connect — Opens an FTP connection
### Description
```
ftp_connect(string $hostname, int $port = 21, int $timeout = 90): FTP\Connection|false
```
**ftp\_connect()** opens an FTP connection to the specified `hostname`.
### Parameters
`hostname`
The FTP server address. This parameter shouldn't have any trailing slashes and shouldn't be prefixed with `ftp://`.
`port`
This parameter specifies an alternate port to connect to. If it is omitted or set to zero, then the default FTP port, 21, will be used.
`timeout`
This parameter specifies the timeout in seconds for all subsequent network operations. If omitted, the default value is 90 seconds. The timeout can be changed and queried at any time with [ftp\_set\_option()](function.ftp-set-option) and [ftp\_get\_option()](function.ftp-get-option).
### Return Values
Returns an [FTP\Connection](class.ftp-connection) instance on success, or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | Returns an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was returned. |
### Examples
**Example #1 **ftp\_connect()** example**
```
<?php
$ftp_server = "ftp.example.com";
// set up a connection or die
$ftp = ftp_connect($ftp_server) or die("Couldn't connect to $ftp_server");
?>
```
### See Also
* [ftp\_close()](function.ftp-close) - Closes an FTP connection
* [ftp\_ssl\_connect()](function.ftp-ssl-connect) - Opens a Secure SSL-FTP connection
php Generator::send Generator::send
===============
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
Generator::send — Send a value to the generator
### Description
```
public Generator::send(mixed $value): mixed
```
Sends the given value to the generator as the result of the current [yield](language.generators.syntax#control-structures.yield) expression and resumes execution of the generator.
If the generator is not at a [yield](language.generators.syntax#control-structures.yield) expression when this method is called, it will first be let to advance to the first [yield](language.generators.syntax#control-structures.yield) expression before sending the value. As such it is not necessary to "prime" PHP generators with a [Generator::next()](generator.next) call (like it is done in Python).
### Parameters
`value`
Value to send into the generator. This value will be the return value of the [yield](language.generators.syntax#control-structures.yield) expression the generator is currently at.
### Return Values
Returns the yielded value.
### Examples
**Example #1 Using **Generator::send()** to inject values**
```
<?php
function printer() {
echo "I'm printer!".PHP_EOL;
while (true) {
$string = yield;
echo $string.PHP_EOL;
}
}
$printer = printer();
$printer->send('Hello world!');
$printer->send('Bye world!');
?>
```
The above example will output:
```
I'm printer!
Hello world!
Bye world!
```
| programming_docs |
php None Conditional subpatterns
-----------------------
It is possible to cause the matching process to obey a subpattern conditionally or to choose between two alternative subpatterns, depending on the result of an assertion, or whether a previous capturing subpattern matched or not. The two possible forms of conditional subpattern are
```
(?(condition)yes-pattern)
(?(condition)yes-pattern|no-pattern)
```
If the condition is satisfied, the yes-pattern is used; otherwise the no-pattern (if present) is used. If there are more than two alternatives in the subpattern, a compile-time error occurs.
There are two kinds of condition. If the text between the parentheses consists of a sequence of digits, then the condition is satisfied if the capturing subpattern of that number has previously matched. Consider the following pattern, which contains non-significant white space to make it more readable (assume the [PCRE\_EXTENDED](reference.pcre.pattern.modifiers) option) and to divide it into three parts for ease of discussion:
```
( \( )? [^()]+ (?(1) \) )
```
The first part matches an optional opening parenthesis, and if that character is present, sets it as the first captured substring. The second part matches one or more characters that are not parentheses. The third part is a conditional subpattern that tests whether the first set of parentheses matched or not. If they did, that is, if subject started with an opening parenthesis, the condition is **`true`**, and so the yes-pattern is executed and a closing parenthesis is required. Otherwise, since no-pattern is not present, the subpattern matches nothing. In other words, this pattern matches a sequence of non-parentheses, optionally enclosed in parentheses.
If the condition is the string `(R)`, it is satisfied if a recursive call to the pattern or subpattern has been made. At "top level", the condition is false.
If the condition is not a sequence of digits or (R), it must be an assertion. This may be a positive or negative lookahead or lookbehind assertion. Consider this pattern, again containing non-significant white space, and with the two alternatives on the second line:
```
(?(?=[^a-z]*[a-z])
\d{2}-[a-z]{3}-\d{2} | \d{2}-\d{2}-\d{2} )
```
The condition is a positive lookahead assertion that matches an optional sequence of non-letters followed by a letter. In other words, it tests for the presence of at least one letter in the subject. If a letter is found, the subject is matched against the first alternative; otherwise it is matched against the second. This pattern matches strings in one of the two forms dd-aaa-dd or dd-dd-dd, where aaa are letters and dd are digits.
php ZipArchive::setCompressionIndex ZipArchive::setCompressionIndex
===============================
(PHP 7, PHP 8, PECL zip >= 1.13.0)
ZipArchive::setCompressionIndex — Set the compression method of an entry defined by its index
### Description
```
public ZipArchive::setCompressionIndex(int $index, int $method, int $compflags = 0): bool
```
Set the compression method of an entry defined by its index.
### Parameters
`index`
Index of the entry.
`method`
The compression method, one of the **`ZipArchive::CM_*`** constants.
`compflags`
Compression level.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Add files with different compression methods to an archive**
```
<?php
$zip = new ZipArchive;
$res = $zip->open('test.zip', ZipArchive::CREATE);
if ($res === TRUE) {
$zip->addFromString('foo', 'Some text');
$zip->addFromString('bar', 'Some other text');
$zip->setCompressionIndex(0, ZipArchive::CM_STORE);
$zip->setCompressionIndex(1, ZipArchive::CM_DEFLATE);
$zip->close();
echo 'ok';
} else {
echo 'failed';
}
?>
```
php svn_repos_open svn\_repos\_open
================
(PECL svn >= 0.1.0)
svn\_repos\_open — Open a shared lock on a repository
### Description
```
svn_repos_open(string $path): resource
```
**Warning**This function is currently not documented; only its argument list is available.
Open a shared lock on a repository.
### Notes
**Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
php Ds\Deque::merge Ds\Deque::merge
===============
(PECL ds >= 1.0.0)
Ds\Deque::merge — Returns the result of adding all given values to the deque
### Description
```
public Ds\Deque::merge(mixed $values): Ds\Deque
```
Returns the result of adding all given values to the deque.
### Parameters
`values`
A [traversable](class.traversable) object or an array.
### Return Values
The result of adding all given values to the deque, effectively the same as adding the values to a copy, then returning that copy.
>
> **Note**:
>
>
> The current instance won't be affected.
>
>
### Examples
**Example #1 **Ds\Deque::merge()** example**
```
<?php
$deque = new \Ds\Deque([1, 2, 3]);
var_dump($deque->merge([4, 5, 6]));
var_dump($deque);
?>
```
The above example will output something similar to:
```
object(Ds\Deque)#2 (6) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
[5]=>
int(6)
}
object(Ds\Deque)#1 (3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
```
php BackedEnum::from BackedEnum::from
================
(PHP 8 >= 8.1.0)
BackedEnum::from — Maps a scalar to an enum instance
### Description
```
public static BackedEnum::from(int|string $value): static
```
The **from()** method translates a string or int into the corresponding Enum case, if any. If there is no matching case defined, it will throw a [ValueError](class.valueerror).
### Parameters
`value`
The scalar value to map to an enum case.
### Return Values
A case instance of this enumeration.
### Examples
**Example #1 Basic usage**
The following example illustrates how enum cases are returned.
```
<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
$h = Suit::from('H');
var_dump($h);
$b = Suit::from('B');
?>
```
The above example will output:
```
enum(Suit::Hearts)
Fatal error: Uncaught ValueError: "B" is not a valid backing value for enum "Suit" in /file.php:15
```
### See Also
* [UnitEnum::cases()](unitenum.cases) - Generates a list of cases on an enum
* [BackedEnum::tryFrom()](backedenum.tryfrom) - Maps a scalar to an enum instance or null
php None Name resolution rules
---------------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
For the purposes of these resolution rules, here are some important definitions:
**Namespace name definitions** Unqualified name This is an identifier without a namespace separator, such as `Foo`
Qualified name This is an identifier with a namespace separator, such as `Foo\Bar`
Fully qualified name This is an identifier with a namespace separator that begins with a namespace separator, such as `\Foo\Bar`. The namespace `\Foo` is also a fully qualified name.
Relative name This is an identifier starting with `namespace`, such as `namespace\Foo\Bar`.
Names are resolved following these resolution rules:
1. Fully qualified names always resolve to the name without leading namespace separator. For instance `\A\B` resolves to `A\B`.
2. Relative names always resolve to the name with `namespace` replaced by the current namespace. If the name occurs in the global namespace, the `namespace\` prefix is stripped. For example `namespace\A` inside namespace `X\Y` resolves to `X\Y\A`. The same name inside the global namespace resolves to `A`.
3. For qualified names the first segment of the name is translated according to the current class/namespace import table. For example, if the namespace `A\B\C` is imported as `C`, the name `C\D\E` is translated to `A\B\C\D\E`.
4. For qualified names, if no import rule applies, the current namespace is prepended to the name. For example, the name `C\D\E` inside namespace `A\B`, resolves to `A\B\C\D\E`.
5. For unqualified names, the name is translated according to the current import table for the respective symbol type. This means that class-like names are translated according to the class/namespace import table, function names according to the function import table and constants according to the constant import table. For example, after `use A\B\C;` a usage such as `new C()` resolves to the name `A\B\C()`. Similarly, after `use function A\B\fn;` a usage such as `fn()` resolves to the name `A\B\fn`.
6. For unqualified names, if no import rule applies and the name refers to a class-like symbol, the current namespace is prepended. For example `new C()` inside namespace `A\B` resolves to name `A\B\C`.
7. For unqualified names, if no import rule applies and the name refers to a function or constant and the code is outside the global namespace, the name is resolved at runtime. Assuming the code is in namespace `A\B`, here is how a call to function `foo()` is resolved:
1. It looks for a function from the current namespace: `A\B\foo()`.
2. It tries to find and call the *global* function `foo()`.
**Example #1 Name resolutions illustrated**
```
<?php
namespace A;
use B\D, C\E as F;
// function calls
foo(); // first tries to call "foo" defined in namespace "A"
// then calls global function "foo"
\foo(); // calls function "foo" defined in global scope
my\foo(); // calls function "foo" defined in namespace "A\my"
F(); // first tries to call "F" defined in namespace "A"
// then calls global function "F"
// class references
new B(); // creates object of class "B" defined in namespace "A"
// if not found, it tries to autoload class "A\B"
new D(); // using import rules, creates object of class "D" defined in namespace "B"
// if not found, it tries to autoload class "B\D"
new F(); // using import rules, creates object of class "E" defined in namespace "C"
// if not found, it tries to autoload class "C\E"
new \B(); // creates object of class "B" defined in global scope
// if not found, it tries to autoload class "B"
new \D(); // creates object of class "D" defined in global scope
// if not found, it tries to autoload class "D"
new \F(); // creates object of class "F" defined in global scope
// if not found, it tries to autoload class "F"
// static methods/namespace functions from another namespace
B\foo(); // calls function "foo" from namespace "A\B"
B::foo(); // calls method "foo" of class "B" defined in namespace "A"
// if class "A\B" not found, it tries to autoload class "A\B"
D::foo(); // using import rules, calls method "foo" of class "D" defined in namespace "B"
// if class "B\D" not found, it tries to autoload class "B\D"
\B\foo(); // calls function "foo" from namespace "B"
\B::foo(); // calls method "foo" of class "B" from global scope
// if class "B" not found, it tries to autoload class "B"
// static methods/namespace functions of current namespace
A\B::foo(); // calls method "foo" of class "B" from namespace "A\A"
// if class "A\A\B" not found, it tries to autoload class "A\A\B"
\A\B::foo(); // calls method "foo" of class "B" from namespace "A"
// if class "A\B" not found, it tries to autoload class "A\B"
?>
```
php PDOStatement::bindColumn PDOStatement::bindColumn
========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0)
PDOStatement::bindColumn — Bind a column to a PHP variable
### Description
```
public PDOStatement::bindColumn(
string|int $column,
mixed &$var,
int $type = PDO::PARAM_STR,
int $maxLength = 0,
mixed $driverOptions = null
): bool
```
**PDOStatement::bindColumn()** arranges to have a particular variable bound to a given column in the result-set from a query. Each call to [PDOStatement::fetch()](pdostatement.fetch) or [PDOStatement::fetchAll()](pdostatement.fetchall) will update all the variables that are bound to columns.
>
> **Note**:
>
>
> Since information about the columns is not always available to PDO until the statement is executed, portable applications should call this function *after* [PDOStatement::execute()](pdostatement.execute).
>
> However, to be able to bind a LOB column as a stream when using the *PgSQL driver*, applications should call this method *before* calling [PDOStatement::execute()](pdostatement.execute), otherwise the large object OID will be returned as an integer.
>
>
### Parameters
`column`
Number of the column (1-indexed) or name of the column in the result set. If using the column name, be aware that the name should match the case of the column, as returned by the driver.
`var`
Name of the PHP variable to which the column will be bound.
`type`
Data type of the parameter, specified by the [`PDO::PARAM_*` constants](https://www.php.net/manual/en/pdo.constants.php).
`maxLength`
A hint for pre-allocation.
`driverOptions`
Optional parameter(s) for the driver.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Binding result set output to PHP variables**
Binding columns in the result set to PHP variables is an effective way to make the data contained in each row immediately available to your application. The following example demonstrates how PDO allows you to bind and retrieve columns with a variety of options and with intelligent defaults.
```
<?php
$stmt = $dbh->prepare('SELECT name, colour, calories FROM fruit');
$stmt->execute();
/* Bind by column number */
$stmt->bindColumn(1, $name);
$stmt->bindColumn(2, $colour);
/* Bind by column name */
$stmt->bindColumn('calories', $cals);
while ($stmt->fetch(PDO::FETCH_BOUND)) {
print $name . "\t" . $colour . "\t" . $cals . "\n";
}
```
The above example will output something similar to:
```
apple red 150
banana yellow 175
kiwi green 75
orange orange 150
mango red 200
strawberry red 25
```
### See Also
* [PDOStatement::execute()](pdostatement.execute) - Executes a prepared statement
* [PDOStatement::fetch()](pdostatement.fetch) - Fetches the next row from a result set
* [PDOStatement::fetchAll()](pdostatement.fetchall) - Fetches the remaining rows from a result set
* [PDOStatement::fetchColumn()](pdostatement.fetchcolumn) - Returns a single column from the next row of a result set
php DirectoryIterator::getBasename DirectoryIterator::getBasename
==============================
(PHP 5 >= 5.2.2, PHP 7, PHP 8)
DirectoryIterator::getBasename — Get base name of current DirectoryIterator item
### Description
```
public DirectoryIterator::getBasename(string $suffix = ""): string
```
Get the base name of the current [DirectoryIterator](class.directoryiterator) item.
### Parameters
`suffix`
If the base name ends in `suffix`, this will be cut.
### Return Values
The base name of the current [DirectoryIterator](class.directoryiterator) item.
### Examples
**Example #1 A **DirectoryIterator::getBasename()** example**
This example will list the full base name and the base name with suffix `.jpg` removed for the files in the directory containing the script.
```
<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
if ($fileinfo->isFile()) {
echo $fileinfo->getBasename() . "\n";
echo $fileinfo->getBasename('.jpg') . "\n";
}
}
?>
```
The above example will output something similar to:
```
apple.jpg
apple
banana.jpg
banana
index.php
index.php
pear.jpg
pear
```
### See Also
* [DirectoryIterator::getFilename()](directoryiterator.getfilename) - Return file name of current DirectoryIterator item
* [DirectoryIterator::getPath()](directoryiterator.getpath) - Get path of current Iterator item without filename
* [DirectoryIterator::getPathname()](directoryiterator.getpathname) - Return path and file name of current DirectoryIterator item
* [basename()](function.basename) - Returns trailing name component of path
* [pathinfo()](function.pathinfo) - Returns information about a file path
php ReflectionClass::isEnum ReflectionClass::isEnum
=======================
(PHP 8 >= 8.1.0)
ReflectionClass::isEnum — Returns whether this is an enum
### Description
```
public ReflectionClass::isEnum(): bool
```
Checks if a class is an [enum](https://www.php.net/manual/en/language.enumerations.php).
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if this is an [enum](https://www.php.net/manual/en/language.enumerations.php), **`false`** otherwise.
php imagecopymergegray imagecopymergegray
==================
(PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8)
imagecopymergegray — Copy and merge part of an image with gray scale
### Description
```
imagecopymergegray(
GdImage $dst_image,
GdImage $src_image,
int $dst_x,
int $dst_y,
int $src_x,
int $src_y,
int $src_width,
int $src_height,
int $pct
): bool
```
**imagecopymergegray()** copy a part of `src_image` onto `dst_image` starting at the x,y coordinates `src_x`, `src_y` with a width of `src_width` and a height of `src_height`. The portion defined will be copied onto the x,y coordinates, `dst_x` and `dst_y`.
This function is identical to [imagecopymerge()](function.imagecopymerge) except that when merging it preserves the hue of the source by converting the destination pixels to gray scale before the copy operation.
### Parameters
`dst_image`
Destination image resource.
`src_image`
Source image resource.
`dst_x`
x-coordinate of destination point.
`dst_y`
y-coordinate of destination point.
`src_x`
x-coordinate of source point.
`src_y`
y-coordinate of source point.
`src_width`
Source width.
`src_height`
Source height.
`pct`
The `src_image` will be changed to grayscale according to `pct` where 0 is fully grayscale and 100 is unchanged. When `pct` = 100 this function behaves identically to [imagecopy()](function.imagecopy) for pallete images, except for ignoring alpha components, while it implements alpha transparency for true colour images.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `dst_image` and `src_image` expect [GdImage](class.gdimage) instances now; previously, resources were expected. |
### Examples
**Example #1 **imagecopymergegray()** usage**
```
<?php
// Create image instances
$dest = imagecreatefromgif('php.gif');
$src = imagecreatefromgif('php.gif');
// Copy and merge - Gray = 20%
imagecopymergegray($dest, $src, 10, 10, 0, 0, 100, 47, 20);
// Output and free from memory
header('Content-Type: image/gif');
imagegif($dest);
imagedestroy($dest);
imagedestroy($src);
?>
```
php Memcached::appendByKey Memcached::appendByKey
======================
(PECL memcached >= 0.1.0)
Memcached::appendByKey — Append data to an existing item on a specific server
### Description
```
public Memcached::appendByKey(string $server_key, string $key, string $value): bool
```
**Memcached::appendByKey()** is functionally equivalent to [Memcached::append()](memcached.append), except that the free-form `server_key` can be used to map the `key` to a specific server.
### Parameters
`server_key`
The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations.
`key`
The key under which to store the value.
`value`
The string to append.
### Return Values
Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTSTORED`** if the key does not exist.
### See Also
* [Memcached::append()](memcached.append) - Append data to an existing item
* [Memcached::prepend()](memcached.prepend) - Prepend data to an existing item
| programming_docs |
php Gmagick::getimageredprimary Gmagick::getimageredprimary
===========================
(PECL gmagick >= Unknown)
Gmagick::getimageredprimary — Returns the chromaticity red primary point
### Description
```
public Gmagick::getimageredprimary(): array
```
Returns the chromaticity red primary point as an array with the keys "x" and "y".
### Parameters
This function has no parameters.
### Return Values
Returns the chromaticity red primary point as an array with the keys "x" and "y".
### Errors/Exceptions
Throws an **GmagickException** on error.
php imagepalettecopy imagepalettecopy
================
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
imagepalettecopy — Copy the palette from one image to another
### Description
```
imagepalettecopy(GdImage $dst, GdImage $src): void
```
**imagepalettecopy()** copies the palette from the `src` image to the `dst` image.
### Parameters
`dst`
The destination image object.
`src`
The source image object.
### Return Values
No value is returned.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `dst` and `src` expect [GdImage](class.gdimage) instances now; previously, resources were expected. |
### Examples
**Example #1 **imagepalettecopy()** example**
```
<?php
// Create two palette images
$palette1 = imagecreate(100, 100);
$palette2 = imagecreate(100, 100);
// Allocate the background to be
// green in the first palette image
$green = imagecolorallocate($palette1, 0, 255, 0);
// Copy the palette from image 1 to image 2
imagepalettecopy($palette2, $palette1);
// Since the palette is now copied we can use the
// green color allocated to image 1 without using
// imagecolorallocate() twice
imagefilledrectangle($palette2, 0, 0, 99, 99, $green);
// Output image to the browser
header('Content-type: image/png');
imagepng($palette2);
imagedestroy($palette1);
imagedestroy($palette2);
?>
```
php PharData::copy PharData::copy
==============
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)
PharData::copy — Copy a file internal to the phar archive to another new file within the phar
### Description
```
public PharData::copy(string $from, string $to): bool
```
Copy a file internal to the tar/zip archive to another new file within the same archive. This is an object-oriented alternative to using [copy()](function.copy) with the phar stream wrapper.
### Parameters
`from`
`to`
### Return Values
returns **`true`** on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown.
### Errors/Exceptions
throws [UnexpectedValueException](class.unexpectedvalueexception) if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a [PharException](class.pharexception) if writing the changes to the phar fails.
### Examples
**Example #1 A **PharData::copy()** example**
This example shows using **PharData::copy()** and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All PharData methods throw exceptions, whereas the stream wrapper uses [trigger\_error()](function.trigger-error).
```
<?php
try {
$phar = new PharData('myphar.tar');
$phar['a'] = 'hi';
$phar->copy('a', 'b');
echo $phar['b']; // outputs "phar://myphar.tar/b"
} catch (Exception $e) {
// handle error
}
// the stream wrapper equivalent of the above code.
// E_WARNINGS are triggered on error rather than exceptions.
copy('phar://myphar.tar/a', 'phar//myphar.tar/c');
echo file_get_contents('phar://myphar.tar/c'); // outputs "hi"
?>
```
php Ds\Set::union Ds\Set::union
=============
(PECL ds >= 1.0.0)
Ds\Set::union — Creates a new set using values from the current instance and another set
### Description
```
public Ds\Set::union(Ds\Set $set): Ds\Set
```
Creates a new set that contains the values of the current instance as well as the values of another `set`.
`A ∪ B = {x: x ∈ A ∨ x ∈ B}`
### Parameters
`set`
The other set, to combine with the current instance.
### Return Values
A new set containing all the values of the current instance as well as another `set`.
### See Also
* [» Union](https://en.wikipedia.org/wiki/Union_(set_theory)) on Wikipedia
### Examples
**Example #1 **Ds\Set::union()** example**
```
<?php
$a = new \Ds\Set([1, 2, 3]);
$b = new \Ds\Set([3, 4, 5]);
var_dump($a->union($b));
?>
```
The above example will output something similar to:
```
object(Ds\Set)#3 (5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
int(4)
[4]=>
int(5)
}
```
php ReflectionFiber::getExecutingLine ReflectionFiber::getExecutingLine
=================================
(PHP 8 >= 8.1.0)
ReflectionFiber::getExecutingLine — Get the line number of the current execution point
### Description
```
public ReflectionFiber::getExecutingLine(): int
```
Returns the line number of the current execution point in the reflected [Fiber](class.fiber). If the fiber has not been started or has terminated, an [Error](class.error) is thrown.
### Parameters
This function has no parameters.
### Return Values
The line number of the current execution point in the fiber.
php OAuth::__destruct OAuth::\_\_destruct
===================
(PECL OAuth >= 0.99.9)
OAuth::\_\_destruct — The destructor
### Description
```
public OAuth::__destruct(): void
```
The destructor.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
### See Also
* [OAuth::\_\_construct()](oauth.construct) - Create a new OAuth object
php Ds\Collection::isEmpty Ds\Collection::isEmpty
======================
(PECL ds >= 1.0.0)
Ds\Collection::isEmpty — Returns whether the collection is empty
### Description
```
abstract public Ds\Collection::isEmpty(): bool
```
Returns whether the collection is empty.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if the collection is empty, **`false`** otherwise.
### Examples
**Example #1 **Ds\Collection::isEmpty()** example**
```
<?php
$a = new \Ds\Vector([1, 2, 3]);
$b = new \Ds\Vector();
var_dump($a->isEmpty());
var_dump($b->isEmpty());
?>
```
The above example will output something similar to:
```
bool(false)
bool(true)
```
php socket_set_timeout socket\_set\_timeout
====================
(PHP 4, PHP 5, PHP 7, PHP 8)
socket\_set\_timeout — Alias of [stream\_set\_timeout()](function.stream-set-timeout)
### Description
This function is an alias of: [stream\_set\_timeout()](function.stream-set-timeout).
php ReflectionEnumBackedCase::getBackingValue ReflectionEnumBackedCase::getBackingValue
=========================================
(PHP 8 >= 8.1.0)
ReflectionEnumBackedCase::getBackingValue — Gets the scalar value backing this Enum case
### Description
```
public ReflectionEnumBackedCase::getBackingValue(): int|string
```
Gets the scalar value backing this Enum case.
### Parameters
This function has no parameters.
### Return Values
The scalar equivalent of this enum case.
### Examples
**Example #1 **ReflectionEnum::getBackingValue()** example**
```
<?php
enum Suit: string
{
case Hearts = 'H';
case Diamonds = 'D';
case Clubs = 'C';
case Spades = 'S';
}
$rEnum = new ReflectionEnum(Suit::class);
$rCase = $rEnum->getCase('Spades');
var_dump($rCase->getBackingValue());
?>
```
The above example will output:
```
string(1) "S"
```
### See Also
* [Enumerations](https://www.php.net/manual/en/language.enumerations.php)
php None Enum values in constant expressions
-----------------------------------
Because cases are represented as constants on the enum itself, they may be used as static values in most constant expressions: property defaults, static variable defaults, parameter defaults, global and class constant values. They may not be used in other enum case values, but normal constants may refer to an enum case.
However, implicit magic method calls such as [ArrayAccess](class.arrayaccess) on enums are not allowed in static or constant definitions as we cannot absolutely guarantee that the resulting value is deterministic or that the method invocation is free of side effects. Function calls, method calls, and property access continue to be invalid operations in constant expressions.
```
<?php
// This is an entirely legal Enum definition.
enum Direction implements ArrayAccess
{
case Up;
case Down;
public function offsetGet($val) { ... }
public function offsetExists($val) { ... }
public function offsetSet($val) { throw new Exception(); }
public function offsetUnset($val) { throw new Exception(); }
}
class Foo
{
// This is allowed.
const Bar = Direction::Down;
// This is disallowed, as it may not be deterministic.
const Bar = Direction::Up['short'];
// Fatal error: Cannot use [] on enums in constant expression
}
// This is entirely legal, because it's not a constant expression.
$x = Direction::Up['short'];
?>
```
php mailparse_msg_parse_file mailparse\_msg\_parse\_file
===========================
(PECL mailparse >= 0.9.0)
mailparse\_msg\_parse\_file — Parses a file
### Description
```
mailparse_msg_parse_file(string $filename): resource
```
Parses a file. This is the optimal way of parsing a mail file that you have on disk.
### Parameters
`filename`
Path to the file holding the message. The file is opened and streamed through the parser.
>
> **Note**:
>
>
> The message contained in `filename` is supposed to end with a newline (`CRLF`); otherwise the last line of the message will not be parsed.
>
>
### Return Values
Returns a `MIME` resource representing the structure, or **`false`** on error.
### Notes
>
> **Note**:
>
>
> It is recommended to call [mailparse\_msg\_free()](function.mailparse-msg-free) on the result of this function, when it is no longer needed, to avoid memory leaks.
>
>
### See Also
* [mailparse\_msg\_free()](function.mailparse-msg-free) - Frees a MIME resource
* [mailparse\_msg\_create()](function.mailparse-msg-create) - Create a mime mail resource
php ReflectionFunctionAbstract::getEndLine ReflectionFunctionAbstract::getEndLine
======================================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
ReflectionFunctionAbstract::getEndLine — Gets end line number
### Description
```
public ReflectionFunctionAbstract::getEndLine(): int|false
```
Get the ending line number.
### Parameters
This function has no parameters.
### Return Values
The ending line number of the user defined function, or **`false`** if unknown.
### See Also
* [ReflectionFunctionAbstract::getStartLine()](reflectionfunctionabstract.getstartline) - Gets starting line number
php The SolrUtils class
The SolrUtils class
===================
Introduction
------------
(PECL solr >= 0.9.2)
Contains utility methods for retrieving the current extension version and preparing query phrases.
Also contains method for escaping query strings and parsing XML responses.
Class synopsis
--------------
abstract class **SolrUtils** { /\* Methods \*/
```
public static digestXmlResponse(string $xmlresponse, int $parse_mode = 0): SolrObject
```
```
public static escapeQueryChars(string $str): string|false
```
```
public static getSolrVersion(): string
```
```
public static queryPhrase(string $str): string
```
} Table of Contents
-----------------
* [SolrUtils::digestXmlResponse](solrutils.digestxmlresponse) — Parses an response XML string into a SolrObject
* [SolrUtils::escapeQueryChars](solrutils.escapequerychars) — Escapes a lucene query string
* [SolrUtils::getSolrVersion](solrutils.getsolrversion) — Returns the current version of the Solr extension
* [SolrUtils::queryPhrase](solrutils.queryphrase) — Prepares a phrase from an unescaped lucene string
php ZipArchive::isEncryptionMethodSupported ZipArchive::isEncryptionMethodSupported
=======================================
(PHP >= 8.0.0, PECL zip >= 1.19.0)
ZipArchive::isEncryptionMethodSupported — Check if a encryption method is supported by libzip
### Description
```
public static ZipArchive::isEncryptionMethodSupported(int $method, bool $enc = true): bool
```
Check if a compression method is supported by libzip.
### Parameters
`method`
The encryption method, one of the **`ZipArchive::EM_*`** constants.
`enc`
If **`true`** check for encryption, else check for decryption.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Notes
>
> **Note**:
>
>
> This function is only available if built against libzip ≥ 1.7.0.
>
>
### See Also
* [ZipArchive::setEncryptionIndex()](ziparchive.setencryptionindex) - Set the encryption method of an entry defined by its index
* [ZipArchive::setEncryptionName()](ziparchive.setencryptionname) - Set the encryption method of an entry defined by its name
php IntlBreakIterator::createCodePointInstance IntlBreakIterator::createCodePointInstance
==========================================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
IntlBreakIterator::createCodePointInstance — Create break iterator for boundaries of code points
### Description
```
public static IntlBreakIterator::createCodePointInstance(): IntlCodePointBreakIterator
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php DOMDocument::createAttribute DOMDocument::createAttribute
============================
(PHP 5, PHP 7, PHP 8)
DOMDocument::createAttribute — Create new attribute
### Description
```
public DOMDocument::createAttribute(string $localName): DOMAttr|false
```
This function creates a new instance of class [DOMAttr](class.domattr). This node will not show up in the document unless it is inserted with (e.g.) [DOMNode::appendChild()](domnode.appendchild).
### Parameters
`localName`
The name of the attribute.
### Return Values
The new [DOMAttr](class.domattr) or **`false`** if an error occurred.
### Errors/Exceptions
**`DOM_INVALID_CHARACTER_ERR`**
Raised if `localName` contains an invalid character.
### See Also
* [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children
* [DOMDocument::createAttributeNS()](domdocument.createattributens) - Create new attribute node with an associated namespace
* [DOMDocument::createCDATASection()](domdocument.createcdatasection) - Create new cdata node
* [DOMDocument::createComment()](domdocument.createcomment) - Create new comment node
* [DOMDocument::createDocumentFragment()](domdocument.createdocumentfragment) - Create new document fragment
* [DOMDocument::createElement()](domdocument.createelement) - Create new element node
* [DOMDocument::createElementNS()](domdocument.createelementns) - Create new element node with an associated namespace
* [DOMDocument::createEntityReference()](domdocument.createentityreference) - Create new entity reference node
* [DOMDocument::createProcessingInstruction()](domdocument.createprocessinginstruction) - Creates new PI node
* [DOMDocument::createTextNode()](domdocument.createtextnode) - Create new text node
php stats_rand_ranf stats\_rand\_ranf
=================
(PECL stats >= 1.0.0)
stats\_rand\_ranf — Generates a random floating point number between 0 and 1
### Description
```
stats_rand_ranf(): float
```
Returns a random floating point number from a uniform distribution between 0 (exclusive) and 1 (exclusive).
### Parameters
This function has no parameters.
### Return Values
A random floating point number
php Memcached::touch Memcached::touch
================
(PECL memcached >= 2.0.0)
Memcached::touch — Set a new expiration on an item
### Description
```
public Memcached::touch(string $key, int $expiration): bool
```
**Memcached::touch()** sets a new expiration value on the given key.
### Parameters
`key`
The key under which to store the value.
`expiration`
The expiration time, defaults to 0. See [Expiration Times](https://www.php.net/manual/en/memcached.expiration.php) for more info.
### Return Values
Returns **`true`** on success or **`false`** on failure. Use [Memcached::getResultCode()](memcached.getresultcode) if necessary.
### See Also
* [Memcached::touchByKey()](memcached.touchbykey) - Set a new expiration on an item on a specific server
php phpdbg_break_function phpdbg\_break\_function
=======================
(PHP 5 >= 5.6.3, PHP 7, PHP 8)
phpdbg\_break\_function — Inserts a breakpoint at entry to a function
### Description
```
phpdbg_break_function(string $function): void
```
Insert a breakpoint at the entry to the given `function`.
### Parameters
`function`
The name of the function.
### Return Values
No value is returned.
### See Also
* [phpdbg\_break\_file()](function.phpdbg-break-file) - Inserts a breakpoint at a line in a file
* [phpdbg\_break\_method()](function.phpdbg-break-method) - Inserts a breakpoint at entry to a method
* [phpdbg\_break\_next()](function.phpdbg-break-next) - Inserts a breakpoint at the next opcode
* [phpdbg\_clear()](function.phpdbg-clear) - Clears all breakpoints
php RegexIterator::setMode RegexIterator::setMode
======================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
RegexIterator::setMode — Sets the operation mode
### Description
```
public RegexIterator::setMode(int $mode): void
```
Sets the operation mode.
### Parameters
`mode`
The operation mode.
The available modes are listed below. The actual meanings of these modes are described in the [predefined constants](class.regexiterator#regexiterator.constants).
**[RegexIterator](class.regexiterator) modes**| value | constant |
| --- | --- |
| 0 | [RegexIterator::MATCH](class.regexiterator#regexiterator.constants.match) |
| 1 | [RegexIterator::GET\_MATCH](class.regexiterator#regexiterator.constants.get-match) |
| 2 | [RegexIterator::ALL\_MATCHES](class.regexiterator#regexiterator.constants.all-matches) |
| 3 | [RegexIterator::SPLIT](class.regexiterator#regexiterator.constants.split) |
| 4 | [RegexIterator::REPLACE](class.regexiterator#regexiterator.constants.replace) |
### Return Values
No value is returned.
### Examples
**Example #1 **RegexIterator::setMode()** example**
```
<?php
$test = array ('str1' => 'test 1', 'test str2' => 'another test', 'str3' => 'test 123');
$arrayIterator = new ArrayIterator($test);
// Filter everything that starts with 'test ' followed by one or more numbers.
$regexIterator = new RegexIterator($arrayIterator, '/^test (\d+)/');
// Operation mode: Replace actual value with the matches
$regexIterator->setMode(RegexIterator::GET_MATCH);
foreach ($regexIterator as $key => $value) {
// print out the matched number(s)
echo $key . ' => ' . $value[1] . PHP_EOL;
}
?>
```
The above example will output something similar to:
```
str1 => 1
str3 => 123
```
### See Also
* [RegexIterator::getMode()](regexiterator.getmode) - Returns operation mode
php openal_context_process openal\_context\_process
========================
(PECL openal >= 0.1.0)
openal\_context\_process — Process the specified context
### Description
```
openal_context_process(resource $context): bool
```
### Parameters
`context`
An [Open AL(Context)](https://www.php.net/manual/en/openal.resources.php) resource (previously created by [openal\_context\_create()](function.openal-context-create)).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [openal\_context\_create()](function.openal-context-create) - Create an audio processing context
* [openal\_context\_current()](function.openal-context-current) - Make the specified context current
* [openal\_context\_suspend()](function.openal-context-suspend) - Suspend the specified context
| programming_docs |
php ibase_add_user ibase\_add\_user
================
(PHP 5, PHP 7 < 7.4.0)
ibase\_add\_user — Add a user to a security database
### Description
```
ibase_add_user(
resource $service_handle,
string $user_name,
string $password,
string $first_name = ?,
string $middle_name = ?,
string $last_name = ?
): bool
```
### Parameters
`service_handle`
The handle on the database server service.
`user_name`
The login name of the new database user.
`password`
The password of the new user.
`first_name`
The first name of the new database user.
`middle_name`
The middle name of the new database user.
`last_name`
The last name of the new database user.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [ibase\_modify\_user()](function.ibase-modify-user) - Modify a user to a security database
* [ibase\_delete\_user()](function.ibase-delete-user) - Delete a user from a security database
php GearmanClient::setContext GearmanClient::setContext
=========================
(PECL gearman >= 0.6.0)
GearmanClient::setContext — Set application context
### Description
```
public GearmanClient::setContext(string $context): bool
```
Sets an arbitrary string to provide application context that can later be retrieved by [GearmanClient::context()](gearmanclient.context).
### Parameters
`context`
Arbitrary context data
### Return Values
Always returns **`true`**.
### See Also
* [GearmanClient::context()](gearmanclient.context) - Get the application context
php odbc_tables odbc\_tables
============
(PHP 4, PHP 5, PHP 7, PHP 8)
odbc\_tables — Get the list of table names stored in a specific data source
### Description
```
odbc_tables(
resource $odbc,
?string $catalog = null,
?string $schema = null,
?string $table = null,
?string $types = null
): resource|false
```
Lists all tables in the requested range.
To support enumeration of qualifiers, owners, and table types, the following special semantics for the `catalog`, `schema`, `table`, and `table_type` are available:
* If `catalog` is a single percent character (%) and `schema` and `table` are empty strings, then the result set contains a list of valid qualifiers for the data source. (All columns except the TABLE\_QUALIFIER column contain NULLs.)
* If `schema` is a single percent character (%) and `catalog` and `table` are empty strings, then the result set contains a list of valid owners for the data source. (All columns except the TABLE\_OWNER column contain NULLs.)
* If `table_type` is a single percent character (%) and `catalog`, `schema` and `table` are empty strings, then the result set contains a list of valid table types for the data source. (All columns except the TABLE\_TYPE column contain NULLs.)
### Parameters
`odbc`
The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details.
`catalog`
The catalog ('qualifier' in ODBC 2 parlance).
`schema`
The schema ('owner' in ODBC 2 parlance). This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.
`table`
The name. This parameter accepts the following search patterns: `%` to match zero or more characters, and `_` to match a single character.
`types`
If `table_type` is not an empty string, it must contain a list of comma-separated values for the types of interest; each value may be enclosed in single quotes (`'`) or unquoted. For example, `'TABLE','VIEW'` or `TABLE, VIEW`. If the data source does not support a specified table type, **odbc\_tables()** does not return any results for that type.
### Return Values
Returns an ODBC result identifier containing the information or **`false`** on failure.
The result set has the following columns:
* `TABLE_CAT`
* `TABLE_SCHEM`
* `TABLE_NAME`
* `TABLE_TYPE`
* `REMARKS`
Drivers can report additional columns. The result set is ordered by `TABLE_TYPE`, `TABLE_CAT`, `TABLE_SCHEM` and `TABLE_NAME`.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `schema`, `table` and `types` are now nullable. |
### Examples
**Example #1 List Tables in a Catalog**
```
<?php
$conn = odbc_connect($dsn, $user, $pass);
$tables = odbc_tables($conn, 'SalesOrders', 'dbo', '%', 'TABLE');
while (($row = odbc_fetch_array($tables))) {
print_r($row);
break; // further rows omitted for brevity
}
?>
```
The above example will output something similar to:
```
Array
(
[TABLE_CAT] => SalesOrders
[TABLE_SCHEM] => dbo
[TABLE_NAME] => Orders
[TABLE_TYPE] => TABLE
[REMARKS] =>
)
```
### See Also
* [odbc\_tableprivileges()](function.odbc-tableprivileges) - Lists tables and the privileges associated with each table
* [odbc\_columns()](function.odbc-columns) - Lists the column names in specified tables
* [odbc\_specialcolumns()](function.odbc-specialcolumns) - Retrieves special columns
* [odbc\_statistics()](function.odbc-statistics) - Retrieve statistics about a table
* [odbc\_procedures()](function.odbc-procedures) - Get the list of procedures stored in a specific data source
php DirectoryIterator::isDot DirectoryIterator::isDot
========================
(PHP 5, PHP 7, PHP 8)
DirectoryIterator::isDot — Determine if current DirectoryIterator item is '.' or '..'
### Description
```
public DirectoryIterator::isDot(): bool
```
Determines if the current [DirectoryIterator](class.directoryiterator) item is a directory and either `.` or `..`
### Parameters
This function has no parameters.
### Return Values
**`true`** if the entry is `.` or `..`, otherwise **`false`**
### Examples
**Example #1 A **DirectoryIterator::isDot()** example**
This example will list all files, omitting the `.` and `..` entries.
```
<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
if (!$fileinfo->isDot()) {
echo $fileinfo->getFilename() . "\n";
}
}
?>
```
The above example will output something similar to:
```
apple.jpg
banana.jpg
example.php
pears.jpg
```
### See Also
* [DirectoryIterator::getType()](directoryiterator.gettype) - Determine the type of the current DirectoryIterator item
* [DirectoryIterator::isDir()](directoryiterator.isdir) - Determine if current DirectoryIterator item is a directory
* [DirectoryIterator::isFile()](directoryiterator.isfile) - Determine if current DirectoryIterator item is a regular file
* [DirectoryIterator::isLink()](directoryiterator.islink) - Determine if current DirectoryIterator item is a symbolic link
php SplDoublyLinkedList::shift SplDoublyLinkedList::shift
==========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SplDoublyLinkedList::shift — Shifts a node from the beginning of the doubly linked list
### Description
```
public SplDoublyLinkedList::shift(): mixed
```
### Parameters
This function has no parameters.
### Return Values
The value of the shifted node.
### Errors/Exceptions
Throws [RuntimeException](class.runtimeexception) when the data-structure is empty.
php SolrQuery::setGroup SolrQuery::setGroup
===================
(PECL solr >= 2.2.0)
SolrQuery::setGroup — Enable/Disable result grouping (group parameter)
### Description
```
public SolrQuery::setGroup(bool $value): SolrQuery
```
Enable/Disable result grouping (group parameter)
### Parameters
`value`
### Return Values
### See Also
* [SolrQuery::getGroup()](solrquery.getgroup) - Returns true if grouping is enabled
* [SolrQuery::addGroupField()](solrquery.addgroupfield) - Add a field to be used to group results
* [SolrQuery::addGroupFunction()](solrquery.addgroupfunction) - Allows grouping results based on the unique values of a function query (group.func parameter)
* [SolrQuery::addGroupQuery()](solrquery.addgroupquery) - Allows grouping of documents that match the given query
* [SolrQuery::addGroupSortField()](solrquery.addgroupsortfield) - Add a group sort field (group.sort parameter)
* [SolrQuery::setGroupFacet()](solrquery.setgroupfacet) - Sets group.facet parameter
* [SolrQuery::setGroupOffset()](solrquery.setgroupoffset) - Sets the group.offset parameter
* [SolrQuery::setGroupLimit()](solrquery.setgrouplimit) - Specifies the number of results to return for each group. The server default value is 1
* [SolrQuery::setGroupMain()](solrquery.setgroupmain) - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple
* [SolrQuery::setGroupNGroups()](solrquery.setgroupngroups) - If true, Solr includes the number of groups that have matched the query in the results
* [SolrQuery::setGroupTruncate()](solrquery.setgrouptruncate) - If true, facet counts are based on the most relevant document of each group matching the query
* [SolrQuery::setGroupFormat()](solrquery.setgroupformat) - Sets the group format, result structure (group.format parameter)
* [SolrQuery::setGroupCachePercent()](solrquery.setgroupcachepercent) - Enables caching for result grouping
php popen popen
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
popen — Opens process file pointer
### Description
```
popen(string $command, string $mode): resource|false
```
Opens a pipe to a process executed by forking the command given by `command`.
### Parameters
`command`
The command
`mode`
The mode. Either `'r'` for reading, or `'w'` for writing.
On Windows, **popen()** defaults to text mode, i.e. any `\n` characters written to or read from the pipe will be translated to `\r\n`. If this is not desired, binary mode can be enforced by setting `mode` to `'rb'` and `'wb'`, respectively.
### Return Values
Returns a file pointer identical to that returned by [fopen()](function.fopen), except that it is unidirectional (may only be used for reading or writing) and must be closed with [pclose()](function.pclose). This pointer may be used with [fgets()](function.fgets), [fgetss()](function.fgetss), and [fwrite()](function.fwrite). When the mode is 'r', the returned file pointer equals to the STDOUT of the command, when the mode is 'w', the returned file pointer equals to the STDIN of the command.
If an error occurs, returns **`false`**.
### Examples
**Example #1 **popen()** example**
```
<?php
$handle = popen("/bin/ls", "r");
?>
```
If the command to be executed could not be found, a valid resource is returned. This may seem odd, but makes sense; it allows you to access any error message returned by the shell:
**Example #2 **popen()** example**
```
<?php
error_reporting(E_ALL);
/* Add redirection so we can get stderr. */
$handle = popen('/path/to/executable 2>&1', 'r');
echo "'$handle'; " . gettype($handle) . "\n";
$read = fread($handle, 2096);
echo $read;
pclose($handle);
?>
```
### Notes
>
> **Note**:
>
>
> If you're looking for bi-directional support (two-way), use [proc\_open()](function.proc-open).
>
>
### See Also
* [pclose()](function.pclose) - Closes process file pointer
* [fopen()](function.fopen) - Opens file or URL
* [proc\_open()](function.proc-open) - Execute a command and open file pointers for input/output
php RecursiveIteratorIterator::beginIteration RecursiveIteratorIterator::beginIteration
=========================================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
RecursiveIteratorIterator::beginIteration — Begin Iteration
### Description
```
public RecursiveIteratorIterator::beginIteration(): void
```
Called when iteration begins (after the first [RecursiveIteratorIterator::rewind()](recursiveiteratoriterator.rewind) call.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php SimpleXMLElement::getName SimpleXMLElement::getName
=========================
(PHP 5 >= 5.1.3, PHP 7, PHP 8)
SimpleXMLElement::getName — Gets the name of the XML element
### Description
```
public SimpleXMLElement::getName(): string
```
Gets the name of the XML element.
### Parameters
This function has no parameters.
### Return Values
The `getName` method returns as a string the name of the XML tag referenced by the SimpleXMLElement object.
### Examples
>
> **Note**:
>
>
> Listed examples may include `example.php`, which refers to the XML string found in the first example of the [basic usage](https://www.php.net/manual/en/simplexml.examples-basic.php) guide.
>
>
**Example #1 Get XML element names**
```
<?php
include 'example.php';
$sxe = new SimpleXMLElement($xmlstr);
echo $sxe->getName() . "\n";
foreach ($sxe->children() as $child)
{
echo $child->getName() . "\n";
}
?>
```
The above example will output:
```
movies
movie
```
php hash_hkdf hash\_hkdf
==========
(PHP 7 >= 7.1.2, PHP 8)
hash\_hkdf — Generate a HKDF key derivation of a supplied key input
### Description
```
hash_hkdf(
string $algo,
string $key,
int $length = 0,
string $info = "",
string $salt = ""
): string
```
### Parameters
`algo`
Name of selected hashing algorithm (i.e. "sha256", "sha512", "haval160,4", etc..) See [hash\_algos()](function.hash-algos) for a list of supported algorithms.
>
> **Note**:
>
>
> Non-cryptographic hash functions are not allowed.
>
>
`key`
Input keying material (raw binary). Cannot be empty.
`length`
Desired output length in bytes. Cannot be greater than 255 times the chosen hash function size.
If `length` is `0`, the output length will default to the chosen hash function size.
`info`
Application/context-specific info string.
`salt`
Salt to use during derivation.
While optional, adding random salt significantly improves the strength of HKDF.
### Return Values
Returns a string containing a raw binary representation of the derived key (also known as output keying material - OKM).
### Errors/Exceptions
Throws a [ValueError](class.valueerror) exception if `key` is empty, `algo` is unknown/non-cryptographic, `length` is less than `0` or too large (greater than 255 times the size of the hash function).
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | Now throws a [ValueError](class.valueerror) exception on error. Previously, **`false`** was returned and an **`E_WARNING`** message was emitted. |
### Examples
**Example #1 **hash\_hkdf()** example**
```
<?php
// Generate a random key, and salt to strengthen it during derivation.
$inputKey = random_bytes(32);
$salt = random_bytes(16);
// Derive a pair of separate keys, using the same input created above.
$encryptionKey = hash_hkdf('sha256', $inputKey, 32, 'aes-256-encryption', $salt);
$authenticationKey = hash_hkdf('sha256', $inputKey, 32, 'sha-256-authentication', $salt);
var_dump($encryptionKey !== $authenticationKey); // bool(true)
?>
```
The above example produces a pair of separate keys, suitable for creation of an encrypt-then-HMAC construct, using AES-256 and SHA-256 for encryption and authentication respectively.
### See Also
* [hash\_pbkdf2()](function.hash-pbkdf2) - Generate a PBKDF2 key derivation of a supplied password
* [» RFC 5869](http://www.faqs.org/rfcs/rfc5869)
* [» userland implementation](https://github.com/narfbg/hash_hkdf_compat)
php Parle\Parser::sigil Parle\Parser::sigil
===================
(PECL parle >= 0.5.1)
Parle\Parser::sigil — Retrieve a matching part of a rule
### Description
```
public Parle\Parser::sigil(int $idx): string
```
Retrieve a part of the match by a rule. This method is equivalent to the pseudo variable functionality in Bison.
### Parameters
`idx`
Match index, zero based.
### Return Values
Returns a string with the matched part.
php None Anchors
-------
Outside a character class, in the default matching mode, the circumflex character (`^`) is an assertion which is true only if the current matching point is at the start of the subject string. Inside a character class, circumflex (`^`) has an entirely different meaning (see below).
Circumflex (`^`) need not be the first character of the pattern if a number of alternatives are involved, but it should be the first thing in each alternative in which it appears if the pattern is ever to match that branch. If all possible alternatives start with a circumflex (`^`), that is, if the pattern is constrained to match only at the start of the subject, it is said to be an "anchored" pattern. (There are also other constructs that can cause a pattern to be anchored.)
A dollar character (`$`) is an assertion which is **`true`** only if the current matching point is at the end of the subject string, or immediately before a newline character that is the last character in the string (by default). Dollar (`$`) need not be the last character of the pattern if a number of alternatives are involved, but it should be the last item in any branch in which it appears. Dollar has no special meaning in a character class.
The meaning of dollar can be changed so that it matches only at the very end of the string, by setting the [PCRE\_DOLLAR\_ENDONLY](reference.pcre.pattern.modifiers) option at compile or matching time. This does not affect the \Z assertion.
The meanings of the circumflex and dollar characters are changed if the [PCRE\_MULTILINE](reference.pcre.pattern.modifiers) option is set. When this is the case, they match immediately after and immediately before an internal "\n" character, respectively, in addition to matching at the start and end of the subject string. For example, the pattern /^abc$/ matches the subject string "def\nabc" in multiline mode, but not otherwise. Consequently, patterns that are anchored in single line mode because all branches start with "^" are not anchored in multiline mode. The [PCRE\_DOLLAR\_ENDONLY](reference.pcre.pattern.modifiers) option is ignored if [PCRE\_MULTILINE](reference.pcre.pattern.modifiers) is set.
Note that the sequences \A, \Z, and \z can be used to match the start and end of the subject in both modes, and if all branches of a pattern start with \A is it always anchored, whether [PCRE\_MULTILINE](reference.pcre.pattern.modifiers) is set or not.
php Ds\Set::toArray Ds\Set::toArray
===============
(PECL ds >= 1.0.0)
Ds\Set::toArray — Converts the set to an array
### Description
```
public Ds\Set::toArray(): array
```
Converts the set to an array.
>
> **Note**:
>
>
> Casting to an array is not supported yet.
>
>
### Parameters
This function has no parameters.
### Return Values
An array containing all the values in the same order as the set.
### Examples
**Example #1 **Ds\Set::toArray()** example**
```
<?php
$set = new \Ds\Set([1, 2, 3]);
var_dump($set->toArray());
?>
```
The above example will output something similar to:
```
array(3) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
}
```
php eio_grp eio\_grp
========
(PECL eio >= 0.0.1dev)
eio\_grp — Creates a request group
### Description
```
eio_grp(callable $callback, string $data = NULL): resource
```
**eio\_grp()** creates a request group.
### Parameters
`callback`
`callback` function is called when the request is done. It should match the following prototype:
```
void callback(mixed $data, int $result[, resource $req]);
```
`data`
is custom data passed to the request.
`result`
request-specific result value; basically, the value returned by corresponding system call.
`req`
is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error)
`data`
Arbitrary variable passed to `callback`.
### Return Values
**eio\_grp()** returns request group resource on success, or **`false`** on failure.
### Examples
**Example #1 **eio\_grp()** example**
```
<?php
$temp_filename = dirname(__FILE__) ."/eio-file.tmp";
$fp = fopen($temp_filename, "w");
fwrite($fp, "some data");
fclose($fp);
$my_file_fd = NULL;
/* Is called when the group requests are done */
function my_grp_done($data, $result) {
// Remove the file, if it still exists
@unlink($data);
}
/* Is called when the temporary file is opened */
function my_grp_file_opened_callback($data, $result) {
global $my_file_fd, $grp;
$my_file_fd = $result;
$req = eio_read($my_file_fd, 4, 0,
EIO_PRI_DEFAULT, "my_grp_file_read_callback");
eio_grp_add($grp, $req);
}
/* Is called when the file is read */
function my_grp_file_read_callback($data, $result) {
global $my_file_fd, $grp;
var_dump($result);
// Create request to close the file
$req = eio_close($my_file_fd);
// Add request to the group
eio_grp_add($grp, $req);
}
// Create request group
$grp = eio_grp("my_grp_done", $temp_filename);
// Create request
$req = eio_open($temp_filename, EIO_O_RDWR | EIO_O_APPEND , NULL,
EIO_PRI_DEFAULT, "my_grp_file_opened_callback", NULL);
// Add request to the group
eio_grp_add($grp, $req);
// Process requests
eio_event_loop();
?>
```
The above example will output something similar to:
```
string(4) "some"
```
### See Also
* [eio\_grp\_cancel()](function.eio-grp-cancel) - Cancels a request group
* [eio\_grp\_add()](function.eio-grp-add) - Adds a request to the request group
| programming_docs |
php imagebmp imagebmp
========
(PHP 7 >= 7.2.0, PHP 8)
imagebmp — Output a BMP image to browser or file
### Description
```
imagebmp(GdImage $image, resource|string|null $file = null, bool $compressed = true): bool
```
Outputs or saves a BMP version of the given `image`.
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`file`
The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or **`null`**, the raw image stream will be output directly.
>
> **Note**:
>
>
> **`null`** is invalid if the `compressed` arguments is not used.
>
>
`compressed`
Whether the BMP should be compressed with run-length encoding (RLE), or not.
### Return Values
Returns **`true`** on success or **`false`** on failure.
**Caution**However, if libgd fails to output the image, this function returns **`true`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
| 8.0.0 | The type of `compressed` is bool now; formerly it was int. |
### Examples
**Example #1 Saving a BMP file**
```
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'BMP with PHP', $text_color);
// Save the image
imagebmp($im, 'php.bmp');
// Free up memory
imagedestroy($im);
?>
```
php stats_dens_gamma stats\_dens\_gamma
==================
(PECL stats >= 1.0.0)
stats\_dens\_gamma — Probability density function of the gamma distribution
### Description
```
stats_dens_gamma(float $x, float $shape, float $scale): float
```
Returns the probability density at `x`, where the random variable follows the gamma distribution of which the shape parameter is `shape` and the scale parameter is `scale`.
### Parameters
`x`
The value at which the probability density is calculated
`shape`
The shape parameter of the distribution
`scale`
The scale parameter of the distribution
### Return Values
The probability density at `x` or **`false`** for failure.
php Imagick::thumbnailImage Imagick::thumbnailImage
=======================
(PECL imagick 2, PECL imagick 3)
Imagick::thumbnailImage — Changes the size of an image
### Description
```
public Imagick::thumbnailImage(
int $columns,
int $rows,
bool $bestfit = false,
bool $fill = false,
bool $legacy = false
): bool
```
Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small, low cost thumbnail images suited for display on the Web. If **`true`** is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until they match or are smaller than the parameter given for the side.
> **Note**: The behavior of the parameter `bestfit` changed in Imagick 3.0.0. Before this version given dimensions 400x400 an image of dimensions 200x150 would be left untouched. In Imagick 3.0.0 and later the image would be scaled up to size 400x300 as this is the "best fit" for the given dimensions. If `bestfit` parameter is used both width and height must be given.
>
>
### Parameters
`columns`
Image width
`rows`
Image height
`bestfit`
Whether to force maximum values
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
### Examples
**Example #1 **Imagick::thumbnailImage()****
```
<?php
function thumbnailImage($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
$imagick->setbackgroundcolor('rgb(64, 64, 64)');
$imagick->thumbnailImage(100, 100, true, true);
header("Content-Type: image/jpg");
echo $imagick->getImageBlob();
}
?>
```
php Ds\Map::__construct Ds\Map::\_\_construct
=====================
(PECL ds >= 1.0.0)
Ds\Map::\_\_construct — Creates a new instance
### Description
public **Ds\Map::\_\_construct**([mixed](language.types.declarations#language.types.declarations.mixed) `...$values`) Creates a new instance, using either a [traversable](class.traversable) object or an array for the initial `values`.
### Parameters
`values`
A traversable object or an array to use for the initial values.
### Examples
**Example #1 **Ds\Map::\_\_construct()** example**
```
<?php
$map = new \Ds\Map();
var_dump($map);
$map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]);
var_dump($map);
?>
```
The above example will output something similar to:
```
object(Ds\Map)#1 (0) {
}
object(Ds\Map)#2 (3) {
[0]=>
object(Ds\Pair)#1 (2) {
["key"]=>
string(1) "a"
["value"]=>
int(1)
}
[1]=>
object(Ds\Pair)#3 (2) {
["key"]=>
string(1) "b"
["value"]=>
int(2)
}
[2]=>
object(Ds\Pair)#4 (2) {
["key"]=>
string(1) "c"
["value"]=>
int(3)
}
}
```
php eio_chown eio\_chown
==========
(PECL eio >= 0.0.1dev)
eio\_chown — Change file/directory permissions
### Description
```
eio_chown(
string $path,
int $uid,
int $gid = -1,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource
```
Changes file, or directory permissions.
### Parameters
`path`
Path to file or directory.
**Warning**Avoid relative paths
`uid`
User ID. Is ignored when equal to -1.
`gid`
Group ID. Is ignored when equal to -1.
`pri`
The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**.
`callback`
`callback` function is called when the request is done. It should match the following prototype:
```
void callback(mixed $data, int $result[, resource $req]);
```
`data`
is custom data passed to the request.
`result`
request-specific result value; basically, the value returned by corresponding system call.
`req`
is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error)
`data`
Arbitrary variable passed to `callback`.
### Return Values
**eio\_chown()** returns request resource on success, or **`false`** on failure.
### See Also
* [eio\_chmod()](function.eio-chmod) - Change file/directory permissions
php The ReflectionFunctionAbstract class
The ReflectionFunctionAbstract class
====================================
Introduction
------------
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
A parent class to [ReflectionFunction](class.reflectionfunction), read its description for details.
Class synopsis
--------------
abstract class **ReflectionFunctionAbstract** implements [Reflector](class.reflector) { /\* Properties \*/ public string [$name](class.reflectionfunctionabstract#reflectionfunctionabstract.props.name); /\* Methods \*/
```
private __clone(): void
```
```
public getAttributes(?string $name = null, int $flags = 0): array
```
```
public getClosureScopeClass(): ?ReflectionClass
```
```
public getClosureThis(): ?object
```
```
public getClosureUsedVariables(): array
```
```
public getDocComment(): string|false
```
```
public getEndLine(): int|false
```
```
public getExtension(): ?ReflectionExtension
```
```
public getExtensionName(): string|false
```
```
public getFileName(): string|false
```
```
public getName(): string
```
```
public getNamespaceName(): string
```
```
public getNumberOfParameters(): int
```
```
public getNumberOfRequiredParameters(): int
```
```
public getParameters(): array
```
```
public getReturnType(): ?ReflectionType
```
```
public getShortName(): string
```
```
public getStartLine(): int|false
```
```
public getStaticVariables(): array
```
```
public getTentativeReturnType(): ?ReflectionType
```
```
public hasReturnType(): bool
```
```
public hasTentativeReturnType(): bool
```
```
public inNamespace(): bool
```
```
public isClosure(): bool
```
```
public isDeprecated(): bool
```
```
public isGenerator(): bool
```
```
public isInternal(): bool
```
```
public isUserDefined(): bool
```
```
public isVariadic(): bool
```
```
public returnsReference(): bool
```
```
abstract public __toString(): void
```
} Properties
----------
name Name of the function. Read-only, throws [ReflectionException](class.reflectionexception) in attempt to write.
Table of Contents
-----------------
* [ReflectionFunctionAbstract::\_\_clone](reflectionfunctionabstract.clone) — Clones function
* [ReflectionFunctionAbstract::getAttributes](reflectionfunctionabstract.getattributes) — Gets Attributes
* [ReflectionFunctionAbstract::getClosureScopeClass](reflectionfunctionabstract.getclosurescopeclass) — Returns the scope associated to the closure
* [ReflectionFunctionAbstract::getClosureThis](reflectionfunctionabstract.getclosurethis) — Returns this pointer bound to closure
* [ReflectionFunctionAbstract::getClosureUsedVariables](reflectionfunctionabstract.getclosureusedvariables) — Returns an array of the used variables in the Closure
* [ReflectionFunctionAbstract::getDocComment](reflectionfunctionabstract.getdoccomment) — Gets doc comment
* [ReflectionFunctionAbstract::getEndLine](reflectionfunctionabstract.getendline) — Gets end line number
* [ReflectionFunctionAbstract::getExtension](reflectionfunctionabstract.getextension) — Gets extension info
* [ReflectionFunctionAbstract::getExtensionName](reflectionfunctionabstract.getextensionname) — Gets extension name
* [ReflectionFunctionAbstract::getFileName](reflectionfunctionabstract.getfilename) — Gets file name
* [ReflectionFunctionAbstract::getName](reflectionfunctionabstract.getname) — Gets function name
* [ReflectionFunctionAbstract::getNamespaceName](reflectionfunctionabstract.getnamespacename) — Gets namespace name
* [ReflectionFunctionAbstract::getNumberOfParameters](reflectionfunctionabstract.getnumberofparameters) — Gets number of parameters
* [ReflectionFunctionAbstract::getNumberOfRequiredParameters](reflectionfunctionabstract.getnumberofrequiredparameters) — Gets number of required parameters
* [ReflectionFunctionAbstract::getParameters](reflectionfunctionabstract.getparameters) — Gets parameters
* [ReflectionFunctionAbstract::getReturnType](reflectionfunctionabstract.getreturntype) — Gets the specified return type of a function
* [ReflectionFunctionAbstract::getShortName](reflectionfunctionabstract.getshortname) — Gets function short name
* [ReflectionFunctionAbstract::getStartLine](reflectionfunctionabstract.getstartline) — Gets starting line number
* [ReflectionFunctionAbstract::getStaticVariables](reflectionfunctionabstract.getstaticvariables) — Gets static variables
* [ReflectionFunctionAbstract::getTentativeReturnType](reflectionfunctionabstract.gettentativereturntype) — Returns the tentative return type associated with the function
* [ReflectionFunctionAbstract::hasReturnType](reflectionfunctionabstract.hasreturntype) — Checks if the function has a specified return type
* [ReflectionFunctionAbstract::hasTentativeReturnType](reflectionfunctionabstract.hastentativereturntype) — Returns whether the function has a tentative return type
* [ReflectionFunctionAbstract::inNamespace](reflectionfunctionabstract.innamespace) — Checks if function in namespace
* [ReflectionFunctionAbstract::isClosure](reflectionfunctionabstract.isclosure) — Checks if closure
* [ReflectionFunctionAbstract::isDeprecated](reflectionfunctionabstract.isdeprecated) — Checks if deprecated
* [ReflectionFunctionAbstract::isGenerator](reflectionfunctionabstract.isgenerator) — Returns whether this function is a generator
* [ReflectionFunctionAbstract::isInternal](reflectionfunctionabstract.isinternal) — Checks if is internal
* [ReflectionFunctionAbstract::isUserDefined](reflectionfunctionabstract.isuserdefined) — Checks if user defined
* [ReflectionFunctionAbstract::isVariadic](reflectionfunctionabstract.isvariadic) — Checks if the function is variadic
* [ReflectionFunctionAbstract::returnsReference](reflectionfunctionabstract.returnsreference) — Checks if returns reference
* [ReflectionFunctionAbstract::\_\_toString](reflectionfunctionabstract.tostring) — To string
php odbc_num_rows odbc\_num\_rows
===============
(PHP 4, PHP 5, PHP 7, PHP 8)
odbc\_num\_rows — Number of rows in a result
### Description
```
odbc_num_rows(resource $statement): int
```
Gets the number of rows in a result. For INSERT, UPDATE and DELETE statements **odbc\_num\_rows()** returns the number of rows affected. For a SELECT clause this `can` be the number of rows available.
### Parameters
`statement`
The result identifier returned by [odbc\_exec()](function.odbc-exec).
### Return Values
Returns the number of rows in an ODBC result. This function will return -1 on error.
### Notes
>
> **Note**:
>
>
> Using **odbc\_num\_rows()** to determine the number of rows available after a SELECT will return -1 with many drivers.
>
>
php SplFileInfo::getATime SplFileInfo::getATime
=====================
(PHP 5 >= 5.1.2, PHP 7, PHP 8)
SplFileInfo::getATime — Gets last access time of the file
### Description
```
public SplFileInfo::getATime(): int|false
```
Gets the last access time for the file.
### Parameters
This function has no parameters.
### Return Values
Returns the time the file was last accessed on success, or **`false`** on failure.
### Errors/Exceptions
Throws [RunTimeException](class.runtimeexception) on error.
### See Also
* [fileatime()](function.fileatime) - Gets last access time of file
php ReflectionClass::getConstants ReflectionClass::getConstants
=============================
(PHP 5, PHP 7, PHP 8)
ReflectionClass::getConstants — Gets constants
### Description
```
public ReflectionClass::getConstants(?int $filter = null): array
```
Gets all defined constants from a class, regardless of their visibility.
### Parameters
`filter`
The optional filter, for filtering desired constant visibilities. It's configured using the [ReflectionClassConstant constants](class.reflectionclassconstant#reflectionclassconstant.constants.modifiers), and defaults to all constant visibilities.
### Return Values
An array of constants, where the keys hold the name and the values the value of the constants.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `filter` has been added. |
### See Also
* [ReflectionClass::getConstant()](reflectionclass.getconstant) - Gets defined constant
php Yaf_Route_Map::assemble Yaf\_Route\_Map::assemble
=========================
(Yaf >=2.3.0)
Yaf\_Route\_Map::assemble — Assemble a url
### Description
```
public Yaf_Route_Map::assemble(array $info, array $query = ?): string
```
Assemble a url.
### Parameters
`info`
`query`
### Return Values
Returns string on success or **`null`** on failure.
### Errors/Exceptions
May throw [Yaf\_Exception\_TypeError](class.yaf-exception-typeerror).
### Examples
**Example #1 **Yaf\_Route\_Map::assemble()**example**
```
<?php
$router = new Yaf_Router();
$route = new Yaf_Route_Map();
$router->addRoute("map", $route);
var_dump($router->getRoute('map')->assemble(
array(
':c' => 'foo_bar'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
)
);
$route = new Yaf_Route_Map(true, '_');
$router->addRoute("map", $route);
var_dump($router->getRoute('map')->assemble(
array(
':a' => 'foo_bar'
),
array(
'tkey1' => 'tval1',
'tkey2' => 'tval2'
)
)
);
```
The above example will output something similar to:
```
string(%d) "/foo/bar?tkey1=tval1&tkey2=tval2"
string(%d) "/foo/bar/_/tkey1/tval1/tkey2/tval2"
```
php SolrParams::getParams SolrParams::getParams
=====================
(PECL solr >= 0.9.2)
SolrParams::getParams — Returns an array of non URL-encoded parameters
### Description
```
final public SolrParams::getParams(): array
```
Returns an array of non URL-encoded parameters
### Parameters
This function has no parameters.
### Return Values
Returns an array of non URL-encoded parameters
php array_diff_ukey array\_diff\_ukey
=================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
array\_diff\_ukey — Computes the difference of arrays using a callback function on the keys for comparison
### Description
```
array_diff_ukey(array $array, array ...$arrays, callable $key_compare_func): array
```
Compares the keys from `array` against the keys from `arrays` and returns the difference. This function is like [array\_diff()](function.array-diff) except the comparison is done on the keys instead of the values.
Unlike [array\_diff\_key()](function.array-diff-key) a user supplied callback function is used for the indices comparison, not internal function.
### Parameters
`array`
The array to compare from
`arrays`
Arrays to compare against
`key_compare_func`
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
```
callback(mixed $a, mixed $b): int
```
### Return Values
Returns an array containing all the entries from `array` that are not present in any of the other arrays.
### Examples
**Example #1 **array\_diff\_ukey()** example**
```
<?php
function key_compare_func($key1, $key2)
{
if ($key1 == $key2)
return 0;
else if ($key1 > $key2)
return 1;
else
return -1;
}
$array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4);
$array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8);
var_dump(array_diff_ukey($array1, $array2, 'key_compare_func'));
?>
```
The above example will output:
```
array(2) {
["red"]=>
int(2)
["purple"]=>
int(4)
}
```
### Notes
>
> **Note**:
>
>
> This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using `array_diff_ukey($array1[0], $array2[0], 'callback_func');`.
>
>
### See Also
* [array\_diff()](function.array-diff) - Computes the difference of arrays
* [array\_udiff()](function.array-udiff) - Computes the difference of arrays by using a callback function for data comparison
* [array\_diff\_assoc()](function.array-diff-assoc) - Computes the difference of arrays with additional index check
* [array\_diff\_uassoc()](function.array-diff-uassoc) - Computes the difference of arrays with additional index check which is performed by a user supplied callback function
* [array\_udiff\_assoc()](function.array-udiff-assoc) - Computes the difference of arrays with additional index check, compares data by a callback function
* [array\_udiff\_uassoc()](function.array-udiff-uassoc) - Computes the difference of arrays with additional index check, compares data and indexes by a callback function
* [array\_diff\_key()](function.array-diff-key) - Computes the difference of arrays using keys for comparison
* [array\_intersect()](function.array-intersect) - Computes the intersection of arrays
* [array\_intersect\_assoc()](function.array-intersect-assoc) - Computes the intersection of arrays with additional index check
* [array\_intersect\_uassoc()](function.array-intersect-uassoc) - Computes the intersection of arrays with additional index check, compares indexes by a callback function
* [array\_intersect\_key()](function.array-intersect-key) - Computes the intersection of arrays using keys for comparison
* [array\_intersect\_ukey()](function.array-intersect-ukey) - Computes the intersection of arrays using a callback function on the keys for comparison
| programming_docs |
php FilesystemIterator::setFlags FilesystemIterator::setFlags
============================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
FilesystemIterator::setFlags — Sets handling flags
### Description
```
public FilesystemIterator::setFlags(int $flags): void
```
Sets handling flags.
### Parameters
`flags`
The handling flags to set. See the [FilesystemIterator constants](class.filesystemiterator#filesystemiterator.constants).
### Return Values
No value is returned.
### Examples
**Example #1 [FilesystemIterator::key()](filesystemiterator.key) example**
This example demonstrates the difference between the [FilesystemIterator::KEY\_AS\_PATHNAME](class.filesystemiterator#filesystemiterator.constants.key-as-pathname) and [FilesystemIterator::KEY\_AS\_FILENAME](class.filesystemiterator#filesystemiterator.constants.key-as-filename) flags.
```
<?php
$iterator = new FilesystemIterator(dirname(__FILE__), FilesystemIterator::KEY_AS_PATHNAME);
echo "Key as Pathname:\n";
foreach ($iterator as $key => $fileinfo) {
echo $key . "\n";
}
$iterator->setFlags(FilesystemIterator::KEY_AS_FILENAME);
echo "\nKey as Filename:\n";
foreach ($iterator as $key => $fileinfo) {
echo $key . "\n";
}
?>
```
Output of the above example in PHP 8.2 is similar to:
```
Key as Pathname:
/www/examples/.
/www/examples/..
/www/examples/apple.jpg
/www/examples/banana.jpg
/www/examples/example.php
Key as Filename:
.
..
apple.jpg
banana.jpg
example.php
```
### See Also
* [FilesystemIterator::\_\_construct()](filesystemiterator.construct) - Constructs a new filesystem iterator
* [FilesystemIterator::getFlags()](filesystemiterator.getflags) - Get the handling flags
php fdf_set_opt fdf\_set\_opt
=============
(PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN)
fdf\_set\_opt — Sets an option of a field
### Description
```
fdf_set_opt(
resource $fdf_document,
string $fieldname,
int $element,
string $str1,
string $str2
): bool
```
Sets options of the given field.
### Parameters
`fdf_document`
The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string).
`fieldname`
Name of the FDF field, as a string.
`element`
`str1`
`str2`
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [fdf\_set\_flags()](function.fdf-set-flags) - Sets a flag of a field
php Gmagick::setimagerenderingintent Gmagick::setimagerenderingintent
================================
(PECL gmagick >= Unknown)
Gmagick::setimagerenderingintent — Sets the image rendering intent
### Description
```
public Gmagick::setimagerenderingintent(int $rendering_intent): Gmagick
```
Sets the image rendering intent.
### Parameters
`rendering_intent`
One of the [Rendering Intent](https://www.php.net/manual/en/gmagick.constants.php#gmagick.constants.renderingintent) constant (`Gmagick::RENDERINGINTENT_*`).
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php The NumberFormatter class
The NumberFormatter class
=========================
Introduction
------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
Programs store and operate on numbers using a locale-independent binary representation. When displaying or printing a number it is converted to a locale-specific string. For example, the number 12345.67 is "12,345.67" in the US, "12 345,67" in France and "12.345,67" in Germany.
By invoking the methods provided by the NumberFormatter class, you can format numbers, currencies, and percentages according to the specified or default locale. NumberFormatter is locale-sensitive so you need to create a new NumberFormatter for each locale. NumberFormatter methods format primitive-type numbers, such as double and output the number as a locale-specific string.
For currencies you can use currency format type to create a formatter that returns a string with the formatted number and the appropriate currency sign. Of course, the NumberFormatter class is unaware of exchange rates so, the number output is the same regardless of the specified currency. This means that the same number has different monetary values depending on the currency locale. If the number is 9988776.65 the results will be:
* 9 988 776,65 € in France
* 9.988.776,65 € in Germany
* $9,988,776.65 in the United States
In order to format percentages, create a locale-specific formatter with percentage format type. With this formatter, a decimal fraction such as 0.75 is displayed as 75%.
For more complex formatting, like spelled-out numbers, the rule-based number formatters are used.
Class synopsis
--------------
class **NumberFormatter** { /\* Methods \*/ public [\_\_construct](numberformatter.create)(string `$locale`, int `$style`, ?string `$pattern` = **`null`**)
```
public static create(string $locale, int $style, ?string $pattern = null): ?NumberFormatter
```
```
public formatCurrency(float $amount, string $currency): string|false
```
```
public format(int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false
```
```
public getAttribute(int $attribute): int|float|false
```
```
public getErrorCode(): int
```
```
public getErrorMessage(): string
```
```
public getLocale(int $type = ULOC_ACTUAL_LOCALE): string|false
```
```
public getPattern(): string|false
```
```
public getSymbol(int $symbol): string|false
```
```
public getTextAttribute(int $attribute): string|false
```
```
public parseCurrency(string $string, string &$currency, int &$offset = null): float|false
```
```
public parse(string $string, int $type = NumberFormatter::TYPE_DOUBLE, int &$offset = null): int|float|false
```
```
public setAttribute(int $attribute, int|float $value): bool
```
```
public setPattern(string $pattern): bool
```
```
public setSymbol(int $symbol, string $value): bool
```
```
public setTextAttribute(int $attribute, string $value): bool
```
} Predefined Constants
--------------------
These styles are used by the [numfmt\_create()](numberformatter.create) to define the type of the formatter.
**`NumberFormatter::PATTERN_DECIMAL`** (int) Decimal format defined by pattern **`NumberFormatter::DECIMAL`** (int) Decimal format **`NumberFormatter::CURRENCY`** (int) Currency format **`NumberFormatter::PERCENT`** (int) Percent format **`NumberFormatter::SCIENTIFIC`** (int) Scientific format **`NumberFormatter::SPELLOUT`** (int) Spellout rule-based format **`NumberFormatter::ORDINAL`** (int) Ordinal rule-based format **`NumberFormatter::DURATION`** (int) Duration rule-based format **`NumberFormatter::PATTERN_RULEBASED`** (int) Rule-based format defined by pattern **`NumberFormatter::CURRENCY_ACCOUNTING`** (int) Currency format for accounting, e.g., `($3.00)` for negative currency amount instead of `-$3.00`. Available as of PHP 7.4.1 and ICU 53. **`NumberFormatter::DEFAULT_STYLE`** (int) Default format for the locale **`NumberFormatter::IGNORE`** (int) Alias for PATTERN\_DECIMAL These constants define how the numbers are parsed or formatted. They should be used as arguments to [numfmt\_format()](numberformatter.format) and [numfmt\_parse()](numberformatter.parse).
**`NumberFormatter::TYPE_DEFAULT`** (int) Derive the type from variable type **`NumberFormatter::TYPE_INT32`** (int) Format/parse as 32-bit integer **`NumberFormatter::TYPE_INT64`** (int) Format/parse as 64-bit integer **`NumberFormatter::TYPE_DOUBLE`** (int) Format/parse as floating point value **`NumberFormatter::TYPE_CURRENCY`** (int) Format/parse as currency value Number format attribute used by [numfmt\_get\_attribute()](numberformatter.getattribute) and [numfmt\_set\_attribute()](numberformatter.setattribute).
**`NumberFormatter::PARSE_INT_ONLY`** (int) Parse integers only. **`NumberFormatter::GROUPING_USED`** (int) Use grouping separator. **`NumberFormatter::DECIMAL_ALWAYS_SHOWN`** (int) Always show decimal point. **`NumberFormatter::MAX_INTEGER_DIGITS`** (int) Maximum integer digits. **`NumberFormatter::MIN_INTEGER_DIGITS`** (int) Minimum integer digits. **`NumberFormatter::INTEGER_DIGITS`** (int) Integer digits. **`NumberFormatter::MAX_FRACTION_DIGITS`** (int) Maximum fraction digits. **`NumberFormatter::MIN_FRACTION_DIGITS`** (int) Minimum fraction digits. **`NumberFormatter::FRACTION_DIGITS`** (int) Fraction digits. **`NumberFormatter::MULTIPLIER`** (int) Multiplier. **`NumberFormatter::GROUPING_SIZE`** (int) Grouping size. **`NumberFormatter::ROUNDING_MODE`** (int) Rounding Mode. **`NumberFormatter::ROUNDING_INCREMENT`** (int) Rounding increment. **`NumberFormatter::FORMAT_WIDTH`** (int) The width to which the output of format() is padded. **`NumberFormatter::PADDING_POSITION`** (int) The position at which padding will take place. See pad position constants for possible argument values. **`NumberFormatter::SECONDARY_GROUPING_SIZE`** (int) Secondary grouping size. **`NumberFormatter::SIGNIFICANT_DIGITS_USED`** (int) Use significant digits. **`NumberFormatter::MIN_SIGNIFICANT_DIGITS`** (int) Minimum significant digits. **`NumberFormatter::MAX_SIGNIFICANT_DIGITS`** (int) Maximum significant digits. **`NumberFormatter::LENIENT_PARSE`** (int) Lenient parse mode used by rule-based formats. Number format text attribute used by [numfmt\_get\_text\_attribute()](numberformatter.gettextattribute) and [numfmt\_set\_text\_attribute()](numberformatter.settextattribute).
**`NumberFormatter::POSITIVE_PREFIX`** (int) Positive prefix. **`NumberFormatter::POSITIVE_SUFFIX`** (int) Positive suffix. **`NumberFormatter::NEGATIVE_PREFIX`** (int) Negative prefix. **`NumberFormatter::NEGATIVE_SUFFIX`** (int) Negative suffix. **`NumberFormatter::PADDING_CHARACTER`** (int) The character used to pad to the format width. **`NumberFormatter::CURRENCY_CODE`** (int) The ISO currency code. **`NumberFormatter::DEFAULT_RULESET`** (int) The default rule set. This is only available with rule-based formatters. **`NumberFormatter::PUBLIC_RULESETS`** (int) The public rule sets. This is only available with rule-based formatters. This is a read-only attribute. The public rulesets are returned as a single string, with each ruleset name delimited by ';' (semicolon). Number format symbols used by [numfmt\_get\_symbol()](numberformatter.getsymbol) and [numfmt\_set\_symbol()](numberformatter.setsymbol).
**`NumberFormatter::DECIMAL_SEPARATOR_SYMBOL`** (int) The decimal separator. **`NumberFormatter::GROUPING_SEPARATOR_SYMBOL`** (int) The grouping separator. **`NumberFormatter::PATTERN_SEPARATOR_SYMBOL`** (int) The pattern separator. **`NumberFormatter::PERCENT_SYMBOL`** (int) The percent sign. **`NumberFormatter::ZERO_DIGIT_SYMBOL`** (int) Zero. **`NumberFormatter::DIGIT_SYMBOL`** (int) Character representing a digit in the pattern. **`NumberFormatter::MINUS_SIGN_SYMBOL`** (int) The minus sign. **`NumberFormatter::PLUS_SIGN_SYMBOL`** (int) The plus sign. **`NumberFormatter::CURRENCY_SYMBOL`** (int) The currency symbol. **`NumberFormatter::INTL_CURRENCY_SYMBOL`** (int) The international currency symbol. **`NumberFormatter::MONETARY_SEPARATOR_SYMBOL`** (int) The monetary separator. **`NumberFormatter::EXPONENTIAL_SYMBOL`** (int) The exponential symbol. **`NumberFormatter::PERMILL_SYMBOL`** (int) Per mill symbol. **`NumberFormatter::PAD_ESCAPE_SYMBOL`** (int) Escape padding character. **`NumberFormatter::INFINITY_SYMBOL`** (int) Infinity symbol. **`NumberFormatter::NAN_SYMBOL`** (int) Not-a-number symbol. **`NumberFormatter::SIGNIFICANT_DIGIT_SYMBOL`** (int) Significant digit symbol. **`NumberFormatter::MONETARY_GROUPING_SEPARATOR_SYMBOL`** (int) The monetary grouping separator. Rounding mode values used by [numfmt\_get\_attribute()](numberformatter.getattribute) and [numfmt\_set\_attribute()](numberformatter.setattribute) with **`NumberFormatter::ROUNDING_MODE`** attribute.
**`NumberFormatter::ROUND_CEILING`** (int) Rounding mode to round towards positive infinity. **`NumberFormatter::ROUND_DOWN`** (int) Rounding mode to round towards zero. **`NumberFormatter::ROUND_FLOOR`** (int) Rounding mode to round towards negative infinity. **`NumberFormatter::ROUND_HALFDOWN`** (int) Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down. **`NumberFormatter::ROUND_HALFEVEN`** (int) Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. **`NumberFormatter::ROUND_HALFUP`** (int) Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round up. **`NumberFormatter::ROUND_UP`** (int) Rounding mode to round away from zero. Pad position values used by [numfmt\_get\_attribute()](numberformatter.getattribute) and [numfmt\_set\_attribute()](numberformatter.setattribute) with **`NumberFormatter::PADDING_POSITION`** attribute.
**`NumberFormatter::PAD_AFTER_PREFIX`** (int) Pad characters inserted after the prefix. **`NumberFormatter::PAD_AFTER_SUFFIX`** (int) Pad characters inserted after the suffix. **`NumberFormatter::PAD_BEFORE_PREFIX`** (int) Pad characters inserted before the prefix. **`NumberFormatter::PAD_BEFORE_SUFFIX`** (int) Pad characters inserted before the suffix. See Also
--------
* [» ICU formatting documentation](https://unicode-org.github.io/icu/userguide/format_parse/)
* [» ICU number formatters](https://unicode-org.github.io/icu/userguide/format_parse/numbers/)
* [» ICU decimal formatters](http://www.icu-project.org/apiref/icu4c/classDecimalFormat.html#details)
* [» ICU rule-based number formatters](http://www.icu-project.org/apiref/icu4c/classRuleBasedNumberFormat.html#details)
Table of Contents
-----------------
* [NumberFormatter::create](numberformatter.create) — Create a number formatter
* [NumberFormatter::formatCurrency](numberformatter.formatcurrency) — Format a currency value
* [NumberFormatter::format](numberformatter.format) — Format a number
* [NumberFormatter::getAttribute](numberformatter.getattribute) — Get an attribute
* [NumberFormatter::getErrorCode](numberformatter.geterrorcode) — Get formatter's last error code
* [NumberFormatter::getErrorMessage](numberformatter.geterrormessage) — Get formatter's last error message
* [NumberFormatter::getLocale](numberformatter.getlocale) — Get formatter locale
* [NumberFormatter::getPattern](numberformatter.getpattern) — Get formatter pattern
* [NumberFormatter::getSymbol](numberformatter.getsymbol) — Get a symbol value
* [NumberFormatter::getTextAttribute](numberformatter.gettextattribute) — Get a text attribute
* [NumberFormatter::parseCurrency](numberformatter.parsecurrency) — Parse a currency number
* [NumberFormatter::parse](numberformatter.parse) — Parse a number
* [NumberFormatter::setAttribute](numberformatter.setattribute) — Set an attribute
* [NumberFormatter::setPattern](numberformatter.setpattern) — Set formatter pattern
* [NumberFormatter::setSymbol](numberformatter.setsymbol) — Set a symbol value
* [NumberFormatter::setTextAttribute](numberformatter.settextattribute) — Set a text attribute
php Locale::getDisplayLanguage Locale::getDisplayLanguage
==========================
locale\_get\_display\_language
==============================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
Locale::getDisplayLanguage -- locale\_get\_display\_language — Returns an appropriately localized display name for language of the inputlocale
### Description
Object-oriented style
```
public static Locale::getDisplayLanguage(string $locale, ?string $displayLocale = null): string|false
```
Procedural style
```
locale_get_display_language(string $locale, ?string $displayLocale = null): string|false
```
Returns an appropriately localized display name for language of the input locale. If is **`null`** then the default locale is used.
### Parameters
`locale`
The locale to return a display language for
`displayLocale`
Optional format locale to use to display the language name
### Return Values
Display name of the language for the `locale` in the format appropriate for `displayLocale`, or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `displayLocale` is nullable now. |
### Examples
**Example #1 **locale\_get\_display\_language()** example**
```
<?php
echo locale_get_display_language('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo locale_get_display_language('sl-Latn-IT-nedis', 'de');
?>
```
**Example #2 OO example**
```
<?php
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'en');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'fr');
echo ";\n";
echo Locale::getDisplayLanguage('sl-Latn-IT-nedis', 'de');
?>
```
The above example will output:
```
Slovenian;
slov\xc3\xa8ne;
Slowenisch
```
### See Also
* [locale\_get\_display\_name()](locale.getdisplayname) - Returns an appropriately localized display name for the input locale
* [locale\_get\_display\_script()](locale.getdisplayscript) - Returns an appropriately localized display name for script of the input locale
* [locale\_get\_display\_region()](locale.getdisplayregion) - Returns an appropriately localized display name for region of the input locale
* [locale\_get\_display\_variant()](locale.getdisplayvariant) - Returns an appropriately localized display name for variants of the input locale
php ibase_maintain_db ibase\_maintain\_db
===================
(PHP 5, PHP 7 < 7.4.0)
ibase\_maintain\_db — Execute a maintenance command on the database server
### Description
```
ibase_maintain_db(
resource $service_handle,
string $db,
int $action,
int $argument = 0
): bool
```
**Warning**This function is currently not documented; only its argument list is available.
### Return Values
Returns **`true`** on success or **`false`** on failure.
php Ds\Pair::jsonSerialize Ds\Pair::jsonSerialize
======================
(PECL ds >= 1.0.0)
Ds\Pair::jsonSerialize — Returns a representation that can be converted to JSON
See [JsonSerializable::jsonSerialize()](jsonserializable.jsonserialize)
>
> **Note**:
>
>
> You should never need to call this directly.
>
>
php GearmanClient::doHigh GearmanClient::doHigh
=====================
(PECL gearman >= 0.5.0)
GearmanClient::doHigh — Run a single high priority task
### Description
```
public GearmanClient::doHigh(string $function_name, string $workload, string $unique = ?): string
```
Runs a single high priority task and returns a string representation of the result. It is up to the [GearmanClient](class.gearmanclient) and [GearmanWorker](class.gearmanworker) to agree on the format of the result. High priority tasks will get precedence over normal and low priority tasks in the job queue.
### Parameters
`function_name`
A registered function the worker is to execute
`workload`
Serialized data to be processed
`unique`
A unique ID used to identify a particular task
### Return Values
A string representing the results of running a task.
### See Also
* [GearmanClient::doNormal()](gearmanclient.donormal) - Run a single task and return a result
* [GearmanClient::doLow()](gearmanclient.dolow) - Run a single low priority task
* [GearmanClient::doBackground()](gearmanclient.dobackground) - Run a task in the background
* [GearmanClient::doHighBackground()](gearmanclient.dohighbackground) - Run a high priority task in the background
* [GearmanClient::doLowBackground()](gearmanclient.dolowbackground) - Run a low priority task in the background
| programming_docs |
php filectime filectime
=========
(PHP 4, PHP 5, PHP 7, PHP 8)
filectime — Gets inode change time of file
### Description
```
filectime(string $filename): int|false
```
Gets the inode change time of a file.
### Parameters
`filename`
Path to the file.
### Return Values
Returns the time the file was last changed, or **`false`** on failure. The time is returned as a Unix timestamp.
### Errors/Exceptions
Upon failure, an **`E_WARNING`** is emitted.
### Examples
**Example #1 A **filectime()** example**
```
<?php
// outputs e.g. somefile.txt was last changed: December 29 2002 22:16:23.
$filename = 'somefile.txt';
if (file_exists($filename)) {
echo "$filename was last changed: " . date("F d Y H:i:s.", filectime($filename));
}
?>
```
### Notes
>
> **Note**:
>
>
> Note: In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the permissions, owner, group, or other metadata from the inode is updated. See also [filemtime()](function.filemtime) (which is what you want to use when you want to create "Last Modified" footers on web pages) and [fileatime()](function.fileatime).
>
>
>
> **Note**:
>
>
> Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.
>
>
>
> **Note**:
>
>
> Note that time resolution may differ from one file system to another.
>
>
>
> **Note**: The results of this function are cached. See [clearstatcache()](function.clearstatcache) for more details.
>
>
**Tip**As of PHP 5.0.0, this function can also be used with *some* URL wrappers. Refer to [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality.
### See Also
* [filemtime()](function.filemtime) - Gets file modification time
php None Predefined Variables
--------------------
PHP provides a large number of predefined variables to any script which it runs. Many of these variables, however, cannot be fully documented as they are dependent upon which server is running, the version and setup of the server, and other factors. Some of these variables will not be available when PHP is run on the [command line](https://www.php.net/manual/en/features.commandline.php). Refer to the [list of predefined variables](https://www.php.net/manual/en/reserved.variables.php) for details.
PHP also provides an additional set of predefined arrays containing variables from the web server (if applicable), the environment, and user input. These arrays are rather special in that they are automatically global - i.e., automatically available in every scope. For this reason, they are often known as "superglobals". (There is no mechanism in PHP for user-defined superglobals.) Refer to the [list of superglobals](language.variables.superglobals) for details.
>
> **Note**: **Variable variables**
>
>
>
> Superglobals cannot be used as [variable variables](language.variables.variable) inside functions or class methods.
>
>
If certain variables in [variables\_order](https://www.php.net/manual/en/ini.core.php#ini.variables-order) are not set, their appropriate PHP predefined arrays are also left empty.
php IntlBreakIterator::getPartsIterator IntlBreakIterator::getPartsIterator
===================================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
IntlBreakIterator::getPartsIterator — Create iterator for navigating fragments between boundaries
### Description
```
public IntlBreakIterator::getPartsIterator(string $type = IntlPartsIterator::KEY_SEQUENTIAL): IntlPartsIterator
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`type`
Optional key type. Possible values are:
* **`IntlPartsIterator::KEY_SEQUENTIAL`** - The default. Sequentially increasing integers used as key.
* **`IntlPartsIterator::KEY_LEFT`** - Byte offset left of current part used as key.
* **`IntlPartsIterator::KEY_RIGHT`** - Byte offset right of current part used as key.
### Return Values
php Zookeeper::exists Zookeeper::exists
=================
(PECL zookeeper >= 0.1.0)
Zookeeper::exists — Checks the existence of a node in zookeeper synchronously
### Description
```
public Zookeeper::exists(string $path, callable $watcher_cb = null): array
```
### Parameters
`path`
The name of the node. Expressed as a file name with slashes separating ancestors of the node.
`watcher_cb`
if nonzero, a watch will be set at the server to notify the client if the node changes. The watch will be set even if the node does not
### Return Values
Returns the value of stat for the path if the given node exists, otherwise false.
### Errors/Exceptions
This method emits PHP error/warning when parameters count or types are wrong or fail to check the existence of a node.
**Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives.
### Examples
**Example #1 **Zookeeper::exists()** example**
Check the existence of a node.
```
<?php
$zookeeper = new Zookeeper('locahost:2181');
$path = '/path/to/node';
$r = $zookeeper->exists($path);
if ($r)
echo 'EXISTS';
else
echo 'N/A or ERR';
?>
```
The above example will output:
```
EXISTS
```
### See Also
* [Zookeeper::get()](zookeeper.get) - Gets the data associated with a node synchronously
* [ZookeeperException](class.zookeeperexception)
php Ds\Sequence::find Ds\Sequence::find
=================
(PECL ds >= 1.0.0)
Ds\Sequence::find — Attempts to find a value's index
### Description
```
abstract public Ds\Sequence::find(mixed $value): mixed
```
Returns the index of the `value`, or **`false`** if not found.
### Parameters
`value`
The value to find.
### Return Values
The index of the value, or **`false`** if not found.
>
> **Note**:
>
>
> Values will be compared by value and by type.
>
>
### Examples
**Example #1 **Ds\Sequence::find()** example**
```
<?php
$sequence = new \Ds\Vector(["a", 1, true]);
var_dump($sequence->find("a")); // 0
var_dump($sequence->find("b")); // false
var_dump($sequence->find("1")); // false
var_dump($sequence->find(1)); // 1
?>
```
The above example will output something similar to:
```
int(0)
bool(false)
bool(false)
int(1)
```
php stream_select stream\_select
==============
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
stream\_select — Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds
### Description
```
stream_select(
?array &$read,
?array &$write,
?array &$except,
?int $seconds,
?int $microseconds = null
): int|false
```
The **stream\_select()** function accepts arrays of streams and waits for them to change status. Its operation is equivalent to that of the [socket\_select()](function.socket-select) function except in that it acts on streams.
### Parameters
`read`
The streams listed in the `read` array will be watched to see if characters become available for reading (more precisely, to see if a read will not block - in particular, a stream resource is also ready on end-of-file, in which case an [fread()](function.fread) will return a zero length string).
`write`
The streams listed in the `write` array will be watched to see if a write will not block.
`except`
The streams listed in the `except` array will be watched for high priority exceptional ("out-of-band") data arriving.
>
> **Note**:
>
>
> When **stream\_select()** returns, the arrays `read`, `write` and `except` are modified to indicate which stream resource(s) actually changed status. The original keys of the arrays are preserved.
>
>
`seconds`
The `seconds` and `microseconds` together form the *timeout* parameter, `seconds` specifies the number of seconds while `microseconds` the number of microseconds. The `timeout` is an upper bound on the amount of time that **stream\_select()** will wait before it returns. If `seconds` and `microseconds` are both set to `0`, **stream\_select()** will not wait for data - instead it will return immediately, indicating the current status of the streams.
If `seconds` is **`null`** **stream\_select()** can block indefinitely, returning only when an event on one of the watched streams occurs (or if a signal interrupts the system call).
**Warning** Using a timeout value of `0` allows you to instantaneously poll the status of the streams, however, it is NOT a good idea to use a `0` timeout value in a loop as it will cause your script to consume too much CPU time.
It is much better to specify a timeout value of a few seconds, although if you need to be checking and running other code concurrently, using a timeout value of at least `200000` microseconds will help reduce the CPU usage of your script.
Remember that the timeout value is the maximum time that will elapse; **stream\_select()** will return as soon as the requested streams are ready for use.
`microseconds`
See `seconds` description.
### Return Values
On success **stream\_select()** returns the number of stream resources contained in the modified arrays, which may be zero if the timeout expires before anything interesting happens. On error **`false`** is returned and a warning raised (this can happen if the system call is interrupted by an incoming signal).
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | `microseconds` is now nullable. |
### Examples
**Example #1 **stream\_select()** Example**
This example checks to see if data has arrived for reading on either `$stream1` or `$stream2`. Since the timeout value is `0` it will return immediately:
```
<?php
/* Prepare the read array */
$read = array($stream1, $stream2);
$write = NULL;
$except = NULL;
if (false === ($num_changed_streams = stream_select($read, $write, $except, 0))) {
/* Error handling */
} elseif ($num_changed_streams > 0) {
/* At least on one of the streams something interesting happened */
}
?>
```
### Notes
>
> **Note**:
>
>
> Due to a limitation in the current Zend Engine it is not possible to pass a constant modifier like **`null`** directly as a parameter to a function which expects this parameter to be passed by reference. Instead use a temporary variable or an expression with the leftmost member being a temporary variable:
>
>
>
> ```
> <?php
> $e = NULL;
> stream_select($r, $w, $e, 0);
> ?>
> ```
>
>
> **Note**:
>
>
> Be sure to use the `===` operator when checking for an error. Since the **stream\_select()** may return 0 the comparison with `==` would evaluate to **`true`**:
>
>
>
> ```
> <?php
> $e = NULL;
> if (false === stream_select($r, $w, $e, 0)) {
> echo "stream_select() failed\n";
> }
> ?>
> ```
>
>
> **Note**:
>
>
> If you read/write to a stream returned in the arrays be aware that they do not necessarily read/write the full amount of data you have requested. Be prepared to even only be able to read/write a single byte.
>
>
>
> **Note**:
>
>
> Some streams (like `zlib`) cannot be selected by this function.
>
>
>
> **Note**: **Windows compatibility**
>
>
>
> Use of **stream\_select()** on file descriptors returned by [proc\_open()](function.proc-open) will fail and return **`false`** under Windows.
>
> **`STDIN`** from a console changes status as soon as *any* input events are available, but reading from the stream may still block.
>
>
### See Also
* [stream\_set\_blocking()](function.stream-set-blocking) - Set blocking/non-blocking mode on a stream
php OAuthProvider::__construct OAuthProvider::\_\_construct
============================
(PECL OAuth >= 1.0.0)
OAuthProvider::\_\_construct — Constructs a new OAuthProvider object
### Description
```
public OAuthProvider::__construct(array $params_array = ?)
```
Initiates a new [OAuthProvider](class.oauthprovider) object.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`params_array`
Setting these optional parameters is limited to the [CLI SAPI](https://www.php.net/manual/en/features.commandline.php).
### Return Values
An [OAuthProvider](class.oauthprovider) object.
### Examples
**Example #1 **OAuthProvider::\_\_construct()** example**
```
<?php
try {
$op = new OAuthProvider();
// Uses user-defined callback functions
$op->consumerHandler(array($this, 'lookupConsumer'));
$op->timestampNonceHandler(array($this, 'timestampNonceChecker'));
$op->tokenHandler(array($this, 'myTokenHandler'));
// Ignore the foo_uri parameter
$op->setParam('foo_uri', NULL);
// No token needed for this end point
$op->setRequestTokenPath('/v1/oauth/request_token');
$op->checkOAuthRequest();
} catch (OAuthException $e) {
echo OAuthProvider::reportProblem($e);
}
?>
```
### See Also
* [OAuthProvider::setParam()](oauthprovider.setparam) - Set a parameter
php ZipArchive::getCommentIndex ZipArchive::getCommentIndex
===========================
(PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0)
ZipArchive::getCommentIndex — Returns the comment of an entry using the entry index
### Description
```
public ZipArchive::getCommentIndex(int $index, int $flags = 0): string|false
```
Returns the comment of an entry using the entry index.
### Parameters
`index`
Index of the entry
`flags`
If flags is set to **`ZipArchive::FL_UNCHANGED`**, the original unchanged comment is returned.
### Return Values
Returns the comment on success or **`false`** on failure.
### Examples
**Example #1 Dump an entry comment**
```
<?php
$zip = new ZipArchive;
$res = $zip->open('test1.zip');
if ($res === TRUE) {
var_dump($zip->getCommentIndex(1));
} else {
echo 'failed, code:' . $res;
}
?>
```
php mysqli::stat mysqli::stat
============
mysqli\_stat
============
(PHP 5, PHP 7, PHP 8)
mysqli::stat -- mysqli\_stat — Gets the current system status
### Description
Object-oriented style
```
public mysqli::stat(): string|false
```
Procedural style
```
mysqli_stat(mysqli $mysql): string|false
```
**mysqli\_stat()** returns a string containing information similar to that provided by the 'mysqladmin status' command. This includes uptime in seconds and the number of running threads, questions, reloads, and open tables.
### Parameters
`mysql`
Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init)
### Return Values
A string describing the server status. **`false`** if an error occurred.
### Examples
**Example #1 **mysqli::stat()** example**
Object-oriented style
```
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf ("System status: %s\n", $mysqli->stat());
$mysqli->close();
?>
```
Procedural style
```
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
printf("System status: %s\n", mysqli_stat($link));
mysqli_close($link);
?>
```
The above examples will output:
```
System status: Uptime: 272 Threads: 1 Questions: 5340 Slow queries: 0
Opens: 13 Flush tables: 1 Open tables: 0 Queries per second avg: 19.632
Memory in use: 8496K Max memory used: 8560K
```
### See Also
* [mysqli\_get\_server\_info()](mysqli.get-server-info) - Returns the version of the MySQL server
php openssl_pkey_get_public openssl\_pkey\_get\_public
==========================
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
openssl\_pkey\_get\_public — Extract public key from certificate and prepare it for use
### Description
```
openssl_pkey_get_public(OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $public_key): OpenSSLAsymmetricKey|false
```
**openssl\_pkey\_get\_public()** extracts the public key from `public_key` and prepares it for use by other functions.
### Parameters
`public_key`
`public_key` can be one of the following:
1. an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) instance
2. a string having the format file://path/to/file.pem. The named file must contain a PEM encoded certificate/public key (it may contain both).
3. A PEM formatted public key.
### Return Values
Returns an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) instance on success, or **`false`** on error.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | On success, this function returns an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` was returned. |
| 8.0.0 | `public_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) or [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` or `OpenSSL X.509` was accepted. |
php The SolrObject class
The SolrObject class
====================
Introduction
------------
(PECL solr >= 0.9.2)
This is an object whose properties can also by accessed using the array syntax. All its properties are read-only.
Class synopsis
--------------
final class **SolrObject** implements [ArrayAccess](class.arrayaccess) { /\* Methods \*/ public [\_\_construct](solrobject.construct)()
```
public getPropertyNames(): array
```
```
public offsetExists(string $property_name): bool
```
```
public offsetGet(string $property_name): mixed
```
```
public offsetSet(string $property_name, string $property_value): void
```
```
public offsetUnset(string $property_name): void
```
public [\_\_destruct](solrobject.destruct)() } Table of Contents
-----------------
* [SolrObject::\_\_construct](solrobject.construct) — Creates Solr object
* [SolrObject::\_\_destruct](solrobject.destruct) — Destructor
* [SolrObject::getPropertyNames](solrobject.getpropertynames) — Returns an array of all the names of the properties
* [SolrObject::offsetExists](solrobject.offsetexists) — Checks if the property exists
* [SolrObject::offsetGet](solrobject.offsetget) — Used to retrieve a property
* [SolrObject::offsetSet](solrobject.offsetset) — Sets the value for a property
* [SolrObject::offsetUnset](solrobject.offsetunset) — Unsets the value for the property
php xmlrpc_server_destroy xmlrpc\_server\_destroy
=======================
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
xmlrpc\_server\_destroy — Destroys server resources
### Description
```
xmlrpc_server_destroy(resource $server): bool
```
**Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
**Warning**This function is currently not documented; only its argument list is available.
php curl_share_init curl\_share\_init
=================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
curl\_share\_init — Initialize a cURL share handle
### Description
```
curl_share_init(): CurlShareHandle
```
Allows to share data between cURL handles.
### Parameters
This function has no parameters.
### Return Values
Returns a cURL share handle.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | This function returns a [CurlShareHandle](class.curlsharehandle) instance now; previously, a resource was returned. |
### Examples
**Example #1 **curl\_share\_init()** example**
This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing.
```
<?php
// Create cURL share handle and set it to share cookie data
$sh = curl_share_init();
curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE);
// Initialize the first cURL handle and assign the share handle to it
$ch1 = curl_init("http://example.com/");
curl_setopt($ch1, CURLOPT_SHARE, $sh);
// Execute the first cURL handle
curl_exec($ch1);
// Initialize the second cURL handle and assign the share handle to it
$ch2 = curl_init("http://php.net/");
curl_setopt($ch2, CURLOPT_SHARE, $sh);
// Execute the second cURL handle
// all cookies from $ch1 handle are shared with $ch2 handle
curl_exec($ch2);
// Close the cURL share handle
curl_share_close($sh);
// Close the cURL handles
curl_close($ch1);
curl_close($ch2);
?>
```
### See Also
* [curl\_share\_setopt()](function.curl-share-setopt) - Set an option for a cURL share handle
* [curl\_share\_close()](function.curl-share-close) - Close a cURL share handle
| programming_docs |
php svn_status svn\_status
===========
(PECL svn >= 0.1.0)
svn\_status — Returns the status of working copy files and directories
### Description
```
svn_status(string $path, int $flags = 0): array
```
Returns the status of working copy files and directories, giving modifications, additions, deletions and other changes to items in the working copy.
### Parameters
`path`
Local path to file or directory to retrieve status of.
> **Note**: Relative paths will be resolved as if the current working directory was the one that contains the PHP binary. To use the calling script's working directory, use [realpath()](function.realpath) or dirname(\_\_FILE\_\_).
>
>
`flags`
Any combination of **`Svn::NON_RECURSIVE`**, **`Svn::ALL`** (regardless of modification status), **`Svn::SHOW_UPDATES`** (entries will be added for items that are out-of-date), **`Svn::NO_IGNORE`** (disregard `svn:ignore` properties when scanning for new files) and **`Svn::IGNORE_EXTERNALS`**.
### Return Values
Returns a numerically indexed array of associative arrays detailing the status of items in the repository:
```
Array (
[0] => Array (
// information on item
)
[1] => ...
)
```
The information on the item is an associative array that can contain the following keys:
path
String path to file/directory of this entry on local filesystem. text\_status
Status of item's text. Refer to [status constants](https://www.php.net/manual/en/svn.constants.php#svn.constants.status) for possible values. repos\_text\_status
Status of item's text in repository. Only accurate if `update` was set to **`true`**. Refer to [status constants](https://www.php.net/manual/en/svn.constants.php#svn.constants.status) for possible values. prop\_status
Status of item's properties. Refer to [status constants](https://www.php.net/manual/en/svn.constants.php#svn.constants.status) for possible values. repos\_prop\_status
Status of item's property in repository. Only accurate if `update` was set to **`true`**. Refer to [status constants](https://www.php.net/manual/en/svn.constants.php#svn.constants.status) for possible values. locked
Whether or not the item is locked. (Only set if **`true`**.) copied
Whether or not the item was copied (scheduled for addition with history). (Only set if **`true`**.) switched
Whether or not the item was switched using the switch command. (Only set if **`true`**) These keys are only set if the item is versioned:
name
Base name of item in repository. url
URL of item in repository. repos
Base URL of repository. revision
Integer revision of item in working copy. kind
Type of item, i.e. file or directory. Refer to [type constants](https://www.php.net/manual/en/svn.constants.php#svn.constants.type) for possible values. schedule
Scheduled action for item, i.e. addition or deletion. Constants for these magic numbers are not available, they can be emulated by using:
```
<?php
if (!defined('svn_wc_schedule_normal')) {
define('svn_wc_schedule_normal', 0); // nothing special
define('svn_wc_schedule_add', 1); // item will be added
define('svn_wc_schedule_delete', 2); // item will be deleted
define('svn_wc_schedule_replace', 3); // item will be added and deleted
}
?>
```
deleted
Whether or not the item was deleted, but parent revision lags behind. (Only set if **`true`**.) absent
Whether or not the item is absent, that is, Subversion knows that there should be something there but there isn't. (Only set if **`true`**.) incomplete
Whether or not the entries file for a directory is incomplete. (Only set if **`true`**.) cmt\_date
Integer Unix timestamp of last commit date. (Unaffected by `update`.) cmt\_rev
Integer revision of last commit. (Unaffected by `update`.) cmt\_author
String author of last commit. (Unaffected by `update`.) prop\_time
Integer Unix timestamp of last up-to-date time for properties text\_time
Integer Unix timestamp of last up-to-date time for text ### Examples
**Example #1 Basic example**
This example demonstrates a basic, theoretical usage of this function.
```
<?php
print_r(svn_status(realpath('wc')));
?>
```
The above example will output something similar to:
```
Array (
[0] => Array (
[path] => /home/bob/wc/sandwich.txt
[text_status] => 8 // item was modified
[repos_text_status] => 1 // no information available, use update
[prop_status] => 3 // no changes
[repos_prop_status] => 1 // no information available, use update
[name] => sandwich.txt
[url] => http://www.example.com/svnroot/deli/trunk/sandwich.txt
[repos] => http://www.example.com/svnroot/
[revision] => 123
[kind] => 1 // file
[schedule] => 0 // no special actions scheduled
[cmt_date] => 1165543135
[cmt_rev] => 120
[cmt_author] => Alice
[prop_time] => 1180201728
[text_time] => 1180201729
)
)
```
### Notes
**Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
### See Also
* [svn\_update()](function.svn-update) - Update working copy
* [svn\_log()](function.svn-log) - Returns the commit log messages of a repository URL
* [» SVN documentation for svn status](http://svnbook.red-bean.com/en/1.2/svn.ref.svn.c.status.html)
php ArrayIterator::natcasesort ArrayIterator::natcasesort
==========================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
ArrayIterator::natcasesort — Sort entries naturally, case insensitive
### Description
```
public ArrayIterator::natcasesort(): bool
```
Sort the entries by values using a case insensitive "natural order" algorithm.
>
> **Note**:
>
>
> If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
>
>
### Parameters
This function has no parameters.
### Return Values
Always returns **`true`**.
### See Also
* [ArrayIterator::asort()](arrayiterator.asort) - Sort entries by values
* [ArrayIterator::ksort()](arrayiterator.ksort) - Sort entries by keys
* [ArrayIterator::natsort()](arrayiterator.natsort) - Sort entries naturally
* [ArrayIterator::uasort()](arrayiterator.uasort) - Sort with a user-defined comparison function and maintain index association
* [ArrayIterator::uksort()](arrayiterator.uksort) - Sort by keys using a user-defined comparison function
* [natcasesort()](function.natcasesort) - Sort an array using a case insensitive "natural order" algorithm
php eio_mknod eio\_mknod
==========
(PECL eio >= 0.0.1dev)
eio\_mknod — Create a special or ordinary file
### Description
```
eio_mknod(
string $path,
int $mode,
int $dev,
int $pri = EIO_PRI_DEFAULT,
callable $callback = NULL,
mixed $data = NULL
): resource
```
**eio\_mknod()** creates ordinary or special(often) file.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`path`
Path for the new node(file).
`mode`
Specifies both the permissions to use and the type of node to be created. It should be a combination (using bitwise OR) of one of the file types listed below and the permissions for the new node(e.g. 0640). Possible file types are: **`EIO_S_IFREG`**(regular file), **`EIO_S_IFCHR`**(character file), **`EIO_S_IFBLK`**(block special file), **`EIO_S_IFIFO`**(FIFO - named pipe) and **`EIO_S_IFSOCK`**(UNIX domain socket). To specify permissions *EIO\_S\_I\** constants could be used.
`dev`
If the file type is **`EIO_S_IFCHR`** or **`EIO_S_IFBLK`** then dev specifies the major and minor numbers of the newly created device special file. Otherwise `dev` ignored. See *mknod(2) man page for details*.
`pri`
The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**.
`callback`
`callback` function is called when the request is done. It should match the following prototype:
```
void callback(mixed $data, int $result[, resource $req]);
```
`data`
is custom data passed to the request.
`result`
request-specific result value; basically, the value returned by corresponding system call.
`req`
is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error)
`data`
Arbitrary variable passed to `callback`.
### Return Values
**eio\_mknod()** returns request resource on success, or **`false`** on failure.
### Examples
**Example #1 **eio\_mknod()** example**
```
<?php
// FIFO name
$temp_filename = "/tmp/eio-temp-fifo";
/* Is called when eio_mknod() finishes */
function my_mknod_callback($data, $result) {
$s = stat($data);
var_dump($s);
if ($result == 0) {
echo "eio_mknod_ok";
}
@unlink($data);
}
eio_mknod($temp_filename, EIO_S_IFIFO, 0,
EIO_PRI_DEFAULT, "my_mknod_callback", $temp_filename);
eio_event_loop();
?>
```
The above example will output something similar to:
```
array(26) {
[0]=>
int(17)
[1]=>
int(2337608)
[2]=>
int(4096)
[3]=>
int(1)
[4]=>
int(1000)
[5]=>
int(100)
[6]=>
int(0)
[7]=>
int(0)
[8]=>
int(1318241261)
[9]=>
int(1318241261)
[10]=>
int(1318241261)
[11]=>
int(4096)
[12]=>
int(0)
["dev"]=>
int(17)
["ino"]=>
int(2337608)
["mode"]=>
int(4096)
["nlink"]=>
int(1)
["uid"]=>
int(1000)
["gid"]=>
int(100)
["rdev"]=>
int(0)
["size"]=>
int(0)
["atime"]=>
int(1318241261)
["mtime"]=>
int(1318241261)
["ctime"]=>
int(1318241261)
["blksize"]=>
int(4096)
["blocks"]=>
int(0)
}
eio_mknod_ok
```
### See Also
* [eio\_open()](function.eio-open) - Opens a file
php XMLReader::readInnerXml XMLReader::readInnerXml
=======================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
XMLReader::readInnerXml — Retrieve XML from current node
### Description
```
public XMLReader::readInnerXml(): string
```
Reads the contents of the current node, including child nodes and markup.
### Parameters
This function has no parameters.
### Return Values
Returns the contents of the current node as a string. Empty string on failure.
### Notes
**Caution**This function is only available when PHP is compiled against libxml 20620 or later.
### See Also
* [XMLReader::readString()](xmlreader.readstring) - Reads the contents of the current node as a string
* [XMLReader::readOuterXml()](xmlreader.readouterxml) - Retrieve XML from current node, including itself
* [XMLReader::expand()](xmlreader.expand) - Returns a copy of the current node as a DOM object
php SolrDocument::__destruct SolrDocument::\_\_destruct
==========================
(PECL solr >= 0.9.2)
SolrDocument::\_\_destruct — Destructor
### Description
public **SolrDocument::\_\_destruct**() Destructor for SolrDocument.
### Parameters
This function has no parameters.
### Return Values
php ldap_close ldap\_close
===========
(PHP 4, PHP 5, PHP 7, PHP 8)
ldap\_close — Alias of [ldap\_unbind()](function.ldap-unbind)
### Description
This function is an alias of: [ldap\_unbind()](function.ldap-unbind).
php IntlIterator::valid IntlIterator::valid
===================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
IntlIterator::valid — Check if current position is valid
### Description
```
public IntlIterator::valid(): bool
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php The Yaf_Request_Abstract class
The Yaf\_Request\_Abstract class
================================
Introduction
------------
(Yaf >=1.0.0)
Class synopsis
--------------
class **Yaf\_Request\_Abstract** { /\* Constants \*/ const string [SCHEME\_HTTP](class.yaf-request-abstract#yaf-request-abstract.constants.scheme-http) = http;
const string [SCHEME\_HTTPS](class.yaf-request-abstract#yaf-request-abstract.constants.scheme-https) = https; /\* Properties \*/
public [$module](class.yaf-request-abstract#yaf-request-abstract.props.module);
public [$controller](class.yaf-request-abstract#yaf-request-abstract.props.controller);
public [$action](class.yaf-request-abstract#yaf-request-abstract.props.action);
public [$method](class.yaf-request-abstract#yaf-request-abstract.props.method);
protected [$params](class.yaf-request-abstract#yaf-request-abstract.props.params);
protected [$language](class.yaf-request-abstract#yaf-request-abstract.props.language);
protected [$\_exception](class.yaf-request-abstract#yaf-request-abstract.props.exception);
protected [$\_base\_uri](class.yaf-request-abstract#yaf-request-abstract.props.base-uri);
protected [$uri](class.yaf-request-abstract#yaf-request-abstract.props.uri);
protected [$dispatched](class.yaf-request-abstract#yaf-request-abstract.props.dispatched);
protected [$routed](class.yaf-request-abstract#yaf-request-abstract.props.routed); /\* Methods \*/
```
public clearParams(): bool
```
```
public getActionName(): void
```
```
public getBaseUri(): void
```
```
public getControllerName(): void
```
```
public getEnv(string $name, string $default = ?): void
```
```
public getException(): void
```
```
public getLanguage(): void
```
```
public getMethod(): string
```
```
public getModuleName(): void
```
```
public getParam(string $name, string $default = ?): mixed
```
```
public getParams(): array
```
```
public getRequestUri(): void
```
```
public getServer(string $name, string $default = ?): void
```
```
public isCli(): bool
```
```
public isDispatched(): bool
```
```
public isGet(): bool
```
```
public isHead(): bool
```
```
public isOptions(): bool
```
```
public isPost(): bool
```
```
public isPut(): bool
```
```
public isRouted(): bool
```
```
public isXmlHttpRequest(): bool
```
```
public setActionName(string $action, bool $format_name = true): void
```
```
public setBaseUri(string $uir): bool
```
```
public setControllerName(string $controller, bool $format_name = true): void
```
```
public setDispatched(): void
```
```
public setModuleName(string $module, bool $format_name = true): void
```
```
public setParam(string $name, string $value = ?): bool
```
```
public setRequestUri(string $uir): void
```
```
public setRouted(string $flag = ?): void
```
} Properties
----------
module controller action method params language \_exception \_base\_uri uri dispatched routed Predefined Constants
--------------------
**`Yaf_Request_Abstract::SCHEME_HTTP`** **`Yaf_Request_Abstract::SCHEME_HTTPS`** Table of Contents
-----------------
* [Yaf\_Request\_Abstract::clearParams](yaf-request-abstract.clearparams) — Remove all params
* [Yaf\_Request\_Abstract::getActionName](yaf-request-abstract.getactionname) — The getActionName purpose
* [Yaf\_Request\_Abstract::getBaseUri](yaf-request-abstract.getbaseuri) — The getBaseUri purpose
* [Yaf\_Request\_Abstract::getControllerName](yaf-request-abstract.getcontrollername) — The getControllerName purpose
* [Yaf\_Request\_Abstract::getEnv](yaf-request-abstract.getenv) — Retrieve ENV varialbe
* [Yaf\_Request\_Abstract::getException](yaf-request-abstract.getexception) — The getException purpose
* [Yaf\_Request\_Abstract::getLanguage](yaf-request-abstract.getlanguage) — Retrieve client's preferred language
* [Yaf\_Request\_Abstract::getMethod](yaf-request-abstract.getmethod) — Retrieve the request method
* [Yaf\_Request\_Abstract::getModuleName](yaf-request-abstract.getmodulename) — The getModuleName purpose
* [Yaf\_Request\_Abstract::getParam](yaf-request-abstract.getparam) — Retrieve calling parameter
* [Yaf\_Request\_Abstract::getParams](yaf-request-abstract.getparams) — Retrieve all calling parameters
* [Yaf\_Request\_Abstract::getRequestUri](yaf-request-abstract.getrequesturi) — The getRequestUri purpose
* [Yaf\_Request\_Abstract::getServer](yaf-request-abstract.getserver) — Retrieve SERVER variable
* [Yaf\_Request\_Abstract::isCli](yaf-request-abstract.iscli) — Determine if request is CLI request
* [Yaf\_Request\_Abstract::isDispatched](yaf-request-abstract.isdispatched) — Determin if the request is dispatched
* [Yaf\_Request\_Abstract::isGet](yaf-request-abstract.isget) — Determine if request is GET request
* [Yaf\_Request\_Abstract::isHead](yaf-request-abstract.ishead) — Determine if request is HEAD request
* [Yaf\_Request\_Abstract::isOptions](yaf-request-abstract.isoptions) — Determine if request is OPTIONS request
* [Yaf\_Request\_Abstract::isPost](yaf-request-abstract.ispost) — Determine if request is POST request
* [Yaf\_Request\_Abstract::isPut](yaf-request-abstract.isput) — Determine if request is PUT request
* [Yaf\_Request\_Abstract::isRouted](yaf-request-abstract.isrouted) — Determin if request has been routed
* [Yaf\_Request\_Abstract::isXmlHttpRequest](yaf-request-abstract.isxmlhttprequest) — Determine if request is AJAX request
* [Yaf\_Request\_Abstract::setActionName](yaf-request-abstract.setactionname) — Set action name
* [Yaf\_Request\_Abstract::setBaseUri](yaf-request-abstract.setbaseuri) — Set base URI
* [Yaf\_Request\_Abstract::setControllerName](yaf-request-abstract.setcontrollername) — Set controller name
* [Yaf\_Request\_Abstract::setDispatched](yaf-request-abstract.setdispatched) — The setDispatched purpose
* [Yaf\_Request\_Abstract::setModuleName](yaf-request-abstract.setmodulename) — Set module name
* [Yaf\_Request\_Abstract::setParam](yaf-request-abstract.setparam) — Set a calling parameter to a request
* [Yaf\_Request\_Abstract::setRequestUri](yaf-request-abstract.setrequesturi) — The setRequestUri purpose
* [Yaf\_Request\_Abstract::setRouted](yaf-request-abstract.setrouted) — The setRouted purpose
php IntlTimeZone::hasSameRules IntlTimeZone::hasSameRules
==========================
intltz\_has\_same\_rules
========================
(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)
IntlTimeZone::hasSameRules -- intltz\_has\_same\_rules — Check if this zone has the same rules and offset as another zone
### Description
Object-oriented style (method):
```
public IntlTimeZone::hasSameRules(IntlTimeZone $other): bool
```
Procedural style:
```
intltz_has_same_rules(IntlTimeZone $timezone, IntlTimeZone $other): bool
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`other`
### Return Values
php escapeshellcmd escapeshellcmd
==============
(PHP 4, PHP 5, PHP 7, PHP 8)
escapeshellcmd — Escape shell metacharacters
### Description
```
escapeshellcmd(string $command): string
```
**escapeshellcmd()** escapes any characters in a string that might be used to trick a shell command into executing arbitrary commands. This function should be used to make sure that any data coming from user input is escaped before this data is passed to the [exec()](function.exec) or [system()](function.system) functions, or to the [backtick operator](language.operators.execution).
Following characters are preceded by a backslash: `&#;`|*?~<>^()[]{}$\`, `\x0A` and `\xFF`. `'` and `"` are escaped only if they are not paired. On Windows, all these characters plus `%` and `!` are preceded by a caret (`^`).
### Parameters
`command`
The command that will be escaped.
### Return Values
The escaped string.
### Examples
**Example #1 **escapeshellcmd()** example**
```
<?php
// We allow arbitrary number of arguments intentionally here.
$command = './configure '.$_POST['configure_options'];
$escaped_command = escapeshellcmd($command);
system($escaped_command);
?>
```
**Warning** **escapeshellcmd()** should be used on the whole command string, and it still allows the attacker to pass arbitrary number of arguments. For escaping a single argument [escapeshellarg()](function.escapeshellarg) should be used instead.
**Warning** Spaces will not be escaped by **escapeshellcmd()** which can be problematic on Windows with paths like: `C:\Program Files\ProgramName\program.exe`. This can be mitigated using the following code snippet:
```
<?php
$cmd = preg_replace('`(?<!^) `', '^ ', escapeshellcmd($cmd));
```
### See Also
* [escapeshellarg()](function.escapeshellarg) - Escape a string to be used as a shell argument
* [exec()](function.exec) - Execute an external program
* [popen()](function.popen) - Opens process file pointer
* [system()](function.system) - Execute an external program and display the output
* [backtick operator](language.operators.execution)
| programming_docs |
php DOMNode::isDefaultNamespace DOMNode::isDefaultNamespace
===========================
(PHP 5, PHP 7, PHP 8)
DOMNode::isDefaultNamespace — Checks if the specified namespaceURI is the default namespace or not
### Description
```
public DOMNode::isDefaultNamespace(string $namespace): bool
```
Tells whether `namespace` is the default namespace.
### Parameters
`namespace`
The namespace URI to look for.
### Return Values
Return **`true`** if `namespace` is the default namespace, **`false`** otherwise.
php get_class_vars get\_class\_vars
================
(PHP 4, PHP 5, PHP 7, PHP 8)
get\_class\_vars — Get the default properties of the class
### Description
```
get_class_vars(string $class): array
```
Get the default properties of the given class.
### Parameters
`class`
The class name
### Return Values
Returns an associative array of declared properties visible from the current scope, with their default value. The resulting array elements are in the form of `varname => value`. In case of an error, it returns **`false`**.
### Examples
**Example #1 **get\_class\_vars()** example**
```
<?php
class myclass {
var $var1; // this has no default value...
var $var2 = "xyz";
var $var3 = 100;
private $var4;
// constructor
function __construct() {
// change some properties
$this->var1 = "foo";
$this->var2 = "bar";
return true;
}
}
$my_class = new myclass();
$class_vars = get_class_vars(get_class($my_class));
foreach ($class_vars as $name => $value) {
echo "$name : $value\n";
}
?>
```
The above example will output:
```
var1 :
var2 : xyz
var3 : 100
```
**Example #2 **get\_class\_vars()** and scoping behaviour**
```
<?php
function format($array)
{
return implode('|', array_keys($array)) . "\r\n";
}
class TestCase
{
public $a = 1;
protected $b = 2;
private $c = 3;
public static function expose()
{
echo format(get_class_vars(__CLASS__));
}
}
TestCase::expose();
echo format(get_class_vars('TestCase'));
?>
```
The above example will output:
```
// 5.0.0
a| * b| TestCase c
a| * b| TestCase c
// 5.0.1 - 5.0.2
a|b|c
a|b|c
// 5.0.3 +
a|b|c
a
```
### See Also
* [get\_class\_methods()](function.get-class-methods) - Gets the class methods' names
* [get\_object\_vars()](function.get-object-vars) - Gets the properties of the given object
php The DateTimeInterface interface
The DateTimeInterface interface
===============================
Introduction
------------
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
**DateTimeInterface** was created so that parameter, return, or property type declarations may accept either [DateTimeImmutable](class.datetimeimmutable) or [DateTime](class.datetime) as a value. It is not possible to implement this interface with userland classes.
Common constants that allow for formatting [DateTimeImmutable](class.datetimeimmutable) or [DateTime](class.datetime) objects through [DateTimeImmutable::format()](datetime.format) and [DateTime::format()](datetime.format) are also defined on this interface.
Interface synopsis
------------------
interface **DateTimeInterface** { /\* Constants \*/ public const string [ATOM](class.datetimeinterface#datetimeinterface.constants.atom) = "Y-m-d\\TH:i:sP";
public const string [COOKIE](class.datetimeinterface#datetimeinterface.constants.cookie) = "l, d-M-Y H:i:s T";
public const string [ISO8601](class.datetimeinterface#datetimeinterface.constants.iso8601) = "Y-m-d\\TH:i:sO";
public const string [ISO8601\_EXPANDED](class.datetimeinterface#datetimeinterface.constants.iso8601-expanded) = "X-m-d\\TH:i:sP";
public const string [RFC822](class.datetimeinterface#datetimeinterface.constants.rfc822) = "D, d M y H:i:s O";
public const string [RFC850](class.datetimeinterface#datetimeinterface.constants.rfc850) = "l, d-M-y H:i:s T";
public const string [RFC1036](class.datetimeinterface#datetimeinterface.constants.rfc1036) = "D, d M y H:i:s O";
public const string [RFC1123](class.datetimeinterface#datetimeinterface.constants.rfc1123) = "D, d M Y H:i:s O";
public const string [RFC7231](class.datetimeinterface#datetimeinterface.constants.rfc7231) = "D, d M Y H:i:s \\G\\M\\T";
public const string [RFC2822](class.datetimeinterface#datetimeinterface.constants.rfc2822) = "D, d M Y H:i:s O";
public const string [RFC3339](class.datetimeinterface#datetimeinterface.constants.rfc3339) = "Y-m-d\\TH:i:sP";
public const string [RFC3339\_EXTENDED](class.datetimeinterface#datetimeinterface.constants.rfc3339-extended) = "Y-m-d\\TH:i:s.vP";
public const string [RSS](class.datetimeinterface#datetimeinterface.constants.rss) = "D, d M Y H:i:s O";
public const string [W3C](class.datetimeinterface#datetimeinterface.constants.w3c) = "Y-m-d\\TH:i:sP"; /\* Methods \*/
```
public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval
```
```
public format(string $format): string
```
```
public getOffset(): int
```
```
public getTimestamp(): int
```
```
public getTimezone(): DateTimeZone|false
```
```
public __wakeup(): void
```
} Predefined Constants
--------------------
**`DateTimeInterface::ATOM`** **`DATE_ATOM`**
Atom (example: 2005-08-15T15:52:01+00:00) **`DateTimeInterface::COOKIE`** **`DATE_COOKIE`**
HTTP Cookies (example: Monday, 15-Aug-2005 15:52:01 UTC) **`DateTimeInterface::ISO8601`** **`DATE_ISO8601`**
ISO-8601 (example: 2005-08-15T15:52:01+0000)
> **Note**: This format is not compatible with ISO-8601, but is left this way for backward compatibility reasons. Use **`DateTimeInterface::ISO8601_EXPANDED`**, **`DateTimeInterface::ATOM`** for compatibility with ISO-8601 instead.
>
>
**`DateTimeInterface::ISO8601_EXPANDED`** **`DATE_ISO8601_EXPANDED`**
ISO-8601 Expanded (example: +10191-07-26T08:59:52+01:00)
> **Note**: This format allows for year ranges outside of ISO-8601's normal range of `0000`-`9999` by always including a sign character. It also addresses that that timezone part (`+01:00`) is compatible with ISO-8601.
>
>
**`DateTimeInterface::RFC822`** **`DATE_RFC822`**
RFC 822 (example: Mon, 15 Aug 05 15:52:01 +0000) **`DateTimeInterface::RFC850`** **`DATE_RFC850`**
RFC 850 (example: Monday, 15-Aug-05 15:52:01 UTC) **`DateTimeInterface::RFC1036`** **`DATE_RFC1036`**
RFC 1036 (example: Mon, 15 Aug 05 15:52:01 +0000) **`DateTimeInterface::RFC1123`** **`DATE_RFC1123`**
RFC 1123 (example: Mon, 15 Aug 2005 15:52:01 +0000) **`DateTimeInterface::RFC7231`** **`DATE_RFC7231`**
RFC 7231 (since PHP 7.0.19 and 7.1.5) (example: Sat, 30 Apr 2016 17:52:13 GMT) **`DateTimeInterface::RFC2822`** **`DATE_RFC2822`**
RFC 2822 (example: Mon, 15 Aug 2005 15:52:01 +0000) **`DateTimeInterface::RFC3339`** **`DATE_RFC3339`**
Same as **`DATE_ATOM`** **`DateTimeInterface::RFC3339_EXTENDED`** **`DATE_RFC3339_EXTENDED`**
RFC 3339 EXTENDED format (example: 2005-08-15T15:52:01.000+00:00) **`DateTimeInterface::RSS`** **`DATE_RSS`**
RSS (example: Mon, 15 Aug 2005 15:52:01 +0000) **`DateTimeInterface::W3C`** **`DATE_W3C`**
World Wide Web Consortium (example: 2005-08-15T15:52:01+00:00) Changelog
---------
| Version | Description |
| --- | --- |
| 8.2.0 | The constant **`DateTimeInterface::ISO8601_EXPANDED`** was added. |
| 7.2.0 | The class constants of [DateTime](class.datetime) are now defined on **DateTimeInterface**. |
Table of Contents
-----------------
* [DateTimeInterface::diff](datetime.diff) — Returns the difference between two DateTime objects
* [DateTimeInterface::format](datetime.format) — Returns date formatted according to given format
* [DateTimeInterface::getOffset](datetime.getoffset) — Returns the timezone offset
* [DateTimeInterface::getTimestamp](datetime.gettimestamp) — Gets the Unix timestamp
* [DateTimeInterface::getTimezone](datetime.gettimezone) — Return time zone relative to given DateTime
* [DateTime::\_\_wakeup](datetime.wakeup) — The \_\_wakeup handler
php Imagick::setCompression Imagick::setCompression
=======================
(PECL imagick 2, PECL imagick 3)
Imagick::setCompression — Sets the object's default compression type
### Description
```
public Imagick::setCompression(int $compression): bool
```
Sets the object's default compression type
### Parameters
`compression`
The compression type. See the [Imagick::COMPRESSION\_\*](https://www.php.net/manual/en/imagick.constants.php) constants.
### Return Values
Returns **`true`** on success.
php Imagick::setColorspace Imagick::setColorspace
======================
(PECL imagick 3)
Imagick::setColorspace — Set colorspace
### Description
```
public Imagick::setColorspace(int $COLORSPACE): bool
```
Sets the global colorspace value for the object. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.
### Parameters
`COLORSPACE`
One of the [COLORSPACE constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.colorspace)
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
php password_get_info password\_get\_info
===================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
password\_get\_info — Returns information about the given hash
### Description
```
password_get_info(string $hash): array
```
When passed in a valid hash created by an algorithm supported by [password\_hash()](function.password-hash), this function will return an array of information about that hash.
### Parameters
`hash`
A hash created by [password\_hash()](function.password-hash).
### Return Values
Returns an associative array with three elements:
* `algo`, which will match a [password algorithm constant](https://www.php.net/manual/en/password.constants.php)
* `algoName`, which has the human readable name of the algorithm
* `options`, which includes the options provided when calling [password\_hash()](function.password-hash)
php Imagick::getReleaseDate Imagick::getReleaseDate
=======================
(PECL imagick 2, PECL imagick 3)
Imagick::getReleaseDate — Returns the ImageMagick release date
### Description
```
public static Imagick::getReleaseDate(): string
```
Returns the ImageMagick release date as a string.
### Parameters
This function has no parameters.
### Return Values
Returns the ImageMagick release date as a string.
### Errors/Exceptions
Throws ImagickException on error.
php imagexbm imagexbm
========
(PHP 5, PHP 7, PHP 8)
imagexbm — Output an XBM image to browser or file
### Description
```
imagexbm(GdImage $image, ?string $filename, ?int $foreground_color = null): bool
```
Outputs or save an XBM version of the given `image`.
> **Note**: **imagexbm()** doesn't apply any padding, so the image width has to be a multiple of 8. This restriction does no longer apply as of PHP 7.0.9.
>
>
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`filename`
The path to save the file to, given as string. If **`null`**, the raw image stream will be output directly.
The `filename` (without the .xbm extension) is also used for the C identifiers of the XBM, whereby non alphanumeric characters of the current locale are substituted by underscores. If `filename` is set to **`null`**, `image` is used to build the C identifiers.
`foreground_color`
You can set the foreground color with this parameter by setting an identifier obtained from [imagecolorallocate()](function.imagecolorallocate). The default foreground color is black. All other colors are treated as background.
### Return Values
Returns **`true`** on success or **`false`** on failure.
**Caution**However, if libgd fails to output the image, this function returns **`true`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
| 8.0.0 | `foreground_color` is now nullable. |
| 8.0.0 | The fourth parameter, which was unused, has been removed. |
### Examples
**Example #1 Saving an XBM file**
```
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Save the image
imagexbm($im, 'simpletext.xbm');
// Free up memory
imagedestroy($im);
?>
```
**Example #2 Saving an XBM file with a different foreground color**
```
<?php
// Create a blank image and add some text
$im = imagecreatetruecolor(120, 20);
$text_color = imagecolorallocate($im, 233, 14, 91);
imagestring($im, 1, 5, 5, 'A Simple Text String', $text_color);
// Set a replacement foreground color
$foreground_color = imagecolorallocate($im, 255, 0, 0);
// Save the image
imagexbm($im, NULL, $foreground_color);
// Free up memory
imagedestroy($im);
?>
```
### Notes
php SolrDisMaxQuery::removeBoostQuery SolrDisMaxQuery::removeBoostQuery
=================================
(No version information available, might only be in Git)
SolrDisMaxQuery::removeBoostQuery — Removes a boost query partial by field name (bq)
### Description
```
public SolrDisMaxQuery::removeBoostQuery(string $field): SolrDisMaxQuery
```
Removes a boost query partial from the existing query, only if [SolrDisMaxQuery::addBoostQuery()](solrdismaxquery.addboostquery) was used.
### Parameters
`field`
Field Name
### Return Values
[SolrDisMaxQuery](class.solrdismaxquery)
### Examples
**Example #1 **SolrDisMaxQuery::removeBoostQuery()** example**
```
<?php
$dismaxQuery = new SolrDisMaxQuery("lucene");
$dismaxQuery
->addBoostQuery('cat', 'electronics', 5.1)
->addBoostQuery('cat', 'hard drive')
;
echo $dismaxQuery.PHP_EOL;
// now remove a query part with field 'cat'
$dismaxQuery
->removeBoostQuery('cat');
echo $dismaxQuery . PHP_EOL;
?>
```
The above example will output something similar to:
```
q=lucene&defType=edismax&bq=cat:electronics^5.1 cat:hard drive
q=lucene&defType=edismax&bq=cat:hard drive
```
### See Also
* [SolrDisMaxQuery::addBoostQuery()](solrdismaxquery.addboostquery) - Adds a boost query field with value and optional boost (bq parameter)
* [SolrDisMaxQuery::setBoostQuery()](solrdismaxquery.setboostquery) - Directly Sets Boost Query Parameter (bq)
php ImagickDraw::getTextAntialias ImagickDraw::getTextAntialias
=============================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::getTextAntialias — Returns the current text antialias setting
### Description
```
public ImagickDraw::getTextAntialias(): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Returns the current text antialias setting, which determines whether text is antialiased. Text is antialiased by default.
### Return Values
Returns **`true`** if text is antialiased and **`false`** if not.
php Error
Error
=====
Introduction
------------
(PHP 7, PHP 8)
**Error** is the base class for all internal PHP errors.
Class synopsis
--------------
class **Error** implements [Throwable](class.throwable) { /\* Properties \*/ protected string [$message](class.error#error.props.message) = "";
private string [$string](class.error#error.props.string) = "";
protected int [$code](class.error#error.props.code);
protected string [$file](class.error#error.props.file) = "";
protected int [$line](class.error#error.props.line);
private array [$trace](class.error#error.props.trace) = [];
private ?[Throwable](class.throwable) [$previous](class.error#error.props.previous) = null; /\* Methods \*/ public [\_\_construct](error.construct)(string `$message` = "", int `$code` = 0, ?[Throwable](class.throwable) `$previous` = **`null`**)
```
final public getMessage(): string
```
```
final public getPrevious(): ?Throwable
```
```
final public getCode(): int
```
```
final public getFile(): string
```
```
final public getLine(): int
```
```
final public getTrace(): array
```
```
final public getTraceAsString(): string
```
```
public __toString(): string
```
```
private __clone(): void
```
} Properties
----------
message The error message
code The error code
file The filename where the error happened
line The line where the error happened
previous The previously thrown exception
string The string representation of the stack trace
trace The stack trace as an array
Table of Contents
-----------------
* [Error::\_\_construct](error.construct) — Construct the error object
* [Error::getMessage](error.getmessage) — Gets the error message
* [Error::getPrevious](error.getprevious) — Returns previous Throwable
* [Error::getCode](error.getcode) — Gets the error code
* [Error::getFile](error.getfile) — Gets the file in which the error occurred
* [Error::getLine](error.getline) — Gets the line in which the error occurred
* [Error::getTrace](error.gettrace) — Gets the stack trace
* [Error::getTraceAsString](error.gettraceasstring) — Gets the stack trace as a string
* [Error::\_\_toString](error.tostring) — String representation of the error
* [Error::\_\_clone](error.clone) — Clone the error
php posix_times posix\_times
============
(PHP 4, PHP 5, PHP 7, PHP 8)
posix\_times — Get process times
### Description
```
posix_times(): array|false
```
Gets information about the current CPU usage.
### Parameters
This function has no parameters.
### Return Values
Returns a hash of strings with information about the current process CPU usage. The indices of the hash are:
* ticks - the number of clock ticks that have elapsed since reboot.
* utime - user time used by the current process.
* stime - system time used by the current process.
* cutime - user time used by current process and children.
* cstime - system time used by current process and children.
The function returns **`false`** on failure. ### Examples
**Example #1 Example use of **posix\_times()****
```
<?php
$times = posix_times();
print_r($times);
?>
```
The above example will output something similar to:
```
Array
(
[ticks] => 25814410
[utime] => 1
[stime] => 1
[cutime] => 0
[cstime] => 0
)
```
### Notes
**Warning** This function isn't reliable to use, it may return negative values for high times.
php Gmagick::queryfontmetrics Gmagick::queryfontmetrics
=========================
(PECL gmagick >= Unknown)
Gmagick::queryfontmetrics — Returns an array representing the font metrics
### Description
```
public Gmagick::queryfontmetrics(GmagickDraw $draw, string $text): array
```
MagickQueryFontMetrics() returns an array representing the font metrics.
### Parameters
This function has no parameters.
### Return Values
The Gmagick object on success
### Errors/Exceptions
Throws an **GmagickException** on error.
php sqlsrv_free_stmt sqlsrv\_free\_stmt
==================
(No version information available, might only be in Git)
sqlsrv\_free\_stmt — Frees all resources for the specified statement
### Description
```
sqlsrv_free_stmt(resource $stmt): bool
```
Frees all resources for the specified statement. The statement cannot be used after **sqlsrv\_free\_stmt()** has been called on it. If **sqlsrv\_free\_stmt()** is called on an in-progress statement that alters server state, statement execution is terminated and the statement is rolled back.
### Parameters
`stmt`
The statement for which resources are freed. Note that **`null`** is a valid parameter value. This allows the function to be called multiple times in a script.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **sqlsrv\_free\_stmt()** example**
```
<?php
$serverName = "serverName\sqlexpress";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$stmt = sqlsrv_query( $conn, "SELECT * FROM Table_1");
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
/*-------------------------------
Process query results here.
-------------------------------*/
/* Free the statement resources. */
sqlsrv_free_stmt( $stmt);
?>
```
### Notes
The main difference between **sqlsrv\_free\_stmt()** and [sqlsrv\_cancel()](function.sqlsrv-cancel) is that a statement resource cancelled with [sqlsrv\_cancel()](function.sqlsrv-cancel) can be re-executed if it was created with [sqlsrv\_prepare()](function.sqlsrv-prepare). A statement resource cancelled with **sqlsrv\_free\_statement()** cannot be re-executed.
### See Also
* [sqlsrv\_cancel()](function.sqlsrv-cancel) - Cancels a statement
| programming_docs |
php socket_getsockname socket\_getsockname
===================
(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket\_getsockname — Queries the local side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
### Description
```
socket_getsockname(Socket $socket, string &$address, int &$port = null): bool
```
> **Note**: **socket\_getsockname()** should not be used with **`AF_UNIX`** sockets created with [socket\_connect()](function.socket-connect). Only sockets created with [socket\_accept()](function.socket-accept) or a primary server socket following a call to [socket\_bind()](function.socket-bind) will return meaningful values.
>
>
### Parameters
`socket`
A [Socket](class.socket) instance created with [socket\_create()](function.socket-create) or [socket\_accept()](function.socket-accept).
`address`
If the given socket is of type **`AF_INET`** or **`AF_INET6`**, **socket\_getsockname()** will return the local *IP address* in appropriate notation (e.g. `127.0.0.1` or `fe80::1`) in the `address` parameter and, if the optional `port` parameter is present, also the associated port.
If the given socket is of type **`AF_UNIX`**, **socket\_getsockname()** will return the Unix filesystem path (e.g. `/var/run/daemon.sock`) in the `address` parameter.
`port`
If provided, this will hold the associated port.
### Return Values
Returns **`true`** on success or **`false`** on failure. **socket\_getsockname()** may also return **`false`** if the socket type is not any of **`AF_INET`**, **`AF_INET6`**, or **`AF_UNIX`**, in which case the last socket error code is *not* updated.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. |
### See Also
* [socket\_getpeername()](function.socket-getpeername) - Queries the remote side of the given socket which may either result in host/port or in a Unix filesystem path, dependent on its type
* [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket
* [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error
php filter_var_array filter\_var\_array
==================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
filter\_var\_array — Gets multiple variables and optionally filters them
### Description
```
filter_var_array(array $array, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null
```
This function is useful for retrieving many values without repetitively calling [filter\_var()](function.filter-var).
### Parameters
`array`
An array with string keys containing the data to filter.
`options`
An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a [filter type](https://www.php.net/manual/en/filter.filters.php), or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are `filter` which specifies the [filter type](https://www.php.net/manual/en/filter.filters.php), `flags` which specifies any flags that apply to the filter, and `options` which specifies any options that apply to the filter. See the example below for a better understanding.
This parameter can be also an integer holding a [filter constant](https://www.php.net/manual/en/filter.constants.php). Then all values in the input array are filtered by this filter.
`add_empty`
Add missing keys as **`null`** to the return value.
### Return Values
An array containing the values of the requested variables on success, or **`false`** on failure. An array value will be **`false`** if the filter fails, or **`null`** if the variable is not set.
### Examples
**Example #1 A **filter\_var\_array()** example**
```
<?php
$data = array(
'product_id' => 'libgd<script>',
'component' => '10',
'versions' => '2.0.33',
'testscalar' => array('2', '23', '10', '12'),
'testarray' => '2',
);
$args = array(
'product_id' => FILTER_SANITIZE_ENCODED,
'component' => array('filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
'options' => array('min_range' => 1, 'max_range' => 10)
),
'versions' => FILTER_SANITIZE_ENCODED,
'doesnotexist' => FILTER_VALIDATE_INT,
'testscalar' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_REQUIRE_SCALAR,
),
'testarray' => array(
'filter' => FILTER_VALIDATE_INT,
'flags' => FILTER_FORCE_ARRAY,
)
);
$myinputs = filter_var_array($data, $args);
var_dump($myinputs);
echo "\n";
?>
```
The above example will output:
```
array(6) {
["product_id"]=>
string(17) "libgd%3Cscript%3E"
["component"]=>
array(1) {
[0]=>
int(10)
}
["versions"]=>
string(6) "2.0.33"
["doesnotexist"]=>
NULL
["testscalar"]=>
bool(false)
["testarray"]=>
array(1) {
[0]=>
int(2)
}
}
```
### See Also
* [filter\_input\_array()](function.filter-input-array) - Gets external variables and optionally filters them
* [filter\_var()](function.filter-var) - Filters a variable with a specified filter
* [filter\_input()](function.filter-input) - Gets a specific external variable by name and optionally filters it
* [Types of filters](https://www.php.net/manual/en/filter.filters.php)
php DirectoryIterator::getMTime DirectoryIterator::getMTime
===========================
(PHP 5, PHP 7, PHP 8)
DirectoryIterator::getMTime — Get last modification time of current DirectoryIterator item
### Description
```
public DirectoryIterator::getMTime(): int
```
Get the last modification time of the current [DirectoryIterator](class.directoryiterator) item, as a Unix timestamp.
### Parameters
This function has no parameters.
### Return Values
The last modification time of the file, as a Unix timestamp.
### Examples
**Example #1 A **DirectoryIterator::getMTime()** example**
Displays a list of the files in the directory of the script and their last modified times.
```
<?php
$iterator = new DirectoryIterator(dirname(__FILE__));
foreach ($iterator as $fileinfo) {
if ($fileinfo->isFile()) {
echo $fileinfo->getFilename() . " " . $fileinfo->getMTime() . "\n";
}
}
?>
```
The above example will output something similar to:
```
apple.jpg 1240047118
banana.jpg 1240065176
index.php 1240047208
pear.jpg 12240047979
```
### See Also
* [DirectoryIterator::getATime()](directoryiterator.getatime) - Get last access time of the current DirectoryIterator item
* [DirectoryIterator::getCTime()](directoryiterator.getctime) - Get inode change time of the current DirectoryIterator item
* [filemtime()](function.filemtime) - Gets file modification time
php geoip_database_info geoip\_database\_info
=====================
(PECL geoip >= 0.2.0)
geoip\_database\_info — Get GeoIP Database information
### Description
```
geoip_database_info(int $database = GEOIP_COUNTRY_EDITION): string
```
The **geoip\_database\_info()** function returns the corresponding GeoIP Database version as it is defined inside the binary file.
If this function is called without arguments, it returns the version of the GeoIP Free Country Edition.
### Parameters
`database`
The database type as an integer. You can use the [various constants](https://www.php.net/manual/en/geoip.constants.php) defined with this extension (ie: GEOIP\_\*\_EDITION).
### Return Values
Returns the corresponding database version, or **`null`** on error.
### Examples
**Example #1 A **geoip\_database\_info()** example**
This will output information regarding the database.
```
<?php
print geoip_database_info(GEOIP_COUNTRY_EDITION);
?>
```
The above example will output:
```
GEO-106FREE 20060801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved
```
php readline_list_history readline\_list\_history
=======================
(PHP 4, PHP 5, PHP 7, PHP 8)
readline\_list\_history — Lists the history
### Description
```
readline_list_history(): array
```
Gets the entire command line history.
### Parameters
This function has no parameters.
### Return Values
Returns an array of the entire command line history. The elements are indexed by integers starting at zero.
php The RegexIterator class
The RegexIterator class
=======================
Introduction
------------
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
This iterator can be used to filter another iterator based on a regular expression.
Class synopsis
--------------
class **RegexIterator** extends [FilterIterator](class.filteriterator) { /\* Constants \*/ public const int [USE\_KEY](class.regexiterator#regexiterator.constants.use-key);
public const int [INVERT\_MATCH](class.regexiterator#regexiterator.constants.invert-match);
public const int [MATCH](class.regexiterator#regexiterator.constants.match);
public const int [GET\_MATCH](class.regexiterator#regexiterator.constants.get-match);
public const int [ALL\_MATCHES](class.regexiterator#regexiterator.constants.all-matches);
public const int [SPLIT](class.regexiterator#regexiterator.constants.split);
public const int [REPLACE](class.regexiterator#regexiterator.constants.replace); /\* Properties \*/
public ?string [$replacement](class.regexiterator#regexiterator.props.replacement) = null; /\* Methods \*/ public [\_\_construct](regexiterator.construct)(
[Iterator](class.iterator) `$iterator`,
string `$pattern`,
int `$mode` = RegexIterator::MATCH,
int `$flags` = 0,
int `$pregFlags` = 0
)
```
public accept(): bool
```
```
public getFlags(): int
```
```
public getMode(): int
```
```
public getPregFlags(): int
```
```
public getRegex(): string
```
```
public setFlags(int $flags): void
```
```
public setMode(int $mode): void
```
```
public setPregFlags(int $pregFlags): void
```
/\* Inherited methods \*/
```
public FilterIterator::accept(): bool
```
```
public FilterIterator::current(): mixed
```
```
public FilterIterator::getInnerIterator(): Iterator
```
```
public FilterIterator::key(): mixed
```
```
public FilterIterator::next(): void
```
```
public FilterIterator::rewind(): void
```
```
public FilterIterator::valid(): bool
```
```
public IteratorIterator::current(): mixed
```
```
public IteratorIterator::getInnerIterator(): ?Iterator
```
```
public IteratorIterator::key(): mixed
```
```
public IteratorIterator::next(): void
```
```
public IteratorIterator::rewind(): void
```
```
public IteratorIterator::valid(): bool
```
} Predefined Constants
--------------------
RegexIterator operation modes
-----------------------------
**`RegexIterator::ALL_MATCHES`** Return all matches for the current entry (see [preg\_match\_all()](function.preg-match-all)).
**`RegexIterator::GET_MATCH`** Return the first match for the current entry (see [preg\_match()](function.preg-match)).
**`RegexIterator::MATCH`** Only execute match (filter) for the current entry (see [preg\_match()](function.preg-match)).
**`RegexIterator::REPLACE`** Replace the current entry (see [preg\_replace()](function.preg-replace); Not fully implemented yet)
**`RegexIterator::SPLIT`** Returns the split values for the current entry (see [preg\_split()](function.preg-split)).
RegexIterator Flags
-------------------
**`RegexIterator::USE_KEY`** Special flag: Match the entry key instead of the entry value.
**`RegexIterator::INVERT_MATCH`** Inverts the return value of [RegexIterator::accept()](regexiterator.accept).
Properties
----------
replacement Table of Contents
-----------------
* [RegexIterator::accept](regexiterator.accept) — Get accept status
* [RegexIterator::\_\_construct](regexiterator.construct) — Create a new RegexIterator
* [RegexIterator::getFlags](regexiterator.getflags) — Get flags
* [RegexIterator::getMode](regexiterator.getmode) — Returns operation mode
* [RegexIterator::getPregFlags](regexiterator.getpregflags) — Returns the regular expression flags
* [RegexIterator::getRegex](regexiterator.getregex) — Returns current regular expression
* [RegexIterator::setFlags](regexiterator.setflags) — Sets the flags
* [RegexIterator::setMode](regexiterator.setmode) — Sets the operation mode
* [RegexIterator::setPregFlags](regexiterator.setpregflags) — Sets the regular expression flags
php The SimpleXMLIterator class
The SimpleXMLIterator class
===========================
Introduction
------------
(PHP 5 >= 5.1.3, PHP 7, PHP 8)
The SimpleXMLIterator provides recursive iteration over all nodes of a [SimpleXMLElement](class.simplexmlelement) object.
Class synopsis
--------------
class **SimpleXMLIterator** extends [SimpleXMLElement](class.simplexmlelement) { /\* Methods \*/
```
public current(): mixed
```
```
public getChildren(): SimpleXMLIterator
```
```
public hasChildren(): bool
```
```
public key(): mixed
```
```
public next(): void
```
```
public rewind(): void
```
```
public valid(): bool
```
/\* Inherited methods \*/
```
public SimpleXMLElement::addAttribute(string $qualifiedName, string $value, ?string $namespace = null): void
```
```
public SimpleXMLElement::addChild(string $qualifiedName, ?string $value = null, ?string $namespace = null): ?SimpleXMLElement
```
```
public SimpleXMLElement::asXML(?string $filename = null): string|bool
```
```
public SimpleXMLElement::attributes(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
```
```
public SimpleXMLElement::children(?string $namespaceOrPrefix = null, bool $isPrefix = false): ?SimpleXMLElement
```
```
public SimpleXMLElement::count(): int
```
```
public SimpleXMLElement::getDocNamespaces(bool $recursive = false, bool $fromRoot = true): array|false
```
```
public SimpleXMLElement::getName(): string
```
```
public SimpleXMLElement::getNamespaces(bool $recursive = false): array
```
```
public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool
```
```
public SimpleXMLElement::__toString(): string
```
```
public SimpleXMLElement::xpath(string $expression): array|null|false
```
} Changelog
---------
| Version | Description |
| --- | --- |
| 8.0.0 | **SimpleXMLIterator** implements [Stringable](class.stringable) now. |
Table of Contents
-----------------
* [SimpleXMLIterator::current](simplexmliterator.current) — Returns the current element
* [SimpleXMLIterator::getChildren](simplexmliterator.getchildren) — Returns the sub-elements of the current element
* [SimpleXMLIterator::hasChildren](simplexmliterator.haschildren) — Checks whether the current element has sub elements
* [SimpleXMLIterator::key](simplexmliterator.key) — Return current key
* [SimpleXMLIterator::next](simplexmliterator.next) — Move to next element
* [SimpleXMLIterator::rewind](simplexmliterator.rewind) — Rewind to the first element
* [SimpleXMLIterator::valid](simplexmliterator.valid) — Check whether the current element is valid
php Parle\RLexer::reset Parle\RLexer::reset
===================
(PECL parle >= 0.7.1)
Parle\RLexer::reset — Reset lexer
### Description
```
public Parle\RLexer::reset(int $pos): void
```
Reset lexing optionally supplying the desired offset.
### Parameters
`pos`
Reset position.
### Return Values
No value is returned.
php ReflectionFunctionAbstract::getDocComment ReflectionFunctionAbstract::getDocComment
=========================================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
ReflectionFunctionAbstract::getDocComment — Gets doc comment
### Description
```
public ReflectionFunctionAbstract::getDocComment(): string|false
```
Get a Doc comment from a function.
### Parameters
This function has no parameters.
### Return Values
The doc comment if it exists, otherwise **`false`**
### See Also
* [ReflectionFunctionAbstract::getStartLine()](reflectionfunctionabstract.getstartline) - Gets starting line number
php xmlrpc_get_type xmlrpc\_get\_type
=================
(PHP 4 >= 4.1.0, PHP 5, PHP 7)
xmlrpc\_get\_type — Gets xmlrpc type for a PHP value
### Description
```
xmlrpc_get_type(mixed $value): string
```
**Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk.
This function is especially useful for base64 and datetime strings.
### Parameters
`value`
PHP value
### Return Values
Returns the XML-RPC type.
### Examples
**Example #1 XML-RPC type example**
```
<?php
echo xmlrpc_get_type(null) . "\n"; // base64
echo xmlrpc_get_type(false) . "\n"; // boolean
echo xmlrpc_get_type(1) . "\n"; // int
echo xmlrpc_get_type(1.0) . "\n"; // double
echo xmlrpc_get_type("") . "\n"; // string
echo xmlrpc_get_type(array()) . "\n"; // array
echo xmlrpc_get_type(new stdClass) . "\n"; // array
echo xmlrpc_get_type(STDIN) . "\n"; // int
?>
```
### See Also
* [xmlrpc\_set\_type()](function.xmlrpc-set-type) - Sets xmlrpc type, base64 or datetime, for a PHP string value
php sodium_crypto_pwhash_str sodium\_crypto\_pwhash\_str
===========================
(PHP 7 >= 7.2.0, PHP 8)
sodium\_crypto\_pwhash\_str — Get an ASCII-encoded hash
### Description
```
sodium_crypto_pwhash_str(string $password, int $opslimit, int $memlimit): string
```
Uses a CPU- and memory-hard hash algorithm along with a randomly-generated salt, and memory and CPU limits to generate an ASCII-encoded hash suitable for password storage.
### Parameters
`password`
string; The password to generate a hash for.
`opslimit`
Represents a maximum amount of computations to perform. Raising this number will make the function require more CPU cycles to compute a key. There are constants available to set the operations limit to appropriate values depending on intended use, in order of strength: **`SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE`**, **`SODIUM_CRYPTO_PWHASH_OPSLIMIT_MODERATE`** and **`SODIUM_CRYPTO_PWHASH_OPSLIMIT_SENSITIVE`**.
`memlimit`
The maximum amount of RAM that the function will use, in bytes. There are constants to help you choose an appropriate value, in order of size: **`SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE`**, **`SODIUM_CRYPTO_PWHASH_MEMLIMIT_MODERATE`**, and **`SODIUM_CRYPTO_PWHASH_MEMLIMIT_SENSITIVE`**. Typically these should be paired with the matching opslimit values.
### Return Values
Returns the hashed password.
In order to produce the same password hash from the same password, the same values for `opslimit` and `memlimit` must be used. These are embedded within the generated hash, so everything that's needed to verify the hash is included. This allows the [sodium\_crypto\_pwhash\_str\_verify()](function.sodium-crypto-pwhash-str-verify) function to verify the hash without needing separate storage for the other parameters.
### Examples
**Example #1 **sodium\_crypto\_pwhash\_str()** example**
```
<?php
$password = 'password';
echo sodium_crypto_pwhash_str(
$password,
SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE,
SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE
);
```
The above example will output something similar to:
```
$argon2id$v=19$m=65536,t=2,p=1$oWIfdaXwWwhVmovOBc2NAQ$EbsZ+JnZyyavkafS0hoc4HdaOB0ILWZESAZ7kVGa+Iw
```
### Notes
>
> **Note**:
>
>
> Hashes are calculated using the Argon2ID algorithm, providing resistance to both GPU and side-channel attacks. In contrast to the [password\_hash()](function.password-hash) function, there is no salt parameter (a salt is generated automatically), and the `opslimit` and `memlimit` parameters are not optional.
>
>
### See Also
* [sodium\_crypto\_pwhash\_str\_verify()](function.sodium-crypto-pwhash-str-verify) - Verifies that a password matches a hash
* [sodium\_crypto\_pwhash()](function.sodium-crypto-pwhash) - Derive a key from a password, using Argon2
* [password\_hash()](function.password-hash) - Creates a password hash
* [password\_verify()](function.password-verify) - Verifies that a password matches a hash
* [» Libsodium Argon2 docs](https://download.libsodium.org/doc/password_hashing/the_argon2i_function.html)
| programming_docs |
php session_regenerate_id session\_regenerate\_id
=======================
(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)
session\_regenerate\_id — Update the current session id with a newly generated one
### Description
```
session_regenerate_id(bool $delete_old_session = false): bool
```
**session\_regenerate\_id()** will replace the current session id with a new one, and keep the current session information.
When [session.use\_trans\_sid](https://www.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid) is enabled, output must be started after **session\_regenerate\_id()** call. Otherwise, old session ID is used.
**Warning** Currently, session\_regenerate\_id does not handle an unstable network well, e.g. Mobile and WiFi network. Therefore, you may experience a lost session by calling session\_regenerate\_id.
You should not destroy old session data immediately, but should use destroy time-stamp and control access to old session ID. Otherwise, concurrent access to page may result in inconsistent state, or you may have lost session, or it may cause client(browser) side race condition and may create many session ID needlessly. Immediate session data deletion disables session hijack attack detection and prevention also.
### Parameters
`delete_old_session`
Whether to delete the old associated session file or not. You should not delete old session if you need to avoid races caused by deletion or detect/avoid session hijack attacks.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 A **session\_regenerate\_id()** example**
```
<?php
// NOTE: This code is not fully working code, but an example!
session_start();
// Check destroyed time-stamp
if (isset($_SESSION['destroyed'])
&& $_SESSION['destroyed'] < time() - 300) {
// Should not happen usually. This could be attack or due to unstable network.
// Remove all authentication status of this users session.
remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
throw(new DestroyedSessionAccessException);
}
$old_sessionid = session_id();
// Set destroyed timestamp
$_SESSION['destroyed'] = time(); // session_regenerate_id() saves old session data
// Simply calling session_regenerate_id() may result in lost session, etc.
// See next example.
session_regenerate_id();
// New session does not need destroyed timestamp
unset($_SESSION['destroyed']);
$new_sessionid = session_id();
echo "Old Session: $old_sessionid<br />";
echo "New Session: $new_sessionid<br />";
print_r($_SESSION);
?>
```
Current session module does not handle unstable network well. You should manage session ID to avoid lost session by session\_regenerate\_id.
**Example #2 Avoiding lost session by **session\_regenerate\_id()****
```
<?php
// NOTE: This code is not fully working code, but an example!
// my_session_start() and my_session_regenerate_id() avoid lost sessions by
// unstable network. In addition, this code may prevent exploiting stolen
// session by attackers.
function my_session_start() {
session_start();
if (isset($_SESSION['destroyed'])) {
if ($_SESSION['destroyed'] < time()-300) {
// Should not happen usually. This could be attack or due to unstable network.
// Remove all authentication status of this users session.
remove_all_authentication_flag_from_active_sessions($_SESSION['userid']);
throw(new DestroyedSessionAccessException);
}
if (isset($_SESSION['new_session_id'])) {
// Not fully expired yet. Could be lost cookie by unstable network.
// Try again to set proper session ID cookie.
// NOTE: Do not try to set session ID again if you would like to remove
// authentication flag.
session_commit();
session_id($_SESSION['new_session_id']);
// New session ID should exist
session_start();
return;
}
}
}
function my_session_regenerate_id() {
// New session ID is required to set proper session ID
// when session ID is not set due to unstable network.
$new_session_id = session_create_id();
$_SESSION['new_session_id'] = $new_session_id;
// Set destroy timestamp
$_SESSION['destroyed'] = time();
// Write and close current session;
session_commit();
// Start session with new session ID
session_id($new_session_id);
ini_set('session.use_strict_mode', 0);
session_start();
ini_set('session.use_strict_mode', 1);
// New session does not need them
unset($_SESSION['destroyed']);
unset($_SESSION['new_session_id']);
}
?>
```
### See Also
* [session\_id()](function.session-id) - Get and/or set the current session id
* [session\_create\_id()](function.session-create-id) - Create new session id
* [session\_start()](function.session-start) - Start new or resume existing session
* [session\_destroy()](function.session-destroy) - Destroys all data registered to a session
* [session\_reset()](function.session-reset) - Re-initialize session array with original values
* [session\_name()](function.session-name) - Get and/or set the current session name
php radius_create_request radius\_create\_request
=======================
(PECL radius >= 1.1.0)
radius\_create\_request — Create accounting or authentication request
### Description
```
radius_create_request(resource $radius_handle, int $type): bool
```
A Radius request consists of a code specifying the kind of request, and zero or more attributes which provide additional information. To begin constructing a new request, call **radius\_create\_request()**.
> **Note**: Attention: You must call this function, before you can put any attribute!
>
>
### Parameters
`radius_handle`
`type`
Type is **`RADIUS_ACCESS_REQUEST`** or **`RADIUS_ACCOUNTING_REQUEST`**.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **radius\_create\_request()** example**
```
<?php
if (!radius_create_request($res, RADIUS_ACCESS_REQUEST)) {
echo 'RadiusError:' . radius_strerror($res). "\n<br />";
exit;
}
?>
```
### See Also
* [radius\_send\_request()](function.radius-send-request) - Sends the request and waits for a reply
php Imagick::uniqueImageColors Imagick::uniqueImageColors
==========================
(PECL imagick 2,PECL imagick 3)
Imagick::uniqueImageColors — Discards all but one of any pixel color
### Description
```
public Imagick::uniqueImageColors(): bool
```
Discards all but one of any pixel color. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success.
### Examples
**Example #1 **Imagick::uniqueImageColors()****
```
<?php
function uniqueImageColors($imagePath) {
$imagick = new \Imagick(realpath($imagePath));
//Reduce the image to 256 colours nicely.
$imagick->quantizeImage(256, \Imagick::COLORSPACE_YIQ, 0, false, false);
$imagick->uniqueImageColors();
$imagick->scaleimage($imagick->getImageWidth(), $imagick->getImageHeight() * 20);
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>
```
php The Reflector interface
The Reflector interface
=======================
Introduction
------------
(PHP 5, PHP 7, PHP 8)
**Reflector** is an interface implemented by all exportable Reflection classes.
Interface synopsis
------------------
interface **Reflector** extends [Stringable](class.stringable) { /\* Methods \*/
```
public static export(): string
```
```
public __toString(): string
```
/\* Inherited methods \*/
```
public Stringable::__toString(): string
```
} Changelog
---------
| Version | Description |
| --- | --- |
| 8.0.0 | **Reflector** implements [Stringable](class.stringable) now. |
Table of Contents
-----------------
* [Reflector::export](reflector.export) — Exports
* [Reflector::\_\_toString](reflector.tostring) — To string
php ldap_explode_dn ldap\_explode\_dn
=================
(PHP 4, PHP 5, PHP 7, PHP 8)
ldap\_explode\_dn — Splits DN into its component parts
### Description
```
ldap_explode_dn(string $dn, int $with_attrib): array|false
```
Splits the DN returned by [ldap\_get\_dn()](function.ldap-get-dn) and breaks it up into its component parts. Each part is known as Relative Distinguished Name, or RDN.
### Parameters
`dn`
The distinguished name of an LDAP entity.
`with_attrib`
Used to request if the RDNs are returned with only values or their attributes as well. To get RDNs with the attributes (i.e. in attribute=value format) set `with_attrib` to 0 and to get only values set it to 1.
### Return Values
Returns an array of all DN components, or **`false`** on failure. The first element in the array has `count` key and represents the number of returned values, next elements are numerically indexed DN components.
php Yaf_Config_Ini::next Yaf\_Config\_Ini::next
======================
(Yaf >=1.0.0)
Yaf\_Config\_Ini::next — Advance the internal pointer
### Description
```
public Yaf_Config_Ini::next(): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php posix_ctermid posix\_ctermid
==============
(PHP 4, PHP 5, PHP 7, PHP 8)
posix\_ctermid — Get path name of controlling terminal
### Description
```
posix_ctermid(): string|false
```
Generates a string which is the pathname for the current controlling terminal for the process. On error this will set errno, which can be checked using [posix\_get\_last\_error()](function.posix-get-last-error)
### Parameters
This function has no parameters.
### Return Values
Upon successful completion, returns string of the pathname to the current controlling terminal. Otherwise **`false`** is returned and errno is set, which can be checked with [posix\_get\_last\_error()](function.posix-get-last-error).
### Examples
**Example #1 **posix\_ctermid()** example**
This example will display the path to the current TTY.
```
<?php
echo "I am running from ".posix_ctermid();
?>
```
### See Also
* [posix\_ttyname()](function.posix-ttyname) - Determine terminal device name
* [posix\_get\_last\_error()](function.posix-get-last-error) - Retrieve the error number set by the last posix function that failed
php Imagick::transparentPaintImage Imagick::transparentPaintImage
==============================
(PECL imagick 2 >= 2.3.0, PECL imagick 3)
Imagick::transparentPaintImage — Paints pixels transparent
### Description
```
public Imagick::transparentPaintImage(
mixed $target,
float $alpha,
float $fuzz,
bool $invert
): bool
```
Paints pixels matching the target color transparent. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer.
### Parameters
`target`
The target color to paint
`alpha`
The level of transparency: 1.0 is fully opaque and 0.0 is fully transparent.
`fuzz`
The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color.
`invert`
If **`true`** paints any pixel that does not match the target color.
### Return Values
Returns **`true`** on success.
### Examples
**Example #1 **Imagick::transparentPaintImage()****
```
<?php
function transparentPaintImage($color, $alpha, $fuzz) {
$imagick = new \Imagick(realpath("images/BlueScreen.jpg"));
//Need to be in a format that supports transparency
$imagick->setimageformat('png');
$imagick->transparentPaintImage(
$color, $alpha, $fuzz * \Imagick::getQuantum(), false
);
//Not required, but helps tidy up left over pixels
$imagick->despeckleimage();
header("Content-Type: image/png");
echo $imagick->getImageBlob();
}
?>
```
php Imagick::setImageBiasQuantum Imagick::setImageBiasQuantum
============================
(PECL imagick 3 >= 3.3.0)
Imagick::setImageBiasQuantum — Description
**Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged.
### Description
```
public Imagick::setImageBiasQuantum(string $bias): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`bias`
### Return Values
php OAuth::generateSignature OAuth::generateSignature
========================
(No version information available, might only be in Git)
OAuth::generateSignature — Generate a signature
### Description
```
public OAuth::generateSignature(string $http_method, string $url, mixed $extra_parameters = ?): string|false
```
Generate a signature based on the final HTTP method, URL and a string/array of parameters.
### Parameters
`http_method`
HTTP method for request
`url`
URL for request
`extra_parameters`
String or array of additional parameters.
### Return Values
A string containing the generated signature or **`false`** on failure
php SimpleXMLElement::xpath SimpleXMLElement::xpath
=======================
(PHP 5, PHP 7, PHP 8)
SimpleXMLElement::xpath — Runs XPath query on XML data
### Description
```
public SimpleXMLElement::xpath(string $expression): array|null|false
```
The `xpath` method searches the SimpleXML node for children matching the XPath `expression`.
### Parameters
`expression`
An XPath path
### Return Values
Returns an array of SimpleXMLElement objects on success; or **`null`** or **`false`** in case of an error.
### Examples
**Example #1 Xpath**
```
<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<d>
<c>code</c>
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
/* Search for <a><b><c> */
$result = $xml->xpath('/a/b/c');
foreach ($result as $node) {
echo '/a/b/c: ',$node,"\n";
}
/* Relative paths also work... */
$result = $xml->xpath('b/c');
foreach ($result as $node) {
echo 'b/c: ',$node,"\n";
}
?>
```
The above example will output:
```
/a/b/c: text
/a/b/c: stuff
b/c: text
b/c: stuff
```
Notice that the two results are equal.
### See Also
* [SimpleXMLElement::registerXPathNamespace()](simplexmlelement.registerxpathnamespace) - Creates a prefix/ns context for the next XPath query
* [SimpleXMLElement::getDocNamespaces()](simplexmlelement.getdocnamespaces) - Returns namespaces declared in document
* [SimpleXMLElement::getNamespaces()](simplexmlelement.getnamespaces) - Returns namespaces used in document
* [Basic SimpleXML usage](https://www.php.net/manual/en/simplexml.examples-basic.php)
php ImagickDraw::setFillPatternURL ImagickDraw::setFillPatternURL
==============================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::setFillPatternURL — Sets the URL to use as a fill pattern for filling objects
### Description
```
public ImagickDraw::setFillPatternURL(string $fill_url): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Sets the URL to use as a fill pattern for filling objects. Only local URLs ("#identifier") are supported at this time. These local URLs are normally created by defining a named fill pattern with DrawPushPattern/DrawPopPattern.
### Parameters
`fill_url`
URL to use to obtain fill pattern.
### Return Values
Returns **`true`** on success or **`false`** on failure.
php Ev::resume Ev::resume
==========
(PECL ev >= 0.2.0)
Ev::resume — Resume previously suspended default event loop
### Description
```
final public static Ev::resume(): void
```
[Ev::suspend()](ev.suspend) and **Ev::resume()** methods suspend and resume a loop correspondingly.
All timer watchers will be delayed by the time spend between *suspend* and *resume* , and all *periodic* watchers will be rescheduled(that is, they will lose any events that would have occurred while suspended).
After calling [Ev::suspend()](ev.suspend) it is not allowed to call any function on the given loop other than **Ev::resume()** . Also it is not allowed to call **Ev::resume()** without a previous call to [Ev::suspend()](ev.suspend) .
Calling *suspend* / *resume* has the side effect of updating the event loop time(see [Ev::nowUpdate()](ev.nowupdate) ).
### Parameters
This function has no parameters.
### Return Values
No value is returned.
### See Also
* [Ev::suspend()](ev.suspend) - Suspend the default event loop
php fbird_free_query fbird\_free\_query
==================
(PHP 5, PHP 7 < 7.4.0)
fbird\_free\_query — Alias of [ibase\_free\_query()](function.ibase-free-query)
### Description
This function is an alias of: [ibase\_free\_query()](function.ibase-free-query).
php Ds\PriorityQueue::toArray Ds\PriorityQueue::toArray
=========================
(PECL ds >= 1.0.0)
Ds\PriorityQueue::toArray — Converts the queue to an array
### Description
```
public Ds\PriorityQueue::toArray(): array
```
Converts the queue to an array.
>
> **Note**:
>
>
> This method is not destructive.
>
>
>
> **Note**:
>
>
> Casting to an array is not supported yet.
>
>
### Parameters
This function has no parameters.
### Return Values
An array containing all the values in the same order as the queue.
### Examples
**Example #1 **Ds\PriorityQueue::toArray()** example**
```
<?php
$queue = new \Ds\PriorityQueue();
$queue->push("a", 5);
$queue->push("b", 15);
$queue->push("c", 10);
var_dump($queue->toArray());
?>
```
The above example will output something similar to:
```
array(3) {
[0]=>
string(1) "b"
[1]=>
string(1) "c"
[2]=>
string(1) "a"
}
```
php The SplDoublyLinkedList class
The SplDoublyLinkedList class
=============================
Introduction
------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
The SplDoublyLinkedList class provides the main functionalities of a doubly linked list.
Class synopsis
--------------
class **SplDoublyLinkedList** implements [Iterator](class.iterator), [Countable](class.countable), [ArrayAccess](class.arrayaccess), [Serializable](class.serializable) { /\* Constants \*/ public const int [IT\_MODE\_LIFO](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-lifo);
public const int [IT\_MODE\_FIFO](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-fifo);
public const int [IT\_MODE\_DELETE](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-delete);
public const int [IT\_MODE\_KEEP](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-keep); /\* Methods \*/
```
public add(int $index, mixed $value): void
```
```
public bottom(): mixed
```
```
public count(): int
```
```
public current(): mixed
```
```
public getIteratorMode(): int
```
```
public isEmpty(): bool
```
```
public key(): int
```
```
public next(): void
```
```
public offsetExists(int $index): bool
```
```
public offsetGet(int $index): mixed
```
```
public offsetSet(?int $index, mixed $value): void
```
```
public offsetUnset(int $index): void
```
```
public pop(): mixed
```
```
public prev(): void
```
```
public push(mixed $value): void
```
```
public rewind(): void
```
```
public serialize(): string
```
```
public setIteratorMode(int $mode): int
```
```
public shift(): mixed
```
```
public top(): mixed
```
```
public unserialize(string $data): void
```
```
public unshift(mixed $value): void
```
```
public valid(): bool
```
} Predefined Constants
--------------------
Iteration Direction
-------------------
**`SplDoublyLinkedList::IT_MODE_LIFO`** The list will be iterated in a last in, first out order, like a stack.
**`SplDoublyLinkedList::IT_MODE_FIFO`** The list will be iterated in a first in, first out order, like a queue.
Iteration Behavior
------------------
**`SplDoublyLinkedList::IT_MODE_DELETE`** Iteration will remove the iterated elements.
**`SplDoublyLinkedList::IT_MODE_KEEP`** Iteration will not remove the iterated elements.
Table of Contents
-----------------
* [SplDoublyLinkedList::add](spldoublylinkedlist.add) — Add/insert a new value at the specified index
* [SplDoublyLinkedList::bottom](spldoublylinkedlist.bottom) — Peeks at the node from the beginning of the doubly linked list
* [SplDoublyLinkedList::count](spldoublylinkedlist.count) — Counts the number of elements in the doubly linked list
* [SplDoublyLinkedList::current](spldoublylinkedlist.current) — Return current array entry
* [SplDoublyLinkedList::getIteratorMode](spldoublylinkedlist.getiteratormode) — Returns the mode of iteration
* [SplDoublyLinkedList::isEmpty](spldoublylinkedlist.isempty) — Checks whether the doubly linked list is empty
* [SplDoublyLinkedList::key](spldoublylinkedlist.key) — Return current node index
* [SplDoublyLinkedList::next](spldoublylinkedlist.next) — Move to next entry
* [SplDoublyLinkedList::offsetExists](spldoublylinkedlist.offsetexists) — Returns whether the requested $index exists
* [SplDoublyLinkedList::offsetGet](spldoublylinkedlist.offsetget) — Returns the value at the specified $index
* [SplDoublyLinkedList::offsetSet](spldoublylinkedlist.offsetset) — Sets the value at the specified $index to $value
* [SplDoublyLinkedList::offsetUnset](spldoublylinkedlist.offsetunset) — Unsets the value at the specified $index
* [SplDoublyLinkedList::pop](spldoublylinkedlist.pop) — Pops a node from the end of the doubly linked list
* [SplDoublyLinkedList::prev](spldoublylinkedlist.prev) — Move to previous entry
* [SplDoublyLinkedList::push](spldoublylinkedlist.push) — Pushes an element at the end of the doubly linked list
* [SplDoublyLinkedList::rewind](spldoublylinkedlist.rewind) — Rewind iterator back to the start
* [SplDoublyLinkedList::serialize](spldoublylinkedlist.serialize) — Serializes the storage
* [SplDoublyLinkedList::setIteratorMode](spldoublylinkedlist.setiteratormode) — Sets the mode of iteration
* [SplDoublyLinkedList::shift](spldoublylinkedlist.shift) — Shifts a node from the beginning of the doubly linked list
* [SplDoublyLinkedList::top](spldoublylinkedlist.top) — Peeks at the node from the end of the doubly linked list
* [SplDoublyLinkedList::unserialize](spldoublylinkedlist.unserialize) — Unserializes the storage
* [SplDoublyLinkedList::unshift](spldoublylinkedlist.unshift) — Prepends the doubly linked list with an element
* [SplDoublyLinkedList::valid](spldoublylinkedlist.valid) — Check whether the doubly linked list contains more nodes
| programming_docs |
php uopz_delete uopz\_delete
============
(PECL uopz 1, PECL uopz 2)
uopz\_delete — Delete a function
**Warning**This function has been *REMOVED* in PECL uopz 5.0.0.
### Description
```
uopz_delete(string $function): void
```
```
uopz_delete(string $class, string $function): void
```
Deletes a function or method
### Parameters
`class`
`function`
### Return Values
### Examples
**Example #1 **uopz\_delete()** example**
```
<?php
uopz_delete("strlen");
echo strlen("Hello World");
?>
```
The above example will output something similar to:
```
PHP Fatal error: Call to undefined function strlen() in /path/to/script.php on line 4
```
**Example #2 **uopz\_delete()** class example**
```
<?php
class My {
public static function strlen($arg) {
return strlen($arg);
}
}
uopz_delete(My::class, "strlen");
echo My::strlen("Hello World");
?>
```
The above example will output something similar to:
```
PHP Fatal error: Call to undefined method My::strlen() in /path/to/script.php on line 10
```
php filesize filesize
========
(PHP 4, PHP 5, PHP 7, PHP 8)
filesize — Gets file size
### Description
```
filesize(string $filename): int|false
```
Gets the size for the given file.
### Parameters
`filename`
Path to the file.
### Return Values
Returns the size of the file in bytes, or **`false`** (and generates an error of level **`E_WARNING`**) in case of an error.
> **Note**: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB.
>
>
### Errors/Exceptions
Upon failure, an **`E_WARNING`** is emitted.
### Examples
**Example #1 **filesize()** example**
```
<?php
// outputs e.g. somefile.txt: 1024 bytes
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';
?>
```
### Notes
> **Note**: The results of this function are cached. See [clearstatcache()](function.clearstatcache) for more details.
>
>
**Tip**As of PHP 5.0.0, this function can also be used with *some* URL wrappers. Refer to [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality.
### See Also
* [file\_exists()](function.file-exists) - Checks whether a file or directory exists
php IntlDatePatternGenerator::getBestPattern IntlDatePatternGenerator::getBestPattern
========================================
(PHP 8 >= 8.1.0)
IntlDatePatternGenerator::getBestPattern — Determines the most suitable date/time format
### Description
```
public IntlDatePatternGenerator::getBestPattern(string $skeleton): string|false
```
Determines which date/time format is most suitable for a particular locale.
### Parameters
`skeleton`
The skeleton.
### Return Values
Returns a format, accepted by [DateTimeInterface::format()](datetime.format) on success, or **`false`** on failure.
### Examples
**Example #1 **IntlDatePatternGenerator::getBestPattern()** example**
```
<?php
$skeleton = 'YYYYMMdd';
$today = \DateTimeImmutable::createFromFormat('Y-m-d', '2021-04-24');
$patternGenerator = new \IntlDatePatternGenerator('de_DE');
$pattern = $patternGenerator->getBestPattern($skeleton);
echo 'de: ', \IntlDateFormatter::formatObject($today, $pattern, 'de_DE'), "\n";
$patternGenerator = new \IntlDatePatternGenerator('en_US');
$pattern = $patternGenerator->getBestPattern($skeleton);
echo 'en: ', \IntlDateFormatter::formatObject($today, $pattern, 'en_US');
?>
```
The above example will output:
```
de: 24.04.2021
en: 04/24/2021
```
php OAuthProvider::removeRequiredParameter OAuthProvider::removeRequiredParameter
======================================
(PECL OAuth >= 1.0.0)
OAuthProvider::removeRequiredParameter — Remove a required parameter
### Description
```
final public OAuthProvider::removeRequiredParameter(string $req_params): bool
```
Removes a required parameter.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`req_params`
The required parameter to be removed.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [OAuthProvider::setParam()](oauthprovider.setparam) - Set a parameter
* [OAuthProvider::addRequiredParameter()](oauthprovider.addrequiredparameter) - Add required parameters
php IntlCalendar::getRepeatedWallTimeOption IntlCalendar::getRepeatedWallTimeOption
=======================================
(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)
IntlCalendar::getRepeatedWallTimeOption — Get behavior for handling repeating wall time
### Description
Object-oriented style
```
public IntlCalendar::getRepeatedWallTimeOption(): int
```
Procedural style
```
intlcal_get_repeated_wall_time_option(IntlCalendar $calendar): int
```
Gets the current strategy for dealing with wall times that are repeated whenever the clock is set back during dailight saving time end transitions. The default value is **`IntlCalendar::WALLTIME_LAST`**.
This function requires ICU 4.9 or later.
### Parameters
`calendar`
An [IntlCalendar](class.intlcalendar) instance.
### Return Values
One of the constants **`IntlCalendar::WALLTIME_FIRST`** or **`IntlCalendar::WALLTIME_LAST`**.
### Examples
**Example #1 **IntlCalendar::getRepeatedWallTimeOption()****
```
<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'en_US');
ini_set('intl.error_level', E_WARNING);
//On October 27th at 0200, the clock goes back 1 hour and from GMT+01 to GMT+00
$cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30);
var_dump($cal->getRepeatedWalltimeOption()); // 0 WALLTIME_LAST
$formatter = IntlDateFormatter::create(
NULL,
IntlDateFormatter::FULL,
IntlDateFormatter::FULL,
'UTC'
);
var_dump($formatter->format($cal->getTime() / 1000.));
$cal->setRepeatedWalltimeOption(IntlCalendar::WALLTIME_FIRST);
var_dump($cal->getRepeatedWalltimeOption()); // 1 WALLTIME_FIRST
$cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1);
var_dump($formatter->format($cal->getTime() / 1000.));
```
The above example will output:
```
int(0)
string(42) "Sunday, October 27, 2013 at 1:30:00 AM GMT"
int(1)
string(43) "Sunday, October 27, 2013 at 12:30:00 AM GMT"
```
### See Also
* [IntlCalendar::getSkippedWallTimeOption()](intlcalendar.getskippedwalltimeoption) - Get behavior for handling skipped wall time
* [IntlCalendar::setSkippedWallTimeOption()](intlcalendar.setskippedwalltimeoption) - Set behavior for handling skipped wall times at positive timezone offset transitions
* [IntlCalendar::setRepeatedWallTimeOption()](intlcalendar.setrepeatedwalltimeoption) - Set behavior for handling repeating wall times at negative timezone offset transitions
php ImagickDraw::pathMoveToAbsolute ImagickDraw::pathMoveToAbsolute
===============================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::pathMoveToAbsolute — Starts a new sub-path
### Description
```
public ImagickDraw::pathMoveToAbsolute(float $x, float $y): bool
```
**Warning**This function is currently not documented; only its argument list is available.
Starts a new sub-path at the given coordinate using absolute coordinates. The current point then becomes the specified coordinate.
### Parameters
`x`
x coordinate of the starting point
`y`
y coordinate of the starting point
### Return Values
No value is returned.
php PDOStatement::closeCursor PDOStatement::closeCursor
=========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0)
PDOStatement::closeCursor — Closes the cursor, enabling the statement to be executed again
### Description
```
public PDOStatement::closeCursor(): bool
```
**PDOStatement::closeCursor()** frees up the connection to the server so that other SQL statements may be issued, but leaves the statement in a state that enables it to be executed again.
This method is useful for database drivers that do not support executing a PDOStatement object when a previously executed PDOStatement object still has unfetched rows. If your database driver suffers from this limitation, the problem may manifest itself in an out-of-sequence error.
**PDOStatement::closeCursor()** is implemented either as an optional driver specific method (allowing for maximum efficiency), or as the generic PDO fallback if no driver specific function is installed. The PDO generic fallback is semantically the same as writing the following code in your PHP script:
```
<?php
do {
while ($stmt->fetch())
;
if (!$stmt->nextRowset())
break;
} while (true);
?>
```
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 A **PDOStatement::closeCursor()** example**
In the following example, the $stmt PDOStatement object returns multiple rows but the application fetches only the first row, leaving the PDOStatement object in a state of having unfetched rows. To ensure that the application will work with all database drivers, the author inserts a call to **PDOStatement::closeCursor()** on $stmt before executing the $otherStmt PDOStatement object.
```
<?php
/* Create a PDOStatement object */
$stmt = $dbh->prepare('SELECT foo FROM bar');
/* Create a second PDOStatement object */
$otherStmt = $dbh->prepare('SELECT foobaz FROM foobar');
/* Execute the first statement */
$stmt->execute();
/* Fetch only the first row from the results */
$stmt->fetch();
/* The following call to closeCursor() may be required by some drivers */
$stmt->closeCursor();
/* Now we can execute the second statement */
$otherStmt->execute();
?>
```
### See Also
* [PDOStatement::execute()](pdostatement.execute) - Executes a prepared statement
php DOMEntityReference::__construct DOMEntityReference::\_\_construct
=================================
(PHP 5, PHP 7, PHP 8)
DOMEntityReference::\_\_construct — Creates a new DOMEntityReference object
### Description
public **DOMEntityReference::\_\_construct**(string `$name`) Creates a new [DOMEntityReference](class.domentityreference) object.
### Parameters
`name`
The name of the entity reference.
### Examples
**Example #1 Creating a new DOMEntityReference**
```
<?php
$dom = new DOMDocument('1.0', 'iso-8859-1');
$element = $dom->appendChild(new DOMElement('root'));
$entity = $element->appendChild(new DOMEntityReference('nbsp'));
echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root> </root> */
?>
```
### See Also
* [DOMDocument::createEntityReference()](domdocument.createentityreference) - Create new entity reference node
php Ev::run Ev::run
=======
(PECL ev >= 0.2.0)
Ev::run — Begin checking for events and calling callbacks for the default loop
### Description
```
final public static Ev::run( int $flags = ?): void
```
Begin checking for events and calling callbacks *for the default loop* . Returns when a callback calls [Ev::stop()](ev.stop) method, or the flags are nonzero(in which case the return value is true) or when there are no active watchers which reference the loop( [EvWatcher::keepalive()](evwatcher.keepalive) is **`true`**), in which case the return value will be **`false`**. The return value can generally be interpreted as *if **`true`**, there is more work left to do* .
### Parameters
`flags` Optional parameter `flags` can be one of the following:
**List for possible values of `flags`** | `flags` | Description |
| --- | --- |
| **`0`** | The default behavior described above |
| **`Ev::RUN_ONCE`** | Block at most one(wait, but don't loop) |
| **`Ev::RUN_NOWAIT`** | Don't block at all(fetch/handle events, but don't wait) |
See [the run flag constants](class.ev#ev.constants.run-flags) .
### Return Values
No value is returned.
### See Also
* [Ev::stop()](ev.stop) - Stops the default event loop
* [EvLoop::run()](evloop.run) - Begin checking for events and calling callbacks for the loop
php ssh2_sftp_symlink ssh2\_sftp\_symlink
===================
(PECL ssh2 >= 0.9.0)
ssh2\_sftp\_symlink — Create a symlink
### Description
```
ssh2_sftp_symlink(resource $sftp, string $target, string $link): bool
```
Creates a symbolic link named `link` on the remote filesystem pointing to `target`.
### Parameters
`sftp`
An SSH2 SFTP resource opened by [ssh2\_sftp()](function.ssh2-sftp).
`target`
Target of the symbolic link.
`link`
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Creating a symbolic link**
```
<?php
$connection = ssh2_connect('shell.example.com', 22);
ssh2_auth_password($connection, 'username', 'password');
$sftp = ssh2_sftp($connection);
ssh2_sftp_symlink($sftp, '/var/run/mysql.sock', '/tmp/mysql.sock');
?>
```
### See Also
* [ssh2\_sftp\_readlink()](function.ssh2-sftp-readlink) - Return the target of a symbolic link
* [symlink()](function.symlink) - Creates a symbolic link
php SVMModel::predict SVMModel::predict
=================
(PECL svm >= 0.1.0)
SVMModel::predict — Predict a value for previously unseen data
### Description
```
public SVMModel::predict(array $data): float
```
This function accepts an array of data and attempts to predict the class or regression value based on the model extracted from previously trained data.
### Parameters
`data`
The array to be classified. This should be a series of key => value pairs in increasing key order, but not necessarily continuous.
### Return Values
Float the predicted value. This will be a class label in the case of classification, a real value in the case of regression. Throws SVMException on error
### See Also
* [SVM::train()](svm.train) - Create a SVMModel based on training data
php tidyNode::isJste tidyNode::isJste
================
(PHP 5, PHP 7, PHP 8)
tidyNode::isJste — Checks if this node is JSTE
### Description
```
public tidyNode::isJste(): bool
```
Tells if the node is JSTE.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if the node is JSTE, **`false`** otherwise.
### Examples
**Example #1 Extract JSTE code from a mixed HTML document**
```
<?php
$html = <<< HTML
<html><head>
<?php echo '<title>title</title>'; ?>
<#
/* JSTE code */
alert('Hello World');
#>
</head>
<body>
<?php
// PHP code
echo 'hello world!';
?>
<%
/* ASP code */
response.write("Hello World!")
%>
<!-- Comments -->
Hello World
</body></html>
Outside HTML
HTML;
$tidy = tidy_parse_string($html);
$num = 0;
get_nodes($tidy->html());
function get_nodes($node) {
// check if the current node is of requested type
if($node->isJste()) {
echo "\n\n# jste node #" . ++$GLOBALS['num'] . "\n";
echo $node->value;
}
// check if the current node has childrens
if($node->hasChildren()) {
foreach($node->child as $child) {
get_nodes($child);
}
}
}
?>
```
The above example will output:
```
# jste node #1
<#
/* JSTE code */
alert('Hello World');
#>
```
php Imagick::getImageDelay Imagick::getImageDelay
======================
(PECL imagick 2, PECL imagick 3)
Imagick::getImageDelay — Gets the image delay
### Description
```
public Imagick::getImageDelay(): int
```
Gets the image delay.
### Parameters
This function has no parameters.
### Return Values
Returns the image delay.
### Errors/Exceptions
Throws ImagickException on error.
php imageopenpolygon imageopenpolygon
================
(PHP 7 >= 7.2.0, PHP 8)
imageopenpolygon — Draws an open polygon
### Description
Signature as of PHP 8.0.0 (not supported with named arguments)
```
imageopenpolygon(GdImage $image, array $points, int $color): bool
```
Alternative signature (deprecated as of PHP 8.1.0)
```
imageopenpolygon(
GdImage $image,
array $points,
int $num_points,
int $color
): bool
```
**imageopenpolygon()** draws an open polygon on the given `image`. Contrary to [imagepolygon()](function.imagepolygon), no line is drawn between the last and the first point.
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`points`
An array containing the polygon's vertices, e.g.:
| | |
| --- | --- |
| points[0] | = x0 |
| points[1] | = y0 |
| points[2] | = x1 |
| points[3] | = y1 |
`num_points`
Total number of points (vertices), which must be at least 3.
If this parameter is omitted as per the second signature, `points` must have an even number of elements, and `num_points` is assumed to be `count($points)/2`. `color`
A color identifier created with [imagecolorallocate()](function.imagecolorallocate).
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The parameter `num_points` has been deprecated. |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
### Examples
**Example #1 **imageopenpolygon()** example**
```
<?php
// Create a blank image
$image = imagecreatetruecolor(400, 300);
// Allocate a color for the polygon
$col_poly = imagecolorallocate($image, 255, 255, 255);
// Draw the polygon
imageopenpolygon($image, array(
0, 0,
100, 200,
300, 200
),
3,
$col_poly);
// Output the picture to the browser
header('Content-type: image/png');
imagepng($image);
imagedestroy($image);
?>
```
The above example will output something similar to:
### See Also
* [imagepolygon()](function.imagepolygon) - Draws a polygon
php mysqli::multi_query mysqli::multi\_query
====================
mysqli\_multi\_query
====================
(PHP 5, PHP 7, PHP 8)
mysqli::multi\_query -- mysqli\_multi\_query — Performs one or more queries on the database
### Description
Object-oriented style
```
public mysqli::multi_query(string $query): bool
```
Procedural style
```
mysqli_multi_query(mysqli $mysql, string $query): bool
```
Executes one or multiple queries which are concatenated by a semicolon.
Queries are sent asynchronously in a single call to the database, but the database processes them sequentially. **mysqli\_multi\_query()** waits for the first query to complete before returning control to PHP. The MySQL server will then process the next query in the sequence. Once the next result is ready, MySQL will wait for the next execution of [mysqli\_next\_result()](mysqli.next-result) from PHP.
It is recommended to use [do-while](control-structures.do.while) to process multiple queries. The connection will be busy until all queries have completed and their results are fetched to PHP. No other statement can be issued on the same connection until all queries are processed. To proceed to the next query in the sequence, use [mysqli\_next\_result()](mysqli.next-result). If the next result is not ready yet, mysqli will wait for the response from the MySQL server. To check if there are more results, use [mysqli\_more\_results()](mysqli.more-results).
For queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, [mysqli\_use\_result()](mysqli.use-result) or [mysqli\_store\_result()](mysqli.store-result) can be used to retrieve the result set. For queries which do not produce a result set, the same functions can be used to retrieve information such as the number of affected rows.
**Tip** Executing `CALL` statements for stored procedures can produce multiple result sets. If the stored procedure contains `SELECT` statements, the result sets are returned in the order that they are produced as the procedure executes. In general, the caller cannot know how many result sets a procedure will return and must be prepared to retrieve multiple results. The final result from the procedure is a status result that includes no result set. The status indicates whether the procedure succeeded or an error occurred.
### Parameters
`mysql`
Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init)
`query`
A string containing the queries to be executed. Multiple queries must be separated by a semicolon.
**Warning** Security warning: SQL injection
===============================
If the query contains any variable input then [parameterized prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the [mysqli\_real\_escape\_string()](mysqli.real-escape-string) function.
### Return Values
Returns **`false`** if the first statement failed. To retrieve subsequent errors from other statements you have to call [mysqli\_next\_result()](mysqli.next-result) first.
### Examples
**Example #1 **mysqli::multi\_query()** example**
Object-oriented style
```
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
$mysqli->multi_query($query);
do {
/* store the result set in PHP */
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if ($mysqli->more_results()) {
printf("-----------------\n");
}
} while ($mysqli->next_result());
```
Procedural style
```
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT CURRENT_USER();";
$query .= "SELECT Name FROM City ORDER BY ID LIMIT 20, 5";
/* execute multi query */
mysqli_multi_query($link, $query);
do {
/* store the result set in PHP */
if ($result = mysqli_store_result($link)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
}
/* print divider */
if (mysqli_more_results($link)) {
printf("-----------------\n");
}
} while (mysqli_next_result($link));
```
The above examples will output something similar to:
```
my_user@localhost
-----------------
Amersfoort
Maastricht
Dordrecht
Leiden
Haarlemmermeer
```
### See Also
* [mysqli\_query()](mysqli.query) - Performs a query on the database
* [mysqli\_use\_result()](mysqli.use-result) - Initiate a result set retrieval
* [mysqli\_store\_result()](mysqli.store-result) - Transfers a result set from the last query
* [mysqli\_next\_result()](mysqli.next-result) - Prepare next result from multi\_query
* [mysqli\_more\_results()](mysqli.more-results) - Check if there are any more query results from a multi query
| programming_docs |
php SolrQuery::getFields SolrQuery::getFields
====================
(PECL solr >= 0.9.2)
SolrQuery::getFields — Returns the list of fields that will be returned in the response
### Description
```
public SolrQuery::getFields(): array
```
Returns the list of fields that will be returned in the response
### Parameters
This function has no parameters.
### Return Values
Returns an array on success and **`null`** if not set.
php ReflectionClass::isInterface ReflectionClass::isInterface
============================
(PHP 5, PHP 7, PHP 8)
ReflectionClass::isInterface — Checks if the class is an interface
### Description
```
public ReflectionClass::isInterface(): bool
```
Checks whether the class is an interface.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Basic usage of **ReflectionClass::isInterface()****
```
<?php
interface SomeInterface {
public function interfaceMethod();
}
$class = new ReflectionClass('SomeInterface');
var_dump($class->isInterface());
?>
```
The above example will output:
```
bool(true)
```
### See Also
* [ReflectionClass::isInstance()](reflectionclass.isinstance) - Checks class for instance
php Yaf_Controller_Abstract::getName Yaf\_Controller\_Abstract::getName
==================================
(Yaf >=3.2.0)
Yaf\_Controller\_Abstract::getName — Get self name
### Description
```
public Yaf_Controller_Abstract::getName(): string
```
get the controller's name
### Parameters
This function has no parameters.
### Return Values
string, controller name
php range range
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
range — Create an array containing a range of elements
### Description
```
range(string|int|float $start, string|int|float $end, int|float $step = 1): array
```
Create an array containing a range of elements.
### Parameters
`start`
First value of the sequence.
`end`
The sequence is ended upon reaching the `end` value.
`step`
If a `step` value is given, it will be used as the increment (or decrement) between elements in the sequence. `step` must not equal `0` and must not exceed the specified range. If not specified, `step` will default to 1.
### Return Values
Returns an array of elements from `start` to `end`, inclusive.
### Examples
**Example #1 **range()** examples**
```
<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
echo $number;
}
echo "\n";
// The step parameter
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
echo $number;
}
echo "\n";
// Usage of character sequences
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
echo $letter;
}
echo "\n";
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
echo $letter;
}
?>
```
### Notes
>
> **Note**:
>
>
> Character sequence values are limited to a length of one. If a length greater than one is entered, only the first character is used.
>
>
### See Also
* [shuffle()](function.shuffle) - Shuffle an array
* [array\_fill()](function.array-fill) - Fill an array with values
* [foreach](control-structures.foreach)
php XMLReader::setRelaxNGSchemaSource XMLReader::setRelaxNGSchemaSource
=================================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
XMLReader::setRelaxNGSchemaSource — Set the data containing a RelaxNG Schema
### Description
```
public XMLReader::setRelaxNGSchemaSource(?string $source): bool
```
Set the data containing a RelaxNG Schema to use for validation.
### Parameters
`source`
String containing the RelaxNG Schema.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [XMLReader::setRelaxNGSchema()](xmlreader.setrelaxngschema) - Set the filename or URI for a RelaxNG Schema
* [XMLReader::setSchema()](xmlreader.setschema) - Validate document against XSD
* [XMLReader::isValid()](xmlreader.isvalid) - Indicates if the parsed document is valid
php bzcompress bzcompress
==========
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
bzcompress — Compress a string into bzip2 encoded data
### Description
```
bzcompress(string $data, int $block_size = 4, int $work_factor = 0): string|int
```
**bzcompress()** compresses the given string and returns it as bzip2 encoded data.
### Parameters
`data`
The string to compress.
`block_size`
Specifies the blocksize used during compression and should be a number from 1 to 9 with 9 giving the best compression, but using more resources to do so.
`work_factor`
Controls how the compression phase behaves when presented with worst case, highly repetitive, input data. The value can be between 0 and 250 with 0 being a special case.
Regardless of the `work_factor`, the generated output is the same.
### Return Values
The compressed string, or an error number if an error occurred.
### Examples
**Example #1 Compressing data**
```
<?php
$str = "sample data";
$bzstr = bzcompress($str, 9);
echo $bzstr;
?>
```
### See Also
* [bzdecompress()](function.bzdecompress) - Decompresses bzip2 encoded data
php imagecreatefromjpeg imagecreatefromjpeg
===================
(PHP 4, PHP 5, PHP 7, PHP 8)
imagecreatefromjpeg — Create a new image from file or URL
### Description
```
imagecreatefromjpeg(string $filename): GdImage|false
```
**imagecreatefromjpeg()** returns an image identifier representing the image obtained from the given filename.
**Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
### Parameters
`filename`
Path to the JPEG image.
### Return Values
Returns an image object on success, **`false`** on errors.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. |
### Examples
**Example #1 Example to handle an error during loading of a JPEG**
```
<?php
function LoadJpeg($imgname)
{
/* Attempt to open */
$im = @imagecreatefromjpeg($imgname);
/* See if it failed */
if(!$im)
{
/* Create a black image */
$im = imagecreatetruecolor(150, 30);
$bgc = imagecolorallocate($im, 255, 255, 255);
$tc = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 150, 30, $bgc);
/* Output an error message */
imagestring($im, 1, 5, 5, 'Error loading ' . $imgname, $tc);
}
return $im;
}
header('Content-Type: image/jpeg');
$img = LoadJpeg('bogus.image');
imagejpeg($img);
imagedestroy($img);
?>
```
The above example will output something similar to:
php is_bool is\_bool
========
(PHP 4, PHP 5, PHP 7, PHP 8)
is\_bool — Finds out whether a variable is a boolean
### Description
```
is_bool(mixed $value): bool
```
Finds whether the given variable is a boolean.
### Parameters
`value`
The variable being evaluated.
### Return Values
Returns **`true`** if `value` is a bool, **`false`** otherwise.
### Examples
**Example #1 **is\_bool()** examples**
```
<?php
$a = false;
$b = 0;
// Since $a is a boolean, it will return true
if (is_bool($a) === true) {
echo "Yes, this is a boolean";
}
// Since $b is not a boolean, it will return false
if (is_bool($b) === false) {
echo "No, this is not a boolean";
}
?>
```
### See Also
* [is\_float()](function.is-float) - Finds whether the type of a variable is float
* [is\_int()](function.is-int) - Find whether the type of a variable is integer
* [is\_string()](function.is-string) - Find whether the type of a variable is string
* [is\_object()](function.is-object) - Finds whether a variable is an object
* [is\_array()](function.is-array) - Finds whether a variable is an array
php phpdbg_prompt phpdbg\_prompt
==============
(PHP 5 >= 5.6.0, PHP 7, PHP 8)
phpdbg\_prompt — Sets the command prompt
### Description
```
phpdbg_prompt(string $string): void
```
Set the command prompt to the given `string`.
### Parameters
`string`
The string to use as command prompt.
### Return Values
No value is returned.
### See Also
* [phpdbg\_color()](function.phpdbg-color) - Sets the color of certain elements
php EventBuffer::substr EventBuffer::substr
===================
(PECL event >= 1.6.0)
EventBuffer::substr — Substracts a portion of the buffer data
### Description
```
public EventBuffer::substr( int $start , int $length = ?): string
```
Substracts up to `length` bytes of the buffer data beginning at `start` position.
### Parameters
`start` The start position of data to be substracted.
`length` Maximum number of bytes to substract.
### Return Values
Returns the data substracted as a string on success, or **`false`** on failure.
### See Also
* [EventBuffer::read()](eventbuffer.read) - Read data from an evbuffer and drain the bytes read
php mb_ereg_search_setpos mb\_ereg\_search\_setpos
========================
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
mb\_ereg\_search\_setpos — Set start point of next regular expression match
### Description
```
mb_ereg_search_setpos(int $offset): bool
```
**mb\_ereg\_search\_setpos()** sets the starting point of a match for [mb\_ereg\_search()](function.mb-ereg-search).
### Parameters
`offset`
The position to set. If it is negative, it counts from the end of the string.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 7.1.0 | Support for negative `offset`s has been added. |
### Notes
>
> **Note**:
>
>
> The internal encoding or the character encoding specified by [mb\_regex\_encoding()](function.mb-regex-encoding) will be used as the character encoding for this function.
>
>
>
### See Also
* [mb\_regex\_encoding()](function.mb-regex-encoding) - Set/Get character encoding for multibyte regex
* [mb\_ereg\_search\_init()](function.mb-ereg-search-init) - Setup string and regular expression for a multibyte regular expression match
php IntlChar::isISOControl IntlChar::isISOControl
======================
(PHP 7, PHP 8)
IntlChar::isISOControl — Check if code point is an ISO control code
### Description
```
public static IntlChar::isISOControl(int|string $codepoint): ?bool
```
Determines whether the specified code point is an ISO control code.
**`true`** for U+0000..U+001f and U+007f..U+009f (general category "Cc").
### Parameters
`codepoint`
The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`)
### Return Values
Returns **`true`** if `codepoint` is an ISO control code, **`false`** if not. Returns **`null`** on failure.
### Examples
**Example #1 Testing different code points**
```
<?php
var_dump(IntlChar::isISOControl(" "));
var_dump(IntlChar::isISOControl("\n"));
var_dump(IntlChar::isISOControl("\u{200e}"));
?>
```
The above example will output:
```
bool(false)
bool(true)
bool(false)
```
### See Also
* [IntlChar::iscntrl()](intlchar.iscntrl) - Check if code point is a control character
php Yaf_Config_Ini::__get Yaf\_Config\_Ini::\_\_get
=========================
(Yaf >=1.0.0)
Yaf\_Config\_Ini::\_\_get — Retrieve a element
### Description
```
public Yaf_Config_Ini::__get(string $name = ?): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`name`
### Return Values
php mysqli::real_escape_string mysqli::real\_escape\_string
============================
mysqli\_real\_escape\_string
============================
(PHP 5, PHP 7, PHP 8)
mysqli::real\_escape\_string -- mysqli\_real\_escape\_string — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection
### Description
Object-oriented style
```
public mysqli::real_escape_string(string $string): string
```
Procedural style
```
mysqli_real_escape_string(mysqli $mysql, string $string): string
```
This function is used to create a legal SQL string that you can use in an SQL statement. The given string is encoded to produce an escaped SQL string, taking into account the current character set of the connection.
**Caution** Security: the default character set
===================================
The character set must be set either at the server level, or with the API function [mysqli\_set\_charset()](mysqli.set-charset) for it to affect **mysqli\_real\_escape\_string()**. See the concepts section on [character sets](https://www.php.net/manual/en/mysqlinfo.concepts.charset.php) for more information.
### Parameters
`mysql`
Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init)
`string`
The string to be escaped.
Characters encoded are `NUL (ASCII 0), \n, \r, \, ', ", and
Control-Z`.
### Return Values
Returns an escaped string.
### Examples
**Example #1 **mysqli::real\_escape\_string()** example**
Object-oriented style
```
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with escaped $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
$mysqli->real_escape_string($city));
$result = $mysqli->query($query);
printf("Select returned %d rows.\n", $result->num_rows);
/* this query will fail, because we didn't escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = $mysqli->query($query);
```
Procedural style
```
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
$city = "'s-Hertogenbosch";
/* this query with escaped $city will work */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'",
mysqli_real_escape_string($mysqli, $city));
$result = mysqli_query($mysqli, $query);
printf("Select returned %d rows.\n", mysqli_num_rows($result));
/* this query will fail, because we didn't escape $city */
$query = sprintf("SELECT CountryCode FROM City WHERE name='%s'", $city);
$result = mysqli_query($mysqli, $query);
```
The above examples will output something similar to:
```
Select returned 1 rows.
Fatal error: Uncaught mysqli_sql_exception: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's-Hertogenbosch'' at line 1 in...
```
### See Also
* [mysqli\_set\_charset()](mysqli.set-charset) - Sets the client character set
php SolrQuery::setFacetMinCount SolrQuery::setFacetMinCount
===========================
(PECL solr >= 0.9.2)
SolrQuery::setFacetMinCount — Maps to facet.mincount
### Description
```
public SolrQuery::setFacetMinCount(int $mincount, string $field_override = ?): SolrQuery
```
Sets the minimum counts for facet fields that should be included in the response
### Parameters
`mincount`
The minimum count
`field_override`
The name of the field.
### Return Values
Returns the current SolrQuery object, if the return value is used.
php EventHttpConnection::getBase EventHttpConnection::getBase
============================
(PECL event >= 1.2.6-beta)
EventHttpConnection::getBase — Returns event base associated with the connection
### Description
```
public EventHttpConnection::getBase(): EventBase
```
Returns event base associated with the connection.
### Parameters
This function has no parameters.
### Return Values
On success returns [EventBase](class.eventbase) object associated with the connection. Otherwise **`false`**.
php fbird_delete_user fbird\_delete\_user
===================
(PHP 5, PHP 7 < 7.4.0)
fbird\_delete\_user — Alias of [ibase\_delete\_user()](function.ibase-delete-user)
### Description
This function is an alias of: [ibase\_delete\_user()](function.ibase-delete-user).
### See Also
* [fbird\_add\_user()](function.fbird-add-user) - Alias of ibase\_add\_user
* [fbird\_modify\_user()](function.fbird-modify-user) - Alias of ibase\_modify\_user
php SplFileInfo::getLinkTarget SplFileInfo::getLinkTarget
==========================
(PHP 5 >= 5.2.2, PHP 7, PHP 8)
SplFileInfo::getLinkTarget — Gets the target of a link
### Description
```
public SplFileInfo::getLinkTarget(): string|false
```
Gets the target of a filesystem link.
>
> **Note**:
>
>
> The target may not be the real path on the filesystem. Use [SplFileInfo::getRealPath()](splfileinfo.getrealpath) to determine the true path on the filesystem.
>
>
### Parameters
This function has no parameters.
### Return Values
Returns the target of the filesystem link on success, or **`false`** on failure.
### Errors/Exceptions
Throws [RuntimeException](class.runtimeexception) on error.
### Examples
**Example #1 **SplFileInfo::getLinkTarget()** example**
```
<?php
$info = new SplFileInfo('/Users/bbieber/workspace');
if ($info->isLink()) {
var_dump($info->getLinkTarget());
var_dump($info->getRealPath());
}
?>
```
The above example will output something similar to:
```
string(19) "Documents/workspace"
string(34) "/Users/bbieber/Documents/workspace"
```
### See Also
* [SplFileInfo::isLink()](splfileinfo.islink) - Tells if the file is a link
* [SplFileInfo::getRealPath()](splfileinfo.getrealpath) - Gets absolute path to file
php The V8JsException class
The V8JsException class
=======================
Introduction
------------
(PECL v8js >= 0.1.0)
Class synopsis
--------------
class **V8JsException** extends [Exception](class.exception) { /\* Properties \*/ protected [$JsFileName](class.v8jsexception#v8jsexception.props.jsfilename);
protected [$JsLineNumber](class.v8jsexception#v8jsexception.props.jslinenumber);
protected [$JsSourceLine](class.v8jsexception#v8jsexception.props.jssourceline);
protected [$JsTrace](class.v8jsexception#v8jsexception.props.jstrace); /\* Inherited properties \*/
protected string [$message](class.exception#exception.props.message) = "";
private string [$string](class.exception#exception.props.string) = "";
protected int [$code](class.exception#exception.props.code);
protected string [$file](class.exception#exception.props.file) = "";
protected int [$line](class.exception#exception.props.line);
private array [$trace](class.exception#exception.props.trace) = [];
private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Methods \*/
```
final public getJsFileName(): string
```
```
final public getJsLineNumber(): int
```
```
final public getJsSourceLine(): string
```
```
final public getJsTrace(): string
```
/\* Inherited methods \*/
```
final public Exception::getMessage(): string
```
```
final public Exception::getPrevious(): ?Throwable
```
```
final public Exception::getCode(): int
```
```
final public Exception::getFile(): string
```
```
final public Exception::getLine(): int
```
```
final public Exception::getTrace(): array
```
```
final public Exception::getTraceAsString(): string
```
```
public Exception::__toString(): string
```
```
private Exception::__clone(): void
```
} Properties
----------
JsFileName JsLineNumber JsSourceLine JsTrace Table of Contents
-----------------
* [V8JsException::getJsFileName](v8jsexception.getjsfilename) — The getJsFileName purpose
* [V8JsException::getJsLineNumber](v8jsexception.getjslinenumber) — The getJsLineNumber purpose
* [V8JsException::getJsSourceLine](v8jsexception.getjssourceline) — The getJsSourceLine purpose
* [V8JsException::getJsTrace](v8jsexception.getjstrace) — The getJsTrace purpose
| programming_docs |
php The ImagickPixel class
The ImagickPixel class
======================
Class synopsis
--------------
(PECL imagick 2, PECL imagick 3)
class **ImagickPixel** {
```
public clear(): bool
```
```
public __construct(string $color = ?)
```
```
public destroy(): bool
```
```
public getColor(int $normalized = 0): array
```
```
public getColorAsString(): string
```
```
public getColorCount(): int
```
```
public getColorQuantum(): array
```
```
public getColorValue(int $color): float
```
```
public getColorValueQuantum(int $color): int|float
```
```
public getHSL(): array
```
```
public getIndex(): int
```
```
public isPixelSimilar(ImagickPixel $color, float $fuzz): bool
```
```
public isPixelSimilarQuantum(string $color, string $fuzz = ?): bool
```
```
public isSimilar(ImagickPixel $color, float $fuzz): bool
```
```
public setColor(string $color): bool
```
```
public setcolorcount(int $colorCount): bool
```
```
public setColorValue(int $color, float $value): bool
```
```
public setColorValueQuantum(int $color, int|float $value): bool
```
```
public setHSL(float $hue, float $saturation, float $luminosity): bool
```
```
public setIndex(int $index): bool
```
} Table of Contents
-----------------
* [ImagickPixel::clear](imagickpixel.clear) — Clears resources associated with this object
* [ImagickPixel::\_\_construct](imagickpixel.construct) — The ImagickPixel constructor
* [ImagickPixel::destroy](imagickpixel.destroy) — Deallocates resources associated with this object
* [ImagickPixel::getColor](imagickpixel.getcolor) — Returns the color
* [ImagickPixel::getColorAsString](imagickpixel.getcolorasstring) — Returns the color as a string
* [ImagickPixel::getColorCount](imagickpixel.getcolorcount) — Returns the color count associated with this color
* [ImagickPixel::getColorQuantum](imagickpixel.getcolorquantum) — Description
* [ImagickPixel::getColorValue](imagickpixel.getcolorvalue) — Gets the normalized value of the provided color channel
* [ImagickPixel::getColorValueQuantum](imagickpixel.getcolorvaluequantum) — Description
* [ImagickPixel::getHSL](imagickpixel.gethsl) — Returns the normalized HSL color of the ImagickPixel object
* [ImagickPixel::getIndex](imagickpixel.getindex) — Description
* [ImagickPixel::isPixelSimilar](imagickpixel.ispixelsimilar) — Check the distance between this color and another
* [ImagickPixel::isPixelSimilarQuantum](imagickpixel.ispixelsimilarquantum) — Description
* [ImagickPixel::isSimilar](imagickpixel.issimilar) — Check the distance between this color and another
* [ImagickPixel::setColor](imagickpixel.setcolor) — Sets the color
* [ImagickPixel::setColorCount](imagickpixel.setcolorcount) — Description
* [ImagickPixel::setColorValue](imagickpixel.setcolorvalue) — Sets the normalized value of one of the channels
* [ImagickPixel::setColorValueQuantum](imagickpixel.setcolorvaluequantum) — Description
* [ImagickPixel::setHSL](imagickpixel.sethsl) — Sets the normalized HSL color
* [ImagickPixel::setIndex](imagickpixel.setindex) — Description
php The Yaf_Registry class
The Yaf\_Registry class
=======================
Introduction
------------
(Yaf >=1.0.0)
All methods of **Yaf\_Registry** declared as static, making it unversally accessible. This provides the ability to get or set any custom data from anyway in your code as necessary.
Class synopsis
--------------
class **Yaf\_Registry** { /\* Properties \*/ static [$\_instance](class.yaf-registry#yaf-registry.props.instance);
protected [$\_entries](class.yaf-registry#yaf-registry.props.entries); /\* Methods \*/ private [\_\_construct](yaf-registry.construct)()
```
public static del(string $name): void
```
```
public static get(string $name): mixed
```
```
public static has(string $name): bool
```
```
public static set(string $name, string $value): bool
```
} Properties
----------
\_instance \_entries Table of Contents
-----------------
* [Yaf\_Registry::\_\_construct](yaf-registry.construct) — Yaf\_Registry implements singleton
* [Yaf\_Registry::del](yaf-registry.del) — Remove an item from registry
* [Yaf\_Registry::get](yaf-registry.get) — Retrieve an item from registry
* [Yaf\_Registry::has](yaf-registry.has) — Check whether an item exists
* [Yaf\_Registry::set](yaf-registry.set) — Add an item into registry
php stats_rand_gen_noncentral_f stats\_rand\_gen\_noncentral\_f
===============================
(PECL stats >= 1.0.0)
stats\_rand\_gen\_noncentral\_f — Generates a random deviate from the noncentral F distribution
### Description
```
stats_rand_gen_noncentral_f(float $dfn, float $dfd, float $xnonc): float
```
Returns a random deviate from the non-central F distribution where the degrees of freedoms are `dfn` (numerator) and `dfd` (denominator), and the non-centrality parameter is `xnonc`.
### Parameters
`dfn`
The degrees of freedom of the numerator
`dfd`
The degrees of freedom of the denominator
`xnonc`
The non-centrality parameter
### Return Values
A random deviate
php spl_object_hash spl\_object\_hash
=================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
spl\_object\_hash — Return hash id for given object
### Description
```
spl_object_hash(object $object): string
```
This function returns a unique identifier for the object. This id can be used as a hash key for storing objects, or for identifying an object, as long as the object is not destroyed. Once the object is destroyed, its hash may be reused for other objects. This behavior is similar to [spl\_object\_id()](function.spl-object-id).
### Parameters
`object`
Any object.
### Return Values
A string that is unique for each currently existing object and is always the same for each object.
### Examples
**Example #1 A **spl\_object\_hash()** example**
```
<?php
$id = spl_object_hash($object);
$storage[$id] = $object;
?>
```
### Notes
>
> **Note**:
>
>
> When an object is destroyed, its hash may be reused for other objects.
>
>
### See Also
* [spl\_object\_id()](function.spl-object-id) - Return the integer object handle for given object
php ReflectionClassConstant::__toString ReflectionClassConstant::\_\_toString
=====================================
(PHP 7 >= 7.1.0, PHP 8)
ReflectionClassConstant::\_\_toString — Returns the string representation of the ReflectionClassConstant object
### Description
```
public ReflectionClassConstant::__toString(): string
```
Returns the string representation of the ReflectionClassConstant object.
### Parameters
This function has no parameters.
### Return Values
A string representation of this [ReflectionClassConstant](class.reflectionclassconstant) instance.
### See Also
* [ReflectionClassConstant::export()](reflectionclassconstant.export) - Export
* [\_\_toString()](language.oop5.magic#object.tostring)
php Gmagick::setimageinterlacescheme Gmagick::setimageinterlacescheme
================================
(PECL gmagick >= Unknown)
Gmagick::setimageinterlacescheme — Sets the interlace scheme of the image
### Description
```
public Gmagick::setimageinterlacescheme(int $interlace): Gmagick
```
Sets the interlace scheme of the image.
### Parameters
`interlace`
One of the [Interlace](https://www.php.net/manual/en/gmagick.constants.php#gmagick.constants.interlace) constant (`Gmagick::INTERLACE_*`).
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php streamWrapper::stream_tell streamWrapper::stream\_tell
===========================
(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)
streamWrapper::stream\_tell — Retrieve the current position of a stream
### Description
```
public streamWrapper::stream_tell(): int
```
This method is called in response to [fseek()](function.fseek) to determine the current position.
### Parameters
This function has no parameters.
### Return Values
Should return the current position of the stream.
### See Also
* **streamWrapper::stream\_tell()**
php token_get_all token\_get\_all
===============
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
token\_get\_all — Split given source into PHP tokens
### Description
```
token_get_all(string $code, int $flags = 0): array
```
**token\_get\_all()** parses the given `code` string into PHP language tokens using the Zend engine's lexical scanner.
For a list of parser tokens, see [List of Parser Tokens](https://www.php.net/manual/en/tokens.php), or use [token\_name()](function.token-name) to translate a token value into its string representation.
### Parameters
`code`
The PHP source to parse.
`flags`
Valid flags:
* **`TOKEN_PARSE`** - Recognises the ability to use reserved words in specific contexts.
### Return Values
An array of token identifiers. Each individual token identifier is either a single character (i.e.: `;`, `.`, `>`, `!`, etc...), or a three element array containing the token index in element 0, the string content of the original token in element 1 and the line number in element 2.
### Examples
**Example #1 **token\_get\_all()** example**
```
<?php
$tokens = token_get_all('<?php echo; ?>');
foreach ($tokens as $token) {
if (is_array($token)) {
echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
}
}
?>
```
The above example will output something similar to:
```
Line 1: T_OPEN_TAG ('<?php ')
Line 1: T_ECHO ('echo')
Line 1: T_WHITESPACE (' ')
Line 1: T_CLOSE_TAG ('?>')
```
**Example #2 **token\_get\_all()** incorrect usage example**
```
<?php
$tokens = token_get_all('/* comment */');
foreach ($tokens as $token) {
if (is_array($token)) {
echo "Line {$token[2]}: ", token_name($token[0]), " ('{$token[1]}')", PHP_EOL;
}
}
?>
```
The above example will output something similar to:
```
Line 1: T_INLINE_HTML ('/* comment */')
```
Note in the previous example that the string is parsed as **`T_INLINE_HTML`** rather than the expected **`T_COMMENT`**. This is because no open tag was used in the code provided. This would be equivalent to putting a comment outside of the PHP tags in a normal file.
**Example #3 **token\_get\_all()** on a class using a reserved word example**
```
<?php
$source = <<<'code'
<?php
class A
{
const PUBLIC = 1;
}
code;
$tokens = token_get_all($source, TOKEN_PARSE);
foreach ($tokens as $token) {
if (is_array($token)) {
echo token_name($token[0]) , PHP_EOL;
}
}
?>
```
The above example will output something similar to:
```
T_OPEN_TAG
T_WHITESPACE
T_CLASS
T_WHITESPACE
T_STRING
T_CONST
T_WHITESPACE
T_STRING
T_LNUMBER
```
Without the **`TOKEN_PARSE`** flag, the penultimate token (**`T_STRING`**) would have been **`T_PUBLIC`**. ### See Also
* [PhpToken::tokenize()](phptoken.tokenize) - Splits given source into PHP tokens, represented by PhpToken objects.
* [token\_name()](function.token-name) - Get the symbolic name of a given PHP token
php SolrResponse::getRawRequest SolrResponse::getRawRequest
===========================
(PECL solr >= 0.9.2)
SolrResponse::getRawRequest — Returns the raw request sent to the Solr server
### Description
```
public SolrResponse::getRawRequest(): string
```
Returns the raw request sent to the Solr server.
### Parameters
This function has no parameters.
### Return Values
Returns the raw request sent to the Solr server
php QuickHashIntSet::exists QuickHashIntSet::exists
=======================
(PECL quickhash >= Unknown)
QuickHashIntSet::exists — This method checks whether a key is part of the set
### Description
```
public QuickHashIntSet::exists(int $key): bool
```
This method checks whether an entry with the provided key exists in the set.
### Parameters
`key`
The key of the entry to check for whether it exists in the set.
### Return Values
Returns **`true`** when the entry was found, or **`false`** when the entry is not found.
### Examples
**Example #1 **QuickHashIntSet::exists()** example**
```
<?php
//generate 200000 elements
$array = range( 0, 199999 );
$existingEntries = array_rand( array_flip( $array ), 180000 );
$testForEntries = array_rand( array_flip( $array ), 1000 );
$foundCount = 0;
echo "Creating set: ", microtime( true ), "\n";
$set = new QuickHashIntSet( 100000 );
echo "Adding elements: ", microtime( true ), "\n";
foreach( $existingEntries as $key )
{
$set->add( $key );
}
echo "Doing 1000 tests: ", microtime( true ), "\n";
foreach( $testForEntries as $key )
{
$foundCount += $set->exists( $key );
}
echo "Done, $foundCount found: ", microtime( true ), "\n";
?>
```
The above example will output something similar to:
```
Creating set: 1263588703.0748
Adding elements: 1263588703.0757
Doing 1000 tests: 1263588703.7851
Done, 898 found: 1263588703.7897
```
php imagecreatefromwebp imagecreatefromwebp
===================
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
imagecreatefromwebp — Create a new image from file or URL
### Description
```
imagecreatefromwebp(string $filename): GdImage|false
```
**imagecreatefromwebp()** returns an image identifier representing the image obtained from the given filename. Note that animated WebP files cannot be read.
**Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
### Parameters
`filename`
Path to the WebP image.
### Return Values
Returns an image object on success, **`false`** on errors.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. |
### Examples
**Example #1 Convert an WebP image to a jpeg image using **imagecreatefromwebp()****
```
<?php
// Load the WebP file
$im = imagecreatefromwebp('./example.webp');
// Convert it to a jpeg file with 100% quality
imagejpeg($im, './example.jpeg', 100);
imagedestroy($im);
?>
```
php The Zookeeper class
The Zookeeper class
===================
Introduction
------------
(PECL zookeeper >= 0.1.0)
Represents ZooKeeper session.
Class synopsis
--------------
class **Zookeeper** { /\* Methods \*/ public [\_\_construct](zookeeper.construct)(string `$host` = '', [callable](language.types.callable) `$watcher_cb` = **`null`**, int `$recv_timeout` = 10000)
```
public addAuth(string $scheme, string $cert, callable $completion_cb = null): bool
```
```
public close(): void
```
```
public connect(string $host, callable $watcher_cb = null, int $recv_timeout = 10000): void
```
```
public create(
string $path,
string $value,
array $acls,
int $flags = null
): string
```
```
public delete(string $path, int $version = -1): bool
```
```
public exists(string $path, callable $watcher_cb = null): array
```
```
public get(
string $path,
callable $watcher_cb = null,
array &$stat = null,
int $max_size = 0
): string
```
```
public getAcl(string $path): array
```
```
public getChildren(string $path, callable $watcher_cb = null): array
```
```
public getClientId(): int
```
```
public getConfig(): ZookeeperConfig
```
```
public getRecvTimeout(): int
```
```
public getState(): int
```
```
public isRecoverable(): bool
```
```
public set(
string $path,
string $value,
int $version = -1,
array &$stat = null
): bool
```
```
public setAcl(string $path, int $version, array $acl): bool
```
```
public static setDebugLevel(int $logLevel): bool
```
```
public static setDeterministicConnOrder(bool $yesOrNo): bool
```
```
public setLogStream(resource $stream): bool
```
```
public setWatcher(callable $watcher_cb): bool
```
/\* Constants \*/ const int [PERM\_READ](class.zookeeper#zookeeper.class.constants.perm-read) = 1;
const int [PERM\_WRITE](class.zookeeper#zookeeper.class.constants.perm-write) = 2;
const int [PERM\_CREATE](class.zookeeper#zookeeper.class.constants.perm-create) = 4;
const int [PERM\_DELETE](class.zookeeper#zookeeper.class.constants.perm-delete) = 8;
const int [PERM\_ADMIN](class.zookeeper#zookeeper.class.constants.perm-admin) = 16;
const int [PERM\_ALL](class.zookeeper#zookeeper.class.constants.perm-all) = 31;
const int [EPHEMERAL](class.zookeeper#zookeeper.class.constants.ephemeral) = 1;
const int [SEQUENCE](class.zookeeper#zookeeper.class.constants.sequence) = 2;
const int [LOG\_LEVEL\_ERROR](class.zookeeper#zookeeper.class.constants.log-level-error) = 1;
const int [LOG\_LEVEL\_WARN](class.zookeeper#zookeeper.class.constants.log-level-warn) = 2;
const int [LOG\_LEVEL\_INFO](class.zookeeper#zookeeper.class.constants.log-level-info) = 3;
const int [LOG\_LEVEL\_DEBUG](class.zookeeper#zookeeper.class.constants.log-level-debug) = 4;
const int [EXPIRED\_SESSION\_STATE](class.zookeeper#zookeeper.class.constants.expired-session-state) = -112;
const int [AUTH\_FAILED\_STATE](class.zookeeper#zookeeper.class.constants.auth-failed-state) = -113;
const int [CONNECTING\_STATE](class.zookeeper#zookeeper.class.constants.connecting-state) = 1;
const int [ASSOCIATING\_STATE](class.zookeeper#zookeeper.class.constants.associating-state) = 2;
const int [CONNECTED\_STATE](class.zookeeper#zookeeper.class.constants.connected-state) = 3;
const int [READONLY\_STATE](class.zookeeper#zookeeper.class.constants.readonly-state) = 5;
const int [NOTCONNECTED\_STATE](class.zookeeper#zookeeper.class.constants.notconnected-state) = 999;
const int [CREATED\_EVENT](class.zookeeper#zookeeper.class.constants.created-event) = 1;
const int [DELETED\_EVENT](class.zookeeper#zookeeper.class.constants.deleted-event) = 2;
const int [CHANGED\_EVENT](class.zookeeper#zookeeper.class.constants.changed-event) = 3;
const int [CHILD\_EVENT](class.zookeeper#zookeeper.class.constants.child-event) = 4;
const int [SESSION\_EVENT](class.zookeeper#zookeeper.class.constants.session-event) = -1;
const int [NOTWATCHING\_EVENT](class.zookeeper#zookeeper.class.constants.notwatching-event) = -2;
const int [SYSTEMERROR](class.zookeeper#zookeeper.class.constants.systemerror) = -1;
const int [RUNTIMEINCONSISTENCY](class.zookeeper#zookeeper.class.constants.runtimeinconsistency) = -2;
const int [DATAINCONSISTENCY](class.zookeeper#zookeeper.class.constants.datainconsistency) = -3;
const int [CONNECTIONLOSS](class.zookeeper#zookeeper.class.constants.connectionloss) = -4;
const int [MARSHALLINGERROR](class.zookeeper#zookeeper.class.constants.marshallingerror) = -5;
const int [UNIMPLEMENTED](class.zookeeper#zookeeper.class.constants.unimplemented) = -6;
const int [OPERATIONTIMEOUT](class.zookeeper#zookeeper.class.constants.operationtimeout) = -7;
const int [BADARGUMENTS](class.zookeeper#zookeeper.class.constants.badarguments) = -8;
const int [INVALIDSTATE](class.zookeeper#zookeeper.class.constants.invalidstate) = -9;
const int [NEWCONFIGNOQUORUM](class.zookeeper#zookeeper.class.constants.newconfignoquorum) = -13;
const int [RECONFIGINPROGRESS](class.zookeeper#zookeeper.class.constants.reconfiginprogress) = -14;
const int [OK](class.zookeeper#zookeeper.class.constants.ok) = 0;
const int [APIERROR](class.zookeeper#zookeeper.class.constants.apierror) = -100;
const int [NONODE](class.zookeeper#zookeeper.class.constants.nonode) = -101;
const int [NOAUTH](class.zookeeper#zookeeper.class.constants.noauth) = -102;
const int [BADVERSION](class.zookeeper#zookeeper.class.constants.badversion) = -103;
const int [NOCHILDRENFOREPHEMERALS](class.zookeeper#zookeeper.class.constants.nochildrenforephemerals) = -108;
const int [NODEEXISTS](class.zookeeper#zookeeper.class.constants.nodeexists) = -110;
const int [NOTEMPTY](class.zookeeper#zookeeper.class.constants.notempty) = -111;
const int [SESSIONEXPIRED](class.zookeeper#zookeeper.class.constants.sessionexpired) = -112;
const int [INVALIDCALLBACK](class.zookeeper#zookeeper.class.constants.invalidcallback) = -113;
const int [INVALIDACL](class.zookeeper#zookeeper.class.constants.invalidacl) = -114;
const int [AUTHFAILED](class.zookeeper#zookeeper.class.constants.authfailed) = -115;
const int [CLOSING](class.zookeeper#zookeeper.class.constants.closing) = -116;
const int [NOTHING](class.zookeeper#zookeeper.class.constants.nothing) = -117;
const int [SESSIONMOVED](class.zookeeper#zookeeper.class.constants.sessionmoved) = -118;
const int [NOTREADONLY](class.zookeeper#zookeeper.class.constants.notreadonly) = -119;
const int [EPHEMERALONLOCALSESSION](class.zookeeper#zookeeper.class.constants.ephemeralonlocalsession) = -120;
const int [NOWATCHER](class.zookeeper#zookeeper.class.constants.nowatcher) = -121;
const int [RECONFIGDISABLED](class.zookeeper#zookeeper.class.constants.reconfigdisabled) = -122; } Predefined Constants
--------------------
ZooKeeper Permissions
----------------------
**`Zookeeper::PERM_READ`** Can read nodes value and list its children
**`Zookeeper::PERM_WRITE`** Can set the nodes value
**`Zookeeper::PERM_CREATE`** Can create children
**`Zookeeper::PERM_DELETE`** Can delete children
**`Zookeeper::PERM_ADMIN`** Can execute set\_acl()
**`Zookeeper::PERM_ALL`** All of the above flags ORd together
ZooKeeper Create Flags
-----------------------
**`Zookeeper::EPHEMERAL`** If Zookeeper::EPHEMERAL flag is set, the node will automatically get removed if the client session goes away.
**`Zookeeper::SEQUENCE`** If the Zookeeper::SEQUENCE flag is set, a unique monotonically increasing sequence number is appended to the path name. The sequence number is always fixed length of 10 digits, 0 padded.
ZooKeeper Log Levels
---------------------
**`Zookeeper::LOG_LEVEL_ERROR`** Outputs only error mesages
**`Zookeeper::LOG_LEVEL_WARN`** Outputs errors/warnings
**`Zookeeper::LOG_LEVEL_INFO`** Outputs big action messages besides errors/warnings
**`Zookeeper::LOG_LEVEL_DEBUG`** Outputs all
ZooKeeper States
-----------------
**`Zookeeper::EXPIRED_SESSION_STATE`** Connected but session expired
**`Zookeeper::AUTH_FAILED_STATE`** Connected but auth failed
**`Zookeeper::CONNECTING_STATE`** Connecting
**`Zookeeper::ASSOCIATING_STATE`** Associating
**`Zookeeper::CONNECTED_STATE`** Connected
**`Zookeeper::READONLY_STATE`** TODO: help us improve this extension.
**`Zookeeper::NOTCONNECTED_STATE`** Connection failed
ZooKeeper Watch Types
----------------------
**`Zookeeper::CREATED_EVENT`** A node has been created
This is only generated by watches on non-existent nodes. These watches are set using Zookeeper::exists.
**`Zookeeper::DELETED_EVENT`** A node has been deleted
This is only generated by watches on nodes. These watches are set using Zookeeper::exists and Zookeeper::get.
**`Zookeeper::CHANGED_EVENT`** A node has changed
This is only generated by watches on nodes. These watches are set using Zookeeper::exists and Zookeeper::get.
**`Zookeeper::CHILD_EVENT`** A change as occurred in the list of children
This is only generated by watches on the child list of a node. These watches are set using Zookeeper::getChildren.
**`Zookeeper::SESSION_EVENT`** A session has been lost
This is generated when a client loses contact or reconnects with a server.
**`Zookeeper::NOTWATCHING_EVENT`** A watch has been removed
This is generated when the server for some reason, probably a resource constraint, will no longer watch a node for a client.
ZooKeeper System and Server-side Errors
----------------------------------------
**`Zookeeper::SYSTEMERROR`** This is never thrown by the server, it shouldn't be used other than to indicate a range. Specifically error codes greater than this value, but lesser than Zookeeper::APIERROR, are system errors.
**`Zookeeper::RUNTIMEINCONSISTENCY`** A runtime inconsistency was found.
**`Zookeeper::DATAINCONSISTENCY`** A data inconsistency was found.
**`Zookeeper::CONNECTIONLOSS`** Connection to the server has been lost.
**`Zookeeper::MARSHALLINGERROR`** Error while marshalling or unmarshalling data.
**`Zookeeper::UNIMPLEMENTED`** Operation is unimplemented.
**`Zookeeper::OPERATIONTIMEOUT`** Operation timeout.
**`Zookeeper::BADARGUMENTS`** Invalid arguments.
**`Zookeeper::INVALIDSTATE`** Invliad zhandle state.
**`Zookeeper::NEWCONFIGNOQUORUM`** No quorum of new config is connected and up-to-date with the leader of last committed config - try invoking reconfiguration after new servers are connected and synced.
Available as of ZooKeeper 3.5.0
**`Zookeeper::RECONFIGINPROGRESS`** Reconfiguration requested while another reconfiguration is currently in progress. This is currently not supported. Please retry.
Available as of ZooKeeper 3.5.0
ZooKeeper API Errors
---------------------
**`Zookeeper::OK`** Everything is OK.
**`Zookeeper::APIERROR`** This is never thrown by the server, it shouldn't be used other than to indicate a range. Specifically error codes greater than this value are API errors (while values less than this indicate a Zookeeper::SYSTEMERROR).
**`Zookeeper::NONODE`** Node does not exist.
**`Zookeeper::NOAUTH`** Not authenticated.
**`Zookeeper::BADVERSION`** Version conflict.
**`Zookeeper::NOCHILDRENFOREPHEMERALS`** Ephemeral nodes may not have children.
**`Zookeeper::NODEEXISTS`** The node already exists.
**`Zookeeper::NOTEMPTY`** The node has children.
**`Zookeeper::SESSIONEXPIRED`** The session has been expired by the server.
**`Zookeeper::INVALIDCALLBACK`** Invalid callback specified.
**`Zookeeper::INVALIDACL`** Invalid ACL specified.
**`Zookeeper::AUTHFAILED`** Client authentication failed.
**`Zookeeper::CLOSING`** ZooKeeper is closing.
**`Zookeeper::NOTHING`** (not error) No server responses to process.
**`Zookeeper::SESSIONMOVED`** Session moved to another server, so operation is ignored.
**`Zookeeper::NOTREADONLY`** State-changing request is passed to read-only server.
**`Zookeeper::EPHEMERALONLOCALSESSION`** Attempt to create ephemeral node on a local session.
**`Zookeeper::NOWATCHER`** The watcher couldn't be found.
**`Zookeeper::RECONFIGDISABLED`** Attempts to perform a reconfiguration operation when reconfiguration feature is disabled.
Table of Contents
-----------------
* [Zookeeper::addAuth](zookeeper.addauth) — Specify application credentials
* [Zookeeper::close](zookeeper.close) — Close the zookeeper handle and free up any resources
* [Zookeeper::connect](zookeeper.connect) — Create a handle to used communicate with zookeeper
* [Zookeeper::\_\_construct](zookeeper.construct) — Create a handle to used communicate with zookeeper
* [Zookeeper::create](zookeeper.create) — Create a node synchronously
* [Zookeeper::delete](zookeeper.delete) — Delete a node in zookeeper synchronously
* [Zookeeper::exists](zookeeper.exists) — Checks the existence of a node in zookeeper synchronously
* [Zookeeper::get](zookeeper.get) — Gets the data associated with a node synchronously
* [Zookeeper::getAcl](zookeeper.getacl) — Gets the acl associated with a node synchronously
* [Zookeeper::getChildren](zookeeper.getchildren) — Lists the children of a node synchronously
* [Zookeeper::getClientId](zookeeper.getclientid) — Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO\_CONNECTED\_STATE)
* [Zookeeper::getConfig](zookeeper.getconfig) — Get instance of ZookeeperConfig
* [Zookeeper::getRecvTimeout](zookeeper.getrecvtimeout) — Return the timeout for this session, only valid if the connections is currently connected (ie. last watcher state is ZOO\_CONNECTED\_STATE). This value may change after a server re-connect
* [Zookeeper::getState](zookeeper.getstate) — Get the state of the zookeeper connection
* [Zookeeper::isRecoverable](zookeeper.isrecoverable) — Checks if the current zookeeper connection state can be recovered
* [Zookeeper::set](zookeeper.set) — Sets the data associated with a node
* [Zookeeper::setAcl](zookeeper.setacl) — Sets the acl associated with a node synchronously
* [Zookeeper::setDebugLevel](zookeeper.setdebuglevel) — Sets the debugging level for the library
* [Zookeeper::setDeterministicConnOrder](zookeeper.setdeterministicconnorder) — Enable/disable quorum endpoint order randomization
* [Zookeeper::setLogStream](zookeeper.setlogstream) — Sets the stream to be used by the library for logging
* [Zookeeper::setWatcher](zookeeper.setwatcher) — Set a watcher function
| programming_docs |
php imagerotate imagerotate
===========
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
imagerotate — Rotate an image with a given angle
### Description
```
imagerotate(
GdImage $image,
float $angle,
int $background_color,
bool $ignore_transparent = false
): GdImage|false
```
Rotates the `image` image using the given `angle` in degrees.
The center of rotation is the center of the image, and the rotated image may have different dimensions than the original image.
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`angle`
Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image anticlockwise.
`background_color`
Specifies the color of the uncovered zone after the rotation
`ignore_transparent`
This parameter is unused.
### Return Values
Returns an image object for the rotated image, or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
| 8.0.0 | The unused `ignore_transparent` expects a bool now; previously it expected an int. |
### Examples
**Example #1 Rotate an image 180 degrees**
This example rotates an image 180 degrees - upside down.
```
<?php
// File and rotation
$filename = 'test.jpg';
$degrees = 180;
// Content type
header('Content-type: image/jpeg');
// Load
$source = imagecreatefromjpeg($filename);
// Rotate
$rotate = imagerotate($source, $degrees, 0);
// Output
imagejpeg($rotate);
// Free the memory
imagedestroy($source);
imagedestroy($rotate);
?>
```
The above example will output something similar to:
### Notes
>
> **Note**:
>
>
> This function is affected by the interpolation method set by [imagesetinterpolation()](function.imagesetinterpolation).
>
>
>
### See Also
* [imagesetinterpolation()](function.imagesetinterpolation) - Set the interpolation method
php xdiff_string_patch xdiff\_string\_patch
====================
(PECL xdiff >= 0.2.0)
xdiff\_string\_patch — Patch a string with an unified diff
### Description
```
xdiff_string_patch(
string $str,
string $patch,
int $flags = ?,
string &$error = ?
): string
```
Patches a `str` string with an unified patch in `patch` parameter and returns the result. `patch` has to be an unified diff created by [xdiff\_file\_diff()](function.xdiff-file-diff)/[xdiff\_string\_diff()](function.xdiff-string-diff) function. An optional `flags` parameter specifies mode of operation. Any rejected parts of the patch will be stored inside `error` variable if it is provided.
### Parameters
`str`
The original string.
`patch`
The unified patch string. It has to be created using [xdiff\_string\_diff()](function.xdiff-string-diff), [xdiff\_file\_diff()](function.xdiff-file-diff) functions or compatible tools.
`flags`
`flags` can be either **`XDIFF_PATCH_NORMAL`** (default mode, normal patch) or **`XDIFF_PATCH_REVERSE`** (reversed patch).
Starting from version 1.5.0, you can also use binary OR to enable **`XDIFF_PATCH_IGNORESPACE`** flag.
`error`
If provided then rejected parts are stored inside this variable.
### Return Values
Returns the patched string, or **`false`** on error.
### Examples
**Example #1 **xdiff\_string\_patch()** example**
The following code applies changes to some article.
```
<?php
$old_article = file_get_contents('./old_article.txt');
$diff = $_SERVER['patch']; /* Let's say that someone pasted a patch to html form */
$errors = '';
$new_article = xdiff_string_patch($old_article, $diff, XDIFF_PATCH_NORMAL, $errors);
if (is_string($new_article)) {
echo "New article:\n";
echo $new_article;
}
if (strlen($errors)) {
echo "Rejects: \n";
echo $errors;
}
?>
```
### See Also
* [xdiff\_string\_diff()](function.xdiff-string-diff) - Make unified diff of two strings
php PharFileInfo::getPharFlags PharFileInfo::getPharFlags
==========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)
PharFileInfo::getPharFlags — Returns the Phar file entry flags
### Description
```
public PharFileInfo::getPharFlags(): int
```
This returns the flags set in the manifest for a Phar. This will always return `0` in the current implementation.
### Parameters
This function has no parameters.
### Return Values
The Phar flags (always `0` in the current implementation)
### Examples
**Example #1 A **PharFileInfo::getPharFlags()** example**
```
<?php
try {
$p = new Phar('/path/to/my.phar', 0, 'my.phar');
$p['myfile.txt'] = 'hi';
$file = $p['myfile.txt'];
var_dump($file->getPharFlags());
} catch (Exception $e) {
echo 'Could not create/modify my.phar: ', $e;
}
?>
```
The above example will output:
```
int(0)
```
php V8JsException::getJsLineNumber V8JsException::getJsLineNumber
==============================
(PECL v8js >= 0.1.0)
V8JsException::getJsLineNumber — The getJsLineNumber purpose
### Description
```
final public V8JsException::getJsLineNumber(): int
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
php SolrQuery::setTermsMinCount SolrQuery::setTermsMinCount
===========================
(PECL solr >= 0.9.2)
SolrQuery::setTermsMinCount — Sets the minimum document frequency
### Description
```
public SolrQuery::setTermsMinCount(int $frequency): SolrQuery
```
Sets the minimum doc frequency to return in order to be included
### Parameters
`frequency`
The minimum frequency
### Return Values
Returns the current SolrQuery object, if the return value is used.
php Imagick::getImageChannelExtrema Imagick::getImageChannelExtrema
===============================
(PECL imagick 2, PECL imagick 3)
Imagick::getImageChannelExtrema — Gets the extrema for one or more image channels
**Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged.
### Description
```
public Imagick::getImageChannelExtrema(int $channel): array
```
Gets the extrema for one or more image channels. Return value is an associative array with the keys "minima" and "maxima".
### Parameters
`channel`
Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel).
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
php Gmagick::destroy Gmagick::destroy
================
(PECL gmagick >= Unknown)
Gmagick::destroy — The destroy purpose
### Description
```
public Gmagick::destroy(): bool
```
Destroys the [Gmagick](class.gmagick) object and frees all resources associated with it
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Errors/Exceptions
Throws an **GmagickException** on error.
php imagegrabscreen imagegrabscreen
===============
(PHP 5 >= 5.2.2, PHP 7, PHP 8)
imagegrabscreen — Captures the whole screen
### Description
```
imagegrabscreen(): GdImage|false
```
Grabs a screenshot of the whole screen.
>
> **Note**:
>
>
> This function is only available on Windows.
>
>
### Parameters
This function has no parameters.
### Return Values
Returns an image object on success, **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. |
### Examples
**Example #1 **imagegrabscreen()** example**
This example demonstrates how to take a screenshot of the current screen and save it as a png image.
```
<?php
$im = imagegrabscreen();
imagepng($im, "myscreenshot.png");
imagedestroy($im);
?>
```
### See Also
* [imagegrabwindow()](function.imagegrabwindow) - Captures a window
php EventHttp::setTimeout EventHttp::setTimeout
=====================
(PECL event >= 1.4.0-beta)
EventHttp::setTimeout — Sets the timeout for an HTTP request
### Description
```
public EventHttp::setTimeout( int $value ): void
```
Sets the timeout for an HTTP request.
### Parameters
`value` The timeout in seconds.
### Return Values
No value is returned.
php LimitIterator::__construct LimitIterator::\_\_construct
============================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
LimitIterator::\_\_construct — Construct a LimitIterator
### Description
public **LimitIterator::\_\_construct**([Iterator](class.iterator) `$iterator`, int `$offset` = 0, int `$limit` = -1) Constructs a new [LimitIterator](class.limititerator) from an `iterator` with a given starting `offset` and maximum `limit`.
### Parameters
`iterator`
The [Iterator](class.iterator) to limit.
`offset`
Optional offset of the limit.
`limit`
Optional count of the limit.
### Errors/Exceptions
Throws a [ValueError](class.valueerror) if the `offset` is less than `0` or the `limit` is less than `-1`.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | Now throws a [ValueError](class.valueerror) if `offset` is less than `0`; previously it threw a [RuntimeException](class.runtimeexception). |
| 8.0.0 | Now throws a [ValueError](class.valueerror) if `limit` is less than `-1`; previously it threw a [RuntimeException](class.runtimeexception). |
### Examples
**Example #1 **LimitIterator::\_\_construct()** example**
```
<?php
$ait = new ArrayIterator(array('a', 'b', 'c', 'd', 'e'));
$lit = new LimitIterator($ait, 1, 3);
foreach ($lit as $value) {
echo $value . "\n";
}
?>
```
The above example will output:
```
b
c
d
```
### See Also
* [LimitIterator examples](class.limititerator#limititerator.examples)
php Imagick::cycleColormapImage Imagick::cycleColormapImage
===========================
(PECL imagick 2, PECL imagick 3)
Imagick::cycleColormapImage — Displaces an image's colormap
### Description
```
public Imagick::cycleColormapImage(int $displace): bool
```
Displaces an image's colormap by a given number of positions. If you cycle the colormap a number of times you can produce a psychedelic effect.
### Parameters
`displace`
The amount to displace the colormap.
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
php GearmanJob::sendStatus GearmanJob::sendStatus
======================
(PECL gearman >= 0.6.0)
GearmanJob::sendStatus — Send status
### Description
```
public GearmanJob::sendStatus(int $numerator, int $denominator): bool
```
Sends status information to the job server and any listening clients. Use this to specify what percentage of the job has been completed.
### Parameters
`numerator`
The numerator of the precentage completed expressed as a fraction.
`denominator`
The denominator of the precentage completed expressed as a fraction.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [GearmanClient::jobStatus()](gearmanclient.jobstatus) - Get the status of a background job
* [GearmanTask::taskDenominator()](gearmantask.taskdenominator) - Get completion percentage denominator
* [GearmanTask::taskNumerator()](gearmantask.tasknumerator) - Get completion percentage numerator
php gmp_random gmp\_random
===========
(PHP 4 >= 4.0.4, PHP 5, PHP 7)
gmp\_random — Random number
**Warning**This function has been *DEPRECATED* as of PHP 7.2.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged.
### Description
```
gmp_random(int $limiter = 20): GMP
```
Generate a random number. The number will be between 0 and (2 \*\* n) - 1, where n is the number of bits per limb multiplied by `limiter`. If `limiter` is negative, negative numbers are generated.
A limb is an internal GMP mechanism. The number of bits in a limb is not static, and can vary from system to system. Generally, the number of bits in a limb is either 32 or 64, but this is not guaranteed.
### Parameters
`limiter`
The limiter.
A [GMP](class.gmp) object, an int or a numeric string.
### Return Values
A random GMP number.
### Examples
**Example #1 **gmp\_random()** example**
```
<?php
$rand1 = gmp_random(1); // random number from 0 to 1 * bits per limb
$rand2 = gmp_random(2); // random number from 0 to 2 * bits per limb
echo gmp_strval($rand1) . "\n";
echo gmp_strval($rand2) . "\n";
?>
```
The above example will output:
```
1915834968
8642564075890328087
```
php ftp_cdup ftp\_cdup
=========
(PHP 4, PHP 5, PHP 7, PHP 8)
ftp\_cdup — Changes to the parent directory
### Description
```
ftp_cdup(FTP\Connection $ftp): bool
```
Changes to the parent directory.
### Parameters
`ftp`
An [FTP\Connection](class.ftp-connection) instance.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **ftp\_cdup()** example**
```
<?php
// set up basic connection
$ftp = ftp_connect($ftp_server);
// login with username and password
$login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);
// change the current directory to html
ftp_chdir($ftp, 'html');
echo ftp_pwd($ftp); // /html
// return to the parent directory
if (ftp_cdup($ftp)) {
echo "cdup successful\n";
} else {
echo "cdup not successful\n";
}
echo ftp_pwd($ftp); // /
ftp_close($ftp);
?>
```
### See Also
* [ftp\_chdir()](function.ftp-chdir) - Changes the current directory on a FTP server
* [ftp\_pwd()](function.ftp-pwd) - Returns the current directory name
php array_chunk array\_chunk
============
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
array\_chunk — Split an array into chunks
### Description
```
array_chunk(array $array, int $length, bool $preserve_keys = false): array
```
Chunks an array into arrays with `length` elements. The last chunk may contain less than `length` elements.
### Parameters
`array`
The array to work on
`length`
The size of each chunk
`preserve_keys`
When set to **`true`** keys will be preserved. Default is **`false`** which will reindex the chunk numerically
### Return Values
Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing `length` elements.
### Errors/Exceptions
If `length` is less than `1`, a [ValueError](class.valueerror) will be thrown.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | If `length` is less than `1`, a [ValueError](class.valueerror) will be thrown now; previously, an error of level **`E_WARNING`** has been raised instead, and the function returned **`null`**. |
### Examples
**Example #1 **array\_chunk()** example**
```
<?php
$input_array = array('a', 'b', 'c', 'd', 'e');
print_r(array_chunk($input_array, 2));
print_r(array_chunk($input_array, 2, true));
?>
```
The above example will output:
```
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[2] => c
[3] => d
)
[2] => Array
(
[4] => e
)
)
```
### See Also
* [array\_slice()](function.array-slice) - Extract a slice of the array
php The WeakReference class
The WeakReference class
=======================
Introduction
------------
(PHP 7 >= 7.4.0, PHP 8)
Weak references allow the programmer to retain a reference to an object which does not prevent the object from being destroyed. They are useful for implementing cache like structures.
**WeakReference**s cannot be serialized.
Class synopsis
--------------
final class **WeakReference** { /\* Methods \*/ public [\_\_construct](weakreference.construct)()
```
public static create(object $object): WeakReference
```
```
public get(): ?object
```
} WeakReference Examples
----------------------
**Example #1 Basic WeakReference Usage**
```
<?php
$obj = new stdClass;
$weakref = WeakReference::create($obj);
var_dump($weakref->get());
unset($obj);
var_dump($weakref->get());
?>
```
The above example will output something similar to:
```
object(stdClass)#1 (0) {
}
NULL
```
Table of Contents
-----------------
* [WeakReference::\_\_construct](weakreference.construct) — Constructor that disallows instantiation
* [WeakReference::create](weakreference.create) — Create a new weak reference
* [WeakReference::get](weakreference.get) — Get a weakly referenced Object
php SplFileObject::hasChildren SplFileObject::hasChildren
==========================
(PHP 5 >= 5.1.2, PHP 7, PHP 8)
SplFileObject::hasChildren — SplFileObject does not have children
### Description
```
public SplFileObject::hasChildren(): false
```
An [SplFileObject](class.splfileobject) does not have children so this method always return **`false`**.
### Parameters
This function has no parameters.
### Return Values
Returns **`false`**
### See Also
* [RecursiveIterator::hasChildren()](recursiveiterator.haschildren) - Returns if an iterator can be created for the current entry
php pg_set_error_verbosity pg\_set\_error\_verbosity
=========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
pg\_set\_error\_verbosity — Determines the verbosity of messages returned by [pg\_last\_error()](function.pg-last-error) and [pg\_result\_error()](function.pg-result-error)
### Description
```
pg_set_error_verbosity(PgSql\Connection $connection = ?, int $verbosity): int
```
Determines the verbosity of messages returned by [pg\_last\_error()](function.pg-last-error) and [pg\_result\_error()](function.pg-result-error).
**pg\_set\_error\_verbosity()** sets the verbosity mode, returning the connection's previous setting. In **`PGSQL_ERRORS_TERSE`** mode, returned messages include severity, primary text, and position only; this will normally fit on a single line. The default mode (**`PGSQL_ERRORS_DEFAULT`**) produces messages that include the above plus any detail, hint, or context fields (these may span multiple lines). The **`PGSQL_ERRORS_VERBOSE`** mode includes all available fields. Changing the verbosity does not affect the messages available from already-existing result objects, only subsequently-created ones.
### Parameters
`connection`
An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect).
**Warning**As of PHP 8.1.0, using the default connection is deprecated.
`verbosity`
The required verbosity: **`PGSQL_ERRORS_TERSE`**, **`PGSQL_ERRORS_DEFAULT`** or **`PGSQL_ERRORS_VERBOSE`**.
### Return Values
The previous verbosity level: **`PGSQL_ERRORS_TERSE`**, **`PGSQL_ERRORS_DEFAULT`** or **`PGSQL_ERRORS_VERBOSE`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **pg\_set\_error\_verbosity()** example**
```
<?php
$dbconn = pg_connect("dbname=publisher") or die("Could not connect");
if (!pg_connection_busy($dbconn)) {
pg_send_query($dbconn, "select * from doesnotexist;");
}
pg_set_error_verbosity($dbconn, PGSQL_ERRORS_VERBOSE);
$res1 = pg_get_result($dbconn);
echo pg_result_error($res1);
?>
```
### See Also
* [pg\_last\_error()](function.pg-last-error) - Get the last error message string of a connection
* [pg\_result\_error()](function.pg-result-error) - Get error message associated with result
| programming_docs |
php Ds\Sequence::first Ds\Sequence::first
==================
(PECL ds >= 1.0.0)
Ds\Sequence::first — Returns the first value in the sequence
### Description
```
abstract public Ds\Sequence::first(): mixed
```
Returns the first value in the sequence.
### Parameters
This function has no parameters.
### Return Values
The first value in the sequence.
### Errors/Exceptions
[UnderflowException](class.underflowexception) if empty.
### Examples
**Example #1 **Ds\Sequence::first()** example**
```
<?php
$sequence = new \Ds\Vector([1, 2, 3]);
var_dump($sequence->first());
?>
```
The above example will output something similar to:
```
int(1)
```
php php_user_filter::onClose php\_user\_filter::onClose
==========================
(PHP 5, PHP 7, PHP 8)
php\_user\_filter::onClose — Called when closing the filter
### Description
```
public php_user_filter::onClose(): void
```
This method is called upon filter shutdown (typically, this is also during stream shutdown), and is executed *after* the `flush` method is called. If any resources were allocated or initialized during `onCreate()` this would be the time to destroy or dispose of them.
### Parameters
This function has no parameters.
### Return Values
Return value is ignored.
php ArrayObject::exchangeArray ArrayObject::exchangeArray
==========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
ArrayObject::exchangeArray — Exchange the array for another one
### Description
```
public ArrayObject::exchangeArray(array|object $array): array
```
Exchange the current array with another array or object.
### Parameters
`array`
The new array or object to exchange with the current array.
### Return Values
Returns the old array.
### Examples
**Example #1 **ArrayObject::exchangeArray()** example**
```
<?php
// Array of available fruits
$fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10);
// Array of locations in Europe
$locations = array('Amsterdam', 'Paris', 'London');
$fruitsArrayObject = new ArrayObject($fruits);
// Now exchange fruits for locations
$old = $fruitsArrayObject->exchangeArray($locations);
print_r($old);
print_r($fruitsArrayObject);
?>
```
The above example will output:
```
Array
(
[lemons] => 1
[oranges] => 4
[bananas] => 5
[apples] => 10
)
ArrayObject Object
(
[0] => Amsterdam
[1] => Paris
[2] => London
)
```
php hash_init hash\_init
==========
(PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL hash >= 1.1)
hash\_init — Initialize an incremental hashing context
### Description
```
hash_init(
string $algo,
int $flags = 0,
string $key = "",
array $options = []
): HashContext
```
### Parameters
`algo`
Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..). For a list of supported algorithms see [hash\_algos()](function.hash-algos).
`flags`
Optional settings for hash generation, currently supports only one option: **`HASH_HMAC`**. When specified, the `key` *must* be specified.
`key`
When **`HASH_HMAC`** is specified for `flags`, a shared secret key to be used with the HMAC hashing method must be supplied in this parameter.
`options`
An array of options for the various hashing algorithms. Currently, only the "seed" parameter is supported by the MurmurHash variants.
### Return Values
Returns a Hashing Context for use with [hash\_update()](function.hash-update), [hash\_update\_stream()](function.hash-update-stream), [hash\_update\_file()](function.hash-update-file), and [hash\_final()](function.hash-final).
### Errors/Exceptions
Throws a [ValueError](class.valueerror) exception if `algo` is unknown or is a non-cryptographic hash function, or if `key` is empty.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `options` parameter has been added. |
| 8.0.0 | Now throws an [ValueError](class.valueerror) exception if the `algo` is unknown or is a non-cryptographic hash function, or if `key` is empty. Previously, **`false`** was returned and an **`E_WARNING`** message was emitted. |
| 7.2.0 | Usage of non-cryptographic hash functions (adler32, crc32, crc32b, fnv132, fnv1a32, fnv164, fnv1a64, joaat) with **`HASH_HMAC`** was disabled. |
| 7.2.0 | Return [HashContext](class.hashcontext) instead of resource. |
### Examples
**Example #1 Incremental hashing example**
```
<?php
$ctx = hash_init('md5');
hash_update($ctx, 'The quick brown fox ');
hash_update($ctx, 'jumped over the lazy dog.');
echo hash_final($ctx);
?>
```
The above example will output:
```
5c6ffbdd40d9556b73a21e63c3e0e904
```
### See Also
* [hash()](function.hash) - Generate a hash value (message digest)
* [hash\_algos()](function.hash-algos) - Return a list of registered hashing algorithms
* [hash\_file()](function.hash-file) - Generate a hash value using the contents of a given file
* [hash\_hmac()](function.hash-hmac) - Generate a keyed hash value using the HMAC method
* [hash\_hmac\_file()](function.hash-hmac-file) - Generate a keyed hash value using the HMAC method and the contents of a given file
php XMLReader::moveToAttribute XMLReader::moveToAttribute
==========================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
XMLReader::moveToAttribute — Move cursor to a named attribute
### Description
```
public XMLReader::moveToAttribute(string $name): bool
```
Positions cursor on the named attribute.
### Parameters
`name`
The name of the attribute.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [XMLReader::moveToElement()](xmlreader.movetoelement) - Position cursor on the parent Element of current Attribute
* [XMLReader::moveToAttributeNo()](xmlreader.movetoattributeno) - Move cursor to an attribute by index
* [XMLReader::moveToAttributeNs()](xmlreader.movetoattributens) - Move cursor to a named attribute
* [XMLReader::moveToFirstAttribute()](xmlreader.movetofirstattribute) - Position cursor on the first Attribute
php gnupg_listsignatures gnupg\_listsignatures
=====================
(PECL gnupg >= 0.5)
gnupg\_listsignatures — List key signatures
### Description
```
gnupg_listsignatures(resource $identifier, string $keyid): array
```
### Parameters
`identifier`
The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**.
`keyid`
The key ID to list signatures for.
### Return Values
On success, this function returns an array of key signatures. On failure, this function returns **`null`**.
### Examples
**Example #1 Procedural **gnupg\_listsignatures()** example**
```
<?php
$res = gnupg_init();
$signatures = gnupg_listsignatures($res, "8660281B6051D071D94B5B230549F9DC851566DC");
print_r($signatures);
?>
```
**Example #2 OO **gnupg\_listsignatures()** example**
```
<?php
$gpg = new gnupg();
$signatures = $gpg->listsignatures("8660281B6051D071D94B5B230549F9DC851566DC");
print_r($signatures);
?>
```
php Gmagick::labelimage Gmagick::labelimage
===================
(PECL gmagick >= Unknown)
Gmagick::labelimage — Adds a label to an image
### Description
```
public Gmagick::labelimage(string $label): mixed
```
Adds a label to an image.
### Parameters
`label`
The label to add
### Return Values
Gmagick with label.
### Errors/Exceptions
Throws an **GmagickException** on error.
php xattr_list xattr\_list
===========
(PECL xattr >= 0.9.0)
xattr\_list — Get a list of extended attributes
### Description
```
xattr_list(string $filename, int $flags = 0): array
```
This functions gets a list of names of extended attributes of a file.
Extended attributes have two different namespaces: user and root. The user namespace is available to all users, while the root namespace is available only to users with root privileges. xattr operates on the user namespace by default, but this can be changed with the `flags` parameter.
### Parameters
`filename`
The path of the file.
`flags`
**Supported xattr flags**| **`XATTR_DONTFOLLOW`** | Do not follow the symbolic link but operate on symbolic link itself. |
| **`XATTR_ROOT`** | Set attribute in root (trusted) namespace. Requires root privileges. |
### Return Values
This function returns an array with names of extended attributes.
### Examples
**Example #1 Prints names of all extended attributes of file**
```
<?php
$file = 'some_file';
$root_attributes = xattr_list($file, XATTR_ROOT);
$user_attributes = xattr_list($file);
echo "Root attributes: \n";
foreach ($root_attributes as $attr_name) {
printf("%s\n", $attr_name);
}
echo "\n User attributes: \n";
foreach ($attributes as $attr_name) {
printf("%s\n", $attr_name);
}
?>
```
### See Also
* [xattr\_get()](function.xattr-get) - Get an extended attribute
php ReflectionClass::setStaticPropertyValue ReflectionClass::setStaticPropertyValue
=======================================
(PHP 5 >= 5.1.2, PHP 7, PHP 8)
ReflectionClass::setStaticPropertyValue — Sets static property value
### Description
```
public ReflectionClass::setStaticPropertyValue(string $name, mixed $value): void
```
Sets static property value.
### Parameters
`name`
Property name.
`value`
New property value.
### Return Values
No value is returned.
### See Also
* [ReflectionClass::getStaticPropertyValue()](reflectionclass.getstaticpropertyvalue) - Gets static property value
php tidy::getOpt tidy::getOpt
============
tidy\_getopt
============
(PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2)
tidy::getOpt -- tidy\_getopt — Returns the value of the specified configuration option for the tidy document
### Description
Object-oriented style
```
public tidy::getOpt(string $option): string|int|bool
```
Procedural style
```
tidy_getopt(tidy $tidy, string $option): string|int|bool
```
Returns the value of the specified `option` for the specified tidy `tidy`.
### Parameters
`tidy`
The [Tidy](class.tidy) object.
`option`
You will find a list with each configuration option and their types at: [» http://api.html-tidy.org/#quick-reference](http://api.html-tidy.org/#quick-reference).
### Return Values
Returns the value of the specified `option`. The return type depends on the type of the specified one.
### Examples
**Example #1 **tidy\_getopt()** example**
```
<?php
$html ='<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN">
<html><head><title>Title</title></head>
<body>
<p><img src="img.png"></p>
</body></html>';
$config = array('accessibility-check' => 3,
'alt-text' => 'some text');
$tidy = new tidy();
$tidy->parseString($html, $config);
var_dump($tidy->getOpt('accessibility-check')); //integer
var_dump($tidy->getOpt('lower-literals')); //boolean
var_dump($tidy->getOpt('alt-text')); //string
?>
```
The above example will output:
```
int(3)
bool(true)
string(9) "some text"
```
php sapi_windows_cp_set sapi\_windows\_cp\_set
======================
(PHP 7 >= 7.1.0, PHP 8)
sapi\_windows\_cp\_set — Set process codepage
### Description
```
sapi_windows_cp_set(int $codepage): bool
```
Set the codepage of the current process.
### Parameters
`codepage`
A codepage identifier.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [sapi\_windows\_cp\_get()](function.sapi-windows-cp-get) - Get current codepage
php rename rename
======
(PHP 4, PHP 5, PHP 7, PHP 8)
rename — Renames a file or directory
### Description
```
rename(string $from, string $to, ?resource $context = null): bool
```
Attempts to rename `from` to `to`, moving it between directories if necessary. If renaming a file and `to` exists, it will be overwritten. If renaming a directory and `to` exists, this function will emit a warning.
### Parameters
`from`
The old name.
>
> **Note**:
>
>
> The wrapper used in `from` *must* match the wrapper used in `to`.
>
>
`to`
The new name.
> **Note**: On Windows, if `to` already exists, it must be writable. Otherwise **rename()** fails and issues **`E_WARNING`**.
>
>
`context`
A [context stream](https://www.php.net/manual/en/stream.contexts.php) resource.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 Example with **rename()****
```
<?php
rename("/tmp/tmp_file.txt", "/home/user/login/docs/my_file.txt");
?>
```
### See Also
* [copy()](function.copy) - Copies file
* [unlink()](function.unlink) - Deletes a file
* [move\_uploaded\_file()](function.move-uploaded-file) - Moves an uploaded file to a new location
php The EventConfig class
The EventConfig class
=====================
Introduction
------------
(PECL event >= 1.2.6-beta)
Represents configuration structure which could be used in construction of the [EventBase](class.eventbase) .
Class synopsis
--------------
final class **EventConfig** { /\* Constants \*/ const int [FEATURE\_ET](class.eventconfig#eventconfig.constants.feature-et) = 1;
const int [FEATURE\_O1](class.eventconfig#eventconfig.constants.feature-o1) = 2;
const int [FEATURE\_FDS](class.eventconfig#eventconfig.constants.feature-fds) = 4; /\* Methods \*/
```
public avoidMethod( string $method ): bool
```
```
public __construct()
```
```
public requireFeatures( int $feature ): bool
```
```
public setFlags( int $flags ): bool
```
```
public setMaxDispatchInterval( int $max_interval , int $max_callbacks , int $min_priority ): void
```
} Predefined Constants
--------------------
**`EventConfig::FEATURE_ET`** Requires a backend method that supports edge-triggered I/O.
**`EventConfig::FEATURE_O1`** Requires a backend method where adding or deleting a single event, or having a single event become active, is an O(1) operation.
**`EventConfig::FEATURE_FDS`** Requires a backend method that can support arbitrary file descriptor types, and not just sockets.
Table of Contents
-----------------
* [EventConfig::avoidMethod](eventconfig.avoidmethod) — Tells libevent to avoid specific event method
* [EventConfig::\_\_construct](eventconfig.construct) — Constructs EventConfig object
* [EventConfig::requireFeatures](eventconfig.requirefeatures) — Enters a required event method feature that the application demands
* [EventConfig::setFlags](eventconfig.setflags) — Sets one or more flags to configure the eventual EventBase will be initialized
* [EventConfig::setMaxDispatchInterval](eventconfig.setmaxdispatchinterval) — Prevents priority inversion
php stats_dens_weibull stats\_dens\_weibull
====================
(PECL stats >= 1.0.0)
stats\_dens\_weibull — Probability density function of the Weibull distribution
### Description
```
stats_dens_weibull(float $x, float $a, float $b): float
```
Returns the probability density at `x`, where the random variable follows the Weibull distribution of which the shape parameter is `a` and the scale parameter is `b`.
### Parameters
`x`
The value at which the probability density is calculated
`a`
The shape parameter of the distribution
`b`
The scale parameter of the distribution
### Return Values
The probability density at `x` or **`false`** for failure.
php None Using namespaces: fallback to global function/constant
------------------------------------------------------
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
Inside a namespace, when PHP encounters an unqualified Name in a class name, function or constant context, it resolves these with different priorities. Class names always resolve to the current namespace name. Thus to access internal or non-namespaced user classes, one must refer to them with their fully qualified Name as in:
**Example #1 Accessing global classes inside a namespace**
```
<?php
namespace A\B\C;
class Exception extends \Exception {}
$a = new Exception('hi'); // $a is an object of class A\B\C\Exception
$b = new \Exception('hi'); // $b is an object of class Exception
$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>
```
For functions and constants, PHP will fall back to global functions or constants if a namespaced function or constant does not exist.
**Example #2 global functions/constants fallback inside a namespace**
```
<?php
namespace A\B\C;
const E_ERROR = 45;
function strlen($str)
{
return \strlen($str) - 1;
}
echo E_ERROR, "\n"; // prints "45"
echo INI_ALL, "\n"; // prints "7" - falls back to global INI_ALL
echo strlen('hi'), "\n"; // prints "1"
if (is_array('hi')) { // prints "is not array"
echo "is array\n";
} else {
echo "is not array\n";
}
?>
```
php AppendIterator::rewind AppendIterator::rewind
======================
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
AppendIterator::rewind — Rewinds the Iterator
### Description
```
public AppendIterator::rewind(): void
```
Rewind to the first element of the first inner Iterator.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
### See Also
* [Iterator::rewind()](iterator.rewind) - Rewind the Iterator to the first element
* [AppendIterator::current()](appenditerator.current) - Gets the current value
* [AppendIterator::key()](appenditerator.key) - Gets the current key
* [AppendIterator::next()](appenditerator.next) - Moves to the next element
* [AppendIterator::valid()](appenditerator.valid) - Checks validity of the current element
php Expressions
Expressions
===========
Expressions are the most important building blocks of PHP. In PHP, almost anything you write is an expression. The simplest yet most accurate way to define an expression is "anything that has a value".
The most basic forms of expressions are constants and variables. When you type `$a = 5`, you're assigning `5` into $a. `5`, obviously, has the value 5, or in other words `5` is an expression with the value of 5 (in this case, `5` is an integer constant).
After this assignment, you'd expect $a's value to be 5 as well, so if you wrote `$b = $a`, you'd expect it to behave just as if you wrote `$b = 5`. In other words, $a is an expression with the value of 5 as well. If everything works right, this is exactly what will happen.
Slightly more complex examples for expressions are functions. For instance, consider the following function:
```
<?php
function foo ()
{
return 5;
}
?>
```
Assuming you're familiar with the concept of functions (if you're not, take a look at the chapter about [functions](https://www.php.net/manual/en/language.functions.php)), you'd assume that typing `$c = foo()` is essentially just like writing `$c = 5`, and you're right. Functions are expressions with the value of their return value. Since `foo()` returns 5, the value of the expression '`foo()`' is 5. Usually functions don't just return a static value but compute something.
Of course, values in PHP don't have to be integers, and very often they aren't. PHP supports four scalar value types: int values, floating point values (float), string values and bool values (scalar values are values that you can't 'break' into smaller pieces, unlike arrays, for instance). PHP also supports two composite (non-scalar) types: arrays and objects. Each of these value types can be assigned into variables or returned from functions.
PHP takes expressions much further, in the same way many other languages do. PHP is an expression-oriented language, in the sense that almost everything is an expression. Consider the example we've already dealt with, `$a = 5`. It's easy to see that there are two values involved here, the value of the integer constant `5`, and the value of $a which is being updated to 5 as well. But the truth is that there's one additional value involved here, and that's the value of the assignment itself. The assignment itself evaluates to the assigned value, in this case 5. In practice, it means that `$a = 5`, regardless of what it does, is an expression with the value 5. Thus, writing something like `$b = ($a = 5)` is like writing `$a = 5; $b = 5;` (a semicolon marks the end of a statement). Since assignments are parsed in a right to left order, you can also write `$b = $a = 5`.
Another good example of expression orientation is pre- and post-increment and decrement. Users of PHP and many other languages may be familiar with the notation of `variable++` and `variable--`. These are [increment and decrement operators](language.operators.increment). In PHP, like in C, there are two types of increment - pre-increment and post-increment. Both pre-increment and post-increment essentially increment the variable, and the effect on the variable is identical. The difference is with the value of the increment expression. Pre-increment, which is written `++$variable`, evaluates to the incremented value (PHP increments the variable before reading its value, thus the name 'pre-increment'). Post-increment, which is written `$variable++` evaluates to the original value of $variable, before it was incremented (PHP increments the variable after reading its value, thus the name 'post-increment').
A very common type of expressions are [comparison](language.operators.comparison) expressions. These expressions evaluate to either **`false`** or **`true`**. PHP supports > (bigger than), >= (bigger than or equal to), == (equal), != (not equal), < (smaller than) and <= (smaller than or equal to). The language also supports a set of strict equivalence operators: === (equal to and same type) and !== (not equal to or not same type). These expressions are most commonly used inside conditional execution, such as `if` statements.
The last example of expressions we'll deal with here is combined operator-assignment expressions. You already know that if you want to increment $a by 1, you can simply write `$a++` or `++$a`. But what if you want to add more than one to it, for instance 3? You could write `$a++` multiple times, but this is obviously not a very efficient or comfortable way. A much more common practice is to write `$a =
$a + 3`. `$a + 3` evaluates to the value of $a plus 3, and is assigned back into $a, which results in incrementing $a by 3. In PHP, as in several other languages like C, you can write this in a shorter way, which with time would become clearer and quicker to understand as well. Adding 3 to the current value of $a can be written `$a += 3`. This means exactly "take the value of $a, add 3 to it, and assign it back into $a". In addition to being shorter and clearer, this also results in faster execution. The value of `$a += 3`, like the value of a regular assignment, is the assigned value. Notice that it is NOT 3, but the combined value of $a plus 3 (this is the value that's assigned into $a). Any two-place operator can be used in this operator-assignment mode, for example `$a -= 5` (subtract 5 from the value of $a), `$b *= 7` (multiply the value of $b by 7), etc.
There is one more expression that may seem odd if you haven't seen it in other languages, the ternary conditional operator:
```
<?php
$first ? $second : $third
?>
```
If the value of the first subexpression is **`true`** (non-zero), then the second subexpression is evaluated, and that is the result of the conditional expression. Otherwise, the third subexpression is evaluated, and that is the value.
The following example should help you understand pre- and post-increment and expressions in general a bit better:
```
<?php
function double($i)
{
return $i*2;
}
$b = $a = 5; /* assign the value five into the variable $a and $b */
$c = $a++; /* post-increment, assign original value of $a
(5) to $c */
$e = $d = ++$b; /* pre-increment, assign the incremented value of
$b (6) to $d and $e */
/* at this point, both $d and $e are equal to 6 */
$f = double($d++); /* assign twice the value of $d before
the increment, 2*6 = 12 to $f */
$g = double(++$e); /* assign twice the value of $e after
the increment, 2*7 = 14 to $g */
$h = $g += 10; /* first, $g is incremented by 10 and ends with the
value of 24. the value of the assignment (24) is
then assigned into $h, and $h ends with the value
of 24 as well. */
?>
```
Some expressions can be considered as statements. In this case, a statement has the form of '`expr ;`' that is, an expression followed by a semicolon. In `$b = $a = 5;`, `$a = 5` is a valid expression, but it's not a statement by itself. `$b = $a = 5;`, however, is a valid statement.
One last thing worth mentioning is the truth value of expressions. In many events, mainly in conditional execution and loops, you're not interested in the specific value of the expression, but only care about whether it means **`true`** or **`false`**. The constants **`true`** and **`false`** (case-insensitive) are the two possible boolean values. When necessary, an expression is automatically converted to boolean. See the [section about type-casting](language.types.type-juggling#language.types.typecasting) for details about how.
PHP provides a full and powerful implementation of expressions, and documenting it entirely goes beyond the scope of this manual. The above examples should give you a good idea about what expressions are and how you can construct useful expressions. Throughout the rest of this manual we'll write expr to indicate any valid PHP expression.
| programming_docs |
php Imagick::setImageDelay Imagick::setImageDelay
======================
(PECL imagick 2, PECL imagick 3)
Imagick::setImageDelay — Sets the image delay
### Description
```
public Imagick::setImageDelay(int $delay): bool
```
Sets the image delay. For an animated image this is the amount of time that this frame of the image should be displayed for, before displaying the next frame.
The delay can be set individually for each frame in an image.
### Parameters
`delay`
The amount of time expressed in 'ticks' that the image should be displayed for. For animated GIFs there are 100 ticks per second, so a value of 20 would be 20/100 of a second aka 1/5th of a second.
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
### Examples
**Example #1 Modify animated Gif with **Imagick::setImageDelay()****
```
<?php
// Modify an animated Gif so that it's frames are played at a variable speed,
// varying between being shown for 50ms down to 0ms, which will cause the frame
// to be skipped in most browsers.
$imagick = new Imagick(realpath("Test.gif"));
$imagick = $imagick->coalesceImages();
$frameCount = 0;
foreach ($imagick as $frame) {
$imagick->setImageDelay((($frameCount % 11) * 5));
$frameCount++;
}
$imagick = $imagick->deconstructImages();
$imagick->writeImages("/path/to/save/output.gif", true);
?>
```
php gnupg_encryptsign gnupg\_encryptsign
==================
(PECL gnupg >= 0.2)
gnupg\_encryptsign — Encrypts and signs a given text
### Description
```
gnupg_encryptsign(resource $identifier, string $plaintext): string
```
Encrypts and signs the given `plaintext` with the keys, which were set with [gnupg\_addsignkey](function.gnupg-addsignkey) and [gnupg\_addencryptkey](function.gnupg-addencryptkey) before and returns the encrypted and signed text.
### Parameters
`identifier`
The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**.
`plaintext`
The text being encrypted.
### Return Values
On success, this function returns the encrypted and signed text. On failure, this function returns **`false`**.
### Examples
**Example #1 Procedural **gnupg\_encryptsign()** example**
```
<?php
$res = gnupg_init();
gnupg_addencryptkey($res,"8660281B6051D071D94B5B230549F9DC851566DC");
gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = gnupg_encryptsign($res, "just a test");
echo $enc;
?>
```
**Example #2 OO **gnupg\_encryptsign()** example**
```
<?php
$gpg = new gnupg();
$gpg->addencryptkey("8660281B6051D071D94B5B230549F9DC851566DC");
$gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test");
$enc = $gpg->encryptsign("just a test");
echo $enc;
?>
```
php SoapClient::__getLastRequest SoapClient::\_\_getLastRequest
==============================
(PHP 5, PHP 7, PHP 8)
SoapClient::\_\_getLastRequest — Returns last SOAP request
### Description
```
public SoapClient::__getLastRequest(): ?string
```
Returns the XML sent in the last SOAP request.
>
> **Note**:
>
>
> This method works only if the [SoapClient](class.soapclient) object was created with the `trace` option set to **`true`**.
>
>
### Parameters
This function has no parameters.
### Return Values
The last SOAP request, as an XML string.
### Examples
**Example #1 SoapClient::\_\_getLastRequest() example**
```
<?php
$client = new SoapClient("some.wsdl", array('trace' => 1));
$result = $client->SomeFunction();
echo "REQUEST:\n" . $client->__getLastRequest() . "\n";
?>
```
### See Also
* [SoapClient::\_\_getLastRequestHeaders()](soapclient.getlastrequestheaders) - Returns the SOAP headers from the last request
* [SoapClient::\_\_getLastResponse()](soapclient.getlastresponse) - Returns last SOAP response
* [SoapClient::\_\_getLastResponseHeaders()](soapclient.getlastresponseheaders) - Returns the SOAP headers from the last response
php arsort arsort
======
(PHP 4, PHP 5, PHP 7, PHP 8)
arsort — Sort an array in descending order and maintain index association
### Description
```
arsort(array &$array, int $flags = SORT_REGULAR): bool
```
Sorts `array` in place in descending order, such that its keys maintain their correlation with the values they are associated with.
This is used mainly when sorting associative arrays where the actual element order is significant.
>
> **Note**:
>
>
> If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
>
>
>
> **Note**:
>
>
> Resets array's internal pointer to the first element.
>
>
### Parameters
`array`
The input array.
`flags`
The optional second parameter `flags` may be used to modify the sorting behavior using these values:
Sorting type flags:
* **`SORT_REGULAR`** - compare items normally; the details are described in the [comparison operators](language.operators.comparison) section
* **`SORT_NUMERIC`** - compare items numerically
* **`SORT_STRING`** - compare items as strings
* **`SORT_LOCALE_STRING`** - compare items as strings, based on the current locale. It uses the locale, which can be changed using [setlocale()](function.setlocale)
* **`SORT_NATURAL`** - compare items as strings using "natural ordering" like [natsort()](function.natsort)
* **`SORT_FLAG_CASE`** - can be combined (bitwise OR) with **`SORT_STRING`** or **`SORT_NATURAL`** to sort strings case-insensitively
### Return Values
Always returns **`true`**.
### Examples
**Example #1 **arsort()** example**
```
<?php
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple");
arsort($fruits);
foreach ($fruits as $key => $val) {
echo "$key = $val\n";
}
?>
```
The above example will output:
```
a = orange
d = lemon
b = banana
c = apple
```
The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained.
### See Also
* [sort()](function.sort) - Sort an array in ascending order
* [asort()](function.asort) - Sort an array in ascending order and maintain index association
* The [comparison of array sorting functions](https://www.php.net/manual/en/array.sorting.php)
php Gmagick::setimagecolorspace Gmagick::setimagecolorspace
===========================
(PECL gmagick >= Unknown)
Gmagick::setimagecolorspace — Sets the image colorspace
### Description
```
public Gmagick::setimagecolorspace(int $colorspace): Gmagick
```
Sets the image colorspace.
### Parameters
`colorspace`
One of the [Colorspace](https://www.php.net/manual/en/gmagick.constants.php#gmagick.constants.colorspace) constant (`Gmagick::COLORSPACE_*`).
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php The Volatile class
The Volatile class
==================
Introduction
------------
(PECL pthreads >= 3.0.0)
The **Volatile** class is new to pthreads v3. Its introduction is a consequence of the new immutability semantics of [Threaded](class.threaded) members of [Threaded](class.threaded) classes. The **Volatile** class enables for mutability of its [Threaded](class.threaded) members, and is also used to store PHP arrays in [Threaded](class.threaded) contexts.
Class synopsis
--------------
class **Volatile** extends [Threaded](class.threaded) implements [Collectable](class.collectable), [Traversable](class.traversable) { /\* Inherited methods \*/
```
public Threaded::chunk(int $size, bool $preserve): array
```
```
public Threaded::count(): int
```
```
public Threaded::extend(string $class): bool
```
```
public Threaded::isRunning(): bool
```
```
public Threaded::isTerminated(): bool
```
```
public Threaded::merge(mixed $from, bool $overwrite = ?): bool
```
```
public Threaded::notify(): bool
```
```
public Threaded::notifyOne(): bool
```
```
public Threaded::pop(): bool
```
```
public Threaded::run(): void
```
```
public Threaded::shift(): mixed
```
```
public Threaded::synchronized(Closure $block, mixed ...$args): mixed
```
```
public Threaded::wait(int $timeout = ?): bool
```
} Examples
--------
**Example #1 New immutability semantics of Threaded**
```
<?php
class Task extends Threaded
{
public function __construct()
{
$this->data = new Threaded();
// attempt to overwrite a Threaded property of a Threaded class (invalid)
$this->data = new StdClass();
}
}
var_dump((new Task())->data);
```
The above example will output something similar to:
```
RuntimeException: Threaded members previously set to Threaded objects are immutable, cannot overwrite data in %s:%d
```
**Example #2 Volatile use-case**
```
<?php
class Task extends Volatile
{
public function __construct()
{
$this->data = new Threaded();
// attempt to overwrite a Threaded property of a Volatile class (valid)
$this->data = new StdClass();
}
}
var_dump((new Task())->data);
```
The above example will output something similar to:
```
object(stdClass)#3 (0) {
}
```
php SolrQuery::addStatsFacet SolrQuery::addStatsFacet
========================
(PECL solr >= 0.9.2)
SolrQuery::addStatsFacet — Requests a return of sub results for values within the given facet
### Description
```
public SolrQuery::addStatsFacet(string $field): SolrQuery
```
Requests a return of sub results for values within the given facet. Maps to the stats.facet field
### Parameters
`field`
The name of the field
### Return Values
Returns the current SolrQuery object, if the return value is used.
php Memcached::addServer Memcached::addServer
====================
(PECL memcached >= 0.1.0)
Memcached::addServer — Add a server to the server pool
### Description
```
public Memcached::addServer(string $host, int $port, int $weight = 0): bool
```
**Memcached::addServer()** adds the specified server to the server pool. No connection is established to the server at this time, but if you are using consistent key distribution option (via **`Memcached::DISTRIBUTION_CONSISTENT`** or **`Memcached::OPT_LIBKETAMA_COMPATIBLE`**), some of the internal data structures will have to be updated. Thus, if you need to add multiple servers, it is better to use [Memcached::addServers()](memcached.addservers) as the update then happens only once.
The same server may appear multiple times in the server pool, because no duplication checks are made. This is not advisable; instead, use the `weight` option to increase the selection weighting of this server.
### Parameters
`host`
The hostname of the memcache server. If the hostname is invalid, data-related operations will set **`Memcached::RES_HOST_LOOKUP_FAILURE`** result code. As of version 2.0.0b1, this parameter may also specify the path of a unix socket filepath ex. `/path/to/memcached.sock` to use UNIX domain sockets, in this case `port` must also be set to `0`.
`port`
The port on which memcache is running. Usually, this is `11211`. As of version 2.0.0b1, set this parameter to `0` when using UNIX domain sockets.
`weight`
The weight of the server relative to the total weight of all the servers in the pool. This controls the probability of the server being selected for operations. This is used only with consistent distribution option and usually corresponds to the amount of memory available to memcache on that server.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **Memcached::addServer()** example**
```
<?php
$m = new Memcached();
/* Add 2 servers, so that the second one
is twice as likely to be selected. */
$m->addServer('mem1.domain.com', 11211, 33);
$m->addServer('mem2.domain.com', 11211, 67);
?>
```
### See Also
* [Memcached::addServers()](memcached.addservers) - Add multiple servers to the server pool
* [Memcached::resetServerList()](memcached.resetserverlist) - Clears all servers from the server list
php Imagick::hasNextImage Imagick::hasNextImage
=====================
(PECL imagick 2, PECL imagick 3)
Imagick::hasNextImage — Checks if the object has more images
### Description
```
public Imagick::hasNextImage(): bool
```
Returns **`true`** if the object has more images when traversing the list in the forward direction.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** if the object has more images when traversing the list in the forward direction, returns **`false`** if there are none.
php stats_cdf_beta stats\_cdf\_beta
================
(PECL stats >= 1.0.0)
stats\_cdf\_beta — Calculates any one parameter of the beta distribution given values for the others
### Description
```
stats_cdf_beta(
float $par1,
float $par2,
float $par3,
int $which
): float
```
Returns the cumulative distribution function, its inverse, or one of its parameters, of the beta distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.
The following table lists the return value and parameters by `which`. CDF, x, alpha, and beta denotes cumulative distribution function, the value of the random variable, and shape parameters of the beta distribution, respectively.
**Return value and parameters**| `which` | Return value | `par1` | `par2` | `par3` |
| --- | --- | --- | --- | --- |
| 1 | CDF | x | alpha | beta |
| 2 | x | CDF | alpha | beta |
| 3 | alpha | x | CDF | beta |
| 4 | beta | x | CDF | alpha |
### Parameters
`par1`
The first parameter
`par2`
The second parameter
`par3`
The third parameter
`which`
The flag to determine what to be calculated
### Return Values
Returns CDF, x, alpha, or beta, determined by `which`.
php mkdir mkdir
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
mkdir — Makes directory
### Description
```
mkdir(
string $directory,
int $permissions = 0777,
bool $recursive = false,
?resource $context = null
): bool
```
Attempts to create the directory specified by `directory`.
### Parameters
`directory`
The directory path.
**Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
`permissions`
The permissions are 0777 by default, which means the widest possible access. For more information on permissions, read the details on the [chmod()](function.chmod) page.
>
> **Note**:
>
>
> `permissions` is ignored on Windows.
>
>
Note that you probably want to specify the `permissions` as an octal number, which means it should have a leading zero. The `permissions` is also modified by the current umask, which you can change using [umask()](function.umask).
`recursive`
If **`true`**, then any parent directories to the `directory` specified will also be created, with the same permissions.
`context`
A [context stream](https://www.php.net/manual/en/stream.contexts.php) resource.
### Return Values
Returns **`true`** on success or **`false`** on failure.
>
> **Note**:
>
>
> If the directory to be created already exists, that is considered an error and **`false`** will still be returned. Use [is\_dir()](function.is-dir) or [file\_exists()](function.file-exists) to check if the directory already exists before trying to create it.
>
>
### Errors/Exceptions
Emits an **`E_WARNING`** level error if the directory already exists.
Emits an **`E_WARNING`** level error if the relevant permissions prevent creating the directory.
### Examples
**Example #1 **mkdir()** example**
```
<?php
mkdir("/path/to/my/dir", 0700);
?>
```
**Example #2 **mkdir()** using the `recursive` parameter**
```
<?php
// Desired directory structure
$structure = './depth1/depth2/depth3/';
// To create the nested structure, the $recursive parameter
// to mkdir() must be specified.
if (!mkdir($structure, 0777, true)) {
die('Failed to create directories...');
}
// ...
?>
```
### See Also
* [is\_dir()](function.is-dir) - Tells whether the filename is a directory
* [rmdir()](function.rmdir) - Removes directory
* [umask()](function.umask) - Changes the current umask
php Imagick::setImageColormapColor Imagick::setImageColormapColor
==============================
(PECL imagick 2, PECL imagick 3)
Imagick::setImageColormapColor — Sets the color of the specified colormap index
### Description
```
public Imagick::setImageColormapColor(int $index, ImagickPixel $color): bool
```
Sets the color of the specified colormap index.
### Parameters
`index`
`color`
### Return Values
Returns **`true`** on success.
### Errors/Exceptions
Throws ImagickException on error.
php wddx_serialize_vars wddx\_serialize\_vars
=====================
(PHP 4, PHP 5, PHP 7)
wddx\_serialize\_vars — Serialize variables into a WDDX packet
**Warning**This function was *REMOVED* in PHP 7.4.0.
### Description
```
wddx_serialize_vars(mixed $var_name, mixed ...$var_names): string
```
Creates a WDDX packet with a structure that contains the serialized representation of the passed variables.
### Parameters
This function takes a variable number of parameters.
`var_name`
Can be either a string naming a variable or an array containing strings naming the variables or another array, etc.
`var_names`
### Return Values
Returns the WDDX packet, or **`false`** on error.
### Examples
**Example #1 **wddx\_serialize\_vars()** example**
```
<?php
$a = 1;
$b = 5.5;
$c = array("blue", "orange", "violet");
$d = "colors";
$clvars = array("c", "d");
echo wddx_serialize_vars("a", "b", $clvars);
?>
```
The above example will output:
```
<wddxPacket version='1.0'><header/><data><struct><var name='a'><number>1</number></var>
<var name='b'><number>5.5</number></var><var name='c'><array length='3'>
<string>blue</string><string>orange</string><string>violet</string></array></var>
<var name='d'><string>colors</string></var></struct></data></wddxPacket>
```
php phpdbg_end_oplog phpdbg\_end\_oplog
==================
(PHP 7, PHP 8)
phpdbg\_end\_oplog —
### Description
```
phpdbg_end_oplog(array $options = []): ?array
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`options`
### Return Values
php str_pad str\_pad
========
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
str\_pad — Pad a string to a certain length with another string
### Description
```
str_pad(
string $string,
int $length,
string $pad_string = " ",
int $pad_type = STR_PAD_RIGHT
): string
```
This function returns the `string` string padded on the left, the right, or both sides to the specified padding length. If the optional argument `pad_string` is not supplied, the `string` is padded with spaces, otherwise it is padded with characters from `pad_string` up to the limit.
### Parameters
`string`
The input string.
`length`
If the value of `length` is negative, less than, or equal to the length of the input string, no padding takes place, and `string` will be returned.
`pad_string`
>
> **Note**:
>
>
> The `pad_string` may be truncated if the required number of padding characters can't be evenly divided by the `pad_string`'s length.
>
>
`pad_type`
Optional argument `pad_type` can be **`STR_PAD_RIGHT`**, **`STR_PAD_LEFT`**, or **`STR_PAD_BOTH`**. If `pad_type` is not specified it is assumed to be **`STR_PAD_RIGHT`**.
### Return Values
Returns the padded string.
### Examples
**Example #1 **str\_pad()** example**
```
<?php
$input = "Alien";
echo str_pad($input, 10); // produces "Alien "
echo str_pad($input, 10, "-=", STR_PAD_LEFT); // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH); // produces "__Alien___"
echo str_pad($input, 6, "___"); // produces "Alien_"
echo str_pad($input, 3, "*"); // produces "Alien"
?>
```
| programming_docs |
php Yaf_Request_Abstract::setRouted Yaf\_Request\_Abstract::setRouted
=================================
(Yaf >=1.0.0)
Yaf\_Request\_Abstract::setRouted — The setRouted purpose
### Description
```
public Yaf_Request_Abstract::setRouted(string $flag = ?): void
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`flag`
### Return Values
php SNMP::getErrno SNMP::getErrno
==============
(PHP 5 >= 5.4.0, PHP 7, PHP 8)
SNMP::getErrno — Get last error code
### Description
```
public SNMP::getErrno(): int
```
Returns error code from last SNMP request.
### Parameters
This function has no parameters.
### Return Values
Returns one of SNMP error code values described in constants chapter.
### Examples
**Example #1 **SNMP::getErrno()** example**
```
<?php
$session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity');
var_dump(@$session->get('.1.3.6.1.2.1.1.1.0'));
var_dump($session->getErrno() == SNMP::ERRNO_TIMEOUT);
?>
```
The above example will output:
```
bool(false)
bool(true)
```
### See Also
* [SNMP::getError()](snmp.geterror) - Get last error message
php wincache_ucache_inc wincache\_ucache\_inc
=====================
(PECL wincache >= 1.1.0)
wincache\_ucache\_inc — Increments the value associated with the key
### Description
```
wincache_ucache_inc(string $key, int $inc_by = 1, bool &$success = ?): mixed
```
Increments the value associated with the `key` by 1 or as specified by `inc_by`.
### Parameters
`key`
The `key` that was used to store the variable in the cache. `key` is case sensitive.
`inc_by`
The value by which the variable associated with the `key` will get incremented. If the argument is a floating point number it will be truncated to nearest integer. The variable associated with the `key` should be of type `long`, otherwise the function fails and returns **`false`**.
`success`
Will be set to **`true`** on success and **`false`** on failure.
### Return Values
Returns the incremented value on success and **`false`** on failure.
### Examples
**Example #1 Using **wincache\_ucache\_inc()****
```
<?php
wincache_ucache_set('counter', 1);
var_dump(wincache_ucache_inc('counter', 2921, $success));
var_dump($success);
?>
```
The above example will output:
```
int(2922)
bool(true)
```
### See Also
* [wincache\_ucache\_dec()](function.wincache-ucache-dec) - Decrements the value associated with the key
* [wincache\_ucache\_cas()](function.wincache-ucache-cas) - Compares the variable with old value and assigns new value to it
php ctype_space ctype\_space
============
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
ctype\_space — Check for whitespace character(s)
### Description
```
ctype_space(mixed $text): bool
```
Checks if all of the characters in the provided string, `text`, creates whitespace.
### Parameters
`text`
The tested string.
>
> **Note**:
>
>
> If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer.
>
>
>
**Warning** As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to [chr()](function.chr) should be made.
### Return Values
Returns **`true`** if every character in `text` creates some sort of white space, **`false`** otherwise. Besides the blank character this also includes tab, vertical tab, line feed, carriage return and form feed characters. When called with an empty string the result will always be **`false`**.
### Examples
**Example #1 A **ctype\_space()** example**
```
<?php
$strings = array(
'string1' => "\n\r\t",
'string2' => "\narf12",
'string3' => '\n\r\t' // note the single quotes
);
foreach ($strings as $name => $testcase) {
if (ctype_space($testcase)) {
echo "The string '$name' consists of whitespace characters only.\n";
} else {
echo "The string '$name' contains non-whitespace characters.\n";
}
}
?>
```
The above example will output:
```
The string 'string1' consists of whitespace characters only.
The string 'string2' contains non-whitespace characters.
The string 'string3' contains non-whitespace characters.
```
### See Also
* [ctype\_cntrl()](function.ctype-cntrl) - Check for control character(s)
* [ctype\_graph()](function.ctype-graph) - Check for any printable character(s) except space
* [ctype\_punct()](function.ctype-punct) - Check for any printable character which is not whitespace or an alphanumeric character
php posix_getuid posix\_getuid
=============
(PHP 4, PHP 5, PHP 7, PHP 8)
posix\_getuid — Return the real user ID of the current process
### Description
```
posix_getuid(): int
```
Return the numeric real user ID of the current process.
### Parameters
This function has no parameters.
### Return Values
Returns the user id, as an int
### Examples
**Example #1 Example use of **posix\_getuid()****
```
<?php
echo posix_getuid(); //10000
?>
```
### See Also
* [posix\_getpwuid()](function.posix-getpwuid) - Return info about a user by user id
* POSIX man page GETUID(2)
php get_defined_functions get\_defined\_functions
=======================
(PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8)
get\_defined\_functions — Returns an array of all defined functions
### Description
```
get_defined_functions(bool $exclude_disabled = true): array
```
Gets an array of all defined functions.
### Parameters
`exclude_disabled`
Whether disabled functions should be excluded from the return value.
### Return Values
Returns a multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. The internal functions will be accessible via $arr["internal"], and the user defined ones using $arr["user"] (see example below).
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | The default value of the `exclude_disabled` parameter has been changed from **`false`** to **`true`**. |
| 7.0.15, 7.1.1 | The `exclude_disabled` parameter has been added. |
### Examples
**Example #1 **get\_defined\_functions()** example**
```
<?php
function myrow($id, $data)
{
return "<tr><th>$id</th><td>$data</td></tr>\n";
}
$arr = get_defined_functions();
print_r($arr);
?>
```
The above example will output something similar to:
```
Array
(
[internal] => Array
(
[0] => zend_version
[1] => func_num_args
[2] => func_get_arg
[3] => func_get_args
[4] => strlen
[5] => strcmp
[6] => strncmp
...
[750] => bcscale
[751] => bccomp
)
[user] => Array
(
[0] => myrow
)
)
```
### See Also
* [function\_exists()](function.function-exists) - Return true if the given function has been defined
* [get\_defined\_vars()](function.get-defined-vars) - Returns an array of all defined variables
* [get\_defined\_constants()](function.get-defined-constants) - Returns an associative array with the names of all the constants and their values
* [get\_declared\_classes()](function.get-declared-classes) - Returns an array with the name of the defined classes
php fastcgi_finish_request fastcgi\_finish\_request
========================
(PHP 5 >= 5.3.3, PHP 7, PHP 8)
fastcgi\_finish\_request — Flushes all response data to the client
### Description
```
fastcgi_finish_request(): bool
```
This function flushes all response data to the client and finishes the request. This allows for time consuming tasks to be performed without leaving the connection to the client open.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
php ImagickPixel::getHSL ImagickPixel::getHSL
====================
(PECL imagick 2, PECL imagick 3)
ImagickPixel::getHSL — Returns the normalized HSL color of the ImagickPixel object
### Description
```
public ImagickPixel::getHSL(): array
```
Returns the normalized HSL color described by the ImagickPixel object, with each of the three values as floating point numbers between 0.0 and 1.0.
### Parameters
This function has no parameters.
### Return Values
Returns the HSL value in an array with the keys "hue", "saturation", and "luminosity". Throws ImagickPixelException on failure.
### Examples
**Example #1 Basic **Imagick::getHSL()** example**
```
<?php
$color = new ImagickPixel('rgb(90%, 10%, 10%)');
$colorInfo = $color->getHSL();
print_r($colorInfo);
?>
```
The above example will output:
```
Array
(
[hue] => 0
[saturation] => 0.80001220740379
[luminosity] => 0.50000762951095
)
```
### Notes
>
> **Note**:
>
>
> Available with ImageMagick library version 6.2.9 and higher.
>
>
php GearmanWorker::work GearmanWorker::work
===================
(PECL gearman >= 0.5.0)
GearmanWorker::work — Wait for and perform jobs
### Description
```
public GearmanWorker::work(): bool
```
Waits for a job to be assigned and then calls the appropriate callback function. Issues an **`E_WARNING`** with the last Gearman error if the return code is not one of **`GEARMAN_SUCCESS`**, **`GEARMAN_IO_WAIT`**, or **`GEARMAN_WORK_FAIL`**.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **GearmanWorker::work()** example**
```
<?php
# create the worker
$worker = new GearmanWorker();
# add the default job server (localhost)
$worker->addServer();
# add the reverse function
$worker->addFunction("reverse", "my_reverse_function");
# start te worker listening for job submissions
while ($worker->work());
function my_reverse_function($job)
{
return strrev($job->workload());
}
?>
```
### See Also
* [GearmanWorker::addFunction()](gearmanworker.addfunction) - Register and add callback function
php PharData::convertToExecutable PharData::convertToExecutable
=============================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)
PharData::convertToExecutable — Convert a non-executable tar/zip archive to an executable phar archive
### Description
```
public PharData::convertToExecutable(?int $format = null, ?int $compression = null, ?string $extension = null): ?Phar
```
>
> **Note**:
>
>
> This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown.
>
>
>
This method is used to convert a non-executable tar or zip archive to an executable phar archive. Any of the three executable file formats (phar, tar or zip) can be used, and whole-archive compression can also be performed.
If no changes are specified, this method throws a [BadMethodCallException](class.badmethodcallexception).
If successful, the method creates a new archive on disk and returns a [Phar](class.phar) object. The old archive is not removed from disk, and should be done manually after the process has finished.
### Parameters
`format`
This should be one of `Phar::PHAR`, `Phar::TAR`, or `Phar::ZIP`. If set to **`null`**, the existing file format will be preserved.
`compression`
This should be one of `Phar::NONE` for no whole-archive compression, `Phar::GZ` for zlib-based compression, and `Phar::BZ2` for bzip-based compression.
`extension`
This parameter is used to override the default file extension for a converted archive. Note that all zip- and tar-based phar archives must contain `.phar` in their file extension in order to be processed as a phar archive.
If converting to a phar-based archive, the default extensions are `.phar`, `.phar.gz`, or `.phar.bz2` depending on the specified compression. For tar-based phar archives, the default extensions are `.phar.tar`, `.phar.tar.gz`, and `.phar.tar.bz2`. For zip-based phar archives, the default extension is `.phar.zip`.
### Return Values
The method returns a [Phar](class.phar) object on success, or **`null`** on failure.
### Errors/Exceptions
This method throws [BadMethodCallException](class.badmethodcallexception) when unable to compress, an unknown compression method has been specified, the requested archive is buffering with [Phar::startBuffering()](phar.startbuffering) and has not concluded with [Phar::stopBuffering()](phar.stopbuffering), an [UnexpectedValueException](class.unexpectedvalueexception) if write support is disabled, and a [PharException](class.pharexception) if any problems are encountered during the phar creation process.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `format`, `compression`, and `localName` are now nullable. |
### Examples
**Example #1 A **PharData::convertToExecutable()** example**
Using PharData::convertToExecutable():
```
<?php
try {
$tarphar = new PharData('myphar.tar');
// convert it to the phar file format
// note that myphar.tar is *not* unlinked
$phar = $tarphar->convertToExecutable(Phar::PHAR); // creates myphar.phar
$phar->setStub($phar->createDefaultStub('cli.php', 'web/index.php'));
// creates myphar.phar.tgz
$compressed = $tarphar->convertToExecutable(Phar::TAR, Phar::GZ, '.phar.tgz');
} catch (Exception $e) {
// handle the error here
}
?>
```
### See Also
* [Phar::convertToExecutable()](phar.converttoexecutable) - Convert a phar archive to another executable phar archive file format
* [Phar::convertToData()](phar.converttodata) - Convert a phar archive to a non-executable tar or zip file
* [PharData::convertToData()](phardata.converttodata) - Convert a phar archive to a non-executable tar or zip file
php SplFixedArray::__wakeup SplFixedArray::\_\_wakeup
=========================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
SplFixedArray::\_\_wakeup — Reinitialises the array after being unserialised
### Description
```
public SplFixedArray::__wakeup(): void
```
Reinitialises the array after being unserialised.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php gztell gztell
======
(PHP 4, PHP 5, PHP 7, PHP 8)
gztell — Tell gz-file pointer read/write position
### Description
```
gztell(resource $stream): int|false
```
Gets the position of the given file pointer; i.e., its offset into the uncompressed file stream.
### Parameters
`stream`
The gz-file pointer. It must be valid, and must point to a file successfully opened by [gzopen()](function.gzopen).
### Return Values
The position of the file pointer or **`false`** if an error occurs.
### See Also
* [gzopen()](function.gzopen) - Open gz-file
* [gzseek()](function.gzseek) - Seek on a gz-file pointer
* [gzrewind()](function.gzrewind) - Rewind the position of a gz-file pointer
php pg_delete pg\_delete
==========
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
pg\_delete — Deletes records
### Description
```
pg_delete(
PgSql\Connection $connection,
string $table_name,
array $conditions,
int $flags = PGSQL_DML_EXEC
): string|bool
```
**pg\_delete()** deletes records from a table specified by the keys and values in `conditions`.
If `flags` is specified, [pg\_convert()](function.pg-convert) is applied to `conditions` with the specified flags.
By default **pg\_delete()** passes raw values. Values must be escaped or the **`PGSQL_DML_ESCAPE`** flag must be specified in `flags`. **`PGSQL_DML_ESCAPE`** quotes and escapes parameters/identifiers. Therefore, table/column names become case sensitive.
Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values.
### Parameters
`connection`
An [PgSql\Connection](class.pgsql-connection) instance.
`table_name`
Name of the table from which to delete rows.
`conditions`
An array whose keys are field names in the table `table_name`, and whose values are the values of those fields that are to be deleted.
`flags`
Any number of **`PGSQL_CONV_FORCE_NULL`**, **`PGSQL_DML_NO_CONV`**, **`PGSQL_DML_ESCAPE`**, **`PGSQL_DML_EXEC`**, **`PGSQL_DML_ASYNC`** or **`PGSQL_DML_STRING`** combined. If **`PGSQL_DML_STRING`** is part of the `flags` then query string is returned. When **`PGSQL_DML_NO_CONV`** or **`PGSQL_DML_ESCAPE`** is set, it does not call [pg\_convert()](function.pg-convert) internally.
### Return Values
Returns **`true`** on success or **`false`** on failure. Returns string if **`PGSQL_DML_STRING`** is passed via `flags`.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **pg\_delete()** example**
```
<?php
$db = pg_connect('dbname=foo');
// This is safe somewhat, since all values are escaped.
// However PostgreSQL supports JSON/Array. These are not
// safe by neither escape nor prepared query.
$res = pg_delete($db, 'post_log', $_POST, PG_DML_ESCAPE);
if ($res) {
echo "POST data is deleted: $res\n";
} else {
echo "User must have sent wrong inputs\n";
}
?>
```
### See Also
* [pg\_convert()](function.pg-convert) - Convert associative array values into forms suitable for SQL statements
php Locale::acceptFromHttp Locale::acceptFromHttp
======================
locale\_accept\_from\_http
==========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0)
Locale::acceptFromHttp -- locale\_accept\_from\_http — Tries to find out best available locale based on HTTP "Accept-Language" header
### Description
Object-oriented style
```
public static Locale::acceptFromHttp(string $header): string|false
```
Procedural style
```
locale_accept_from_http(string $header): string|false
```
Tries to find locale that can satisfy the language list that is requested by the HTTP "Accept-Language" header.
### Parameters
`header`
The string containing the "Accept-Language" header according to format in RFC 2616.
### Return Values
The corresponding locale identifier.
Returns **`false`** when the length of `header` exceeds **`INTL_MAX_LOCALE_LEN`**.
### Examples
**Example #1 **locale\_accept\_from\_http()** example**
```
<?php
$locale = locale_accept_from_http($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>
```
**Example #2 OO example**
```
<?php
$locale = Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']);
echo $locale;
?>
```
The above example will output:
```
en_US
```
### See Also
* [locale\_lookup()](locale.lookup) - Searches the language tag list for the best match to the language
php ldap_get_dn ldap\_get\_dn
=============
(PHP 4, PHP 5, PHP 7, PHP 8)
ldap\_get\_dn — Get the DN of a result entry
### Description
```
ldap_get_dn(LDAP\Connection $ldap, LDAP\ResultEntry $entry): string|false
```
Finds out the DN of an entry in the result.
### Parameters
`ldap`
An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect).
`entry`
An [LDAP\ResultEntry](class.ldap-result-entry) instance.
### Return Values
Returns the DN of the result entry and **`false`** on error.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. |
| 8.1.0 | The `entry` parameter expects an [LDAP\ResultEntry](class.ldap-result-entry) instance now; previously, a [resource](language.types.resource) was expected. |
| programming_docs |
php IntlCalendar::isLenient IntlCalendar::isLenient
=======================
(PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1)
IntlCalendar::isLenient — Whether date/time interpretation is in lenient mode
### Description
Object-oriented style
```
public IntlCalendar::isLenient(): bool
```
Procedural style
```
intlcal_is_lenient(IntlCalendar $calendar): bool
```
Returns whether the current date/time interpretations is lenient (the default). If that is case, some out of range values for fields will be accepted instead of raising an error.
### Parameters
`calendar`
An [IntlCalendar](class.intlcalendar) instance.
### Return Values
A bool representing whether the calendar is set to lenient mode.
### Examples
**Example #1 **IntlCalendar::isLenient()****
```
<?php
ini_set('date.timezone', 'Europe/Lisbon');
ini_set('intl.default_locale', 'pt_PT');
ini_set('intl.use_exceptions', '1');
$cal = new IntlGregorianCalendar(2013, 6 /* July */, 1);
var_dump(IntlDateFormatter::formatObject($cal), // 01/07/2013, 00:00:00
$cal->isLenient()); // true
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // 02/08/2013, 00:00:00
$cal->setLenient(false);
var_dump($cal->isLenient()); // false
$cal->set(IntlCalendar::FIELD_DAY_OF_MONTH, 33);
var_dump(IntlDateFormatter::formatObject($cal)); // error
```
The above example will output:
```
string(20) "01/07/2013, 00:00:00"
bool(true)
string(20) "02/08/2013, 00:00:00"
bool(false)
Fatal error: Uncaught exception 'IntlException' with message 'datefmt_format_object: error obtaining instant from IntlCalendar' in /home/foobar/example.php:16
Stack trace:
#0 /home/foobar/example.php(16): IntlDateFormatter::formatObject(Object(IntlGregorianCalendar))
#1 {main}
thrown in /home/foobar/example.php on line 16
```
php ReflectionAttribute::getArguments ReflectionAttribute::getArguments
=================================
(PHP 8)
ReflectionAttribute::getArguments — Gets arguments passed to attribute
### Description
```
public ReflectionAttribute::getArguments(): array
```
Gets arguments passed to attribute.
### Parameters
This function has no parameters.
### Return Values
The arguments passed to attribute.
php sodium_crypto_sign_verify_detached sodium\_crypto\_sign\_verify\_detached
======================================
(PHP 7 >= 7.2.0, PHP 8)
sodium\_crypto\_sign\_verify\_detached — Verify signature for the message
### Description
```
sodium_crypto_sign_verify_detached(string $signature, string $message, string $public_key): bool
```
Verify signature for the message
### Parameters
`signature`
The cryptographic signature obtained from [sodium\_crypto\_sign\_detached()](function.sodium-crypto-sign-detached)
`message`
The message being verified
`public_key`
Ed25519 public key
### Return Values
Returns **`true`** on success or **`false`** on failure.
php SQLite3::createAggregate SQLite3::createAggregate
========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3::createAggregate — Registers a PHP function for use as an SQL aggregate function
### Description
```
public SQLite3::createAggregate(
string $name,
callable $stepCallback,
callable $finalCallback,
int $argCount = -1
): bool
```
Registers a PHP function or user-defined function for use as an SQL aggregate function for use within SQL statements.
### Parameters
`name`
Name of the SQL aggregate to be created or redefined.
`stepCallback`
Callback function called for each row of the result set. Your PHP function should accumulate the result and store it in the aggregation context.
This function need to be defined as:
```
step(
mixed $context,
int $rownumber,
mixed $value,
mixed ...$values
): mixed
```
`context`
**`null`** for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain the aggregate state.
`rownumber`
The current row number.
`value`
The first argument passed to the aggregate.
`values`
Further arguments passed to the aggregate.
The return value of this function will be used as the `context` argument in the next call of the step or finalize functions. `finalCallback`
Callback function to aggregate the "stepped" data from each row. Once all the rows have been processed, this function will be called and it should then take the data from the aggregation context and return the result. This callback function should return a type understood by SQLite (i.e. [scalar type](language.types.intro)).
This function need to be defined as:
```
fini(mixed $context, int $rownumber): mixed
```
`context`
Holds the return value from the very last call to the step function.
`rownumber`
Always `0`.
The return value of this function will be used as the return value for the aggregate. `argCount`
The number of arguments that the SQL aggregate takes. If this parameter is negative, then the SQL aggregate may take any number of arguments.
### Return Values
Returns **`true`** upon successful creation of the aggregate, or **`false`** on failure.
### Examples
**Example #1 max\_length aggregation function example**
```
<?php
$data = array(
'one',
'two',
'three',
'four',
'five',
'six',
'seven',
'eight',
'nine',
'ten',
);
$db = new SQLite3(':memory:');
$db->exec("CREATE TABLE strings(a)");
$insert = $db->prepare('INSERT INTO strings VALUES (?)');
foreach ($data as $str) {
$insert->bindValue(1, $str);
$insert->execute();
}
$insert = null;
function max_len_step($context, $rownumber, $string)
{
if (strlen($string) > $context) {
$context = strlen($string);
}
return $context;
}
function max_len_finalize($context, $rownumber)
{
return $context === null ? 0 : $context;
}
$db->createAggregate('max_len', 'max_len_step', 'max_len_finalize');
var_dump($db->querySingle('SELECT max_len(a) from strings'));
?>
```
The above example will output:
```
int(5)
```
In this example, we are creating an aggregating function that will calculate the length of the longest string in one of the columns of the table. For each row, the `max_len_step` function is called and passed a `$context` parameter. The context parameter is just like any other PHP variable and be set to hold an array or even an object value. In this example, we are simply using it to hold the maximum length we have seen so far; if the `$string` has a length longer than the current maximum, we update the context to hold this new maximum length.
After all of the rows have been processed, SQLite calls the `max_len_finalize` function to determine the aggregate result. Here, we could perform some kind of calculation based on the data found in the `$context`. In our simple example though, we have been calculating the result as the query progressed, so we simply need to return the context value.
**Tip** It is NOT recommended for you to store a copy of the values in the context and then process them at the end, as you would cause SQLite to use a lot of memory to process the query - just think of how much memory you would need if a million rows were stored in memory, each containing a string 32 bytes in length.
**Tip** You can use **SQLite3::createAggregate()** to override SQLite native SQL functions.
php iconv_strrpos iconv\_strrpos
==============
(PHP 5, PHP 7, PHP 8)
iconv\_strrpos — Finds the last occurrence of a needle within a haystack
### Description
```
iconv_strrpos(string $haystack, string $needle, ?string $encoding = null): int|false
```
Finds the last occurrence of a `needle` within a `haystack`.
In contrast to [strrpos()](function.strrpos), the return value of **iconv\_strrpos()** is the number of characters that appear before the needle, rather than the offset in bytes to the position where the needle has been found. The characters are counted on the basis of the specified character set `encoding`.
### Parameters
`haystack`
The entire string.
`needle`
The searched substring.
`encoding`
If `encoding` parameter is omitted or **`null`**, `string` are assumed to be encoded in [iconv.internal\_encoding](https://www.php.net/manual/en/iconv.configuration.php).
If `haystack` or `needle` is not a string, it is converted to a string and applied as the ordinal value of a character.
### Return Values
Returns the numeric position of the last occurrence of `needle` in `haystack`.
If `needle` is not found, **iconv\_strrpos()** will return **`false`**.
**Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `encoding` is nullable now. |
### See Also
* [strrpos()](function.strrpos) - Find the position of the last occurrence of a substring in a string
* [iconv\_strpos()](function.iconv-strpos) - Finds position of first occurrence of a needle within a haystack
* [mb\_strrpos()](function.mb-strrpos) - Find position of last occurrence of a string in a string
php SolrClient::deleteByIds SolrClient::deleteByIds
=======================
(PECL solr >= 0.9.2)
SolrClient::deleteByIds — Deletes by Ids
### Description
```
public SolrClient::deleteByIds(array $ids): SolrUpdateResponse
```
Deletes a collection of documents with the specified set of ids.
### Parameters
`ids`
An array of IDs representing the uniqueKey field declared in the schema for each document to be deleted. This must be an actual php variable.
### Return Values
Returns a [SolrUpdateResponse](class.solrupdateresponse) on success and throws an exception on failure.
### Errors/Exceptions
Throws [SolrClientException](class.solrclientexception) if the client had failed, or there was a connection issue.
Throws [SolrServerException](class.solrserverexception) if the Solr Server had failed to process the request.
### See Also
* [SolrClient::deleteById()](solrclient.deletebyid) - Delete by Id
* [SolrClient::deleteByQuery()](solrclient.deletebyquery) - Deletes all documents matching the given query
* [SolrClient::deleteByQueries()](solrclient.deletebyqueries) - Removes all documents matching any of the queries
php ldap_8859_to_t61 ldap\_8859\_to\_t61
===================
(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)
ldap\_8859\_to\_t61 — Translate 8859 characters to t61 characters
### Description
```
ldap_8859_to_t61(string $value): string|false
```
Translate `ISO-8859` characters to `t61` characters.
This function is useful if you have to talk to a legacy `LDAPv2` server.
### Parameters
`value`
The text to be translated.
### Return Values
Return the `t61` translation of `value`, or **`false`** on failure.
### See Also
* [ldap\_t61\_to\_8859()](function.ldap-t61-to-8859) - Translate t61 characters to 8859 characters
php stats_dens_exponential stats\_dens\_exponential
========================
(PECL stats >= 1.0.0)
stats\_dens\_exponential — Probability density function of the exponential distribution
### Description
```
stats_dens_exponential(float $x, float $scale): float
```
Returns the probability density at `x`, where the random variable follows the exponential distribution of which the scale is `scale`.
### Parameters
`x`
The value at which the probability density is calculated
`scale`
The scale of the distribution
### Return Values
The probability density at `x` or **`false`** for failure.
php get_include_path get\_include\_path
==================
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
get\_include\_path — Gets the current include\_path configuration option
### Description
```
get_include_path(): string|false
```
Gets the current [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path) configuration option value.
### Parameters
This function has no parameters.
### Return Values
Returns the path, as a string, or **`false`** on failure.
### Examples
**Example #1 **get\_include\_path()** example**
```
<?php
echo get_include_path();
// Or using ini_get()
echo ini_get('include_path');
?>
```
### See Also
* [ini\_get()](function.ini-get) - Gets the value of a configuration option
* [restore\_include\_path()](function.restore-include-path) - Restores the value of the include\_path configuration option
* [set\_include\_path()](function.set-include-path) - Sets the include\_path configuration option
* [include](function.include) - include
php fbird_wait_event fbird\_wait\_event
==================
(PHP 5, PHP 7 < 7.4.0)
fbird\_wait\_event — Alias of [ibase\_wait\_event()](function.ibase-wait-event)
### Description
This function is an alias of: [ibase\_wait\_event()](function.ibase-wait-event).
### See Also
* [fbird\_set\_event\_handler()](function.fbird-set-event-handler) - Alias of ibase\_set\_event\_handler
* [fbird\_free\_event\_handler()](function.fbird-free-event-handler) - Alias of ibase\_free\_event\_handler
php Phar::setStub Phar::setStub
=============
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0)
Phar::setStub — Used to set the PHP loader or bootstrap stub of a Phar archive
### Description
```
public Phar::setStub(string $stub, int $len = -1): bool
```
>
> **Note**:
>
>
> This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown.
>
>
>
This method is used to add a PHP bootstrap loader stub to a new Phar archive, or to replace the loader stub in an existing Phar archive.
The loader stub for a Phar archive is used whenever an archive is included directly as in this example:
```
<?php
include 'myphar.phar';
?>
```
The loader is not accessed when including a file through the `phar` stream wrapper like so:
```
<?php
include 'phar://myphar.phar/somefile.php';
?>
```
### Parameters
`stub`
A string or an open stream handle to use as the executable stub for this phar archive.
`len`
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Errors/Exceptions
[UnexpectedValueException](class.unexpectedvalueexception) is thrown if [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) is enabled in php.ini. [PharException](class.pharexception) is thrown if any problems are encountered flushing changes to disk.
### Examples
**Example #1 A **Phar::setStub()** example**
```
<?php
try {
$p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');
$p['a.php'] = '<?php var_dump("Hello");';
$p->setStub('<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include 'phar://brandnewphar.phar/a.php';
var_dump($p->getStub());
$p['b.php'] = '<?php var_dump("World");';
$p->setStub('<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>');
include 'phar://brandnewphar.phar/b.php';
var_dump($p->getStub());
} catch (Exception $e) {
echo 'Write operations failed on brandnewphar.phar: ', $e;
}
?>
```
The above example will output:
```
string(5) "Hello"
string(82) "<?php var_dump("First"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
string(5) "World"
string(83) "<?php var_dump("Second"); Phar::mapPhar("brandnewphar.phar"); __HALT_COMPILER(); ?>"
```
### See Also
* [Phar::getStub()](phar.getstub) - Return the PHP loader or bootstrap stub of a Phar archive
* [Phar::createDefaultStub()](phar.createdefaultstub) - Create a phar-file format specific stub
php Imagick::getColorspace Imagick::getColorspace
======================
(PECL imagick 3)
Imagick::getColorspace — Gets the colorspace
### Description
```
public Imagick::getColorspace(): int
```
Gets the global colorspace value. This method is available if Imagick has been compiled against ImageMagick version 6.5.7 or newer.
### Parameters
This function has no parameters.
### Return Values
Returns an integer which can be compared against [COLORSPACE constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.colorspace).
php stats_dens_normal stats\_dens\_normal
===================
(PECL stats >= 1.0.0)
stats\_dens\_normal — Probability density function of the normal distribution
### Description
```
stats_dens_normal(float $x, float $ave, float $stdev): float
```
Returns the probability density at `x`, where the random variable follows the normal distribution of which the mean is `ave` and the standard deviation is `stdev`.
### Parameters
`x`
The value at which the probability density is calculated
`ave`
The mean of the distribution
`stdev`
The standard deviation of the distribution
### Return Values
The probability density at `x` or **`false`** for failure.
php IntlCalendar::setMinimalDaysInFirstWeek IntlCalendar::setMinimalDaysInFirstWeek
=======================================
(PHP 5 >= 5.5.1, PHP 7, PHP 8)
IntlCalendar::setMinimalDaysInFirstWeek — Set minimal number of days the first week in a year or month can have
### Description
Object-oriented style
```
public IntlCalendar::setMinimalDaysInFirstWeek(int $days): bool
```
Procedural style
```
intlcal_set_minimal_days_in_first_week(IntlCalendar $calendar, int $days): bool
```
Sets the smallest number of days the first week of a year or month must have in the new year or month. For instance, in the Gregorian calendar, if this value is 1, then the first week of the year will necessarily include January 1st, while if this value is 7, then the week with January 1st will be the first week of the year only if the day of the week for January 1st matches the day of the week returned by [IntlCalendar::getFirstDayOfWeek()](intlcalendar.getfirstdayofweek); otherwise it will be the previous yearʼs last week.
### Parameters
`calendar`
An [IntlCalendar](class.intlcalendar) instance.
`days`
The number of minimal days to set.
### Return Values
**`true`** on success, **`false`** on failure.
php Gmagick::quantizeimages Gmagick::quantizeimages
=======================
(PECL gmagick >= Unknown)
Gmagick::quantizeimages — The quantizeimages purpose
### Description
```
public Gmagick::quantizeimages(
int $numColors,
int $colorspace,
int $treeDepth,
bool $dither,
bool $measureError
): Gmagick
```
Analyzes the colors within a sequence of images and chooses a fixed number of colors to represent the image. The goal of the algorithm is to minimize the color difference between the input and output image while minimizing the processing time.
### Parameters
`numColors`
The number of colors.
`colorspace`
Perform color reduction in this colorspace, typically RGBColorspace.
`treeDepth`
Normally, this integer value is zero or one. A zero or one tells Quantize to choose a optimal tree depth of Log4(number\_colors).% A tree of this depth generally allows the best representation of the reference image with the least amount of memory and the fastest computational speed. In some cases, such as an image with low color dispersion (a few number of colors), a value other than Log4(number\_colors) is required. To expand the color tree completely, use a value of 8.
`dither`
A value other than zero distributes the difference between an original image and the corresponding color reduced algorithm to neighboring pixels along a Hilbert curve.
`measureError`
A value other than zero measures the difference between the original and quantized images. This difference is the total quantization error. The error is computed by summing over all pixels in an image the distance squared in RGB space between each reference pixel value and its quantized value.
### Return Values
The Gmagick object on success
### Errors/Exceptions
Throws an **GmagickException** on error.
| programming_docs |
php fbird_commit_ret fbird\_commit\_ret
==================
(PHP 5, PHP 7 < 7.4.0)
fbird\_commit\_ret — Alias of [ibase\_commit\_ret()](function.ibase-commit-ret)
### Description
This function is an alias of: [ibase\_commit\_ret()](function.ibase-commit-ret).
php uasort uasort
======
(PHP 4, PHP 5, PHP 7, PHP 8)
uasort — Sort an array with a user-defined comparison function and maintain index association
### Description
```
uasort(array &$array, callable $callback): bool
```
Sorts `array` in place such that its keys maintain their correlation with the values they are associated with, using a user-defined comparison function.
This is used mainly when sorting associative arrays where the actual element order is significant.
>
> **Note**:
>
>
> If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined.
>
>
>
> **Note**:
>
>
> Resets array's internal pointer to the first element.
>
>
### Parameters
`array`
The input array.
`callback`
The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second.
```
callback(mixed $a, mixed $b): int
```
### Return Values
Always returns **`true`**.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | If `callback` expects a parameter to be passed by reference, this function will now emit an **`E_WARNING`**. |
### Examples
**Example #1 Basic **uasort()** example**
```
<?php
// Comparison function
function cmp($a, $b) {
if ($a == $b) {
return 0;
}
return ($a < $b) ? -1 : 1;
}
// Array to be sorted
$array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4);
print_r($array);
// Sort and print the resulting array
uasort($array, 'cmp');
print_r($array);
?>
```
The above example will output:
```
Array
(
[a] => 4
[b] => 8
[c] => -1
[d] => -9
[e] => 2
[f] => 5
[g] => 3
[h] => -4
)
Array
(
[d] => -9
[h] => -4
[c] => -1
[e] => 2
[g] => 3
[a] => 4
[f] => 5
[b] => 8
)
```
### See Also
* [usort()](function.usort) - Sort an array by values using a user-defined comparison function
* [uksort()](function.uksort) - Sort an array by keys using a user-defined comparison function
* The [comparison of array sorting functions](https://www.php.net/manual/en/array.sorting.php)
php recode_string recode\_string
==============
(PHP 4, PHP 5, PHP 7 < 7.4.0)
recode\_string — Recode a string according to a recode request
### Description
```
recode_string(string $request, string $string): string
```
Recode the string `string` according to the recode request `request`.
### Parameters
`request`
The desired recode request type
`string`
The string to be recoded
### Return Values
Returns the recoded string or **`false`**, if unable to perform the recode request.
### Examples
**Example #1 Basic **recode\_string()** example**
```
<?php
echo recode_string("us..flat", "The following character has a diacritical mark: á");
?>
```
### Notes
A simple recode request may be "lat1..iso646-de".
### See Also
* The GNU Recode documentation of your installation for detailed instructions about recode requests.
* [mb\_convert\_encoding()](function.mb-convert-encoding) - Convert a string from one character encoding to another
* [UConverter::transcode()](uconverter.transcode) - Convert a string from one character encoding to another
* [iconv()](function.iconv) - Convert a string from one character encoding to another
php Yaf_Dispatcher::getApplication Yaf\_Dispatcher::getApplication
===============================
(Yaf >=1.0.0)
Yaf\_Dispatcher::getApplication — Retrieve the application
### Description
```
public Yaf_Dispatcher::getApplication(): Yaf_Application
```
Retrieve the [Yaf\_Application](class.yaf-application) instance. same as [Yaf\_Application::app()](yaf-application.app).
### Parameters
This function has no parameters.
### Return Values
### See Also
* [Yaf\_Application::app()](yaf-application.app) - Retrieve an Application instance
php GearmanClient::doJobHandle GearmanClient::doJobHandle
==========================
(PECL gearman >= 0.5.0)
GearmanClient::doJobHandle — Get the job handle for the running task
### Description
```
public GearmanClient::doJobHandle(): string
```
Gets that job handle for a running task. This should be used between repeated [GearmanClient::doNormal()](gearmanclient.donormal) calls. The job handle can then be used to get information on the task.
### Parameters
This function has no parameters.
### Return Values
The job handle for the running task.
### See Also
* [GearmanClient::jobStatus()](gearmanclient.jobstatus) - Get the status of a background job
php mysqli::begin_transaction mysqli::begin\_transaction
==========================
mysqli\_begin\_transaction
==========================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
mysqli::begin\_transaction -- mysqli\_begin\_transaction — Starts a transaction
### Description
Object-oriented style
```
public mysqli::begin_transaction(int $flags = 0, ?string $name = null): bool
```
Procedural style:
```
mysqli_begin_transaction(mysqli $mysql, int $flags = 0, ?string $name = null): bool
```
Begins a transaction. Requires the InnoDB engine (it is enabled by default). For additional details about how MySQL transactions work, see [» http://dev.mysql.com/doc/mysql/en/commit.html](http://dev.mysql.com/doc/mysql/en/commit.html).
### Parameters
`mysql`
Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init)
`flags`
Valid flags are:
* **`MYSQLI_TRANS_START_READ_ONLY`**: Start the transaction as "START TRANSACTION READ ONLY". Requires MySQL 5.6 and above.
* **`MYSQLI_TRANS_START_READ_WRITE`**: Start the transaction as "START TRANSACTION READ WRITE". Requires MySQL 5.6 and above.
* **`MYSQLI_TRANS_START_WITH_CONSISTENT_SNAPSHOT`**: Start the transaction as "START TRANSACTION WITH CONSISTENT SNAPSHOT".
`name`
Savepoint name for the transaction.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `name` is now nullable. |
### Examples
**Example #1 **mysqli::begin\_transaction()** example**
Object-oriented style
```
<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
$mysqli->query("CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Start transaction */
$mysqli->begin_transaction();
try {
/* Insert some values */
$mysqli->query("INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");
/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = $mysqli->prepare('INSERT INTO language(Code, Speakers) VALUES (?,?)');
$stmt->bind_param('ss', $language_code, $native_speakers);
$stmt->execute();
/* If code reaches this point without errors then commit the data in the database */
$mysqli->commit();
} catch (mysqli_sql_exception $exception) {
$mysqli->rollback();
throw $exception;
}
```
Procedural style
```
<?php
/* Tell mysqli to throw an exception if an error occurs */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = mysqli_connect("localhost", "my_user", "my_password", "world");
/* The table engine has to support transactions */
mysqli_query($mysqli, "CREATE TABLE IF NOT EXISTS language (
Code text NOT NULL,
Speakers int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;");
/* Start transaction */
mysqli_begin_transaction($mysqli);
try {
/* Insert some values */
mysqli_query($mysqli, "INSERT INTO language(Code, Speakers) VALUES ('DE', 42000123)");
/* Try to insert invalid values */
$language_code = 'FR';
$native_speakers = 'Unknown';
$stmt = mysqli_prepare($mysqli, 'INSERT INTO language(Code, Speakers) VALUES (?,?)');
mysqli_stmt_bind_param($stmt, 'ss', $language_code, $native_speakers);
mysqli_stmt_execute($stmt);
/* If code reaches this point without errors then commit the data in the database */
mysqli_commit($mysqli);
} catch (mysqli_sql_exception $exception) {
mysqli_rollback($mysqli);
throw $exception;
}
```
### Notes
>
> **Note**:
>
>
> This function does not work with non transactional table types (like MyISAM or ISAM).
>
>
### See Also
* [mysqli\_autocommit()](mysqli.autocommit) - Turns on or off auto-committing database modifications
* [mysqli\_commit()](mysqli.commit) - Commits the current transaction
* [mysqli\_rollback()](mysqli.rollback) - Rolls back current transaction
php pg_lo_truncate pg\_lo\_truncate
================
(PHP 5 >= 5.6.0, PHP 7, PHP 8)
pg\_lo\_truncate — Truncates a large object
### Description
```
pg_lo_truncate(PgSql\Lob $lob, int $size): bool
```
**pg\_lo\_truncate()** truncates an [PgSql\Lob](class.pgsql-lob) instance.
To use the large object interface, it is necessary to enclose it within a transaction block.
### Parameters
`lob`
An [PgSql\Lob](class.pgsql-lob) instance, returned by [pg\_lo\_open()](function.pg-lo-open).
`size`
The number of bytes to truncate.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `lob` parameter expects an [PgSql\Lob](class.pgsql-lob) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 **pg\_lo\_truncate()** example**
```
<?php
$doc_oid = 189762345;
$database = pg_connect("dbname=jacarta");
pg_query($database, "begin");
$handle = pg_lo_open($database, $doc_oid, "r");
// Truncate to 0
pg_lo_truncate($handle, 0);
pg_query($database, "commit");
echo $data;
?>
```
### See Also
* [pg\_lo\_tell()](function.pg-lo-tell) - Returns current seek position a of large object
php stomp_version stomp\_version
==============
(PECL stomp >= 0.1.0)
stomp\_version — Gets the current stomp extension version
### Description
```
stomp_version(): string
```
Returns a string containing the version of the current stomp extension.
### Parameters
This function has no parameters.
### Return Values
It returns the current stomp extension version
### Examples
**Example #1 **stomp\_version()** example**
```
<?php
var_dump(stomp_version());
?>
```
The above example will output something similar to:
```
string(5) "0.2.0"
```
php SQLite3::lastInsertRowID SQLite3::lastInsertRowID
========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3::lastInsertRowID — Returns the row ID of the most recent INSERT into the database
### Description
```
public SQLite3::lastInsertRowID(): int
```
Returns the row ID of the most recent INSERT into the database.
### Parameters
This function has no parameters.
### Return Values
Returns the row ID of the most recent INSERT into the database. If no successful INSERTs into rowid tables have ever occurred on this database connection, then **SQLite3::lastInsertRowID()** returns `0`.
php odbc_error odbc\_error
===========
(PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8)
odbc\_error — Get the last error code
### Description
```
odbc_error(?resource $odbc = null): string
```
Returns a six-digit ODBC state, or an empty string if there has been no errors.
### Parameters
`odbc`
The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details.
### Return Values
If `odbc` is specified, the last state of that connection is returned, else the last state of any connection is returned.
This function returns meaningful value only if last odbc query failed (i.e. [odbc\_exec()](function.odbc-exec) returned **`false`**).
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `odbc` is nullable now. |
### See Also
* [odbc\_errormsg()](function.odbc-errormsg) - Get the last error message
* [odbc\_exec()](function.odbc-exec) - Directly execute an SQL statement
php md5_file md5\_file
=========
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
md5\_file — Calculates the md5 hash of a given file
### Description
```
md5_file(string $filename, bool $binary = false): string|false
```
Calculates the MD5 hash of the file specified by the `filename` parameter using the [» RSA Data Security, Inc. MD5 Message-Digest Algorithm](http://www.faqs.org/rfcs/rfc1321), and returns that hash. The hash is a 32-character hexadecimal number.
### Parameters
`filename`
The filename
`binary`
When **`true`**, returns the digest in raw binary format with a length of 16.
### Return Values
Returns a string on success, **`false`** otherwise.
### Examples
**Example #1 Usage example of **md5\_file()****
```
<?php
$file = 'php-5.3.0alpha2-Win32-VC9-x64.zip';
echo 'MD5 file hash of ' . $file . ': ' . md5_file($file);
?>
```
### See Also
* [md5()](function.md5) - Calculate the md5 hash of a string
* [sha1\_file()](function.sha1-file) - Calculate the sha1 hash of a file
* [crc32()](function.crc32) - Calculates the crc32 polynomial of a string
php addslashes addslashes
==========
(PHP 4, PHP 5, PHP 7, PHP 8)
addslashes — Quote string with slashes
### Description
```
addslashes(string $string): string
```
Returns a string with backslashes added before characters that need to be escaped. These characters are:
* single quote (`'`)
* double quote (`"`)
* backslash (`\`)
* NUL (the NUL byte)
A use case of **addslashes()** is escaping the aforementioned characters in a string that is to be evaluated by PHP:
```
<?php
$str = "O'Reilly?";
eval("echo '" . addslashes($str) . "';");
?>
```
The **addslashes()** is sometimes incorrectly used to try to prevent [SQL Injection](https://www.php.net/manual/en/security.database.sql-injection.php). Instead, database-specific escaping functions and/or prepared statements should be used.
### Parameters
`string`
The string to be escaped.
### Return Values
Returns the escaped string.
### Examples
**Example #1 An **addslashes()** example**
```
<?php
$str = "Is your name O'Reilly?";
// Outputs: Is your name O\'Reilly?
echo addslashes($str);
?>
```
### See Also
* [stripcslashes()](function.stripcslashes) - Un-quote string quoted with addcslashes
* [stripslashes()](function.stripslashes) - Un-quotes a quoted string
* [addcslashes()](function.addcslashes) - Quote string with slashes in a C style
* [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities
* [quotemeta()](function.quotemeta) - Quote meta characters
* [get\_magic\_quotes\_gpc()](function.get-magic-quotes-gpc) - Gets the current configuration setting of magic\_quotes\_gpc
php fdf_set_version fdf\_set\_version
=================
(PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN)
fdf\_set\_version — Sets version number for a FDF file
### Description
```
fdf_set_version(resource $fdf_document, string $version): bool
```
Sets the FDF `version` for the given document.
Some features supported by this extension are only available in newer FDF versions.
### Parameters
`fdf_document`
The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string).
`version`
The version number. For the current FDF toolkit 5.0, this may be either `1.2`, `1.3` or `1.4`.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [fdf\_get\_version()](function.fdf-get-version) - Gets version number for FDF API or file
php Yaf_Plugin_Abstract::dispatchLoopStartup Yaf\_Plugin\_Abstract::dispatchLoopStartup
==========================================
(Yaf >=1.0.0)
Yaf\_Plugin\_Abstract::dispatchLoopStartup — Hook before dispatch loop
### Description
```
public Yaf_Plugin_Abstract::dispatchLoopStartup(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void
```
### Parameters
`request`
`response`
### Return Values
php Phar::unlinkArchive Phar::unlinkArchive
===================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0)
Phar::unlinkArchive — Completely remove a phar archive from disk and from memory
### Description
```
final public static Phar::unlinkArchive(string $filename): bool
```
Removes a phar archive from disk and memory.
### Parameters
`filename`
The path on disk to the phar archive.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Errors/Exceptions
[PharException](class.pharexception) is thrown if there are any open file pointers to the phar archive, or any existing [Phar](class.phar), [PharData](class.phardata), or [PharFileInfo](class.pharfileinfo) objects referring to the phar archive.
### Examples
**Example #1 A **Phar::unlinkArchive()** example**
```
<?php
// simple usage
Phar::unlinkArchive('/path/to/my.phar');
// more common example:
$p = new Phar('my.phar');
$fp = fopen('phar://my.phar/file.txt', 'r');
// this creates 'my.phar.gz'
$gp = $p->compress(Phar::GZ);
// remove all references to the archive
unset($p);
fclose($fp);
// now remove all traces of the archive
Phar::unlinkArchive('my.phar');
?>
```
### See Also
* [Phar::delete()](phar.delete) - Delete a file within a phar archive
* [Phar::offsetUnset()](phar.offsetunset) - Remove a file from a phar
php SolrQuery::getMltFields SolrQuery::getMltFields
=======================
(PECL solr >= 0.9.2)
SolrQuery::getMltFields — Returns all the fields to use for similarity
### Description
```
public SolrQuery::getMltFields(): array
```
Returns all the fields to use for similarity
### Parameters
This function has no parameters.
### Return Values
Returns an array on success and **`null`** if not set.
php mb_ereg_search_pos mb\_ereg\_search\_pos
=====================
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
mb\_ereg\_search\_pos — Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
### Description
```
mb_ereg_search_pos(?string $pattern = null, ?string $options = null): array|false
```
Returns position and length of a matched part of the multibyte regular expression for a predefined multibyte string
The string for match is specified by [mb\_ereg\_search\_init()](function.mb-ereg-search-init). If it is not specified, the previous one will be used.
### Parameters
`pattern`
The search pattern.
`options`
The search option. See [mb\_regex\_set\_options()](function.mb-regex-set-options) for explanation.
### Return Values
An array containing two elements. The first element is the offset, in bytes, where the match begins relative to the start of the search string, and the second element is the length in bytes of the match.
If an error occurs, **`false`** is returned.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `pattern` and `options` are nullable now. |
### Notes
>
> **Note**:
>
>
> The internal encoding or the character encoding specified by [mb\_regex\_encoding()](function.mb-regex-encoding) will be used as the character encoding for this function.
>
>
>
### See Also
* [mb\_regex\_encoding()](function.mb-regex-encoding) - Set/Get character encoding for multibyte regex
* [mb\_ereg\_search\_init()](function.mb-ereg-search-init) - Setup string and regular expression for a multibyte regular expression match
| programming_docs |
php ldap_get_values ldap\_get\_values
=================
(PHP 4, PHP 5, PHP 7, PHP 8)
ldap\_get\_values — Get all values from a result entry
### Description
```
ldap_get_values(LDAP\Connection $ldap, LDAP\ResultEntry $entry, string $attribute): array|false
```
Reads all the values of the attribute in the entry in the result.
This call needs a `entry`, so needs to be preceded by one of the ldap search calls and one of the calls to get an individual entry.
You application will either be hard coded to look for certain attributes (such as "surname" or "mail") or you will have to use the [ldap\_get\_attributes()](function.ldap-get-attributes) call to work out what attributes exist for a given entry.
### Parameters
`ldap`
An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect).
`entry`
An [LDAP\ResultEntry](class.ldap-result-entry) instance.
`attribute`
### Return Values
Returns an array of values for the attribute on success and **`false`** on error. The number of values can be found by indexing "count" in the resultant array. Individual values are accessed by integer index in the array. The first index is 0.
LDAP allows more than one entry for an attribute, so it can, for example, store a number of email addresses for one person's directory entry all labeled with the attribute "mail"
```
return_value["count"] = number of values for attribute
return_value[0] = first value of attribute
return_value[i] = ith value of attribute
```
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. |
| 8.1.0 | The `entry` parameter expects an [LDAP\ResultEntry](class.ldap-result-entry) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 List all values of the "mail" attribute for a directory entry**
```
<?php
// $ds is a valid LDAP\Connection instance for a directory server
// $sr is a valid search result from a prior call to
// one of the ldap directory search calls
// $entry is a valid entry identifier from a prior call to
// one of the calls that returns a directory entry
$values = ldap_get_values($ds, $entry, "mail");
echo $values["count"] . " email addresses for this entry.<br />";
for ($i=0; $i < $values["count"]; $i++) {
echo $values[$i] . "<br />";
}
?>
```
### See Also
* [ldap\_get\_values\_len()](function.ldap-get-values-len) - Get all binary values from a result entry
php ReflectionClass::getInterfaceNames ReflectionClass::getInterfaceNames
==================================
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
ReflectionClass::getInterfaceNames — Gets the interface names
### Description
```
public ReflectionClass::getInterfaceNames(): array
```
Get the interface names.
### Parameters
This function has no parameters.
### Return Values
A numerical array with interface names as the values.
### Examples
**Example #1 **ReflectionClass::getInterfaceNames()** example**
```
<?php
interface Foo { }
interface Bar { }
class Baz implements Foo, Bar { }
$rc1 = new ReflectionClass("Baz");
print_r($rc1->getInterfaceNames());
?>
```
The above example will output something similar to:
```
Array
(
[0] => Foo
[1] => Bar
)
```
### See Also
* [ReflectionClass::getInterfaces()](reflectionclass.getinterfaces) - Gets the interfaces
php The Generator class
The Generator class
===================
Introduction
------------
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
**Generator** objects are returned from [generators](https://www.php.net/manual/en/language.generators.php).
**Caution** **Generator** objects cannot be instantiated via [new](language.oop5.basic#language.oop5.basic.new).
Class synopsis
--------------
final class **Generator** implements [Iterator](class.iterator) { /\* Methods \*/
```
public current(): mixed
```
```
public getReturn(): mixed
```
```
public key(): mixed
```
```
public next(): void
```
```
public rewind(): void
```
```
public send(mixed $value): mixed
```
```
public throw(Throwable $exception): mixed
```
```
public valid(): bool
```
```
public __wakeup(): void
```
} See Also
--------
See also [object iteration](language.oop5.iterations).
Table of Contents
-----------------
* [Generator::current](generator.current) — Get the yielded value
* [Generator::getReturn](generator.getreturn) — Get the return value of a generator
* [Generator::key](generator.key) — Get the yielded key
* [Generator::next](generator.next) — Resume execution of the generator
* [Generator::rewind](generator.rewind) — Rewind the iterator
* [Generator::send](generator.send) — Send a value to the generator
* [Generator::throw](generator.throw) — Throw an exception into the generator
* [Generator::valid](generator.valid) — Check if the iterator has been closed
* [Generator::\_\_wakeup](generator.wakeup) — Serialize callback
php pspell_clear_session pspell\_clear\_session
======================
(PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8)
pspell\_clear\_session — Clear the current session
### Description
```
pspell_clear_session(PSpell\Dictionary $dictionary): bool
```
**pspell\_clear\_session()** clears the current session. The current wordlist becomes blank, and, for example, if you try to save it with [pspell\_save\_wordlist()](function.pspell-save-wordlist), nothing happens.
### Parameters
`dictionary`
An [PSpell\Dictionary](class.pspell-dictionary) instance.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `dictionary` parameter expects an [PSpell\Dictionary](class.pspell-dictionary) instance now; previously, a [resource](language.types.resource) was expected. |
### Examples
**Example #1 [pspell\_add\_to\_personal()](function.pspell-add-to-personal) Example**
```
<?php
$pspell_config = pspell_config_create("en");
pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws");
$pspell = pspell_new_config($pspell_config);
pspell_add_to_personal($pspell, "Vlad");
pspell_clear_session($pspell);
pspell_save_wordlist($pspell); //"Vlad" will not be saved
?>
```
php preg_grep preg\_grep
==========
(PHP 4, PHP 5, PHP 7, PHP 8)
preg\_grep — Return array entries that match the pattern
### Description
```
preg_grep(string $pattern, array $array, int $flags = 0): array|false
```
Returns the array consisting of the elements of the `array` array that match the given `pattern`.
### Parameters
`pattern`
The pattern to search for, as a string.
`array`
The input array.
`flags`
If set to **`PREG_GREP_INVERT`**, this function returns the elements of the input array that do *not* match the given `pattern`.
### Return Values
Returns an array indexed using the keys from the `array` array, or **`false`** on failure.
### Errors/Exceptions
If the regex pattern passed does not compile to a valid regex, an **`E_WARNING`** is emitted.
### Examples
**Example #1 **preg\_grep()** example**
```
<?php
// return all array elements
// containing floating point numbers
$fl_array = preg_grep("/^(\d+)?\.\d+$/", $array);
?>
```
### See Also
* [PCRE Patterns](https://www.php.net/manual/en/pcre.pattern.php)
* [preg\_quote()](function.preg-quote) - Quote regular expression characters
* [preg\_match\_all()](function.preg-match-all) - Perform a global regular expression match
* [preg\_filter()](function.preg-filter) - Perform a regular expression search and replace
* [preg\_last\_error()](function.preg-last-error) - Returns the error code of the last PCRE regex execution
php localtime localtime
=========
(PHP 4, PHP 5, PHP 7, PHP 8)
localtime — Get the local time
### Description
```
localtime(?int $timestamp = null, bool $associative = false): array
```
The **localtime()** function returns an array identical to that of the structure returned by the C function call.
### Parameters
`timestamp`
The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or **`null`**. In other words, it defaults to the value of [time()](function.time).
`associative`
Determines whether the function should return a regular, numerically indexed array, or an associative one.
### Return Values
If `associative` is set to **`false`** or not supplied then the array is returned as a regular, numerically indexed array. If `associative` is set to **`true`** then **localtime()** returns an associative array containing the elements of the structure returned by the C function call to localtime. The keys of the associative array are as follows:
* "tm\_sec" - seconds, `0` to `59`
* "tm\_min" - minutes, `0` to `59`
* "tm\_hour" - hours, `0` to `23`
* "tm\_mday" - day of the month, `1` to `31`
* "tm\_mon" - month of the year, `0` (Jan) to `11` (Dec)
* "tm\_year" - years since 1900
* "tm\_wday" - day of the week, `0` (Sun) to `6` (Sat)
* "tm\_yday" - day of the year, `0` to `365`
* "tm\_isdst" - is daylight savings time in effect? Positive if yes, `0` if not, negative if unknown.
### Errors/Exceptions
Every call to a date/time function will generate a **`E_WARNING`** if the time zone is not valid. See also [date\_default\_timezone\_set()](function.date-default-timezone-set)
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `timestamp` is nullable now. |
### Examples
**Example #1 **localtime()** example**
```
<?php
$localtime = localtime();
$localtime_assoc = localtime(time(), true);
print_r($localtime);
print_r($localtime_assoc);
?>
```
The above example will output something similar to:
```
Array
(
[0] => 24
[1] => 3
[2] => 19
[3] => 3
[4] => 3
[5] => 105
[6] => 0
[7] => 92
[8] => 1
)
Array
(
[tm_sec] => 24
[tm_min] => 3
[tm_hour] => 19
[tm_mday] => 3
[tm_mon] => 3
[tm_year] => 105
[tm_wday] => 0
[tm_yday] => 92
[tm_isdst] => 1
)
```
### See Also
* [getdate()](function.getdate) - Get date/time information
php curl_error curl\_error
===========
(PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8)
curl\_error — Return a string containing the last error for the current session
### Description
```
curl_error(CurlHandle $handle): string
```
Returns a clear text error message for the last cURL operation.
### Parameters
`handle` A cURL handle returned by [curl\_init()](function.curl-init).
### Return Values
Returns the error message or `''` (the empty string) if no error occurred.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `handle` expects a [CurlHandle](class.curlhandle) instance now; previously, a resource was expected. |
### Examples
**Example #1 **curl\_error()** example**
```
<?php
// Create a curl handle to a non-existing location
$ch = curl_init('http://404.php.net/');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if(curl_exec($ch) === false)
{
echo 'Curl error: ' . curl_error($ch);
}
else
{
echo 'Operation completed without any errors';
}
// Close handle
curl_close($ch);
?>
```
### See Also
* [curl\_errno()](function.curl-errno) - Return the last error number
* [» Curl error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html)
php RecursiveTreeIterator::beginChildren RecursiveTreeIterator::beginChildren
====================================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
RecursiveTreeIterator::beginChildren — Begin children
### Description
```
public RecursiveTreeIterator::beginChildren(): void
```
Called when recursing one level down.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php posix_getgroups posix\_getgroups
================
(PHP 4, PHP 5, PHP 7, PHP 8)
posix\_getgroups — Return the group set of the current process
### Description
```
posix_getgroups(): array|false
```
Gets the group set of the current process.
### Parameters
This function has no parameters.
### Return Values
Returns an array of integers containing the numeric group ids of the group set of the current process, or **`false`** on failure.
### Examples
**Example #1 Example use of **posix\_getgroups()****
```
<?php
$groups = posix_getgroups();
print_r($groups);
?>
```
The above example will output something similar to:
```
Array
(
[0] => 4
[1] => 20
[2] => 24
[3] => 25
[4] => 29
[5] => 30
[6] => 33
[7] => 44
[8] => 46
[9] => 104
[10] => 109
[11] => 110
[12] => 1000
)
```
### See Also
* [posix\_getgrgid()](function.posix-getgrgid) - Return info about a group by group id
php OAuth::fetch OAuth::fetch
============
(PECL OAuth >= 0.99.1)
OAuth::fetch — Fetch an OAuth protected resource
### Description
```
public OAuth::fetch(
string $protected_resource_url,
array $extra_parameters = ?,
string $http_method = ?,
array $http_headers = ?
): mixed
```
Fetch a resource.
### Parameters
`protected_resource_url`
URL to the OAuth protected resource.
`extra_parameters`
Extra parameters to send with the request for the resource.
`http_method`
One of the **`OAUTH_HTTP_METHOD_*`** [OAUTH constants](https://www.php.net/manual/en/oauth.constants.php), which includes GET, POST, PUT, HEAD, or DELETE.
HEAD (**`OAUTH_HTTP_METHOD_HEAD`**) can be useful for discovering information prior to the request (if OAuth credentials are in the `Authorization` header).
`http_headers`
HTTP client headers (such as User-Agent, Accept, etc.)
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| PECL oauth 1.0.0 | Previously returned **`null`** on failure, instead of **`false`**. |
| PECL oauth 0.99.5 | The `http_method` parameter was added |
| PECL oauth 0.99.8 | The `http_headers` parameter was added |
### Examples
**Example #1 **OAuth::fetch()** example**
```
<?php
try {
$oauth = new OAuth("consumer_key","consumer_secret",OAUTH_SIG_METHOD_HMACSHA1,OAUTH_AUTH_TYPE_AUTHORIZATION);
$oauth->setToken("access_token","access_token_secret");
$oauth->fetch("http://photos.example.net/photo?file=vacation.jpg");
$response_info = $oauth->getLastResponseInfo();
header("Content-Type: {$response_info["content_type"]}");
echo $oauth->getLastResponse();
} catch(OAuthException $E) {
echo "Exception caught!\n";
echo "Response: ". $E->lastResponse . "\n";
}
?>
```
### See Also
* [OAuth::getLastResponse()](oauth.getlastresponse) - Get the last response
* [OAuth::getLastResponseInfo()](oauth.getlastresponseinfo) - Get HTTP information about the last response
* [OAuth::setToken()](oauth.settoken) - Sets the token and secret
php base64_decode base64\_decode
==============
(PHP 4, PHP 5, PHP 7, PHP 8)
base64\_decode — Decodes data encoded with MIME base64
### Description
```
base64_decode(string $string, bool $strict = false): string|false
```
Decodes a base64 encoded `string`.
### Parameters
`string`
The encoded data.
`strict`
If the `strict` parameter is set to **`true`** then the **base64\_decode()** function will return **`false`** if the input contains character from outside the base64 alphabet. Otherwise invalid characters will be silently discarded.
### Return Values
Returns the decoded data or **`false`** on failure. The returned data may be binary.
### Examples
**Example #1 **base64\_decode()** example**
```
<?php
$str = 'VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==';
echo base64_decode($str);
?>
```
The above example will output:
```
This is an encoded string
```
### See Also
* [base64\_encode()](function.base64-encode) - Encodes data with MIME base64
* [» RFC 2045](http://www.faqs.org/rfcs/rfc2045) section 6.8
php ob_flush ob\_flush
=========
(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)
ob\_flush — Flush (send) the output buffer
### Description
```
ob_flush(): bool
```
This function will send the contents of the output buffer (if any). If you want to further process the buffer's contents you have to call [ob\_get\_contents()](function.ob-get-contents) before **ob\_flush()** as the buffer contents are discarded after **ob\_flush()** is called.
This function does not destroy the output buffer like [ob\_end\_flush()](function.ob-end-flush) does.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### See Also
* [ob\_get\_contents()](function.ob-get-contents) - Return the contents of the output buffer
* [ob\_clean()](function.ob-clean) - Clean (erase) the output buffer
* [ob\_end\_flush()](function.ob-end-flush) - Flush (send) the output buffer and turn off output buffering
* [ob\_end\_clean()](function.ob-end-clean) - Clean (erase) the output buffer and turn off output buffering
php readline_info readline\_info
==============
(PHP 4, PHP 5, PHP 7, PHP 8)
readline\_info — Gets/sets various internal readline variables
### Description
```
readline_info(?string $var_name = null, int|string|bool|null $value = null): mixed
```
Gets or sets various internal readline variables.
### Parameters
`var_name`
A variable name.
`value`
If provided, this will be the new value of the setting.
### Return Values
If called with no parameters, this function returns an array of values for all the settings readline uses. The elements will be indexed by the following values: `done`, `end`, `erase_empty_line`, `library_version`, `line_buffer`, `mark`, `pending_input`, `point`, `prompt`, `readline_name`, and `terminal_name`. The array will only contain those elements which are supported by the library used to built the readline extension.
If called with one or two parameters, the old value is returned.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `var_name` and `value` are nullable now. |
php Componere\Method::getReflector Componere\Method::getReflector
==============================
(Componere 2 >= 2.1.0)
Componere\Method::getReflector — Reflection
### Description
```
public Componere\Method::getReflector(): ReflectionMethod
```
Shall create or return a ReflectionMethod
### Return Values
A ReflectionMethod for the current method (cached)
php array_unshift array\_unshift
==============
(PHP 4, PHP 5, PHP 7, PHP 8)
array\_unshift — Prepend one or more elements to the beginning of an array
### Description
```
array_unshift(array &$array, mixed ...$values): int
```
**array\_unshift()** prepends passed elements to the front of the `array`. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be changed.
>
> **Note**:
>
>
> Resets array's internal pointer to the first element.
>
>
### Parameters
`array`
The input array.
`values`
The values to prepend.
### Return Values
Returns the new number of elements in the `array`.
### Changelog
| Version | Description |
| --- | --- |
| 7.3.0 | This function can now be called with only one parameter. Formerly, at least two parameters have been required. |
### Examples
**Example #1 **array\_unshift()** example**
```
<?php
$queue = [
"orange",
"banana"
];
array_unshift($queue, "apple", "raspberry");
var_dump($queue);
?>
```
The above example will output:
```
array(4) {
[0] =>
string(5) "apple"
[1] =>
string(9) "raspberry"
[2] =>
string(6) "orange"
[3] =>
string(6) "banana"
}
```
**Example #2 Usage with associative arrays**
If one associative array is prepended to another associative array, the prepended array is numerically indexed into the former array.
```
<?php
$foods = [
'apples' => [
'McIntosh' => 'red',
'Granny Smith' => 'green',
],
'oranges' => [
'Navel' => 'orange',
'Valencia' => 'orange',
],
];
$vegetables = [
'lettuce' => [
'Iceberg' => 'green',
'Butterhead' => 'green',
],
'carrots' => [
'Deep Purple Hybrid' => 'purple',
'Imperator' => 'orange',
],
'cucumber' => [
'Kirby' => 'green',
'Gherkin' => 'green',
],
];
array_unshift($foods, $vegetables);
var_dump($foods);
```
The above example will output:
```
array(3) {
[0] =>
array(3) {
'lettuce' =>
array(2) {
'Iceberg' =>
string(5) "green"
'Butterhead' =>
string(5) "green"
}
'carrots' =>
array(2) {
'Deep Purple Hybrid' =>
string(6) "purple"
'Imperator' =>
string(6) "orange"
}
'cucumber' =>
array(2) {
'Kirby' =>
string(5) "green"
'Gherkin' =>
string(5) "green"
}
}
'apples' =>
array(2) {
'McIntosh' =>
string(3) "red"
'Granny Smith' =>
string(5) "green"
}
'oranges' =>
array(2) {
'Navel' =>
string(6) "orange"
'Valencia' =>
string(6) "orange"
}
}
```
### See Also
* [array\_merge()](function.array-merge) - Merge one or more arrays
* [array\_shift()](function.array-shift) - Shift an element off the beginning of array
* [array\_push()](function.array-push) - Push one or more elements onto the end of array
* [array\_pop()](function.array-pop) - Pop the element off the end of array
| programming_docs |
php xdiff_file_diff_binary xdiff\_file\_diff\_binary
=========================
(PECL xdiff >= 0.2.0)
xdiff\_file\_diff\_binary — Alias of [xdiff\_file\_bdiff()](function.xdiff-file-bdiff)
### Description
```
xdiff_file_diff_binary(string $old_file, string $new_file, string $dest): bool
```
Makes a binary diff of two files and stores the result in a patch file. This function works with both text and binary files. Resulting patch file can be later applied using [xdiff\_file\_bpatch()](function.xdiff-file-bpatch).
Starting with version 1.5.0 this function is an alias of [xdiff\_file\_bdiff()](function.xdiff-file-bdiff).
### Parameters
`old_file`
Path to the first file. This file acts as "old" file.
`new_file`
Path to the second file. This file acts as "new" file.
`dest`
Path of the resulting patch file. Resulting file contains differences between "old" and "new" files. It is in binary format and is human-unreadable.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **xdiff\_file\_diff\_binary()** example**
The following code makes binary diff of two archives.
```
<?php
$old_version = 'my_script_1.0.tgz';
$new_version = 'my_script_1.1.tgz';
xdiff_file_diff_binary($old_version, $new_version, 'my_script.bdiff');
?>
```
### Notes
>
> **Note**:
>
>
> Both files will be loaded into memory so ensure that your memory\_limit is set high enough.
>
>
### See Also
* [xdiff\_file\_bdiff()](function.xdiff-file-bdiff) - Make binary diff of two files
* [xdiff\_file\_bpatch()](function.xdiff-file-bpatch) - Patch a file with a binary diff
php The XMLParser class
The XMLParser class
===================
Introduction
------------
(PHP 8)
A fully opaque class which replaces `xml` resources as of PHP 8.0.0.
Class synopsis
--------------
final class **XMLParser** { /\* Methods \*/ public [\_\_construct](xmlparser.construct)() } Table of Contents
-----------------
* [XMLParser::\_\_construct](xmlparser.construct) — Construct a new XMLParser instance
php gzgetc gzgetc
======
(PHP 4, PHP 5, PHP 7, PHP 8)
gzgetc — Get character from gz-file pointer
### Description
```
gzgetc(resource $stream): string|false
```
Returns a string containing a single (uncompressed) character read from the given gz-file pointer.
### Parameters
`stream`
The gz-file pointer. It must be valid, and must point to a file successfully opened by [gzopen()](function.gzopen).
### Return Values
The uncompressed character or **`false`** on EOF (unlike [gzeof()](function.gzeof)).
### Examples
**Example #1 **gzgetc()** example**
```
<?php
$gz = gzopen('somefile.gz', 'r');
while (!gzeof($gz)) {
echo gzgetc($gz);
}
gzclose($gz);
?>
```
### See Also
* [gzopen()](function.gzopen) - Open gz-file
* [gzgets()](function.gzgets) - Get line from file pointer
php ibase_connect ibase\_connect
==============
(PHP 5, PHP 7 < 7.4.0)
ibase\_connect — Open a connection to a database
### Description
```
ibase_connect(
string $database = ?,
string $username = ?,
string $password = ?,
string $charset = ?,
int $buffers = ?,
int $dialect = ?,
string $role = ?,
int $sync = ?
): resource
```
Establishes a connection to an Firebird/InterBase server.
In case a second call is made to **ibase\_connect()** with the same arguments, no new link will be established, but instead, the link identifier of the already opened link will be returned. The link to the server will be closed as soon as the execution of the script ends, unless it's closed earlier by explicitly calling [ibase\_close()](function.ibase-close).
### Parameters
`database`
The `database` argument has to be a valid path to database file on the server it resides on. If the server is not local, it must be prefixed with either 'hostname:' (TCP/IP), 'hostname/port:' (TCP/IP with interbase server on custom TCP port), '//hostname/' (NetBEUI), depending on the connection protocol used.
`username`
The user name. Can be set with the `ibase.default_user` php.ini directive.
`password`
The password for `username`. Can be set with the `ibase.default_password` php.ini directive.
`charset`
`charset` is the default character set for a database.
`buffers`
`buffers` is the number of database buffers to allocate for the server-side cache. If 0 or omitted, server chooses its own default.
`dialect`
`dialect` selects the default SQL dialect for any statement executed within a connection, and it defaults to the highest one supported by client libraries.
`role`
Functional only with InterBase 5 and up.
`sync`
### Return Values
Returns an Firebird/InterBase link identifier on success, or **`false`** on error.
### Errors/Exceptions
If you get some error like "arithmetic exception, numeric overflow, or string truncation. Cannot transliterate character between character sets" (this occurs when you try use some character with accents) when using this and after [ibase\_query()](function.ibase-query) you must set the character set (i.e. ISO8859\_1 or your current character set).
### Examples
**Example #1 **ibase\_connect()** example**
```
<?php
$host = 'localhost:/path/to/your.gdb';
$dbh = ibase_connect($host, $username, $password);
$stmt = 'SELECT * FROM tblname';
$sth = ibase_query($dbh, $stmt);
while ($row = ibase_fetch_object($sth)) {
echo $row->email, "\n";
}
ibase_free_result($sth);
ibase_close($dbh);
?>
```
### See Also
* [ibase\_pconnect()](function.ibase-pconnect) - Open a persistent connection to an InterBase database
* [ibase\_close()](function.ibase-close) - Close a connection to an InterBase database
php The RarEntry class
The RarEntry class
==================
Introduction
------------
(PECL rar >= 0.1)
A RAR entry, representing a directory or a compressed file inside a RAR archive.
Class synopsis
--------------
final class **RarEntry** { /\* Constants \*/ const int [HOST\_MSDOS](class.rarentry#rarentry.constants.host-msdos) = 0;
const int [HOST\_OS2](class.rarentry#rarentry.constants.host-os2) = 1;
const int [HOST\_WIN32](class.rarentry#rarentry.constants.host-win32) = 2;
const int [HOST\_UNIX](class.rarentry#rarentry.constants.host-unix) = 3;
const int [HOST\_MACOS](class.rarentry#rarentry.constants.host-macos) = 4;
const int [HOST\_BEOS](class.rarentry#rarentry.constants.host-beos) = 5;
const int [ATTRIBUTE\_WIN\_READONLY](class.rarentry#rarentry.constants.attribute-win-readonly) = 1;
const int [ATTRIBUTE\_WIN\_HIDDEN](class.rarentry#rarentry.constants.attribute-win-hidden) = 2;
const int [ATTRIBUTE\_WIN\_SYSTEM](class.rarentry#rarentry.constants.attribute-win-system) = 4;
const int [ATTRIBUTE\_WIN\_DIRECTORY](class.rarentry#rarentry.constants.attribute-win-directory) = 16;
const int [ATTRIBUTE\_WIN\_ARCHIVE](class.rarentry#rarentry.constants.attribute-win-archive) = 32;
const int [ATTRIBUTE\_WIN\_DEVICE](class.rarentry#rarentry.constants.attribute-win-device) = 64;
const int [ATTRIBUTE\_WIN\_NORMAL](class.rarentry#rarentry.constants.attribute-win-normal) = 128;
const int [ATTRIBUTE\_WIN\_TEMPORARY](class.rarentry#rarentry.constants.attribute-win-temporary) = 256;
const int [ATTRIBUTE\_WIN\_SPARSE\_FILE](class.rarentry#rarentry.constants.attribute-win-sparse-file) = 512;
const int [ATTRIBUTE\_WIN\_REPARSE\_POINT](class.rarentry#rarentry.constants.attribute-win-reparse-point) = 1024;
const int [ATTRIBUTE\_WIN\_COMPRESSED](class.rarentry#rarentry.constants.attribute-win-compressed) = 2048;
const int [ATTRIBUTE\_WIN\_OFFLINE](class.rarentry#rarentry.constants.attribute-win-offline) = 4096;
const int [ATTRIBUTE\_WIN\_NOT\_CONTENT\_INDEXED](class.rarentry#rarentry.constants.attribute-win-not-content-indexed) = 8192;
const int [ATTRIBUTE\_WIN\_ENCRYPTED](class.rarentry#rarentry.constants.attribute-win-encrypted) = 16384;
const int [ATTRIBUTE\_WIN\_VIRTUAL](class.rarentry#rarentry.constants.attribute-win-virtual) = 65536;
const int [ATTRIBUTE\_UNIX\_WORLD\_EXECUTE](class.rarentry#rarentry.constants.attribute-unix-world-execute) = 1;
const int [ATTRIBUTE\_UNIX\_WORLD\_WRITE](class.rarentry#rarentry.constants.attribute-unix-world-write) = 2;
const int [ATTRIBUTE\_UNIX\_WORLD\_READ](class.rarentry#rarentry.constants.attribute-unix-world-read) = 4;
const int [ATTRIBUTE\_UNIX\_GROUP\_EXECUTE](class.rarentry#rarentry.constants.attribute-unix-group-execute) = 8;
const int [ATTRIBUTE\_UNIX\_GROUP\_WRITE](class.rarentry#rarentry.constants.attribute-unix-group-write) = 16;
const int [ATTRIBUTE\_UNIX\_GROUP\_READ](class.rarentry#rarentry.constants.attribute-unix-group-read) = 32;
const int [ATTRIBUTE\_UNIX\_OWNER\_EXECUTE](class.rarentry#rarentry.constants.attribute-unix-owner-execute) = 64;
const int [ATTRIBUTE\_UNIX\_OWNER\_WRITE](class.rarentry#rarentry.constants.attribute-unix-owner-write) = 128;
const int [ATTRIBUTE\_UNIX\_OWNER\_READ](class.rarentry#rarentry.constants.attribute-unix-owner-read) = 256;
const int [ATTRIBUTE\_UNIX\_STICKY](class.rarentry#rarentry.constants.attribute-unix-sticky) = 512;
const int [ATTRIBUTE\_UNIX\_SETGID](class.rarentry#rarentry.constants.attribute-unix-setgid) = 1024;
const int [ATTRIBUTE\_UNIX\_SETUID](class.rarentry#rarentry.constants.attribute-unix-setuid) = 2048;
const int [ATTRIBUTE\_UNIX\_FINAL\_QUARTET](class.rarentry#rarentry.constants.attribute-unix-final-quartet) = 61440;
const int [ATTRIBUTE\_UNIX\_FIFO](class.rarentry#rarentry.constants.attribute-unix-fifo) = 4096;
const int [ATTRIBUTE\_UNIX\_CHAR\_DEV](class.rarentry#rarentry.constants.attribute-unix-char-dev) = 8192;
const int [ATTRIBUTE\_UNIX\_DIRECTORY](class.rarentry#rarentry.constants.attribute-unix-directory) = 16384;
const int [ATTRIBUTE\_UNIX\_BLOCK\_DEV](class.rarentry#rarentry.constants.attribute-unix-block-dev) = 24576;
const int [ATTRIBUTE\_UNIX\_REGULAR\_FILE](class.rarentry#rarentry.constants.attribute-unix-regular-file) = 32768;
const int [ATTRIBUTE\_UNIX\_SYM\_LINK](class.rarentry#rarentry.constants.attribute-unix-sym-link) = 40960;
const int [ATTRIBUTE\_UNIX\_SOCKET](class.rarentry#rarentry.constants.attribute-unix-socket) = 49152; /\* Methods \*/
```
public extract(
string $dir,
string $filepath = "",
string $password = NULL,
bool $extended_data = false
): bool
```
```
public getAttr(): int
```
```
public getCrc(): string
```
```
public getFileTime(): string
```
```
public getHostOs(): int
```
```
public getMethod(): int
```
```
public getName(): string
```
```
public getPackedSize(): int
```
```
public getStream(string $password = ?): resource|false
```
```
public getUnpackedSize(): int
```
```
public getVersion(): int
```
```
public isDirectory(): bool
```
```
public isEncrypted(): bool
```
```
public __toString(): string
```
} Predefined Constants
--------------------
**`RarEntry::HOST_MSDOS`** If the return value of [RarEntry::getHostOs()](rarentry.gethostos) equals this constant, MS-DOS was used to add this entry. Use instead of **`RAR_HOST_MSDOS`**.
**`RarEntry::HOST_OS2`** If the return value of [RarEntry::getHostOs()](rarentry.gethostos) equals this constant, OS/2 was used to add this entry. Intended to replace **`RAR_HOST_OS2`**.
**`RarEntry::HOST_WIN32`** If the return value of [RarEntry::getHostOs()](rarentry.gethostos) equals this constant, Microsoft Windows was used to add this entry. Intended to replace **`RAR_HOST_WIN32`**.
**`RarEntry::HOST_UNIX`** If the return value of [RarEntry::getHostOs()](rarentry.gethostos) equals this constant, an unspecified UNIX OS was used to add this entry. Intended to replace **`RAR_HOST_UNIX`**.
**`RarEntry::HOST_MACOS`** If the return value of [RarEntry::getHostOs()](rarentry.gethostos) equals this constant, Mac OS was used to add this entry.
**`RarEntry::HOST_BEOS`** If the return value of [RarEntry::getHostOs()](rarentry.gethostos) equals this constant, BeOS was used to add this entry. Intended to replace **`RAR_HOST_BEOS`**.
**`RarEntry::ATTRIBUTE_WIN_READONLY`** Bit that represents a Windows entry with a read-only attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_HIDDEN`** Bit that represents a Windows entry with a hidden attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_SYSTEM`** Bit that represents a Windows entry with a system attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_DIRECTORY`** Bit that represents a Windows entry with a directory attribute (entry is a directory). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows. See also [RarEntry::isDirectory()](rarentry.isdirectory), which also works with entries that were not added in WinRAR.
**`RarEntry::ATTRIBUTE_WIN_ARCHIVE`** Bit that represents a Windows entry with an archive attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_DEVICE`** Bit that represents a Windows entry with a device attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_NORMAL`** Bit that represents a Windows entry with a normal file attribute (entry is NOT a directory). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows. See also [RarEntry::isDirectory()](rarentry.isdirectory), which also works with entries that were not added in WinRAR.
**`RarEntry::ATTRIBUTE_WIN_TEMPORARY`** Bit that represents a Windows entry with a temporary attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_SPARSE_FILE`** Bit that represents a Windows entry with a sparse file attribute (file is an NTFS sparse file). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_REPARSE_POINT`** Bit that represents a Windows entry with a reparse point attribute (entry is an NTFS reparse point, e.g. a directory junction or a mount file system). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_COMPRESSED`** Bit that represents a Windows entry with a compressed attribute (NTFS only). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_OFFLINE`** Bit that represents a Windows entry with an offline attribute (entry is offline and not accessible). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_NOT_CONTENT_INDEXED`** Bit that represents a Windows entry with a not content indexed attribute (entry is to be indexed). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_ENCRYPTED`** Bit that represents a Windows entry with an encrypted attribute (NTFS only). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_WIN_VIRTUAL`** Bit that represents a Windows entry with a virtual attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is Microsoft Windows.
**`RarEntry::ATTRIBUTE_UNIX_WORLD_EXECUTE`** Bit that represents a UNIX entry that is world executable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_WORLD_WRITE`** Bit that represents a UNIX entry that is world writable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_WORLD_READ`** Bit that represents a UNIX entry that is world readable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_GROUP_EXECUTE`** Bit that represents a UNIX entry that is group executable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_GROUP_WRITE`** Bit that represents a UNIX entry that is group writable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_GROUP_READ`** Bit that represents a UNIX entry that is group readable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_OWNER_EXECUTE`** Bit that represents a UNIX entry that is owner executable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_OWNER_WRITE`** Bit that represents a UNIX entry that is owner writable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_OWNER_READ`** Bit that represents a UNIX entry that is owner readable. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_STICKY`** Bit that represents the UNIX sticky bit. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_SETGID`** Bit that represents the UNIX setgid attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_SETUID`** Bit that represents the UNIX setuid attribute. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX.
**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`** Mask to isolate the last four bits (nibble) of UNIX attributes (\_S\_IFMT, the type of file mask). To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constants [**`RarEntry::ATTRIBUTE_UNIX_FIFO`**](class.rarentry#rarentry.constants.attribute-unix-fifo), [**`RarEntry::ATTRIBUTE_UNIX_CHAR_DEV`**](class.rarentry#rarentry.constants.attribute-unix-char-dev), [**`RarEntry::ATTRIBUTE_UNIX_DIRECTORY`**](class.rarentry#rarentry.constants.attribute-unix-directory), [**`RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV`**](class.rarentry#rarentry.constants.attribute-unix-block-dev), [**`RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE`**](class.rarentry#rarentry.constants.attribute-unix-regular-file), [**`RarEntry::ATTRIBUTE_UNIX_SYM_LINK`**](class.rarentry#rarentry.constants.attribute-unix-sym-link) and [**`RarEntry::ATTRIBUTE_UNIX_SOCKET`**](class.rarentry#rarentry.constants.attribute-unix-socket).
**`RarEntry::ATTRIBUTE_UNIX_FIFO`** Unix FIFOs will have attributes whose last four bits have this value. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constant [**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`**](class.rarentry#rarentry.constants.attribute-unix-final-quartet).
**`RarEntry::ATTRIBUTE_UNIX_CHAR_DEV`** Unix character devices will have attributes whose last four bits have this value. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constant [**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`**](class.rarentry#rarentry.constants.attribute-unix-final-quartet).
**`RarEntry::ATTRIBUTE_UNIX_DIRECTORY`** Unix directories will have attributes whose last four bits have this value. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constant [**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`**](class.rarentry#rarentry.constants.attribute-unix-final-quartet). See also [RarEntry::isDirectory()](rarentry.isdirectory), which also works with entries that were added in other operating systems.
**`RarEntry::ATTRIBUTE_UNIX_BLOCK_DEV`** Unix block devices will have attributes whose last four bits have this value. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constant [**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`**](class.rarentry#rarentry.constants.attribute-unix-final-quartet).
**`RarEntry::ATTRIBUTE_UNIX_REGULAR_FILE`** Unix regular files (not directories) will have attributes whose last four bits have this value. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constant [**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`**](class.rarentry#rarentry.constants.attribute-unix-final-quartet). See also [RarEntry::isDirectory()](rarentry.isdirectory), which also works with entries that were added in other operating systems.
**`RarEntry::ATTRIBUTE_UNIX_SYM_LINK`** Unix symbolic links will have attributes whose last four bits have this value. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constant [**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`**](class.rarentry#rarentry.constants.attribute-unix-final-quartet).
**`RarEntry::ATTRIBUTE_UNIX_SOCKET`** Unix sockets will have attributes whose last four bits have this value. To be used with [RarEntry::getAttr()](rarentry.getattr) on entries whose host OS is UNIX and with the constant [**`RarEntry::ATTRIBUTE_UNIX_FINAL_QUARTET`**](class.rarentry#rarentry.constants.attribute-unix-final-quartet).
Table of Contents
-----------------
* [RarEntry::extract](rarentry.extract) — Extract entry from the archive
* [RarEntry::getAttr](rarentry.getattr) — Get attributes of the entry
* [RarEntry::getCrc](rarentry.getcrc) — Get CRC of the entry
* [RarEntry::getFileTime](rarentry.getfiletime) — Get entry last modification time
* [RarEntry::getHostOs](rarentry.gethostos) — Get entry host OS
* [RarEntry::getMethod](rarentry.getmethod) — Get pack method of the entry
* [RarEntry::getName](rarentry.getname) — Get name of the entry
* [RarEntry::getPackedSize](rarentry.getpackedsize) — Get packed size of the entry
* [RarEntry::getStream](rarentry.getstream) — Get file handler for entry
* [RarEntry::getUnpackedSize](rarentry.getunpackedsize) — Get unpacked size of the entry
* [RarEntry::getVersion](rarentry.getversion) — Get minimum version of RAR program required to unpack the entry
* [RarEntry::isDirectory](rarentry.isdirectory) — Test whether an entry represents a directory
* [RarEntry::isEncrypted](rarentry.isencrypted) — Test whether an entry is encrypted
* [RarEntry::\_\_toString](rarentry.tostring) — Get text representation of entry
| programming_docs |
php Yaf_View_Simple::__get Yaf\_View\_Simple::\_\_get
==========================
(Yaf >=1.0.0)
Yaf\_View\_Simple::\_\_get — Retrieve assigned variable
### Description
```
public Yaf_View_Simple::__get(string $name = ?): void
```
Retrieve assigned varaiable
>
> **Note**:
>
>
> parameter can be empty since 2.1.11
>
>
### Parameters
`name`
the assigned variable name
if this is empty, all assigned variables will be returned
### Return Values
php ibase_set_event_handler ibase\_set\_event\_handler
==========================
(PHP 5, PHP 7 < 7.4.0)
ibase\_set\_event\_handler — Register a callback function to be called when events are posted
### Description
```
ibase_set_event_handler(callable $event_handler, string $event_name, string ...$even_names): resource
```
```
ibase_set_event_handler(
resource $connection,
callable $event_handler,
string $event_name,
string ...$event_names
): resource
```
This function registers a PHP user function as event handler for the specified events.
### Parameters
`event_handler`
The callback is called with the event name and the link resource as arguments whenever one of the specified events is posted by the database.
The callback must return **`false`** if the event handler should be canceled. Any other return value is ignored. This function accepts up to 15 event arguments.
`event_name`
An event name.
`event_names`
At most 15 events allowed.
### Return Values
The return value is an event resource. This resource can be used to free the event handler using [ibase\_free\_event\_handler()](function.ibase-free-event-handler).
### Examples
**Example #1 **ibase\_set\_event\_handler()** example**
```
<?php
function event_handler($event_name, $link)
{
if ($event_name == "NEW ORDER") {
// process new order
ibase_query($link, "UPDATE orders SET status='handled'");
} else if ($event_name == "DB_SHUTDOWN") {
// free event handler
return false;
}
}
ibase_set_event_handler($link, "event_handler", "NEW_ORDER", "DB_SHUTDOWN");
?>
```
### See Also
* [ibase\_free\_event\_handler()](function.ibase-free-event-handler) - Cancels a registered event handler
* [ibase\_wait\_event()](function.ibase-wait-event) - Wait for an event to be posted by the database
php runkit7_method_redefine runkit7\_method\_redefine
=========================
(PECL runkit7 >= Unknown)
runkit7\_method\_redefine — Dynamically changes the code of the given method
### Description
```
runkit7_method_redefine(
string $class_name,
string $method_name,
string $argument_list,
string $code,
int $flags = RUNKIT7_ACC_PUBLIC,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool
```
```
runkit7_method_redefine(
string $class_name,
string $method_name,
Closure $closure,
int $flags = RUNKIT7_ACC_PUBLIC,
string $doc_comment = null,
string $return_type = ?,
bool $is_strict = ?
): bool
```
### Parameters
`class_name`
The class in which to redefine the method
`method_name`
The name of the method to redefine
`argument_list`
Comma-delimited list of arguments for the redefined method
`code`
The new code to be evaluated when `method_name` is called
`closure`
A [closure](class.closure) that defines the method.
`flags`
The redefined method can be **`RUNKIT7_ACC_PUBLIC`**, **`RUNKIT7_ACC_PROTECTED`** or **`RUNKIT7_ACC_PRIVATE`** optionally combined via bitwise OR with **`RUNKIT7_ACC_STATIC`**
`doc_comment`
The doc comment of the method.
`return_type`
The return type of the method.
`is_strict`
Whether the method behaves as if it was declared in a file with `strict_types=1`.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Examples
**Example #1 **runkit7\_method\_redefine()** example**
```
<?php
class Example {
function foo() {
return "foo!\n";
}
}
// create an Example object
$e = new Example();
// output Example::foo() (before redefine)
echo "Before: " . $e->foo();
// Redefine the 'foo' method
runkit7_method_redefine(
'Example',
'foo',
'',
'return "bar!\n";',
RUNKIT7_ACC_PUBLIC
);
// output Example::foo() (after redefine)
echo "After: " . $e->foo();
?>
```
The above example will output:
```
Before: foo!
After: bar!
```
### See Also
* [runkit7\_method\_add()](function.runkit7-method-add) - Dynamically adds a new method to a given class
* [runkit7\_method\_copy()](function.runkit7-method-copy) - Copies a method from class to another
* [runkit7\_method\_remove()](function.runkit7-method-remove) - Dynamically removes the given method
* [runkit7\_method\_rename()](function.runkit7-method-rename) - Dynamically changes the name of the given method
* [runkit7\_function\_redefine()](function.runkit7-function-redefine) - Replace a function definition with a new implementation
php The InvalidArgumentException class
The InvalidArgumentException class
==================================
Introduction
------------
(PHP 5 >= 5.1.0, PHP 7, PHP 8)
Exception thrown if an argument is not of the expected type.
Class synopsis
--------------
class **InvalidArgumentException** extends [LogicException](class.logicexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = "";
private string [$string](class.exception#exception.props.string) = "";
protected int [$code](class.exception#exception.props.code);
protected string [$file](class.exception#exception.props.file) = "";
protected int [$line](class.exception#exception.props.line);
private array [$trace](class.exception#exception.props.trace) = [];
private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/
```
final public Exception::getMessage(): string
```
```
final public Exception::getPrevious(): ?Throwable
```
```
final public Exception::getCode(): int
```
```
final public Exception::getFile(): string
```
```
final public Exception::getLine(): int
```
```
final public Exception::getTrace(): array
```
```
final public Exception::getTraceAsString(): string
```
```
public Exception::__toString(): string
```
```
private Exception::__clone(): void
```
}
php password_verify password\_verify
================
(PHP 5 >= 5.5.0, PHP 7, PHP 8)
password\_verify — Verifies that a password matches a hash
### Description
```
password_verify(string $password, string $hash): bool
```
Verifies that the given hash matches the given password. **password\_verify()** is compatible with [crypt()](function.crypt). Therefore, password hashes created by [crypt()](function.crypt) can be used with **password\_verify()**.
Note that [password\_hash()](function.password-hash) returns the algorithm, cost and salt as part of the returned hash. Therefore, all information that's needed to verify the hash is included in it. This allows the verify function to verify the hash without needing separate storage for the salt or algorithm information.
This function is safe against timing attacks.
### Parameters
`password`
The user's password.
`hash`
A hash created by [password\_hash()](function.password-hash).
### Return Values
Returns **`true`** if the password and hash match, or **`false`** otherwise.
### Examples
**Example #1 **password\_verify()** example**
```
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
?>
```
The above example will output:
```
Password is valid!
```
### See Also
* [password\_hash()](function.password-hash) - Creates a password hash
* [» userland implementation](https://github.com/ircmaxell/password_compat)
* [sodium\_crypto\_pwhash\_str\_verify()](function.sodium-crypto-pwhash-str-verify) - Verifies that a password matches a hash
php ImagickPixel::getColorQuantum ImagickPixel::getColorQuantum
=============================
(No version information available, might only be in Git)
ImagickPixel::getColorQuantum — Description
### Description
```
public ImagickPixel::getColorQuantum(): array
```
Returns the color of the pixel in an array as Quantum values. If ImageMagick was compiled as HDRI these will be floats, otherwise they will be integers.
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
This function has no parameters.
### Return Values
Returns an array with keys `"r"`, `"g"`, `"b"`, `"a"`.
php proc_close proc\_close
===========
(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)
proc\_close — Close a process opened by [proc\_open()](function.proc-open) and return the exit code of that process
### Description
```
proc_close(resource $process): int
```
**proc\_close()** is similar to [pclose()](function.pclose) except that it only works on processes opened by [proc\_open()](function.proc-open). **proc\_close()** waits for the process to terminate, and returns its exit code. Open pipes to that process are closed when this function is called, in order to avoid a deadlock - the child process may not be able to exit while the pipes are open.
### Parameters
`process`
The [proc\_open()](function.proc-open) resource that will be closed.
### Return Values
Returns the termination status of the process that was run. In case of an error then `-1` is returned.
>
> **Note**:
>
>
> If PHP has been compiled with --enable-sigchild, the return value of this function is undefined.
>
>
php gc_enable gc\_enable
==========
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
gc\_enable — Activates the circular reference collector
### Description
```
gc_enable(): void
```
Activates the circular reference collector, setting [zend.enable\_gc](https://www.php.net/manual/en/info.configuration.php#ini.zend.enable-gc) to `1`.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
### See Also
* [Garbage Collection](https://www.php.net/manual/en/features.gc.php)
php imagecreatefromxpm imagecreatefromxpm
==================
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
imagecreatefromxpm — Create a new image from file or URL
### Description
```
imagecreatefromxpm(string $filename): GdImage|false
```
**imagecreatefromxpm()** returns an image identifier representing the image obtained from the given filename.
**Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
### Parameters
`filename`
Path to the XPM image.
### Return Values
Returns an image object on success, **`false`** on errors.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. |
### Examples
**Example #1 Creating an image instance using **imagecreatefromxpm()****
```
<?php
// Check for XPM support
if(!(imagetypes() & IMG_XPM))
{
die('Support for xpm was not found!');
}
// Create the image instance
$xpm = imagecreatefromxpm('./example.xpm');
// Do image operations here
// PHP has no support for writing xpm images
// so in this case we save the image as a
// jpeg file with 100% quality
imagejpeg($xpm, './example.jpg', 100);
imagedestroy($xpm);
?>
```
php ftp_append ftp\_append
===========
(PHP 7 >= 7.2.0, PHP 8)
ftp\_append — Append the contents of a file to another file on the FTP server
### Description
```
ftp_append(
FTP\Connection $ftp,
string $remote_filename,
string $local_filename,
int $mode = FTP_BINARY
): bool
```
**Warning**This function is currently not documented; only its argument list is available.
### Parameters
`ftp`
An [FTP\Connection](class.ftp-connection) instance.
`remote_filename`
`local_filename`
`mode`
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. |
php isset isset
=====
(PHP 4, PHP 5, PHP 7, PHP 8)
isset — Determine if a variable is declared and is different than **`null`**
### Description
```
isset(mixed $var, mixed ...$vars): bool
```
Determine if a variable is considered set, this means if a variable is declared and is different than **`null`**.
If a variable has been unset with the [unset()](function.unset) function, it is no longer considered to be set.
**isset()** will return **`false`** when checking a variable that has been assigned to **`null`**. Also note that a null character (`"\0"`) is not equivalent to the PHP **`null`** constant.
If multiple parameters are supplied then **isset()** will return **`true`** only if all of the parameters are considered set. Evaluation goes from left to right and stops as soon as an unset variable is encountered.
### Parameters
`var`
The variable to be checked.
`vars`
Further variables.
### Return Values
Returns **`true`** if `var` exists and has any value other than **`null`**. **`false`** otherwise.
### Examples
**Example #1 **isset()** Examples**
```
<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
echo "This var is set so I will print.";
}
// In the next examples we'll use var_dump to output
// the return value of isset().
$a = "test";
$b = "anothertest";
var_dump(isset($a)); // TRUE
var_dump(isset($a, $b)); // TRUE
unset ($a);
var_dump(isset($a)); // FALSE
var_dump(isset($a, $b)); // FALSE
$foo = NULL;
var_dump(isset($foo)); // FALSE
?>
```
This also work for elements in arrays:
```
<?php
$a = array ('test' => 1, 'hello' => NULL, 'pie' => array('a' => 'apple'));
var_dump(isset($a['test'])); // TRUE
var_dump(isset($a['foo'])); // FALSE
var_dump(isset($a['hello'])); // FALSE
// The key 'hello' equals NULL so is considered unset
// If you want to check for NULL key values then try:
var_dump(array_key_exists('hello', $a)); // TRUE
// Checking deeper array values
var_dump(isset($a['pie']['a'])); // TRUE
var_dump(isset($a['pie']['b'])); // FALSE
var_dump(isset($a['cake']['a']['b'])); // FALSE
?>
```
**Example #2 **isset()** on String Offsets**
```
<?php
$expected_array_got_string = 'somestring';
var_dump(isset($expected_array_got_string['some_key']));
var_dump(isset($expected_array_got_string[0]));
var_dump(isset($expected_array_got_string['0']));
var_dump(isset($expected_array_got_string[0.5]));
var_dump(isset($expected_array_got_string['0.5']));
var_dump(isset($expected_array_got_string['0 Mostel']));
?>
```
The above example will output:
```
bool(false)
bool(true)
bool(true)
bool(true)
bool(false)
bool(false)
```
### Notes
**Warning** **isset()** only works with variables as passing anything else will result in a parse error. For checking if [constants](language.constants) are set use the [defined()](function.defined) function.
> **Note**: Because this is a language construct and not a function, it cannot be called using [variable functions](functions.variable-functions), or [named arguments](functions.arguments#functions.named-arguments).
>
>
>
> **Note**:
>
>
> When using **isset()** on inaccessible object properties, the [\_\_isset()](language.oop5.overloading#object.isset) overloading method will be called, if declared.
>
>
### See Also
* [empty()](function.empty) - Determine whether a variable is empty
* [\_\_isset()](language.oop5.overloading#object.isset)
* [unset()](function.unset) - Unset a given variable
* [defined()](function.defined) - Checks whether a given named constant exists
* [the type comparison tables](https://www.php.net/manual/en/types.comparisons.php)
* [array\_key\_exists()](function.array-key-exists) - Checks if the given key or index exists in the array
* [is\_null()](function.is-null) - Finds whether a variable is null
* the error control [@](language.operators.errorcontrol) operator
php pfsockopen pfsockopen
==========
(PHP 4, PHP 5, PHP 7, PHP 8)
pfsockopen — Open persistent Internet or Unix domain socket connection
### Description
```
pfsockopen(
string $hostname,
int $port = -1,
int &$error_code = null,
string &$error_message = null,
?float $timeout = null
): resource|false
```
This function behaves exactly as [fsockopen()](function.fsockopen) with the difference that the connection is not closed after the script finishes. It is the persistent version of [fsockopen()](function.fsockopen).
### Parameters
For parameter information, see the [fsockopen()](function.fsockopen) documentation.
### Return Values
**pfsockopen()** returns a file pointer which may be used together with the other file functions (such as [fgets()](function.fgets), [fgetss()](function.fgetss), [fwrite()](function.fwrite), [fclose()](function.fclose), and [feof()](function.feof)), or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `timeout` is nullable now. |
### See Also
* [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection
php ImagickDraw::getTextUnderColor ImagickDraw::getTextUnderColor
==============================
(PECL imagick 2, PECL imagick 3)
ImagickDraw::getTextUnderColor — Returns the text under color
### Description
```
public ImagickDraw::getTextUnderColor(): ImagickPixel
```
**Warning**This function is currently not documented; only its argument list is available.
Returns the color of a background rectangle to place under text annotations.
### Return Values
Returns an [ImagickPixel](class.imagickpixel) object describing the color.
php imagesavealpha imagesavealpha
==============
(PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8)
imagesavealpha — Whether to retain full alpha channel information when saving images
### Description
```
imagesavealpha(GdImage $image, bool $enable): bool
```
**imagesavealpha()** sets the flag which determines whether to retain full alpha channel information (as opposed to single-color transparency) when saving images. This is only supported for image formats which support full alpha channel information, i.e. `PNG`, `WebP` and `AVIF`.
> **Note**: **imagesavealpha()** is only meaningful for `PNG` images, since the full alpha channel is always saved for `WebP` and `AVIF`. It is not recommended to rely on this behavior, as it may change in the future. Thus, **imagesavealpha()** should be called deliberately also for `WebP` and `AVIF` images.
>
>
Alphablending has to be disabled (`imagealphablending($im, false)`) to retain the alpha-channel in the first place.
### Parameters
`image`
A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor).
`enable`
Whether to save the alpha channel or not. Defaults to **`false`**.
### Return Values
Returns **`true`** on success or **`false`** on failure.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. |
### Examples
**Example #1 Basic **imagesavealpha()** Usage**
```
<?php
// Load a png image with alpha channel
$png = imagecreatefrompng('./alphachannel_example.png');
// Turn off alpha blending
imagealphablending($png, false);
// Do desired operations
// Set alpha flag
imagesavealpha($png, true);
// Output image to browser
header('Content-Type: image/png');
imagepng($png);
imagedestroy($png);
?>
```
### See Also
* [imagealphablending()](function.imagealphablending) - Set the blending mode for an image
| programming_docs |
php stats_cdf_gamma stats\_cdf\_gamma
=================
(PECL stats >= 1.0.0)
stats\_cdf\_gamma — Calculates any one parameter of the gamma distribution given values for the others
### Description
```
stats_cdf_gamma(
float $par1,
float $par2,
float $par3,
int $which
): float
```
Returns the cumulative distribution function, its inverse, or one of its parameters, of the gamma distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`.
The following table lists the return value and parameters by `which`. CDF, x, k, and theta denotes cumulative distribution function, the value of the random variable, and the shape and the scale parameter of the gamma distribution, respectively.
**Return value and parameters**| `which` | Return value | `par1` | `par2` | `par3` |
| --- | --- | --- | --- | --- |
| 1 | CDF | x | k | theta |
| 2 | x | CDF | k | theta |
| 3 | k | x | CDF | theta |
| 4 | theta | x | CDF | k |
### Parameters
`par1`
The first parameter
`par2`
The second parameter
`par3`
The third parameter
`which`
The flag to determine what to be calculated
### Return Values
Returns CDF, x, k, or theta, determined by `which`.
php Gmagick::read Gmagick::read
=============
(PECL gmagick >= Unknown)
Gmagick::read — Reads image from filename
### Description
```
public Gmagick::read(string $filename): Gmagick
```
Reads image from filename.
### Parameters
`filename`
The image filename.
### Return Values
The [Gmagick](class.gmagick) object.
### Errors/Exceptions
Throws an **GmagickException** on error.
php Imagick::getImageBackgroundColor Imagick::getImageBackgroundColor
================================
(PECL imagick 2, PECL imagick 3)
Imagick::getImageBackgroundColor — Returns the image background color
### Description
```
public Imagick::getImageBackgroundColor(): ImagickPixel
```
Returns the image background color.
### Parameters
This function has no parameters.
### Return Values
Returns an ImagickPixel set to the background color of the image.
### Errors/Exceptions
Throws ImagickException on error.
php enchant_dict_get_error enchant\_dict\_get\_error
=========================
(PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 )
enchant\_dict\_get\_error — Returns the last error of the current spelling-session
### Description
```
enchant_dict_get_error(EnchantDictionary $dictionary): string|false
```
Returns the last error of the current spelling-session
### Parameters
`dictionary`
An Enchant dictionary returned by [enchant\_broker\_request\_dict()](function.enchant-broker-request-dict) or [enchant\_broker\_request\_pwl\_dict()](function.enchant-broker-request-pwl-dict).
### Return Values
Returns the error message as string or **`false`** if no error occurred.
### Changelog
| Version | Description |
| --- | --- |
| 8.0.0 | `dictionary` expects an [EnchantDictionary](class.enchantdictionary) instance now; previoulsy, a [resource](language.types.resource) was expected. |
php Yaf_Request_Abstract::getParams Yaf\_Request\_Abstract::getParams
=================================
(Yaf >=1.0.0)
Yaf\_Request\_Abstract::getParams — Retrieve all calling parameters
### Description
```
public Yaf_Request_Abstract::getParams(): array
```
### Parameters
This function has no parameters.
### Return Values
### See Also
* [Yaf\_Request\_Abstract::setParam()](yaf-request-abstract.setparam) - Set a calling parameter to a request
php SolrQuery::removeFacetField SolrQuery::removeFacetField
===========================
(PECL solr >= 0.9.2)
SolrQuery::removeFacetField — Removes one of the facet.date parameters
### Description
```
public SolrQuery::removeFacetField(string $field): SolrQuery
```
Removes one of the facet.date parameters
### Parameters
`field`
The name of the field
### Return Values
Returns the current SolrQuery object, if the return value is used.
php Imagick::getImageTotalInkDensity Imagick::getImageTotalInkDensity
================================
(PECL imagick 2, PECL imagick 3)
Imagick::getImageTotalInkDensity — Gets the image total ink density
### Description
```
public Imagick::getImageTotalInkDensity(): float
```
Gets the image total ink density.
### Parameters
This function has no parameters.
### Return Values
Returns the image total ink density of the image. Throw an **ImagickException** on error.
php Parle\RLexer::build Parle\RLexer::build
===================
(PECL parle >= 0.5.1)
Parle\RLexer::build — Finalize the lexer rule set
### Description
```
public Parle\RLexer::build(): void
```
Rules, previously added with [Parle\RLexer::push()](parle-rlexer.push) are finalized. This method call has to be done after all the necessary rules was pushed. The rule set becomes read only. The lexing can begin.
### Parameters
This function has no parameters.
### Return Values
No value is returned.
php SQLite3Stmt::clear SQLite3Stmt::clear
==================
(PHP 5 >= 5.3.0, PHP 7, PHP 8)
SQLite3Stmt::clear — Clears all current bound parameters
### Description
```
public SQLite3Stmt::clear(): bool
```
Clears all current bound parameters (sets them to **`null`**).
**Caution** This method needs to be used with [SQLite3Stmt::reset()](sqlite3stmt.reset). If used alone, any call to [SQLite3Stmt::bindValue()](sqlite3stmt.bindvalue) or [SQLite3Stmt::bindParam()](sqlite3stmt.bindparam) will be of no effect and all bound parameters will have the **`null`** value.
### Parameters
This function has no parameters.
### Return Values
Returns **`true`** on successful clearing of bound parameters, **`false`** on failure.
wagtail Welcome to Wagtail’s documentation Welcome to Wagtail’s documentation
==================================
Wagtail is an open source CMS written in [Python](https://www.python.org/) and built on the [Django web framework](https://www.djangoproject.com/).
Below are some useful links to help you get started with Wagtail.
If you’d like to get a quick feel for Wagtail, try spinning up a [temporary developer environment](https://gitpod.io/#https://github.com/wagtail/wagtail-gitpod) in your browser (running on Gitpod - here’s [how it works](https://wagtail.org/blog/gitpod/)).
* **First steps**
+ [Getting started](getting_started/index)
+ [Your first Wagtail site](getting_started/tutorial)
+ [Demo site](getting_started/demo_site)
* **Using Wagtail**
+ [Page models](topics/pages)
+ [Writing templates](topics/writing_templates)
+ [How to use images in templates](topics/images)
+ [Search](topics/search/index)
+ [Third-party tutorials](advanced_topics/third_party_tutorials)
* **For editors**
+ [Editors guide (separate site)](https://guide.wagtail.org/)
Index
-----
* [Getting started](getting_started/index)
+ [Your first Wagtail site](getting_started/tutorial)
+ [Demo site](getting_started/demo_site)
+ [Integrating Wagtail into a Django project](getting_started/integrating_into_django)
+ [The Zen of Wagtail](getting_started/the_zen_of_wagtail)
* [Usage guide](topics/index)
+ [Page models](topics/pages)
+ [Writing templates](topics/writing_templates)
+ [How to use images in templates](topics/images)
+ [Search](topics/search/index)
+ [Snippets](topics/snippets)
+ [How to use StreamField for mixed content](topics/streamfield)
+ [Permissions](topics/permissions)
* [Advanced topics](advanced_topics/index)
+ [Images](advanced_topics/images/index)
+ [Documents](advanced_topics/documents/index)
+ [Embedded content](advanced_topics/embeds)
+ [How to add Wagtail into an existing Django project](advanced_topics/add_to_django_project)
+ [Deploying Wagtail](advanced_topics/deploying)
+ [Performance](advanced_topics/performance)
+ [Internationalisation](advanced_topics/i18n)
+ [Private pages](advanced_topics/privacy)
+ [Customising Wagtail](advanced_topics/customisation/index)
+ [Third-party tutorials](advanced_topics/third_party_tutorials)
+ [Testing your Wagtail site](advanced_topics/testing)
+ [Wagtail API](advanced_topics/api/index)
+ [How to build a site with AMP support](advanced_topics/amp)
+ [Accessibility considerations](advanced_topics/accessibility_considerations)
+ [About StreamField BoundBlocks and values](advanced_topics/boundblocks_and_values)
+ [Multi-site, multi-instance and multi-tenancy](advanced_topics/multi_site_multi_instance_multi_tenancy)
+ [How to use a redirect with Form builder to prevent double submission](advanced_topics/formbuilder_routablepage_redirect)
* [Extending Wagtail](extending/index)
+ [Creating admin views](extending/admin_views)
+ [Generic views](extending/generic_views)
+ [Template components](extending/template_components)
+ [Using forms in admin views](extending/forms)
+ [Adding reports](extending/adding_reports)
+ [Adding new Task types](extending/custom_tasks)
+ [Audit log](extending/audit_log)
+ [Customising the user account settings form](extending/custom_account_settings)
+ [Customising group edit/create views](extending/customising_group_views)
+ [Rich text internals](extending/rich_text_internals)
+ [Extending the Draftail Editor](extending/extending_draftail)
+ [Adding custom bulk actions](extending/custom_bulk_actions)
* [Reference](reference/index)
+ [Pages](reference/pages/index)
+ [StreamField reference](reference/streamfield/index)
+ [Contrib modules](reference/contrib/index)
+ [Management commands](reference/management_commands)
+ [Hooks](reference/hooks)
+ [Signals](reference/signals)
+ [Settings](reference/settings)
+ [The project template](reference/project_template)
+ [Jinja2 template support](reference/jinja2)
+ [Panel API](reference/panel_api)
+ [Viewsets](reference/viewsets)
* [Support](support)
* [Using Wagtail: an Editor’s guide](editor_manual/index)
* [Contributing to Wagtail](contributing/index)
+ [Issue tracking](contributing/issue_tracking)
+ [Development](contributing/developing)
+ [Committing code](contributing/committing)
+ [UI Styleguide](contributing/styleguide)
+ [General coding guidelines](contributing/general_guidelines)
+ [Python coding guidelines](contributing/python_guidelines)
+ [UI Guidelines](contributing/ui_guidelines)
+ [Documentation guidelines](contributing/documentation_guidelines)
+ [Writing documentation](contributing/documentation_modes)
+ [Reporting security issues](contributing/security)
+ [Wagtail’s release process](contributing/release_process)
wagtail Support Support
=======
If you have any problems or questions about working with Wagtail, you are invited to visit any of the following support channels, where volunteer members of the Wagtail community will be happy to assist.
**Please respect the time and effort of volunteers, by not asking the same question in multiple places.** At best, you’ll be spamming the same set of people each time; at worst, you’ll waste the effort of volunteers who spend time answering a question unaware that it has already been answered elsewhere. If you absolutely must ask a question on multiple forums, post it on Stack Overflow first and include the Stack Overflow link in your subsequent posts.
Stack Overflow
--------------
[Stack Overflow](https://stackoverflow.com/questions/tagged/wagtail) is the best place to find answers to your questions about working with Wagtail - there is an active community of Wagtail users and developers responding to questions there. When posting questions, please read Stack Overflow’s advice on [how to ask questions](https://stackoverflow.com/help/how-to-ask) and remember to tag your question with “wagtail”.
Mailing list
------------
For topics and discussions that do not fit Stack Overflow’s question-and-answer format, there is a Wagtail Support mailing list at [groups.google.com/d/forum/wagtail](https://groups.google.com/g/wagtail).
Slack
-----
The Wagtail Slack workspace is open to all users and developers of Wagtail. To join, head to: <https://wagtail.org/slack/>
Please use the **#support** channel for support questions. Support is provided by members of the Wagtail community on a voluntary basis, and we cannot guarantee that questions will be answered quickly (or at all). If you want to see this resource succeed, please consider sticking around to help out! Also, please keep in mind that many of Wagtail’s core and expert developers prefer to handle support queries on a non-realtime basis through Stack Overflow, and questions asked there may well get a better response.
GitHub discussions
------------------
Our [Github discussion boards](https://github.com/wagtail/wagtail/discussions) are open for sharing ideas and plans for the Wagtail project.
Issues
------
If you think you’ve found a bug in Wagtail, or you’d like to suggest a new feature, please check the current list at [github.com/wagtail/wagtail/issues](https://github.com/wagtail/wagtail/issues). If your bug or suggestion isn’t there, raise a new issue, providing as much relevant context as possible.
If your bug report is a security issue, **do not** report it with an issue. Please read our guide to [reporting security issues](contributing/security).
Torchbox
--------
Finally, if you have a query which isn’t relevant for any of the above forums, feel free to contact the Wagtail team at Torchbox directly, on [[email protected]](mailto:hello%40wagtail.org) or [@wagtailcms](https://twitter.com/wagtailcms).
wagtail Using Wagtail: an Editor’s guide Using Wagtail: an Editor’s guide
================================
Wagtail’s Editor Guide now has its own website: [guide.wagtail.org](https://guide.wagtail.org/). This guide is written for the users of a Wagtail-powered site. That is, the content editors, moderators and administrators who will be running things on a day-to-day basis.
wagtail Committing code Committing code
===============
**This section is for the core team of Wagtail, or for anyone interested in the process of getting code committed to Wagtail.**
Code should only be committed after it has been reviewed by at least one other reviewer or committer, unless the change is a small documentation change or fixing a typo. If additional code changes are made after the review, it is OK to commit them without further review if they are uncontroversial and small enough that there is minimal chance of introducing new bugs.
Most code contributions will be in the form of pull requests from Github. Pull requests should not be merged from Github, apart from small documentation fixes, which can be merged with the ‘Squash and merge’ option. Instead, the code should be checked out by a committer locally, the changes examined and rebased, the `CHANGELOG.txt` and release notes updated, and finally the code should be pushed to the `main` branch. This process is covered in more detail below.
Check out the code locally
--------------------------
If the code has been submitted as a pull request, you should fetch the changes and check them out in your Wagtail repository. A simple way to do this is by adding the following `git` alias to your `~/.gitconfig` (assuming `upstream` is `wagtail/wagtail`):
```
[alias]
pr = !sh -c \"git fetch upstream pull/${1}/head:pr/${1} && git checkout pr/${1}\"
```
Now you can check out pull request number `xxxx` by running `git pr xxxx`.
Rebase on to `main`
-------------------
Now that you have the code, you should rebase the commits on to the `main` branch. Rebasing is preferred over merging, as merge commits make the commit history harder to read for small changes.
You can fix up any small mistakes in the commits, such as typos and formatting, as part of the rebase. `git rebase --interactive` is an excellent tool for this job.
Ideally, use this as an opportunity to squash the changes to a few commits, so each commit is making a single meaningful change (and not breaking anything). If this is not possible because of the nature of the changes, it’s acceptable to either squash into a commit or leave all commits unsquashed, depending on which will be more readable in the commit history.
```
# Get the latest commits from Wagtail
git fetch upstream
git checkout main
git merge --ff-only upstream/main
# Rebase this pull request on to main
git checkout pr/xxxx
git rebase main
# Update main to this commit
git checkout main
git merge --ff-only pr/xxxx
```
Update `CHANGELOG.txt` and release notes
----------------------------------------
Note
This should only be done by core committers, once the changes have been reviewed and accepted.
Every significant change to Wagtail should get an entry in the `CHANGELOG.txt`, and the release notes for the current version.
The `CHANGELOG.txt` contains a short summary of each new feature, refactoring, or bug fix in each release. Each summary should be a single line. Bug fixes should be grouped together at the end of the list for each release, and be prefixed with “Fix:”. The name of the contributor should be added at the end of the summary, in brackets. For example:
```
* Fix: Tags added on the multiple image uploader are now saved correctly (Alex Smith)
```
The release notes for each version contain a more detailed description of each change. Backwards compatibility notes should also be included. Large new features or changes should get their own section, while smaller changes and bug fixes should be grouped together in their own section. See previous release notes for examples. The release notes for each version are found in `docs/releases/x.x.x.md`.
If the contributor is a new person, and this is their first contribution to Wagtail, they should be added to the `CONTRIBUTORS.rst` list. Contributors are added in chronological order, with new contributors added to the bottom of the list. Use their preferred name. You can usually find the name of a contributor on their Github profile. If in doubt, or if their name is not on their profile, ask them how they want to be named.
If the changes to be merged are small enough to be a single commit, amend this single commit with the additions to the `CHANGELOG.txt`, release notes, and contributors:
```
git add CHANGELOG.txt docs/releases/x.x.x.md CONTRIBUTORS.md
git commit --amend --no-edit
```
If the changes do not fit in a single commit, make a new commit with the updates to the `CHANGELOG.txt`, release notes, and contributors. The commit message should say `Release notes for #xxxx`:
```
git add CHANGELOG.txt docs/releases/x.x.x.md CONTRIBUTORS.md
git commit -m 'Release notes for #xxxx'
```
Push to `main`
--------------
The changes are ready to be pushed to `main` now.
```
# Check that everything looks OK
git log upstream/main..main --oneline
git push --dry-run upstream main
# Push the commits!
git push upstream main
git branch -d pr/xxxx
```
When you have made a mistake
----------------------------
It’s ok! Everyone makes mistakes. If you realise that recent merged changes have a negative impact, create a new pull request with a revert of the changes and merge it without waiting for a review. The PR will serve as additional documentation for the changes, and will run through the CI tests.
Add commits to someone else’s pull request
------------------------------------------
Github users with write access to wagtail/wagtail (core members) can add commits to the pull request branch of the contributor.
Given that the contributor username is johndoe and his pull request branch is called foo:
```
git clone [email protected]:wagtail/wagtail.git
cd wagtail
git remote add johndoe [email protected]:johndoe/wagtail.git
git fetch johndoe foo
git checkout johndoe/foo
# Make changes
# Commit changes
git push johndoe HEAD:foo
```
| programming_docs |
wagtail Contributing to Wagtail Contributing to Wagtail
=======================
Issues
------
The easiest way to contribute to Wagtail is to tell us how to improve it! First, check to see if your bug or feature request has already been submitted at [github.com/wagtail/wagtail/issues](https://github.com/wagtail/wagtail/issues). If it has, and you have some supporting information which may help us deal with it, comment on the existing issue. If not, please [create a new one](https://github.com/wagtail/wagtail/issues/new), providing as much relevant context as possible. For example, if you’re experiencing problems with installation, detail your environment and the steps you’ve already taken. If something isn’t displaying correctly, tell us what browser you’re using, and include a screenshot if possible.
If your bug report is a security issue, **do not** report it with an issue. Please read our guide to [reporting security issues](security).
* [Issue tracking](issue_tracking)
+ [Issues](issue_tracking#issues)
+ [Pull requests](issue_tracking#pull-requests)
+ [Release schedule](issue_tracking#release-schedule)
Pull requests
-------------
If you’re a Python or Django developer, [fork it](https://github.com/wagtail/wagtail/) and read the [developing docs](developing#developing-for-wagtail) to get stuck in! We welcome all contributions, whether they solve problems which are specific to you or they address existing issues. If you’re stuck for ideas, pick something from the [issue list](https://github.com/wagtail/wagtail/issues?q=is%3Aopen), or email us directly on [[email protected]](mailto:hello%40wagtail.org) if you’d like us to suggest something!
For large-scale changes, we’d generally recommend breaking them down into smaller pull requests that achieve a single well-defined task and can be reviewed individually. If this isn’t possible, we recommend opening a pull request on the [Wagtail RFCs](https://github.com/wagtail/rfcs/) repository, so that there’s a chance for the community to discuss the change before it gets implemented.
* [Development](developing)
+ [Setting up the Wagtail codebase](developing#setting-up-the-wagtail-codebase)
+ [Testing](developing#testing)
+ [Compiling static assets](developing#compiling-static-assets)
+ [Using the pattern library](developing#using-the-pattern-library)
+ [Compiling the documentation](developing#compiling-the-documentation)
+ [Automatically lint and code format on commits](developing#automatically-lint-and-code-format-on-commits)
* [Committing code](committing)
+ [Check out the code locally](committing#check-out-the-code-locally)
+ [Rebase on to `main`](committing#rebase-on-to-main)
+ [Update `CHANGELOG.txt` and release notes](committing#update-changelog-txt-and-release-notes)
+ [Push to `main`](committing#push-to-main)
+ [When you have made a mistake](committing#when-you-have-made-a-mistake)
+ [Add commits to someone else’s pull request](committing#add-commits-to-someone-else-s-pull-request)
Translations
------------
Wagtail has internationalisation support so if you are fluent in a non-English language you can contribute by localising the interface.
Translation work should be submitted through [Transifex](https://explore.transifex.com/torchbox/wagtail/).
Other contributions
-------------------
We welcome contributions to all aspects of Wagtail. If you would like to improve the design of the user interface, or extend the documentation, please submit a pull request as above. If you’re not familiar with Github or pull requests, [contact us directly](mailto:hello%40wagtail.org) and we’ll work something out.
Developing packages for Wagtail
-------------------------------
If you are developing packages for Wagtail, you can add the following [PyPI](https://pypi.org/) classifiers:
* [`Framework :: Wagtail`](https://pypi.org/search/?c=Framework+%3A%3A+Wagtail)
* [`Framework :: Wagtail :: 1`](https://pypi.org/search/?c=Framework+%3A%3A+Wagtail+%3A%3A+1)
* [`Framework :: Wagtail :: 2`](https://pypi.org/search/?c=Framework+%3A%3A+Wagtail+%3A%3A+2)
* [`Framework :: Wagtail :: 3`](https://pypi.org/search/?c=Framework+%3A%3A+Wagtail+%3A%3A+3)
* [`Framework :: Wagtail :: 4`](https://pypi.org/search/?c=Framework+%3A%3A+Wagtail+%3A%3A+4)
You can also find a curated list of awesome packages, articles, and other cool resources from the Wagtail community at [Awesome Wagtail](https://github.com/springload/awesome-wagtail).
More information
----------------
* [UI Styleguide](styleguide)
* [General coding guidelines](general_guidelines)
+ [Language](general_guidelines#language)
+ [File names](general_guidelines#file-names)
* [Python coding guidelines](python_guidelines)
+ [PEP8](python_guidelines#pep8)
+ [Django compatibility](python_guidelines#django-compatibility)
+ [Tests](python_guidelines#tests)
* [UI Guidelines](ui_guidelines)
+ [Linting and formatting](ui_guidelines#linting-and-formatting)
+ [HTML guidelines](ui_guidelines#html-guidelines)
+ [CSS guidelines](ui_guidelines#css-guidelines)
+ [JavaScript guidelines](ui_guidelines#javascript-guidelines)
+ [Multilingual support](ui_guidelines#multilingual-support)
* [Documentation guidelines](documentation_guidelines)
+ [Formatting recommendations](documentation_guidelines#formatting-recommendations)
+ [Formatting to avoid](documentation_guidelines#formatting-to-avoid)
* [Writing documentation](documentation_modes)
+ [Choose a writing mode](documentation_modes#choose-a-writing-mode)
+ [Tutorial](documentation_modes#tutorial)
+ [How-to guide](documentation_modes#how-to-guide)
+ [Reference](documentation_modes#reference)
+ [Explanation](documentation_modes#explanation)
* [Reporting security issues](security)
+ [Supported versions](security#supported-versions)
+ [How Wagtail discloses security issues](security#how-wagtail-discloses-security-issues)
+ [CSV export security considerations](security#csv-export-security-considerations)
* [Wagtail’s release process](release_process)
+ [Official releases](release_process#official-releases)
+ [Release cadence](release_process#release-cadence)
+ [Deprecation policy](release_process#deprecation-policy)
+ [Supported versions](release_process#supported-versions)
+ [Supported versions of Django](release_process#supported-versions-of-django)
+ [Release schedule](release_process#release-schedule)
wagtail Development Development
===========
Setting up a local copy of [the Wagtail git repository](https://github.com/wagtail/wagtail) is slightly more involved than running a release package of Wagtail, as it requires [Node.js](https://nodejs.org/) and npm for building JavaScript and CSS assets. (This is not required when running a release version, as the compiled assets are included in the release package.)
If you’re happy to develop on a local virtual machine, the [docker-wagtail-develop](https://github.com/wagtail/docker-wagtail-develop) and [vagrant-wagtail-develop](https://github.com/wagtail/vagrant-wagtail-develop) setup scripts are the fastest way to get up and running. They will provide you with a running instance of the [Wagtail Bakery demo site](https://github.com/wagtail/bakerydemo/), with the Wagtail and bakerydemo codebases available as shared folders for editing on your host machine.
You can also set up a cloud development environment that you can work with in a browser-based IDE using the [gitpod-wagtail-develop](https://github.com/wagtail/gitpod-wagtail-develop) project.
(Build scripts for other platforms would be very much welcomed - if you create one, please let us know via the [Slack workspace](https://github.com/wagtail/wagtail/wiki/Slack)!)
If you’d prefer to set up all the components manually, read on. These instructions assume that you’re familiar with using pip and [virtual environments](https://docs.python.org/3/tutorial/venv.html) to manage Python packages.
Setting up the Wagtail codebase
-------------------------------
The preferred way to install the correct version of Node is to use [Node Version Manager (nvm)](https://github.com/nvm-sh/nvm) or [Fast Node Manager (fnm)](https://github.com/Schniz/fnm), which will always align the version with the supplied `.nvmrc` file in the root of the project. To ensure you are running the correct version of Node, run `nvm install` or `fnm install` from the project root. Alternatively, you can install [Node.js](https://nodejs.org/) directly, ensure you install the version as declared in the project’s root `.nvmrc` file.
You will also need to install the **libjpeg** and **zlib** libraries, if you haven’t done so already - see Pillow’s [platform-specific installation instructions](https://pillow.readthedocs.io/en/stable/installation.html#external-libraries).
Clone a copy of [the Wagtail codebase](https://github.com/wagtail/wagtail):
```
git clone https://github.com/wagtail/wagtail.git
cd wagtail
```
**With your preferred virtualenv activated,** install the Wagtail package in development mode with the included testing and documentation dependencies:
```
pip install -e '.[testing,docs]' -U
```
Install the tool chain for building static assets:
```
npm ci
```
Compile the assets:
```
npm run build
```
Any Wagtail sites you start up in this virtualenv will now run against this development instance of Wagtail. We recommend using the [Wagtail Bakery demo site](https://github.com/wagtail/bakerydemo/) as a basis for developing Wagtail. Keep in mind that the setup steps for a Wagtail site may include installing a release version of Wagtail, which will override the development version you’ve just set up. In this case, you should install the site before running the `pip install -e` step, or re-run that step after the site is installed.
Testing
-------
From the root of the Wagtail codebase, run the following command to run all the Python tests:
```
python runtests.py
```
### Running only some of the tests
At the time of writing, Wagtail has well over 2500 tests, which takes a while to run. You can run tests for only one part of Wagtail by passing in the path as an argument to `runtests.py` or `tox`:
```
# Running in the current environment
python runtests.py wagtail
# Running in a specified Tox environment
tox -e py39-dj32-sqlite-noelasticsearch wagtail
# See a list of available Tox environments
tox -l
```
You can also run tests for individual TestCases by passing in the path as an argument to `runtests.py`
```
# Running in the current environment
python runtests.py wagtail.tests.test_blocks.TestIntegerBlock
# Running in a specified Tox environment
tox -e py39-dj32-sqlite-noelasticsearch wagtail.tests.test_blocks.TestIntegerBlock
```
### Running migrations for the test app models
You can create migrations for the test app by running the following from the Wagtail root.
```
django-admin makemigrations --settings=wagtail.test.settings
```
### Testing against PostgreSQL
Note
In order to run these tests, you must install the required modules for PostgreSQL as described in Django’s [Databases documentation](https://docs.djangoproject.com/en/stable/ref/databases/).
By default, Wagtail tests against SQLite. You can switch to using PostgreSQL by using the `--postgres` argument:
```
python runtests.py --postgres
```
If you need to use a different user, password, host or port, use the `PGUSER`, `PGPASSWORD`, `PGHOST` and `PGPORT` environment variables respectively.
### Testing against a different database
Note
In order to run these tests, you must install the required client libraries and modules for the given database as described in Django’s [Databases documentation](https://docs.djangoproject.com/en/stable/ref/databases/) or 3rd-party database backend’s documentation.
If you need to test against a different database, set the `DATABASE_ENGINE` environment variable to the name of the Django database backend to test against:
```
DATABASE_ENGINE=django.db.backends.mysql python runtests.py
```
This will create a new database called `test_wagtail` in MySQL and run the tests against it.
If you need to use different connection settings, use the following environment variables which correspond to the respective keys within Django’s [DATABASES](https://docs.djangoproject.com/en/stable/ref/settings/#databases) settings dictionary:
* `DATABASE_ENGINE`
* `DATABASE_NAME`
* `DATABASE_PASSWORD`
* `DATABASE_HOST`
+ Note that for MySQL, this must be `127.0.0.1` rather than `localhost` if you need to connect using a TCP socket
* `DATABASE_PORT`
It is also possible to set `DATABASE_DRIVER`, which corresponds to the `driver` value within `OPTIONS` if an SQL Server engine is used.
### Testing Elasticsearch
You can test Wagtail against Elasticsearch by passing the `--elasticsearch` argument to `runtests.py`:
```
python runtests.py --elasticsearch
```
Wagtail will attempt to connect to a local instance of Elasticsearch (`http://localhost:9200`) and use the index `test_wagtail`.
If your Elasticsearch instance is located somewhere else, you can set the `ELASTICSEARCH_URL` environment variable to point to its location:
```
ELASTICSEARCH_URL=http://my-elasticsearch-instance:9200 python runtests.py --elasticsearch
```
### Unit tests for JavaScript
We use [Jest](https://jestjs.io/) for unit tests of client-side business logic or UI components. From the root of the Wagtail codebase, run the following command to run all the front-end unit tests:
```
npm run test:unit
```
### Integration tests
Our end-to-end browser testing suite also uses [Jest](https://jestjs.io/), combined with [Puppeteer](https://pptr.dev/). We set this up to be installed separately so as not to increase the installation size of the existing Node tooling. To run the tests, you will need to install the dependencies and, in a separate terminal, run the test suite’s Django development server:
```
export DJANGO_SETTINGS_MODULE=wagtail.test.settings_ui
# Assumes the current environment contains a valid installation of Wagtail for local development.
./wagtail/test/manage.py migrate
./wagtail/test/manage.py createcachetable
[email protected] DJANGO_SUPERUSER_USERNAME=admin DJANGO_SUPERUSER_PASSWORD=changeme ./wagtail/test/manage.py createsuperuser --noinput
./wagtail/test/manage.py runserver 0:8000
# In a separate terminal:
npm --prefix client/tests/integration install
npm run test:integration
```
Integration tests target `http://localhost:8000` by default. Use the `TEST_ORIGIN` environment variable to use a different port, or test a remote Wagtail instance: `TEST_ORIGIN=http://localhost:9000 npm run test:integration`.
### Browser and device support
Wagtail is meant to be used on a wide variety of devices and browsers. Supported browser / device versions include:
| Browser | Device/OS | Version(s) |
| --- | --- | --- |
| Mobile Safari | iOS Phone | Last 2 |
| Mobile Safari | iOS Tablet | Last 2 |
| Chrome | Android | Last 2 |
| Chrome | Desktop | Last 2 |
| MS Edge | Windows | Last 2 |
| Firefox | Desktop | Latest |
| Firefox ESR | Desktop | Latest |
| Safari | macOS | Last 3 |
We aim for Wagtail to work in those environments, there are known support gaps for Safari 13 introduced in Wagtail 4.0 to provide better support for RTL languages. Our development standards ensure that the site is usable on other browsers **and will work on future browsers**.
IE 11 support has been officially dropped in 2.15 as it is gradually falling out of use. Features already known not to work include:
* Rich text copy-paste in the rich text editor.
* Sticky toolbar in the rich text editor.
* Focus outline styles in the main menu & explorer menu.
* Keyboard access to the actions in page listing tables.
**Unsupported browsers / devices include:**
| Browser | Device/OS | Version(s) |
| --- | --- | --- |
| Stock browser | Android | All |
| IE | Desktop | All |
| Safari | Windows | All |
### Accessibility targets
We want to make Wagtail accessible for users of a wide variety of assistive technologies. The specific standard we aim for is [WCAG2.1](https://www.w3.org/TR/WCAG21/), AA level. Here are specific assistive technologies we aim to test for, and ultimately support:
* [NVDA](https://www.nvaccess.org/download/) on Windows with Firefox ESR
* [VoiceOver](https://support.apple.com/en-gb/guide/voiceover-guide/welcome/web) on macOS with Safari
* [Windows Magnifier](https://support.microsoft.com/en-gb/help/11542/windows-use-magnifier) and macOS Zoom
* Windows Speech Recognition and macOS Dictation
* Mobile [VoiceOver](https://support.apple.com/en-gb/guide/voiceover-guide/welcome/web) on iOS, or [TalkBack](https://support.google.com/accessibility/android/answer/6283677?hl=en-GB) on Android
* Windows [High-contrast mode](https://support.microsoft.com/en-us/windows/use-high-contrast-mode-in-windows-10-fedc744c-90ac-69df-aed5-c8a90125e696)
We aim for Wagtail to work in those environments. Our development standards ensure that the site is usable with other assistive technologies. In practice, testing with assistive technology can be a daunting task that requires specialised training – here are tools we rely on to help identify accessibility issues, to use during development and code reviews:
* [react-axe](https://github.com/dequelabs/react-axe) integrated directly in our build tools, to identify actionable issues. Logs its results in the browser console.
* [@wordpress/jest-puppeteer-axe](https://github.com/WordPress/gutenberg/tree/trunk/packages/jest-puppeteer-axe) running Axe checks as part of integration tests.
* [Axe](https://chrome.google.com/webstore/detail/axe/lhdoppojpmngadmnindnejefpokejbdd) Chrome extension for more comprehensive automated tests of a given page.
* [Accessibility Insights for Web](https://accessibilityinsights.io/docs/en/web/overview) Chrome extension for semi-automated tests, and manual audits.
### Known accessibility issues
Wagtail’s administration interface isn’t fully accessible at the moment. We actively work on fixing issues both as part of ongoing maintenance and bigger overhauls. To learn about known issues, check out:
* The [WCAG2.1 AA for CMS admin](https://github.com/wagtail/wagtail/projects/5) issues backlog.
* Our [2021 accessibility audit](https://docs.google.com/spreadsheets/d/1l7tnpEyJiC5BWE_JX0XCkknyrjxYA5T2aee5JgPnmi4/edit).
The audit also states which parts of Wagtail have and haven’t been tested, how issues affect WCAG 2.1 compliance, and the likely impact on users.
Compiling static assets
-----------------------
All static assets such as JavaScript, CSS, images, and fonts for the Wagtail admin are compiled from their respective sources by Webpack. The compiled assets are not committed to the repository, and are compiled before packaging each new release. Compiled assets should not be submitted as part of a pull request.
To compile the assets, run:
```
npm run build
```
This must be done after every change to the source files. To watch the source files for changes and then automatically recompile the assets, run:
```
npm start
```
Using the pattern library
-------------------------
Wagtail’s UI component library is built with [Storybook](https://storybook.js.org/) and [django-pattern-library](https://github.com/torchbox/django-pattern-library). To run it locally,
```
export DJANGO_SETTINGS_MODULE=wagtail.test.settings_ui
# Assumes the current environment contains a valid installation of Wagtail for local development.
./wagtail/test/manage.py migrate
./wagtail/test/manage.py createcachetable
./wagtail/test/manage.py runserver 0:8000
# In a separate terminal:
npm run storybook
```
The last command will start Storybook at `http://localhost:6006/`. It will proxy specific requests to Django at `http://localhost:8000` by default. Use the `TEST_ORIGIN` environment variable to use a different port for Django: `TEST_ORIGIN=http://localhost:9000 npm run storybook`.
Compiling the documentation
---------------------------
The Wagtail documentation is built by Sphinx. To install Sphinx and compile the documentation, run:
```
cd /path/to/wagtail
# Install the documentation dependencies
pip install -e .[docs]
# or if using zsh as your shell:
# pip install -e '.[docs]' -U
# Compile the docs
cd docs/
make html
```
The compiled documentation will now be in `docs/_build/html`. Open this directory in a web browser to see it. Python comes with a module that makes it very easy to preview static files in a web browser. To start this simple server, run the following commands:
```
cd docs/_build/html/
python -m http.server 8080
```
Now you can open <http://localhost:8080/> in your web browser to see the compiled documentation.
Sphinx caches the built documentation to speed up subsequent compilations. Unfortunately, this cache also hides any warnings thrown by unmodified documentation source files. To clear the built HTML and start fresh, so you can see all warnings thrown when building the documentation, run:
```
cd docs/
make clean
make html
```
Wagtail also provides a way for documentation to be compiled automatically on each change. To do this, you can run the following command to see the changes automatically at `localhost:4000`:
```
cd docs/
make livehtml
```
Automatically lint and code format on commits
---------------------------------------------
[pre-commit](https://pre-commit.com/) is configured to automatically run code linting and formatting checks with every commit. To install pre-commit into your git hooks run:
```
pre-commit install
```
pre-commit should now run on every commit you make.
| programming_docs |
wagtail Documentation guidelines Documentation guidelines
========================
* [Formatting recommendations](#formatting-recommendations)
* [Formatting to avoid](#formatting-to-avoid)
Formatting recommendations
--------------------------
Wagtail’s documentation uses a mixture of [Markdown](https://myst-parser.readthedocs.io/en/stable/syntax/syntax.html) and [reStructuredText](https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html). We encourage writing documentation in Markdown first, and only reaching for more advanced reStructuredText formatting if there is a compelling reason.
Here are formats we encourage using when writing documentation for Wagtail.
### Paragraphs
It all starts here. Keep your sentences short, varied in length.
Separate text with an empty line to create a new paragraph.
### Heading levels
Use heading levels to create sections, and allow users to link straight to a specific section. Start documents with an `# h1`, and proceed with `## h2` and further sub-sections without skipping levels.
```
# Heading level 1
## Heading level 2
### Heading level 3
```
### Lists
Use bullets for unordered lists, numbers when ordered. Prefer dashes `-` for bullets. Nest by indenting with 4 spaces.
```
- Bullet 1
- Bullet 2
- Nested bullet 2
- Bullet 3
1. Numbered list 1
2. Numbered list 2
3. Numbered list 3
```
Rendered output * Bullet 1
* Bullet 2
+ Nested bullet 2
* Bullet 3
1. Numbered list 1
2. Numbered list 2
3. Numbered list 3
### Inline styles
Use **bold** and *italic* sparingly, inline `code` when relevant.
```
Use **bold** and _italic_ sparingly, inline `code` when relevant.
```
### Code blocks
Make sure to include the correct language code for syntax highlighting, and to format your code according to our coding guidelines. Frequently used: `python`, `css`, `html`, `html+django`, `javascript`, `sh`.
```
```python
INSTALLED_APPS = [
...
"wagtail",
...
]
```
```
Rendered output
```
INSTALLED_APPS = [
...
"wagtail",
...
]
```
#### When using console (terminal) code blocks
Note
`$` or `>` prompts are not needed, this makes it harder to copy and paste the lines and can be difficult to consistently add in every single code snippet.
Use `sh` as it has better support for comment and code syntax highlighting in MyST’s parser, plus is more compatible with GitHub and VSCode.
```
```sh
# some comment
some command
```
```
Rendered output
```
# some comment
some command
```
Use `doscon` (DOS Console) only if explicitly calling out Windows commands alongside their bash equivalent.
```
```doscon
# some comment
some command
```
```
Rendered output
```
# some comment
some command
```
### Links
Links are fundamental in documentation. Use internal links to tie your content to other docs, and external links as needed. Pick relevant text for links, so readers know where they will land.
Don’t rely on [`links over code`](https://www.example.com/), as they are impossible to spot.
```
An [external link](https://wwww.example.com).
An [internal link to another document](/reference/contrib/legacy_richtext).
An auto generated link label to a page [](/getting_started/tutorial).
A [link to a reference](register_reports_menu_item).
```
Rendered output An [external link](https://wwww.example.com). An [internal link to another document](../reference/contrib/legacy_richtext). An auto generated link label to a page [Your first Wagtail site](../getting_started/tutorial). A [link to a reference](../reference/hooks#register-reports-menu-item).
#### Reference links
Reference links (links to a target within a page) rely on the page having a reference created. Each reference must have a unique name and should use the `lower_snake_case` format. A reference can be added as follows:
```
(my_awesome_section)=
##### Some awesome section title
...
```
The reference can be linked to, with an optional label, using the Markdown link syntax as follows:
```
- Auto generated label (preferred) [](my_awesome_section)
- [label for section](my_awesome_section)
```
Rendered output ##### Some awesome section title
…
* Auto generated label (preferred) [Some awesome section title](#my-awesome-section)
* [label for section](#my-awesome-section)
You can read more about other methods of linking to, and creating references in the MyST parser docs section on [Targets and cross-referencing](https://myst-parser.readthedocs.io/en/stable/syntax/syntax.html#targets-and-cross-referencing).
### Note and warning call-outs
Use notes and warnings sparingly, as they rely on reStructuredText syntax which is more complicated for future editors.
```
```{note}
Notes can provide complementary information.
```
```{warning}
Warnings can be scary.
```
```
Rendered output Note
Notes can provide complementary information.
Warning
Warnings can be scary.
These call-outs do not support titles, so be careful not to include them, titles will just be moved to the body of the call-out.
```
```{note} Title's here will not work correctly
Notes can provide complementary information.
```
```
### Images
Images are hard to keep up-to-date as documentation evolves, but can be worthwhile nonetheless. Here are guidelines when adding images:
* All images should have meaningful [alt text](https://axesslab.com/alt-texts/) unless they are decorative.
* Images are served as-is – pick the correct format, and losslessly compress all images.
* Use absolute paths for image files so they are more portable.
```

```
Rendered output ### Autodoc
With its [autodoc](https://www.sphinx-doc.org/en/master/usage/extensions/autodoc.html) feature, Sphinx supports writing documentation in Python docstrings for subsequent integration in the project’s documentation pages. This is a very powerful feature which we highly recommend using to document Wagtail’s APIs.
```
```{eval-rst}
.. module:: wagtail.coreutils
.. autofunction:: cautious_slugify
```
```
Rendered output ### Tables
Only use tables when needed, using the [GitHub Flavored Markdown table syntax](https://github.github.com/gfm/#tables-extension-).
```
| Browser | Device/OS |
| ------------- | --------- |
| Stock browser | Android |
| IE | Desktop |
| Safari | Windows |
```
Rendered output
| Browser | Device/OS |
| --- | --- |
| Stock browser | Android |
| IE | Desktop |
| Safari | Windows |
### Tables of contents
`toctree` and `contents` can be used as reStructuredText directives.
```
```{toctree}
---
maxdepth: 2
titlesonly:
---
getting_started/index
topics/index
```
```{contents}
---
local:
depth: 1
---
```
```
### Version added, changed, deprecations
Sphinx offers release-metadata directives to generate this information consistently. Use as appropriate.
```
```{versionadded} 2.15
```
```{versionchanged} 2.15
```
```
Rendered output New in version 2.15.
Changed in version 2.15.
### Progressive disclosure
We can add supplementary information in documentation with the HTML `<details>` element. This relies on HTML syntax, which can be hard to author consistently, so keep this type of formatting to a minimum.
```
<details>
<summary>Supplementary information</summary>
This will be visible when expanding the content.
</details>
```
Example:
Supplementary information This will be visible when expanding the content.
wagtail UI Styleguide UI Styleguide
=============
Developers working on the Wagtail UI or creating new UI components may wish to test their work against our Styleguide, which is provided as the contrib module “wagtailstyleguide”.
To install the styleguide module on your site, add it to the list of `INSTALLED_APPS` in your settings:
```
INSTALLED_APPS = (
# ...
'wagtail.contrib.styleguide',
# ...
)
```
This will add a ‘Styleguide’ item to the Settings menu in the admin.
At present the styleguide is static: new UI components must be added to it manually, and there are no hooks into it for other modules to use. We hope to support hooks in the future.
The styleguide doesn’t currently provide examples of all the core interface components; notably the Page, Document, Image and Snippet chooser interfaces are not currently represented.
wagtail UI Guidelines UI Guidelines
=============
Wagtail’s user interface is built with:
* **HTML** using [Django templates](https://docs.djangoproject.com/en/stable/ref/templates/language/)
* **CSS** using [Sass](https://sass-lang.com/) and [Tailwind](https://tailwindcss.com/)
* **JavaScript** with [TypeScript](https://www.typescriptlang.org/)
* **SVG** for our icons, minified with [SVGO](https://jakearchibald.github.io/svgomg/)
Linting and formatting
----------------------
Here are the available commands:
* `make lint` will run all linting, `make lint-server` lints templates, `make lint-client` lints JS/CSS.
* `make format` will run all formatting and fixing of linting issues. There is also `make format-server` and `make format-client`.
Have a look at our `Makefile` tasks and `package.json` scripts if you prefer more granular options.
HTML guidelines
---------------
We use [djhtml](https://github.com/rtts/djhtml) for formatting and [Curlylint](https://www.curlylint.org/) for linting.
* Write [valid](https://validator.w3.org/nu/), [semantic](https://html5doctor.com/element-index/) HTML.
* Follow [ARIA authoring practices](https://w3c.github.io/aria-practices/), in particular [No ARIA is better than Bad ARIA](https://w3c.github.io/aria-practices/#no_aria_better_bad_aria).
* Use classes for styling, `data-` attributes for JavaScript behaviour, IDs for semantics only.
* For comments, use [Django template syntax](https://docs.djangoproject.com/en/stable/ref/templates/language/#comments) instead of HTML.
CSS guidelines
--------------
We use [Prettier](https://prettier.io/) for formatting and [Stylelint](https://stylelint.io/) for linting.
* We follow [BEM](https://getbem.com/) and [ITCSS](https://www.xfive.co/blog/itcss-scalable-maintainable-css-architecture/), with a large amount of utilities created with [Tailwind](https://tailwindcss.com/).
* Familiarise yourself with our [stylelint-config-wagtail](https://github.com/wagtail/stylelint-config-wagtail) configuration, which details our preferred code style.
* Use `rems` for `font-size`, because they offer absolute control over text. Additionally, unit-less `line-height` is preferred because it does not inherit a percentage value of its parent element, but instead is based on a multiplier of the `font-size`.
* Always use variables for design tokens such as colours or font sizes, rather than hard-coding specific values.
* We use the `w-` prefix for all styles intended to be reusable by Wagtail site implementers.
JavaScript guidelines
---------------------
We use [Prettier](https://prettier.io/) for formatting and [ESLint](https://eslint.org/) for linting.
* We follow a somewhat relaxed version of the [Airbnb styleguide](https://github.com/airbnb/javascript).
* Familiarise yourself with our [eslint-config-wagtail](https://github.com/wagtail/eslint-config-wagtail) configuration, which details our preferred code style.
Multilingual support
--------------------
This is an area of active improvement for Wagtail, with [ongoing discussions](https://github.com/wagtail/wagtail/discussions/8017).
* Always use the `trimmed` attribute on `blocktrans` tags to prevent unnecessary whitespace from being added to the translation strings.
wagtail Reporting security issues Reporting security issues
=========================
Note
Please report security issues **only** to [[email protected]](mailto:security%40wagtail.org).
Most normal bugs in Wagtail are reported as [GitHub issues](https://github.com/wagtail/wagtail/issues), but due to the sensitive nature of security issues, we ask that they not be publicly reported in this fashion.
Instead, if you believe you’ve found something in Wagtail which has security implications, please send a description of the issue via email to [[email protected]](mailto:security%40wagtail.org). Mail sent to that address reaches a subset of the core team, who can forward security issues to other core team members for broader discussion if needed.
Once you’ve submitted an issue via email, you should receive an acknowledgement from a member of the security team within 48 hours, and depending on the action to be taken, you may receive further followup emails.
If you want to send an encrypted email (optional), the public key ID for [[email protected]](mailto:security%40wagtail.org) is `0xbed227b4daf93ff9`, and this public key is available from most commonly-used keyservers.
Django security issues should be reported directly to the Django Project, following [Django’s security policies](https://docs.djangoproject.com/en/dev/internals/security/) (upon which Wagtail’s own policies are based).
Supported versions
------------------
At any given time, the Wagtail team provides official security support for several versions of Wagtail:
* The `main` development branch, hosted on GitHub, which will become the next release of Wagtail, receives security support.
* The two most recent Wagtail release series receive security support. For example, during the development cycle leading to the release of Wagtail 2.6, support will be provided for Wagtail 2.5 and Wagtail 2.4. Upon the release of Wagtail 2.6, Wagtail 2.4’s security support will end.
* The latest long-term support release will receive security updates.
When new releases are issued for security reasons, the accompanying notice will include a list of affected versions. This list is comprised solely of supported versions of Wagtail: older versions may also be affected, but we do not investigate to determine that, and will not issue patches or new releases for those versions.
How Wagtail discloses security issues
-------------------------------------
Our process for taking a security issue from private discussion to public disclosure involves multiple steps.
There is no fixed period of time by which a confirmed security issue will be resolved as this is dependent on the issue, however it will be a priority of the Wagtail team to issue a security release as soon as possible.
The reporter of the issue will receive notification of the date on which we plan to take the issue public. On the day of disclosure, we will take the following steps:
1. Apply the relevant patch(es) to Wagtail’s codebase. The commit messages for these patches will indicate that they are for security issues, but will not describe the issue in any detail; instead, they will warn of upcoming disclosure.
2. Issue the relevant release(s), by placing new packages on [the Python Package Index](https://pypi.org/project/wagtail/), tagging the new release(s) in Wagtail’s GitHub repository and updating Wagtail’s [release notes](https://docs.wagtail.org/en/stable/releases/index.html).
3. Post a public entry on [Wagtail’s blog](https://wagtail.org/blog/), describing the issue and its resolution in detail, pointing to the relevant patches and new releases, and crediting the reporter of the issue (if the reporter wishes to be publicly identified).
4. Post a notice to the [Wagtail support forum](https://groups.google.com/g/wagtail) and Twitter feed ([@WagtailCMS](https://twitter.com/wagtailcms)) that links to the blog post.
If a reported issue is believed to be particularly time-sensitive – due to a known exploit in the wild, for example – the time between advance notification and public disclosure may be shortened considerably.
CSV export security considerations
----------------------------------
In various places Wagtail provides the option to export data in CSV format, and several reporters have raised the possibility of a malicious user inserting data that will be interpreted as a formula when loaded into a spreadsheet package such as Microsoft Excel. We do not consider this to be a security vulnerability in Wagtail. CSV as defined by [RFC 4180](https://datatracker.ietf.org/doc/html/rfc4180) is purely a data format, and makes no assertions about how that data is to be interpreted; the decision made by certain software to treat some strings as executable code has no basis in the specification. As such, Wagtail cannot be responsible for the data it generates being loaded into a software package that interprets it insecurely, any more than it would be responsible for its data being loaded into a missile control system. This is consistent with [the Google security team’s position](https://sites.google.com/site/bughunteruniversity/nonvuln/csv-excel-formula-injection).
Since the CSV format has no concept of formulae or macros, there is also no agreed-upon convention for escaping data to prevent it from being interpreted in that way; commonly-suggested approaches such as prefixing the field with a quote character would corrupt legitimate data (such as phone numbers beginning with ‘+’) when interpreted by software correctly following the CSV specification.
Wagtail’s data exports default to XLSX, which can be loaded into spreadsheet software without any such issues. This minimises the risk of a user handling CSV files insecurely, as they would have to explicitly choose CSV over the more familiar XLSX format.
wagtail Issue tracking Issue tracking
==============
We welcome bug reports, feature requests and pull requests through Wagtail’s [Github issue tracker](https://github.com/wagtail/wagtail/issues).
Issues
------
An issue must always correspond to a specific action with a well-defined completion state: fixing a bug, adding a new feature, updating documentation, or cleaning up code. Open-ended issues where the end result is not immediately clear (“come up with a way of doing translations” or “Add more features to rich text fields.”) are better suited to [Github discussions](https://github.com/wagtail/wagtail/discussions), so that there can be feedback on clear way to progress the issue and identify when it has been completed through separate issues created from the discussion.
Do not use issues for support queries or other questions (“How do I do X?” - although “Implement a way of doing X” or “Document how to do X” could well be valid issues). These should be asked on [Stack Overflow](https://stackoverflow.com/questions/tagged/wagtail) instead. For discussions that do not fit Stack Overflow’s question-and-answer format, see the other (Wagtail community support options)[https://github.com/wagtail/wagtail#community-support].
As soon as a ticket is opened - ideally within one day - a member of the core team will give it an initial classification, by either closing it due to it being invalid or updating it with the relevant labels. When a bug is opened, it will automatically be assigned the [`type:Bug`](https://github.com/wagtail/wagtail/labels/type%3ABug) and [`status:Unconfirmed`](https://github.com/wagtail/wagtail/labels/status%3AUnconfirmed) labels, once confirmed the bug can have the unconfirmed status removed. A member of the team will potentially also add a release milestone to help guide the priority of this issue. Anyone is invited to help Wagtail with reproducing `status:Unconfirmed` bugs and commenting if it is a valid bug or not with additional steps to reproduce if needed.
Don’t be discouraged if you feel that your ticket has been given a lower priority than it deserves - this decision isn’t permanent. We will consider all feedback, and reassign or reopen tickets where appropriate. (From the other side, this means that the core team member doing the classification should feel free to make bold unilateral decisions - there’s no need to seek consensus first. If they make the wrong judgement call, that can always be reversed later.)
The possible milestones that it might be assigned to are as follows:
* **invalid** (closed): this issue doesn’t identify a specific action to be taken, or the action is not one that we want to take. For example - a bug report for something that’s working as designed, or a feature request for something that’s actively harmful.
* **real-soon-now**: no-one on the core team has resources allocated to work on this right now, but we know it’s a pain point, and it will be prioritised whenever we next get a chance to choose something new to work on. In practice, that kind of free choice doesn’t happen very often - there are lots of pressures determining what we work on from day to day - so if this is a feature or fix you need, we encourage you to work on it and contribute a pull request, rather than waiting for the core team to get round to it!
* A specific version number (for example **1.6**): the issue is important enough that it needs to be fixed in this version. There are resources allocated and/or plans to work on the issue in the given version.
* No milestone: the issue is accepted as valid once the `status:Unconfirmed` label is removed (when it’s confirmed as a report for a legitimate bug, or a useful feature request) but is not deemed a priority to work on (in the opinion of the core team). For example - a bug that’s only cosmetic, or a feature that would be kind of neat but not really essential. There are no resources allocated to it - feel free to take it on!
On some occasions it may take longer for the core team to classify an issue into a milestone. For example:
* It may require a non-trivial amount of work to confirm the presence of a bug. In this case, feedback and further details from other contributors, whether or not they can replicate the bug, would be particularly welcomed.
* It may require further discussion to decide whether the proposal is a good idea or not - if so, it will be tagged [“design decision needed”](https://github.com/wagtail/wagtail/labels/status%3ANeeds%20Design%20Decision).
We will endeavour to make sure that issues don’t remain in this state for prolonged periods. Issues and PRs tagged “design decision needed” will be revisited regularly and discussed with at least two core contributors - we aim to review each ticket at least once per release cycle (= 6 weeks) as part of weekly core team meetings.
Pull requests
-------------
As with issues, the core team will classify pull requests as soon as they are opened, usually within one day. Unless the change is invalid or particularly contentious (in which case it will be closed or marked as “design decision needed”). It will generally be classified under the next applicable version - the next minor release for new features, or the next patch release for bugfixes - and marked as ‘Needs review’.
* All contributors, core and non-core, are invited to offer feedback on the pull request.
* Core team members are invited to assign themselves to the pull request for review.
* More specific details on how to triage Pull Requests can be found on the [PR triage wiki page](https://github.com/wagtail/wagtail/wiki/PR-triage).
Subsequently (ideally within a week or two, but possibly longer for larger submissions) a core team member will merge it if it is ready to be merged, or tag it as requiring further work (‘needs work’ / ‘needs tests’ / ‘needs docs’). Pull requests that require further work are handled and prioritised in the same way as issues - anyone is welcome to pick one up from the backlog, whether or not they were the original committer.
Rebasing / squashing of pull requests is welcome, but not essential. When doing so, do not squash commits that need reviewing into previous ones and make sure to preserve the sequence of changes. To fix mistakes in earlier commits, use `git commit --fixup` so that the final merge can be done with `git rebase -i --autosquash`.
Core team members working on Wagtail are expected to go through the same process with their own fork of the project.
Release schedule
----------------
We aim to release a new version every 2 months. To keep to this schedule, we will tend to ‘bump’ issues and PRs to a future release where necessary, rather than let them delay the present one. For this reason, an issue being tagged under a particular release milestone should not be taken as any kind of guarantee that the feature will actually be shipped in that release.
* See the [Release Schedule wiki page](https://github.com/wagtail/wagtail/wiki/Release-schedule) for a full list of dates.
* See the [Roadmap wiki page](https://github.com/wagtail/wagtail/wiki/Roadmap) for a general guide of project planning.
| programming_docs |
wagtail Writing documentation Writing documentation
=====================
Wagtail documentation is written in **four modes** of information delivery. Each type of information delivery has a purpose and targets a specific audience.
* [Tutorial](#doc-mode-tutorial), learning-oriented
* [How-to guide](#doc-mode-how-to-guide), goal-oriented
* [Reference](#doc-mode-reference), information-oriented
* [Explanation](#doc-mode-explanation), understanding-oriented
We are following Daniele Procida’s [Diátaxis documentation framework](https://diataxis.fr/).
Choose a writing mode
---------------------
Each page of the Wagtail documentation should be written in single mode of information delivery. Single pages with mixed modes are harder to understand. If you have documents that mix the types of information delivery, it’s best to split them up. Add links to the first section of each document to cross reference other documents on the same topic.
Writing documentation in a specific mode will help our users to understand and quickly find what they are looking for.
Tutorial
--------
Tutorials are designed to be **learning-oriented** resources which guide newcomers through a specific topic. To help effective learning, tutorials should provide examples to illustrate the subjects they cover.
Tutorials may not necessarily follow best practices. They are designed to make it easier to get started. A tutorial is concrete and particular. It must be repeatable, instil confidence, and should result in success, every time, for every learner.
### Do
* Use conversational language
* Use contractions, speak in the first person plural, be reassuring. For example: “We’re going to do this.”
* Use pictures or concrete outputs of code to reassure people that they’re on the right track. For example: “Your new login page should look like this:” or “Your directory should now have three files”.
### Don’t
* Tell people what they’re going to learn. Instead, tell them what tasks they’re going to complete.
* Use optionality in a tutorial. The word ‘if’ is a sign of danger! For example: “If you want to do this…” The expected actions and outcomes should be unambiguous.
* Assume that learners have a prior understanding of the subject.
[More about tutorials](https://diataxis.fr/tutorials/)
How-to guide
------------
A guide offers advice on how best to achieve a given task. How-to guides are **task-oriented** with a clear **goal or objective**.
### Do
* Name the guide well - ensure that the learner understands what exactly the guide does.
* Focus on actions and outcomes. For example: “If you do X, Y should happen.”
* Assume that the learner has a basic understanding of the general concepts
* Point the reader to additional resources
### Don’t
* Use an unnecessarily strict tone of voice. For example: “You must absolutely NOT do X.”
[More about how-to guides](https://diataxis.fr/how-to-guides/)
Reference
---------
Reference material is **information-oriented**. A reference is well-structured and allows the reader to find information about a specific topic. They should be short and to the point. Boring is fine! Use an imperative voice. For example: “Inherit from the Page model”.
Most references will be auto-generated based on doc-strings in the Python code.
[More about reference](https://diataxis.fr/reference/)
Explanation
-----------
Explanations are **understanding-oriented**. They are high-level and offer context to concepts and design decisions. There is little or no code involved in explanations, which are used to deepen the theoretical understanding of a practical draft. Explanations are used to establish connections and may require some prior knowledge of the principles being explored.
[More about explanation](https://diataxis.fr/explanation/)
wagtail General coding guidelines General coding guidelines
=========================
Language
--------
British English is preferred for user-facing text; this text should also be marked for translation (using the `django.utils.translation.gettext` function and `{% trans %}` template tag, for example). However, identifiers within code should use American English if the British or international spelling would conflict with built-in language keywords; for example, CSS code should consistently use the spelling `color` to avoid inconsistencies like `background-color: $colour-red`.
### Latin phrases and abbreviations
Try to avoid Latin phrases (such as `ergo` or `de facto`) and abbreviations (such as `i.e.` or `e.g.`), and use common English phrases instead. Alternatively find a simpler way to communicate the concept or idea to the reader. The exception is `etc.` which can be used when space is limited.
Examples:
| Don’t use this | Use this instead |
| --- | --- |
| e.g. | for example, such as |
| i.e. | that is |
| viz. | namely |
| ergo | therefore |
File names
----------
Where practical, try to adhere to the existing convention of file names within the folder where added.
Examples:
* Django templates - `lower_snake_case.html`
* Documentation - `lower_snake_case.md`
wagtail Python coding guidelines Python coding guidelines
========================
PEP8
----
We ask that all Python contributions adhere to the [PEP8](https://peps.python.org/pep-0008/) style guide. All files should be formatted using the [black](https://github.com/psf/black) auto-formatter. This will be run by `pre-commit` if that is configured.
* The project repository includes an `.editorconfig` file. We recommend using a text editor with [EditorConfig](https://editorconfig.org/) support to avoid indentation and whitespace issues. Python and HTML files use 4 spaces for indentation.
In addition, import lines should be sorted according to [isort](https://pycqa.github.io/isort/) 5.6.4 rules. If you have installed Wagtail’s testing dependencies (`pip install -e '.[testing]'`), you can check your code by running `make lint`. You can also just check python related linting by running `make lint-server`.
You can run all Python formatting with `make format`. Similar to linting you can format python/template only files by running `make format-server`.
Django compatibility
--------------------
Wagtail is written to be compatible with multiple versions of Django. Sometimes, this requires running one piece of code for recent version of Django, and another piece of code for older versions of Django. In these cases, always check which version of Django is being used by inspecting `django.VERSION`:
```
import django
if django.VERSION >= (1, 9):
# Use new attribute
related_field = field.rel
else:
# Use old, deprecated attribute
related_field = field.related
```
Always compare against the version using greater-or-equals (`>=`), so that code for newer versions of Django is first.
Do not use a `try ... except` when seeing if an object has an attribute or method introduced in a newer versions of Django, as it does not clearly express why the `try ... except` is used. An explicit check against the Django version makes the intention of the code very clear.
```
# Do not do this
try:
related_field = field.rel
except AttributeError:
related_field = field.related
```
If the code needs to use something that changed in a version of Django many times, consider making a function that encapsulates the check:
```
import django
def related_field(field):
if django.VERSION >= (1, 9):
return field.rel
else:
return field.related
```
If a new function has been introduced by Django that you think would be very useful for Wagtail, but is not available in older versions of Django that Wagtail supports, that function can be copied over in to Wagtail. If the user is running a new version of Django that has the function, the function should be imported from Django. Otherwise, the version bundled with Wagtail should be used. A link to the Django source code where this function was taken from should be included:
```
import django
if django.VERSION >= (1, 9):
from django.core.validators import validate_unicode_slug
else:
# Taken from https://github.com/django/django/blob/1.9/django/core/validators.py#L230
def validate_unicode_slug(value):
# Code left as an exercise to the reader
pass
```
Tests
-----
Wagtail has a suite of tests, which we are committed to improving and expanding. See [Testing](developing#testing).
We run continuous integration to ensure that no commits or pull requests introduce test failures. If your contributions add functionality to Wagtail, please include the additional tests to cover it; if your contributions alter existing functionality, please update the relevant tests accordingly.
wagtail Wagtail’s release process Wagtail’s release process
=========================
Official releases
-----------------
Release numbering works as follows:
* Versions are numbered in the form `A.B` or `A.B.C`.
* `A.B` is the *feature release* version number. Each version will be mostly backwards compatible with the previous release. Exceptions to this rule will be listed in the release notes.
* `C` is the *patch release* version number, which is incremented for bugfix and security releases. These releases will be 100% backwards-compatible with the previous patch release. The only exception is when a security or data loss issue can’t be fixed without breaking backwards-compatibility. If this happens, the release notes will provide detailed upgrade instructions.
* Before a new feature release, we’ll make at least one release candidate release. These are of the form `A.BrcN`, which means the `Nth` release candidate of version `A.B`.
In git, each Wagtail release will have a tag indicating its version number. Additionally, each release series has its own branch, called `stable/A.B.x`, and bugfix/security releases will be issued from those branches.
**Feature release**
Feature releases (A.B, A.B+1, etc.) happen every three months – see [release schedule](#release-schedule) for details. These releases will contain new features and improvements to existing features.
**Patch release**
Patch releases (A.B.C, A.B.C+1, etc.) will be issued as needed, to fix bugs and/or security issues.
These releases will be 100% compatible with the associated feature release, unless this is impossible for security reasons or to prevent data loss. So the answer to “should I upgrade to the latest patch release?” will always be “yes.”
**Long-term support release**
Certain feature releases will be designated as long-term support (LTS) releases. These releases will get security and data loss fixes applied for a guaranteed period of time, typically six months.
Release cadence
---------------
Wagtail uses a loose form of [semantic versioning](https://semver.org/). SemVer makes it easier to see at a glance how compatible releases are with each other. It also helps to anticipate when compatibility shims will be removed. It’s not a pure form of SemVer as each feature release will continue to have a few documented backwards incompatibilities where a deprecation path isn’t possible or not worth the cost.
Deprecation policy
------------------
A feature release may deprecate certain features from previous releases. If a feature is deprecated in feature release A.B, it will continue to work in the following version but raise warnings. Features deprecated in release A.B will be removed in the A.B+2 release to ensure deprecations are done over at least 2 feature releases.
So, for example, if we decided to start the deprecation of a function in Wagtail 1.4:
* Wagtail 1.4 will contain a backwards-compatible replica of the function which will raise a `RemovedInWagtail16Warning`.
* Wagtail 1.5 will still contain the backwards-compatible replica.
* Wagtail 1.6 will remove the feature outright.
The warnings are silent by default. You can turn on display of these warnings with the `python -Wd` option.
Supported versions
------------------
At any moment in time, Wagtail’s developer team will support a set of releases to varying levels.
* The current development `main` will get new features and bug fixes requiring non-trivial refactoring.
* Patches applied to the `main` branch must also be applied to the last feature release branch, to be released in the next patch release of that feature series, when they fix critical problems:
+ Security issues.
+ Data loss bugs.
+ Crashing bugs.
+ Major functionality bugs in newly-introduced features.
+ Regressions from older versions of Wagtail.The rule of thumb is that fixes will be backported to the last feature release for bugs that would have prevented a release in the first place (release blockers).
* Security fixes and data loss bugs will be applied to the current `main`, the last feature release branch, and any other supported long-term support release branches.
* Documentation fixes generally will be more freely backported to the last release branch. That’s because it’s highly advantageous to have the docs for the last release be up-to-date and correct, and the risk of introducing regressions is much less of a concern.
As a concrete example, consider a moment in time halfway between the release of Wagtail 1.6 and 1.7. At this point in time:
* Features will be added to `main`, to be released as Wagtail 1.7.
* Critical bug fixes will be applied to the `stable/1.6.x` branch, and released as 1.6.1, 1.6.2, etc.
* Security fixes and bug fixes for data loss issues will be applied to `main` and to the `stable/1.6.x` and `stable/1.4.x` (LTS) branches. They will trigger the release of `1.6.1`, `1.4.8`, etc.
* Documentation fixes will be applied to `main`, and, if easily backported, to the latest stable branch, `1.6.x`.
Supported versions of Django
----------------------------
Each release of Wagtail declares which versions of Django it supports.
Typically, a new Wagtail feature release supports the last long-term support version and all following versions of Django.
For example, consider a moment in time before release of Wagtail 1.5 and after the following releases:
* Django 1.8 (LTS)
* Django 1.9
* Wagtail 1.4 (LTS) - Released before Django 1.10 and supports Django 1.8 and 1.9
* Django 1.10
Wagtail 1.5 will support Django 1.8 (LTS), 1.9, 1.10. Wagtail 1.4 will still support only Django 1.8 (LTS) and 1.9.
Release schedule
----------------
Wagtail uses a [time-based release schedule](https://github.com/wagtail/wagtail/wiki/Release-schedule), with feature releases every three months.
After each feature release, the release manager will announce a timeline for the next feature release.
### Release cycle
Each release cycle consists of three parts:
#### Phase one: feature proposal
The first phase of the release process will include figuring out what major features to include in the next version. This should include a good deal of preliminary work on those features – working code trumps grand design.
#### Phase two: development
The second part of the release schedule is the “heads-down” working period. Using the roadmap produced at the end of phase one, we’ll all work very hard to get everything on it done.
At the end of phase two, any unfinished features will be postponed until the next release.
At this point, the `stable/A.B.x` branch will be forked from `main`.
#### Phase three: bugfixes
The last part of a release cycle is spent fixing bugs – no new features will be accepted during this time.
Once all known blocking bugs have been addressed, a release candidate will be made available for testing. The final release will usually follow two weeks later, although this period may be extended if the further release blockers are found.
During this phase, committers will be more and more conservative with backports, to avoid introducing regressions. After the release candidate, only release blockers and documentation fixes should be backported.
Developers should avoid adding any new translatable strings after the release candidate - this ensures that translators have the full period between the release candidate and the final release to bring translations up to date. Translations will be re-imported immediately before the final release.
In parallel to this phase, `main` can receive new features, to be released in the `A.B+1` cycle.
### Bug-fix releases
After a feature release `A.B`, the previous release will go into bugfix mode.
The branch for the previous feature release `stable/A.B-1.x` will include bugfixes. Critical bugs fixed on `main` must *also* be fixed on the bugfix branch; this means that commits need to cleanly separate bug fixes from feature additions. The developer who commits a fix to `main` will be responsible for also applying the fix to the current bugfix branch.
wagtail About StreamField BoundBlocks and values About StreamField BoundBlocks and values
========================================
All StreamField block types accept a `template` parameter to determine how they will be rendered on a page. However, for blocks that handle basic Python data types, such as `CharBlock` and `IntegerBlock`, there are some limitations on where the template will take effect, since those built-in types (`str`, `int` and so on) cannot be ‘taught’ about their template rendering. As an example of this, consider the following block definition:
```
class HeadingBlock(blocks.CharBlock):
class Meta:
template = 'blocks/heading.html'
```
where `blocks/heading.html` consists of:
```
<h1>{{ value }}</h1>
```
This gives us a block that behaves as an ordinary text field, but wraps its output in `<h1>` tags whenever it is rendered:
```
class BlogPage(Page):
body = StreamField([
# ...
('heading', HeadingBlock()),
# ...
], use_json_field=True)
```
```
{% load wagtailcore_tags %}
{% for block in page.body %}
{% if block.block_type == 'heading' %}
{% include_block block %} {# This block will output its own <h1>...</h1> tags. #}
{% endif %}
{% endfor %}
```
This kind of arrangement - a value that supposedly represents a plain text string, but has its own custom HTML representation when output on a template - would normally be a very messy thing to achieve in Python, but it works here because the items you get when iterating over a StreamField are not actually the ‘native’ values of the blocks. Instead, each item is returned as an instance of `BoundBlock` - an object that represents the pairing of a value and its block definition. By keeping track of the block definition, a `BoundBlock` always knows which template to render. To get to the underlying value - in this case, the text content of the heading - you would need to access `block.value`. Indeed, if you were to output `{% include_block block.value %}` on the page, you would find that it renders as plain text, without the `<h1>` tags.
(More precisely, the items returned when iterating over a StreamField are instances of a class `StreamChild`, which provides the `block_type` property as well as `value`.)
Experienced Django developers may find it helpful to compare this to the `BoundField` class in Django’s forms framework, which represents the pairing of a form field value with its corresponding form field definition, and therefore knows how to render the value as an HTML form field.
Most of the time, you won’t need to worry about these internal details; Wagtail will use the template rendering wherever you would expect it to. However, there are certain cases where the illusion isn’t quite complete - namely, when accessing children of a `ListBlock` or `StructBlock`. In these cases, there is no `BoundBlock` wrapper, and so the item cannot be relied upon to know its own template rendering. For example, consider the following setup, where our `HeadingBlock` is a child of a StructBlock:
```
class EventBlock(blocks.StructBlock):
heading = HeadingBlock()
description = blocks.TextBlock()
# ...
class Meta:
template = 'blocks/event.html'
```
In `blocks/event.html`:
```
{% load wagtailcore_tags %}
<div class="event {% if value.heading == 'Party!' %}lots-of-balloons{% endif %}">
{% include_block value.heading %}
- {% include_block value.description %}
</div>
```
In this case, `value.heading` returns the plain string value rather than a `BoundBlock`; this is necessary because otherwise the comparison in `{% if value.heading == 'Party!' %}` would never succeed. This in turn means that `{% include_block value.heading %}` renders as the plain string, without the `<h1>` tags. To get the HTML rendering, you need to explicitly access the `BoundBlock` instance through `value.bound_blocks.heading`:
```
{% load wagtailcore_tags %}
<div class="event {% if value.heading == 'Party!' %}lots-of-balloons{% endif %}">
{% include_block value.bound_blocks.heading %}
- {% include_block value.description %}
</div>
```
In practice, it would probably be more natural and readable to make the `<h1>` tag explicit in the EventBlock’s template:
```
{% load wagtailcore_tags %}
<div class="event {% if value.heading == 'Party!' %}lots-of-balloons{% endif %}">
<h1>{{ value.heading }}</h1>
- {% include_block value.description %}
</div>
```
This limitation does not apply to StructBlock and StreamBlock values as children of a StructBlock, because Wagtail implements these as complex objects that know their own template rendering, even when not wrapped in a `BoundBlock`. For example, if a StructBlock is nested in another StructBlock, as in:
```
class EventBlock(blocks.StructBlock):
heading = HeadingBlock()
description = blocks.TextBlock()
guest_speaker = blocks.StructBlock([
('first_name', blocks.CharBlock()),
('surname', blocks.CharBlock()),
('photo', ImageChooserBlock()),
], template='blocks/speaker.html')
```
then `{% include_block value.guest_speaker %}` within the EventBlock’s template will pick up the template rendering from `blocks/speaker.html` as intended.
In summary, interactions between BoundBlocks and plain values work according to the following rules:
1. When iterating over the value of a StreamField or StreamBlock (as in `{% for block in page.body %}`), you will get back a sequence of BoundBlocks.
2. If you have a BoundBlock instance, you can access the plain value as `block.value`.
3. Accessing a child of a StructBlock (as in `value.heading`) will return a plain value; to retrieve the BoundBlock instead, use `value.bound_blocks.heading`.
4. Likewise, accessing children of a ListBlock (for example `for item in value`) will return plain values; to retrieve BoundBlocks instead, use `value.bound_blocks`.
5. StructBlock and StreamBlock values always know how to render their own templates, even if you only have the plain value rather than the BoundBlock.
Changed in version 2.16: The value of a ListBlock now provides a `bound_blocks` property; previously it was a plain Python list of child values.
| programming_docs |
wagtail How to add Wagtail into an existing Django project How to add Wagtail into an existing Django project
==================================================
To install Wagtail completely from scratch, create a new Django project and an app within that project. For instructions on these tasks, see [Writing your first Django app](https://docs.djangoproject.com/en/stable/intro/tutorial01/ "(in Django v4.1)"). Your project directory will look like the following:
```
myproject/
myproject/
__init__.py
settings.py
urls.py
wsgi.py
myapp/
__init__.py
models.py
tests.py
admin.py
views.py
manage.py
```
From your app directory, you can safely remove `admin.py` and `views.py`, since Wagtail will provide this functionality for your models. Configuring Django to load Wagtail involves adding modules and variables to `settings.py` and URL configuration to `urls.py`. For a more complete view of what’s defined in these files, see [Django Settings](https://docs.djangoproject.com/en/stable/topics/settings/ "(in Django v4.1)") and [Django URL Dispatcher](https://docs.djangoproject.com/en/stable/topics/http/urls/ "(in Django v4.1)").
What follows is a settings reference which skips many boilerplate Django settings. If you just want to get your Wagtail install up quickly without fussing with settings at the moment, see [Ready to Use Example Configuration Files](#complete-example-config).
Middleware (`settings.py`)
--------------------------
```
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'wagtail.contrib.redirects.middleware.RedirectMiddleware',
]
```
Wagtail depends on the default set of Django middleware modules, to cover basic security and functionality such as login sessions. One additional middleware module is provided:
**`RedirectMiddleware`**
Wagtail provides a simple interface for adding arbitrary redirects to your site and this module makes it happen.
Apps (`settings.py`)
--------------------
```
INSTALLED_APPS = [
'myapp', # your own app
'wagtail.contrib.forms',
'wagtail.contrib.redirects',
'wagtail.embeds',
'wagtail.sites',
'wagtail.users',
'wagtail.snippets',
'wagtail.documents',
'wagtail.images',
'wagtail.search',
'wagtail.admin',
'wagtail',
'taggit',
'modelcluster',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
```
Wagtail requires several Django app modules, third-party apps, and defines several apps of its own. Wagtail was built to be modular, so many Wagtail apps can be omitted to suit your needs. Your own app (here `myapp`) is where you define your models, templates, static assets, template tags, and other custom functionality for your site.
### Wagtail Apps
**`wagtail`**
The core functionality of Wagtail, such as the `Page` class, the Wagtail tree, and model fields.
**`wagtail.admin`**
The administration interface for Wagtail, including page edit handlers.
**`wagtail.documents`**
The Wagtail document content type.
**`wagtail.snippets`**
Editing interface for non-Page models and objects. See [Snippets](../topics/snippets#snippets).
**`wagtail.users`**
User editing interface.
**`wagtail.images`**
The Wagtail image content type.
**`wagtail.embeds`**
Module governing oEmbed and Embedly content in Wagtail rich text fields. See .
**`wagtail.search`**
Search framework for Page content. See [Search](../topics/search/index#wagtailsearch).
**`wagtail.sites`**
Management UI for Wagtail sites.
**`wagtail.contrib.redirects`**
Admin interface for creating arbitrary redirects on your site.
**`wagtail.contrib.forms`**
Models for creating forms on your pages and viewing submissions. See [Form builder](../reference/contrib/forms/index#form-builder).
### Third-Party Apps
**`taggit`**
Tagging framework for Django. This is used internally within Wagtail for image and document tagging and is available for your own models as well. See [Tagging](../reference/pages/model_recipes#tagging) for a Wagtail model recipe or the [Taggit Documentation](https://django-taggit.readthedocs.io/en/stable/).
**`modelcluster`**
Extension of Django ForeignKey relation functionality, which is used in Wagtail pages for on-the-fly related object creation. For more information, see [Inline Panels and Model Clusters](../reference/pages/panels#inline-panels) or [the django-modelcluster github project page](https://github.com/wagtail/django-modelcluster).
URL Patterns
------------
```
from django.contrib import admin
from wagtail import urls as wagtail_urls
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.documents import urls as wagtaildocs_urls
urlpatterns = [
path('django-admin/', admin.site.urls),
path('admin/', include(wagtailadmin_urls)),
path('documents/', include(wagtaildocs_urls)),
# Optional URL for including your own vanilla Django urls/views
re_path(r'', include('myapp.urls')),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's serving mechanism
re_path(r'', include(wagtail_urls)),
]
```
This block of code for your project’s `urls.py` does a few things:
* Load the vanilla Django admin interface to `/django-admin/`
* Load the Wagtail admin and its various apps
* Dispatch any vanilla Django apps you’re using other than Wagtail which require their own URL configuration (this is optional, since Wagtail might be all you need)
* Lets Wagtail handle any further URL dispatching.
That’s not everything you might want to include in your project’s URL configuration, but it’s what’s necessary for Wagtail to flourish.
Ready to Use Example Configuration Files
----------------------------------------
These two files should reside in your project directory (`myproject/myproject/`).
### `settings.py`
```
import os
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BASE_DIR = os.path.dirname(PROJECT_DIR)
DEBUG = True
# Application definition
INSTALLED_APPS = [
'myapp',
'wagtail.contrib.forms',
'wagtail.contrib.redirects',
'wagtail.embeds',
'wagtail.sites',
'wagtail.users',
'wagtail.snippets',
'wagtail.documents',
'wagtail.images',
'wagtail.search',
'wagtail.admin',
'wagtail',
'taggit',
'modelcluster',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
'wagtail.contrib.redirects.middleware.RedirectMiddleware',
]
ROOT_URLCONF = 'myproject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [
os.path.join(PROJECT_DIR, 'templates'),
],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'myproject.wsgi.application'
# Database
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'myprojectdb',
'USER': 'postgres',
'PASSWORD': '',
'HOST': '', # Set to empty string for localhost.
'PORT': '', # Set to empty string for default.
'CONN_MAX_AGE': 600, # number of seconds database connections should persist for
}
}
# Internationalization
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
STATICFILES_FINDERS = [
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
]
STATICFILES_DIRS = [
os.path.join(PROJECT_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
ADMINS = [
# ('Your Name', '[email protected]'),
]
MANAGERS = ADMINS
# Default to dummy email backend. Configure dev/production/local backend
# as per https://docs.djangoproject.com/en/stable/topics/email/#email-backends
EMAIL_BACKEND = 'django.core.mail.backends.dummy.EmailBackend'
# Hosts/domain names that are valid for this site; required if DEBUG is False
ALLOWED_HOSTS = []
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'change-me'
EMAIL_SUBJECT_PREFIX = '[Wagtail] '
INTERNAL_IPS = ('127.0.0.1', '10.0.2.2')
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See https://docs.djangoproject.com/en/stable/topics/logging for
# more details on how to customise your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
# WAGTAIL SETTINGS
# This is the human-readable name of your Wagtail install
# which welcomes users upon login to the Wagtail admin.
WAGTAIL_SITE_NAME = 'My Project'
# Replace the search backend
#WAGTAILSEARCH_BACKENDS = {
# 'default': {
# 'BACKEND': 'wagtail.search.backends.elasticsearch5',
# 'INDEX': 'myapp'
# }
#}
# Wagtail email notifications from address
# WAGTAILADMIN_NOTIFICATION_FROM_EMAIL = '[email protected]'
# Wagtail email notification format
# WAGTAILADMIN_NOTIFICATION_USE_HTML = True
# Reverse the default case-sensitive handling of tags
TAGGIT_CASE_INSENSITIVE = True
```
### `urls.py`
```
from django.urls import include, path, re_path
from django.conf.urls.static import static
from django.views.generic.base import RedirectView
from django.contrib import admin
from django.conf import settings
import os.path
from wagtail import urls as wagtail_urls
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.documents import urls as wagtaildocs_urls
urlpatterns = [
path('django-admin/', admin.site.urls),
path('admin/', include(wagtailadmin_urls)),
path('documents/', include(wagtaildocs_urls)),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's serving mechanism
re_path(r'', include(wagtail_urls)),
]
if settings.DEBUG:
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns() # tell gunicorn where static files are in dev mode
urlpatterns += static(settings.MEDIA_URL + 'images/', document_root=os.path.join(settings.MEDIA_ROOT, 'images'))
urlpatterns += [
path('favicon.ico', RedirectView.as_view(url=settings.STATIC_URL + 'myapp/images/favicon.ico'))
]
```
wagtail Accessibility considerations Accessibility considerations
============================
Accessibility for CMS-driven websites is a matter of [modeling content appropriately](#content-modeling), [creating accessible templates](#accessibility-in-templates), and [authoring accessible content](#authoring-accessible-content) with readability and accessibility guidelines in mind.
Wagtail generally puts developers in control of content modeling and front-end markup, but there are a few areas to be aware of nonetheless, and ways to help authors be aware of readability best practices. Note there is much more to building accessible websites than we cover here – see our list of [accessibility resources](#accessibility-resources) for more information.
* [Content modeling](#content-modeling)
* [Accessibility in templates](#accessibility-in-templates)
* [Authoring accessible content](#authoring-accessible-content)
* [Accessibility resources](#accessibility-resources)
Content modeling
----------------
As part of defining your site’s models, here are areas to pay special attention to:
### Alt text for images
The default behaviour for Wagtail images is to use the `title` field as the alt text ([#4945](https://github.com/wagtail/wagtail/issues/4945)). This is inappropriate, as it’s not communicated in the CMS interface, and the image upload form uses the image’s filename as the title by default.
Ideally, always add an optional “alt text” field wherever an image is used, alongside the image field:
* For normal fields, add an alt text field to your image’s panel.
* For StreamField, add an extra field to your image block.
* For rich text – Wagtail already makes it possible to customise alt text for rich text images.
When defining the alt text fields, make sure they are optional so editors can choose to not write any alt text for decorative images. Take the time to provide `help_text` with appropriate guidance. For example, linking to [established resources on alt text](https://axesslab.com/alt-texts/).
Note
Should I add an alt text field on the Image model for my site?
It’s better than nothing to have a dedicated alt field on the Image model ([#5789](https://github.com/wagtail/wagtail/pull/5789)), and may be appropriate for some websites, but we recommend to have it inline with the content because ideally alt text should be written for the context the image is used in:
* If the alt text’s content is already part of the rest of the page, ideally the image should not repeat the same content.
* Ideally, the alt text should be written based on the context the image is displayed in.
* An image might be decorative in some cases but not in others. For example, thumbnails in page listings can often be considered decorative.
See [RFC 51: Contextual alt text](https://github.com/wagtail/rfcs/pull/51) for a long-term solution to this problem.
### Embeds title
Missing embed titles are common failures in accessibility audits of Wagtail websites. In some cases, Wagtail embeds’ iframe doesn’t have a `title` attribute set. This is generally a problem with OEmbed providers like YouTube ([#5982](https://github.com/wagtail/wagtail/issues/5982)). This is very problematic for screen reader users, who rely on the title to understand what the embed is, and whether to interact with it or not.
If your website relies on embeds that have are missing titles, make sure to either:
* Add the OEmbed *title* field as a `title` on the `iframe`.
* Add a custom mandatory Title field to your embeds, and add it as the `iframe`’s `title`.
### Available heading levels
Wagtail makes it very easy for developers to control which heading levels should be available for any given content, via [rich text features](customisation/page_editing_interface#rich-text-features) or custom StreamField blocks. In both cases, take the time to restrict what heading levels are available so the pages’ document outline is more likely to be logical and sequential. Consider using the following restrictions:
* Disallow `h1` in rich text. There should only be one `h1` tag per page, which generally maps to the page’s `title`.
* Limit heading levels to `h2` for the main content of a page. Add `h3` only if deemed necessary. Avoid other levels as a general rule.
* For content that is displayed in a specific section of the page, limit heading levels to those directly below the section’s main heading.
If managing headings via StreamField, make sure to apply the same restrictions there.
### Bold and italic formatting in rich text
By default, Wagtail stores its bold formatting as a `b` tag, and italic as `i` ([#4665](https://github.com/wagtail/wagtail/issues/4665)). While those tags don’t necessarily always have correct semantics (`strong` and `em` are more ubiquitous), there isn’t much consequence for screen reader users, as by default screen readers do not announce content differently based on emphasis.
If this is a concern to you, you can change which tags are used when saving content with [rich text format converters](../extending/rich_text_internals#rich-text-format-converters). In the future, [rich text rewrite handlers](../extending/rich_text_internals#rich-text-rewrite-handlers) should also support this being done without altering the storage format ([#4223](https://github.com/wagtail/wagtail/issues/4223)).
### TableBlock
The [TableBlock](../reference/contrib/table_block) default implementation makes it too easy for end-users to miss they need either row or column headers ([#5989](https://github.com/wagtail/wagtail/issues/5989%3E)). Make sure to always have either row headers or column headers set. Always add a Caption, so screen reader users navigating the site’s tables know where they are.
Accessibility in templates
--------------------------
Here are common gotchas to be aware of to make the site’s templates as accessible as possible,
### Alt text in templates
See the [content modelling](#content-modeling) section above. Additionally, make sure to [customise images’ alt text](../topics/images#image-tag-alt), either setting it to the relevant field, or to an empty string for decorative images, or images where the alt text would be a repeat of other content. Even when your images have alt text coming directly from the image model, you still need to decide whether there should be alt text for the particular context the image is used in. For example, avoid alt text in listings where the alt text just repeats the listing items’ title.
### Empty heading tags
In both rich text and custom StreamField blocks, it’s sometimes easy for editors to create a heading block but not add any content to it. If this is a problem for your site,
* Add validation rules to those fields, making sure the page can’t be saved with the empty headings, for example by using the [StreamField](../topics/streamfield) `CharBlock` which is required by default.
* Consider adding similar validation rules for rich text fields ([#6526](https://github.com/wagtail/wagtail/issues/6526)).
Additionally, you can hide empty heading blocks with CSS:
```
h1:empty,
h2:empty,
h3:empty,
h4:empty,
h5:empty,
h6:empty {
display: none;
}
```
### Forms
The [Form builder](../reference/contrib/forms/index#form-builder) uses Django’s forms API. Here are considerations specific to forms in templates:
* Avoid rendering helpers such as `as_table`, `as_ul`, `as_p`, which can make forms harder to navigate for screen reader users or cause HTML validation issues (see Django ticket [#32339](https://code.djangoproject.com/ticket/32339)).
* Make sure to visually distinguish required and optional fields.
* Take the time to group related fields together in `fieldset`, with an appropriate `legend`, in particular for radios and checkboxes (see Django ticket [#32338](https://code.djangoproject.com/ticket/32338)).
* If relevant, use the appropriate `autocomplete` and `autocapitalize` attributes.
* For Date and Datetime fields, make sure to display the expected format or an example value (see Django ticket [#32340](https://code.djangoproject.com/ticket/32340)). Or use [input type=”date”](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/date).
* For Number fields, consider whether `input type="number"` really is appropriate, or whether there may be [better alternatives such as inputmode](https://technology.blog.gov.uk/2020/02/24/why-the-gov-uk-design-system-team-changed-the-input-type-for-numbers/).
Make sure to test your forms’ implementation with assistive technologies, and review [official W3C guidance on accessible forms development](https://www.w3.org/WAI/tutorials/forms/) for further information.
Authoring accessible content
----------------------------
Here are things you can do to help authors create accessible content.
### wagtail-accessibility
[wagtail-accessibility](https://github.com/neon-jungle/wagtail-accessibility) is a third-party package which adds [tota11y](https://khan.github.io/tota11y/) to Wagtail previews. This makes it easy for authors to run basic accessibility checks – validating the page’s heading outline, or link text.
### help\_text and HelpPanel
Occasional Wagtail users may not be aware of your site’s content guidelines, or best practices of writing for the web. Use fields’ `help_text` and `HelpPanel` (see [Panel types](../reference/pages/panels)).
### Readability
Readability is fundamental to accessibility. One of the ways to improve text content is to have a clear target for reading level / reading age, which can be assessed with [wagtail-readinglevel](https://github.com/vixdigital/wagtail-readinglevel) as a score displayed in rich text fields.
Accessibility resources
-----------------------
We focus on considerations specific to Wagtail websites, but there is much more to accessibility. Here are valuable resources to learn more, for developers but also designers and authors:
* [W3C Accessibility Fundamentals](https://www.w3.org/WAI/fundamentals/)
* [The A11Y Project](https://www.a11yproject.com/)
* [US GSA – Accessibility for Teams](https://accessibility.digital.gov/)
* [UK GDS – Dos and don’ts on designing for accessibility](https://accessibility.blog.gov.uk/2016/09/02/dos-and-donts-on-designing-for-accessibility/)
* [Accessibility Developer Guide](https://www.accessibility-developer-guide.com/)
| programming_docs |
wagtail Advanced topics Advanced topics
===============
* [Images](images/index)
+ [Generating renditions in Python](images/renditions)
+ [Animated GIF support](images/animated_gifs)
+ [Image file formats](images/image_file_formats)
+ [Custom image models](images/custom_image_model)
+ [Changing rich text representation](images/changing_rich_text_representation)
+ [Feature Detection](images/feature_detection)
+ [Dynamic image serve view](images/image_serve_view)
+ [Focal points](images/focal_points)
+ [Title generation on upload](images/title_generation_on_upload)
* [Documents](documents/index)
+ [Custom document model](documents/custom_document_model)
+ [Title generation on upload](documents/title_generation_on_upload)
* [Embedded content](embeds)
+ [Embedding content on your site](embeds#embedding-content-on-your-site)
+ [Configuring embed “finders”](embeds#configuring-embed-finders)
+ [The `Embed` model](embeds#the-embed-model)
* [How to add Wagtail into an existing Django project](add_to_django_project)
+ [Middleware (`settings.py`)](add_to_django_project#middleware-settings-py)
+ [Apps (`settings.py`)](add_to_django_project#apps-settings-py)
+ [URL Patterns](add_to_django_project#url-patterns)
+ [Ready to Use Example Configuration Files](add_to_django_project#ready-to-use-example-configuration-files)
* [Deploying Wagtail](deploying)
+ [On your server](deploying#on-your-server)
+ [On Divio Cloud](deploying#on-divio-cloud)
+ [On PythonAnywhere](deploying#on-pythonanywhere)
+ [On Google Cloud](deploying#on-google-cloud)
+ [On alwaysdata](deploying#on-alwaysdata)
+ [On other PAASs and IAASs](deploying#on-other-paass-and-iaass)
+ [Deployment tips](deploying#deployment-tips)
* [Performance](performance)
+ [Editor interface](performance#editor-interface)
+ [Public users](performance#public-users)
* [Internationalisation](i18n)
+ [Multi-language content](i18n#multi-language-content)
+ [Alternative internationalisation plugins](i18n#alternative-internationalisation-plugins)
+ [Wagtail admin translations](i18n#wagtail-admin-translations)
+ [Change Wagtail admin language on a per-user basis](i18n#change-wagtail-admin-language-on-a-per-user-basis)
+ [Changing the primary language of your Wagtail installation](i18n#changing-the-primary-language-of-your-wagtail-installation)
* [Private pages](privacy)
+ [Setting up a login page](privacy#setting-up-a-login-page)
+ [Setting up a global “password required” page](privacy#setting-up-a-global-password-required-page)
+ [Setting a “password required” page for a specific page type](privacy#setting-a-password-required-page-for-a-specific-page-type)
* [Customising Wagtail](customisation/index)
+ [Customising the editing interface](customisation/page_editing_interface)
+ [Customising admin templates](customisation/admin_templates)
+ [Custom user models](customisation/custom_user_models)
+ [How to build custom StreamField blocks](customisation/streamfield_blocks)
* [Third-party tutorials](third_party_tutorials)
+ [Tip](third_party_tutorials#tip)
* [Testing your Wagtail site](testing)
+ [WagtailPageTestCase](testing#wagtailpagetestcase)
+ [Form data helpers](testing#module-wagtail.test.utils.form_data)
+ [Fixtures](testing#fixtures)
* [Wagtail API](api/index)
+ [Wagtail API v2 Configuration Guide](api/v2/configuration)
+ [Wagtail API v2 Usage Guide](api/v2/usage)
* [How to build a site with AMP support](amp)
+ [Overview](amp#overview)
+ [Creating the second page tree](amp#creating-the-second-page-tree)
+ [Making pages aware of “AMP mode”](amp#making-pages-aware-of-amp-mode)
+ [Write a template context processor so that AMP state can be checked in templates](amp#write-a-template-context-processor-so-that-amp-state-can-be-checked-in-templates)
+ [Using a different page template when AMP mode is active](amp#using-a-different-page-template-when-amp-mode-is-active)
+ [Overriding the `{% image %}` tag to output `<amp-img>` tags](amp#overriding-the-image-tag-to-output-amp-img-tags)
* [Accessibility considerations](accessibility_considerations)
+ [Content modeling](accessibility_considerations#content-modeling)
+ [Accessibility in templates](accessibility_considerations#accessibility-in-templates)
+ [Authoring accessible content](accessibility_considerations#authoring-accessible-content)
+ [Accessibility resources](accessibility_considerations#accessibility-resources)
* [About StreamField BoundBlocks and values](boundblocks_and_values)
* [Multi-site, multi-instance and multi-tenancy](multi_site_multi_instance_multi_tenancy)
+ [Multi-site](multi_site_multi_instance_multi_tenancy#multi-site)
+ [Multi-instance](multi_site_multi_instance_multi_tenancy#multi-instance)
+ [Multi-tenancy](multi_site_multi_instance_multi_tenancy#multi-tenancy)
* [How to use a redirect with Form builder to prevent double submission](formbuilder_routablepage_redirect)
wagtail How to use a redirect with Form builder to prevent double submission How to use a redirect with Form builder to prevent double submission
====================================================================
It is common for form submission HTTP responses to be a `302 Found` temporary redirection to a new page. By default `wagtail.contrib.forms.models.FormPage` success responses don’t do this, meaning there is a risk that users will refresh the success page and re-submit their information.
Instead of rendering the `render_landing_page` content in the POST response, we will redirect to a `route` of the `FormPage` instance at a child URL path. The content will still be managed within the same form page’s admin. This approach uses the additional contrib module `wagtail.contrib.routable_page`.
An alternative approach is to redirect to an entirely different page, which does not require the `routable_page` module. See [Custom landing page redirect](../reference/contrib/forms/customisation#form-builder-custom-landing-page-redirect).
Make sure `"wagtail.contrib.routable_page"` is added to `INSTALLED_APPS`, see [RoutablePageMixin](../reference/contrib/routablepage#routable-page-mixin) documentation.
```
from django.shortcuts import redirect
from wagtail.contrib.forms.models import AbstractEmailForm
from wagtail.contrib.routable_page.models import RoutablePageMixin, path
class FormPage(RoutablePageMixin, AbstractEmailForm):
# fields, content_panels, …
@path("")
def index_route(self, request, *args, **kwargs):
"""Serve the form, and validate it on POST"""
return super(AbstractEmailForm, self).serve(request, *args, **kwargs)
def render_landing_page(self, request, form_submission, *args, **kwargs):
"""Redirect instead to self.thank_you route"""
url = self.reverse_subpage("thank_you")
# If a form_submission instance is available, append the ID to URL.
if form_submission:
url += "?id=%s" % form_submission.id
return redirect(self.url + url, permanent=False)
@path("thank-you/")
def thank_you(self, request):
"""Return the superclass's landing page, after redirect."""
form_submission = None
try:
submission_id = int(request.GET["id"])
except (KeyError, TypeError):
pass
else:
submission_class = self.get_submission_class()
try:
form_submission = submission_class.objects.get(id=submission_id)
except submission_class.DoesNotExist:
pass
return super().render_landing_page(request, form_submission)
```
wagtail Multi-site, multi-instance and multi-tenancy Multi-site, multi-instance and multi-tenancy
============================================
This page gives background information on how to run multiple Wagtail sites (with the same source code).
* [Multi-site](#multi-site)
* [Multi-instance](#multi-instance)
* [Multi-tenancy](#multi-tenancy)
Multi-site
----------
Multi-site is a Wagtail project configuration where content creators go into a single admin interface and manage the content of multiple websites. Permission to manage specific content, and restricting access to other content, is possible to some extent.
Multi-site configuration is a single code base, on a single server, connecting to a single database. Media is stored in a single media root directory. Content can be shared between sites.
Wagtail supports multi-site out of the box: Wagtail comes with a [site model](../reference/pages/model_reference#wagtail.models.Site "wagtail.models.Site"). The site model contains a hostname, port, and root page field. When a URL is requested, the request comes in, the domain name and port are taken from the request object to look up the correct site object. The root page is used as starting point to resolve the URL and serve the correct page.
Wagtail also comes with [site settings](../reference/contrib/settings#site-settings). *Site settings* are ‘singletons’ that let you store additional information on a site. For example, social media settings, a field to upload a logo, or a choice field to select a theme.
Model objects can be linked to a site by placing a foreign key field on the model pointing to the site object. A request object can be used to look up the current site. This way, content belonging to a specific site can be served.
User, groups, and permissions can be configured in such a way that content creators can only manage the pages, images, and documents of a specific site. Wagtail can have multiple *site objects* and multiple *page trees*. Permissions can be linked to a specific page tree or a subsection thereof. Collections are used to categorize images and documents. A collection can be restricted to users who are in a specific group.
Some projects require content editors to have permissions on specific sites and restrict access to other sites. Splitting *all* content per site and guaranteeing that no content ‘leaks’ is difficult to realize in a multi-site project. If you require full separation of content, then multi-instance might be a better fit…
Multi-instance
--------------
Multi-instance is a Wagtail project configuration where a single set of project files is used by multiple websites. Each website has its own settings file, and a dedicated database and media directory. Each website runs in its own server process. This guarantees the *total separation* of *all content*.
Assume the domains a.com and b.com. Settings files can be `base.py`, `acom.py`, and `bcom.py`. The base settings will contain all settings like normal. The contents of site-specific settings override the base settings:
```
# settings/acom.py
from base import \* # noqa
ALLOWED_HOSTS = ['a.com']
DATABASES["NAME"] = "acom"
DATABASES["PASSWORD"] = "password-for-acom"
MEDIA_DIR = BASE_DIR / "acom-media"
```
Each site can be started with its own settings file. In development `./manage.py runserver --settings settings.acom`. In production, for example with uWSGI, specify the correct settings with `env = DJANGO_SETTINGS_MODULE=settings.acom`.
Because each site has its own database and media folder, nothing can ‘leak’ to another site. But this also means that content cannot be shared between sites as one can do when using the multi-site option.
In this configuration, multiple sites share the same, single set of project files. Deployment would update the single set of project files and reload each instance.
This multi-instance configuration isn’t that different from deploying the project code several times. However, having a single set of project files, and only differentiate with settings files, is the closest Wagtail can get to true multi-tenancy. Every site is identical, content is separated, including user management. ‘Adding a new tenant’ is adding a new settings file and running a new instance.
In a multi-instance configuration, each instance requires a certain amount of server resources (CPU and memory). That means adding sites will increase server load. This only scales up to a certain point.
Multi-tenancy
-------------
Multi-tenancy is a project configuration in which a single instance of the software serves multiple tenants. A tenant is a group of users who have access and permission to a single site. Multitenant software is designed to provide every tenant its configuration, data, and user management.
Wagtail supports *multi-site*, where user management and content are shared. Wagtail can run *multi-instance* where there is full separation of content at the cost of running multiple instances. Multi-tenancy combines the best of both worlds: a single instance, and the full separation of content per site and user management.
Wagtail does not support full multi-tenancy at this moment. But it is on our radar, we would like to improve Wagtail to add multi-tenancy - while still supporting the existing multi-site option. If you have ideas or like to contribute, join us on [Slack](../support#slack) in the multi-tenancy channel.
Wagtail currently has the following features to support multi-tenancy:
* A Site model mapping a hostname to a root page
* Permissions to allow groups of users to manage:
+ arbitrary sections of the page tree
+ sections of the collection tree (coming soon)
+ one or more collections of documents and images
* The page API is automatically scoped to the host used for the request
But several features do not currently support multi-tenancy:
* Snippets are global pieces of content so not suitable for multi-tenancy but any model that can be registered as a snippet can also be managed via the Wagtail model admin. You can add a site\_id to the model and then use the model admin get\_queryset method to determine which site can manage each object. The built-in snippet choosers can be replaced by [modelchooser](https://pypi.org/project/wagtail-modelchooser/) that allows filtering the queryset to restrict which sites may display which objects.
* Site, site setting, user, and group management. At the moment, your best bet is to only allow superusers to manage these objects.
* Workflows and workflow tasks
* Site history
* Redirects
Permission configuration for built-in models like Sites, Site settings and Users is not site-specific, so any user with permission to edit a single entry can edit them all. This limitation can be mostly circumvented by only allowing superusers to manage these models.
Python, Django, and Wagtail allow you to override, extend and customise functionality. Here are some ideas that may help you create a multi-tenancy solution for your site:
* Django allows to override templates, this also works in the Wagtail admin.
* A custom user model can be used to link users to a specific site.
* Custom admin views can provide more restrictive user management.
We welcome interested members of the Wagtail community to contribute code and ideas.
wagtail Performance Performance
===========
Wagtail is designed for speed, both in the editor interface and on the front-end, but if you want even better performance or you need to handle very high volumes of traffic, here are some tips on eking out the most from your installation.
Editor interface
----------------
We have tried to minimise external dependencies for a working installation of Wagtail, in order to make it as simple as possible to get going. However, a number of default settings can be configured for better performance:
### Cache
We recommend [Redis](https://redis.io/) as a fast, persistent cache. Install Redis through your package manager (on Debian or Ubuntu: `sudo apt-get install redis-server`), add `django-redis` to your `requirements.txt`, and enable it as a cache backend:
```
CACHES = {
'default': {
'BACKEND': 'django_redis.cache.RedisCache',
'LOCATION': 'redis://127.0.0.1:6379/dbname',
# for django-redis < 3.8.0, use:
# 'LOCATION': '127.0.0.1:6379',
'OPTIONS': {
'CLIENT_CLASS': 'django_redis.client.DefaultClient',
}
}
}
```
### Caching image renditions
If you define a cache named ‘renditions’ (typically alongside your ‘default’ cache), Wagtail will cache image rendition lookups, which may improve the performance of pages which include many images.
```
CACHES = {
'default': {...},
'renditions': {
'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',
'LOCATION': '127.0.0.1:11211',
'TIMEOUT': 600,
'OPTIONS': {
'MAX_ENTRIES': 1000
}
}
}
```
### Image URLs
If all you need is the URL to an image (such as for use in meta tags or other tag attributes), it is likely more efficient to use the [image serve view](images/image_serve_view#using-images-outside-wagtail) and `{% image_url %}` tag:
```
<meta property="og:image" content="{% image_url page.hero_image width-600 %}" />
```
Rather than finding or creating the rendition in the page request, the image serve view offloads this to a separate view, which only creates the rendition when the user requests the image (or returning an existing rendition if it already exists). This can drastically speed up page loads with many images. This may increase the number of requests handled by Wagtail if you’re using an external storage backend (for example Amazon S3).
Another side benefit is it prevents errors during conversation from causing page errors. If an image is too large for Willow to handle (the size of an image can be constrained with [`WAGTAILIMAGES_MAX_IMAGE_PIXELS`](../reference/settings#wagtailimages-max-image-pixels)), Willow may crash. As the resize is done outside the page load, the image will be missing, but the rest of the page content will remain.
The same can be achieved in Python using [`generate_image_url`](images/image_serve_view#dynamic-image-urls).
### Search
Wagtail has strong support for [Elasticsearch](https://www.elastic.co) - both in the editor interface and for users of your site - but can fall back to a database search if Elasticsearch isn’t present. Elasticsearch is faster and more powerful than the Django ORM for text search, so we recommend installing it or using a hosted service like [Searchly](http://www.searchly.com/).
For details on configuring Wagtail for Elasticsearch, see [Elasticsearch Backend](../topics/search/backends#wagtailsearch-backends-elasticsearch).
### Database
Wagtail is tested on PostgreSQL, SQLite and MySQL. It may work on some third-party database backends as well, but this is not guaranteed. We recommend PostgreSQL for production use.
### Templates
The overhead from reading and compiling templates adds up. Django wraps its default loaders with [cached template loader](https://docs.djangoproject.com/en/stable/ref/templates/api/#django.template.loaders.cached.Loader "(in Django v4.1)") which stores the compiled `Template` in memory and returns it for subsequent requests. The cached loader is automatically enabled when `DEBUG` is `False`. If you are using custom loaders, update your settings to use it:
```
TEMPLATES = [{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'OPTIONS': {
'loaders': [
('django.template.loaders.cached.Loader', [
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
'path.to.custom.Loader',
]),
],
},
}]
```
Public users
------------
### Caching proxy
To support high volumes of traffic with excellent response times, we recommend a caching proxy. Both [Varnish](https://varnish-cache.org/) and [Squid](http://www.squid-cache.org/) have been tested in production. Hosted proxies like [Cloudflare](https://www.cloudflare.com/) should also work well.
Wagtail supports automatic cache invalidation for Varnish/Squid. See [Frontend cache invalidator](../reference/contrib/frontendcache#frontend-cache-purging) for more information.
### Image attributes
For some images, it may be beneficial to lazy load images, so the rest of the page can continue to load. It can be configured site-wide [Adding default attributes to all images](../topics/images#adding-default-attributes-to-images) or per-image [More control over the img tag](../topics/images#image-tag-alt). For more details you can read about the [`loading='lazy'` attribute](https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading#images_and_iframes) and the [`'decoding='async'` attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img#attr-decoding) or this [web.dev article on lazy loading images](https://web.dev/lazy-loading-images/).
This optimisation is already handled for you for images in the admin site.
| programming_docs |
wagtail Deploying Wagtail Deploying Wagtail
=================
On your server
--------------
Wagtail is straightforward to deploy on modern Linux-based distributions, and should run with any of the combinations detailed in Django’s [deployment documentation](https://docs.djangoproject.com/en/stable/howto/deployment/ "(in Django v4.1)"). See the section on <performance> for the non-Python services we recommend.
On Divio Cloud
--------------
[Divio Cloud](https://www.divio.com/) is a Dockerised cloud hosting platform for Python/Django that allows you to launch and deploy Wagtail projects in minutes. With a free account, you can create a Wagtail project. Choose from a:
* [site based on the Wagtail Bakery project](https://www.divio.com/wagtail/), or
* [brand new Wagtail project](https://control.divio.com/control/project/create) (see the [how to get started notes](https://docs.divio.com/en/latest/introduction/wagtail/)).
Divio Cloud also hosts a [live Wagtail Bakery demo](https://www.divio.com/wagtail/) (no account required).
On PythonAnywhere
-----------------
[PythonAnywhere](https://www.pythonanywhere.com/) is a Platform-as-a-Service (PaaS) focused on Python hosting and development. It allows developers to quickly develop, host, and scale applications in a cloud environment. Starting with a free plan they also provide MySQL and PostgreSQL databases as well as very flexible and affordable paid plans, so there’s all you need to host a Wagtail site. To get quickly up and running you may use the [wagtail-pythonanywhere-quickstart](https://github.com/texperience/wagtail-pythonanywhere-quickstart).
On Google Cloud
---------------
[Google Cloud](https://cloud.google.com) is an Infrastructure-as-a-Service (IaaS) that offers multiple managed products, supported by Python client libraries, to help you build, deploy, and monitor your applications. You can deploy Wagtail, or any Django application, in a number of ways, including on [App Engine](https://www.youtube.com/watch?v=uD9PTag2-PQ) or [Cloud Run](https://codelabs.developers.google.com/codelabs/cloud-run-wagtail/#0).
On alwaysdata
-------------
[alwaysdata](https://www.alwaysdata.com/) is a Platform-as-a-Service (PaaS) providing Public and Private Cloud offers. Starting with a free plan they provide MySQL/PostgreSQL databases, emails, free SSL certificates, included backups, etc.
To get your Wagtail application running you may:
* [Install Wagtail from alwaysdata Marketplace](https://www.alwaysdata.com/en/marketplace/wagtail/)
* [Configure a Django application](https://help.alwaysdata.com/en/languages/python/django/)
On other PAASs and IAASs
------------------------
We know of Wagtail sites running on [Heroku](https://spapas.github.io/2014/02/13/wagtail-tutorial/), Digital Ocean and elsewhere. If you have successfully installed Wagtail on your platform or infrastructure, please [contribute](../contributing/index) your notes to this documentation!
Deployment tips
---------------
### Static files
As with all Django projects, static files are only served by the Django application server during development, when running through the `manage.py runserver` command. In production, these need to be handled separately at the web server level. See [Django’s documentation on deploying static files](https://docs.djangoproject.com/en/stable/howto/static-files/deployment/ "(in Django v4.1)").
The JavaScript and CSS files used by the Wagtail admin frequently change between releases of Wagtail - it’s important to avoid serving outdated versions of these files due to browser or server-side caching, as this can cause hard-to-diagnose issues. We recommend enabling [ManifestStaticFilesStorage](https://docs.djangoproject.com/en/stable/ref/contrib/staticfiles/#django.contrib.staticfiles.storage.ManifestStaticFilesStorage "(in Django v4.1)") in the `STATICFILES_STORAGE` setting - this ensures that different versions of files are assigned distinct URLs.
### User Uploaded Files
Wagtail follows [Django’s conventions for managing uploaded files](https://docs.djangoproject.com/en/stable/topics/files/ "(in Django v4.1)"). So by default, Wagtail uses Django’s built-in `FileSystemStorage` class which stores files on your site’s server, in the directory specified by the `MEDIA_ROOT` setting. Alternatively, Wagtail can be configured to store uploaded images and documents on a cloud storage service such as Amazon S3; this is done through the [DEFAULT\_FILE\_STORAGE](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-DEFAULT_FILE_STORAGE) setting in conjunction with an add-on package such as [django-storages](https://django-storages.readthedocs.io/).
When using `FileSystemStorage`, image urls are constructed starting from the path specified by the `MEDIA_URL`. In most cases, you should configure your web server to serve image files directly (without passing through Django/Wagtail). When using one of the cloud storage backends, images urls go directly to the cloud storage file url. If you would like to serve your images from a separate asset server or CDN, you can [configure the image serve view](images/image_serve_view#image-serve-view-redirect-action) to redirect instead.
Document serving is controlled by the [WAGTAILDOCS\_SERVE\_METHOD](../reference/settings#wagtaildocs-serve-method) method. When using `FileSystemStorage`, documents are stored in a `documents` subdirectory within your site’s `MEDIA_ROOT`. If all your documents are public, you can set the `WAGTAILDOCS_SERVE_METHOD` to `direct` and configure your web server to serve the files itself. However, if you use Wagtail’s Collection Privacy settings to restrict access to some or all of your documents, you may or may not want to configure your web server to serve the documents directly. The default setting is `redirect` which allows Wagtail to perform any configured privacy checks before offloading serving the actual document to your web server or CDN. This means that Wagtail constructs document links that pass through Wagtail, but the final url in the user’s browser is served directly by your web server. If a user bookmarks this url, they will be able to access the file without passing through Wagtail’s privacy checks. If this is not acceptable, you may want to set the `WAGTAILDOCS_SERVE_METHOD` to `serve_view` and configure your web server so it will not serve document files itself. If you are serving documents from the cloud and need to enforce privacy settings, you should make sure the documents are not publicly accessible using the cloud service’s file url.
### Cloud storage
Be aware that setting up remote storage will not entirely offload file handling tasks from the application server - some Wagtail functionality requires files to be read back by the application server. In particular, original image files need to be read back whenever a new resized rendition is created, and documents may be configured to be served through a Django view in order to enforce permission checks (see [WAGTAILDOCS\_SERVE\_METHOD](../reference/settings#wagtaildocs-serve-method)).
Note that the django-storages Amazon S3 backends (`storages.backends.s3boto.S3BotoStorage` and `storages.backends.s3boto3.S3Boto3Storage`) **do not correctly handle duplicate filenames** in their default configuration. When using these backends, `AWS_S3_FILE_OVERWRITE` must be set to `False`.
If you are also serving Wagtail’s static files from remote storage (using Django’s [STATICFILES\_STORAGE](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-STATICFILES_STORAGE) setting), you’ll need to ensure that it is configured to serve [CORS HTTP headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS), as current browsers will reject remotely-hosted font files that lack a valid header. For Amazon S3, refer to the documentation [Setting Bucket and Object Access Permissions](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/set-permissions.html), or (for the `storages.backends.s3boto.S3Boto3Storage` backend only) add the following to your Django settings:
```
AWS_S3_OBJECT_PARAMETERS = {
"ACL": "public-read"
}
```
The `ACL` parameter accepts a list of predefined configurations for Amazon S3. For more information, refer to the documentation [Canned ACL](https://docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html#canned-acl).
For Google Cloud Storage, create a `cors.json` configuration:
```
[
{
"origin": ["*"],
"responseHeader": ["Content-Type"],
"method": ["GET"],
"maxAgeSeconds": 3600
}
]
```
Then, apply this CORS configuration to the storage bucket:
```
gsutil cors set cors.json gs://$GS_BUCKET_NAME
```
For other storage services, refer to your provider’s documentation, or the documentation for the Django storage backend library you’re using.
wagtail Internationalisation Internationalisation
====================
* [Multi-language content](#multi-language-content)
+ [Overview](#overview)
+ [Wagtail’s approach to multi-lingual content](#wagtail-s-approach-to-multi-lingual-content)
- [Page structure](#page-structure)
- [How locales and translations are recorded in the database](#how-locales-and-translations-are-recorded-in-the-database)
- [Translated homepages](#translated-homepages)
- [Language detection and routing](#language-detection-and-routing)
- [Locales](#locales)
+ [Configuration](#configuration)
- [Enabling internationalisation](#enabling-internationalisation)
- [Configuring available languages](#configuring-available-languages)
- [Enabling the locale management UI (optional)](#enabling-the-locale-management-ui-optional)
- [Adding a language prefix to URLs](#adding-a-language-prefix-to-urls)
- [User language auto-detection](#user-language-auto-detection)
- [Custom routing/language detection](#custom-routing-language-detection)
+ [Recipes for internationalised sites](#recipes-for-internationalised-sites)
- [Language/region selector](#language-region-selector)
- [API filters for headless sites](#api-filters-for-headless-sites)
- [Translatable snippets](#translatable-snippets)
+ [Translation workflow](#translation-workflow)
- [Wagtail Localize](#wagtail-localize)
* [Alternative internationalisation plugins](#alternative-internationalisation-plugins)
* [Wagtail admin translations](#wagtail-admin-translations)
* [Change Wagtail admin language on a per-user basis](#change-wagtail-admin-language-on-a-per-user-basis)
* [Changing the primary language of your Wagtail installation](#changing-the-primary-language-of-your-wagtail-installation)
Multi-language content
----------------------
### Overview
Out of the box, Wagtail assumes all content will be authored in a single language. This document describes how to configure Wagtail for authoring content in multiple languages.
Note
Wagtail provides the infrastructure for creating and serving content in multiple languages. There are two options for managing translations across different languages in the admin interface: [wagtail.contrib.simple\_translation](../reference/contrib/simple_translation#simple-translation) or the more advanced [wagtail-localize](https://github.com/wagtail/wagtail-localize) (third-party package).
This document only covers the internationalisation of content managed by Wagtail. For information on how to translate static content in template files, JavaScript code, etc, refer to the [Django internationalisation docs](https://docs.djangoproject.com/en/3.1/topics/i18n/translation/). Or, if you are building a headless site, refer to the docs of the frontend framework you are using.
### Wagtail’s approach to multi-lingual content
This section provides an explanation of Wagtail’s internationalisation approach. If you’re in a hurry, you can skip to [Configuration](#configuration).
In summary:
* Wagtail stores content in a separate page tree for each locale
* It has a built-in `Locale` model and all pages are linked to a `Locale` with the `locale` foreign key field
* It records which pages are translations of each other using a shared UUID stored in the `translation_key` field
* It automatically routes requests through translations of the site’s homepage
* It uses Django’s `i18n_patterns` and `LocaleMiddleware` for language detection
#### Page structure
Wagtail stores content in a separate page tree for each locale.
For example, if you have two sites in two locales, then you will see four homepages at the top level of the page hierarchy in the explorer.
This approach has some advantages for the editor experience as well:
* There is no default language for editing, so content can be authored in any language and then translated to any other.
* Translations of a page are separate pages so they can be published at different times.
* Editors can be given permission to edit content in one locale and not others.
#### How locales and translations are recorded in the database
All pages (and any snippets that have translation enabled) have a `locale` and `translation_key` field:
* `locale` is a foreign key to the `Locale` model
* `translation_key` is a UUID that’s used to find translations of a piece of content. Translations of the same page/snippet share the same value in this field
These two fields have a ‘unique together’ constraint so you can’t have more than one translation in the same locale.
#### Translated homepages
When you set up a site in Wagtail, you select the site’s homepage in the ‘root page’ field and all requests to that site’s root URL will be routed to that page.
Multi-lingual sites have a separate homepage for each locale that exist as siblings in the page tree. Wagtail finds the other homepages by looking for translations of the site’s ‘root page’.
This means that to make a site available in another locale, you just need to translate and publish its homepage in that new locale.
If Wagtail can’t find a homepage that matches the user’s language, it will fall back to the page that is selected as the ‘root page’ on the site record, so you can use this field to specify the default language of your site.
#### Language detection and routing
For detecting the user’s language and adding a prefix to the URLs (`/en/`, `/fr-fr/`, for example), Wagtail is designed to work with Django’s built-in internationalisation utilities such as `i18n_patterns` and `LocaleMiddleware`. This means that Wagtail should work seamlessly with any other internationalised Django applications on your site.
#### Locales
The locales that are enabled on a site are recorded in the `Locale` model in `wagtailcore`. This model has just two fields: ID and `language_code` which stores the [BCP-47 language tag](https://en.wikipedia.org/wiki/IETF_language_tag) that represents this locale.
The locale records can be set up with an [optional management UI](#enabling-locale-management) or created in the shell. The possible values of the `language_code` field are controlled by the `WAGTAIL_CONTENT_LANGUAGES` setting.
Note
Read this if you’ve changed `LANGUAGE_CODE` before enabling internationalisation
On initial migration, Wagtail creates a `Locale` record for the language that was set in the `LANGUAGE_CODE` setting at the time the migration was run. All pages will be assigned to this `Locale` when Wagtail’s internationalisation is disabled.
If you have changed the `LANGUAGE_CODE` setting since updating to Wagtail 2.11, you will need to manually update the record in the `Locale` model too before enabling internationalisation, as your existing content will be assigned to the old code.
### Configuration
In this section, we will go through the minimum configuration required to enable content to be authored in multiple languages.
* [Enabling internationalisation](#enabling-internationalisation)
* [Configuring available languages](#configuring-available-languages)
* [Enabling the locale management UI (optional)](#enabling-the-locale-management-ui-optional)
* [Adding a language prefix to URLs](#adding-a-language-prefix-to-urls)
* [User language auto-detection](#user-language-auto-detection)
* [Custom routing/language detection](#custom-routing-language-detection)
#### Enabling internationalisation
To enable internationalisation in both Django and Wagtail, set the following settings to `True`:
```
# my_project/settings.py
USE_I18N = True
WAGTAIL_I18N_ENABLED = True
```
In addition, you might also want to enable Django’s localisation support. This will make dates and numbers display in the user’s local format:
```
# my_project/settings.py
USE_L10N = True
```
#### Configuring available languages
Next we need to configure the available languages. There are two settings for this that are each used for different purposes:
* `LANGUAGES` - This sets which languages are available on the frontend of the site.
* `WAGTAIL_CONTENT_LANGUAGES` - This sets which the languages Wagtail content can be authored in.
You can set both of these settings to the exact same value. For example, to enable English, French, and Spanish:
```
# my_project/settings.py
WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [
('en', "English"),
('fr', "French"),
('es', "Spanish"),
]
```
Note
Whenever `WAGTAIL_CONTENT_LANGUAGES` is changed, the `Locale` model needs to be updated as well to match.
This can either be done with a data migration or with the optional locale management UI described in the next section.
You can also set these to different values. You might want to do this if you want to have some programmatic localisation (like date formatting or currency, for example) but use the same Wagtail content in multiple regions:
```
# my_project/settings.py
LANGUAGES = [
('en-GB', "English (Great Britain)"),
('en-US', "English (United States)"),
('en-CA', "English (Canada)"),
('fr-FR', "French (France)"),
('fr-CA', "French (Canada)"),
]
WAGTAIL_CONTENT_LANGUAGES = [
('en-GB', "English"),
('fr-FR', "French"),
]
```
When configured like this, the site will be available in all the different locales in the first list, but there will only be two language trees in Wagtail.
All the `en-` locales will use the “English” language tree, and the `fr-` locales will use the “French” language tree. The differences between each locale in a language would be programmatic. For example: which date/number format to use, and what currency to display prices in.
#### Enabling the locale management UI (optional)
An optional locale management app exists to allow a Wagtail administrator to set up the locales from the Wagtail admin interface.
To enable it, add `wagtail.locales` into `INSTALLED_APPS`:
```
# my_project/settings.py
INSTALLED_APPS = [
# ...
'wagtail.locales',
# ...
]
```
#### Adding a language prefix to URLs
To allow all of the page trees to be served at the same domain, we need to add a URL prefix for each language.
To implement this, we can use Django’s built-in [i18n\_patterns](https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#language-prefix-in-url-patterns) function, which adds a language prefix to all of the URL patterns passed into it. This activates the language code specified in the URL and Wagtail takes this into account when it decides how to route the request.
In your project’s `urls.py` add Wagtail’s core URLs (and any other URLs you want to be translated) into an `i18n_patterns` block:
```
# /my_project/urls.py
# ...
from django.conf.urls.i18n import i18n_patterns
# Non-translatable URLs
# Note: if you are using the Wagtail API or sitemaps,
# these should not be added to `i18n_patterns` either
urlpatterns = [
path('django-admin/', admin.site.urls),
path('admin/', include(wagtailadmin_urls)),
path('documents/', include(wagtaildocs_urls)),
]
# Translatable URLs
# These will be available under a language code prefix. For example /en/search/
urlpatterns += i18n_patterns(
path('search/', search_views.search, name='search'),
path("", include(wagtail_urls)),
)
```
##### Bypass language prefix for the default language
If you want your default language to have URLs that resolve normally without a language prefix, you can set the `prefix_default_language` parameter of `i18n_patterns` to `False`. For example, if you have your languages configured like this:
```
# myproject/settings.py
# ...
LANGUAGE_CODE = 'en'
WAGTAIL_CONTENT_LANGUAGES = LANGUAGES = [
('en', "English"),
('fr', "French"),
]
# ...
```
And your `urls.py` configured like this:
```
# myproject/urls.py
# ...
# These URLs will be available under a language code prefix only for languages that
# are not set as default in LANGUAGE_CODE.
urlpatterns += i18n_patterns(
path('search/', search_views.search, name='search'),
path("", include(wagtail_urls)),
prefix_default_language=False,
)
```
Your URLs will now be prefixed only for the French version of your website, for example:
```
- /search/
- /fr/search/
```
#### User language auto-detection
After wrapping your URL patterns with `i18n_patterns`, your site will now respond on URL prefixes. But now it won’t respond on the root path.
To fix this, we need to detect the user’s browser language and redirect them to the best language prefix. The recommended approach to do this is with Django’s `LocaleMiddleware`:
```
# my_project/settings.py
MIDDLEWARE = [
# ...
'django.middleware.locale.LocaleMiddleware',
# ...
]
```
#### Custom routing/language detection
You don’t strictly have to use `i18n_patterns` or `LocaleMiddleware` for this and you can write your own logic if you need to.
All Wagtail needs is the language to be activated (using Django’s `django.utils.translation.activate` function) before the `wagtail.views.serve` view is called.
### Recipes for internationalised sites
#### Language/region selector
Perhaps the most important bit of internationalisation-related UI you can add to your site is a selector to allow users to switch between different languages.
If you’re not convinced that you need this, have a look at <https://www.w3.org/International/questions/qa-site-conneg#yyyshortcomings> for some rationale.
##### Basic example
Here is a basic example of how to add links between translations of a page.
This example, however, will only include languages defined in `WAGTAIL_CONTENT_LANGUAGES` and not any extra languages that might be defined in `LANGUAGES`. For more information on what both of these settings mean, see [Configuring available languages](#configuring-available-languages).
If both settings are set to the same value, this example should work well for you, otherwise skip to the next section that has a more complicated example which takes this into account.
```
{# make sure these are at the top of the file #}
{% load i18n wagtailcore_tags %}
{% if page %}
{% for translation in page.get_translations.live %}
{% get_language_info for translation.locale.language_code as lang %}
<a href="{% pageurl translation %}" rel="alternate" hreflang="{{ language_code }}">
{{ lang.name_local }}
</a>
{% endfor %}
{% endif %}
```
Let’s break this down:
```
{% if page %}
...
{% endif %}
```
If this is part of a shared base template it may be used in situations where no page object is available, such as 404 error responses, so check that we have a page before proceeding.
```
{% for translation in page.get_translations.live %}
...
{% endfor %}
```
This `for` block iterates through all published translations of the current page.
```
{% get_language_info for translation.locale.language_code as lang %}
```
This is a Django built-in tag that gets info about the language of the translation. For more information, see [get\_language\_info() in the Django docs](https://docs.djangoproject.com/en/3.1/topics/i18n/translation/#django.utils.translation.get_language_info).
```
<a href="{% pageurl translation %}" rel="alternate" hreflang="{{ language_code }}">
{{ lang.name_local }}
</a>
```
This adds a link to the translation. We use `{{ lang.name_local }}` to display the name of the locale in its own language. We also add `rel` and `hreflang` attributes to the `<a>` tag for SEO.
##### Handling locales that share content
Rather than iterating over pages, this example iterates over all of the configured languages and finds the page for each one. This works better than the [Basic example](#basic-example) above on sites that have extra Django `LANGUAGES` that share the same Wagtail content.
For this example to work, you firstly need to add Django’s [django.template.context\_processors.i18n](https://docs.djangoproject.com/en/3.1/ref/templates/api/#django-template-context-processors-i18n) context processor to your `TEMPLATES` setting:
```
# myproject/settings.py
TEMPLATES = [
{
# ...
'OPTIONS': {
'context_processors': [
# ...
'django.template.context_processors.i18n',
],
},
},
]
```
Now for the example itself:
```
{% for language_code, language_name in LANGUAGES %}
{% get_language_info for language_code as lang %}
{% language language_code %}
<a href="{% pageurl page.localized %}" rel="alternate" hreflang="{{ language_code }}">
{{ lang.name_local }}
</a>
{% endlanguage %}
{% endfor %}
```
Let’s break this down too:
```
{% for language_code, language_name in LANGUAGES %}
...
{% endfor %}
```
This `for` block iterates through all of the configured languages on the site. The `LANGUAGES` variable comes from the `django.template.context_processors.i18n` context processor.
```
{% get_language_info for language_code as lang %}
```
Does exactly the same as the previous example.
```
{% language language_code %}
...
{% endlanguage %}
```
This `language` tag comes from Django’s `i18n` tag library. It changes the active language for just the code contained within it.
```
<a href="{% pageurl page.localized %}" rel="alternate" hreflang="{{ language_code }}">
{{ lang.name_local }}
</a>
```
The only difference with the `<a>` tag here from the `<a>` tag in the previous example is how we’re getting the page’s URL: `{% pageurl page.localized %}`.
All page instances in Wagtail have a `.localized` attribute which fetches the translation of the page in the current active language. This is why we activated the language previously.
Another difference here is that if the same translated page is shared in two locales, Wagtail will generate the correct URL for the page based on the current active locale. This is the key difference between this example and the previous one as the previous one can only get the URL of the page in its default locale.
#### API filters for headless sites
For headless sites, the Wagtail API supports two extra filters for internationalised sites:
* `?locale=` Filters pages by the given locale
* `?translation_of=` Filters pages to only include translations of the given page ID
For more information, see [Special filters for internationalized sites](api/v2/usage#apiv2-i18n-filters).
#### Translatable snippets
You can make a snippet translatable by making it inherit from `wagtail.models.TranslatableMixin`. For example:
```
# myapp/models.py
from django.db import models
from wagtail.models import TranslatableMixin
from wagtail.snippets.models import register_snippet
@register_snippet
class Advert(TranslatableMixin, models.Model):
name = models.CharField(max_length=255)
```
The `TranslatableMixin` model adds the `locale` and `translation_key` fields to the model.
##### Making snippets with existing data translatable
For snippets with existing data, it’s not possible to just add `TranslatableMixin`, make a migration, and run it. This is because the `locale` and `translation_key` fields are both required and `translation_key` needs a unique value for each instance.
To migrate the existing data properly, we firstly need to use `BootstrapTranslatableMixin`, which excludes these constraints, then add a data migration to set the two fields, then switch to `TranslatableMixin`.
This is only needed if there are records in the database. So if the model is empty, you can go straight to adding `TranslatableMixin` and skip this.
###### Step 1: Add `BootstrapTranslatableMixin` to the model
This will add the two fields without any constraints:
```
# myapp/models.py
from django.db import models
from wagtail.models import BootstrapTranslatableMixin
from wagtail.snippets.models import register_snippet
@register_snippet
class Advert(BootstrapTranslatableMixin, models.Model):
name = models.CharField(max_length=255)
# if the model has a Meta class, ensure it inherits from
# BootstrapTranslatableMixin.Meta too
class Meta(BootstrapTranslatableMixin.Meta):
verbose_name = 'adverts'
```
Run `python manage.py makemigrations myapp` to generate the schema migration.
###### Step 2: Create a data migration
Create a data migration with the following command:
```
python manage.py makemigrations myapp --empty
```
This will generate a new empty migration in the app’s `migrations` folder. Edit that migration and add a `BootstrapTranslatableModel` for each model to bootstrap in that app:
```
from django.db import migrations
from wagtail.models import BootstrapTranslatableModel
class Migration(migrations.Migration):
dependencies = [
('myapp', '0002_bootstraptranslations'),
]
# Add one operation for each model to bootstrap here
# Note: Only include models that are in the same app!
operations = [
BootstrapTranslatableModel('myapp.Advert'),
]
```
Repeat this for any other apps that contain a model to be bootstrapped.
###### Step 3: Change `BootstrapTranslatableMixin` to `TranslatableMixin`
Now that we have a migration that fills in the required fields, we can swap out `BootstrapTranslatableMixin` for `TranslatableMixin` that has all the constraints:
```
# myapp/models.py
from wagtail.models import TranslatableMixin # Change this line
@register_snippet
class Advert(TranslatableMixin, models.Model): # Change this line
name = models.CharField(max_length=255)
class Meta(TranslatableMixin.Meta): # Change this line, if present
verbose_name = 'adverts'
```
###### Step 4: Run `makemigrations` to generate schema migrations, then migrate!
Run `makemigrations` to generate the schema migration that adds the constraints into the database, then run `migrate` to run all of the migrations:
```
python manage.py makemigrations myapp
python manage.py migrate
```
When prompted to select a fix for the nullable field ‘locale’ being changed to non-nullable, select the option “Ignore for now” (as this has been handled by the data migration).
### Translation workflow
As mentioned at the beginning, Wagtail does supply `wagtail.contrib.simple_translation`.
The simple\_translation module provides a user interface that allows users to copy pages and translatable snippets into another language.
* Copies are created in the source language (not translated)
* Copies of pages are in draft status
Content editors need to translate the content and publish the pages.
To enable add `"wagtail.contrib.simple_translation"` to `INSTALLED_APPS` and run `python manage.py migrate` to create the `submit_translation` permissions. In the Wagtail admin, go to settings and give some users or groups the “Can submit translations” permission.
Note
Simple Translation is optional. It can be switched out by third-party packages. Like the more advanced [wagtail-localize](https://github.com/wagtail/wagtail-localize).
#### Wagtail Localize
As part of the initial work on implementing internationalisation for Wagtail core, we also created a translation package called `wagtail-localize`. This supports translating pages within Wagtail, using PO files, machine translation, and external integration with translation services.
Github: <https://github.com/wagtail/wagtail-localize>
Alternative internationalisation plugins
----------------------------------------
Before official multi-language support was added into Wagtail, site implementors had to use external plugins. These have not been replaced by Wagtail’s own implementation as they use slightly different approaches, one of them might fit your use case better:
* [Wagtailtrans](https://github.com/wagtail/wagtailtrans)
* [wagtail-modeltranslation](https://github.com/infoportugal/wagtail-modeltranslation)
For a comparison of these options, see AccordBox’s blog post [How to support multi-language in Wagtail CMS](https://www.accordbox.com/blog/how-support-multi-language-wagtail-cms/).
Wagtail admin translations
--------------------------
The Wagtail admin backend has been translated into many different languages. You can find a list of currently available translations on Wagtail’s [Transifex page](https://explore.transifex.com/torchbox/wagtail/). (Note: if you’re using an old version of Wagtail, this page may not accurately reflect what languages you have available).
If your language isn’t listed on that page, you can easily contribute new languages or correct mistakes. Sign up and submit changes to [Transifex](https://explore.transifex.com/torchbox/wagtail/). Translation updates are typically merged into an official release within one month of being submitted.
Change Wagtail admin language on a per-user basis
-------------------------------------------------
Logged-in users can set their preferred language from `/admin/account/`. By default, Wagtail provides a list of languages that have a >= 90% translation coverage. It is possible to override this list via the [WAGTAILADMIN\_PERMITTED\_LANGUAGES](../reference/settings#wagtailadmin-permitted-languages) setting.
In case there is zero or one language permitted, the form will be hidden.
If there is no language selected by the user, the `LANGUAGE_CODE` will be used.
Changing the primary language of your Wagtail installation
----------------------------------------------------------
The default language of Wagtail is `en-us` (American English). You can change this by tweaking a couple of Django settings:
* Make sure [USE\_I18N](https://docs.djangoproject.com/en/stable/ref/settings/#use-i18n) is set to `True`
* Set [LANGUAGE\_CODE](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-LANGUAGE_CODE) to your websites’ primary language
If there is a translation available for your language, the Wagtail admin backend should now be in the language you’ve chosen.
| programming_docs |
wagtail Third-party tutorials Third-party tutorials
=====================
Warning
The following list is a collection of tutorials and development notes from third-party developers. Some of the older links may not apply to the latest Wagtail versions.
* [Guide to integrate Wagtail CRX with a Snipcart storefront](https://github.com/justicepelteir/wagtail_crx_snipcart_storefront) (9 October 2022)
* [Adding featured events to the HomePage with Wagtail 4.0 (video)](https://www.youtube.com/watch?v=opQ_ktAXplo) (6 October 2022)
* [Creating an interactive event budgeting tool within Wagtail](https://dev.to/lb/creating-an-interactive-event-budgeting-tool-within-wagtail-53b3) (4 October 2022)
* [Deploy Django Wagtail to Render](https://stackingtabs.medium.com/deploy-django-wagtail-to-render-7d33c4b09bf9) (23 September 2022)
* [Using a migration to apply permissions to Wagtail snippets](https://sixfeetup.com/blog/a-look-at-using-wagtail-snippets-with-django) (7 September 2022)
* [Deploying a Wagtail site to Fly.io - Part 1 of 5](https://usher.dev/posts/wagtail-on-flyio/part-1/) (30 August 2022)
* [Hosting a Wagtail site on Digital Ocean with CapRover](https://medium.com/@Gidsey/hosting-a-wagtail-site-on-digital-ocean-with-caprover-e71306e8d053) (21 July 2022)
* [Add Heading Blocks with Bookmarks in Wagtail](https://enzedonline.com/en/tech-blog/how-to-add-heading-blocks-with-bookmarks-in-wagtail/) (5 July 2022)
* [Import files into Wagtail](https://cynthiakiser.com/blog/2022/07/02/import-files-into-wagtail.html) (2 July 2022)
* [Adding MapBox Blocks to Wagtail Stream Fields](https://enzedonline.com/en/tech-blog/adding-mapbox-blocks-to-wagtail-stream-fields/) (19 June 2022)
* [5 Tips to Streamline Your Wagtail CMS Development](https://profil-software.com/blog/development/5-tips-to-streamline-your-wagtail-cms-development/) (14 June 2022)
* [Wagtail 3 Upgrade: Per Site Features](https://cynthiakiser.com/blog/2022/06/02/wagtail-3-upgrade-part-2.html) (2 June 2022)
* [Wagtail 3 Upgrade: Per User FieldPanel Permissions](https://cynthiakiser.com/blog/2022/06/01/wagtail-3-upgrade-part-1.html) (1 June 2022)
* [Upgrading to Wagtail 3.0](https://enzedonline.com/en/tech-blog/upgrading-to-wagtail-3-0/) (3 May 2022)
* [Django for E-Commerce: A Developers Guide (with Wagtail CMS Tutorial) - Updated](https://snipcart.com/blog/django-ecommerce-tutorial-wagtail-cms) (21 March 2022)
* [How to install Wagtail on Ubuntu 20.04|22.04](https://nextgentips.com/2022/03/01/how-to-install-wagtail-on-ubuntu-20-0422-04/) (1 March 2022)
* [Building a blog with Wagtail (tutorial part 1 of 2)](https://paulgrajewski.medium.com/wagtail-blog-part-1-ad0df1c59f4) (27 February 2022); [part 2 of 2](https://paulgrajewski.medium.com/wagtail-blog-part-2-3fe698e38983) (6 March 2022)
* [Creating a schematic editor within Wagtail CMS with StimulusJS](https://dev.to/lb/creating-a-schematic-editor-within-the-wagtail-cms-with-stimulusjs-n5j) (20 February 2022)
* [Adding Placeholder Text to Wagtail Forms](https://www.coderedcorp.com/blog/adding-placeholder-text-to-wagtail-forms/) (11 February 2022)
* [Deploying a Wagtail 2.16 website to Heroku](https://dev.to/kalobtaulien/deploying-a-wagtail-216-website-to-heroku-1iki) (9 February 2022)
* [Build an E-Commerce Site with Wagtail CMS, Bootstrap & Django Framework](https://dev.to/paulwababu/build-an-e-commerce-site-with-wagtail-cms-bootstrap-django-framework-4jdb) (7 February 2022)
* [Complex Custom Field Pagination in Django (Wagtail)](https://dev.awhileback.net/hacking-the-django-paginator/) (3 February 2022)
* [How to Connect Wagtail and React](https://stackingtabs.medium.com/how-to-connect-wagtail-and-react-7f6d1adf230) (31 January 2022)
* [Wagtail: Dynamically Adding Admin Menu Items](https://cynthiakiser.com/blog/2022/01/25/dynamically-adding-menu-items-in-the-wagtail-admin.html) (25 January 2022)
* [Headless Wagtail, what are the pain points? (with solutions)](https://tommasoamici.com/blog/headless-wagtail-what-are-the-pain-points) (24 January 2022)
* [A collection of UIKit components that can be used as a Wagtail StreamField block](https://pythonawesome.com/a-collection-of-uikit-components-that-can-be-used-as-a-wagtail-streamfield-block/) (14 January 2022)
* [Introduction to Wagtail CMS](https://blog.reallyroxanna.codes/introduction-to-wagtail-cms) (1 January 2022)
* [How to make Wagtail project have good coding style](https://www.accordbox.com/blog/how-to-make-wagtail-project-have-good-coding-style/) (18 December 2021)
* [Wagtail: The Django newcomer - German](https://cmsstash.de/cms-reviews/wagtail) (13 December 2021)
* [Create a Developer Portfolio with Wagtail Part 10: Dynamic Site Settings](https://engineertodeveloper.com/wagtail-dynamic-site-settings/) (3 December 2021)
* [Dockerize Wagtail CMS for your development environment](https://jortdevreeze.com/en/blog/dockerize-wagtail-cms-for-your-development-environment/) (29 November 2021)
* [How To Add an Email Newsletter to Wagtail](https://engineertodeveloper.com/how-to-add-an-email-newsletter-to-wagtail/) (25 November 2021)
* [Dealing with UNIQUE Fields on a Multi-lingual Site](https://enzedonline.com/en/tech-blog/dealing-with-unique-fields-on-a-multi-lingual-site/) (6 November 2021)
* [General Wagtail Tips & Ticks](https://github.com/spapas/wagtail-faq) (26 October 2021)
* [Branching workflows in Wagtail](https://importthis.tech/wagtail-branching-workflows) (12 October 2021)
* [Wagtail is the best python CMS in our galaxy - Russian](https://habr.com/ru/post/582898/) (12 October 2021)
* [Adding Tasks with a Checklist to Wagtail Workflows](https://dev.to/lb/adding-tasks-with-a-checklist-to-wagtail-workflows-29b8) (22 September 2021)
* [How to create a Zen (Focused) mode for the Wagtail CMS admin](https://dev.to/lb/how-to-create-a-zen-focused-mode-for-the-wagtail-cms-admin-3ipk) (5 September 2021)
* [How to Install Wagtail on Shared Hosting without Root (CPanel)](https://chemicloud.com/kb/article/install-wagtail-without-root-access/) (26 August 2021)
* [Django for E-Commerce: A Developers Guide (with Wagtail CMS Tutorial)](https://dev.to/realguillaume/django-for-e-commerce-a-developers-guide-with-wagtail-cms-tutorial-57on) (26 August 2021)
* [How to create a Kanban (Trello style) view of your ModelAdmin data in Wagtail](https://dev.to/lb/how-to-create-a-kanban-trello-style-view-of-your-modeladmin-data-in-wagtail-20eg) (20 August 2021)
* [eBook: The Definitive Guide to Next.js and Wagtail](https://www.accordbox.com/blog/ebook-the-definitive-guide-to-nextjs-and-wagtail/) (19 August 2021)
* [How to build an interactive guide for users in the Wagtail CMS admin](https://dev.to/lb/how-to-build-an-interactive-guide-for-users-in-the-wagtail-cms-admin-2dcp) (19 August 2021)
* [Add Custom User Model (with custom fields like phone no, profile picture) to django or wagtail sites](https://medium.com/@altaf008bd/wagtail-add-custom-fields-including-image-to-custom-user-model-1c976ddbc24) (16 August 2021)
* [File size limits in Nginx and animated GIF support](https://www.meagenvoss.com/blog/random-wagtail-thing-i-learned-file-size-limits-in-nginx-and-animated-gif-support/) (14 August 2021)
* [Deploying Wagtail site on Digital Ocean](https://www.craftplustech.com/blog/deploying-wagtail-site-on-digital-ocean/) (11 August 2021)
* [Multi-language Wagtail websites with XLIFF](https://www.fourdigits.nl/blog/multi-language-wagtail-websites-with-xliff/) (21 June 2021)
* [Add & Configure Mail in Django (or Wagtail) using Sendgrid](https://mpettersson.com/blog/how-to-add-and-configure-a-mail-service-in-django-or-wagtail/) (28 May 2021)
* [Advanced Django Development: How to build a professional CMS for any business? (3 part tutorial)](https://medium.com/engineerx/advanced-django-development-how-to-build-a-professional-cms-for-any-business-part-1-9859cb5b4d24) (2 April 2021)
* [Matomo Analytics with WagtailCMS](https://experiencednovice.dev/blog/matomo-analytics-with-wagtailcms/) (31 March 2021)
* [Dockerizing a Wagtail App](https://www.accordbox.com/blog/dockerizing-wagtail-app/) (16 March 2021)
* [Deploying Wagtail on CentOS8 with MariaDB/Nginx/Gunicorn](https://experiencednovice.dev/blog/deploying-wagtail-on-centos8/) (7 March 2021)
* [How to add a List of Related Fields to a Page](https://learningtofly.dev/blog/wagtail-how-to-add-a-list-of-related-fields-to-a-page) (6 March 2021)
* [Wagtail - `get_absolute_url`, without domain](https://kuttler.eu/code/wagtail-get_absolute_url-without-domain/) (3 March 2021)
* [How To Alternate Blocks in Your Django & Wagtail Templates](https://www.coderedcorp.com/blog/how-to-alternate-blocks-in-your-templates/) (19 February 2021)
* [Build a Blog With Wagtail CMS (second version)](https://www.accordbox.com/blog/build-blog-wagtail-cms-second-version-available/) (13 January 2021)
* [Migrate your Wagtail Website from wagtailtrans to the new wagtail-localize](https://www.cnc.io/en/blog/wagtailtrans-to-wagtail-localize-migration) (10 January 2021)
* [How to Use the Wagtail CMS for Django: An Overview](https://steelkiwi.com/blog/how-to-use-the-wagtail-cms-for-django-an-overview/) (21 December 2020)
* [Wagtail `modeladmin` and a dynamic panels list](https://kuttler.eu/code/wagtail-modeladmin-and-dynamic-panels-list/) (14 December 2020)
* [Install and Deploy Wagtail CMS on pythonanywhere.com](https://www.theinsidetrade.com/blog/install-and-deploy-wagtail-cms-pythonanywherecom/) (14 December 2020)
* [Overriding the admin CSS in Wagtail](https://www.yellowduck.be/posts/overriding-the-admin-css-in-wagtail/) (4 December 2020)
* [Migrating your Wagtail site to a different database engine](https://www.yellowduck.be/posts/migrating-your-wagtail-site-to-a-different-database-engine/) (3 December 2020)
* [Wagtail for Django Devs: Create a Developer Portfolio](https://dev.to/brian101co/wagtail-for-django-devs-create-a-developer-portfolio-5e75) (30 November 2020)
* [Create a Developer Portfolio with Wagtail Tutorial Series](https://engineertodeveloper.com/category/wagtail/) (11 November 2020)
* [Wagtail Instagram New oEmbed API](https://www.codista.com/en/blog/wagtail-instagram-new-oembed-api/) (5 November 2020)
* [Image upload in wagtail forms](https://dev.to/lb/image-uploads-in-wagtail-forms-39pl) (21 October 2020)
* [Adding a timeline of your wagtail Posts](https://spapas.github.io/2020/09/18/wagtail-add-posts-timeline/) (18 September 2020)
* [How to create amazing SSR website with Wagtail 2 + Vue 3](https://dev.to/robert197/how-to-create-amazing-ssr-website-with-wagtail-2-vue-3-463j) (1 September 2020)
* [Migrate Wagtail Application Database from SQLite to PostgreSQL](https://medium.com/@ochieng.grace/migrate-wagtail-application-database-from-sqlite-to-postgresql-32f705f2f5f4) (5 June 2020)
* [How to Build Scalable Websites with Wagtail and Nuxt](https://devs-group.medium.com/why-our-websites-stay-ahead-c608e3f4bea4) (14 May 2020)
* [Wagtail multi-language and internationalization](https://dev.to/codista_/wagtail-multi-language-and-internationalization-2gkf) (8 April 2020)
* [Wagtail SEO Guide](https://www.accordbox.com/blog/wagtail-seo-guide/) (30 March 2020)
* [Adding a latest-changes list to your Wagtail site](https://spapas.github.io/2020/03/27/wagtail-add-latest-changes/) (27 March 2020)
* [How to support multi-language in Wagtail CMS](https://www.accordbox.com/blog/how-support-multi-language-wagtail-cms/) (22 February 2020)
* [Deploying my Wagtail blog to Digital Ocean](https://rosederwelt.com/deploying-my-wagtail-blog-digital-ocean-pt-1/) Part 1 of a 2 part series (29 January 2020)
* [How to Create and Manage Menus of Wagtail application](https://www.accordbox.com/blog/wagtail-tutorial-12-how-create-and-manage-menus-wagtail-application/) - An updated overview of implementing menus (22 February 2020)
* [Adding a React component in Wagtail Admin](https://dev.to/lb/adding-a-react-component-in-wagtail-admin-3e) - Shows how to render an interactive timeline of published Pages (30 December 2019)
* [Wagtail API - how to customise the detail URL](https://dev.to/wagtail/wagtail-api-how-to-customize-the-detail-url-2j3l) (19 December 2020)
* [How to Add Django Models to the Wagtail Admin](https://dev.to/revsys/how-to-add-django-models-to-the-wagtail-admin-1mdi) (27 August 2019)
* [How do I Wagtail](https://foundation.mozilla.org/en/docs/how-do-i-wagtail/) - An Editor’s Guide for Mozilla’s usage of Wagtail (25 April 2019)
* [Learn Wagtail](https://learnwagtail.com/) - Regular video tutorials about all aspects of Wagtail (1 March 2019)
* [How to add buttons to ModelAdmin Index View in Wagtail CMS](https://timonweb.com/tutorials/how-to-add-buttons-to-modeladmin-index-view-in-wagtail-cms/) (23 January 2019)
* [Wagtail Tutorial Series](https://www.accordbox.com/blog/wagtail-tutorials/) (20 January 2019)
* [How to Deploy Wagtail to Google App Engine PaaS (Video)](https://www.youtube.com/watch?v=uD9PTag2-PQ) (18 December 2018)
* [How To Prevent Users From Creating Pages by Page Type](https://timonweb.com/tutorials/prevent-users-from-creating-certain-page-types-in-wagtail-cms/) (25 October 2018)
* [How to Deploy Wagtail to Jelastic PaaS](https://jelastic.com/blog/deploy-wagtail-python-cms/) (11 October 2018)
* [Basic Introduction to Setting Up Wagtail](https://medium.com/nonstopio/wagtail-an-open-source-cms-cec6b93706da) (15 August 2018)
* [E-Commerce for Django developers (with Wagtail shop tutorial)](https://snipcart.com/blog/django-ecommerce-tutorial-wagtail-cms) (5 July 2018)
* [Supporting StreamFields, Snippets and Images in a Wagtail GraphQL API](https://wagtail.org/blog/graphql-with-streamfield/) (14 June 2018)
* [Wagtail and GraphQL](https://jossingram.wordpress.com/2018/04/19/wagtail-and-graphql/) (19 April 2018)
* [Wagtail and Azure storage blob containers](https://jossingram.wordpress.com/2017/11/29/wagtail-and-azure-storage-blob-containers/) (29 November 2017)
* [Building TwilioQuest with Twilio Sync, Django [incl. Wagtail], and Vue.js](https://www.twilio.com/blog/2017/11/building-twilioquest-with-twilio-sync-django-and-vue-js.html) (6 November 2017)
* [Upgrading from Wagtail 1.0 to Wagtail 1.11](https://www.caktusgroup.com/blog/2017/07/19/upgrading-wagtail/) (19 July 2017)
* [Wagtail-Multilingual: a simple project to demonstrate how multilingual is implemented](https://github.com/cristovao-alves/Wagtail-Multilingual) (31 January 2017)
* [Wagtail: 2 Steps for Adding Pages Outside of the CMS](https://www.caktusgroup.com/blog/2016/02/15/wagtail-2-steps-adding-pages-outside-cms/) (15 February 2016)
* [Adding a Twitter Widget for Wagtail’s new StreamField](https://jossingram.wordpress.com/2015/04/02/adding-a-twitter-widget-for-wagtails-new-streamfield/) (2 April 2015)
* [Working With Wagtail: Menus](https://www.tivix.com/blog/working-with-wagtail-menus/) (22 January 2015)
* [Upgrading Wagtail to use Django 1.7 locally using vagrant](https://jossingram.wordpress.com/2014/12/10/upgrading-wagtail-to-use-django-1-7-locally-using-vagrant/) (10 December 2014)
* [Wagtail redirect page. Can link to page, URL and document](https://gist.github.com/alej0varas/e7e334643ceab6e65744) (24 September 2014)
* [Outputting JSON for a model with properties and db fields in Wagtail/Django](https://jossingram.wordpress.com/2014/09/24/outputing-json-for-a-model-with-properties-and-db-fields-in-wagtaildjango/) (24 September 2014)
* [Bi-lingual website using Wagtail CMS](https://jossingram.wordpress.com/2014/09/17/bi-lingual-website-using-wagtail-cms/) (17 September 2014)
* [Wagtail CMS – Lesser known features](https://jossingram.wordpress.com/2014/09/12/wagtail-cms-lesser-known-features/) (12 September 2014)
* [Wagtail notes: stateful on/off hallo.js plugins](https://www.coactivate.org/projects/ejucovy/blog/2014/08/09/wagtail-notes-stateful-onoff-hallojs-plugins/) (9 August 2014)
* [Add some blockquote buttons to Wagtail CMS’ WYSIWYG Editor](https://jossingram.wordpress.com/2014/07/24/add-some-blockquote-buttons-to-wagtail-cms-wysiwyg-editor/) (24 July 2014)
* [Adding Bread Crumbs to the front end in Wagtail CMS](https://jossingram.wordpress.com/2014/07/01/adding-bread-crumbs-to-the-front-end-in-wagtail-cms/) (1 July 2014)
* [Extending hallo.js using Wagtail hooks](https://gist.github.com/jeffrey-hearn/502d0914fa4a930f08ac) (9 July 2014)
* [Wagtail notes: custom tabs per page type](https://www.coactivate.org/projects/ejucovy/blog/2014/05/10/wagtail-notes-custom-tabs-per-page-type/) (10 May 2014)
* [Wagtail notes: managing redirects as pages](https://www.coactivate.org/projects/ejucovy/blog/2014/05/10/wagtail-notes-managing-redirects-as-pages/) (10 May 2014)
* [Wagtail notes: dynamic templates per page](https://www.coactivate.org/projects/ejucovy/blog/2014/05/10/wagtail-notes-dynamic-templates-per-page/) (10 May 2014)
* [Wagtail notes: type-constrained PageChooserPanel](https://www.coactivate.org/projects/ejucovy/blog/2014/05/09/wagtail-notes-type-constrained-pagechooserpanel/) (9 May 2014)
You can also find more resources from the community on [Awesome Wagtail](https://github.com/springload/awesome-wagtail).
Tip
---
We are working on a collection of Wagtail tutorials and best practices. Please tweet [@WagtailCMS](https://twitter.com/WagtailCMS) or [contact us directly](mailto:hello%40wagtail.org) to share your Wagtail HOWTOs, development notes or site launches.
wagtail Testing your Wagtail site Testing your Wagtail site
=========================
Wagtail comes with some utilities that simplify writing tests for your site.
WagtailPageTestCase
-------------------
***class* wagtail.test.utils.WagtailPageTestCase** `WagtailPageTestCase` extends `django.test.TestCase`, adding a few new `assert` methods. You should extend this class to make use of its methods:
```
from wagtail.test.utils import WagtailPageTestCase
from myapp.models import MyPage
class MyPageTests(WagtailPageTestCase):
def test_can_create_a_page(self):
...
```
**assertPageIsRoutable(*page, route\_path=”/”, msg=None*)**
Asserts that `page` can be routed to without raising a `Http404` error.
For page types with multiple routes, you can use `route_path` to specify an alternate route to test.
This assertion is great for getting coverage on custom routing logic for page types. Here is an example:
```
from wagtail.test.utils import WagtailPageTestCase
from myapp.models import EventListPage
class EventListPageRoutabilityTests(WagtailPageTestCase):
@classmethod
def setUpTestData(cls):
# create page(s) for testing
...
def test_default_route(self):
self.assertPageIsRoutable(self.page)
def test_year_archive_route(self):
# NOTE: Despite this page type raising a 404 when no events exist for
# the specified year, routing should still be successful
self.assertPageIsRoutable(self.page, "archive/year/1984/")
```
**assertPageIsRenderable(*page, route\_path=”/”, query\_data=None, post\_data=None, user=None, accept\_404=False, accept\_redirect=False, msg=None*)**
Asserts that `page` can be rendered without raising a fatal error.
For page types with multiple routes, you can use `route_path` to specify a partial path to be added to the page’s regular `url`.
When `post_data` is provided, the test makes a `POST` request with `post_data` in the request body. Otherwise, a `GET` request is made.
When supplied, `query_data` is always converted to a querystring and added to the request URL.
When `user` is provided, the test is conducted with them as the active user.
By default, the assertion will fail if the request to the page URL results in a 301, 302 or 404 HTTP response. If you are testing a page/route where a 404 response is expected, you can use `accept_404=True` to indicate this, and the assertion will pass when encountering a 404 response. Likewise, if you are testing a page/route where a redirect response is expected, you can use `accept_redirect=True` to indicate this, and the assertion will pass when encountering 301 or 302 response.
This assertion is great for getting coverage on custom rendering logic for page types. Here is an example:
```
def test_default_route_rendering(self):
self.assertPageIsRenderable(self.page)
def test_year_archive_route_with_zero_matches(self):
# NOTE: Should raise a 404 when no events exist for the specified year
self.assertPageIsRenderable(self.page, "archive/year/1984/", accept_404=True)
def test_month_archive_route_with_zero_matches(self):
# NOTE: Should redirect to year-specific view when no events exist for the specified month
self.assertPageIsRenderable(self.page, "archive/year/1984/07/", accept_redirect=True)
```
**assertPageIsEditable(*page, post\_data=None, user=None, msg=None*)**
Asserts that the page edit view works for `page` without raising a fatal error.
When `user` is provided, the test is conducted with them as the active user. Otherwise, a superuser is created and used for the test.
After a successful `GET` request, a `POST` request is made with field data in the request body. If `post_data` is provided, that will be used for this purpose. If not, this data will be extracted from the `GET` response HTML.
This assertion is great for getting coverage on custom fields, panel configuration and custom validation logic. Here is an example:
```
def test_editability(self):
self.assertPageIsEditable(self.page)
def test_editability_on_post(self):
self.assertPageIsEditable(
self.page,
post_data={
"title": "Fabulous events",
"slug": "events",
"show_featured": True,
"show_expired": False,
"action-publish": "",
}
)
```
**assertPageIsPreviewable(*page, mode=””, post\_data=None, user=None, msg=None*)**
Asserts that the page preview view can be loaded for `page` without raising a fatal error.
For page types that support different preview modes, you can use `mode` to specify the preview mode to be tested.
When `user` is provided, the test is conducted with them as the active user. Otherwise, a superuser is created and used for the test.
To load the preview, the test client needs to make a `POST` request including all required field data in the request body. If `post_data` is provided, that will be used for this purpose. If not, the method will attempt to extract this data from the page edit view.
This assertion is great for getting coverage on custom preview modes, or getting reassurance that custom rendering logic is compatible with Wagtail’s preview mode. Here is an example:
```
def test_general_previewability(self):
self.assertPageIsPreviewable(self.page)
def test_archive_previewability(self):
self.assertPageIsPreviewable(self.page, mode="year-archive")
```
**assertCanCreateAt(*parent\_model, child\_model, msg=None*)** Assert a particular child Page type can be created under a parent Page type. `parent_model` and `child_model` should be the Page classes being tested.
```
def test_can_create_under_home_page(self):
# You can create a ContentPage under a HomePage
self.assertCanCreateAt(HomePage, ContentPage)
```
**assertCanNotCreateAt(*parent\_model, child\_model, msg=None*)** Assert a particular child Page type can not be created under a parent Page type. `parent_model` and `child_model` should be the Page classes being tested.
```
def test_cant_create_under_event_page(self):
# You can not create a ContentPage under an EventPage
self.assertCanNotCreateAt(EventPage, ContentPage)
```
**assertCanCreate(*parent, child\_model, data, msg=None*)** Assert that a child of the given Page type can be created under the parent, using the supplied POST data.
`parent` should be a Page instance, and `child_model` should be a Page subclass. `data` should be a dict that will be POSTed at the Wagtail admin Page creation method.
```
from wagtail.test.utils.form_data import nested_form_data, streamfield
def test_can_create_content_page(self):
# Get the HomePage
root_page = HomePage.objects.get(pk=2)
# Assert that a ContentPage can be made here, with this POST data
self.assertCanCreate(root_page, ContentPage, nested_form_data({
'title': 'About us',
'body': streamfield([
('text', 'Lorem ipsum dolor sit amet'),
])
}))
```
See [Form data helpers](#form-data-test-helpers) for a set of functions useful for constructing POST data.
**assertAllowedParentPageTypes(*child\_model, parent\_models, msg=None*)** Test that the only page types that `child_model` can be created under are `parent_models`.
The list of allowed parent models may differ from those set in `Page.parent_page_types`, if the parent models have set `Page.subpage_types`.
```
def test_content_page_parent_pages(self):
# A ContentPage can only be created under a HomePage
# or another ContentPage
self.assertAllowedParentPageTypes(
ContentPage, {HomePage, ContentPage})
# An EventPage can only be created under an EventIndex
self.assertAllowedParentPageTypes(
EventPage, {EventIndex})
```
**assertAllowedSubpageTypes(*parent\_model, child\_models, msg=None*)** Test that the only page types that can be created under `parent_model` are `child_models`.
The list of allowed child models may differ from those set in `Page.subpage_types`, if the child models have set `Page.parent_page_types`.
```
def test_content_page_subpages(self):
# A ContentPage can only have other ContentPage children
self.assertAllowedSubpageTypes(
ContentPage, {ContentPage})
# A HomePage can have ContentPage and EventIndex children
self.assertAllowedSubpageTypes(
HomePage, {ContentPage, EventIndex})
```
Form data helpers
-----------------
The `assertCanCreate` method requires page data to be passed in the same format that the page edit form would submit. For complex page types, it can be difficult to construct this data structure by hand; the `wagtail.test.utils.form_data` module provides a set of helper functions to assist with this.
Fixtures
--------
### Using `dumpdata`
Creating [fixtures](https://docs.djangoproject.com/en/stable/howto/initial-data/ "(in Django v4.1)") for tests is best done by creating content in a development environment, and using Django’s [dumpdata](https://docs.djangoproject.com/en/stable/ref/django-admin/#django-admin-dumpdata) command.
Note that by default `dumpdata` will represent `content_type` by the primary key; this may cause consistency issues when adding / removing models, as content types are populated separately from fixtures. To prevent this, use the `--natural-foreign` switch, which represents content types by `["app", "model"]` instead.
### Manual modification
You could modify the dumped fixtures manually, or even write them all by hand. Here are a few things to be wary of.
#### Custom Page models
When creating customised Page models in fixtures, you will need to add both a `wagtailcore.page` entry, and one for your custom Page model.
Let’s say you have a `website` module which defines a `Homepage(Page)` class. You could create such a homepage in a fixture with:
```
[
{
"model": "wagtailcore.page",
"pk": 3,
"fields": {
"title": "My Customer's Homepage",
"content_type": ["website", "homepage"],
"depth": 2
}
},
{
"model": "website.homepage",
"pk": 3,
"fields": {}
}
]
```
#### Treebeard fields
Filling in the `path` / `numchild` / `depth` fields is necessary in order for tree operations like `get_parent()` to work correctly. `url_path` is another field that can cause errors in some uncommon cases if it isn’t filled in.
The [Treebeard docs](https://django-treebeard.readthedocs.io/en/latest/mp_tree.html) might help in understanding how this works.
| programming_docs |
wagtail How to build a site with AMP support How to build a site with AMP support
====================================
This recipe document describes a method for creating an [AMP](https://amp.dev/) version of a Wagtail site and hosting it separately to the rest of the site on a URL prefix. It also describes how to make Wagtail render images with the `<amp-img>` tag when a user is visiting a page on the AMP version of the site.
Overview
--------
In the next section, we will add a new URL entry that points at Wagtail’s internal `serve()` view which will have the effect of rendering the whole site again under the `/amp` prefix.
Then, we will add some utilities that will allow us to track whether the current request is in the `/amp` prefixed version of the site without needing a request object.
After that, we will add a template context processor to allow us to check from within templates which version of the site is being rendered.
Then, finally, we will modify the behaviour of the `{% image %}` tag to make it render `<amp-img>` tags when rendering the AMP version of the site.
Creating the second page tree
-----------------------------
We can render the whole site at a different prefix by duplicating the Wagtail URL in the project `urls.py` file and giving it a prefix. This must be before the default URL from Wagtail, or it will try to find `/amp` as a page:
```
# <project>/urls.py
urlpatterns += [
# Add this line just before the default ``include(wagtail_urls)`` line
path('amp/', include(wagtail_urls)),
path('', include(wagtail_urls)),
]
```
If you now open `http://localhost:8000/amp/` in your browser, you should see the homepage.
Making pages aware of “AMP mode”
--------------------------------
All the pages will now render under the `/amp` prefix, but right now there isn’t any difference between the AMP version and the normal version.
To make changes, we need to add a way to detect which URL was used to render the page. To do this, we will have to wrap Wagtail’s `serve()` view and set a thread-local to indicate to all downstream code that AMP mode is active.
Note
Why a thread-local?
(feel free to skip this part if you’re not interested)
Modifying the `request` object would be the most common way to do this. However, the image tag rendering is performed in a part of Wagtail that does not have access to the request.
Thread-locals are global variables that can have a different value for each running thread. As each thread only handles one request at a time, we can use it as a way to pass around data that is specific to that request without having to pass the request object everywhere.
Django uses thread-locals internally to track the currently active language for the request.
Python implements thread-local data through the `threading.local` class, but as of Django 3.x, multiple requests can be handled in a single thread and so thread-locals will no longer be unique to a single request. Django therefore provides `asgiref.Local` as a drop-in replacement.
Now let’s create that thread-local and some utility functions to interact with it, save this module as `amp_utils.py` in an app in your project:
```
# <app>/amp_utils.py
from contextlib import contextmanager
from asgiref.local import Local
_amp_mode_active = Local()
@contextmanager
def activate_amp_mode():
"""
A context manager used to activate AMP mode
"""
_amp_mode_active.value = True
try:
yield
finally:
del _amp_mode_active.value
def amp_mode_active():
"""
Returns True if AMP mode is currently active
"""
return hasattr(_amp_mode_active, 'value')
```
This module defines two functions:
* `activate_amp_mode` is a context manager which can be invoked using Python’s `with` syntax. In the body of the `with` statement, AMP mode would be active.
* `amp_mode_active` is a function that returns `True` when AMP mode is active.
Next, we need to define a view that wraps Wagtail’s builtin `serve` view and invokes the `activate_amp_mode` context manager:
```
# <app>/amp_views.py
from django.template.response import SimpleTemplateResponse
from wagtail.views import serve as wagtail_serve
from .amp_utils import activate_amp_mode
def serve(request, path):
with activate_amp_mode():
response = wagtail_serve(request, path)
# Render template responses now while AMP mode is still active
if isinstance(response, SimpleTemplateResponse):
response.render()
return response
```
Then we need to create a `amp_urls.py` file in the same app:
```
# <app>/amp_urls.py
from django.urls import re_path
from wagtail.urls import serve_pattern
from . import amp_views
urlpatterns = [
re_path(serve_pattern, amp_views.serve, name='wagtail_amp_serve')
]
```
Finally, we need to update the project’s main `urls.py` to use this new URLs file for the `/amp` prefix:
```
# <project>/urls.py
from myapp import amp_urls as wagtail_amp_urls
urlpatterns += [
# Change this line to point at your amp_urls instead of Wagtail's urls
path('amp/', include(wagtail_amp_urls)),
re_path(r'', include(wagtail_urls)),
]
```
After this, there shouldn’t be any noticeable difference to the AMP version of the site.
Write a template context processor so that AMP state can be checked in templates
--------------------------------------------------------------------------------
This is optional, but worth doing so we can confirm that everything is working so far.
Add a `amp_context_processors.py` file into your app that contains the following:
```
# <app>/amp_context_processors.py
from .amp_utils import amp_mode_active
def amp(request):
return {
'amp_mode_active': amp_mode_active(),
}
```
Now add the path to this context processor to the `['OPTIONS']['context_processors']` key of the `TEMPLATES` setting:
```
# Either <project>/settings.py or <project>/settings/base.py
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
# Add this after other context processors
'myapp.amp_context_processors.amp',
],
},
},
]
```
You should now be able to use the `amp_mode_active` variable in templates. For example:
```
{% if amp_mode_active %}
AMP MODE IS ACTIVE!
{% endif %}
```
Using a different page template when AMP mode is active
-------------------------------------------------------
You’re probably not going to want to use the same templates on the AMP site as you do on the normal web site. Let’s add some logic in to make Wagtail use a separate template whenever a page is served with AMP enabled.
We can use a mixin, which allows us to re-use the logic on different page types. Add the following to the bottom of the amp\_utils.py file that you created earlier:
```
# <app>/amp_utils.py
import os.path
...
class PageAMPTemplateMixin:
@property
def amp_template(self):
# Get the default template name and insert `_amp` before the extension
name, ext = os.path.splitext(self.template)
return name + '_amp' + ext
def get_template(self, request):
if amp_mode_active():
return self.amp_template
return super().get_template(request)
```
Now add this mixin to any page model, for example:
```
# <app>/models.py
from .amp_utils import PageAMPTemplateMixin
class MyPageModel(PageAMPTemplateMixin, Page):
...
```
When AMP mode is active, the template at `app_label/mypagemodel_amp.html` will be used instead of the default one.
If you have a different naming convention, you can override the `amp_template` attribute on the model. For example:
```
# <app>/models.py
from .amp_utils import PageAMPTemplateMixin
class MyPageModel(PageAMPTemplateMixin, Page):
amp_template = 'my_custom_amp_template.html'
```
Overriding the `{% image %}` tag to output `<amp-img>` tags
-----------------------------------------------------------
Finally, let’s change Wagtail’s `{% image %}` tag, so it renders an `<amp-img>` tags when rendering pages with AMP enabled. We’ll make the change on the `Rendition` model itself so it applies to both images rendered with the `{% image %}` tag and images rendered in rich text fields as well.
Doing this with a [Custom image model](images/custom_image_model#custom-image-model) is easier, as you can override the `img_tag` method on your custom `Rendition` model to return a different tag.
For example:
```
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe
from wagtail.images.models import AbstractRendition
...
class CustomRendition(AbstractRendition):
def img_tag(self, extra_attributes):
attrs = self.attrs_dict.copy()
attrs.update(extra_attributes)
if amp_mode_active():
return mark_safe('<amp-img{}>'.format(flatatt(attrs)))
else:
return mark_safe('<img{}>'.format(flatatt(attrs)))
...
```
Without a custom image model, you will have to monkey-patch the builtin `Rendition` model. Add this anywhere in your project where it would be imported on start:
```
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe
from wagtail.images.models import Rendition
def img_tag(rendition, extra_attributes={}):
"""
Replacement implementation for Rendition.img_tag
When AMP mode is on, this returns an <amp-img> tag instead of an <img> tag
"""
attrs = rendition.attrs_dict.copy()
attrs.update(extra_attributes)
if amp_mode_active():
return mark_safe('<amp-img{}>'.format(flatatt(attrs)))
else:
return mark_safe('<img{}>'.format(flatatt(attrs)))
Rendition.img_tag = img_tag
```
wagtail Embedded content Embedded content
================
Wagtail supports generating embed code from URLs to content on external providers such as Youtube or Twitter. By default, Wagtail will fetch the embed code directly from the relevant provider’s site using the oEmbed protocol.
Wagtail has a built-in list of the most common providers and this list can be changed [with a setting](#customising-embed-providers). Wagtail also supports fetching embed code using [Embedly](#embedly) and [custom embed finders](#custom-embed-finders).
Embedding content on your site
------------------------------
Wagtail’s embeds module should work straight out of the box for most providers. You can use any of the following methods to call the module:
### Rich text
Wagtail’s default rich text editor has a “media” icon that allows embeds to be placed into rich text. You don’t have to do anything to enable this; just make sure the rich text field’s content is being passed through the `|richtext` filter in the template as this is what calls the embeds module to fetch and nest the embed code.
###
`EmbedBlock` StreamField block type
The `EmbedBlock` block type allows embeds to be placed into a `StreamField`.
The `max_width` and `max_height` arguments are sent to the provider when fetching the embed code.
For example:
```
from wagtail.embeds.blocks import EmbedBlock
class MyStreamField(blocks.StreamBlock):
...
embed = EmbedBlock(max_width=800, max_height=400)
```
###
`{% embed %}` tag
Syntax: `{% embed <url> [max_width=<max width>] %}`
You can nest embeds into a template by passing the URL and an optional `max_width` argument to the `{% embed %}` tag.
The `max_width` argument is sent to the provider when fetching the embed code.
```
{% load wagtailembeds_tags %}
{# Embed a YouTube video #}
{% embed 'https://www.youtube.com/watch?v=Ffu-2jEdLPw' %}
{# This tag can also take the URL from a variable #}
{% embed page.video_url %}
```
### From Python
You can also call the internal `get_embed` function that takes a URL string and returns an `Embed` object (see model documentation below). This also takes a `max_width` keyword argument that is sent to the provider when fetching the embed code.
```
from wagtail.embeds.embeds import get_embed
from wagtail.embeds.exceptions import EmbedException
try:
embed = get_embed('https://www.youtube.com/watch?v=Ffu-2jEdLPw')
print(embed.html)
except EmbedException:
# Cannot find embed
pass
```
Configuring embed “finders”
---------------------------
Embed finders are the modules within Wagtail that are responsible for producing embed code from a URL.
Embed finders are configured using the `WAGTAILEMBEDS_FINDERS` setting. This is a list of finder configurations that are each run in order until one of them successfully returns an embed:
The default configuration is:
```
WAGTAILEMBEDS_FINDERS = [
{
'class': 'wagtail.embeds.finders.oembed'
}
]
```
### oEmbed (default)
The default embed finder fetches the embed code directly from the content provider using the oEmbed protocol. Wagtail has a built-in list of providers which are all enabled by default. You can find that provider list at the following link:
<https://github.com/wagtail/wagtail/blob/main/wagtail/embeds/oembed_providers.py>
#### Customising the provider list
You can limit which providers may be used by specifying the list of providers in the finder configuration.
For example, this configuration will only allow content to be nested from Vimeo and Youtube. It also adds a custom provider:
```
from wagtail.embeds.oembed_providers import youtube, vimeo
# Add a custom provider
# Your custom provider must support oEmbed for this to work. You should be
# able to find these details in the provider's documentation.
# - 'endpoint' is the URL of the oEmbed endpoint that Wagtail will call
# - 'urls' specifies which patterns
my_custom_provider = {
'endpoint': 'https://customvideosite.com/oembed',
'urls': [
'^http(?:s)?://(?:www\\.)?customvideosite\\.com/[^#?/]+/videos/.+$',
]
}
WAGTAILEMBEDS_FINDERS = [
{
'class': 'wagtail.embeds.finders.oembed',
'providers': [youtube, vimeo, my_custom_provider],
}
]
```
#### Customising an individual provider
Multiple finders can be chained together. This can be used for customising the configuration for one provider without affecting the others.
For example, this is how you can instruct Youtube to return videos in HTTPS (which must be done explicitly for YouTube):
```
from wagtail.embeds.oembed_providers import youtube
WAGTAILEMBEDS_FINDERS = [
# Fetches YouTube videos but puts ``?scheme=https`` in the GET parameters
# when calling YouTube's oEmbed endpoint
{
'class': 'wagtail.embeds.finders.oembed',
'providers': [youtube],
'options': {'scheme': 'https'}
},
# Handles all other oEmbed providers the default way
{
'class': 'wagtail.embeds.finders.oembed',
}
]
```
#### How Wagtail uses multiple finders
If multiple providers can handle a URL (for example, a YouTube video was requested using the configuration above), the topmost finder is chosen to perform the request.
Wagtail will not try to run any other finder, even if the chosen one didn’t return an embed.
### Facebook and Instagram
As of October 2020, Facebook deprecated their public oEmbed APIs. If you would like to embed Facebook or Instagram posts in your site, you will need to use the new authenticated APIs. This requires you to set up a Facebook Developer Account and create a Facebook App that includes the *oEmbed Product*. Instructions for creating the necessary app are in the requirements sections of the [Facebook](https://developers.facebook.com/docs/plugins/oembed) and [Instagram](https://developers.facebook.com/docs/instagram/oembed) documentation.
As of June 2021, the *oEmbed Product* has been replaced with the *oEmbed Read* feature. In order to embed Facebook and Instagram posts your app must activate the *oEmbed Read* feature. Furthermore the app must be reviewed and accepted by Facebook. You can find the announcement in the [API changelog](https://developers.facebook.com/docs/graph-api/changelog/version11.0/#oembed).
Apps that activated the oEmbed Product before June 8, 2021 need to activate the oEmbed Read feature and review their app before September 7, 2021.
Once you have your app access tokens (App ID and App Secret), add the Facebook and/or Instagram finders to your `WAGTAILEMBEDS_FINDERS` setting and configure them with the App ID and App Secret from your app:
```
WAGTAILEMBEDS_FINDERS = [
{
'class': 'wagtail.embeds.finders.facebook',
'app_id': 'YOUR FACEBOOK APP_ID HERE',
'app_secret': 'YOUR FACEBOOK APP_SECRET HERE',
},
{
'class': 'wagtail.embeds.finders.instagram',
'app_id': 'YOUR INSTAGRAM APP_ID HERE',
'app_secret': 'YOUR INSTAGRAM APP_SECRET HERE',
},
# Handles all other oEmbed providers the default way
{
'class': 'wagtail.embeds.finders.oembed',
}
]
```
By default, Facebook and Instagram embeds include some JavaScript that is necessary to fully render the embed. In certain cases, this might not be something you want - for example, if you have multiple Facebook embeds, this would result in multiple script tags. By passing `'omitscript': True` in the configuration, you can indicate that these script tags should be omitted from the embed HTML. Note that you will then have to take care of loading this script yourself.
### Embed.ly
[Embed.ly](https://embed.ly) is a paid-for service that can also provide embeds for sites that do not implement the oEmbed protocol.
They also provide some helpful features such as giving embeds a consistent look and a common video playback API which is useful if your site allows videos to be hosted on different providers and you need to implement custom controls for them.
Wagtail has built in support for fetching embeds from Embed.ly. To use it, first pip install the `Embedly` [python package](https://pypi.org/project/Embedly/).
Now add an embed finder to your `WAGTAILEMBEDS_FINDERS` setting that uses the `wagtail.embeds.finders.oembed` class and pass it your API key:
```
WAGTAILEMBEDS_FINDERS = [
{
'class': 'wagtail.embeds.finders.embedly',
'key': 'YOUR EMBED.LY KEY HERE'
}
]
```
### Custom embed finder classes
For complete control, you can create a custom finder class.
Here’s a stub finder class that could be used as a skeleton; please read the docstrings for details of what each method does:
```
from wagtail.embeds.finders.base import EmbedFinder
class ExampleFinder(EmbedFinder):
def __init__(self, **options):
pass
def accept(self, url):
"""
Returns True if this finder knows how to fetch an embed for the URL.
This should not have any side effects (no requests to external servers)
"""
pass
def find_embed(self, url, max_width=None):
"""
Takes a URL and max width and returns a dictionary of information about the
content to be used for embedding it on the site.
This is the part that may make requests to external APIs.
"""
# TODO: Perform the request
return {
'title': "Title of the content",
'author_name': "Author name",
'provider_name': "Provider name (such as YouTube, Vimeo, etc)",
'type': "Either 'photo', 'video', 'link' or 'rich'",
'thumbnail_url': "URL to thumbnail image",
'width': width_in_pixels,
'height': height_in_pixels,
'html': "<h2>The Embed HTML</h2>",
}
```
Once you’ve implemented all of those methods, you just need to add it to your `WAGTAILEMBEDS_FINDERS` setting:
```
WAGTAILEMBEDS_FINDERS = [
{
'class': 'path.to.your.finder.class.here',
# Any other options will be passed as kwargs to the __init__ method
}
]
```
The `Embed` model
-----------------
### Deleting embeds
As long as your embeds configuration is not broken, deleting items in the `Embed` model should be perfectly safe to do. Wagtail will automatically repopulate the records that are being used on the site.
You may want to do this if you’ve changed from oEmbed to Embedly or vice-versa as the embed code they generate may be slightly different and lead to inconsistency on your site.
| programming_docs |
wagtail Private pages Private pages
=============
Users with publish permission on a page can set it to be private by clicking the ‘Privacy’ control in the top right corner of the page explorer or editing interface. This sets a restriction on who is allowed to view the page and its sub-pages. Several different kinds of restriction are available:
* **Accessible to logged-in users:** The user must log in to view the page. All user accounts are granted access, regardless of permission level.
* **Accessible with the following password:** The user must enter the given password to view the page. This is appropriate for situations where you want to share a page with a trusted group of people, but giving them individual user accounts would be overkill. The same password is shared between all users, and this works independently of any user accounts that exist on the site.
* **Accessible to users in specific groups:** The user must be logged in, and a member of one or more of the specified groups, in order to view the page.
Similarly, documents can be made private by placing them in a collection with appropriate privacy settings (see: [Image / document permissions](../topics/permissions#image-document-permissions)).
Private pages and documents work on Wagtail out of the box - the site implementer does not need to do anything to set them up. However, the default “log in” and “password required” forms are only bare-bones HTML pages, and site implementers may wish to replace them with a page customised to their site design.
Setting up a login page
-----------------------
The basic login page can be customised by setting `WAGTAIL_FRONTEND_LOGIN_TEMPLATE` to the path of a template you wish to use:
```
WAGTAIL_FRONTEND_LOGIN_TEMPLATE = 'myapp/login.html'
```
Wagtail uses Django’s standard `django.contrib.auth.views.LoginView` view here, and so the context variables available on the template are as detailed in [Django’s login view documentation](https://docs.djangoproject.com/en/stable/topics/auth/default/#django.contrib.auth.views.LoginView "(in Django v4.1)").
If the stock Django login view is not suitable - for example, you wish to use an external authentication system, or you are integrating Wagtail into an existing Django site that already has a working login view - you can specify the URL of the login view via the `WAGTAIL_FRONTEND_LOGIN_URL` setting:
```
WAGTAIL_FRONTEND_LOGIN_URL = '/accounts/login/'
```
To integrate Wagtail into a Django site with an existing login mechanism, setting `WAGTAIL_FRONTEND_LOGIN_URL = LOGIN_URL` will usually be sufficient.
Setting up a global “password required” page
--------------------------------------------
By setting `PASSWORD_REQUIRED_TEMPLATE` in your Django settings file, you can specify the path of a template which will be used for all “password required” forms on the site (except for page types that specifically override it - see below):
```
PASSWORD_REQUIRED_TEMPLATE = 'myapp/password_required.html'
```
This template will receive the same set of context variables that the blocked page would pass to its own template via `get_context()` - including `page` to refer to the page object itself - plus the following additional variables (which override any of the page’s own context variables of the same name):
* **form** - A Django form object for the password prompt; this will contain a field named `password` as its only visible field. A number of hidden fields may also be present, so the page must loop over `form.hidden_fields` if not using one of Django’s rendering helpers such as `form.as_p`.
* **action\_url** - The URL that the password form should be submitted to, as a POST request.
A basic template suitable for use as `PASSWORD_REQUIRED_TEMPLATE` might look like this:
```
<!DOCTYPE HTML>
<html>
<head>
<title>Password required</title>
</head>
<body>
<h1>Password required</h1>
<p>You need a password to access this page.</p>
<form action="{{ action_url }}" method="POST">
{% csrf_token %}
{{ form.non_field_errors }}
<div>
{{ form.password.errors }}
{{ form.password.label_tag }}
{{ form.password }}
</div>
{% for field in form.hidden_fields %}
{{ field }}
{% endfor %}
<input type="submit" value="Continue" />
</form>
</body>
</html>
```
Password restrictions on documents use a separate template, specified through the setting `DOCUMENT_PASSWORD_REQUIRED_TEMPLATE`; this template also receives the context variables `form` and `action_url` as described above.
Setting a “password required” page for a specific page type
-----------------------------------------------------------
The attribute `password_required_template` can be defined on a page model to use a custom template for the “password required” view, for that page type only. For example, if a site had a page type for displaying embedded videos along with a description, it might choose to use a custom “password required” template that displays the video description as usual, but shows the password form in place of the video embed.
```
class VideoPage(Page):
...
password_required_template = 'video/password_required.html'
```
wagtail Title generation on upload Title generation on upload
==========================
When uploading an image, Wagtail takes the filename, removes the file extension, and populates the title field. This section is about how to customise this filename to title conversion.
The filename to title conversion is used on the single file widget, multiple upload widget, and within chooser modals.
You can also customise this [same behaviour for documents](../documents/title_generation_on_upload).
You can customise the resolved value of this title using a JavaScript [event listener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) which will listen to the `'wagtail:images-upload'` event.
The simplest way to add JavaScript to the editor is via the [`insert_global_admin_js` hook](../../reference/hooks#insert-global-admin-js), however any JavaScript that adds the event listener will work.
DOM Event
---------
The event name to listen for is `'wagtail:images-upload'`. It will be dispatched on the image upload `form`. The event’s `detail` attribute will contain:
* `data` - An object which includes the `title` to be used. It is the filename with the extension removed.
* `maxTitleLength` - An integer (or `null`) which is the maximum length of the `Image` model title field.
* `filename` - The original filename without the extension removed.
To modify the generated `Image` title, access and update `event.detail.data.title`, no return value is needed.
For single image uploads, the custom event will only run if the title does not already have a value so that we do not overwrite whatever the user has typed.
You can prevent the default behaviour by calling `event.preventDefault()`. For the single upload page or modals, this will not pre-fill any value into the title. For multiple upload, this will avoid any title submission and use the filename title only (with file extension) as a title is required to save the image.
The event will ‘bubble’ up so that you can simply add a global `document` listener to capture all of these events, or you can scope your listener or handler logic as needed to ensure you only adjust titles in some specific scenarios.
See MDN for more information about [custom JavasScript events](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events).
Code Examples
-------------
### Removing any url unsafe characters from the title
```
# wagtail_hooks.py
from django.utils.safestring import mark_safe
from wagtail import hooks
@hooks.register("insert_global_admin_js")
def get_global_admin_js():
return mark_safe(
"""
<script>
window.addEventListener('DOMContentLoaded', function () {
document.addEventListener('wagtail:images-upload', function(event) {
var newTitle = (event.detail.data.title || '').replace(/[^a-zA-Z0-9\s-]/g, "");
event.detail.data.title = newTitle;
});
});
</script>
"""
)
```
### Changing generated titles on the page editor only to remove dashes/underscores
Using the [`insert_editor_js` hook](../../reference/hooks#insert-editor-js) instead so that this script will not run on the `Image` upload page, only on page editors.
```
# wagtail_hooks.py
from django.utils.safestring import mark_safe
from wagtail import hooks
@hooks.register("insert_editor_js")
def get_global_admin_js():
return mark_safe(
"""
<script>
window.addEventListener('DOMContentLoaded', function () {
document.addEventListener('wagtail:images-upload', function(event) {
// replace dashes/underscores with a space
var newTitle = (event.detail.data.title || '').replace(/(\s|_|-)/g, " ");
event.detail.data.title = newTitle;
});
});
</script>
"""
)
```
### Stopping pre-filling of title based on filename
```
# wagtail_hooks.py
from django.utils.safestring import mark_safe
from wagtail import hooks
@hooks.register("insert_global_admin_js")
def get_global_admin_js():
return mark_safe(
"""
<script>
window.addEventListener('DOMContentLoaded', function () {
document.addEventListener('wagtail:images-upload', function(event) {
// will stop title pre-fill on single file uploads
// will set the multiple upload title to the filename (with extension)
event.preventDefault();
});
});
</script>
"""
)
```
wagtail Dynamic image serve view Dynamic image serve view
========================
In most cases, developers wanting to generate image renditions in Python should use the `get_rendition()` method. See [Generating renditions in Python](renditions#image-renditions).
If you need to be able to generate image versions for an *external* system such as a blog or mobile app, Wagtail provides a view for dynamically generating renditions of images by calling a unique URL.
The view takes an image id, filter spec and security signature in the URL. If these parameters are valid, it serves an image file matching that criteria.
Like the `{% image %}` tag, the rendition is generated on the first call and subsequent calls are served from a cache.
Setup
-----
Add an entry for the view into your URLs configuration:
```
from wagtail.images.views.serve import ServeView
urlpatterns = [
...
re_path(r'^images/([^/]*)/(\d*)/([^/]*)/[^/]*$', ServeView.as_view(), name='wagtailimages_serve'),
...
# Ensure that the wagtailimages_serve line appears above the default Wagtail page serving route
re_path(r'', include(wagtail_urls)),
]
```
Usage
-----
### Image URL generator UI
When the dynamic serve view is enabled, an image URL generator in the admin interface becomes available automatically. This can be accessed through the edit page of any image by clicking the “URL generator” button on the right hand side.
This interface allows editors to generate URLs to cropped versions of the image.
### Generating dynamic image URLs in Python
Dynamic image URLs can also be generated using Python code and served to a client over an API or used directly in the template.
One advantage of using dynamic image URLs in the template is that they do not block the initial response while rendering like the `{% image %}` tag does.
The `generate_image_url` function in `wagtail.images.views.serve` is a convenience method to generate a dynamic image URL.
Here’s an example of this being used in a view:
```
def display_image(request, image_id):
image = get_object_or_404(Image, id=image_id)
return render(request, 'display_image.html', {
'image_url': generate_image_url(image, 'fill-100x100')
})
```
Image operations can be chained by joining them with a `|` character:
```
return render(request, 'display_image.html', {
'image_url': generate_image_url(image, 'fill-100x100|jpegquality-40')
})
```
In your templates:
```
{% load wagtailimages_tags %}
...
<!-- Get the url for the image scaled to a width of 400 pixels: -->
{% image_url page.photo "width-400" %}
<!-- Again, but this time as a square thumbnail: -->
{% image_url page.photo "fill-100x100|jpegquality-40" %}
<!-- This time using our custom image serve view: -->
{% image_url page.photo "width-400" "mycustomview_serve" %}
```
You can pass an optional view name that will be used to serve the image through. The default is `wagtailimages_serve`
Advanced configuration
----------------------
### Making the view redirect instead of serve
By default, the view will serve the image file directly. This behaviour can be changed to a 301 redirect instead which may be useful if you host your images externally.
To enable this, pass `action='redirect'` into the `ServeView.as_view()` method in your urls configuration:
```
from wagtail.images.views.serve import ServeView
urlpatterns = [
...
re_path(r'^images/([^/]*)/(\d*)/([^/]*)/[^/]*$', ServeView.as_view(action='redirect'), name='wagtailimages_serve'),
]
```
Integration with django-sendfile
--------------------------------
[django-sendfile](https://github.com/johnsensible/django-sendfile) offloads the job of transferring the image data to the web server instead of serving it directly from the Django application. This could greatly reduce server load in situations where your site has many images being downloaded but you’re unable to use a [Caching proxy](../performance#caching-proxy) or a CDN.
You firstly need to install and configure django-sendfile and configure your web server to use it. If you haven’t done this already, please refer to the [installation docs](https://github.com/johnsensible/django-sendfile#django-sendfile).
To serve images with django-sendfile, you can use the `SendFileView` class. This view can be used out of the box:
```
from wagtail.images.views.serve import SendFileView
urlpatterns = [
...
re_path(r'^images/([^/]*)/(\d*)/([^/]*)/[^/]*$', SendFileView.as_view(), name='wagtailimages_serve'),
]
```
You can customise it to override the backend defined in the `SENDFILE_BACKEND` setting:
```
from wagtail.images.views.serve import SendFileView
from project.sendfile_backends import MyCustomBackend
class MySendFileView(SendFileView):
backend = MyCustomBackend
```
You can also customise it to serve private files. For example, if the only need is to be authenticated (Django >= 1.9):
```
from django.contrib.auth.mixins import LoginRequiredMixin
from wagtail.images.views.serve import SendFileView
class PrivateSendFileView(LoginRequiredMixin, SendFileView):
raise_exception = True
```
wagtail Changing rich text representation Changing rich text representation
=================================
The HTML representation of an image in rich text can be customised - for example, to display captions or custom fields.
To do this requires subclassing `Format` (see [Image Formats in the Rich Text Editor](../customisation/page_editing_interface#rich-text-image-formats)), and overriding its `image_to_html` method.
You may then register formats of your subclass using `register_image_format` as usual.
```
# image_formats.py
from wagtail.images.formats import Format, register_image_format
class SubclassedImageFormat(Format):
def image_to_html(self, image, alt_text, extra_attributes=None):
custom_html = # the custom HTML representation of your image here
# in Format, the image's rendition.img_tag(extra_attributes) is used to generate the HTML
# representation
return custom_html
register_image_format(
SubclassedImageFormat('subclassed_format', 'Subclassed Format', classnames, filter_spec)
)
```
As an example, let’s say you want the alt text to be displayed as a caption for the image as well:
```
# image_formats.py
from django.utils.html import format_html
from wagtail.images.formats import Format, register_image_format
class CaptionedImageFormat(Format):
def image_to_html(self, image, alt_text, extra_attributes=None):
default_html = super().image_to_html(image, alt_text, extra_attributes)
return format_html("{}<figcaption>{}</figcaption>", default_html, alt_text)
register_image_format(
CaptionedImageFormat('captioned_fullwidth', 'Full width captioned', 'bodytext-image', 'width-750')
)
```
Note
Any custom HTML image features will not be displayed in the Draftail editor, only on the published page.
wagtail Images Images
======
* [Generating renditions in Python](renditions)
+ [Prefetching image renditions](renditions#prefetching-image-renditions)
+ [Model methods involved in rendition generation](renditions#model-methods-involved-in-rendition-generation)
* [Animated GIF support](animated_gifs)
* [Image file formats](image_file_formats)
+ [Using the picture element](image_file_formats#using-the-picture-element)
* [Custom image models](custom_image_model)
+ [Migrating from the builtin image model](custom_image_model#migrating-from-the-builtin-image-model)
+ [Referring to the image model](custom_image_model#module-wagtail.images)
* [Changing rich text representation](changing_rich_text_representation)
* [Feature Detection](feature_detection)
+ [Installation](feature_detection#installation)
+ [Cropping](feature_detection#cropping)
+ [Switching on feature detection in Wagtail](feature_detection#switching-on-feature-detection-in-wagtail)
+ [Manually running feature detection](feature_detection#manually-running-feature-detection)
* [Dynamic image serve view](image_serve_view)
+ [Setup](image_serve_view#setup)
+ [Usage](image_serve_view#usage)
+ [Advanced configuration](image_serve_view#advanced-configuration)
+ [Integration with django-sendfile](image_serve_view#integration-with-django-sendfile)
* [Focal points](focal_points)
+ [Setting the `background-position` inline style based on the focal point](focal_points#setting-the-background-position-inline-style-based-on-the-focal-point)
+ [Accessing the focal point in templates](focal_points#accessing-the-focal-point-in-templates)
* [Title generation on upload](title_generation_on_upload)
+ [DOM Event](title_generation_on_upload#dom-event)
+ [Code Examples](title_generation_on_upload#code-examples)
wagtail Custom image models Custom image models
===================
The `Image` model can be customised, allowing additional fields to be added to images.
To do this, you need to add two models to your project:
* The image model itself that inherits from `wagtail.images.models.AbstractImage`. This is where you would add your additional fields
* The renditions model that inherits from `wagtail.images.models.AbstractRendition`. This is used to store renditions for the new model.
Here’s an example:
```
# models.py
from django.db import models
from wagtail.images.models import Image, AbstractImage, AbstractRendition
class CustomImage(AbstractImage):
# Add any extra fields to image here
# To add a caption field:
# caption = models.CharField(max_length=255, blank=True)
admin_form_fields = Image.admin_form_fields + (
# Then add the field names here to make them appear in the form:
# 'caption',
)
class CustomRendition(AbstractRendition):
image = models.ForeignKey(CustomImage, on_delete=models.CASCADE, related_name='renditions')
class Meta:
unique_together = (
('image', 'filter_spec', 'focal_point_key'),
)
```
Then set the `WAGTAILIMAGES_IMAGE_MODEL` setting to point to it:
```
WAGTAILIMAGES_IMAGE_MODEL = 'images.CustomImage'
```
Migrating from the builtin image model
--------------------------------------
When changing an existing site to use a custom image model, no images will be copied to the new model automatically. Copying old images to the new model would need to be done manually with a [data migration](https://docs.djangoproject.com/en/stable/topics/migrations/#data-migrations "(in Django v4.1)").
Any templates that reference the builtin image model will still continue to work as before but would need to be updated in order to see any new images.
Referring to the image model
----------------------------
| programming_docs |
wagtail Animated GIF support Animated GIF support
====================
Pillow, Wagtail’s default image library, doesn’t support animated GIFs.
To get animated GIF support, you will have to [install Wand](https://docs.wand-py.org/en/0.6.7/guide/install.html). Wand is a binding to ImageMagick so make sure that has been installed as well.
When installed, Wagtail will automatically use Wand for resizing GIF files but continue to resize other images with Pillow.
wagtail Focal points Focal points
============
Focal points are used to indicate to Wagtail the area of an image that contains the subject. This is used by the `fill` filter to focus the cropping on the subject, and avoid cropping into it.
Focal points can be defined manually by a Wagtail user, or automatically by using face or feature detection.
Setting the `background-position` inline style based on the focal point
-----------------------------------------------------------------------
When using a Wagtail image as the background of an element, you can use the `.background_position_style` attribute on the rendition to position the rendition based on the focal point in the image:
```
{% image page.image width-1024 as image %}
<div style="background-image: url('{{ image.url }}'); {{ image.background_position_style }}">
</div>
```
Accessing the focal point in templates
--------------------------------------
You can access the focal point in the template by accessing the `.focal_point` attribute of a rendition:
```
{% load wagtailimages %}
{% image myimage width-800 as myrendition %}
<img
src="{{ myrendition.url }}"
alt="{{ myimage.title }}"
{% if myrendition.focal_point %}
data-focus-x="{{ myrendition.focal_point.centroid.x }}"
data-focus-y="{{ myrendition.focal_point.centroid.y }}"
data-focus-width="{{ myrendition.focal_point.width }}"
data-focus-height="{{ myrendition.focal_point.height }}"
{% endif %}
/>
```
wagtail Feature Detection Feature Detection
=================
Wagtail has the ability to automatically detect faces and features inside your images and crop the images to those features.
Feature detection uses third-party tools to detect faces/features in an image when the image is uploaded. The detected features are stored internally as a focal point in the `focal_point_{x, y, width, height}` fields on the `Image` model. These fields are used by the `fill` image filter when an image is rendered in a template to crop the image.
Installation
------------
Two third-party tools are known to work with Wagtail: One based on [OpenCV](https://opencv.org/) for general feature detection and one based on [Rustface](https://github.com/torchbox/rustface-py/) for face detection.
### OpenCV on Debian/Ubuntu
Feature detection requires [OpenCV](https://opencv.org/) which can be a bit tricky to install as it’s not currently pip-installable.
There is more than one way to install these components, but in each case you will need to test that both OpenCV itself *and* the Python interface have been correctly installed.
#### Install `opencv-python`
[opencv-python](https://pypi.org/project/opencv-python/) is available on PyPI. It includes a Python interface to OpenCV, as well as the statically-built OpenCV binaries themselves.
To install:
```
pip install opencv-python
```
Depending on what else is installed on your system, this may be all that is required. On lighter-weight Linux systems, you may need to identify and install missing system libraries (for example, a slim version of Debian Stretch requires `libsm6 libxrender1 libxext6` to be installed with `apt`).
#### Install a system-level package
A system-level package can take care of all of the required components. Check what is available for your operating system. For example, [python-opencv](https://packages.debian.org/stretch/python-opencv) is available for Debian; it installs OpenCV itself, and sets up Python bindings.
However, it may make incorrect assumptions about how you’re using Python (for example, which version you’re using) - test as described below.
#### Testing the installation
Test the installation:
```
python3
>>> import cv2
```
An error such as:
```
ImportError: libSM.so.6: cannot open shared object file: No such file or directory
```
indicates that a required system library (in this case `libsm6`) has not been installed.
On the other hand,
```
ModuleNotFoundError: No module named 'cv2'
```
means that the Python components have not been set up correctly in your Python environment.
If you don’t get an import error, installation has probably been successful.
### Rustface
[Rustface](https://github.com/torchbox/rustface-py/) is Python library with prebuilt wheel files provided for Linux and macOS. Although implemented in Rust it is pip-installable:
```
pip install wheel
pip install rustface
```
#### Registering with Willow
Rustface provides a plug-in that needs to be registered with [Willow](https://github.com/wagtail/Willow).
This should be done somewhere that gets run on application startup:
```
from willow.registry import registry
import rustface.willow
registry.register_plugin(rustface.willow)
```
For example, in an app’s [AppConfig.ready](https://docs.djangoproject.com/en/2.2/ref/applications/#django.apps.AppConfig.ready).
Cropping
--------
The face detection algorithm produces a focal area that is tightly cropped to the face rather than the whole head.
For images with a single face this can be okay in some cases (thumbnails for example), it might be overly tight for “headshots”. Image renditions can encompass more of the head by reducing the crop percentage (`-c<percentage>`), at the end of the resize-rule, down to as low as 0%:
```
{% image page.photo fill-200x200-c0 %}
```
Switching on feature detection in Wagtail
-----------------------------------------
Once installed, you need to set the `WAGTAILIMAGES_FEATURE_DETECTION_ENABLED` setting to `True` to automatically detect faces/features whenever a new image is uploaded in to Wagtail or when an image without a focal point is saved (this is done via a pre-save signal handler):
```
# settings.py
WAGTAILIMAGES_FEATURE_DETECTION_ENABLED = True
```
Manually running feature detection
----------------------------------
If you already have images in your Wagtail site and would like to run feature detection on them, or you want to apply feature detection selectively when the `WAGTAILIMAGES_FEATURE_DETECTION_ENABLED` is set to `False` you can run it manually using the `get_suggested_focal_point()` method on the `Image` model.
For example, you can manually run feature detection on all images by running the following code in the python shell:
```
from wagtail.images import get_image_model
Image = get_image_model()
for image in Image.objects.all():
if not image.has_focal_point():
image.set_focal_point(image.get_suggested_focal_point())
image.save()
```
wagtail Generating renditions in Python Generating renditions in Python
===============================
Rendered versions of original images generated by the Wagtail `{% image %}` template tag are called “renditions”, and are stored as new image files in the site’s `[media]/images` directory on the first invocation.
Image renditions can also be generated dynamically from Python via the native `get_rendition()` method, for example:
```
newimage = myimage.get_rendition('fill-300x150|jpegquality-60')
```
If `myimage` had a filename of `foo.jpg`, a new rendition of the image file called `foo.fill-300x150.jpegquality-60.jpg` would be generated and saved into the site’s `[media]/images` directory. Argument options are identical to the `{% image %}` template tag’s filter spec, and should be separated with `|`.
The generated `Rendition` object will have properties specific to that version of the image, such as `url`, `width` and `height`, so something like this could be used in an API generator, for example:
```
url = myimage.get_rendition('fill-300x186|jpegquality-60').url
```
Properties belonging to the original image from which the generated Rendition was created, such as `title`, can be accessed through the Rendition’s `image` property:
```
>>> newimage.image.title
'Blue Sky'
>>> newimage.image.is_landscape()
True
```
See also: [How to use images in templates](../../topics/images#image-tag)
Prefetching image renditions
----------------------------
When using a queryset to render a list of images or objects with images, you can prefetch the renditions needed with a single additional query. For long lists of items, or where multiple renditions are used for each item, this can provide a significant boost to performance.
New in version 4.0: The `prefetch_renditions` method is only applicable in Wagtail versions 4.0 and above.
### Image QuerySets
When working with an Image QuerySet, you can make use of Wagtail’s built-in `prefetch_renditions` queryset method to prefetch the renditions needed.
For example, say you were rendering a list of all the images uploaded by a certain user:
```
def get_images_uploaded_by_user(user):
return ImageModel.objects.filter(uploaded_by_user=user)
```
The above can be modified slightly to prefetch the renditions of the images returned:
```
def get_images_uploaded_by_user(user)::
return ImageModel.objects.filter(uploaded_by_user=user).prefetch_renditions()
```
The above will prefetch all renditions even if we may not need them.
If images in your project tend to have very large numbers of renditions, and you know in advance the ones you need, you might want to consider specifying a set of filters to the `prefetch_renditions` method and only select the renditions you need for rendering. For example:
```
def get_images_uploaded_by_user(user):
# Only specify the renditions required for rendering
return ImageModel.objects.filter(uploaded_by_user=user).prefetch_renditions(
"fill-700x586", "min-600x400", "max-940x680"
)
```
### Non Image Querysets
If you’re working with a non Image Model, you can make use of Django’s built-in `prefetch_related()` queryset method to prefetch renditions.
For example, say you were rendering a list of events (with thumbnail images for each). Your code might look something like this:
```
def get_events():
return EventPage.objects.live().select_related("listing_image")
```
The above can be modified slightly to prefetch the renditions for listing images:
```
def get_events():
return EventPage.objects.live().select_related("listing_image").prefetch_related("listing_image__renditions")
```
If you know in advance the renditions you’ll need, you can filter the renditions queryset to use:
```
from django.db.models import Prefetch
from wagtail.images import get_image_model
def get_events():
Image = get_image_model()
filters = ["fill-300x186", "fill-600x400", "fill-940x680"]
# `Prefetch` is used to fetch only the required renditions
prefetch_images_and_renditions = Prefetch(
"listing_image",
queryset=Image.objects.prefetch_renditions(*filters)
)
return EventPage.objects.live().prefetch_related(prefetch_images_and_renditions)
```
Model methods involved in rendition generation
----------------------------------------------
New in version 3.0: The following method references are only applicable to Wagtail versions 3.0 and above.
The following `AbstractImage` model methods are involved in finding and generating a renditions. If using a custom image model, you can customise the behaviour of either of these methods by overriding them on your model:
wagtail Image file formats Image file formats
==================
Using the picture element
-------------------------
The [picture element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) can be used with the `format-<type>` image operation to specify different image formats and let the browser choose the one it prefers. For example:
```
{% load wagtailimages_tags %}
<picture>
{% image myimage width-1000 format-webp as image_webp %}
<source srcset="{{ image_webp.url }}" type="image/webp">
{% image myimage width-1000 format-png as image_png %}
<source srcset="{{ image_png.url }}" type="image/png">
{% image myimage width-1000 format-png %}
</picture>
```
### Customising output formats
By default all `bmp` and `webp` images are converted to the `png` format when no image output format is given.
The default conversion mapping can be changed by setting the `WAGTAILIMAGES_FORMAT_CONVERSIONS` to a dictionary which maps the input type to an output type.
For example:
```
WAGTAILIMAGES_FORMAT_CONVERSIONS = {
'bmp': 'jpeg',
'webp': 'webp',
}
```
will convert `bmp` images to `jpeg` and disable the default `webp` to `png` conversion.
wagtail Customising admin templates Customising admin templates
===========================
In your projects with Wagtail, you may wish to replace elements such as the Wagtail logo within the admin interface with your own branding. This can be done through Django’s template inheritance mechanism.
You need to create a `templates/wagtailadmin/` folder within one of your apps - this may be an existing one, or a new one created for this purpose, for example, `dashboard`. This app must be registered in `INSTALLED_APPS` before `wagtail.admin`:
```
INSTALLED_APPS = (
# ...
'dashboard',
'wagtail',
'wagtail.admin',
# ...
)
```
Custom branding
---------------
The template blocks that are available to customise the branding in the admin interface are as follows:
### `branding_logo`
To replace the default logo, create a template file `dashboard/templates/wagtailadmin/base.html` that overrides the block `branding_logo`:
```
{% extends "wagtailadmin/base.html" %}
{% load static %}
{% block branding_logo %}
<img src="{% static 'images/custom-logo.svg' %}" alt="Custom Project" width="80" />
{% endblock %}
```
The logo also appears in the following pages and can be replaced with its template file:
* **login page** - create a template file `dashboard/templates/wagtailadmin/login.html` that overwrites the `branding_logo` block.
* **404 error page** - create a template file `dashboard/templates/wagtailadmin/404.html` that overrides the `branding_logo` block.
* **wagtail userbar** - create a template file `dashboard/templates/wagtailadmin/userbar/base.html` that overwrites the `branding_logo` block.
### `branding_favicon`
To replace the favicon displayed when viewing admin pages, create a template file `dashboard/templates/wagtailadmin/admin_base.html` that overrides the block `branding_favicon`:
```
{% extends "wagtailadmin/admin_base.html" %}
{% load static %}
{% block branding_favicon %}
<link rel="shortcut icon" href="{% static 'images/favicon.ico' %}" />
{% endblock %}
```
### `branding_title`
To replace the title prefix (which is ‘Wagtail’ by default), create a template file `dashboard/templates/wagtailadmin/admin_base.html` that overrides the block `branding_title`:
```
{% extends "wagtailadmin/admin_base.html" %}
{% block branding_title %}Frank's CMS{% endblock %}
```
### `branding_login`
To replace the login message, create a template file `dashboard/templates/wagtailadmin/login.html` that overrides the block `branding_login`:
```
{% extends "wagtailadmin/login.html" %}
{% block branding_login %}Sign in to Frank's Site{% endblock %}
```
### `branding_welcome`
To replace the welcome message on the dashboard, create a template file `dashboard/templates/wagtailadmin/home.html` that overrides the block `branding_welcome`:
```
{% extends "wagtailadmin/home.html" %}
{% block branding_welcome %}Welcome to Frank's Site{% endblock %}
```
Custom user interface fonts
---------------------------
To customise the font families used in the admin user interface, inject a CSS file using the hook [insert\_global\_admin\_css](../../reference/hooks#insert-global-admin-css) and override the variables within the `:root` selector:
```
:root {
--w-font-sans: Papyrus;
--w-font-mono: Courier;
}
```
Custom user interface colours
-----------------------------
Warning
The default Wagtail colours conform to the WCAG2.1 AA level colour contrast requirements. When customising the admin colours you should test the contrast using tools like [Axe](https://www.deque.com/axe/browser-extensions/).
To customise the colours used in the admin user interface, inject a CSS file using the hook [insert\_global\_admin\_css](../../reference/hooks#insert-global-admin-css) and set the desired variables within the `:root` selector. There are two ways to customisation options: either set each colour separately (for example `--w-color-primary: #2E1F5E;`); or separately set [HSL](https://en.wikipedia.org/wiki/HSL_and_HSV) (`--w-color-primary-hue`, `--w-color-primary-saturation`, `--w-color-primary-lightness`) variables so all shades are customised at once. For example, setting `--w-color-secondary-hue: 180;` will customise all of the secondary shades at once.
Make sure to test any customisations against our [Contrast Grid](https://contrast-grid.eightshapes.com/?version=1.1.0&es-color-form__tile-size=compact&es-color-form__show-contrast=aaa&es-color-form__show-contrast=aa&es-color-form__show-contrast=aa18&background-colors=%23000000%2C%20black%0D%0A%23F6F6F8%2C%20grey-50%0D%0A%23E0E0E0%2C%20grey-100%0D%0A%23C8C8C8%2C%20grey-150%0D%0A%23929292%2C%20grey-200%0D%0A%235C5C5C%2C%20grey-400%0D%0A%23262626%2C%20grey-600%0D%0A%23FFFFFF%2C%20white%0D%0A%23261A4E%2C%20primary-200%0D%0A%232E1F5E%2C%20primary%0D%0A%23F2FCFC%2C%20secondary-50%0D%0A%2380D7D8%2C%20secondary-75%0D%0A%2300B0B1%2C%20secondary-100%0D%0A%23005B5E%2C%20secondary-400%0D%0A%23004345%2C%20secondary-600%0D%0A%23007D7E%2C%20secondary%0D%0A%23E2F5FC%2C%20info-50%0D%0A%231F7E9A%2C%20info-100%0D%0A%23E0FBF4%2C%20positive-50%0D%0A%231B8666%2C%20positive-100%0D%0A%23FAECD5%2C%20warning-50%0D%0A%23FAA500%2C%20warning-100%0D%0A%23FDE9E9%2C%20critical-50%0D%0A%23FD5765%2C%20critical-100%0D%0A%23CD4444%2C%20critical-200&foreground-colors=%23000000%2C%20black%0D%0A%23F6F6F8%2C%20grey-50%0D%0A%23E0E0E0%2C%20grey-100%0D%0A%23C8C8C8%2C%20grey-150%0D%0A%23929292%2C%20grey-200%0D%0A%235C5C5C%2C%20grey-400%0D%0A%23262626%2C%20grey-600%0D%0A%23FFFFFF%2C%20white%0D%0A%23261A4E%2C%20primary-200%0D%0A%232E1F5E%2C%20primary%0D%0A%23F2FCFC%2C%20secondary-50%0D%0A%2380D7D8%2C%20secondary-75%0D%0A%2300B0B1%2C%20secondary-100%0D%0A%23005B5E%2C%20secondary-400%0D%0A%23004345%2C%20secondary-600%0D%0A%23007D7E%2C%20secondary%0D%0A%231F7E9A%2C%20info-100%0D%0A%231B8666%2C%20positive-100%0D%0A%23FAA500%2C%20warning-100%0D%0A%23FD5765%2C%20critical-100%0D%0A%23CD4444%2C%20critical-200). Try out your own customisations with this interactive style editor:
| | Variable | Usage |
| --- | --- | --- |
| | `--w-color-black` | Shadows only |
| | `--w-color-grey-600` | Body copy, user content |
| | `--w-color-grey-400` | Help text, placeholders, meta text, neutral state indicators |
| | `--w-color-grey-200` | Dividers, button borders |
| | `--w-color-grey-150` | Field borders |
| | `--w-color-grey-100` | Dividers, panel borders |
| | `--w-color-grey-50` | Background for panels, row highlights |
| | `--w-color-white` | Page backgrounds, Panels, Button text |
| | `--w-color-primary` | Wagtail branding, Panels, Headings, Buttons, Labels |
| | `--w-color-primary-200` | Accent for elements used in conjunction with primary colour in sidebar |
| | `--w-color-secondary` | Primary buttons, action links |
| | `--w-color-secondary-600` | Hover states for two-tone buttons |
| | `--w-color-secondary-400` | Two-tone buttons, hover states |
| | `--w-color-secondary-100` | UI element highlights over dark backgrounds |
| | `--w-color-secondary-75` | UI element highlights over dark text |
| | `--w-color-secondary-50` | Button backgrounds, highlighted fields background |
| | `--w-color-info-100` | Background and icons for information messages |
| | `--w-color-info-50` | Background only, for information messages |
| | `--w-color-positive-100` | Positive states |
| | `--w-color-positive-50` | Background only, for positive states |
| | `--w-color-warning-100` | Background and icons for potentially dangerous states |
| | `--w-color-warning-50` | Background only, for potentially dangerous states |
| | `--w-color-critical-200` | Dangerous actions or states (over light background), errors |
| | `--w-color-critical-100` | Dangerous actions or states (over dark background) |
| | `--w-color-critical-50` | Background only, for dangerous states |
Specifying a site or page in the branding
-----------------------------------------
The admin interface has a number of variables available to the renderer context that can be used to customise the branding in the admin page. These can be useful for customising the dashboard on a multitenanted Wagtail installation:
### `root_page`
Returns the highest explorable page object for the currently logged in user. If the user has no explore rights, this will default to `None`.
### `root_site`
Returns the name on the site record for the above root page.
### `site_name`
Returns the value of `root_site`, unless it evaluates to `None`. In that case, it will return the value of `settings.WAGTAIL_SITE_NAME`.
To use these variables, create a template file `dashboard/templates/wagtailadmin/home.html`, just as if you were overriding one of the template blocks in the dashboard, and use them as you would any other Django template variable:
```
{% extends "wagtailadmin/home.html" %}
{% block branding_welcome %}Welcome to the Admin Homepage for {{ root_site }}{% endblock %}
```
Extending the login form
------------------------
To add extra controls to the login form, create a template file `dashboard/templates/wagtailadmin/login.html`.
###
`above_login` and `below_login`
To add content above or below the login form, override these blocks:
```
{% extends "wagtailadmin/login.html" %}
{% block above_login %} If you are not Frank you should not be here! {% endblock %}
```
### `fields`
To add extra fields to the login form, override the `fields` block. You will need to add `{{ block.super }}` somewhere in your block to include the username and password fields:
```
{% extends "wagtailadmin/login.html" %}
{% block fields %}
{{ block.super }}
<li>
<div>
<label for="id_two-factor-auth">Two factor auth token</label>
<input type="text" name="two-factor-auth" id="id_two-factor-auth">
</div>
</li>
{% endblock %}
```
### `submit_buttons`
To add extra buttons to the login form, override the `submit_buttons` block. You will need to add `{{ block.super }}` somewhere in your block to include the sign in button:
```
{% extends "wagtailadmin/login.html" %}
{% block submit_buttons %}
{{ block.super }}
<a href="{% url 'signup' %}"><button type="button" class="button">{% trans 'Sign up' %}</button></a>
{% endblock %}
```
### `login_form`
To completely customise the login form, override the `login_form` block. This block wraps the whole contents of the `<form>` element:
```
{% extends "wagtailadmin/login.html" %}
{% block login_form %}
<p>Some extra form content</p>
{{ block.super }}
{% endblock %}
```
Extending the password reset request form
-----------------------------------------
To add extra controls to the password reset form, create a template file `dashboard/templates/wagtailadmin/account/password_reset/form.html`.
###
`above_form` and `below_form`
To add content above or below the password reset form, override these blocks:
```
{% extends "wagtailadmin/account/password_reset/form.html" %}
{% block above_login %} If you have not received your email within 7 days, call us. {% endblock %}
```
### `submit_buttons`
To add extra buttons to the password reset form, override the `submit_buttons` block. You will need to add `{{ block.super }}` somewhere in your block if you want to include the original submit button:
```
{% extends "wagtailadmin/account/password_reset/form.html" %}
{% block submit_buttons %}
<a href="{% url 'helpdesk' %}">Contact the helpdesk</a>
{% endblock %}
```
Extending client-side components
--------------------------------
Some of Wagtail’s admin interface is written as client-side JavaScript with [React](https://reactjs.org/). In order to customise or extend those components, you may need to use React too, as well as other related libraries. To make this easier, Wagtail exposes its React-related dependencies as global variables within the admin. Here are the available packages:
```
// 'focus-trap-react'
window.FocusTrapReact;
// 'react'
window.React;
// 'react-dom'
window.ReactDOM;
// 'react-transition-group/CSSTransitionGroup'
window.CSSTransitionGroup;
```
Wagtail also exposes some of its own React components. You can reuse:
```
window.wagtail.components.Icon;
window.wagtail.components.Portal;
```
Pages containing rich text editors also have access to:
```
// 'draft-js'
window.DraftJS;
// 'draftail'
window.Draftail;
// Wagtail’s Draftail-related APIs and components.
window.draftail;
window.draftail.DraftUtils;
window.draftail.ModalWorkflowSource;
window.draftail.ImageModalWorkflowSource;
window.draftail.EmbedModalWorkflowSource;
window.draftail.LinkModalWorkflowSource;
window.draftail.DocumentModalWorkflowSource;
window.draftail.Tooltip;
window.draftail.TooltipEntity;
```
| programming_docs |
wagtail Custom user models Custom user models
==================
Custom user forms example
-------------------------
This example shows how to add a text field and foreign key field to a custom user model and configure Wagtail user forms to allow the fields values to be updated.
Create a custom user model. This must at minimum inherit from `AbstractBaseUser` and `PermissionsMixin`. In this case we extend the `AbstractUser` class and add two fields. The foreign key references another model (not shown).
```
from django.contrib.auth.models import AbstractUser
class User(AbstractUser):
country = models.CharField(verbose_name='country', max_length=255)
status = models.ForeignKey(MembershipStatus, on_delete=models.SET_NULL, null=True, default=1)
```
Add the app containing your user model to `INSTALLED_APPS` - it must be above the `'wagtail.users'` line, in order to override Wagtail’s built-in templates - and set [AUTH\_USER\_MODEL](https://docs.djangoproject.com/en/stable/topics/auth/customizing/#substituting-a-custom-user-model) to reference your model. In this example the app is called `users` and the model is `User`
```
AUTH_USER_MODEL = 'users.User'
```
Create your custom user ‘create’ and ‘edit’ forms in your app:
```
from django import forms
from django.utils.translation import gettext_lazy as _
from wagtail.users.forms import UserEditForm, UserCreationForm
from users.models import MembershipStatus
class CustomUserEditForm(UserEditForm):
country = forms.CharField(required=True, label=_("Country"))
status = forms.ModelChoiceField(queryset=MembershipStatus.objects, required=True, label=_("Status"))
class CustomUserCreationForm(UserCreationForm):
country = forms.CharField(required=True, label=_("Country"))
status = forms.ModelChoiceField(queryset=MembershipStatus.objects, required=True, label=_("Status"))
```
Extend the Wagtail user ‘create’ and ‘edit’ templates. These extended templates should be placed in a template directory `wagtailusers/users`.
Template create.html:
```
{% extends "wagtailusers/users/create.html" %}
{% block extra_fields %}
<li>{% include "wagtailadmin/shared/field.html" with field=form.country %}</li>
<li>{% include "wagtailadmin/shared/field.html" with field=form.status %}</li>
{% endblock extra_fields %}
```
Template edit.html:
```
{% extends "wagtailusers/users/edit.html" %}
{% block extra_fields %}
<li>{% include "wagtailadmin/shared/field.html" with field=form.country %}</li>
<li>{% include "wagtailadmin/shared/field.html" with field=form.status %}</li>
{% endblock extra_fields %}
```
The `extra_fields` block allows fields to be inserted below the `last_name` field in the default templates. Other block overriding options exist to allow appending fields to the end or beginning of the existing fields, or to allow all the fields to be redefined.
Add the wagtail settings to your project to reference the user form additions:
```
WAGTAIL_USER_EDIT_FORM = 'users.forms.CustomUserEditForm'
WAGTAIL_USER_CREATION_FORM = 'users.forms.CustomUserCreationForm'
WAGTAIL_USER_CUSTOM_FIELDS = ['country', 'status']
```
wagtail Customising Wagtail Customising Wagtail
===================
* [Customising the editing interface](page_editing_interface)
+ [Customising the tabbed interface](page_editing_interface#customising-the-tabbed-interface)
+ [Rich Text (HTML)](page_editing_interface#rich-text-html)
+ [Customising generated forms](page_editing_interface#customising-generated-forms)
* [Customising admin templates](admin_templates)
+ [Custom branding](admin_templates#custom-branding)
+ [Custom user interface fonts](admin_templates#custom-user-interface-fonts)
+ [Custom user interface colours](admin_templates#custom-user-interface-colours)
+ [Specifying a site or page in the branding](admin_templates#specifying-a-site-or-page-in-the-branding)
+ [Extending the login form](admin_templates#extending-the-login-form)
+ [Extending the password reset request form](admin_templates#extending-the-password-reset-request-form)
+ [Extending client-side components](admin_templates#extending-client-side-components)
* [Custom user models](custom_user_models)
+ [Custom user forms example](custom_user_models#custom-user-forms-example)
* [How to build custom StreamField blocks](streamfield_blocks)
+ [Custom editing interfaces for `StructBlock`](streamfield_blocks#custom-editing-interfaces-for-structblock)
+ [Additional JavaScript on `StructBlock` forms](streamfield_blocks#additional-javascript-on-structblock-forms)
+ [Additional methods and properties on `StructBlock` values](streamfield_blocks#additional-methods-and-properties-on-structblock-values)
+ [Custom block types](streamfield_blocks#custom-block-types)
+ [Handling block definitions within migrations](streamfield_blocks#handling-block-definitions-within-migrations)
wagtail Customising the editing interface Customising the editing interface
=================================
Customising the tabbed interface
--------------------------------
As standard, Wagtail organises panels for pages into three tabs: ‘Content’, ‘Promote’ and ‘Settings’. For snippets Wagtail puts all panels into one page. Depending on the requirements of your site, you may wish to customise this for specific page types or snippets - for example, adding an additional tab for sidebar content. This can be done by specifying an `edit_handler` attribute on the page or snippet model. For example:
```
from wagtail.admin.panels import TabbedInterface, ObjectList
class BlogPage(Page):
# field definitions omitted
content_panels = [
FieldPanel('title', classname="title"),
FieldPanel('date'),
FieldPanel('body'),
]
sidebar_content_panels = [
FieldPanel('advert'),
InlinePanel('related_links', heading="Related links", label="Related link"),
]
edit_handler = TabbedInterface([
ObjectList(content_panels, heading='Content'),
ObjectList(sidebar_content_panels, heading='Sidebar content'),
ObjectList(Page.promote_panels, heading='Promote'),
ObjectList(Page.settings_panels, heading='Settings'),
])
```
Rich Text (HTML)
----------------
Wagtail provides a general-purpose WYSIWYG editor for creating rich text content (HTML) and embedding media such as images, video, and documents. To include this in your models, use the `RichTextField` function when defining a model field:
```
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel
class BookPage(Page):
body = RichTextField()
content_panels = Page.content_panels + [
FieldPanel('body'),
]
```
`RichTextField` inherits from Django’s basic `TextField` field, so you can pass any field parameters into `RichTextField` as if using a normal Django field. Its `max_length` will ignore any rich text formatting. This field does not need a special panel and can be defined with `FieldPanel`.
However, template output from `RichTextField` is special and needs to be filtered in order to preserve embedded content. See [Rich text (filter)](../../topics/writing_templates#rich-text-filter).
### Limiting features in a rich text field
By default, the rich text editor provides users with a wide variety of options for text formatting and inserting embedded content such as images. However, we may wish to restrict a rich text field to a more limited set of features - for example:
* The field might be intended for a short text snippet, such as a summary to be pulled out on index pages, where embedded images or videos would be inappropriate;
* When page content is defined using [StreamField](../../topics/streamfield), elements such as headings, images and videos are usually given their own block types, alongside a rich text block type used for ordinary paragraph text; in this case, allowing headings and images to also exist within the rich text content is redundant (and liable to result in inconsistent designs).
This can be achieved by passing a `features` keyword argument to `RichTextField`, with a list of identifiers for the features you wish to allow:
```
body = RichTextField(features=['h2', 'h3', 'bold', 'italic', 'link'])
```
The feature identifiers provided on a default Wagtail installation are as follows:
* `h1`, `h2`, `h3`, `h4`, `h5`, `h6` - heading elements
* `bold`, `italic` - bold / italic text
* `ol`, `ul` - ordered / unordered lists
* `hr` - horizontal rules
* `link` - page, external and email links
* `document-link` - links to documents
* `image` - embedded images
* `embed` - embedded media (see [Embedded content](../embeds#embedded-content))
We have few additional feature identifiers as well. They are not enabled by default, but you can use them in your list of identifiers. These are as follows:
* `code` - inline code
* `superscript`, `subscript`, `strikethrough` - text formatting
* `blockquote` - blockquote
The process for creating new features is described in the following pages:
* [Rich text internals](../../extending/rich_text_internals)
* [Extending the Draftail Editor](../../extending/extending_draftail)
You can also provide a setting for naming a group of rich text features. See [WAGTAILADMIN\_RICH\_TEXT\_EDITORS](../../reference/settings#wagtailadmin-rich-text-editors).
### Image Formats in the Rich Text Editor
On loading, Wagtail will search for any app with the file `image_formats.py` and execute the contents. This provides a way to customise the formatting options shown to the editor when inserting images in the `RichTextField` editor.
As an example, add a “thumbnail” format:
```
# image_formats.py
from wagtail.images.formats import Format, register_image_format
register_image_format(Format('thumbnail', 'Thumbnail', 'richtext-image thumbnail', 'max-120x120'))
```
To begin, import the `Format` class, `register_image_format` function, and optionally `unregister_image_format` function. To register a new `Format`, call the `register_image_format` with the `Format` object as the argument. The `Format` class takes the following constructor arguments:
**`name`**
The unique key used to identify the format. To unregister this format, call `unregister_image_format` with this string as the only argument.
**`label`**
The label used in the chooser form when inserting the image into the `RichTextField`.
**`classnames`**
The string to assign to the `class` attribute of the generated `<img>` tag.
Note
Any class names you provide must have CSS rules matching them written separately, as part of the front end CSS code. Specifying a `classnames` value of `left` will only ensure that class is output in the generated markup, it won’t cause the image to align itself left.
**`filter_spec`**
The string specification to create the image rendition. For more, see [How to use images in templates](../../topics/images#image-tag).
To unregister, call `unregister_image_format` with the string of the `name` of the `Format` as the only argument.
Warning
Unregistering `Format` objects will cause errors viewing or editing pages that reference them.
Customising generated forms
---------------------------
Wagtail automatically generates forms using the panels configured on the model. By default, this form subclasses [WagtailAdminModelForm](#wagtail.admin.forms.WagtailAdminModelForm "wagtail.admin.forms.WagtailAdminModelForm"), or [WagtailAdminPageForm](#wagtail.admin.forms.WagtailAdminPageForm "wagtail.admin.forms.WagtailAdminPageForm"). for pages. A custom base form class can be configured by setting the `base_form_class` attribute on any model. Custom forms for snippets must subclass [WagtailAdminModelForm](#wagtail.admin.forms.WagtailAdminModelForm "wagtail.admin.forms.WagtailAdminModelForm"), and custom forms for pages must subclass [WagtailAdminPageForm](#wagtail.admin.forms.WagtailAdminPageForm "wagtail.admin.forms.WagtailAdminPageForm").
This can be used to add non-model fields to the form, to automatically generate field content, or to add custom validation logic for your models:
```
from django import forms
from django.db import models
import geocoder # not in Wagtail, for example only - https://geocoder.readthedocs.io/
from wagtail.admin.panels import FieldPanel
from wagtail.admin.forms import WagtailAdminPageForm
from wagtail.models import Page
class EventPageForm(WagtailAdminPageForm):
address = forms.CharField()
def clean(self):
cleaned_data = super().clean()
# Make sure that the event starts before it ends
start_date = cleaned_data['start_date']
end_date = cleaned_data['end_date']
if start_date and end_date and start_date > end_date:
self.add_error('end_date', 'The end date must be after the start date')
return cleaned_data
def save(self, commit=True):
page = super().save(commit=False)
# Update the duration field from the submitted dates
page.duration = (page.end_date - page.start_date).days
# Fetch the location by geocoding the address
page.location = geocoder.arcgis(self.cleaned_data['address'])
if commit:
page.save()
return page
class EventPage(Page):
start_date = models.DateField()
end_date = models.DateField()
duration = models.IntegerField()
location = models.CharField(max_length=255)
content_panels = [
FieldPanel('title'),
FieldPanel('start_date'),
FieldPanel('end_date'),
FieldPanel('address'),
]
base_form_class = EventPageForm
```
Wagtail will generate a new subclass of this form for the model, adding any fields defined in `panels` or `content_panels`. Any fields already defined on the model will not be overridden by these automatically added fields, so the form field for a model field can be overridden by adding it to the custom form.
wagtail How to build custom StreamField blocks How to build custom StreamField blocks
======================================
Custom editing interfaces for `StructBlock`
-------------------------------------------
To customise the styling of a `StructBlock` as it appears in the page editor, you can specify a `form_classname` attribute (either as a keyword argument to the `StructBlock` constructor, or in a subclass’s `Meta`) to override the default value of `struct-block`:
```
class PersonBlock(blocks.StructBlock):
first_name = blocks.CharBlock()
surname = blocks.CharBlock()
photo = ImageChooserBlock(required=False)
biography = blocks.RichTextBlock()
class Meta:
icon = 'user'
form_classname = 'person-block struct-block'
```
You can then provide custom CSS for this block, targeted at the specified classname, by using the [insert\_editor\_css](../../reference/hooks#insert-editor-css) hook.
Note
Wagtail’s editor styling has some built in styling for the `struct-block` class and other related elements. If you specify a value for `form_classname`, it will overwrite the classes that are already applied to `StructBlock`, so you must remember to specify the `struct-block` as well.
For more extensive customisations that require changes to the HTML markup as well, you can override the `form_template` attribute in `Meta` to specify your own template path. The following variables are available on this template:
**`children`**
An `OrderedDict` of `BoundBlock`s for all of the child blocks making up this `StructBlock`.
**`help_text`**
The help text for this block, if specified.
**`classname`** The class name passed as `form_classname` (defaults to `struct-block`).
**`block_definition`** The `StructBlock` instance that defines this block.
**`prefix`** The prefix used on form fields for this block instance, guaranteed to be unique across the form.
To add additional variables, you can override the block’s `get_form_context` method:
```
class PersonBlock(blocks.StructBlock):
first_name = blocks.CharBlock()
surname = blocks.CharBlock()
photo = ImageChooserBlock(required=False)
biography = blocks.RichTextBlock()
def get_form_context(self, value, prefix='', errors=None):
context = super().get_form_context(value, prefix=prefix, errors=errors)
context['suggested_first_names'] = ['John', 'Paul', 'George', 'Ringo']
return context
class Meta:
icon = 'user'
form_template = 'myapp/block_forms/person.html'
```
A form template for a StructBlock must include the output of `render_form` for each child block in the `children` dict, inside a container element with a `data-contentpath` attribute equal to the block’s name. This attribute is used by the commenting framework to attach comments to the correct fields. The StructBlock’s form template is also responsible for rendering labels for each field, but this (and all other HTML markup) can be customised as you see fit. The template below replicates the default StructBlock form rendering:
```
{% load wagtailadmin_tags %}
<div class="{{ classname }}">
{% if help_text %}
<span>
<div class="help">
{% icon name="help" class_name="default" %}
{{ help_text }}
</div>
</span>
{% endif %}
{% for child in children.values %}
<div class="w-field" data-field data-contentpath="{{ child.block.name }}">
{% if child.block.label %}
<label class="w-field__label" {% if child.id_for_label %}for="{{ child.id_for_label }}"{% endif %}>{{ child.block.label }}{% if child.block.required %}<span class="w-required-mark">*</span>{% endif %}</label>
{% endif %}
{{ child.render_form }}
</div>
{% endfor %}
</div>
```
Additional JavaScript on `StructBlock` forms
--------------------------------------------
Often it may be desirable to attach custom JavaScript behaviour to a StructBlock form. For example, given a block such as:
```
class AddressBlock(StructBlock):
street = CharBlock()
town = CharBlock()
state = CharBlock(required=False)
country = ChoiceBlock(choices=[
('us', 'United States'),
('ca', 'Canada'),
('mx', 'Mexico'),
])
```
we may wish to disable the ‘state’ field when a country other than United States is selected. Since new blocks can be added dynamically, we need to integrate with StreamField’s own front-end logic to ensure that our custom JavaScript code is executed when a new block is initialised.
StreamField uses the [telepath](https://wagtail.github.io/telepath/) library to map Python block classes such as `StructBlock` to a corresponding JavaScript implementation. These JavaScript implementations can be accessed through the `window.wagtailStreamField.blocks` namespace, as the following classes:
* `FieldBlockDefinition`
* `ListBlockDefinition`
* `StaticBlockDefinition`
* `StreamBlockDefinition`
* `StructBlockDefinition`
First, we define a telepath adapter for `AddressBlock`, so that it uses our own JavaScript class in place of the default `StructBlockDefinition`. This can be done in the same module as the `AddressBlock` definition:
```
from wagtail.blocks.struct_block import StructBlockAdapter
from wagtail.telepath import register
from django import forms
from django.utils.functional import cached_property
class AddressBlockAdapter(StructBlockAdapter):
js_constructor = 'myapp.blocks.AddressBlock'
@cached_property
def media(self):
structblock_media = super().media
return forms.Media(
js=structblock_media._js + ['js/address-block.js'],
css=structblock_media._css
)
register(AddressBlockAdapter(), AddressBlock)
```
Here `'myapp.blocks.AddressBlock'` is the identifier for our JavaScript class that will be registered with the telepath client-side code, and `'js/address-block.js'` is the file that defines it (as a path within any static file location recognised by Django). This implementation subclasses StructBlockDefinition and adds our custom code to the `render` method:
```
class AddressBlockDefinition extends window.wagtailStreamField.blocks
.StructBlockDefinition {
render(placeholder, prefix, initialState, initialError) {
const block = super.render(
placeholder,
prefix,
initialState,
initialError,
);
const stateField = document.getElementById(prefix + '-state');
const countryField = document.getElementById(prefix + '-country');
const updateStateInput = () => {
if (countryField.value == 'us') {
stateField.removeAttribute('disabled');
} else {
stateField.setAttribute('disabled', true);
}
};
updateStateInput();
countryField.addEventListener('change', updateStateInput);
return block;
}
}
window.telepath.register('myapp.blocks.AddressBlock', AddressBlockDefinition);
```
Additional methods and properties on `StructBlock` values
---------------------------------------------------------
When rendering StreamField content on a template, StructBlock values are represented as `dict`-like objects where the keys correspond to the names of the child blocks. Specifically, these values are instances of the class `wagtail.blocks.StructValue`.
Sometimes, it’s desirable to make additional methods or properties available on this object. For example, given a StructBlock that represents either an internal or external link:
```
class LinkBlock(StructBlock):
text = CharBlock(label="link text", required=True)
page = PageChooserBlock(label="page", required=False)
external_url = URLBlock(label="external URL", required=False)
```
you may want to make a `url` property available, that returns either the page URL or external URL depending which one was filled in. A common mistake is to define this property on the block class itself:
```
class LinkBlock(StructBlock):
text = CharBlock(label="link text", required=True)
page = PageChooserBlock(label="page", required=False)
external_url = URLBlock(label="external URL", required=False)
@property
def url(self): # INCORRECT - will not work
return self.external_url or self.page.url
```
This does not work because the value as seen in the template is not an instance of `LinkBlock`. `StructBlock` instances only serve as specifications for the block’s behaviour, and do not hold block data in their internal state - in this respect, they are similar to Django’s form widget objects (which provide methods for rendering a given value as a form field, but do not hold on to the value itself).
Instead, you should define a subclass of `StructValue` that implements your custom property or method. Within this method, the block’s data can be accessed as `self['page']` or `self.get('page')`, since `StructValue` is a dict-like object.
```
from wagtail.blocks import StructValue
class LinkStructValue(StructValue):
def url(self):
external_url = self.get('external_url')
page = self.get('page')
return external_url or page.url
```
Once this is defined, set the block’s `value_class` option to instruct it to use this class rather than a plain StructValue:
```
class LinkBlock(StructBlock):
text = CharBlock(label="link text", required=True)
page = PageChooserBlock(label="page", required=False)
external_url = URLBlock(label="external URL", required=False)
class Meta:
value_class = LinkStructValue
```
Your extended value class methods will now be available in your template:
```
{% for block in page.body %}
{% if block.block_type == 'link' %}
<a href="{{ link.value.url }}">{{ link.value.text }}</a>
{% endif %}
{% endfor %}
```
Custom block types
------------------
If you need to implement a custom UI, or handle a datatype that is not provided by Wagtail’s built-in block types (and cannot be built up as a structure of existing fields), it is possible to define your own custom block types. For further guidance, refer to the source code of Wagtail’s built-in block classes.
For block types that simply wrap an existing Django form field, Wagtail provides an abstract class `wagtail.blocks.FieldBlock` as a helper. Subclasses should set a `field` property that returns the form field object:
```
class IPAddressBlock(FieldBlock):
def __init__(self, required=True, help_text=None, **kwargs):
self.field = forms.GenericIPAddressField(required=required, help_text=help_text)
super().__init__(**kwargs)
```
Since the StreamField editing interface needs to create blocks dynamically, certain complex widget types will need additional JavaScript code to define how to render and populate them on the client-side. If a field uses a widget type that does not inherit from one of the classes inheriting from `django.forms.widgets.Input`, `django.forms.Textarea`, `django.forms.Select` or `django.forms.RadioSelect`, or has customised client-side behaviour to the extent where it is not possible to read or write its data simply by accessing the form element’s `value` property, you will need to provide a JavaScript handler object, implementing the methods detailed on [Form widget client-side API](../../reference/streamfield/widget_api#streamfield-widget-api).
Handling block definitions within migrations
--------------------------------------------
As with any model field in Django, any changes to a model definition that affect a StreamField will result in a migration file that contains a ‘frozen’ copy of that field definition. Since a StreamField definition is more complex than a typical model field, there is an increased likelihood of definitions from your project being imported into the migration – which would cause problems later on if those definitions are moved or deleted.
To mitigate this, StructBlock, StreamBlock and ChoiceBlock implement additional logic to ensure that any subclasses of these blocks are deconstructed to plain instances of StructBlock, StreamBlock and ChoiceBlock – in this way, the migrations avoid having any references to your custom class definitions. This is possible because these block types provide a standard pattern for inheritance, and know how to reconstruct the block definition for any subclass that follows that pattern.
If you subclass any other block class, such as `FieldBlock`, you will need to either keep that class definition in place for the lifetime of your project, or implement a [custom deconstruct method](https://docs.djangoproject.com/en/stable/topics/migrations/#custom-deconstruct-method "(in Django v4.1)") that expresses your block entirely in terms of classes that are guaranteed to remain in place. Similarly, if you customise a StructBlock, StreamBlock or ChoiceBlock subclass to the point where it can no longer be expressed as an instance of the basic block type – for example, if you add extra arguments to the constructor – you will need to provide your own `deconstruct` method.
| programming_docs |
wagtail Wagtail API Wagtail API
===========
The API module provides a public-facing, JSON-formatted API to allow retrieving content as raw field data. This is useful for cases like serving content to non-web clients (such as a mobile phone app) or pulling content out of Wagtail for use in another site.
See [RFC 8: Wagtail API](https://github.com/wagtail/rfcs/blob/main/text/008-wagtail-api.md#12---stable-and-unstable-versions) for full details on our stabilisation policy.
* [Wagtail API v2 Configuration Guide](v2/configuration)
+ [Basic configuration](v2/configuration#basic-configuration)
+ [Additional settings](v2/configuration#additional-settings)
* [Wagtail API v2 Usage Guide](v2/usage)
+ [Fetching content](v2/usage#fetching-content)
+ [Default endpoint fields](v2/usage#default-endpoint-fields)
+ [Changes since v1](v2/usage#changes-since-v1)
wagtail Wagtail API v2 Configuration Guide Wagtail API v2 Configuration Guide
==================================
This section of the docs will show you how to set up a public API for your Wagtail site.
Even though the API is built on Django REST Framework, you do not need to install this manually as it is already a dependency of Wagtail.
Basic configuration
-------------------
### Enable the app
Firstly, you need to enable Wagtail’s API app so Django can see it. Add `wagtail.api.v2` to `INSTALLED_APPS` in your Django project settings:
```
# settings.py
INSTALLED_APPS = [
...
'wagtail.api.v2',
...
]
```
Optionally, you may also want to add `rest_framework` to `INSTALLED_APPS`. This would make the API browsable when viewed from a web browser but is not required for basic JSON-formatted output.
### Configure endpoints
Next, it’s time to configure which content will be exposed on the API. Each content type (such as pages, images and documents) has its own endpoint. Endpoints are combined by a router, which provides the url configuration you can hook into the rest of your project.
Wagtail provides three endpoint classes you can use:
* Pages `wagtail.api.v2.views.PagesAPIViewSet`
* Images `wagtail.images.api.v2.views.ImagesAPIViewSet`
* Documents `wagtail.documents.api.v2.views.DocumentsAPIViewSet`
You can subclass any of these endpoint classes to customize their functionality. Additionally, there is a base endpoint class you can use for adding different content types to the API: `wagtail.api.v2.views.BaseAPIViewSet`
For this example, we will create an API that includes all three builtin content types in their default configuration:
```
# api.py
from wagtail.api.v2.views import PagesAPIViewSet
from wagtail.api.v2.router import WagtailAPIRouter
from wagtail.images.api.v2.views import ImagesAPIViewSet
from wagtail.documents.api.v2.views import DocumentsAPIViewSet
# Create the router. "wagtailapi" is the URL namespace
api_router = WagtailAPIRouter('wagtailapi')
# Add the three endpoints using the "register_endpoint" method.
# The first parameter is the name of the endpoint (such as pages, images). This
# is used in the URL of the endpoint
# The second parameter is the endpoint class that handles the requests
api_router.register_endpoint('pages', PagesAPIViewSet)
api_router.register_endpoint('images', ImagesAPIViewSet)
api_router.register_endpoint('documents', DocumentsAPIViewSet)
```
Next, register the URLs so Django can route requests into the API:
```
# urls.py
from .api import api_router
urlpatterns = [
...
path('api/v2/', api_router.urls),
...
# Ensure that the api_router line appears above the default Wagtail page serving route
re_path(r'^', include(wagtail_urls)),
]
```
With this configuration, pages will be available at `/api/v2/pages/`, images at `/api/v2/images/` and documents at `/api/v2/documents/`
### Adding custom page fields
It’s likely that you would need to export some custom fields over the API. This can be done by adding a list of fields to be exported into the `api_fields` attribute for each page model.
For example:
```
# blog/models.py
from wagtail.api import APIField
class BlogPageAuthor(Orderable):
page = models.ForeignKey('blog.BlogPage', on_delete=models.CASCADE, related_name='authors')
name = models.CharField(max_length=255)
api_fields = [
APIField('name'),
]
class BlogPage(Page):
published_date = models.DateTimeField()
body = RichTextField()
feed_image = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, null=True, ...)
private_field = models.CharField(max_length=255)
# Export fields over the API
api_fields = [
APIField('published_date'),
APIField('body'),
APIField('feed_image'),
APIField('authors'), # This will nest the relevant BlogPageAuthor objects in the API response
]
```
This will make `published_date`, `body`, `feed_image` and a list of `authors` with the `name` field available in the API. But to access these fields, you must select the `blog.BlogPage` type using the `?type` [parameter in the API itself](usage#apiv2-custom-page-fields).
### Custom serializers
[Serializers](https://www.django-rest-framework.org/api-guide/fields/) are used to convert the database representation of a model into JSON format. You can override the serializer for any field using the `serializer` keyword argument:
```
from rest_framework.fields import DateField
class BlogPage(Page):
...
api_fields = [
# Change the format of the published_date field to "Thursday 06 April 2017"
APIField('published_date', serializer=DateField(format='%A %d %B %Y')),
...
]
```
Django REST framework’s serializers can all take a [source](https://www.django-rest-framework.org/api-guide/fields/#source) argument allowing you to add API fields that have a different field name or no underlying field at all:
```
from rest_framework.fields import DateField
class BlogPage(Page):
...
api_fields = [
# Date in ISO8601 format (the default)
APIField('published_date'),
# A separate published_date_display field with a different format
APIField('published_date_display', serializer=DateField(format='%A %d %B %Y', source='published_date')),
...
]
```
This adds two fields to the API (other fields omitted for brevity):
```
{
"published_date": "2017-04-06",
"published_date_display": "Thursday 06 April 2017"
}
```
### Images in the API
The `ImageRenditionField` serializer allows you to add renditions of images into your API. It requires an image filter string specifying the resize operations to perform on the image. It can also take the `source` keyword argument described above.
For example:
```
from wagtail.api import APIField
from wagtail.images.api.fields import ImageRenditionField
class BlogPage(Page):
...
api_fields = [
# Adds information about the source image (eg, title) into the API
APIField('feed_image'),
# Adds a URL to a rendered thumbnail of the image to the API
APIField('feed_image_thumbnail', serializer=ImageRenditionField('fill-100x100', source='feed_image')),
...
]
```
This would add the following to the JSON:
```
{
"feed_image": {
"id": 45529,
"meta": {
"type": "wagtailimages.Image",
"detail_url": "http://www.example.com/api/v2/images/12/",
"download_url": "/media/images/a_test_image.jpg",
"tags": []
},
"title": "A test image",
"width": 2000,
"height": 1125
},
"feed_image_thumbnail": {
"url": "/media/images/a_test_image.fill-100x100.jpg",
"full_url": "http://www.example.com/media/images/a_test_image.fill-100x100.jpg",
"width": 100,
"height": 100,
"alt": "image alt text"
}
}
```
Note: `download_url` is the original uploaded file path, whereas `feed_image_thumbnail['url']` is the url of the rendered image. When you are using another storage backend, such as S3, `download_url` will return a URL to the image if your media files are properly configured.
Additional settings
-------------------
### `WAGTAILAPI_BASE_URL`
(required when using frontend cache invalidation)
This is used in two places, when generating absolute URLs to document files and invalidating the cache.
Generating URLs to documents will fall back the the current request’s hostname if this is not set. Cache invalidation cannot do this, however, so this setting must be set when using this module alongside the `wagtailfrontendcache` module.
### `WAGTAILAPI_SEARCH_ENABLED`
(default: True)
Setting this to false will disable full text search. This applies to all endpoints.
### `WAGTAILAPI_LIMIT_MAX`
(default: 20)
This allows you to change the maximum number of results a user can request at a time. This applies to all endpoints. Set to `None` for no limit.
wagtail Wagtail API v2 Usage Guide Wagtail API v2 Usage Guide
==========================
The Wagtail API module exposes a public, read only, JSON-formatted API which can be used by external clients (such as a mobile app) or the site’s frontend.
This document is intended for developers using the API exposed by Wagtail. For documentation on how to enable the API module in your Wagtail site, see [Wagtail API v2 Configuration Guide](configuration)
Contents
* [Fetching content](#fetching-content)
+ [Example response](#example-response)
+ [Custom page fields in the API](#custom-page-fields-in-the-api)
+ [Pagination](#pagination)
+ [Ordering](#ordering)
- [Random ordering](#random-ordering)
+ [Filtering](#filtering)
+ [Filtering by tree position (pages only)](#filtering-by-tree-position-pages-only)
+ [Filtering pages by site](#filtering-pages-by-site)
+ [Search](#search)
- [Search operator](#search-operator)
+ [Special filters for internationalized sites](#special-filters-for-internationalized-sites)
- [Filtering pages by locale](#filtering-pages-by-locale)
- [Getting translations of a page](#getting-translations-of-a-page)
+ [Fields](#fields)
- [Additional fields](#additional-fields)
- [All fields](#all-fields)
- [Removing fields](#removing-fields)
- [Removing all default fields](#removing-all-default-fields)
+ [Detail views](#detail-views)
+ [Finding pages by HTML path](#finding-pages-by-html-path)
* [Default endpoint fields](#default-endpoint-fields)
+ [Common fields](#common-fields)
+ [Pages](#pages)
+ [Images](#images)
+ [Documents](#documents)
* [Changes since v1](#changes-since-v1)
+ [Breaking changes](#breaking-changes)
+ [Major features](#major-features)
+ [Minor features](#minor-features)
Fetching content
----------------
To fetch content over the API, perform a `GET` request against one of the following endpoints:
* Pages `/api/v2/pages/`
* Images `/api/v2/images/`
* Documents `/api/v2/documents/`
Note
The available endpoints and their URLs may vary from site to site, depending on how the API has been configured.
### Example response
Each response contains the list of items (`items`) and the total count (`meta.total_count`). The total count is irrespective of pagination.
```
GET /api/v2/endpoint_name/
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": "total number of results"
},
"items": [
{
"id": 1,
"meta": {
"type": "app_name.ModelName",
"detail_url": "http://api.example.com/api/v2/endpoint_name/1/"
},
"field": "value"
},
{
"id": 2,
"meta": {
"type": "app_name.ModelName",
"detail_url": "http://api.example.com/api/v2/endpoint_name/2/"
},
"field": "different value"
}
]
}
```
### Custom page fields in the API
Wagtail sites contain many page types, each with their own set of fields. The `pages` endpoint will only expose the common fields by default (such as `title` and `slug`).
To access custom page fields with the API, select the page type with the `?type` parameter. This will filter the results to only include pages of that type but will also make all the exported custom fields for that type available in the API.
For example, to access the `published_date`, `body` and `authors` fields on the `blog.BlogPage` model in the [configuration docs](configuration#apiv2-page-fields-configuration):
```
GET /api/v2/pages/?type=blog.BlogPage&fields=published_date,body,authors(name)
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 10
},
"items": [
{
"id": 1,
"meta": {
"type": "blog.BlogPage",
"detail_url": "http://api.example.com/api/v2/pages/1/",
"html_url": "http://www.example.com/blog/my-blog-post/",
"slug": "my-blog-post",
"first_published_at": "2016-08-30T16:52:00Z"
},
"title": "Test blog post",
"published_date": "2016-08-30",
"authors": [
{
"id": 1,
"meta": {
"type": "blog.BlogPageAuthor",
},
"name": "Karl Hobley"
}
]
},
...
]
}
```
Note
Only fields that have been explicitly exported by the developer may be used in the API. This is done by adding a `api_fields` attribute to the page model. You can read about configuration [here](configuration#apiv2-page-fields-configuration).
This doesn’t apply to images/documents as there is only one model exposed in those endpoints. But for projects that have customized image/document models, the `api_fields` attribute can be used to export any custom fields into the API.
### Pagination
The number of items in the response can be changed by using the `?limit` parameter (default: 20) and the number of items to skip can be changed by using the `?offset` parameter.
For example:
```
GET /api/v2/pages/?offset=20&limit=20
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 50
},
"items": [
pages 20 - 40 will be listed here.
]
}
```
Note
There may be a maximum value for the `?limit` parameter. This can be modified in your project settings by setting `WAGTAILAPI_LIMIT_MAX` to either a number (the new maximum value) or `None` (which disables maximum value check).
### Ordering
The results can be ordered by any field by setting the `?order` parameter to the name of the field to order by.
```
GET /api/v2/pages/?order=title
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 50
},
"items": [
pages will be listed here in ascending title order (a-z)
]
}
```
The results will be ordered in ascending order by default. This can be changed to descending order by prefixing the field name with a `-` sign.
```
GET /api/v2/pages/?order=-title
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 50
},
"items": [
pages will be listed here in descending title order (z-a)
]
}
```
Note
Ordering is case-sensitive so lowercase letters are always ordered after uppercase letters when in ascending order.
#### Random ordering
Passing `random` into the `?order` parameter will make results return in a random order. If there is no caching, each request will return results in a different order.
```
GET /api/v2/pages/?order=random
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 50
},
"items": [
pages will be listed here in random order
]
}
```
Note
It’s not possible to use `?offset` while ordering randomly because consistent random ordering cannot be guaranteed over multiple requests (so requests for subsequent pages may return results that also appeared in previous pages).
### Filtering
Any field may be used in an exact match filter. Use the filter name as the parameter and the value to match against.
For example, to find a page with the slug “about”:
```
GET /api/v2/pages/?slug=about
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 1
},
"items": [
{
"id": 10,
"meta": {
"type": "standard.StandardPage",
"detail_url": "http://api.example.com/api/v2/pages/10/",
"html_url": "http://www.example.com/about/",
"slug": "about",
"first_published_at": "2016-08-30T16:52:00Z"
},
"title": "About"
},
]
}
```
### Filtering by tree position (pages only)
Pages can additionally be filtered by their relation to other pages in the tree.
The `?child_of` filter takes the id of a page and filters the list of results to contain only direct children of that page.
For example, this can be useful for constructing the main menu, by passing the id of the homepage to the filter:
```
GET /api/v2/pages/?child_of=2&show_in_menus=true
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 5
},
"items": [
{
"id": 3,
"meta": {
"type": "blog.BlogIndexPage",
"detail_url": "http://api.example.com/api/v2/pages/3/",
"html_url": "http://www.example.com/blog/",
"slug": "blog",
"first_published_at": "2016-09-21T13:54:00Z"
},
"title": "About"
},
{
"id": 10,
"meta": {
"type": "standard.StandardPage",
"detail_url": "http://api.example.com/api/v2/pages/10/",
"html_url": "http://www.example.com/about/",
"slug": "about",
"first_published_at": "2016-08-30T16:52:00Z"
},
"title": "About"
},
...
]
}
```
The `?ancestor_of` filter takes the id of a page and filters the list to only include ancestors of that page (parent, grandparent etc.) all the way down to the site’s root page.
For example, when combined with the `type` filter it can be used to find the particular `blog.BlogIndexPage` a `blog.BlogPage` belongs to. By itself, it can be used to to construct a breadcrumb trail from the current page back to the site’s root page.
The `?descendant_of` filter takes the id of a page and filter the list to only include descendants of that page (children, grandchildren etc.).
### Filtering pages by site
New in version 4.0.
By default, the API will look for the site based on the hostname of the request. In some cases, you might want to query pages belonging to a different site. The `?site=` filter is used to filter the listing to only include pages that belong to a specific site. The filter requires the configured hostname of the site. If you have multiple sites using the same hostname but a different port number, it’s possible to filter by port number using the format `hostname:port`. For example:
```
GET /api/v2/pages/?site=demo-site.local
GET /api/v2/pages/?site=demo-site.local:8080
```
### Search
Passing a query to the `?search` parameter will perform a full-text search on the results.
The query is split into “terms” (by word boundary), then each term is normalized (lowercased and unaccented).
For example: `?search=James+Joyce`
#### Search operator
The `search_operator` specifies how multiple terms in the query should be handled. There are two possible values:
* `and` - All terms in the search query (excluding stop words) must exist in each result
* `or` - At least one term in the search query must exist in each result
The `or` operator is generally better than `and` as it allows the user to be inexact with their query and the ranking algorithm will make sure that irrelevant results are not returned at the top of the page.
The default search operator depends on whether the search engine being used by the site supports ranking. If it does (Elasticsearch), the operator will default to `or`. Otherwise (database), it will default to `and`.
For the same reason, it’s also recommended to use the `and` operator when using `?search` in conjunction with `?order` (as this disables ranking).
For example: `?search=James+Joyce&order=-first_published_at&search_operator=and`
### Special filters for internationalized sites
When `WAGTAIL_I18N_ENABLED` is set to `True` (see [Enabling internationalisation](../../i18n#enabling-internationalisation) for more details) two new filters are made available on the pages endpoint.
#### Filtering pages by locale
The `?locale=` filter is used to filter the listing to only include pages in the specified locale. For example:
```
GET /api/v2/pages/?locale=en-us
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 5
},
"items": [
{
"id": 10,
"meta": {
"type": "standard.StandardPage",
"detail_url": "http://api.example.com/api/v2/pages/10/",
"html_url": "http://www.example.com/usa-page/",
"slug": "usa-page",
"first_published_at": "2016-08-30T16:52:00Z",
"locale": "en-us"
},
"title": "American page"
},
...
]
}
```
#### Getting translations of a page
The `?translation_of` filter is used to filter the listing to only include pages that are a translation of the specified page ID. For example:
```
GET /api/v2/pages/?translation_of=10
HTTP 200 OK
Content-Type: application/json
{
"meta": {
"total_count": 2
},
"items": [
{
"id": 11,
"meta": {
"type": "standard.StandardPage",
"detail_url": "http://api.example.com/api/v2/pages/11/",
"html_url": "http://www.example.com/gb-page/",
"slug": "gb-page",
"first_published_at": "2016-08-30T16:52:00Z",
"locale": "en-gb"
},
"title": "British page"
},
{
"id": 12,
"meta": {
"type": "standard.StandardPage",
"detail_url": "http://api.example.com/api/v2/pages/12/",
"html_url": "http://www.example.com/fr-page/",
"slug": "fr-page",
"first_published_at": "2016-08-30T16:52:00Z",
"locale": "fr"
},
"title": "French page"
},
]
}
```
### Fields
By default, only a subset of the available fields are returned in the response. The `?fields` parameter can be used to both add additional fields to the response and remove default fields that you know you won’t need.
#### Additional fields
Additional fields can be added to the response by setting `?fields` to a comma-separated list of field names you want to add.
For example, `?fields=body,feed_image` will add the `body` and `feed_image` fields to the response.
This can also be used across relationships. For example, `?fields=body,feed_image(width,height)` will nest the `width` and `height` of the image in the response.
#### All fields
Setting `?fields` to an asterisk (`*`) will add all available fields to the response. This is useful for discovering what fields have been exported.
For example: `?fields=*`
#### Removing fields
Fields you know that you do not need can be removed by prefixing the name with a `-` and adding it to `?fields`.
For example, `?fields=-title,body` will remove `title` and add `body`.
This can also be used with the asterisk. For example, `?fields=*,-body` adds all fields except for `body`.
#### Removing all default fields
To specify exactly the fields you need, you can set the first item in fields to an underscore (`_`) which removes all default fields.
For example, `?fields=_,title` will only return the title field.
### Detail views
You can retrieve a single object from the API by appending its id to the end of the URL. For example:
* Pages `/api/v2/pages/1/`
* Images `/api/v2/images/1/`
* Documents `/api/v2/documents/1/`
All exported fields will be returned in the response by default. You can use the `?fields` parameter to customize which fields are shown.
For example: `/api/v2/pages/1/?fields=_,title,body` will return just the `title` and `body` of the page with the id of 1.
### Finding pages by HTML path
You can find an individual page by its HTML path using the `/api/v2/pages/find/?html_path=<path>` view.
This will return either a `302` redirect response to that page’s detail view, or a `404` not found response.
For example: `/api/v2/pages/find/?html_path=/` always redirects to the homepage of the site
Default endpoint fields
-----------------------
### Common fields
These fields are returned by every endpoint.
**`id` (number)** The unique ID of the object
Note
Except for page types, every other content type has its own id space so you must combine this with the `type` field in order to get a unique identifier for an object.
**`type` (string)** The type of the object in `app_label.ModelName` format
**`detail_url` (string)** The URL of the detail view for the object
### Pages
**`title` (string)** **`meta.slug` (string)** **`meta.show_in_menus` (boolean)** **`meta.seo_title` (string)** **`meta.search_description` (string)** **`meta.first_published_at` (date/time)** These values are taken from their corresponding fields on the page
**`meta.html_url` (string)** If the site has an HTML frontend that’s generated by Wagtail, this field will be set to the URL of this page
**`meta.parent`** Nests some information about the parent page (only available on detail views)
**`meta.alias_of` (dictionary)** If the page marked as an alias return original page id and full url
### Images
**`title` (string)** The value of the image’s title field. Within Wagtail, this is used in the image’s `alt` HTML attribute.
**`width` (number)** **`height` (number)** The size of the original image file
**`meta.tags` (list of strings)** A list of tags associated with the image
### Documents
**`title` (string)** The value of the document’s title field
**`meta.tags` (list of strings)** A list of tags associated with the document
**`meta.download_url` (string)** A URL to the document file
Changes since v1
----------------
### Breaking changes
* The results list in listing responses has been renamed to `items` (was previously either `pages`, `images` or `documents`)
### Major features
* The `fields` parameter has been improved to allow removing fields, adding all fields and customising nested fields
### Minor features
* `html_url`, `slug`, `first_published_at`, `expires_at` and `show_in_menus` fields have been added to the pages endpoint
* `download_url` field has been added to the documents endpoint
* Multiple page types can be specified in `type` parameter on pages endpoint
* `true` and `false` may now be used when filtering boolean fields
* `order` can now be used in conjunction with `search`
* `search_operator` parameter was added
| programming_docs |
wagtail Title generation on upload Title generation on upload
==========================
When uploading a file (document), Wagtail takes the filename, removes the file extension, and populates the title field. This section is about how to customise this filename to title conversion.
The filename to title conversion is used on the single file widget, multiple upload widget, and within chooser modals.
You can also customise this [same behaviour for images](../images/title_generation_on_upload).
You can customise the resolved value of this title using a JavaScript [event listener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) which will listen to the `'wagtail:documents-upload'` event.
The simplest way to add JavaScript to the editor is via the [`insert_global_admin_js` hook](../../reference/hooks#insert-global-admin-js), however any JavaScript that adds the event listener will work.
DOM Event
---------
The event name to listen for is `'wagtail:documents-upload'`. It will be dispatched on the document upload `form`. The event’s `detail` attribute will contain:
* `data` - An object which includes the `title` to be used. It is the filename with the extension removed.
* `maxTitleLength` - An integer (or `null`) which is the maximum length of the `Document` model title field.
* `filename` - The original filename without the extension removed.
To modify the generated `Document` title, access and update `event.detail.data.title`, no return value is needed.
For single document uploads, the custom event will only run if the title does not already have a value so that we do not overwrite whatever the user has typed.
You can prevent the default behaviour by calling `event.preventDefault()`. For the single upload page or modals, this will not pre-fill any value into the title. For multiple uploads, this will avoid any title submission and use the filename title only (with file extension) as a title is required to save the document.
The event will ‘bubble’ up so that you can simply add a global `document` listener to capture all of these events, or you can scope your listener or handler logic as needed to ensure you only adjust titles in some specific scenarios.
See MDN for more information about [custom JavasScript events](https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events).
Code Examples
-------------
### Adding the file extension to the start of the title
```
# wagtail_hooks.py
from django.utils.safestring import mark_safe
from wagtail import hooks
@hooks.register("insert_global_admin_js")
def get_global_admin_js():
return mark_safe(
"""
<script>
window.addEventListener('DOMContentLoaded', function () {
document.addEventListener('wagtail:documents-upload', function(event) {
var extension = (event.detail.filename.match(/\.([^.]*?)(?=\?|#|$)/) || [''])[1];
var newTitle = '(' + extension.toUpperCase() + ') ' + (event.detail.data.title || '');
event.detail.data.title = newTitle;
});
});
</script>
"""
)
```
### Changing generated titles on the page editor only to remove dashes/underscores
Using the [`insert_editor_js` hook](../../reference/hooks#insert-editor-js) instead so that this script will not run on the `Document` upload page, only on page editors.
```
# wagtail_hooks.py
from django.utils.safestring import mark_safe
from wagtail import hooks
@hooks.register("insert_editor_js")
def get_global_admin_js():
return mark_safe(
"""
<script>
window.addEventListener('DOMContentLoaded', function () {
document.addEventListener('wagtail:documents-upload', function(event) {
// replace dashes/underscores with a space
var newTitle = (event.detail.data.title || '').replace(/(\s|_|-)/g, " ");
event.detail.data.title = newTitle;
});
});
</script>
"""
)
```
### Stopping pre-filling of title based on filename
```
# wagtail_hooks.py
from django.utils.safestring import mark_safe
from wagtail import hooks
@hooks.register("insert_global_admin_js")
def get_global_admin_js():
return mark_safe(
"""
<script>
window.addEventListener('DOMContentLoaded', function () {
document.addEventListener('wagtail:documents-upload', function(event) {
// will stop title pre-fill on single file uploads
// will set the multiple upload title to the filename (with extension)
event.preventDefault();
});
});
</script>
"""
)
```
wagtail Documents Documents
=========
* [Custom document model](custom_document_model)
+ [Referring to the document model](custom_document_model#module-wagtail.documents)
* [Title generation on upload](title_generation_on_upload)
+ [DOM Event](title_generation_on_upload#dom-event)
+ [Code Examples](title_generation_on_upload#code-examples)
wagtail Custom document model Custom document model
=====================
An alternate `Document` model can be used to add custom behaviour and additional fields.
You need to complete the following steps in your project to do this:
* Create a new document model that inherits from `wagtail.documents.models.AbstractDocument`. This is where you would add additional fields.
* Point `WAGTAILDOCS_DOCUMENT_MODEL` to the new model.
Here’s an example:
```
# models.py
from django.db import models
from wagtail.documents.models import Document, AbstractDocument
class CustomDocument(AbstractDocument):
# Custom field example:
source = models.CharField(
max_length=255,
blank=True,
null=True
)
admin_form_fields = Document.admin_form_fields + (
# Add all custom fields names to make them appear in the form:
'source',
)
```
Then in your settings module:
```
# Ensure that you replace app_label with the app you placed your custom
# model in.
WAGTAILDOCS_DOCUMENT_MODEL = 'app_label.CustomDocument'
```
Note
Migrating from the builtin document model
When changing an existing site to use a custom document model, no documents will be copied to the new model automatically. Copying old documents to the new model would need to be done manually with a [data migration](https://docs.djangoproject.com/en/stable/topics/migrations/#data-migrations "(in Django v4.1)").
Any templates that reference the builtin document model will still continue to work as before.
Referring to the document model
-------------------------------
wagtail Generic views Generic views
=============
Wagtail provides a number of generic views for handling common tasks such as creating / editing model instances, and chooser modals. Since these often involve several related views with shared properties (such as the model that we’re working with, and its associated icon) Wagtail also implements the concept of a *viewset*, which allows a bundle of views to be defined collectively, and their URLs to be registered with the admin app as a single operation through the `register_admin_viewset` hook.
ModelViewSet
------------
The `wagtail.admin.viewsets.model.ModelViewSet` class provides the views for listing, creating, editing and deleting model instances. For example, if we have the following model:
```
from django.db import models
class Person(models.Model):
first_name = models.CharField(max_length=255)
last_name = models.CharField(max_length=255)
def __str__(self):
return "%s %s" % (self.first_name, self.last_name)
```
The following definition (to be placed in the same app’s `views.py`) will generate a set of views for managing Person instances:
```
from wagtail.admin.viewsets.model import ModelViewSet
from .models import Person
class PersonViewSet(ModelViewSet):
model = Person
form_fields = ["first_name", "last_name"]
icon = "user"
person_viewset = PersonViewSet("person") # defines /admin/person/ as the base URL
```
This viewset can then be registered with the Wagtail admin to make it available under the URL `/admin/person/`, by adding the following to `wagtail_hooks.py`:
```
from wagtail import hooks
from .views import person_viewset
@hooks.register("register_admin_viewset")
def register_viewset():
return person_viewset
```
Various additional attributes are available to customise the viewset - see [Viewsets](../reference/viewsets).
ChooserViewSet
--------------
The `wagtail.admin.viewsets.chooser.ChooserViewSet` class provides the views that make up a modal chooser interface, allowing users to select from a list of model instances to populate a ForeignKey field. Using the same `Person` model, the following definition (to be placed in `views.py`) will generate the views for a person chooser modal:
```
from wagtail.admin.viewsets.chooser import ChooserViewSet
class PersonChooserViewSet(ChooserViewSet):
# The model can be specified as either the model class or an "app_label.model_name" string;
# using a string avoids circular imports when accessing the StreamField block class (see below)
model = "myapp.Person"
icon = "user"
choose_one_text = "Choose a person"
choose_another_text = "Choose another person"
edit_item_text = "Edit this person"
form_fields = ["first_name", "last_name"] # fields to show in the "Create" tab
person_chooser_viewset = PersonChooserViewSet("person_chooser")
```
Again this can be registered with the `register_admin_viewset` hook:
```
from wagtail import hooks
from .views import person_chooser_viewset
@hooks.register("register_admin_viewset")
def register_viewset():
return person_chooser_viewset
```
Registering a chooser viewset will also set up a chooser widget to be used whenever a ForeignKey field to that model appears in a `WagtailAdminModelForm` - see [Using forms in admin views](forms). In particular, this means that a panel definition such as `FieldPanel("author")`, where `author` is a foreign key to the `Person` model, will automatically use this chooser interface. The chooser widget class can also be retrieved directly (for use in ordinary Django forms, for example) as the `widget_class` property on the viewset. For example, placing the following code in `widgets.py` will make the chooser widget available to be imported with `from myapp.widgets import PersonChooserWidget`:
```
from .views import person_chooser_viewset
PersonChooserWidget = person_chooser_viewset.widget_class
```
The viewset also makes a StreamField chooser block class available, through the method `get_block_class`. Placing the following code in `blocks.py` will make a chooser block available for use in StreamField definitions by importing `from myapp.blocks import PersonChooserBlock`:
```
from .views import person_chooser_viewset
PersonChooserBlock = person_chooser_viewset.get_block_class(
name="PersonChooserBlock", module_path="myapp.blocks"
)
```
Chooser viewsets for non-model datasources
------------------------------------------
While the generic chooser views are primarily designed to use Django models as the data source, choosers based on other sources such as REST API endpoints can be implemented by overriding the individual methods that deal with data retrieval.
Within `wagtail.admin.views.generic.chooser`:
* `BaseChooseView.get_object_list()` - returns a list of records to be displayed in the chooser. (In the default implementation, this is a Django QuerySet, and the records are model instances.)
* `BaseChooseView.columns` - a list of `wagtail.admin.ui.tables.Column` objects specifying the fields of the record to display in the final table
* `BaseChooseView.apply_object_list_ordering(objects)` - given a list of records as returned from `get_object_list`, returns the list with the desired ordering applied
* `ChosenViewMixin.get_object(pk)` - returns the record identified by the given primary key
* `ChosenResponseMixin.get_chosen_response_data(item)` - given a record, returns the dictionary of data that will be passed back to the chooser widget to populate it (consisting of items `id` and `title`, unless the chooser widget’s JavaScript has been customised)
Within `wagtail.admin.widgets`:
* `BaseChooser.get_instance(value)` - given a value that may be a record, a primary key or None, returns the corresponding record or None
* `BaseChooser.get_value_data_from_instance(item)` - given a record, returns the dictionary of data that will populate the chooser widget (consisting of items `id` and `title`, unless the widget’s JavaScript has been customised)
For example, the following code will implement a chooser that runs against a JSON endpoint for the User model at `http://localhost:8000/api/users/`, set up with Django REST Framework using the default configuration and no pagination:
```
from django.views.generic.base import View
import requests
from wagtail.admin.ui.tables import Column, TitleColumn
from wagtail.admin.views.generic.chooser import (
BaseChooseView, ChooseViewMixin, ChooseResultsViewMixin, ChosenResponseMixin, ChosenViewMixin, CreationFormMixin
)
from wagtail.admin.viewsets.chooser import ChooserViewSet
from wagtail.admin.widgets import BaseChooser
class BaseUserChooseView(BaseChooseView):
@property
def columns(self):
return [
TitleColumn(
"title",
label="Title",
accessor='username',
id_accessor='id',
url_name=self.chosen_url_name,
link_attrs={"data-chooser-modal-choice": True},
),
Column(
"email", label="Email", accessor="email"
)
]
def get_object_list(self):
r = requests.get("http://localhost:8000/api/users/")
r.raise_for_status()
results = r.json()
return results
def apply_object_list_ordering(self, objects):
return objects
class UserChooseView(ChooseViewMixin, CreationFormMixin, BaseUserChooseView):
pass
class UserChooseResultsView(ChooseResultsViewMixin, CreationFormMixin, BaseUserChooseView):
pass
class UserChosenViewMixin(ChosenViewMixin):
def get_object(self, pk):
r = requests.get("http://localhost:8000/api/users/%d/" % int(pk))
r.raise_for_status()
return r.json()
class UserChosenResponseMixin(ChosenResponseMixin):
def get_chosen_response_data(self, item):
return {
"id": item["id"],
"title": item["username"],
}
class UserChosenView(UserChosenViewMixin, UserChosenResponseMixin, View):
pass
class BaseUserChooserWidget(BaseChooser):
def get_instance(self, value):
if value is None:
return None
elif isinstance(value, dict):
return value
else:
r = requests.get("http://localhost:8000/api/users/%d/" % int(value))
r.raise_for_status()
return r.json()
def get_value_data_from_instance(self, instance):
return {
"id": instance["id"],
"title": instance["username"],
}
class UserChooserViewSet(ChooserViewSet):
icon = "user"
choose_one_text = "Choose a user"
choose_another_text = "Choose another user"
edit_item_text = "Edit this user"
choose_view_class = UserChooseView
choose_results_view_class = UserChooseResultsView
chosen_view_class = UserChosenView
base_widget_class = BaseUserChooserWidget
user_chooser_viewset = UserChooserViewSet("user_chooser", url_prefix="user-chooser")
```
If the data source implements its own pagination - meaning that the pagination mechanism built into the chooser should be bypassed - the `BaseChooseView.get_results_page(request)` method can be overridden instead of `get_object_list`. This should return an instance of `django.core.paginator.Page`. For example, if the API in the above example followed the conventions of the Wagtail API, implementing pagination with `offset` and `limit` URL parameters and returning a dict consisting of `meta` and `results`, the `BaseUserChooseView` implementation could be modified as follows:
```
from django.core.paginator import Page, Paginator
class APIPaginator(Paginator):
"""
Customisation of Django's Paginator class for use when we don't want it to handle
slicing on the result set, but still want it to generate the page numbering based
on a known result count.
"""
def __init__(self, count, per_page, **kwargs):
self._count = int(count)
super().__init__([], per_page, **kwargs)
@property
def count(self):
return self._count
class BaseUserChooseView(BaseChooseView):
@property
def columns(self):
return [
TitleColumn(
"title",
label="Title",
accessor='username',
id_accessor='id',
url_name=self.chosen_url_name,
link_attrs={"data-chooser-modal-choice": True},
),
Column(
"email", label="Email", accessor="email"
)
]
def get_results_page(self, request):
try:
page_number = int(request.GET.get('p', 1))
except ValueError:
page_number = 1
r = requests.get("http://localhost:8000/api/users/", params={
'offset': (page_number - 1) * self.per_page,
'limit': self.per_page,
})
r.raise_for_status()
result = r.json()
paginator = APIPaginator(result['meta']['total_count'], self.per_page)
page = Page(result['items'], page_number, paginator)
return page
```
wagtail Adding reports Adding reports
==============
Reports are views with listings of pages matching a specific query. They can also export these listings in spreadsheet format. They are found in the *Reports* submenu: by default, the *Locked pages* report is provided, allowing an overview of locked pages on the site.
It is possible to create your own custom reports in the Wagtail admin. Two base classes are provided: `wagtail.admin.views.reports.ReportView`, which provides basic listing and spreadsheet export functionality, and `wagtail.admin.views.reports.PageReportView`, which additionally provides a default set of fields suitable for page listings. For this example, we’ll add a report which shows any pages with unpublished changes.
```
# <project>/views.py
from wagtail.admin.views.reports import PageReportView
class UnpublishedChangesReportView(PageReportView):
pass
```
Defining your report
--------------------
The most important attributes and methods to customise to define your report are:
This retrieves the queryset of pages for your report. For our example:
```
# <project>/views.py
from wagtail.admin.views.reports import PageReportView
from wagtail.models import Page
class UnpublishedChangesReportView(PageReportView):
def get_queryset(self):
return Page.objects.filter(has_unpublished_changes=True)
```
(string)
The template used to render your report. For `ReportView`, this defaults to `"wagtailadmin/reports/base_report.html"`, which provides an empty report page layout; for `PageReportView`, this defaults to `"wagtailadmin/reports/base_page_report.html"` which provides a listing based on the explorer views, displaying action buttons, as well as the title, time of the last update, status, and specific type of any pages. In this example, we’ll change this to a new template in a later section.
(string)
The name of your report, which will be displayed in the header. For our example, we’ll set it to `"Pages with unpublished changes"`.
(string)
The name of the icon, using the standard Wagtail icon names. For example, the locked pages view uses `"locked"`, and for our example report, we’ll set it to `'doc-empty-inverse'`.
Spreadsheet exports
-------------------
(list)
A list of the fields/attributes for each model which are exported as columns in the spreadsheet view. For `ReportView`, this is empty by default, and for `PageReportView`, it corresponds to the listing fields: the title, time of the last update, status, and specific type of any pages. For our example, we might want to know when the page was last published, so we’ll set `list_export` as follows:
`list_export = PageReportView.list_export + ['last_published_at']`
(dictionary)
A dictionary of any fields/attributes in `list_export` for which you wish to manually specify a heading for the spreadsheet column, and their headings. If unspecified, the heading will be taken from the field `verbose_name` if applicable, and the attribute string otherwise. For our example, `last_published_at` will automatically get a heading of `"Last Published At"`, but a simple “Last Published” looks neater. We’ll add that by setting `export_headings`:
`export_headings = dict(last_published_at='Last Published', **PageReportView.export_headings)`
(dictionary)
A dictionary of `(value_class_1, value_class_2, ...)` tuples mapping to `{export_format: preprocessing_function}` dictionaries, allowing custom preprocessing functions to be applied when exporting field values of specific classes (or their subclasses). If unspecified (and `ReportView.custom_field_preprocess` also does not specify a function), `force_str` will be used. To prevent preprocessing, set the preprocessing\_function to `None`.
(dictionary)
A dictionary of `field_name` strings mapping to `{export_format: preprocessing_function}` dictionaries, allowing custom preprocessing functions to be applied when exporting field values of specific classes (or their subclasses). This will take priority over functions specified in `ReportView.custom_value_preprocess`. If unspecified (and `ReportView.custom_value_preprocess` also does not specify a function), `force_str` will be used. To prevent preprocessing, set the preprocessing\_function to `None`.
Customising templates
---------------------
For this example “pages with unpublished changes” report, we’ll add an extra column to the listing template, showing the last publication date for each page. To do this, we’ll extend two templates: `wagtailadmin/reports/base_page_report.html`, and `wagtailadmin/reports/listing/_list_page_report.html`.
```
{# <project>/templates/reports/unpublished_changes_report.html #}
{% extends 'wagtailadmin/reports/base_page_report.html' %}
{% block listing %}
{% include 'reports/include/_list_unpublished_changes.html' %}
{% endblock %}
{% block no_results %}
<p>No pages with unpublished changes.</p>
{% endblock %}
```
```
{# <project>/templates/reports/include/_list_unpublished_changes.html #}
{% extends 'wagtailadmin/reports/listing/_list_page_report.html' %}
{% block extra_columns %}
<th>Last Published</th>
{% endblock %}
{% block extra_page_data %}
<td valign="top">
{{ page.last_published_at }}
</td>
{% endblock %}
```
Finally, we’ll set `UnpublishedChangesReportView.template_name` to this new template: `'reports/unpublished_changes_report.html'`.
Adding a menu item and admin URL
--------------------------------
To add a menu item for your new report to the *Reports* submenu, you will need to use the `register_reports_menu_item` hook (see: [Register Reports Menu Item](../reference/hooks#register-reports-menu-item)). To add an admin url for the report, you will need to use the `register_admin_urls` hook (see: [Register Admin URLs](../reference/hooks#register-admin-urls)). This can be done as follows:
```
# <project>/wagtail_hooks.py
from django.urls import path, reverse
from wagtail.admin.menu import AdminOnlyMenuItem
from wagtail import hooks
from .views import UnpublishedChangesReportView
@hooks.register('register_reports_menu_item')
def register_unpublished_changes_report_menu_item():
return AdminOnlyMenuItem("Pages with unpublished changes", reverse('unpublished_changes_report'), classnames='icon icon-' + UnpublishedChangesReportView.header_icon, order=700)
@hooks.register('register_admin_urls')
def register_unpublished_changes_report_url():
return [
path('reports/unpublished-changes/', UnpublishedChangesReportView.as_view(), name='unpublished_changes_report'),
]
```
Here, we use the `AdminOnlyMenuItem` class to ensure our report icon is only shown to superusers. To make the report visible to all users, you could replace this with `MenuItem`.
The full code
-------------
```
# <project>/views.py
from wagtail.admin.views.reports import PageReportView
from wagtail.models import Page
class UnpublishedChangesReportView(PageReportView):
header_icon = 'doc-empty-inverse'
template_name = 'reports/unpublished_changes_report.html'
title = "Pages with unpublished changes"
list_export = PageReportView.list_export + ['last_published_at']
export_headings = dict(last_published_at='Last Published', **PageReportView.export_headings)
def get_queryset(self):
return Page.objects.filter(has_unpublished_changes=True)
```
```
# <project>/wagtail_hooks.py
from django.urls import path, reverse
from wagtail.admin.menu import AdminOnlyMenuItem
from wagtail import hooks
from .views import UnpublishedChangesReportView
@hooks.register('register_reports_menu_item')
def register_unpublished_changes_report_menu_item():
return AdminOnlyMenuItem("Pages with unpublished changes", reverse('unpublished_changes_report'), classnames='icon icon-' + UnpublishedChangesReportView.header_icon, order=700)
@hooks.register('register_admin_urls')
def register_unpublished_changes_report_url():
return [
path('reports/unpublished-changes/', UnpublishedChangesReportView.as_view(), name='unpublished_changes_report'),
]
```
```
{# <project>/templates/reports/unpublished_changes_report.html #}
{% extends 'wagtailadmin/reports/base_page_report.html' %}
{% block listing %}
{% include 'reports/include/_list_unpublished_changes.html' %}
{% endblock %}
{% block no_results %}
<p>No pages with unpublished changes.</p>
{% endblock %}
```
```
{# <project>/templates/reports/include/_list_unpublished_changes.html #}
{% extends 'wagtailadmin/reports/listing/_list_page_report.html' %}
{% block extra_columns %}
<th>Last Published</th>
{% endblock %}
{% block extra_page_data %}
<td valign="top">
{{ page.last_published_at }}
</td>
{% endblock %}
```
| programming_docs |
wagtail Extending Wagtail Extending Wagtail
=================
The Wagtail admin interface is a suite of Django apps, and so the familiar concepts from Django development - views, templates, URL routes and so on - can be used to add new functionality to Wagtail. Numerous [third-party packages](https://wagtail.org/packages/) can be installed to extend Wagtail’s capabilities.
This section describes the various mechanisms that can be used to integrate your own code into Wagtail’s admin interface.
* [Creating admin views](admin_views)
+ [Defining a view](admin_views#defining-a-view)
+ [Registering a URL route](admin_views#registering-a-url-route)
+ [Adding a template](admin_views#adding-a-template)
+ [Adding a menu item](admin_views#adding-a-menu-item)
+ [Adding a group of menu items](admin_views#adding-a-group-of-menu-items)
* [Generic views](generic_views)
+ [ModelViewSet](generic_views#modelviewset)
+ [ChooserViewSet](generic_views#chooserviewset)
+ [Chooser viewsets for non-model datasources](generic_views#chooser-viewsets-for-non-model-datasources)
* [Template components](template_components)
+ [`render_html()`](template_components#render_html)
+ [`media`](template_components#media)
+ [Creating components](template_components#creating-components)
+ [Passing context to the template](template_components#passing-context-to-the-template)
+ [Adding media definitions](template_components#adding-media-definitions)
+ [Using components on your own templates](template_components#using-components-on-your-own-templates)
* [Using forms in admin views](forms)
+ [Defining admin form widgets](forms#defining-admin-form-widgets)
+ [Panels](forms#panels)
* [Adding reports](adding_reports)
+ [Defining your report](adding_reports#defining-your-report)
+ [Spreadsheet exports](adding_reports#spreadsheet-exports)
+ [Customising templates](adding_reports#customising-templates)
+ [Adding a menu item and admin URL](adding_reports#adding-a-menu-item-and-admin-url)
+ [The full code](adding_reports#the-full-code)
* [Adding new Task types](custom_tasks)
+ [Task models](custom_tasks#task-models)
+ [Custom TaskState models](custom_tasks#custom-taskstate-models)
+ [Customising behaviour](custom_tasks#customising-behaviour)
+ [Adding notifications](custom_tasks#adding-notifications)
* [Audit log](audit_log)
+ [`log()`](audit_log#log)
+ [Log actions provided by Wagtail](audit_log#log-actions-provided-by-wagtail)
+ [Log context](audit_log#log-context)
+ [Log models](audit_log#log-models)
* [Customising the user account settings form](custom_account_settings)
+ [Adding new panels](custom_account_settings#adding-new-panels)
+ [Operating on the `UserProfile` model](custom_account_settings#operating-on-the-userprofile-model)
+ [Creating new tabs](custom_account_settings#creating-new-tabs)
+ [Customising the template](custom_account_settings#customising-the-template)
* [Customising group edit/create views](customising_group_views)
+ [Custom edit/create forms](customising_group_views#custom-edit-create-forms)
* [Rich text internals](rich_text_internals)
+ [Data format](rich_text_internals#data-format)
+ [The feature registry](rich_text_internals#the-feature-registry)
+ [Rewrite handlers](rich_text_internals#rewrite-handlers)
+ [Editor widgets](rich_text_internals#editor-widgets)
+ [Editor plugins](rich_text_internals#editor-plugins)
+ [Format converters](rich_text_internals#format-converters)
* [Extending the Draftail Editor](extending_draftail)
+ [Creating new inline styles](extending_draftail#creating-new-inline-styles)
+ [Creating new blocks](extending_draftail#creating-new-blocks)
+ [Creating new entities](extending_draftail#creating-new-entities)
+ [Integration of the Draftail widgets](extending_draftail#integration-of-the-draftail-widgets)
* [Adding custom bulk actions](custom_bulk_actions)
+ [Registering a custom bulk action](custom_bulk_actions#registering-a-custom-bulk-action)
+ [Adding bulk actions to the page explorer](custom_bulk_actions#adding-bulk-actions-to-the-page-explorer)
+ [Adding bulk actions to the Images listing](custom_bulk_actions#adding-bulk-actions-to-the-images-listing)
+ [Adding bulk actions to the documents listing](custom_bulk_actions#adding-bulk-actions-to-the-documents-listing)
+ [Adding bulk actions to the user listing](custom_bulk_actions#adding-bulk-actions-to-the-user-listing)
+ [Adding bulk actions to the snippets listing](custom_bulk_actions#adding-bulk-actions-to-the-snippets-listing)
wagtail Customising the user account settings form Customising the user account settings form
==========================================
This document describes how to customise the user account settings form that can be found by clicking “Account settings” at the bottom of the main menu.
Adding new panels
-----------------
Each panel on this form is a separate model form which can operate on an instance of either the user model, or the `wagtail.users.models.UserProfile`.
### Basic example
Here is an example of how to add a new form that operates on the user model:
```
# forms.py
from django import forms
from django.contrib.auth import get_user_model
class CustomSettingsForm(forms.ModelForm):
class Meta:
model = get_user_model()
fields = [...]
```
```
# hooks.py
from wagtail.admin.views.account import BaseSettingsPanel
from wagtail import hooks
from .forms import CustomSettingsForm
@hooks.register('register_account_settings_panel')
class CustomSettingsPanel(BaseSettingsPanel):
name = 'custom'
title = "My custom settings"
order = 500
form_class = CustomSettingsForm
form_object = 'user'
```
The attributes are as follows:
* `name` - A unique name for the panel. All form fields are prefixed with this name, so it must be lowercase and cannot contain symbols -
* `title` - The heading that is displayed to the user
* `order` - Used to order panels on a tab. The builtin Wagtail panels start at `100` and increase by `100` for each panel.
* `form_class` - A `ModelForm` subclass that operates on a user or a profile
* `form_object` - Set to `user` to operate on the user, and `profile` to operate on the profile
* `tab` (optional) - Set which tab the panel appears on.
* `template_name` (optional) - Override the default template used for rendering the panel
Operating on the `UserProfile` model
------------------------------------
To add a panel that alters data on the user’s `wagtail.users.models.UserProfile` instance, set `form_object` to `'profile'`:
```
# forms.py
from django import forms
from wagtail.users.models import UserProfile
class CustomProfileSettingsForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = [...]
```
```
# hooks.py
from wagtail.admin.views.account import BaseSettingsPanel
from wagtail import hooks
from .forms import CustomProfileSettingsForm
@hooks.register('register_account_settings_panel')
class CustomSettingsPanel(BaseSettingsPanel):
name = 'custom'
title = "My custom settings"
order = 500
form_class = CustomProfileSettingsForm
form_object = 'profile'
```
Creating new tabs
-----------------
You can define a new tab using the `SettingsTab` class:
```
# hooks.py
from wagtail.admin.views.account import BaseSettingsPanel, SettingsTab
from wagtail import hooks
from .forms import CustomSettingsForm
custom_tab = SettingsTab('custom', "Custom settings", order=300)
@hooks.register('register_account_settings_panel')
class CustomSettingsPanel(BaseSettingsPanel):
name = 'custom'
title = "My custom settings"
tab = custom_tab
order = 100
form_class = CustomSettingsForm
```
`SettingsTab` takes three arguments:
* `name` - A slug to use for the tab (this is placed after the `#` when linking to a tab)
* `title` - The display name of the title
* `order` - The order of the tab. The builtin Wagtail tabs start at `100` and increase by `100` for each tab
Customising the template
------------------------
You can provide a custom template for the panel by specifying a template name:
```
# hooks.py
from wagtail.admin.views.account import BaseSettingsPanel
from wagtail import hooks
from .forms import CustomSettingsForm
@hooks.register('register_account_settings_panel')
class CustomSettingsPanel(BaseSettingsPanel):
name = 'custom'
title = "My custom settings"
order = 500
form_class = CustomSettingsForm
template_name = 'myapp/admin/custom_settings.html'
```
```
{# templates/myapp/admin/custom_settings.html #}
{# This is the default template Wagtail uses, which just renders the form #}
{% block content %}
{% for field in form %}
{% include "wagtailadmin/shared/field.html" with field=field %}
{% endfor %}
{% endblock %}
```
wagtail Adding custom bulk actions Adding custom bulk actions
==========================
This document describes how to add custom bulk actions to different listings.
Registering a custom bulk action
--------------------------------
```
from wagtail.admin.views.bulk_action import BulkAction
from wagtail import hooks
@hooks.register('register_bulk_action')
class CustomDeleteBulkAction(BulkAction):
display_name = _("Delete")
aria_label = _("Delete selected objects")
action_type = "delete"
template_name = "/path/to/confirm_bulk_delete.html"
models = [...]
@classmethod
def execute_action(cls, objects, **kwargs):
for obj in objects:
do_something(obj)
return num_parent_objects, num_child_objects # return the count of updated objects
```
The attributes are as follows:
* `display_name` - The label that will be displayed on the button in the user interface
* `aria_label` - The `aria-label` attribute that will be applied to the button in the user interface
* `action_type` - A unique identifier for the action. Will be required in the url for bulk actions
* `template_name` - The path to the confirmation template
* `models` - A list of models on which the bulk action can act
* `action_priority` (optional) - A number that is used to determine the placement of the button in the list of buttons
* `classes` (optional) - A set of CSS classnames that will be used on the button in the user interface
An example for a confirmation template is as follows:
```
<!-- /path/to/confirm_bulk_delete.html -->
{% extends 'wagtailadmin/bulk_actions/confirmation/base.html' %}
{% load i18n wagtailadmin_tags %}
{% block titletag %}{% blocktrans trimmed count counter=items|length %}Delete 1 item{% plural %}Delete {{ counter }} items{% endblocktrans %}{% endblock %}
{% block header %}
{% trans "Delete" as del_str %}
{% include "wagtailadmin/shared/header.html" with title=del_str icon="doc-empty-inverse" %}
{% endblock header %}
{% block items_with_access %}
{% if items %}
<p>{% trans "Are you sure you want to delete these items?" %}</p>
<ul>
{% for item in items %}
<li>
<a href="" target="_blank" rel="noreferrer">{{ item.item.title }}</a>
</li>
{% endfor %}
</ul>
{% endif %}
{% endblock items_with_access %}
{% block items_with_no_access %}
{% blocktrans trimmed asvar no_access_msg count counter=items_with_no_access|length %}You don't have permission to delete this item{% plural %}You don't have permission to delete these items{% endblocktrans %}
{% include './list_items_with_no_access.html' with items=items_with_no_access no_access_msg=no_access_msg %}
{% endblock items_with_no_access %}
{% block form_section %}
{% if items %}
{% trans 'Yes, delete' as action_button_text %}
{% trans "No, don't delete" as no_action_button_text %}
{% include 'wagtailadmin/bulk_actions/confirmation/form.html' with action_button_class="serious" %}
{% else %}
{% include 'wagtailadmin/bulk_actions/confirmation/go_back.html' %}
{% endif %}
{% endblock form_section %}
```
```
<!-- ./list_items_with_no_access.html -->
{% extends 'wagtailadmin/bulk_actions/confirmation/list_items_with_no_access.html' %}
{% load i18n %}
{% block per_item %}
{% if item.can_edit %}
<a href="{% url 'wagtailadmin_pages:edit' item.item.id %}" target="_blank" rel="noreferrer">{{ item.item.title }}</a>
{% else %}
{{ item.item.title }}
{% endif %}
{% endblock per_item %}
```
The `execute_action` classmethod is the only method that must be overridden for the bulk action to work properly. It takes a list of objects as the only required argument, and a bunch of keyword arguments that can be supplied by overriding the `get_execution_context` method. For example.
```
@classmethod
def execute_action(cls, objects, **kwargs):
# the kwargs here is the output of the get_execution_context method
user = kwargs.get('user', None)
num_parent_objects, num_child_objects = 0, 0
# you could run the action per object or run them in bulk using django's bulk update and delete methods
for obj in objects:
num_child_objects += obj.get_children().count()
num_parent_objects += 1
obj.delete(user=user)
num_parent_objects += 1
return num_parent_objects, num_child_objects
```
The `get_execution_context` method can be overridden to provide context to the `execute_action`
```
def get_execution_context(self):
return { 'user': self.request.user }
```
The `get_context_data` method can be overridden to pass additional context to the confirmation template.
```
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['new_key'] = some_value
return context
```
Thes `check_perm` method can be overridden to check if an object has some permission or not. objects for which the `check_perm` returns `False` will be available in the context under the key `'items_with_no_access'`.
```
def check_perm(self, obj):
return obj.has_perm('some_perm') # returns True or False
```
The success message shown on the admin can be customised by overriding the `get_success_message` method.
```
def get_success_message(self, num_parent_objects, num_child_objects):
return _("{} objects, including {} child objects have been updated".format(num_parent_objects, num_child_objects))
```
Adding bulk actions to the page explorer
----------------------------------------
When creating a custom bulk action class for pages, subclass from `wagtail.admin.views.pages.bulk_actions.page_bulk_action.PageBulkAction` instead of `wagtail.admin.views.bulk_action.BulkAction`
### Basic example
```
from wagtail.admin.views.pages.bulk_actions.page_bulk_action import PageBulkAction
from wagtail import hooks
@hooks.register('register_bulk_action')
class CustomPageBulkAction(PageBulkAction):
...
```
Adding bulk actions to the Images listing
-----------------------------------------
When creating a custom bulk action class for images, subclass from `wagtail.images.views.bulk_actions.image_bulk_action.ImageBulkAction` instead of `wagtail.admin.views.bulk_action.BulkAction`
### Basic example
```
from wagtail.images.views.bulk_actions.image_bulk_action import ImageBulkAction
from wagtail import hooks
@hooks.register('register_bulk_action')
class CustomImageBulkAction(ImageBulkAction):
...
```
Adding bulk actions to the documents listing
--------------------------------------------
When creating a custom bulk action class for documents, subclass from `wagtail.documents.views.bulk_actions.document_bulk_action.DocumentBulkAction` instead of `wagtail.admin.views.bulk_action.BulkAction`
### Basic example
```
from wagtail.documents.views.bulk_actions.document_bulk_action import DocumentBulkAction
from wagtail import hooks
@hooks.register('register_bulk_action')
class CustomDocumentBulkAction(DocumentBulkAction):
...
```
Adding bulk actions to the user listing
---------------------------------------
When creating a custom bulk action class for users, subclass from `wagtail.users.views.bulk_actions.user_bulk_action.UserBulkAction` instead of `wagtail.admin.views.bulk_action.BulkAction`
### Basic example
```
from wagtail.users.views.bulk_actions.user_bulk_action import UserBulkAction
from wagtail import hooks
@hooks.register('register_bulk_action')
class CustomUserBulkAction(UserBulkAction):
...
```
Adding bulk actions to the snippets listing
-------------------------------------------
When creating a custom bulk action class for snippets, subclass from `wagtail.snippets.bulk_actions.snippet_bulk_action.SnippetBulkAction` instead of `wagtail.admin.views.bulk_action.BulkAction`
### Basic example
```
from wagtail.snippets.bulk_actions.snippet_bulk_action import SnippetBulkAction
from wagtail import hooks
@hooks.register('register_bulk_action')
class CustomSnippetBulkAction(SnippetBulkAction):
# ...
```
If you want to apply an action only to certain snippets, override the `models` list in the action class
```
from wagtail.snippets.bulk_actions.snippet_bulk_action import SnippetBulkAction
from wagtail import hooks
@hooks.register('register_bulk_action')
class CustomSnippetBulkAction(SnippetBulkAction):
models = [SnippetA, SnippetB]
# ...
```
wagtail Customising group edit/create views Customising group edit/create views
===================================
The views for managing groups within the app are collected into a ‘viewset’ class, which acts as a single point of reference for all shared components of those views, such as forms. By subclassing the viewset, it is possible to override those components and customise the behaviour of the group management interface.
Custom edit/create forms
------------------------
This example shows how to customise forms on the ‘edit group’ and ‘create group’ views in the Wagtail admin.
Let’s say you need to connect Active Directory groups with Django groups. We create a model for Active Directory groups as follows:
```
from django.contrib.auth.models import Group
from django.db import models
class ADGroup(models.Model):
guid = models.CharField(verbose_name="GUID", max_length=64, db_index=True, unique=True)
name = models.CharField(verbose_name="Group", max_length=255)
domain = models.CharField(verbose_name="Domain", max_length=255, db_index=True)
description = models.TextField(verbose_name="Description", blank=True, null=True)
roles = models.ManyToManyField(Group, verbose_name="Role", related_name="adgroups", blank=True)
class Meta:
verbose_name = "AD group"
verbose_name_plural = "AD groups"
```
However, there is no role field on the Wagtail group ‘edit’ or ‘create’ view. To add it, inherit from `wagtail.users.forms.GroupForm` and add a new field:
```
from django import forms
from wagtail.users.forms import GroupForm as WagtailGroupForm
from .models import ADGroup
class GroupForm(WagtailGroupForm):
adgroups = forms.ModelMultipleChoiceField(
label="AD groups",
required=False,
queryset=ADGroup.objects.order_by("name"),
)
class Meta(WagtailGroupForm.Meta):
fields = WagtailGroupForm.Meta.fields + ("adgroups",)
def __init__(self, initial=None, instance=None, **kwargs):
if instance is not None:
if initial is None:
initial = {}
initial["adgroups"] = instance.adgroups.all()
super().__init__(initial=initial, instance=instance, **kwargs)
def save(self, commit=True):
instance = super().save()
instance.adgroups.set(self.cleaned_data["adgroups"])
return instance
```
Now add your custom form into the group viewset by inheriting the default Wagtail `GroupViewSet` class and overriding the `get_form_class` method.
```
from wagtail.users.views.groups import GroupViewSet as WagtailGroupViewSet
from .forms import GroupForm
class GroupViewSet(WagtailGroupViewSet):
def get_form_class(self, for_update=False):
return GroupForm
```
Add the field to the group ‘edit’/’create’ templates:
```
{% extends "wagtailusers/groups/edit.html" %}
{% load wagtailusers_tags wagtailadmin_tags i18n %}
{% block extra_fields %}
<li>{% include "wagtailadmin/shared/field.html" with field=form.adgroups %}</li>
{% endblock extra_fields %}
```
Finally we configure the `wagtail.users` application to use the custom viewset, by setting up a custom `AppConfig` class. Within your project folder (which will be the package containing the top-level settings and urls modules), create `apps.py` (if it does not exist already) and add:
```
from wagtail.users.apps import WagtailUsersAppConfig
class CustomUsersAppConfig(WagtailUsersAppConfig):
group_viewset = "myapplication.someapp.viewsets.GroupViewSet"
```
Replace `wagtail.users` in `settings.INSTALLED_APPS` with the path to `CustomUsersAppConfig`.
```
INSTALLED_APPS = [
...,
"myapplication.apps.CustomUsersAppConfig",
# "wagtail.users",
...,
]
```
| programming_docs |
wagtail Audit log Audit log
=========
Wagtail provides a mechanism to log actions performed on its objects. Common activities such as page creation, update, deletion, locking and unlocking, revision scheduling and privacy changes are automatically logged at the model level.
The Wagtail admin uses the action log entries to provide a site-wide and page specific history of changes. It uses a registry of ‘actions’ that provide additional context for the logged action.
The audit log-driven Page history replaces the revisions list page, but provide a filter for revision-specific entries.
Note
The audit log does not replace revisions.
The `wagtail.log_actions.log` function can be used to add logging to your own code.
Note
When adding logging, you need to log the action or actions that happen to the object. For example, if the user creates and publishes a page, there should be a “create” entry and a “publish” entry. Or, if the user copies a published page and chooses to keep it published, there should be a “copy” and a “publish” entry for new page.
```
# mypackage/views.py
from wagtail.log_actions import log
def copy_for_translation(page):
# ...
page.copy(log_action='mypackage.copy_for_translation')
def my_method(request, page):
# ..
# Manually log an action
data = {
'make': {'it': 'so'}
}
log(
instance=page, action='mypackage.custom_action', data=data
)
```
Changed in version 2.15: The `log` function was added. Previously, logging was only implemented for pages, and invoked through the `PageLogEntry.objects.log_action` method.
Log actions provided by Wagtail
-------------------------------
| Action | Notes |
| --- | --- |
| `wagtail.create` | The object was created |
| `wagtail.edit` | The object was edited (for pages, saved as draft) |
| `wagtail.delete` | The object was deleted. Will only surface in the Site History for administrators |
| `wagtail.publish` | The page was published |
| `wagtail.publish.schedule` | Draft is scheduled for publishing |
| `wagtail.publish.scheduled` | Draft published via `publish_scheduled` management command |
| `wagtail.schedule.cancel` | Draft scheduled for publishing cancelled via “Cancel scheduled publish” |
| `wagtail.unpublish` | The page was unpublished |
| `wagtail.unpublish.scheduled` | Page unpublished via `publish_scheduled` management command |
| `wagtail.lock` | Page was locked |
| `wagtail.unlock` | Page was unlocked |
| `wagtail.moderation.approve` | The revision was approved for moderation |
| `wagtail.moderation.reject` | The revision was rejected |
| `wagtail.rename` | A page was renamed |
| `wagtail.revert` | The page was reverted to a previous draft |
| `wagtail.copy` | The page was copied to a new location |
| `wagtail.copy_for_translation` | The page was copied into a new locale for translation |
| `wagtail.move` | The page was moved to a new location |
| `wagtail.reorder` | The order of the page under it’s parent was changed |
| `wagtail.view_restriction.create` | The page was restricted |
| `wagtail.view_restriction.edit` | The page restrictions were updated |
| `wagtail.view_restriction.delete` | The page restrictions were removed |
| `wagtail.workflow.start` | The page was submitted for moderation in a Workflow |
| `wagtail.workflow.approve` | The draft was approved at a Workflow Task |
| `wagtail.workflow.reject` | The draft was rejected, and changes requested at a Workflow Task |
| `wagtail.workflow.resume` | The draft was resubmitted to the workflow |
| `wagtail.workflow.cancel` | The workflow was cancelled |
Log context
-----------
The `wagtail.log_actions` module provides a context manager to simplify code that logs a large number of actions, such as import scripts:
```
from wagtail.log_actions import LogContext
with LogContext(user=User.objects.get(username='admin')):
# ...
log(page, 'wagtail.edit')
# ...
log(page, 'wagtail.publish')
```
All `log` calls within the block will then be attributed to the specified user, and assigned a common UUID. A log context is created automatically for views within the Wagtail admin.
Log models
----------
Logs are stored in the database via the models `wagtail.models.PageLogEntry` (for actions on Page instances) and `wagtail.models.ModelLogEntry` (for actions on all other models). Page logs are stored in their own model to ensure that reports can be filtered according to the current user’s permissions, which could not be done efficiently with a generic foreign key.
If your own models have complex reporting requirements that would make `ModelLogEntry` unsuitable, you can configure them to be logged to their own log model; this is done by subclassing the abstract `wagtail.models.BaseLogEntry` model, and registering that model with the log registry’s `register_model` method:
```
from myapp.models import Sprocket, SprocketLogEntry
# here SprocketLogEntry is a subclass of BaseLogEntry
@hooks.register('register_log_actions')
def sprocket_log_model(actions):
actions.register_model(Sprocket, SprocketLogEntry)
```
wagtail Using forms in admin views Using forms in admin views
==========================
[Django’s forms framework](https://docs.djangoproject.com/en/stable/topics/forms/) can be used within Wagtail admin views just like in any other Django app. However, Wagtail also provides various admin-specific form widgets, such as date/time pickers and choosers for pages, documents, images and snippets. By constructing forms using `wagtail.admin.forms.models.WagtailAdminModelForm` as the base class instead of `django.forms.models.ModelForm`, the most appropriate widget will be selected for each model field. For example, given the model and form definition:
```
from django.db import models
from wagtail.admin.forms.models import WagtailAdminModelForm
from wagtail.images.models import Image
class FeaturedImage(models.Model):
date = models.DateField()
image = models.ForeignKey(Image, on_delete=models.CASCADE)
class FeaturedImageForm(WagtailAdminModelForm):
class Meta:
model = FeaturedImage
```
the `date` and `image` fields on the form will use a date picker and image chooser widget respectively.
Defining admin form widgets
---------------------------
If you have implemented a form widget of your own, you can configure `WagtailAdminModelForm` to select it for a given model field type. This is done by calling the `wagtail.admin.forms.models.register_form_field_override` function, typically in an `AppConfig.ready` method.
For example, if the app `wagtail.videos` implements a `Video` model and a `VideoChooser` form widget, the following AppConfig definition will ensure that `WagtailAdminModelForm` selects `VideoChooser` as the form widget for any foreign keys pointing to `Video`:
```
from django.apps import AppConfig
from django.db.models import ForeignKey
class WagtailVideosAppConfig(AppConfig):
name = 'wagtail.videos'
label = 'wagtailvideos'
def ready(self):
from wagtail.admin.forms.models import register_form_field_override
from .models import Video
from .widgets import VideoChooser
register_form_field_override(ForeignKey, to=Video, override={'widget': VideoChooser})
```
Wagtail’s edit views for pages, snippets and ModelAdmin use `WagtailAdminModelForm` as standard, so this change will take effect across the Wagtail admin; a foreign key to `Video` on a page model will automatically use the `VideoChooser` widget, with no need to specify this explicitly.
Panels
------
Panels (also known as edit handlers until Wagtail 3.0) are Wagtail’s mechanism for specifying the content and layout of a model form without having to write a template. They are used for the editing interface for pages and snippets, as well as the [ModelAdmin](../reference/contrib/modeladmin/index) and [site settings](../reference/contrib/settings) contrib modules.
See [Panel types](../reference/pages/panels) for the set of panel types provided by Wagtail. All panels inherit from the base class `wagtail.admin.panels.Panel`. A single panel object (usually `ObjectList` or `TabbedInterface`) exists at the top level and is the only one directly accessed by the view code; panels containing child panels inherit from the base class `wagtail.admin.panels.PanelGroup` and take care of recursively calling methods on their child panels where appropriate.
A view performs the following steps to render a model form through the panels mechanism:
* The top-level panel object for the model is retrieved. Usually this is done by looking up the model’s `edit_handler` property and falling back on an `ObjectList` consisting of children given by the model’s `panels` property. However, it may come from elsewhere - for example, the ModelAdmin module allows defining it on the ModelAdmin configuration object.
* If the `PanelsGroup`s permissions do not allow a user to see this panel, then nothing more will be done.
* The view calls `bind_to_model` on the top-level panel, passing the model class, and this returns a clone of the panel with a `model` property. As part of this process the `on_model_bound` method is invoked on each child panel, to allow it to perform additional initialisation that requires access to the model (for example, this is where `FieldPanel` retrieves the model field definition).
* The view then calls `get_form_class` on the top-level panel to retrieve a ModelForm subclass that can be used to edit the model. This proceeds as follows:
+ Retrieve a base form class from the model’s `base_form_class` property, falling back on `wagtail.admin.forms.WagtailAdminModelForm`
+ Call `get_form_options` on each child panel - which returns a dictionary of properties including `fields` and `widgets` - and merge the results into a single dictionary
+ Construct a subclass of the base form class, with the options dict forming the attributes of the inner `Meta` class.
* An instance of the form class is created as per a normal Django form view.
* The view then calls `get_bound_panel` on the top-level panel, passing `instance`, `form` and `request` as keyword arguments. This returns a `BoundPanel` object, which follows [the template component API](template_components). Finally, the `BoundPanel` object (and its media definition) is rendered onto the template.
New panel types can be defined by subclassing `wagtail.admin.panels.Panel` - see [Panel API](../reference/panel_api).
wagtail Creating admin views Creating admin views
====================
The most common use for adding custom views to the Wagtail admin is to provide an interface for managing a Django model. The [Index](../reference/contrib/modeladmin/index) app makes this simple, providing ready-made views for listing, creating and editing objects with minimal configuration.
For other kinds of admin view that don’t fit this pattern, you can write your own Django views and register them as part of the Wagtail admin through [hooks](../reference/hooks#admin-hooks). In this example, we’ll implement a view that displays a calendar for the current year, using [the calendar module](https://docs.python.org/3/library/calendar.html) from Python’s standard library.
Defining a view
---------------
Within a Wagtail project, create a new `wagtailcalendar` app with `./manage.py startapp wagtailcalendar` and add it to your project’s `INSTALLED_APPS`. (In this case we’re using the name ‘wagtailcalendar’ to avoid clashing with the standard library’s `calendar` module - in general there is no need to use a ‘wagtail’ prefix.)
Edit `views.py` as follows - note that this is a plain Django view with no Wagtail-specific code.
```
import calendar
from django.http import HttpResponse
from django.utils import timezone
def index(request):
current_year = timezone.now().year
calendar_html = calendar.HTMLCalendar().formatyear(current_year)
return HttpResponse(calendar_html)
```
Registering a URL route
-----------------------
At this point, the standard practice for a Django project would be to add a URL route for this view to your project’s top-level URL config module. However, in this case we want the view to only be available to logged-in users, and to appear within the `/admin/` URL namespace which is managed by Wagtail. This is done through the [Register Admin URLs](../reference/hooks#register-admin-urls) hook.
On startup, Wagtail looks for a `wagtail_hooks` submodule within each installed app. In this submodule, you can define functions to be run at various points in Wagtail’s operation, such as building the URL config for the admin, and constructing the main menu.
Create a `wagtail_hooks.py` file within the `wagtailcalendar` app containing the following:
```
from django.urls import path
from wagtail import hooks
from .views import index
@hooks.register('register_admin_urls')
def register_calendar_url():
return [
path('calendar/', index, name='calendar'),
]
```
The calendar will now be visible at the URL `/admin/calendar/`.
Adding a template
-----------------
Currently this view is outputting a plain HTML fragment. Let’s insert this into the usual Wagtail admin page furniture, by creating a template that extends Wagtail’s base template `"wagtailadmin/base.html"`.
Note
The base template and HTML structure are not considered astable part of Wagtail’s API, and may change in futurereleases.
Update `views.py` as follows:
```
import calendar
from django.shortcuts import render
from django.utils import timezone
def index(request):
current_year = timezone.now().year
calendar_html = calendar.HTMLCalendar().formatyear(current_year)
return render(request, 'wagtailcalendar/index.html', {
'current_year': current_year,
'calendar_html': calendar_html,
})
```
Now create a `templates/wagtailcalendar/` folder within the `wagtailcalendar` app, containing `index.html` as follows:
```
{% extends "wagtailadmin/base.html" %}
{% block titletag %}{{ current_year }} calendar{% endblock %}
{% block extra_css %}
{{ block.super }}
<style>
table.month {
margin: 20px;
}
table.month td, table.month th {
padding: 5px;
}
</style>
{% endblock %}
{% block content %}
{% include "wagtailadmin/shared/header.html" with title="Calendar" icon="date" %}
<div class="nice-padding">
{{ calendar_html|safe }}
</div>
{% endblock %}
```
Here we are overriding three of the blocks defined in the base template: `titletag` (which sets the content of the HTML `<title>` tag), `extra_css` (which allows us to provide additional CSS styles specific to this page), and `content` (for the main content area of the page). We’re also including the standard header bar component, and setting a title and icon. For a list of the recognised icon identifiers, see the [style guide](../contributing/styleguide#styleguide).
Revisiting `/admin/calendar/` will now show the calendar within the Wagtail admin page furniture.
Adding a menu item
------------------
Our calendar view is now complete, but there’s no way to reach it from the rest of the admin backend. To add an item to the sidebar menu, we’ll use another hook, [Register Admin Menu Item](../reference/hooks#register-admin-menu-item). Update `wagtail_hooks.py` as follows:
```
from django.urls import path, reverse
from wagtail.admin.menu import MenuItem
from wagtail import hooks
from .views import index
@hooks.register('register_admin_urls')
def register_calendar_url():
return [
path('calendar/', index, name='calendar'),
]
@hooks.register('register_admin_menu_item')
def register_calendar_menu_item():
return MenuItem('Calendar', reverse('calendar'), icon_name='date')
```
A ‘Calendar’ item will now appear in the menu.
Adding a group of menu items
----------------------------
Sometimes you want to group custom views together in a single menu item in the sidebar. Let’s create another view to display only the current calendar month:
```
import calendar
from django.shortcuts import render
from django.utils import timezone
def index(request):
current_year = timezone.now().year
calendar_html = calendar.HTMLCalendar().formatyear(current_year)
return render(request, 'wagtailcalendar/index.html', {
'current_year': current_year,
'calendar_html': calendar_html,
})
def month(request):
current_year = timezone.now().year
current_month = timezone.now().month
calendar_html = calendar.HTMLCalendar().formatmonth(current_year, current_month)
return render(request, 'wagtailcalendar/index.html', {
'current_year': current_year,
'calendar_html': calendar_html,
})
```
We also need to update `wagtail_hooks.py` to register our URL in the admin interface:
```
from django.urls import path
from wagtail import hooks
from .views import index, month
@hooks.register('register_admin_urls')
def register_calendar_url():
return [
path('calendar/', index, name='calendar'),
path('calendar/month/', month, name='calendar-month'),
]
```
The calendar will now be visible at the URL `/admin/calendar/month/`.
Finally we can alter our `wagtail_hooks.py` to include a group of custom menu items. This is similar to adding a single item but involves importing two more classes, `Menu` and `SubmenuMenuItem`.
```
from django.urls import path, reverse
from wagtail.admin.menu import Menu, MenuItem, SubmenuMenuItem
from wagtail import hooks
from .views import index, month
@hooks.register('register_admin_urls')
def register_calendar_url():
return [
path('calendar/', index, name='calendar'),
path('calendar/month/', month, name='calendar-month'),
]
@hooks.register('register_admin_menu_item')
def register_calendar_menu_item():
submenu = Menu(items=[
MenuItem('Calendar', reverse('calendar'), icon_name='date'),
MenuItem('Current month', reverse('calendar-month'), icon_name='date'),
])
return SubmenuMenuItem('Calendar', submenu, icon_name='date')
```
The ‘Calendar’ item will now appear as a group of menu items. When expanded, the ‘Calendar’ item will now show our two custom menu items.
wagtail Rich text internals Rich text internals
===================
At first glance, Wagtail’s rich text capabilities appear to give editors direct control over a block of HTML content. In reality, it’s necessary to give editors a representation of rich text content that is several steps removed from the final HTML output, for several reasons:
* The editor interface needs to filter out certain kinds of unwanted markup; this includes malicious scripting, font styles pasted from an external word processor, and elements which would break the validity or consistency of the site design (for example, pages will generally reserve the `<h1>` element for the page title, and so it would be inappropriate to allow users to insert their own additional `<h1>` elements through rich text).
* Rich text fields can specify a `features` argument to further restrict the elements permitted in the field - see [Rich Text Features](../advanced_topics/customisation/page_editing_interface#rich-text-features).
* Enforcing a subset of HTML helps to keep presentational markup out of the database, making the site more maintainable, and making it easier to repurpose site content (including, potentially, producing non-HTML output such as [LaTeX](https://www.latex-project.org/)).
* Elements such as page links and images need to preserve metadata such as the page or image ID, which is not present in the final HTML representation.
This requires the rich text content to go through a number of validation and conversion steps; both between the editor interface and the version stored in the database, and from the database representation to the final rendered HTML.
For this reason, extending Wagtail’s rich text handling to support a new element is more involved than simply saying (for example) “enable the `<blockquote>` element”, since various components of Wagtail - both client and server-side - need to agree on how to handle that feature, including how it should be exposed in the editor interface, how it should be represented within the database, and (if appropriate) how it should be translated when rendered on the front-end.
The components involved in Wagtail’s rich text handling are described below.
Data format
-----------
Rich text data (as handled by [RichTextField](../advanced_topics/customisation/page_editing_interface#rich-text), and `RichTextBlock` within [StreamField](../topics/streamfield)) is stored in the database in a format that is similar, but not identical, to HTML. For example, a link to a page might be stored as:
```
<p><a linktype="page" id="3">Contact us</a> for more information.</p>
```
Here, the `linktype` attribute identifies a rule that shall be used to rewrite the tag. When rendered on a template through the `|richtext` filter (see [rich text filter](../topics/writing_templates#rich-text-filter)), this is converted into valid HTML:
```
<p><a href="/contact-us/">Contact us</a> for more information.</p>
```
In the case of `RichTextBlock`, the block’s value is a `RichText` object which performs this conversion automatically when rendered as a string, so the `|richtext` filter is not necessary.
Likewise, an image inside rich text content might be stored as:
```
<embed embedtype="image" id="10" alt="A pied wagtail" format="left" />
```
which is converted into an `img` element when rendered:
```
<img
alt="A pied wagtail"
class="richtext-image left"
height="294"
src="/media/images/pied-wagtail.width-500_ENyKffb.jpg"
width="500"
/>
```
Again, the `embedtype` attribute identifies a rule that shall be used to rewrite the tag. All tags other than `<a linktype="...">` and `<embed embedtype="..." />` are left unchanged in the converted HTML.
A number of additional constraints apply to `<a linktype="...">` and `<embed embedtype="..." />` tags, to allow the conversion to be performed efficiently via string replacement:
* The tag name and attributes must be lower-case
* Attribute values must be quoted with double-quotes
* `embed` elements must use XML self-closing tag syntax (those that end in `/>` instead of a closing `</embed>` tag)
* The only HTML entities permitted in attribute values are `<`, `>`, `&` and `"`
The feature registry
--------------------
Any app within your project can define extensions to Wagtail’s rich text handling, such as new `linktype` and `embedtype` rules. An object known as the *feature registry* serves as a central source of truth about how rich text should behave. This object can be accessed through the [Register Rich Text Features](../reference/hooks#register-rich-text-features) hook, which is called on startup to gather all definitions relating to rich text:
```
# my_app/wagtail_hooks.py
from wagtail import hooks
@hooks.register('register_rich_text_features')
def register_my_feature(features):
# add new definitions to 'features' here
```
Rewrite handlers
----------------
Rewrite handlers are classes that know how to translate the content of rich text tags like `<a linktype="...">` and `<embed embedtype="..." />` into front-end HTML. For example, the `PageLinkHandler` class knows how to convert the rich text tag `<a linktype="page" id="123">` into the HTML tag `<a href="/path/to/page/123">`.
Rewrite handlers can also provide other useful information about rich text tags. For example, given an appropriate tag, `PageLinkHandler` can be used to extract which page is being referred to. This can be useful for downstream code that may want information about objects being referenced in rich text.
You can create custom rewrite handlers to support your own new `linktype` and `embedtype` tags. New handlers must be Python classes that inherit from either `wagtail.richtext.LinkHandler` or `wagtail.richtext.EmbedHandler`. Your new classes should override at least some of the following methods (listed here for `LinkHandler`, although `EmbedHandler` has an identical signature):
Below is an example custom rewrite handler that implements these methods to add support for rich text linking to user email addresses. It supports the conversion of rich text tags like `<a linktype="user" username="wagtail">` to valid HTML like `<a href="mailto:[email protected]">`. This example assumes that equivalent front-end functionality has been added to allow users to insert these kinds of links into their rich text editor.
```
from django.contrib.auth import get_user_model
from wagtail.rich_text import LinkHandler
class UserLinkHandler(LinkHandler):
identifier = 'user'
@staticmethod
def get_model():
return get_user_model()
@classmethod
def get_instance(cls, attrs):
model = cls.get_model()
return model.objects.get(username=attrs['username'])
@classmethod
def expand_db_attributes(cls, attrs):
user = cls.get_instance(attrs)
return '<a href="mailto:%s">' % user.email
```
### Registering rewrite handlers
Rewrite handlers must also be registered with the feature registry via the [register rich text features](../reference/hooks#register-rich-text-features) hook. Independent methods for registering both link handlers and embed handlers are provided.
This method allows you to register a custom handler deriving from `wagtail.rich_text.LinkHandler`, and adds it to the list of link handlers available during rich text conversion.
```
# my_app/wagtail_hooks.py
from wagtail import hooks
from my_app.handlers import MyCustomLinkHandler
@hooks.register('register_rich_text_features')
def register_link_handler(features):
features.register_link_type(MyCustomLinkHandler)
```
It is also possible to define link rewrite handlers for Wagtail’s built-in `external` and `email` links, even though they do not have a predefined `linktype`. For example, if you want external links to have a `rel="nofollow"` attribute for SEO purposes:
```
from django.utils.html import escape
from wagtail import hooks
from wagtail.rich_text import LinkHandler
class NoFollowExternalLinkHandler(LinkHandler):
identifier = 'external'
@classmethod
def expand_db_attributes(cls, attrs):
href = attrs["href"]
return '<a href="%s" rel="nofollow">' % escape(href)
@hooks.register('register_rich_text_features')
def register_external_link(features):
features.register_link_type(NoFollowExternalLinkHandler)
```
Similarly you can use `email` linktype to add a custom rewrite handler for email links (for example to obfuscate emails in rich text).
This method allows you to register a custom handler deriving from `wagtail.rich_text.EmbedHandler`, and adds it to the list of embed handlers available during rich text conversion.
```
# my_app/wagtail_hooks.py
from wagtail import hooks
from my_app.handlers import MyCustomEmbedHandler
@hooks.register('register_rich_text_features')
def register_embed_handler(features):
features.register_embed_type(MyCustomEmbedHandler)
```
Editor widgets
--------------
The editor interface used on rich text fields can be configured with the [WAGTAILADMIN\_RICH\_TEXT\_EDITORS](../reference/settings#wagtailadmin-rich-text-editors) setting. Wagtail provides an implementation: `wagtail.admin.rich_text.DraftailRichTextArea` (the [Draftail](https://www.draftail.org/) editor based on [Draft.js](https://draftjs.org/)).
It is possible to create your own rich text editor implementation. At minimum, a rich text editor is a Django ***class* django.forms.Widget** subclass whose constructor accepts an `options` keyword argument (a dictionary of editor-specific configuration options sourced from the `OPTIONS` field in `WAGTAILADMIN_RICH_TEXT_EDITORS`), and which consumes and produces string data in the HTML-like format described above.
Typically, a rich text widget also receives a `features` list, passed from either `RichTextField` / `RichTextBlock` or the `features` option in `WAGTAILADMIN_RICH_TEXT_EDITORS`, which defines the features available in that instance of the editor (see [rich text features](../advanced_topics/customisation/page_editing_interface#rich-text-features)). To opt in to supporting features, set the attribute `accepts_features = True` on your widget class; the widget constructor will then receive the feature list as a keyword argument `features`.
There is a standard set of recognised feature identifiers as listed under [rich text features](../advanced_topics/customisation/page_editing_interface#rich-text-features), but this is not a definitive list; feature identifiers are only defined by convention, and it is up to each editor widget to determine which features it will recognise, and adapt its behaviour accordingly. Individual editor widgets might implement fewer or more features than the default set, either as built-in functionality or through a plugin mechanism if the editor widget has one.
For example, a third-party Wagtail extension might introduce `table` as a new rich text feature, and provide implementations for the Draftail editor (which provides a plugin mechanism). In this case, the third-party extension will not be aware of your custom editor widget, and so the widget will not know how to handle the `table` feature identifier. Editor widgets should silently ignore any feature identifiers that they do not recognise.
The `default_features` attribute of the feature registry is a list of feature identifiers to be used whenever an explicit feature list has not been given in `RichTextField` / `RichTextBlock` or `WAGTAILADMIN_RICH_TEXT_EDITORS`. This list can be modified within the `register_rich_text_features` hook to make new features enabled by default, and retrieved by calling `get_default_features()`.
```
@hooks.register('register_rich_text_features')
def make_h1_default(features):
features.default_features.append('h1')
```
Outside of the `register_rich_text_features` hook - for example, inside a widget class - the feature registry can be imported as the object `wagtail.rich_text.features`. A possible starting point for a rich text editor with feature support would be:
```
from django.forms import widgets
from wagtail.rich_text import features
class CustomRichTextArea(widgets.TextArea):
accepts_features = True
def __init__(self, *args, **kwargs):
self.options = kwargs.pop('options', None)
self.features = kwargs.pop('features', None)
if self.features is None:
self.features = features.get_default_features()
super().__init__(*args, **kwargs)
```
Editor plugins
--------------
Rich text editors often provide a plugin mechanism to allow extending the editor with new functionality. The `register_editor_plugin` method provides a standardised way for `register_rich_text_features` hooks to define plugins to be pulled in to the editor when a given rich text feature is enabled.
`register_editor_plugin` is passed an editor name (a string uniquely identifying the editor widget - Wagtail uses the identifier `draftail` for the built-in editor), a feature identifier, and a plugin definition object. This object is specific to the editor widget and can be any arbitrary value, but will typically include a [Django form media](https://docs.djangoproject.com/en/stable/topics/forms/media/ "(in Django v4.1)") definition referencing the plugin’s JavaScript code - which will then be merged into the editor widget’s own media definition - along with any relevant configuration options to be passed when instantiating the editor.
Within the editor widget, the plugin definition for a given feature can be retrieved via the `get_editor_plugin` method, passing the editor’s own identifier string and the feature identifier. This will return `None` if no matching plugin has been registered.
For details of the plugin formats for Wagtail’s built-in editors, see [Extending the Draftail Editor](extending_draftail).
Format converters
-----------------
Editor widgets will often be unable to work directly with Wagtail’s rich text format, and require conversion to their own native format. For Draftail, this is a JSON-based format known as ContentState (see [How Draft.js Represents Rich Text Data](https://rajaraodv.medium.com/how-draft-js-represents-rich-text-data-eeabb5f25cf2)). Editors based on HTML’s `contentEditable` mechanism require valid HTML, and so Wagtail uses a convention referred to as “editor HTML”, where the additional data required on link and embed elements is stored in `data-` attributes, for example: `<a href="/contact-us/" data-linktype="page" data-id="3">Contact us</a>`.
Wagtail provides two utility classes, `wagtail.admin.rich_text.converters.contentstate.ContentstateConverter` and `wagtail.admin.rich_text.converters.editor_html.EditorHTMLConverter`, to perform conversions between rich text format and the native editor formats. These classes are independent of any editor widget, and distinct from the rewriting process that happens when rendering rich text onto a template.
Both classes accept a `features` list as an argument to their constructor, and implement two methods, `from_database_format(data)` which converts Wagtail rich text data to the editor’s format, and `to_database_format(data)` which converts editor data to Wagtail rich text format.
As with editor plugins, the behaviour of a converter class can vary according to the feature list passed to it. In particular, it can apply whitelisting rules to ensure that the output only contains HTML elements corresponding to the currently active feature set. The feature registry provides a `register_converter_rule` method to allow `register_rich_text_features` hooks to define conversion rules that will be activated when a given feature is enabled.
`register_editor_plugin` is passed a converter name (a string uniquely identifying the converter class - Wagtail uses the identifiers `contentstate` and `editorhtml`), a feature identifier, and a rule definition object. This object is specific to the converter and can be any arbitrary value.
For details of the rule definition format for the `contentstate` converter, see [Extending the Draftail Editor](extending_draftail).
Within a converter class, the rule definition for a given feature can be retrieved via the `get_converter_rule` method, passing the converter’s own identifier string and the feature identifier. This will return `None` if no matching rule has been registered.
| programming_docs |
wagtail Extending the Draftail Editor Extending the Draftail Editor
=============================
Wagtail’s rich text editor is built with [Draftail](https://www.draftail.org/), and its functionality can be extended through plugins.
Plugins come in three types:
* Inline styles – To format a portion of a line, for example `bold`, `italic`, `monospace`.
* Blocks – To indicate the structure of the content, for example `blockquote`, `ol`.
* Entities – To enter additional data/metadata, for example `link` (with a URL), `image` (with a file).
All of these plugins are created with a similar baseline, which we can demonstrate with one of the simplest examples – a custom feature for an inline style of `mark`. Place the following in a `wagtail_hooks.py` file in any installed app:
```
import wagtail.admin.rich_text.editors.draftail.features as draftail_features
from wagtail.admin.rich_text.converters.html_to_contentstate import InlineStyleElementHandler
from wagtail import hooks
# 1. Use the register_rich_text_features hook.
@hooks.register('register_rich_text_features')
def register_mark_feature(features):
"""
Registering the `mark` feature, which uses the `MARK` Draft.js inline style type,
and is stored as HTML with a `<mark>` tag.
"""
feature_name = 'mark'
type_ = 'MARK'
tag = 'mark'
# 2. Configure how Draftail handles the feature in its toolbar.
control = {
'type': type_,
'label': '☆',
'description': 'Mark',
# This isn’t even required – Draftail has predefined styles for MARK.
# 'style': {'textDecoration': 'line-through'},
}
# 3. Call register_editor_plugin to register the configuration for Draftail.
features.register_editor_plugin(
'draftail', feature_name, draftail_features.InlineStyleFeature(control)
)
# 4.configure the content transform from the DB to the editor and back.
db_conversion = {
'from_database_format': {tag: InlineStyleElementHandler(type_)},
'to_database_format': {'style_map': {type_: tag}},
}
# 5. Call register_converter_rule to register the content transformation conversion.
features.register_converter_rule('contentstate', feature_name, db_conversion)
# 6. (optional) Add the feature to the default features list to make it available
# on rich text fields that do not specify an explicit 'features' list
features.default_features.append('mark')
```
These steps will always be the same for all Draftail plugins. The important parts are to:
* Consistently use the feature’s Draft.js type or Wagtail feature names where appropriate.
* Give enough information to Draftail so it knows how to make a button for the feature, and how to render it (more on this later).
* Configure the conversion to use the right HTML element (as they are stored in the DB).
For detailed configuration options, head over to the [Draftail documentation](https://www.draftail.org/docs/formatting-options) to see all of the details. Here are some parts worth highlighting about controls:
* The `type` is the only mandatory piece of information.
* To display the control in the toolbar, combine `icon`, `label` and `description`.
* The controls’ `icon` can be a string to use an icon font with CSS classes, say `'icon': 'fas fa-user',`. It can also be an array of strings, to use SVG paths, or SVG symbol references for example `'icon': ['M100 100 H 900 V 900 H 100 Z'],`. The paths need to be set for a 1024x1024 viewbox.
Creating new inline styles
--------------------------
In addition to the initial example, inline styles take a `style` property to define what CSS rules will be applied to text in the editor. Be sure to read the [Draftail documentation](https://www.draftail.org/docs/formatting-options) on inline styles.
Finally, the DB to/from conversion uses an `InlineStyleElementHandler` to map from a given tag (`<mark>` in the example above) to a Draftail type, and the inverse mapping is done with [Draft.js exporter configuration](https://github.com/springload/draftjs_exporter) of the `style_map`.
Creating new blocks
-------------------
Blocks are nearly as simple as inline styles:
```
import wagtail.admin.rich_text.editors.draftail.features as draftail_features
from wagtail.admin.rich_text.converters.html_to_contentstate import BlockElementHandler
@hooks.register('register_rich_text_features')
def register_help_text_feature(features):
"""
Registering the `help-text` feature, which uses the `help-text` Draft.js block type,
and is stored as HTML with a `<div class="help-text">` tag.
"""
feature_name = 'help-text'
type_ = 'help-text'
control = {
'type': type_,
'label': '?',
'description': 'Help text',
# Optionally, we can tell Draftail what element to use when displaying those blocks in the editor.
'element': 'div',
}
features.register_editor_plugin(
'draftail', feature_name, draftail_features.BlockFeature(control, css={'all': ['help-text.css']})
)
features.register_converter_rule('contentstate', feature_name, {
'from_database_format': {'div[class=help-text]': BlockElementHandler(type_)},
'to_database_format': {'block_map': {type_: {'element': 'div', 'props': {'class': 'help-text'}}}},
})
```
Here are the main differences:
* We can configure an `element` to tell Draftail how to render those blocks in the editor.
* We register the plugin with `BlockFeature`.
* We set up the conversion with `BlockElementHandler` and `block_map`.
Optionally, we can also define styles for the blocks with the `Draftail-block--help-text` (`Draftail-block--<block type>`) CSS class.
That’s it! The extra complexity is that you may need to write CSS to style the blocks in the editor.
Creating new entities
---------------------
Warning
This is an advanced feature. Please carefully consider whether you really need this.
Entities aren’t simply formatting buttons in the toolbar. They usually need to be much more versatile, communicating to APIs or requesting further user input. As such,
* You will most likely need to write a **hefty dose of JavaScript**, some of it with React.
* The API is very **low-level**. You will most likely need some **Draft.js knowledge**.
* Custom UIs in rich text can be brittle. Be ready to spend time **testing in multiple browsers**.
The good news is that having such a low-level API will enable third-party Wagtail plugins to innovate on rich text features, proposing new kinds of experiences. But in the meantime, consider implementing your UI through [StreamField](../topics/streamfield) instead, which has a battle-tested API meant for Django developers.
Here are the main requirements to create a new entity feature:
* Like for inline styles and blocks, register an editor plugin.
* The editor plugin must define a `source`: a React component responsible for creating new entity instances in the editor, using the Draft.js API.
* The editor plugin also needs a `decorator` (for inline entities) or `block` (for block entities): a React component responsible for displaying entity instances within the editor.
* Like for inline styles and blocks, set up the to/from DB conversion.
* The conversion usually is more involved, since entities contain data that needs to be serialised to HTML.
To write the React components, Wagtail exposes its own React, Draft.js and Draftail dependencies as global variables. Read more about this in [ectending clientside components](../advanced_topics/customisation/admin_templates#extending-clientside-components). To go further, please look at the [Draftail documentation](https://www.draftail.org/docs/formatting-options) as well as the [Draft.js exporter documentation](https://github.com/springload/draftjs_exporter).
Here is a detailed example to showcase how those tools are used in the context of Wagtail. For the sake of our example, we can imagine a news team working at a financial newspaper. They want to write articles about the stock market, refer to specific stocks anywhere inside of their content (for example “$TSLA” tokens in a sentence), and then have their article automatically enriched with the stock’s information (a link, a number, a sparkline).
The editor toolbar could contain a “stock chooser” that displays a list of available stocks, then inserts the user’s selection as a textual token. For our example, we will just pick a stock at random:

Those tokens are then saved in the rich text on publish. When the news article is displayed on the site, we then insert live market data coming from an API next to each token:
In order to achieve this, we start with registering the rich text feature like for inline styles and blocks:
```
@hooks.register('register_rich_text_features')
def register_stock_feature(features):
features.default_features.append('stock')
"""
Registering the `stock` feature, which uses the `STOCK` Draft.js entity type,
and is stored as HTML with a `<span data-stock>` tag.
"""
feature_name = 'stock'
type_ = 'STOCK'
control = {
'type': type_,
'label': '$',
'description': 'Stock',
}
features.register_editor_plugin(
'draftail', feature_name, draftail_features.EntityFeature(
control,
js=['stock.js'],
css={'all': ['stock.css']}
)
)
features.register_converter_rule('contentstate', feature_name, {
# Note here that the conversion is more complicated than for blocks and inline styles.
'from_database_format': {'span[data-stock]': StockEntityElementHandler(type_)},
'to_database_format': {'entity_decorators': {type_: stock_entity_decorator}},
})
```
The `js` and `css` keyword arguments on `EntityFeature` can be used to specify additional JS and CSS files to load when this feature is active. Both are optional. Their values are added to a `Media` object, more documentation on these objects is available in the [Django Form Assets documentation](https://docs.djangoproject.com/en/stable/topics/forms/media/ "(in Django v4.1)").
Since entities hold data, the conversion to/from database format is more complicated. We have to create the two handlers:
```
from draftjs_exporter.dom import DOM
from wagtail.admin.rich_text.converters.html_to_contentstate import InlineEntityElementHandler
def stock_entity_decorator(props):
"""
Draft.js ContentState to database HTML.
Converts the STOCK entities into a span tag.
"""
return DOM.create_element('span', {
'data-stock': props['stock'],
}, props['children'])
class StockEntityElementHandler(InlineEntityElementHandler):
"""
Database HTML to Draft.js ContentState.
Converts the span tag into a STOCK entity, with the right data.
"""
mutability = 'IMMUTABLE'
def get_attribute_data(self, attrs):
"""
Take the `stock` value from the `data-stock` HTML attribute.
"""
return { 'stock': attrs['data-stock'] }
```
Note how they both do similar conversions, but use different APIs. `to_database_format` is built with the [Draft.js exporter](https://github.com/springload/draftjs_exporter) components API, whereas `from_database_format` uses a Wagtail API.
The next step is to add JavaScript to define how the entities are created (the `source`), and how they are displayed (the `decorator`). Within `stock.js`, we define the source component:
```
const React = window.React;
const Modifier = window.DraftJS.Modifier;
const EditorState = window.DraftJS.EditorState;
const DEMO_STOCKS = ['AMD', 'AAPL', 'TWTR', 'TSLA', 'BTC'];
// Not a real React component – just creates the entities as soon as it is rendered.
class StockSource extends React.Component {
componentDidMount() {
const { editorState, entityType, onComplete } = this.props;
const content = editorState.getCurrentContent();
const selection = editorState.getSelection();
const randomStock =
DEMO_STOCKS[Math.floor(Math.random() * DEMO_STOCKS.length)];
// Uses the Draft.js API to create a new entity with the right data.
const contentWithEntity = content.createEntity(
entityType.type,
'IMMUTABLE',
{
stock: randomStock,
},
);
const entityKey = contentWithEntity.getLastCreatedEntityKey();
// We also add some text for the entity to be activated on.
const text = `$${randomStock}`;
const newContent = Modifier.replaceText(
content,
selection,
text,
null,
entityKey,
);
const nextState = EditorState.push(
editorState,
newContent,
'insert-characters',
);
onComplete(nextState);
}
render() {
return null;
}
}
```
This source component uses data and callbacks provided by [Draftail](https://www.draftail.org/docs/api). It also uses dependencies from global variables – see [Extending clientside components](../advanced_topics/customisation/admin_templates#extending-clientside-components).
We then create the decorator component:
```
const Stock = (props) => {
const { entityKey, contentState } = props;
const data = contentState.getEntity(entityKey).getData();
return React.createElement(
'a',
{
role: 'button',
onMouseUp: () => {
window.open(`https://finance.yahoo.com/quote/${data.stock}`);
},
},
props.children,
);
};
```
This is a straightforward React component. It does not use JSX since we do not want to have to use a build step for our JavaScript.
Finally, we register the JS components of our plugin:
```
window.draftail.registerPlugin({
type: 'STOCK',
source: StockSource,
decorator: Stock,
});
```
And that’s it! All of this setup will finally produce the following HTML on the site’s front-end:
```
<p>
Anyone following Elon Musk’s <span data-stock="TSLA">$TSLA</span> should
also look into <span data-stock="BTC">$BTC</span>.
</p>
```
To fully complete the demo, we can add a bit of JavaScript to the front-end in order to decorate those tokens with links and a little sparkline.
```
document.querySelectorAll('[data-stock]').forEach((elt) => {
const link = document.createElement('a');
link.href = `https://finance.yahoo.com/quote/${elt.dataset.stock}`;
link.innerHTML = `${elt.innerHTML}<svg width="50" height="20" stroke-width="2" stroke="blue" fill="rgba(0, 0, 255, .2)"><path d="M4 14.19 L 4 14.19 L 13.2 14.21 L 22.4 13.77 L 31.59 13.99 L 40.8 13.46 L 50 11.68 L 59.19 11.35 L 68.39 10.68 L 77.6 7.11 L 86.8 7.85 L 96 4" fill="none"></path><path d="M4 14.19 L 4 14.19 L 13.2 14.21 L 22.4 13.77 L 31.59 13.99 L 40.8 13.46 L 50 11.68 L 59.19 11.35 L 68.39 10.68 L 77.6 7.11 L 86.8 7.85 L 96 4 V 20 L 4 20 Z" stroke="none"></path></svg>`;
elt.innerHTML = '';
elt.appendChild(link);
});
```
Custom block entities can also be created (have a look at the separate [Draftail documentation](https://www.draftail.org/docs/blocks)), but these are not detailed here since [StreamField](../topics/streamfield#streamfield-topic) is the go-to way to create block-level rich text in Wagtail.
Integration of the Draftail widgets
-----------------------------------
To further customise how the Draftail widgets are integrated into the UI, there are additional extension points for CSS and JS:
* In JavaScript, use the `[data-draftail-input]` attribute selector to target the input which contains the data, and `[data-draftail-editor-wrapper]` for the element which wraps the editor.
* The editor instance is bound on the input field for imperative access. Use `document.querySelector('[data-draftail-input]').draftailEditor`.
* In CSS, use the classes prefixed with `Draftail-`.
wagtail Template components Template components
===================
Working with objects that know how to render themselves as elements on an HTML template is a common pattern seen throughout the Wagtail admin. For example, the admin homepage is a view provided by the central `wagtail.admin` app, but brings together information panels sourced from various other modules of Wagtail, such as images and documents (potentially along with others provided by third-party packages). These panels are passed to the homepage via the [`construct_homepage_panels`](../reference/hooks#construct-homepage-panels) hook, and each one is responsible for providing its own HTML rendering. In this way, the module providing the panel has full control over how it appears on the homepage.
Wagtail implements this pattern using a standard object type known as a **component**. A component is a Python object that provides the following methods and properties:
Given a context dictionary from the calling template (which may be a [`Context`](https://docs.djangoproject.com/en/stable/ref/templates/api/#django.template.Context "(in Django v4.1)") object or a plain `dict` of context variables), returns the string representation to be inserted into the template. This will be subject to Django’s HTML escaping rules, so a return value consisting of HTML should typically be returned as a [`SafeString`](https://docs.djangoproject.com/en/stable/ref/utils/#module-django.utils.safestring "(in Django v4.1)") instance.
A (possibly empty) [form media](https://docs.djangoproject.com/en/stable/topics/forms/media/ "(in Django v4.1)") object defining JavaScript and CSS resources used by the component.
Note
Any object implementing this API can be considered a valid component; it does not necessarily have to inherit from the `Component` class described below, and user code that works with components should not assume this (for example, it must not use `isinstance` to check whether a given value is a component).
Creating components
-------------------
The preferred way to create a component is to define a subclass of `wagtail.admin.ui.components.Component` and specify a `template_name` attribute on it. The rendered template will then be used as the component’s HTML representation:
```
from wagtail.admin.ui.components import Component
class WelcomePanel(Component):
template_name = 'my_app/panels/welcome.html'
my_welcome_panel = WelcomePanel()
```
`my_app/templates/my_app/panels/welcome.html`:
```
<h1>Welcome to my app!</h1>
```
For simple cases that don’t require a template, the `render_html` method can be overridden instead:
```
from django.utils.html import format_html
from wagtail.admin.components import Component
class WelcomePanel(Component):
def render_html(self, parent_context):
return format_html("<h1>{}</h1>", "Welcome to my app!")
```
Passing context to the template
-------------------------------
The `get_context_data` method can be overridden to pass context variables to the template. As with `render_html`, this receives the context dictionary from the calling template:
```
from wagtail.admin.ui.components import Component
class WelcomePanel(Component):
template_name = 'my_app/panels/welcome.html'
def get_context_data(self, parent_context):
context = super().get_context_data(parent_context)
context['username'] = parent_context['request'].user.username
return context
```
`my_app/templates/my_app/panels/welcome.html`:
```
<h1>Welcome to my app, {{ username }}!</h1>
```
Adding media definitions
------------------------
Like Django form widgets, components can specify associated JavaScript and CSS resources using either an inner `Media` class or a dynamic `media` property:
```
class WelcomePanel(Component):
template_name = 'my_app/panels/welcome.html'
class Media:
css = {
'all': ('my_app/css/welcome-panel.css',)
}
```
Using components on your own templates
--------------------------------------
The `wagtailadmin_tags` tag library provides a `{% component %}` tag for including components on a template. This takes care of passing context variables from the calling template to the component (which would not be the case for a basic `{{ ... }}` variable tag). For example, given the view:
```
from django.shortcuts import render
def welcome_page(request):
panels = [
WelcomePanel(),
]
render(request, 'my_app/welcome.html', {
'panels': panels,
})
```
the `my_app/welcome.html` template could render the panels as follows:
```
{% load wagtailadmin_tags %}
{% for panel in panels %}
{% component panel %}
{% endfor %}
```
Note that it is your template’s responsibility to output any media declarations defined on the components. For a Wagtail admin view, this is best done by constructing a media object for the whole page within the view, passing this to the template, and outputting it via the base template’s `extra_js` and `extra_css` blocks:
```
from django.forms import Media
from django.shortcuts import render
def welcome_page(request):
panels = [
WelcomePanel(),
]
media = Media()
for panel in panels:
media += panel.media
render(request, 'my_app/welcome.html', {
'panels': panels,
'media': media,
})
```
`my_app/welcome.html`:
```
{% extends "wagtailadmin/base.html" %}
{% load wagtailadmin_tags %}
{% block extra_js %}
{{ block.super }}
{{ media.js }}
{% endblock %}
{% block extra_css %}
{{ block.super }}
{{ media.css }}
{% endblock %}
{% block content %}
{% for panel in panels %}
{% component panel %}
{% endfor %}
{% endblock %}
```
| programming_docs |
wagtail Adding new Task types Adding new Task types
=====================
The Workflow system allows users to create tasks, which represent stages of moderation.
Wagtail provides one built in task type: `GroupApprovalTask`, which allows any user in specific groups to approve or reject moderation.
However, it is possible to add your own task types in code. Instances of your custom task can then be created in the `Tasks` section of the Wagtail Admin.
Task models
-----------
All custom tasks must be models inheriting from `wagtailcore.Task`. In this set of examples, we’ll set up a task which can be approved by only one specific user.
```
# <project>/models.py
from wagtail.models import Task
class UserApprovalTask(Task):
pass
```
Subclassed Tasks follow the same approach as Pages: they are concrete models, with the specific subclass instance accessible by calling `Task.specific()`.
You can now add any custom fields. To make these editable in the admin, add the names of the fields into the `admin_form_fields` attribute:
For example:
```
# <project>/models.py
from django.conf import settings
from django.db import models
from wagtail.models import Task
class UserApprovalTask(Task):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=False)
admin_form_fields = Task.admin_form_fields + ['user']
```
Any fields that shouldn’t be edited after task creation - for example, anything that would fundamentally change the meaning of the task in any history logs - can be added to `admin_form_readonly_on_edit_fields`. For example:
```
# <project>/models.py
from django.conf import settings
from django.db import models
from wagtail.models import Task
class UserApprovalTask(Task):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=False)
admin_form_fields = Task.admin_form_fields + ['user']
# prevent editing of `user` after the task is created
# by default, this attribute contains the 'name' field to prevent tasks from being renamed
admin_form_readonly_on_edit_fields = Task.admin_form_readonly_on_edit_fields + ['user']
```
Wagtail will choose a default form widget to use based on the field type. But you can override the form widget using the `admin_form_widgets` attribute:
```
# <project>/models.py
from django.conf import settings
from django.db import models
from wagtail.models import Task
from .widgets import CustomUserChooserWidget
class UserApprovalTask(Task):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=False)
admin_form_fields = Task.admin_form_fields + ['user']
admin_form_widgets = {
'user': CustomUserChooserWidget,
}
```
Custom TaskState models
-----------------------
You might also need to store custom state information for the task: for example, a rating left by an approving user. Normally, this is done on an instance of `TaskState`, which is created when a page starts the task. However, this can also be subclassed equivalently to `Task`:
```
# <project>/models.py
from wagtail.models import TaskState
class UserApprovalTaskState(TaskState):
pass
```
Your custom task must then be instructed to generate an instance of your custom task state on start instead of a plain `TaskState` instance:
```
# <project>/models.py
from django.conf import settings
from django.db import models
from wagtail.models import Task, TaskState
class UserApprovalTaskState(TaskState):
pass
class UserApprovalTask(Task):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, blank=False)
admin_form_fields = Task.admin_form_fields + ['user']
task_state_class = UserApprovalTaskState
```
Customising behaviour
---------------------
Both `Task` and `TaskState` have a number of methods which can be overridden to implement custom behaviour. Here are some of the most useful:
`Task.user_can_access_editor(page, user)`, `Task.user_can_lock(page, user)`, `Task.user_can_unlock(page, user)`:
These methods determine if users usually without permissions can access the editor, lock, or unlock the page, by returning True or False. Note that returning `False` will not prevent users who would normally be able to perform those actions. For example, for our `UserApprovalTask`:
```
def user_can_access_editor(self, page, user):
return user == self.user
```
`Task.page_locked_for_user(page, user)`:
This returns `True` if the page should be locked and uneditable by the user. It is used by `GroupApprovalTask` to lock the page to any users not in the approval group.
```
def page_locked_for_user(self, page, user):
return user != self.user
```
`Task.get_actions(page, user)`:
This returns a list of `(action_name, action_verbose_name, action_requires_additional_data_from_modal)` tuples, corresponding to the actions available for the task in the edit view menu. `action_requires_additional_data_from_modal` should be a boolean, returning `True` if choosing the action should open a modal for additional data input - for example, entering a comment.
For example:
```
def get_actions(self, page, user):
if user == self.user:
return [
('approve', "Approve", False),
('reject', "Reject", False),
('cancel', "Cancel", False),
]
else:
return []
```
`Task.get_form_for_action(action)`:
Returns a form to be used for additional data input for the given action modal. By default, returns `TaskStateCommentForm`, with a single comment field. The form data returned in `form.cleaned_data` must be fully serializable as JSON.
`Task.get_template_for_action(action)`:
Returns the name of a custom template to be used in rendering the data entry modal for that action.
`Task.on_action(task_state, user, action_name, **kwargs)`:
This performs the actions specified in `Task.get_actions(page, user)`: it is passed an action name, for example `approve`, and the relevant task state. By default, it calls `approve` and `reject` methods on the task state when the corresponding action names are passed through. Any additional data entered in a modal (see `get_form_for_action` and `get_actions`) is supplied as kwargs.
For example, let’s say we wanted to add an additional option: cancelling the entire workflow:
```
def on_action(self, task_state, user, action_name):
if action_name == 'cancel':
return task_state.workflow_state.cancel(user=user)
else:
return super().on_action(task_state, user, workflow_state)
```
`Task.get_task_states_user_can_moderate(user, **kwargs)`:
This returns a QuerySet of `TaskStates` (or subclasses) the given user can moderate - this is currently used to select pages to display on the user’s dashboard.
For example:
```
def get_task_states_user_can_moderate(self, user, **kwargs):
if user == self.user:
# get all task states linked to the (base class of) current task
return TaskState.objects.filter(status=TaskState.STATUS_IN_PROGRESS, task=self.task_ptr)
else:
return TaskState.objects.none()
```
`Task.get_description()`
A class method that returns the human-readable description for the task.
For example:
```
@classmethod
def get_description(cls):
return _("Members of the chosen Wagtail Groups can approve this task")
```
Adding notifications
--------------------
Wagtail’s notifications are sent by `wagtail.admin.mail.Notifier` subclasses: callables intended to be connected to a signal.
By default, email notifications are sent upon workflow submission, approval and rejection, and upon submission to a group approval task.
As an example, we’ll add email notifications for when our new task is started.
```
# <project>/mail.py
from wagtail.admin.mail import EmailNotificationMixin, Notifier
from wagtail.models import TaskState
from .models import UserApprovalTaskState
class BaseUserApprovalTaskStateEmailNotifier(EmailNotificationMixin, Notifier):
"""A base notifier to send updates for UserApprovalTask events"""
def __init__(self):
# Allow UserApprovalTaskState and TaskState to send notifications
super().__init__((UserApprovalTaskState, TaskState))
def can_handle(self, instance, **kwargs):
if super().can_handle(instance, **kwargs) and isinstance(instance.task.specific, UserApprovalTask):
# Don't send notifications if a Task has been cancelled and then resumed - when page was updated to a new revision
return not TaskState.objects.filter(workflow_state=instance.workflow_state, task=instance.task, status=TaskState.STATUS_CANCELLED).exists()
return False
def get_context(self, task_state, **kwargs):
context = super().get_context(task_state, **kwargs)
context['page'] = task_state.workflow_state.page
context['task'] = task_state.task.specific
return context
def get_recipient_users(self, task_state, **kwargs):
# Send emails to the user assigned to the task
approving_user = task_state.task.specific.user
recipients = {approving_user}
return recipients
class UserApprovalTaskStateSubmissionEmailNotifier(BaseUserApprovalTaskStateEmailNotifier):
"""A notifier to send updates for UserApprovalTask submission events"""
notification = 'submitted'
```
Similarly, you could define notifier subclasses for approval and rejection notifications.
Next, you need to instantiate the notifier, and connect it to the `task_submitted` signal.
```
# <project>/signal_handlers.py
from wagtail.signals import task_submitted
from .mail import UserApprovalTaskStateSubmissionEmailNotifier
task_submission_email_notifier = UserApprovalTaskStateSubmissionEmailNotifier()
def register_signal_handlers():
task_submitted.connect(user_approval_task_submission_email_notifier, dispatch_uid='user_approval_task_submitted_email_notification')
```
`register_signal_handlers()` should then be run on loading the app: for example, by adding it to the `ready()` method in your `AppConfig`.
```
# <project>/apps.py
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'myappname'
label = 'myapplabel'
verbose_name = 'My verbose app name'
def ready(self):
from .signal_handlers import register_signal_handlers
register_signal_handlers()
```
Note
In Django versions before 3.2 your `AppConfig` subclass needs to be set as `default_app_config` in `<project>/__init__.py`. See the [relevant section in the Django docs](https://docs.djangoproject.com/en/3.1/ref/applications/#for-application-authors) for the version you are using.
wagtail Reference Reference
=========
* [Pages](pages/index)
+ [Theory](pages/theory)
+ [Recipes](pages/model_recipes)
+ [Panel types](pages/panels)
+ [Model Reference](pages/model_reference)
+ [Page QuerySet reference](pages/queryset_reference)
* [StreamField reference](streamfield/index)
+ [StreamField block reference](streamfield/blocks)
+ [Form widget client-side API](streamfield/widget_api)
* [Contrib modules](contrib/index)
+ [Settings](contrib/settings)
+ [Form builder](contrib/forms/index)
+ [Sitemap generator](contrib/sitemaps)
+ [Frontend cache invalidator](contrib/frontendcache)
+ [`RoutablePageMixin`](contrib/routablepage)
+ [`ModelAdmin`](contrib/modeladmin/index)
+ [Promoted search results](contrib/searchpromotions)
+ [Simple translation](contrib/simple_translation)
+ [TableBlock](contrib/table_block)
+ [Typed table block](contrib/typed_table_block)
+ [Redirects](contrib/redirects)
+ [Legacy richtext](contrib/legacy_richtext)
* [Management commands](management_commands)
* [Hooks](hooks)
* [Signals](signals)
* [Settings](settings)
* [The project template](project_template)
* [Jinja2 template support](jinja2)
* [Panel API](panel_api)
* [Viewsets](viewsets)
wagtail Signals Signals
=======
Wagtail’s [Revision](pages/model_reference#revision-model-ref) and [Page](pages/model_reference#page-model-ref) implement [Signals](https://docs.djangoproject.com/en/stable/topics/signals/ "(in Django v4.1)") from `django.dispatch`. Signals are useful for creating side-effects from page publish/unpublish events.
For example, you could use signals to send publish notifications to a messaging service, or `POST` messages to another app that’s consuming the API, such as a static site generator.
`page_published`
----------------
This signal is emitted from a `Revision` when a page revision is set to `published`.
* `sender` - The page `class`.
* `instance` - The specific `Page` instance.
* `revision` - The `Revision` that was published.
* `kwargs` - Any other arguments passed to `page_published.send()`.
To listen to a signal, implement `page_published.connect(receiver, sender, **kwargs)`. Here’s a simple example showing how you might notify your team when something is published:
```
from wagtail.signals import page_published
import requests
# Let everyone know when a new page is published
def send_to_slack(sender, **kwargs):
instance = kwargs['instance']
url = 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXXXXXXXXXXXXXX'
values = {
"text" : "%s was published by %s " % (instance.title, instance.owner.username),
"channel": "#publish-notifications",
"username": "the squid of content",
"icon_emoji": ":octopus:"
}
response = requests.post(url, values)
# Register a receiver
page_published.connect(send_to_slack)
```
### Receiving specific model events
Sometimes you’re not interested in receiving signals for every model, or you want to handle signals for specific models in different ways. For instance, you may wish to do something when a new blog post is published:
```
from wagtail.signals import page_published
from mysite.models import BlogPostPage
# Do something clever for each model type
def receiver(sender, **kwargs):
# Do something with blog posts
pass
# Register listeners for each page model class
page_published.connect(receiver, sender=BlogPostPage)
```
Wagtail provides access to a list of registered page types through the `get_page_models()` function in `wagtail.models`.
Read the [Django documentation](https://docs.djangoproject.com/en/stable/topics/signals/ "(in Django v4.1)") for more information about specifying senders.
`page_unpublished`
------------------
This signal is emitted from a `Page` when the page is unpublished.
* `sender` - The page `class`.
* `instance` - The specific `Page` instance.
* `kwargs` - Any other arguments passed to `page_unpublished.send()`
`pre_page_move` and `post_page_move`
-------------------------------------
These signals are emitted from a `Page` immediately before and after it is moved.
Subscribe to `pre_page_move` if you need to know values BEFORE any database changes are applied. For example: Getting the page’s previous URL, or that of its descendants.
Subscribe to `post_page_move` if you need to know values AFTER database changes have been applied. For example: Getting the page’s new URL, or that of its descendants.
The following arguments are emitted for both signals:
* `sender` - The page `class`.
* `instance` - The specific `Page` instance.
* `parent_page_before` - The parent page of `instance` **before** moving.
* `parent_page_after` - The parent page of `instance` **after** moving.
* `url_path_before` - The value of `instance.url_path` **before** moving.
* `url_path_after` - The value of `instance.url_path` **after** moving.
* `kwargs` - Any other arguments passed to `pre_page_move.send()` or `post_page_move.send()`.
### Distinguishing between a ‘move’ and a ‘reorder’
The signal can be emitted as a result of a page being moved to a different section (a ‘move’), or as a result of a page being moved to a different position within the same section (a ‘reorder’). Knowing the difference between the two can be particularly useful, because only a ‘move’ affects a page’s URL (and that of its descendants), whereas a ‘reorder’ only affects the natural page order; which is probably less impactful.
The best way to distinguish between a ‘move’ and ‘reorder’ is to compare the `url_path_before` and `url_path_after` values. For example:
```
from wagtail.signals import pre_page_move
from wagtail.contrib.frontend_cache.utils import purge_page_from_cache
# Clear a page's old URLs from the cache when it moves to a different section
def clear_page_url_from_cache_on_move(sender, **kwargs):
if kwargs['url_path_before'] == kwargs['url_path_after']:
# No URLs are changing :) nothing to do here!
return
# The page is moving to a new section (possibly even a new site)
# so clear old URL(s) from the cache
purge_page_from_cache(kwargs['instance'])
# Register a receiver
pre_page_move.connect(clear_old_page_urls_from_cache)
```
`page_slug_changed`
-------------------
This signal is emitted from a `Page` when a change to its slug is published.
The following arguments are emitted by this signal:
* `sender` - The page `class`.
* `instance` - The updated (and saved), specific `Page` instance.
* `instance_before` - A copy of the specific `Page` instance from **before** the changes were saved.
workflow\_submitted
-------------------
This signal is emitted from a `WorkflowState` when a page is submitted to a workflow.
* `sender` - `WorkflowState`
* `instance` - The specific `WorkflowState` instance.
* `user` - The user who submitted the workflow
* `kwargs` - Any other arguments passed to `workflow_submitted.send()`
workflow\_rejected
------------------
This signal is emitted from a `WorkflowState` when a page is rejected from a workflow.
* `sender` - `WorkflowState`
* `instance` - The specific `WorkflowState` instance.
* `user` - The user who rejected the workflow
* `kwargs` - Any other arguments passed to `workflow_rejected.send()`
workflow\_approved
------------------
This signal is emitted from a `WorkflowState` when a page’s workflow completes successfully
* `sender` - `WorkflowState`
* `instance` - The specific `WorkflowState` instance.
* `user` - The user who last approved the workflow
* `kwargs` - Any other arguments passed to `workflow_approved.send()`
workflow\_cancelled
-------------------
This signal is emitted from a `WorkflowState` when a page’s workflow is cancelled
* `sender` - `WorkflowState`
* `instance` - The specific `WorkflowState` instance.
* `user` - The user who cancelled the workflow
* `kwargs` - Any other arguments passed to `workflow_cancelled.send()`
task\_submitted
---------------
This signal is emitted from a `TaskState` when a page is submitted to a task.
* `sender` - `TaskState`
* `instance` - The specific `TaskState` instance.
* `user` - The user who submitted the page to the task
* `kwargs` - Any other arguments passed to `task_submitted.send()`
task\_rejected
--------------
This signal is emitted from a `TaskState` when a page is rejected from a task.
* `sender` - `TaskState`
* `instance` - The specific `TaskState` instance.
* `user` - The user who rejected the task
* `kwargs` - Any other arguments passed to `task_rejected.send()`
task\_approved
--------------
This signal is emitted from a `TaskState` when a page’s task is approved
* `sender` - `TaskState`
* `instance` - The specific `TaskState` instance.
* `user` - The user who approved the task
* `kwargs` - Any other arguments passed to `task_approved.send()`
task\_cancelled
---------------
This signal is emitted from a `TaskState` when a page’s task is cancelled.
* `sender` - `TaskState`
* `instance` - The specific `TaskState` instance.
* `user` - The user who cancelled the task
* `kwargs` - Any other arguments passed to `task_cancelled.send()`
wagtail Hooks Hooks
=====
On loading, Wagtail will search for any app with the file `wagtail_hooks.py` and execute the contents. This provides a way to register your own functions to execute at certain points in Wagtail’s execution, such as when a page is saved or when the main menu is constructed.
Note
Hooks are typically used to customise the view-level behaviour of the Wagtail admin and front-end. For customisations that only deal with model-level behaviour - such as calling an external service when a page or document is added - it is often better to use [Django’s signal mechanism](https://docs.djangoproject.com/en/stable/topics/signals/ "(in Django v4.1)") (see also: [Wagtail signals](signals)), as these are not dependent on a user taking a particular path through the admin interface.
Registering functions with a Wagtail hook is done through the `@hooks.register` decorator:
```
from wagtail import hooks
@hooks.register('name_of_hook')
def my_hook_function(arg1, arg2...)
# your code here
```
Alternatively, `hooks.register` can be called as an ordinary function, passing in the name of the hook and a handler function defined elsewhere:
```
hooks.register('name_of_hook', my_hook_function)
```
If you need your hooks to run in a particular order, you can pass the `order` parameter. If order is not specified then the hooks proceed in the order given by `INSTALLED_APPS`. Wagtail uses hooks internally, too, so you need to be aware of order when overriding built-in Wagtail functionality (such as removing default summary items):
```
@hooks.register('name_of_hook', order=1) # This will run after every hook in the wagtail core
def my_hook_function(arg1, arg2...)
# your code here
@hooks.register('name_of_hook', order=-1) # This will run before every hook in the wagtail core
def my_other_hook_function(arg1, arg2...)
# your code here
@hooks.register('name_of_hook', order=2) # This will run after `my_hook_function`
def yet_another_hook_function(arg1, arg2...)
# your code here
```
Unit testing hooks
------------------
Hooks are usually registered on startup and can’t be changed at runtime. But when writing unit tests, you might want to register a hook function just for a single test or block of code and unregister it so that it doesn’t run when other tests are run.
You can register hooks temporarily using the `hooks.register_temporarily` function, this can be used as both a decorator and a context manager. Here’s an example of how to register a hook function for just a single test:
```
def my_hook_function():
pass
class MyHookTest(TestCase):
@hooks.register_temporarily('name_of_hook', my_hook_function)
def test_my_hook_function(self):
# Test with the hook registered here
pass
```
And here’s an example of registering a hook function for a single block of code:
```
def my_hook_function():
pass
with hooks.register_temporarily('name_of_hook', my_hook_function):
# Hook is registered here
..
# Hook is unregistered here
```
If you need to register multiple hooks in a `with` block, you can pass the hooks in as a list of tuples:
```
def my_hook(...):
pass
def my_other_hook(...):
pass
with hooks.register_temporarily([
('hook_name', my_hook),
('hook_name', my_other_hook),
]):
# All hooks are registered here
..
# All hooks are unregistered here
```
The available hooks are listed below.
Admin modules
-------------
Hooks for building new areas of the admin interface (alongside pages, images, documents and so on).
### `construct_homepage_panels`
Add or remove panels from the Wagtail admin homepage. The callable passed into this hook should take a `request` object and a list of panel objects, and should modify this list in-place as required. Panel objects are [Template components](../extending/template_components#template-components) with an additional `order` property, an integer that determines the panel’s position in the final ordered list. The default panels use integers between `100` and `300`.
```
from django.utils.safestring import mark_safe
from wagtail.admin.ui.components import Component
from wagtail import hooks
class WelcomePanel(Component):
order = 50
def render_html(self, parent_context):
return mark_safe("""
<section class="panel summary nice-padding">
<h3>No, but seriously -- welcome to the admin homepage.</h3>
</section>
""")
@hooks.register('construct_homepage_panels')
def add_another_welcome_panel(request, panels):
panels.append(WelcomePanel())
```
### `construct_homepage_summary_items`
Add or remove items from the ‘site summary’ bar on the admin homepage (which shows the number of pages and other object that exist on the site). The callable passed into this hook should take a `request` object and a list of summary item objects, and should modify this list in-place as required. Summary item objects are instances of `wagtail.admin.site_summary.SummaryItem`, which extends [the Component class](../extending/template_components#creating-template-components) with the following additional methods and properties:
### `construct_main_menu`
Called just before the Wagtail admin menu is output, to allow the list of menu items to be modified. The callable passed to this hook will receive a `request` object and a list of `menu_items`, and should modify `menu_items` in-place as required. Adding menu items should generally be done through the `register_admin_menu_item` hook instead - items added through `construct_main_menu` will not have their `is_shown` check applied.
```
from wagtail import hooks
@hooks.register('construct_main_menu')
def hide_explorer_menu_item_from_frank(request, menu_items):
if request.user.username == 'frank':
menu_items[:] = [item for item in menu_items if item.name != 'explorer']
```
### `describe_collection_contents`
Called when Wagtail needs to find out what objects exist in a collection, if any. Currently this happens on the confirmation before deleting a collection, to ensure that non-empty collections cannot be deleted. The callable passed to this hook will receive a `collection` object, and should return either `None` (to indicate no objects in this collection), or a dict containing the following keys:
* `count` - A numeric count of items in this collection
* `count_text` - A human-readable string describing the number of items in this collection, such as “3 documents”. (Sites with multi-language support should return a translatable string here, most likely using the `django.utils.translation.ngettext` function.)
* `url` (optional) - A URL to an index page that lists the objects being described.
### `register_account_settings_panel`
Registers a new settings panel class to add to the “Account” view in the admin.
This hook can be added to a sub-class of `BaseSettingsPanel`. For example:
```
from wagtail.admin.views.account import BaseSettingsPanel
from wagtail import hooks
@hooks.register('register_account_settings_panel')
class CustomSettingsPanel(BaseSettingsPanel):
name = 'custom'
title = "My custom settings"
order = 500
form_class = CustomSettingsForm
```
Alternatively, it can also be added to a function. For example, this function is equivalent to the above:
```
from wagtail.admin.views.account import BaseSettingsPanel
from wagtail import hooks
class CustomSettingsPanel(BaseSettingsPanel):
name = 'custom'
title = "My custom settings"
order = 500
form_class = CustomSettingsForm
@hooks.register('register_account_settings_panel')
def register_custom_settings_panel(request, user, profile):
return CustomSettingsPanel(request, user, profile)
```
More details about the options that are available can be found at [Customising the user account settings form](../extending/custom_account_settings#custom-account-settings).
### `register_account_menu_item`
Add an item to the “More actions” tab on the “Account” page within the Wagtail admin. The callable for this hook should return a dict with the keys `url`, `label` and `help_text`. For example:
```
from django.urls import reverse
from wagtail import hooks
@hooks.register('register_account_menu_item')
def register_account_delete_account(request):
return {
'url': reverse('delete-account'),
'label': 'Delete account',
'help_text': 'This permanently deletes your account.'
}
```
### `register_admin_menu_item`
Add an item to the Wagtail admin menu. The callable passed to this hook must return an instance of `wagtail.admin.menu.MenuItem`. New items can be constructed from the `MenuItem` class by passing in a `label` which will be the text in the menu item, and the URL of the admin page you want the menu item to link to (usually by calling `reverse()` on the admin view you’ve set up). Additionally, the following keyword arguments are accepted:
* `name` - an internal name used to identify the menu item; defaults to the slugified form of the label.
* `icon_name` - icon to display against the menu item; no defaults, optional, but should be set for top-level menu items so they can be identified when collapsed.
* `classnames` - additional classnames applied to the link
* `order` - an integer which determines the item’s position in the menu
For menu items that are only available to superusers, the subclass `wagtail.admin.menu.AdminOnlyMenuItem` can be used in place of `MenuItem`.
`MenuItem` can be further subclassed to customise its initialisation or conditionally show or hide the item for specific requests (for example, to apply permission checks); see the source code (`wagtail/admin/menu.py`) for details.
```
from django.urls import reverse
from wagtail import hooks
from wagtail.admin.menu import MenuItem
@hooks.register('register_admin_menu_item')
def register_frank_menu_item():
return MenuItem('Frank', reverse('frank'), icon_name='folder-inverse', order=10000)
```
### `register_admin_urls`
Register additional admin page URLs. The callable fed into this hook should return a list of Django URL patterns which define the structure of the pages and endpoints of your extension to the Wagtail admin. For more about vanilla Django URLconfs and views, see [url dispatcher](https://docs.djangoproject.com/en/stable/topics/http/urls/ "(in Django v4.1)").
```
from django.http import HttpResponse
from django.urls import path
from wagtail import hooks
def admin_view(request):
return HttpResponse(
"I have approximate knowledge of many things!",
content_type="text/plain")
@hooks.register('register_admin_urls')
def urlconf_time():
return [
path('how_did_you_almost_know_my_name/', admin_view, name='frank'),
]
```
### `register_group_permission_panel`
Add a new panel to the Groups form in the ‘settings’ area. The callable passed to this hook must return a ModelForm / ModelFormSet-like class, with a constructor that accepts a group object as its `instance` keyword argument, and which implements the methods `save`, `is_valid`, and `as_admin_panel` (which returns the HTML to be included on the group edit page).
### `register_settings_menu_item`
As `register_admin_menu_item`, but registers menu items into the ‘Settings’ sub-menu rather than the top-level menu.
### `construct_settings_menu`
As `construct_main_menu`, but modifies the ‘Settings’ sub-menu rather than the top-level menu.
### `register_reports_menu_item`
As `register_admin_menu_item`, but registers menu items into the ‘Reports’ sub-menu rather than the top-level menu.
### `construct_reports_menu`
As `construct_main_menu`, but modifies the ‘Reports’ sub-menu rather than the top-level menu.
### `register_help_menu_item`
As `register_admin_menu_item`, but registers menu items into the ‘Help’ sub-menu rather than the top-level menu.
### `construct_help_menu`
As `construct_main_menu`, but modifies the ‘Help’ sub-menu rather than the top-level menu.
### `register_admin_search_area`
Add an item to the Wagtail admin search “Other Searches”. Behaviour of this hook is similar to `register_admin_menu_item`. The callable passed to this hook must return an instance of `wagtail.admin.search.SearchArea`. New items can be constructed from the `SearchArea` class by passing the following parameters:
* `label` - text displayed in the “Other Searches” option box.
* `name` - an internal name used to identify the search option; defaults to the slugified form of the label.
* `url` - the URL of the target search page.
* `classnames` - arbitrary CSS classnames applied to the link
* `icon_name` - icon to display next to the label.
* `attrs` - additional HTML attributes to apply to the link.
* `order` - an integer which determines the item’s position in the list of options.
Setting the URL can be achieved using reverse() on the target search page. The GET parameter ‘q’ will be appended to the given URL.
A template tag, `search_other` is provided by the `wagtailadmin_tags` template module. This tag takes a single, optional parameter, `current`, which allows you to specify the `name` of the search option currently active. If the parameter is not given, the hook defaults to a reverse lookup of the page’s URL for comparison against the `url` parameter.
`SearchArea` can be subclassed to customise the HTML output, specify JavaScript files required by the option, or conditionally show or hide the item for specific requests (for example, to apply permission checks); see the source code (`wagtail/admin/search.py`) for details.
```
from django.urls import reverse
from wagtail import hooks
from wagtail.admin.search import SearchArea
@hooks.register('register_admin_search_area')
def register_frank_search_area():
return SearchArea('Frank', reverse('frank'), icon_name='folder-inverse', order=10000)
```
### `register_permissions`
Return a QuerySet of `Permission` objects to be shown in the Groups administration area.
```
from django.contrib.auth.models import Permission
from wagtail import hooks
@hooks.register('register_permissions')
def register_permissions():
app = 'blog'
model = 'extramodelset'
return Permission.objects.filter(content_type__app_label=app, codename__in=[
f"view_{model}", f"add_{model}", f"change_{model}", f"delete_{model}"
])
```
### `filter_form_submissions_for_user`
Allows access to form submissions to be customised on a per-user, per-form basis.
This hook takes two parameters:
* The user attempting to access form submissions
* A `QuerySet` of form pages
The hook must return a `QuerySet` containing a subset of these form pages which the user is allowed to access the submissions for.
For example, to prevent non-superusers from accessing form submissions:
```
from wagtail import hooks
@hooks.register('filter_form_submissions_for_user')
def construct_forms_for_user(user, queryset):
if not user.is_superuser:
queryset = queryset.none()
return queryset
```
Editor interface
----------------
Hooks for customising the editing interface for pages and snippets.
### `register_rich_text_features`
Rich text fields in Wagtail work with a list of ‘feature’ identifiers that determine which editing controls are available in the editor, and which elements are allowed in the output; for example, a rich text field defined as `RichTextField(features=['h2', 'h3', 'bold', 'italic', 'link'])` would allow headings, bold / italic formatting and links, but not (for example) bullet lists or images. The `register_rich_text_features` hook allows new feature identifiers to be defined - see [Limiting features in a rich text field](../advanced_topics/customisation/page_editing_interface#rich-text-features) for details.
### `insert_editor_css`
Add additional CSS files or snippets to the page editor.
```
from django.templatetags.static import static
from django.utils.html import format_html
from wagtail import hooks
@hooks.register('insert_editor_css')
def editor_css():
return format_html(
'<link rel="stylesheet" href="{}">',
static('demo/css/vendor/font-awesome/css/font-awesome.min.css')
)
```
### `insert_global_admin_css`
Add additional CSS files or snippets to all admin pages.
```
from django.utils.html import format_html
from django.templatetags.static import static
from wagtail import hooks
@hooks.register('insert_global_admin_css')
def global_admin_css():
return format_html('<link rel="stylesheet" href="{}">', static('my/wagtail/theme.css'))
```
### `insert_editor_js`
Add additional JavaScript files or code snippets to the page editor.
```
from django.utils.html import format_html_join
from django.utils.safestring import mark_safe
from django.templatetags.static import static
from wagtail import hooks
@hooks.register('insert_editor_js')
def editor_js():
js_files = [
'js/fireworks.js', # https://fireworks.js.org
]
js_includes = format_html_join('\n', '<script src="{0}"></script>',
((static(filename),) for filename in js_files)
)
return js_includes + mark_safe(
"""
<script>
window.addEventListener('DOMContentLoaded', (event) => {
var container = document.createElement('div');
container.style.cssText = 'position: fixed; width: 100%; height: 100%; z-index: 100; top: 0; left: 0; pointer-events: none;';
container.id = 'fireworks';
document.getElementById('main').prepend(container);
var options = { "acceleration": 1.2, "autoresize": true, "mouse": { "click": true, "max": 3 } };
var fireworks = new Fireworks(document.getElementById('fireworks'), options);
fireworks.start();
});
</script>
"""
)
```
### `insert_global_admin_js`
Add additional JavaScript files or code snippets to all admin pages.
```
from django.utils.safestring import mark_safe
from wagtail import hooks
@hooks.register('insert_global_admin_js')
def global_admin_js():
return mark_safe(
'<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r74/three.js"></script>',
)
```
### `register_page_header_buttons`
Add buttons to the secondary dropdown menu in the page header. This works similarly to the `register_page_listing_buttons` hook.
This example will add a simple button to the secondary dropdown menu:
```
from wagtail.admin import widgets as wagtailadmin_widgets
@hooks.register('register_page_header_buttons')
def page_header_buttons(page, page_perms, next_url=None):
yield wagtailadmin_widgets.Button(
'A dropdown button',
'/goes/to/a/url/',
priority=60
)
```
The arguments passed to the hook are as follows:
* `page` - the page object to generate the button for
* `page_perms` - a `PagePermissionTester` object that can be queried to determine the current user’s permissions on the given page
* `next_url` - the URL that the linked action should redirect back to on completion of the action, if the view supports it
The `priority` argument controls the order the buttons are displayed in the dropdown. Buttons are ordered from low to high priority, so a button with `priority=10` will be displayed before a button with `priority=60`.
Editor workflow
---------------
Hooks for customising the way users are directed through the process of creating page content.
### `after_create_page`
Do something with a `Page` object after it has been saved to the database (as a published page or a revision). The callable passed to this hook should take a `request` object and a `page` object. The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object. By default, Wagtail will instead redirect to the Explorer page for the new page’s parent.
```
from django.http import HttpResponse
from wagtail import hooks
@hooks.register('after_create_page')
def do_after_page_create(request, page):
return HttpResponse("Congrats on making content!", content_type="text/plain")
```
If you set attributes on a `Page` object, you should also call `save_revision()`, since the edit and index view pick up their data from the revisions table rather than the actual saved page record.
```
@hooks.register('after_create_page')
def set_attribute_after_page_create(request, page):
page.title = 'Persistent Title'
new_revision = page.save_revision()
if page.live:
# page has been created and published at the same time,
# so ensure that the updated title is on the published version too
new_revision.publish()
```
### `before_create_page`
Called at the beginning of the “create page” view passing in the request, the parent page and page model class.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
Unlike, `after_create_page`, this is run both for both `GET` and `POST` requests.
This can be used to completely override the editor on a per-view basis:
```
from wagtail import hooks
from .models import AwesomePage
from .admin_views import edit_awesome_page
@hooks.register('before_create_page')
def before_create_page(request, parent_page, page_class):
# Use a custom create view for the AwesomePage model
if page_class == AwesomePage:
return create_awesome_page(request, parent_page)
```
### `after_delete_page`
Do something after a `Page` object is deleted. Uses the same behaviour as `after_create_page`.
### `before_delete_page`
Called at the beginning of the “delete page” view passing in the request and the page object.
Uses the same behaviour as `before_create_page`, is is run both for both `GET` and `POST` requests.
```
from django.shortcuts import redirect
from django.utils.html import format_html
from wagtail.admin import messages
from wagtail import hooks
from .models import AwesomePage
@hooks.register('before_delete_page')
def before_delete_page(request, page):
"""Block awesome page deletion and show a message."""
if request.method == 'POST' and page.specific_class in [AwesomePage]:
messages.warning(request, "Awesome pages cannot be deleted, only unpublished")
return redirect('wagtailadmin_pages:delete', page.pk)
```
### `after_edit_page`
Do something with a `Page` object after it has been updated. Uses the same behaviour as `after_create_page`.
### `before_edit_page`
Called at the beginning of the “edit page” view passing in the request and the page object.
Uses the same behaviour as `before_create_page`.
### `after_publish_page`
Do something with a `Page` object after it has been published via page create view or page edit view.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
### `before_publish_page`
Do something with a `Page` object before it has been published via page create view or page edit view.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
### `after_unpublish_page`
Called after unpublish action in “unpublish” view passing in the request and the page object.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
### `before_unpublish_page`
Called before unpublish action in “unpublish” view passing in the request and the page object.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
### `after_copy_page`
Do something with a `Page` object after it has been copied passing in the request, page object and the new copied page. Uses the same behaviour as `after_create_page`.
### `before_copy_page`
Called at the beginning of the “copy page” view passing in the request and the page object.
Uses the same behaviour as `before_create_page`.
### `after_move_page`
Do something with a `Page` object after it has been moved passing in the request and page object. Uses the same behaviour as `after_create_page`.
### `before_move_page`
Called at the beginning of the “move page” view passing in the request, the page object and the destination page object.
Uses the same behaviour as `before_create_page`.
### `before_convert_alias_page`
Called at the beginning of the `convert_alias` view, which is responsible for converting alias pages into normal Wagtail pages.
The request and the page being converted are passed in as arguments to the hook.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
### `after_convert_alias_page`
Do something with a `Page` object after it has been converted from an alias.
The request and the page that was just converted are passed in as arguments to the hook.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
### `construct_translated_pages_to_cascade_actions`
Return additional pages to process in a synced tree setup.
This hook is only triggered on unpublishing a page when `WAGTAIL_I18N_ENABLED = True`.
The list of pages and the action are passed in as arguments to the hook.
The function should return a dictionary with the page from the pages list as key, and a list of additional pages to perform the action on. We recommend they are non-aliased, direct translations of the pages from the function argument.
### `register_page_action_menu_item`
Add an item to the popup menu of actions on the page creation and edit views. The callable passed to this hook must return an instance of `wagtail.admin.action_menu.ActionMenuItem`. `ActionMenuItem` is a subclass of [Component](../extending/template_components#creating-template-components) and so the rendering of the menu item can be customised through `template_name`, `get_context_data`, `render_html` and `Media`. In addition, the following attributes and methods are available to be overridden:
* `order` - an integer (default 100) which determines the item’s position in the menu. Can also be passed as a keyword argument to the object constructor. The lowest-numbered item in this sequence will be selected as the default menu item; as standard, this is “Save draft” (which has an `order` of 0).
* `label` - the displayed text of the menu item
* `get_url` - a method which returns a URL for the menu item to link to; by default, returns `None` which causes the menu item to behave as a form submit button instead
* `name` - value of the `name` attribute of the submit button, if no URL is specified
* `icon_name` - icon to display against the menu item
* `classname` - a `class` attribute value to add to the button element
* `is_shown` - a method which returns a boolean indicating whether the menu item should be shown; by default, true except when editing a locked page
The `get_url`, `is_shown`, `get_context_data` and `render_html` methods all accept a context dictionary containing the following fields:
* `view` - name of the current view: `'create'`, `'edit'` or `'revisions_revert'`
* `page` - for `view` = `'edit'` or `'revisions_revert'`, the page being edited
* `parent_page` - for `view` = `'create'`, the parent page of the page being created
* `request` - the current request object
* `user_page_permissions` - a `UserPagePermissionsProxy` object for the current user, to test permissions against
```
from wagtail import hooks
from wagtail.admin.action_menu import ActionMenuItem
class GuacamoleMenuItem(ActionMenuItem):
name = 'action-guacamole'
label = "Guacamole"
def get_url(self, context):
return "https://www.youtube.com/watch?v=dNJdJIwCF_Y"
@hooks.register('register_page_action_menu_item')
def register_guacamole_menu_item():
return GuacamoleMenuItem(order=10)
```
### `construct_page_action_menu`
Modify the final list of action menu items on the page creation and edit views. The callable passed to this hook receives a list of `ActionMenuItem` objects, a request object and a context dictionary as per `register_page_action_menu_item`, and should modify the list of menu items in-place.
```
@hooks.register('construct_page_action_menu')
def remove_submit_to_moderator_option(menu_items, request, context):
menu_items[:] = [item for item in menu_items if item.name != 'action-submit']
```
The `construct_page_action_menu` hook is called after the menu items have been sorted by their order attributes, and so setting a menu item’s order will have no effect at this point. Instead, items can be reordered by changing their position in the list, with the first item being selected as the default action. For example, to change the default action to Publish:
```
@hooks.register('construct_page_action_menu')
def make_publish_default_action(menu_items, request, context):
for (index, item) in enumerate(menu_items):
if item.name == 'action-publish':
# move to top of list
menu_items.pop(index)
menu_items.insert(0, item)
break
```
### `construct_page_listing_buttons`
Modify the final list of page listing buttons in the page explorer. The callable passed to this hook receives a list of `PageListingButton` objects, a page, a page perms object, and a context dictionary as per `register_page_listing_buttons`, and should modify the list of listing items in-place.
```
@hooks.register('construct_page_listing_buttons')
def remove_page_listing_button_item(buttons, page, page_perms, context=None):
if page.is_root:
buttons.pop() # removes the last 'more' dropdown button on the root page listing buttons
```
### `construct_wagtail_userbar`
Add or remove items from the wagtail userbar. Add, edit, and moderation tools are provided by default. The callable passed into the hook must take the `request` object and a list of menu objects, `items`. The menu item objects must have a `render` method which can take a `request` object and return the HTML string representing the menu item. See the userbar templates and menu item classes for more information.
```
from wagtail import hooks
class UserbarPuppyLinkItem:
def render(self, request):
return '<li><a href="http://cuteoverload.com/tag/puppehs/" ' \
+ 'target="_parent" role="menuitem" class="action icon icon-wagtail">Puppies!</a></li>'
@hooks.register('construct_wagtail_userbar')
def add_puppy_link_item(request, items):
return items.append( UserbarPuppyLinkItem() )
```
Admin workflow
--------------
Hooks for customising the way admins are directed through the process of editing users.
### `after_create_user`
Do something with a `User` object after it has been saved to the database. The callable passed to this hook should take a `request` object and a `user` object. The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object. By default, Wagtail will instead redirect to the User index page.
```
from django.http import HttpResponse
from wagtail import hooks
@hooks.register('after_create_user')
def do_after_create_user(request, user):
return HttpResponse("Congrats on creating a new user!", content_type="text/plain")
```
### `before_create_user`
Called at the beginning of the “create user” view passing in the request.
The function does not have to return anything, but if an object with a `status_code` property is returned, Wagtail will use it as a response object and skip the rest of the view.
Unlike, `after_create_user`, this is run both for both `GET` and `POST` requests.
This can be used to completely override the user editor on a per-view basis:
```
from django.http import HttpResponse
from wagtail import hooks
from .models import AwesomePage
from .admin_views import edit_awesome_page
@hooks.register('before_create_user')
def do_before_create_user(request):
return HttpResponse("A user creation form", content_type="text/plain")
```
### `after_delete_user`
Do something after a `User` object is deleted. Uses the same behaviour as `after_create_user`.
### `before_delete_user`
Called at the beginning of the “delete user” view passing in the request and the user object.
Uses the same behaviour as `before_create_user`.
### `after_edit_user`
Do something with a `User` object after it has been updated. Uses the same behaviour as `after_create_user`.
### `before_edit_user`
Called at the beginning of the “edit user” view passing in the request and the user object.
Uses the same behaviour as `before_create_user`.
Choosers
--------
### `construct_page_chooser_queryset`
Called when rendering the page chooser view, to allow the page listing QuerySet to be customised. The callable passed into the hook will receive the current page QuerySet and the request object, and must return a Page QuerySet (either the original one, or a new one).
```
from wagtail import hooks
@hooks.register('construct_page_chooser_queryset')
def show_my_pages_only(pages, request):
# Only show own pages
pages = pages.filter(owner=request.user)
return pages
```
### `construct_document_chooser_queryset`
Called when rendering the document chooser view, to allow the document listing QuerySet to be customised. The callable passed into the hook will receive the current document QuerySet and the request object, and must return a Document QuerySet (either the original one, or a new one).
```
from wagtail import hooks
@hooks.register('construct_document_chooser_queryset')
def show_my_uploaded_documents_only(documents, request):
# Only show uploaded documents
documents = documents.filter(uploaded_by_user=request.user)
return documents
```
### `construct_image_chooser_queryset`
Called when rendering the image chooser view, to allow the image listing QuerySet to be customised. The callable passed into the hook will receive the current image QuerySet and the request object, and must return an Image QuerySet (either the original one, or a new one).
```
from wagtail import hooks
@hooks.register('construct_image_chooser_queryset')
def show_my_uploaded_images_only(images, request):
# Only show uploaded images
images = images.filter(uploaded_by_user=request.user)
return images
```
Page explorer
-------------
### `construct_explorer_page_queryset`
Called when rendering the page explorer view, to allow the page listing QuerySet to be customised. The callable passed into the hook will receive the parent page object, the current page QuerySet, and the request object, and must return a Page QuerySet (either the original one, or a new one).
```
from wagtail import hooks
@hooks.register('construct_explorer_page_queryset')
def show_my_profile_only(parent_page, pages, request):
# If we're in the 'user-profiles' section, only show the user's own profile
if parent_page.slug == 'user-profiles':
pages = pages.filter(owner=request.user)
return pages
```
### `register_page_listing_buttons`
Add buttons to the actions list for a page in the page explorer. This is useful when adding custom actions to the listing, such as translations or a complex workflow.
This example will add a simple button to the listing:
```
from wagtail.admin import widgets as wagtailadmin_widgets
@hooks.register('register_page_listing_buttons')
def page_listing_buttons(page, page_perms, next_url=None):
yield wagtailadmin_widgets.PageListingButton(
'A page listing button',
'/goes/to/a/url/',
priority=10
)
```
The arguments passed to the hook are as follows:
* `page` - the page object to generate the button for
* `page_perms` - a `PagePermissionTester` object that can be queried to determine the current user’s permissions on the given page
* `next_url` - the URL that the linked action should redirect back to on completion of the action, if the view supports it
The `priority` argument controls the order the buttons are displayed in. Buttons are ordered from low to high priority, so a button with `priority=10` will be displayed before a button with `priority=20`.
### `register_page_listing_more_buttons`
Add buttons to the “More” dropdown menu for a page in the page explorer. This works similarly to the `register_page_listing_buttons` hook but is useful for lesser-used custom actions that are better suited for the dropdown.
This example will add a simple button to the dropdown menu:
```
from wagtail.admin import widgets as wagtailadmin_widgets
@hooks.register('register_page_listing_more_buttons')
def page_listing_more_buttons(page, page_perms, next_url=None):
yield wagtailadmin_widgets.Button(
'A dropdown button',
'/goes/to/a/url/',
priority=60
)
```
The arguments passed to the hook are as follows:
* `page` - the page object to generate the button for
* `page_perms` - a `PagePermissionTester` object that can be queried to determine the current user’s permissions on the given page
* `next_url` - the URL that the linked action should redirect back to on completion of the action, if the view supports it
The `priority` argument controls the order the buttons are displayed in the dropdown. Buttons are ordered from low to high priority, so a button with `priority=10` will be displayed before a button with `priority=60`.
#### Buttons with dropdown lists
The admin widgets also provide `ButtonWithDropdownFromHook`, which allows you to define a custom hook for generating a dropdown menu that gets attached to your button.
Creating a button with a dropdown menu involves two steps. Firstly, you add your button to the `register_page_listing_buttons` hook, just like the example above. Secondly, you register a new hook that yields the contents of the dropdown menu.
This example shows how Wagtail’s default admin dropdown is implemented. You can also see how to register buttons conditionally, in this case by evaluating the `page_perms`:
```
from wagtail.admin import widgets as wagtailadmin_widgets
@hooks.register('register_page_listing_buttons')
def page_custom_listing_buttons(page, page_perms, next_url=None):
yield wagtailadmin_widgets.ButtonWithDropdownFromHook(
'More actions',
hook_name='my_button_dropdown_hook',
page=page,
page_perms=page_perms,
next_url=next_url,
priority=50
)
@hooks.register('my_button_dropdown_hook')
def page_custom_listing_more_buttons(page, page_perms, next_url=None):
if page_perms.can_move():
yield wagtailadmin_widgets.Button('Move', reverse('wagtailadmin_pages:move', args=[page.id]), priority=10)
if page_perms.can_delete():
yield wagtailadmin_widgets.Button('Delete', reverse('wagtailadmin_pages:delete', args=[page.id]), priority=30)
if page_perms.can_unpublish():
yield wagtailadmin_widgets.Button('Unpublish', reverse('wagtailadmin_pages:unpublish', args=[page.id]), priority=40)
```
The template for the dropdown button can be customised by overriding `wagtailadmin/pages/listing/_button_with_dropdown.html`. The JavaScript that runs the dropdowns makes use of custom data attributes, so you should leave `data-dropdown` and `data-dropdown-toggle` in the markup if you customise it.
Page serving
------------
### `before_serve_page`
Called when Wagtail is about to serve a page. The callable passed into the hook will receive the page object, the request object, and the `args` and `kwargs` that will be passed to the page’s `serve()` method. If the callable returns an `HttpResponse`, that response will be returned immediately to the user, and Wagtail will not proceed to call `serve()` on the page.
```
from django.http import HttpResponse
from wagtail import hooks
@hooks.register('before_serve_page')
def block_googlebot(page, request, serve_args, serve_kwargs):
if request.META.get('HTTP_USER_AGENT') == 'GoogleBot':
return HttpResponse("<h1>bad googlebot no cookie</h1>")
```
Document serving
----------------
### `before_serve_document`
Called when Wagtail is about to serve a document. The callable passed into the hook will receive the document object and the request object. If the callable returns an `HttpResponse`, that response will be returned immediately to the user, instead of serving the document. Note that this hook will be skipped if the [`WAGTAILDOCS_SERVE_METHOD`](settings#wagtaildocs-serve-method) setting is set to `direct`.
Snippets
--------
Hooks for working with registered Snippets.
### `after_edit_snippet`
Called when a Snippet is edited. The callable passed into the hook will receive the model instance, the request object. If the callable returns an `HttpResponse`, that response will be returned immediately to the user, and Wagtail will not proceed to call `redirect()` to the listing view.
```
from django.http import HttpResponse
from wagtail import hooks
@hooks.register('after_edit_snippet')
def after_snippet_update(request, instance):
return HttpResponse(f"Congrats on editing a snippet with id {instance.pk}", content_type="text/plain")
```
### `before_edit_snippet`
Called at the beginning of the edit snippet view. The callable passed into the hook will receive the model instance, the request object. If the callable returns an `HttpResponse`, that response will be returned immediately to the user, and Wagtail will not proceed to call `redirect()` to the listing view.
```
from django.http import HttpResponse
from wagtail import hooks
@hooks.register('before_edit_snippet')
def block_snippet_edit(request, instance):
if isinstance(instance, RestrictedSnippet) and instance.prevent_edit:
return HttpResponse("Sorry, you can't edit this snippet", content_type="text/plain")
```
### `after_create_snippet`
Called when a Snippet is created. `after_create_snippet` and `after_edit_snippet` work in identical ways. The only difference is where the hook is called.
### `before_create_snippet`
Called at the beginning of the create snippet view. Works in a similar way to `before_edit_snippet` except the model is passed as an argument instead of an instance.
### `after_delete_snippet`
Called when a Snippet is deleted. The callable passed into the hook will receive the model instance(s) as a queryset along with the request object. If the callable returns an `HttpResponse`, that response will be returned immediately to the user, and Wagtail will not proceed to call `redirect()` to the listing view.
```
from django.http import HttpResponse
from wagtail import hooks
@hooks.register('after_delete_snippet')
def after_snippet_delete(request, instances):
# "instances" is a QuerySet
total = len(instances)
return HttpResponse(f"{total} snippets have been deleted", content_type="text/plain")
```
### `before_delete_snippet`
Called at the beginning of the delete snippet view. The callable passed into the hook will receive the model instance(s) as a queryset along with the request object. If the callable returns an `HttpResponse`, that response will be returned immediately to the user, and Wagtail will not proceed to call `redirect()` to the listing view.
```
from django.http import HttpResponse
from wagtail import hooks
@hooks.register('before_delete_snippet')
def before_snippet_delete(request, instances):
# "instances" is a QuerySet
total = len(instances)
if request.method == 'POST':
# Override the deletion behaviour
instances.delete()
return HttpResponse(f"{total} snippets have been deleted", content_type="text/plain")
```
### `register_snippet_action_menu_item`
Add an item to the popup menu of actions on the snippet creation and edit views. The callable passed to this hook must return an instance of `wagtail.snippets.action_menu.ActionMenuItem`. `ActionMenuItem` is a subclass of [Component](../extending/template_components#creating-template-components) and so the rendering of the menu item can be customised through `template_name`, `get_context_data`, `render_html` and `Media`. In addition, the following attributes and methods are available to be overridden:
* `order`- an integer (default 100) which determines the item’s position in the menu. Can also be passed as a keyword argument to the object constructor. The lowest-numbered item in this sequence will be selected as the default menu item; as standard, this is “Save draft” (which has an`order` of 0).
* `label` - the displayed text of the menu item
* `get_url` - a method which returns a URL for the menu item to link to; by default, returns `None` which causes the menu item to behave as a form submit button instead
* `name` - value of the `name` attribute of the submit button if no URL is specified
* `icon_name` - icon to display against the menu item
* `classname` - a `class` attribute value to add to the button element
* `is_shown` - a method which returns a boolean indicating whether the menu item should be shown; by default, true except when editing a locked page
The `get_url`, `is_shown`, `get_context_data` and `render_html` methods all accept a context dictionary containing the following fields:
* `view` - name of the current view: `'create'` or `'edit'`
* `model` - the snippet’s model class
* `instance` - for `view` = `'edit'`, the instance being edited
* `request` - the current request object
```
from wagtail import hooks
from wagtail.snippets.action_menu import ActionMenuItem
class GuacamoleMenuItem(ActionMenuItem):
name = 'action-guacamole'
label = "Guacamole"
def get_url(self, context):
return "https://www.youtube.com/watch?v=dNJdJIwCF_Y"
@hooks.register('register_snippet_action_menu_item')
def register_guacamole_menu_item():
return GuacamoleMenuItem(order=10)
```
### `construct_snippet_action_menu`
Modify the final list of action menu items on the snippet creation and edit views. The callable passed to this hook receives a list of `ActionMenuItem` objects, a request object and a context dictionary as per `register_snippet_action_menu_item`, and should modify the list of menu items in-place.
```
@hooks.register('construct_snippet_action_menu')
def remove_delete_option(menu_items, request, context):
menu_items[:] = [item for item in menu_items if item.name != 'delete']
```
The `construct_snippet_action_menu` hook is called after the menu items have been sorted by their order attributes, and so setting a menu item’s order will have no effect at this point. Instead, items can be reordered by changing their position in the list, with the first item being selected as the default action. For example, to change the default action to Delete:
```
@hooks.register('construct_snippet_action_menu')
def make_delete_default_action(menu_items, request, context):
for (index, item) in enumerate(menu_items):
if item.name == 'delete':
# move to top of list
menu_items.pop(index)
menu_items.insert(0, item)
break
```
### `register_snippet_listing_buttons`
Add buttons to the actions list for a snippet in the snippets listing. This is useful when adding custom actions to the listing, such as translations or a complex workflow.
This example will add a simple button to the listing:
```
from wagtail.snippets import widgets as wagtailsnippets_widgets
@hooks.register('register_snippet_listing_buttons')
def snippet_listing_buttons(snippet, user, next_url=None):
yield wagtailsnippets_widgets.SnippetListingButton(
'A page listing button',
'/goes/to/a/url/',
priority=10
)
```
The arguments passed to the hook are as follows:
* `snippet` - the snippet object to generate the button for
* `user` - the user who is viewing the snippets listing
* `next_url` - the URL that the linked action should redirect back to on completion of the action, if the view supports it
The `priority` argument controls the order the buttons are displayed in. Buttons are ordered from low to high priority, so a button with `priority=10` will be displayed before a button with `priority=20`.
### `construct_snippet_listing_buttons`
Modify the final list of snippet listing buttons. The callable passed to this hook receives a list of `SnippetListingButton` objects, a user, and a context dictionary as per `register_snippet_listing_buttons`, and should modify the list of menu items in-place.
```
@hooks.register('construct_snippet_listing_buttons')
def remove_snippet_listing_button_item(buttons, snippet, user, context=None):
buttons.pop() # Removes the 'delete' button
```
Bulk actions
------------
Hooks for registering and customising bulk actions. See [Adding custom bulk actions](../extending/custom_bulk_actions#custom-bulk-actions) on how to write custom bulk actions.
### `register_bulk_action`
Registers a new bulk action to add to the list of bulk actions in the explorer
This hook must be registered with a sub-class of `BulkAction` . For example:
```
from wagtail.admin.views.bulk_action import BulkAction
from wagtail import hooks
@hooks.register("register_bulk_action")
class CustomBulkAction(BulkAction):
display_name = _("Custom Action")
action_type = "action"
aria_label = _("Do custom action")
template_name = "/path/to/template"
models = [...] # list of models the action should execute upon
@classmethod
def execute_action(cls, objects, **kwargs):
for object in objects:
do_something(object)
return num_parent_objects, num_child_objects # return the count of updated objects
```
### `before_bulk_action`
Do something right before a bulk action is executed (before the `execute_action` method is called)
This hook can be used to return an HTTP response. For example:
```
from wagtail import hooks
@hooks.register("before_bulk_action")
def hook_func(request, action_type, objects, action_class_instance):
if action_type == 'delete':
return HttpResponse(f"{len(objects)} objects would be deleted", content_type="text/plain")
```
### `after_bulk_action`
Do something right after a bulk action is executed (after the `execute_action` method is called)
This hook can be used to return an HTTP response. For example:
```
from wagtail import hooks
@hooks.register("after_bulk_action")
def hook_func(request, action_type, objects, action_class_instance):
if action_type == 'delete':
return HttpResponse(f"{len(objects)} objects have been deleted", content_type="text/plain")
```
Audit log
---------
### `register_log_actions`
See [Audit log](../extending/audit_log#audit-log)
To add new actions to the registry, call the `register_action` method with the action type, its label and the message to be displayed in administrative listings.
```
from django.utils.translation import gettext_lazy as _
from wagtail import hooks
@hooks.register('register_log_actions')
def additional_log_actions(actions):
actions.register_action('wagtail_package.echo', _('Echo'), _('Sent an echo'))
```
Alternatively, for a log message that varies according to the log entry’s data, create a subclass of `wagtail.log_actions.LogFormatter` that overrides the `format_message` method, and use `register_action` as a decorator on that class:
```
from django.utils.translation import gettext_lazy as _
from wagtail import hooks
from wagtail.log_actions import LogFormatter
@hooks.register('register_log_actions')
def additional_log_actions(actions):
@actions.register_action('wagtail_package.greet_audience')
class GreetingActionFormatter(LogFormatter):
label = _('Greet audience')
def format_message(self, log_entry):
return _('Hello %(audience)s') % {
'audience': log_entry.data['audience'],
}
```
Changed in version 2.15: The `LogFormatter` class was introduced. Previously, dynamic messages were achieved by passing a callable as the `message` argument to `register_action`.
| programming_docs |
wagtail Management commands Management commands
===================
publish\_scheduled
------------------
Changed in version 4.1: This command has been renamed from `publish_scheduled_pages` to `publish_scheduled` and it now also handles non-page objects. The `publish_scheduled_pages` command is still available as an alias, but it is recommended to update your configuration to run the `publish_scheduled` command instead.
```
./manage.py publish_scheduled
```
This command publishes, updates or unpublishes objects that have had these actions scheduled by an editor. We recommend running this command once an hour.
fixtree
-------
```
./manage.py fixtree
```
This command scans for errors in your database and attempts to fix any issues it finds.
move\_pages
-----------
```
manage.py move_pages from to
```
This command moves a selection of pages from one section of the tree to another.
Options:
* **from** This is the **id** of the page to move pages from. All descendants of this page will be moved to the destination. After the operation is complete, this page will have no children.
* **to** This is the **id** of the page to move pages to.
purge\_revisions
----------------
```
manage.py purge_revisions [--days=<number of days>]
```
This command deletes old page revisions which are not in moderation, live, approved to go live, or the latest revision for a page. If the `days` argument is supplied, only revisions older than the specified number of days will be deleted.
update\_index
-------------
```
./manage.py update_index [--backend <backend name>]
```
This command rebuilds the search index from scratch.
It is recommended to run this command once a week and at the following times:
* whenever any pages have been created through a script (after an import, for example)
* whenever any changes have been made to models or search configuration
The search may not return any results while this command is running, so avoid running it at peak times.
### Specifying which backend to update
By default, `update_index` will rebuild all the search indexes listed in `WAGTAILSEARCH_BACKENDS`.
If you have multiple backends and would only like to update one of them, you can use the `--backend` option.
For example, to update just the default backend:
```
python manage.py update_index --backend default
```
The `--chunk_size` option can be used to set the size of chunks that are indexed at a time. This defaults to 1000 but may need to be reduced for larger document sizes.
### Indexing the schema only
You can prevent the `update_index` command from indexing any data by using the `--schema-only` option:
```
python manage.py update_index --schema-only
```
### Silencing the command
You can prevent logs to the console by providing `--verbosity 0` as an argument:
```
$ python manage.py update_index --verbosity 0
```
If this is omitted or provided with any number above 0 it will produce the same logs.
wagtail\_update\_index
----------------------
An alias for the `update_index` command that can be used when another installed package (such as [Haystack](https://haystacksearch.org/)) provides a command named `update_index`. In this case, the other package’s entry in `INSTALLED_APPS` should appear above `wagtail.search` so that its `update_index` command takes precedence over Wagtail’s.
rebuild\_references\_index
--------------------------
```
./manage.py rebuild_references_index
```
This command populates the table that tracks cross-references between objects, used for the usage reports on images, documents and snippets. This table is updated automatically saving objects, but it is recommended to run this command periodically to ensure that the data remains consistent.
search\_garbage\_collect
------------------------
```
./manage.py search_garbage_collect
```
Wagtail keeps a log of search queries that are popular on your website. On high traffic websites, this log may get big and you may want to clean out old search queries. This command cleans out all search query logs that are more than one week old (or a number of days configurable through the [`WAGTAILSEARCH_HITS_MAX_AGE`](settings#wagtailsearch-hits-max-age) setting).
wagtail\_update\_image\_renditions
----------------------------------
```
./manage.py wagtail_update_image_renditions
```
This command provides the ability to regenerate image renditions. This is useful if you have deployed to a server where the image renditions have not yet been generated or you have changed the underlying image rendition behaviour and need to ensure all renditions are created again.
This does not remove rendition images that are unused, this can be done by clearing the folder using `rm -rf` or similar, once this is done you can then use the management command to generate the renditions.
Options:
* **–purge-only** : This argument will purge all image renditions without regenerating them. They will be regenerated when next requested.
wagtail Jinja2 template support Jinja2 template support
=======================
Wagtail supports Jinja2 templating for all front end features. More information on each of the template tags below can be found in the [Writing templates](../topics/writing_templates#writing-templates) documentation.
Configuring Django
------------------
Django needs to be configured to support Jinja2 templates. As the Wagtail admin is written using standard Django templates, Django has to be configured to use **both** templating engines. Add the Jinja2 template backend configuration to the `TEMPLATES` setting for your app as shown here:
```
TEMPLATES = [
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
# ... the rest of the existing Django template configuration ...
},
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'APP_DIRS': True,
'OPTIONS': {
'extensions': [
'wagtail.jinja2tags.core',
'wagtail.admin.jinja2tags.userbar',
'wagtail.images.jinja2tags.images',
],
},
}
]
```
Jinja templates must be placed in a `jinja2/` directory in your app. For example, the standard template location for an `EventPage` model in an `events` app would be `events/jinja2/events/event_page.html`.
By default, the Jinja environment does not have any Django functions or filters. The Django documentation has more information on [`django.template.backends.jinja2.Jinja2`](https://docs.djangoproject.com/en/stable/topics/templates/#django.template.backends.jinja2.Jinja2 "(in Django v4.1)") (configuring Jinja for Django).
`self` in templates
--------------------
In Django templates, `self` can be used to refer to the current page, stream block, or field panel. In Jinja, `self` is reserved for internal use. When writing Jinja templates, use `page` to refer to pages, `value` for stream blocks, and `field_panel` for field panels.
Template tags, functions & filters
----------------------------------
### `pageurl()`
Generate a URL for a Page instance:
```
<a href="{{ pageurl(page.more_information) }}">More information</a>
```
See [pageurl](../topics/writing_templates#pageurl-tag) for more information
### `slugurl()`
Generate a URL for a Page with a slug:
```
<a href="{{ slugurl("about") }}">About us</a>
```
See [slugurl](../topics/writing_templates#slugurl-tag) for more information
### `image()`
Resize an image, and print an `<img>` tag:
```
{# Print an image tag #}
{{ image(page.header_image, "fill-1024x200", class="header-image") }}
{# Resize an image #}
{% set background=image(page.background_image, "max-1024x1024") %}
<div class="wrapper" style="background-image: url({{ background.url }});">
```
See [How to use images in templates](../topics/images#image-tag) for more information
### `|richtext`
Transform Wagtail’s internal HTML representation, expanding internal references to pages and images.
```
{{ page.body|richtext }}
```
See [Rich text (filter)](../topics/writing_templates#rich-text-filter) for more information
### `wagtail_site`
Returns the Site object corresponding to the current request.
```
{{ wagtail_site().site_name }}
```
See [wagtail\_site](../topics/writing_templates#wagtail-site-tag) for more information
### `wagtailuserbar()`
Output the Wagtail contextual flyout menu for editing pages from the front end
```
{{ wagtailuserbar() }}
```
See [Wagtail User Bar](../topics/writing_templates#wagtailuserbar-tag) for more information
### `{% include_block %}`
Output the HTML representation for the stream content as a whole, as well as for each individual block.
Allows to pass template context (by default) to the StreamField template.
```
{% include_block page.body %}
{% include_block page.body with context %} {# The same as the previous #}
{% include_block page.body without context %}
```
See [StreamField template rendering](../topics/streamfield#streamfield-template-rendering) for more information.
Note
The `{% include_block %}` tag is designed to closely follow the syntax and behaviour of Jinja’s `{% include %}`, so it does not implement the Django version’s feature of only passing specified variables into the context.
wagtail The project template The project template
====================
```
mysite/
home/
migrations/
__init__.py
0001_initial.py
0002_create_homepage.py
templates/
home/
home_page.html
__init__.py
models.py
search/
templates/
search/
search.html
__init__.py
views.py
mysite/
settings/
__init__.py
base.py
dev.py
production.py
static/
css/
mysite.css
js/
mysite.js
templates/
404.html
500.html
base.html
__init__.py
urls.py
wsgi.py
Dockerfile
manage.py
requirements.txt
```
The “home” app
--------------
Location: `/mysite/home/`
This app is here to help get you started quicker by providing a `HomePage` model with migrations to create one when you first set up your app.
Default templates and static files
----------------------------------
Location: `/mysite/mysite/templates/` and `/mysite/mysite/static/`
The templates directory contains `base.html`, `404.html` and `500.html`. These files are very commonly needed on Wagtail sites to they have been added into the template.
The static directory contains an empty JavaScript and CSS file.
Django settings
---------------
Location: `/mysite/mysite/settings/`
The Django settings files are split up into `base.py`, `dev.py`, `production.py` and `local.py`.
* `base.py` This file is for global settings that will be used in both development and production. Aim to keep most of your configuration in this file.
* `dev.py` This file is for settings that will only be used by developers. For example: `DEBUG = True`
* `production.py` This file is for settings that will only run on a production server. For example: `DEBUG = False`
* `local.py` This file is used for settings local to a particular machine. This file should never be tracked by a version control system.
Note
On production servers, we recommend that you only store secrets in `local.py` (such as API keys and passwords). This can save you headaches in the future if you are ever trying to debug why a server is behaving badly. If you are using multiple servers which need different settings then we recommend that you create a different `production.py` file for each one.
Dockerfile
----------
Location: `/mysite/Dockerfile`
Contains configuration for building and deploying the site as a [Docker](https://docs.docker.com/) container. To build and use the Docker image for your project, run:
```
docker build -t mysite .
docker run -p 8000:8000 mysite
```
wagtail Settings Settings
========
Wagtail makes use of the following settings, in addition to [Django’s core settings](https://docs.djangoproject.com/en/stable/ref/settings/ "(in Django v4.1)")`:
Sites
-----
### `WAGTAIL_SITE_NAME`
```
WAGTAIL_SITE_NAME = 'Stark Industries Skunkworks'
```
This is the human-readable name of your Wagtail install which welcomes users upon login to the Wagtail admin.
### `WAGTAILADMIN_BASE_URL`
```
WAGTAILADMIN_BASE_URL = 'http://example.com'
```
This is the base URL used by the Wagtail admin site. It is typically used for generating URLs to include in notification emails.
If this setting is not present, Wagtail will try to fall back to `request.site.root_url` or to the request’s host name.
Changed in version 3.0: This setting was previously named `BASE_URL` and was undocumented, using `BASE_URL` will be removed in a future release.
Append Slash
------------
### `WAGTAIL_APPEND_SLASH`
```
# Don't add a trailing slash to Wagtail-served URLs
WAGTAIL_APPEND_SLASH = False
```
Similar to Django’s `APPEND_SLASH`, this setting controls how Wagtail will handle requests that don’t end in a trailing slash.
When `WAGTAIL_APPEND_SLASH` is `True` (default), requests to Wagtail pages which omit a trailing slash will be redirected by Django’s [`CommonMiddleware`](https://docs.djangoproject.com/en/stable/ref/middleware/#django.middleware.common.CommonMiddleware "(in Django v4.1)") to a URL with a trailing slash.
When `WAGTAIL_APPEND_SLASH` is `False`, requests to Wagtail pages will be served both with and without trailing slashes. Page links generated by Wagtail, however, will not include trailing slashes.
Note
If you use the `False` setting, keep in mind that serving your pages both with and without slashes may affect search engines’ ability to index your site. See [this Google Search Central Blog post](https://developers.google.com/search/blog/2010/04/to-slash-or-not-to-slash) for more details.
Search
------
### `WAGTAILSEARCH_BACKENDS`
```
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.search.backends.elasticsearch5',
'INDEX': 'myapp'
}
}
```
Define a search backend. For a full explanation, see [Backends](../topics/search/backends#wagtailsearch-backends).
### `WAGTAILSEARCH_HITS_MAX_AGE`
```
WAGTAILSEARCH_HITS_MAX_AGE = 14
```
Set the number of days (default 7) that search query logs are kept for; these are used to identify popular search terms for [promoted search results](contrib/searchpromotions#editors-picks). Queries older than this will be removed by the [rebuild\_references\_index](management_commands#search-garbage-collect) command.
Internationalisation
--------------------
Wagtail supports internationalisation of content by maintaining separate trees of pages for each language.
For a guide on how to enable internationalisation on your site, see the [configuration guide](../advanced_topics/i18n#enabling-internationalisation).
### `WAGTAIL_I18N_ENABLED`
(boolean, default `False`)
When set to `True`, Wagtail’s internationalisation features will be enabled:
```
WAGTAIL_I18N_ENABLED = True
```
### `WAGTAIL_CONTENT_LANGUAGES`
(list, default `[]`)
A list of languages and/or locales that Wagtail content can be authored in.
For example:
```
WAGTAIL_CONTENT_LANGUAGES = [
('en', _("English")),
('fr', _("French")),
]
```
Each item in the list is a 2-tuple containing a language code and a display name. The language code can either be a language code on its own (such as `en`, `fr`), or it can include a region code (such as `en-gb`, `fr-fr`). You can mix the two formats if you only need to localize in some regions but not others.
This setting follows the same structure of Django’s `LANGUAGES` setting, so they can both be set to the same value:
```
LANGUAGES = WAGTAIL_CONTENT_LANGUAGES = [
('en-gb', _("English (United Kingdom)")),
('en-us', _("English (United States)")),
('es-es', _("Spanish (Spain)")),
('es-mx', _("Spanish (Mexico)")),
]
```
However having them separate allows you to configure many different regions on your site yet have them share Wagtail content (but defer on things like date formatting, currency, etc):
```
LANGUAGES = [
('en', _("English (United Kingdom)")),
('en-us', _("English (United States)")),
('es', _("Spanish (Spain)")),
('es-mx', _("Spanish (Mexico)")),
]
WAGTAIL_CONTENT_LANGUAGES = [
('en', _("English")),
('es', _("Spanish")),
]
```
This would mean that your site will respond on the `https://www.mysite.com/es/` and `https://www.mysite.com/es-MX/` URLs, but both of them will serve content from the same “Spanish” tree in Wagtail.
Note
`WAGTAIL_CONTENT_LANGUAGES` must be a subset of `LANGUAGES`
Note that all languages that exist in `WAGTAIL_CONTENT_LANGUAGES` must also exist in your `LANGUAGES` setting. This is so that Wagtail can generate a live URL to these pages from an untranslated context (such as the admin interface).
Embeds
------
Wagtail supports generating embed code from URLs to content on an external providers such as Youtube or Twitter. By default, Wagtail will fetch the embed code directly from the relevant provider’s site using the oEmbed protocol. Wagtail has a builtin list of the most common providers.
The embeds fetching can be fully configured using the `WAGTAILEMBEDS_FINDERS` setting. This is fully documented in [Configuring embed “finders”](../advanced_topics/embeds#configuring-embed-finders).
### `WAGTAILEMBEDS_RESPONSIVE_HTML`
```
WAGTAILEMBEDS_RESPONSIVE_HTML = True
```
Adds `class="responsive-object"` and an inline `padding-bottom` style to embeds, to assist in making them responsive. See [Responsive Embeds](../topics/writing_templates#responsive-embeds) for details.
Dashboard
---------
### `WAGTAILADMIN_RECENT_EDITS_LIMIT`
```
WAGTAILADMIN_RECENT_EDITS_LIMIT = 5
```
This setting lets you change the number of items shown at ‘Your most recent edits’ on the dashboard.
General editing
---------------
### `WAGTAILADMIN_RICH_TEXT_EDITORS`
```
WAGTAILADMIN_RICH_TEXT_EDITORS = {
'default': {
'WIDGET': 'wagtail.admin.rich_text.DraftailRichTextArea',
'OPTIONS': {
'features': ['h2', 'bold', 'italic', 'link', 'document-link']
}
},
'secondary': {
'WIDGET': 'some.external.RichTextEditor',
}
}
```
Customise the behaviour of rich text fields. By default, `RichTextField` and `RichTextBlock` use the configuration given under the `'default'` key, but this can be overridden on a per-field basis through the `editor` keyword argument, for example `body = RichTextField(editor='secondary')`. Within each configuration block, the following fields are recognised:
* `WIDGET`: The rich text widget implementation to use. Wagtail provides `wagtail.admin.rich_text.DraftailRichTextArea` (a modern extensible editor which enforces well-structured markup). Other widgets may be provided by third-party packages.
* `OPTIONS`: Configuration options to pass to the widget. Recognised options are widget-specific, but `DraftailRichTextArea` accept a `features` list indicating the active rich text features (see [Limiting features in a rich text field](../advanced_topics/customisation/page_editing_interface#rich-text-features)).
If a `'default'` editor is not specified, rich text fields that do not specify an `editor` argument will use the Draftail editor with the default feature set enabled.
### `WAGTAILADMIN_EXTERNAL_LINK_CONVERSION`
```
WAGTAILADMIN_EXTERNAL_LINK_CONVERSION = 'exact'
```
Customise Wagtail’s behaviour when an internal page url is entered in the external link chooser. Possible values for this setting are `'all'`, `'exact'`, `'confirm`, or `''`. The default, `'all'`, means that Wagtail will automatically convert submitted urls that exactly match page urls to the corresponding internal links. If the url is an inexact match - for example, the submitted url has query parameters - then Wagtail will confirm the conversion with the user. `'exact'` means that any inexact matches will be left as external urls, and the confirmation step will be skipped. `'confirm'` means that every link conversion will be confirmed with the user, even if the match is exact. `''` means that Wagtail will not attempt to convert any urls entered to internal page links.
###
`WAGTAIL_DATE_FORMAT`, `WAGTAIL_DATETIME_FORMAT`, `WAGTAIL_TIME_FORMAT`
```
WAGTAIL_DATE_FORMAT = '%d.%m.%Y.'
WAGTAIL_DATETIME_FORMAT = '%d.%m.%Y. %H:%M'
WAGTAIL_TIME_FORMAT = '%H:%M'
```
Specifies the date, time and datetime format to be used in input fields in the Wagtail admin. The format is specified in [Python datetime module syntax](https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior), and must be one of the recognised formats listed in the `DATE_INPUT_FORMATS`, `TIME_INPUT_FORMATS`, or `DATETIME_INPUT_FORMATS` setting respectively (see [DATE\_INPUT\_FORMATS](https://docs.djangoproject.com/en/stable/ref/settings/#std:setting-DATE_INPUT_FORMATS)).
Page editing
------------
### `WAGTAILADMIN_COMMENTS_ENABLED`
```
# Disable commenting
WAGTAILADMIN_COMMENTS_ENABLED = False
```
Sets whether commenting is enabled for pages (`True` by default).
### `WAGTAIL_ALLOW_UNICODE_SLUGS`
```
WAGTAIL_ALLOW_UNICODE_SLUGS = True
```
By default, page slugs can contain any alphanumeric characters, including non-Latin alphabets. Set this to False to limit slugs to ASCII characters.
### `WAGTAIL_AUTO_UPDATE_PREVIEW`
```
WAGTAIL_AUTO_UPDATE_PREVIEW = True
```
When enabled, the preview panel in the page editor is automatically updated on each change. If set to `False`, a refresh button will be shown and the preview is only updated when the button is clicked. This behaviour is enabled by default.
To completely disable the preview panel, set [preview modes](pages/model_reference#wagtail.models.Page.preview_modes "wagtail.models.Page.preview_modes") to be empty on your model `preview_modes = []`.
### `WAGTAIL_AUTO_UPDATE_PREVIEW_INTERVAL`
```
WAGTAIL_AUTO_UPDATE_PREVIEW_INTERVAL = 500
```
The interval (in milliseconds) to check for changes made in the page editor before updating the preview. The default value is `500`.
### `WAGTAILADMIN_GLOBAL_PAGE_EDIT_LOCK`
`WAGTAILADMIN_GLOBAL_PAGE_EDIT_LOCK` can be set to `True` to prevent users from editing pages that they have locked.
### `WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT`
```
WAGTAILADMIN_UNSAFE_PAGE_DELETION_LIMIT = 20
```
This setting enables an additional confirmation step when deleting a page with a large number of child pages. If the number of pages is greater than or equal to this limit (10 by default), the user must enter the site name (as defined by `WAGTAIL_SITE_NAME`) to proceed.
Images
------
### `WAGTAILIMAGES_IMAGE_MODEL`
```
WAGTAILIMAGES_IMAGE_MODEL = 'myapp.MyImage'
```
This setting lets you provide your own image model for use in Wagtail, which should extend the built-in `AbstractImage` class.
### `WAGTAILIMAGES_IMAGE_FORM_BASE`
```
WAGTAILIMAGES_IMAGE_FORM_BASE = 'myapp.forms.MyImageBaseForm'
```
This setting lets you provide your own image base form for use in Wagtail, which should extend the built-in `BaseImageForm` class. You can use it to specify or override the widgets to use in the admin form.
### `WAGTAILIMAGES_MAX_UPLOAD_SIZE`
```
WAGTAILIMAGES_MAX_UPLOAD_SIZE = 20 * 1024 * 1024 # 20MB
```
This setting lets you override the maximum upload size for images (in bytes). If omitted, Wagtail will fall back to using its 10MB default value.
### `WAGTAILIMAGES_MAX_IMAGE_PIXELS`
```
WAGTAILIMAGES_MAX_IMAGE_PIXELS = 128000000 # 128 megapixels
```
This setting lets you override the maximum number of pixels an image can have. If omitted, Wagtail will fall back to using its 128 megapixels default value. The pixel count takes animation frames into account - for example, a 25-frame animation of size 100x100 is considered to have 100 \_ 100 \_ 25 = 250000 pixels.
### `WAGTAILIMAGES_FEATURE_DETECTION_ENABLED`
```
WAGTAILIMAGES_FEATURE_DETECTION_ENABLED = True
```
This setting enables feature detection once OpenCV is installed, see all details on the [Feature Detection](../advanced_topics/images/feature_detection#image-feature-detection) documentation.
### `WAGTAILIMAGES_INDEX_PAGE_SIZE`
```
WAGTAILIMAGES_INDEX_PAGE_SIZE = 20
```
Specifies the number of images per page shown on the main Images listing in the Wagtail admin.
### `WAGTAILIMAGES_USAGE_PAGE_SIZE`
```
WAGTAILIMAGES_USAGE_PAGE_SIZE = 20
```
Specifies the number of items per page shown when viewing an image’s usage.
### `WAGTAILIMAGES_CHOOSER_PAGE_SIZE`
```
WAGTAILIMAGES_CHOOSER_PAGE_SIZE = 12
```
Specifies the number of images shown per page in the image chooser modal.
### `WAGTAILIMAGES_RENDITION_STORAGE`
```
WAGTAILIMAGES_RENDITION_STORAGE = 'myapp.backends.MyCustomStorage'
```
This setting allows image renditions to be stored using an alternative storage backend. The default is `None`, which will use Django’s default `FileSystemStorage`.
Custom storage classes should subclass `django.core.files.storage.Storage`. See the [Django file storage API](https://docs.djangoproject.com/en/stable/ref/files/storage/ "(in Django v4.1)").
Documents
---------
### `WAGTAILDOCS_DOCUMENT_MODEL`
```
WAGTAILDOCS_DOCUMENT_MODEL = 'myapp.MyDocument'
```
This setting lets you provide your own document model for use in Wagtail, which should extend the built-in `AbstractDocument` class.
### `WAGTAILDOCS_DOCUMENT_FORM_BASE`
```
WAGTAILDOCS_DOCUMENT_FORM_BASE = 'myapp.forms.MyDocumentBaseForm'
```
This setting lets you provide your own Document base form for use in Wagtail, which should extend the built-in `BaseDocumentForm` class. You can use it to specify or override the widgets to use in the admin form.
### `WAGTAILDOCS_SERVE_METHOD`
```
WAGTAILDOCS_SERVE_METHOD = 'redirect'
```
Determines how document downloads will be linked to and served. Normally, requests for documents are sent through a Django view, to perform privacy checks (see ) and potentially other housekeeping tasks such as hit counting. To fully protect against users bypassing this check, it needs to happen in the same request where the document is served; however, this incurs a performance hit as the document then needs to be served by the Django server. In particular, this cancels out much of the benefit of hosting documents on external storage, such as S3 or a CDN.
For this reason, Wagtail provides a number of serving methods which trade some of the strictness of the permission check for performance:
* `'direct'` - links to documents point directly to the URL provided by the underlying storage, bypassing the Django view that provides the permission check. This is most useful when deploying sites as fully static HTML (for example using [wagtail-bakery](https://github.com/wagtail/wagtail-bakery) or [Gatsby](https://www.gatsbyjs.org/)).
* `'redirect'` - links to documents point to a Django view which will check the user’s permission; if successful, it will redirect to the URL provided by the underlying storage to allow the document to be downloaded. This is most suitable for remote storage backends such as S3, as it allows the document to be served independently of the Django server. Note that if a user is able to guess the latter URL, they will be able to bypass the permission check; some storage backends may provide configuration options to generate a random or short-lived URL to mitigate this.
* `'serve_view'` - links to documents point to a Django view which both checks the user’s permission, and serves the document. Serving will be handled by [django-sendfile](https://github.com/johnsensible/django-sendfile), if this is installed and supported by your server configuration, or as a streaming response from Django if not. When using this method, it is recommended that you configure your webserver to *disallow* serving documents directly from their location under `MEDIA_ROOT`, as this would provide a way to bypass the permission check.
If `WAGTAILDOCS_SERVE_METHOD` is unspecified or set to `None`, the default method is `'redirect'` when a remote storage backend is in use (one that exposes a URL but not a local filesystem path), and `'serve_view'` otherwise. Finally, some storage backends may not expose a URL at all; in this case, serving will proceed as for `'serve_view'`.
### `WAGTAILDOCS_CONTENT_TYPES`
```
WAGTAILDOCS_CONTENT_TYPES = {
'pdf': 'application/pdf',
'txt': 'text/plain',
}
```
Specifies the MIME content type that will be returned for the given file extension, when using the `serve_view` method. Content types not listed here will be guessed using the Python `mimetypes.guess_type` function, or `application/octet-stream` if unsuccessful.
### `WAGTAILDOCS_INLINE_CONTENT_TYPES`
```
WAGTAILDOCS_INLINE_CONTENT_TYPES = ['application/pdf', 'text/plain']
```
A list of MIME content types that will be shown inline in the browser (by serving the HTTP header `Content-Disposition: inline`) rather than served as a download, when using the `serve_view` method. Defaults to `application/pdf`.
### `WAGTAILDOCS_EXTENSIONS`
```
WAGTAILDOCS_EXTENSIONS = ['pdf', 'docx']
```
A list of allowed document extensions that will be validated during document uploading. If this isn’t supplied all document extensions are allowed. Warning: this doesn’t always ensure that the uploaded file is valid as files can be renamed to have an extension no matter what data they contain.
User Management
---------------
### `WAGTAIL_PASSWORD_MANAGEMENT_ENABLED`
```
WAGTAIL_PASSWORD_MANAGEMENT_ENABLED = True
```
This specifies whether users are allowed to change their passwords (enabled by default).
### `WAGTAIL_PASSWORD_RESET_ENABLED`
```
WAGTAIL_PASSWORD_RESET_ENABLED = True
```
This specifies whether users are allowed to reset their passwords. Defaults to the same as `WAGTAIL_PASSWORD_MANAGEMENT_ENABLED`. Password reset emails will be sent from the address specified in Django’s `DEFAULT_FROM_EMAIL` setting.
### `WAGTAILUSERS_PASSWORD_ENABLED`
```
WAGTAILUSERS_PASSWORD_ENABLED = True
```
This specifies whether password fields are shown when creating or editing users through Settings -> Users (enabled by default). Set this to False (along with `WAGTAIL_PASSWORD_MANAGEMENT_ENABLED` and `WAGTAIL_PASSWORD_RESET_ENABLED`) if your users are authenticated through an external system such as LDAP.
### `WAGTAILUSERS_PASSWORD_REQUIRED`
```
WAGTAILUSERS_PASSWORD_REQUIRED = True
```
This specifies whether password is a required field when creating a new user. True by default; ignored if `WAGTAILUSERS_PASSWORD_ENABLED` is false. If this is set to False, and the password field is left blank when creating a user, then that user will have no usable password; in order to log in, they will have to reset their password (if `WAGTAIL_PASSWORD_RESET_ENABLED` is True) or use an alternative authentication system such as LDAP (if one is set up).
### `WAGTAIL_EMAIL_MANAGEMENT_ENABLED`
```
WAGTAIL_EMAIL_MANAGEMENT_ENABLED = True
```
This specifies whether users are allowed to change their email (enabled by default).
### `WAGTAILADMIN_USER_PASSWORD_RESET_FORM`
```
WAGTAILADMIN_USER_PASSWORD_RESET_FORM = 'users.forms.PasswordResetForm'
```
Allows the default `PasswordResetForm` to be extended with extra fields.
### `WAGTAIL_USER_EDIT_FORM`
```
WAGTAIL_USER_EDIT_FORM = 'users.forms.CustomUserEditForm'
```
Allows the default `UserEditForm` class to be overridden with a custom form when a custom user model is being used and extra fields are required in the user edit form.
For further information See [Custom user models](../advanced_topics/customisation/custom_user_models).
### `WAGTAIL_USER_CREATION_FORM`
```
WAGTAIL_USER_CREATION_FORM = 'users.forms.CustomUserCreationForm'
```
Allows the default `UserCreationForm` class to be overridden with a custom form when a custom user model is being used and extra fields are required in the user creation form.
For further information See [Custom user models](../advanced_topics/customisation/custom_user_models).
### `WAGTAIL_USER_CUSTOM_FIELDS`
```
WAGTAIL_USER_CUSTOM_FIELDS = ['country']
```
A list of the extra custom fields to be appended to the default list.
For further information See [Custom user models](../advanced_topics/customisation/custom_user_models).
### `WAGTAILADMIN_USER_LOGIN_FORM`
```
WAGTAILADMIN_USER_LOGIN_FORM = 'users.forms.LoginForm'
```
Allows the default `LoginForm` to be extended with extra fields.
User preferences
----------------
### `WAGTAIL_GRAVATAR_PROVIDER_URL`
```
WAGTAIL_GRAVATAR_PROVIDER_URL = '//www.gravatar.com/avatar'
```
If a user has not uploaded a profile picture, Wagtail will look for an avatar linked to their email address on gravatar.com. This setting allows you to specify an alternative provider such as like robohash.org, or can be set to `None` to disable the use of remote avatars completely.
### `WAGTAIL_USER_TIME_ZONES`
Logged-in users can choose their current time zone for the admin interface in the account settings. If is no time zone selected by the user, then `TIME_ZONE` will be used. (Note that time zones are only applied to datetime fields, not to plain time or date fields. This is a Django design decision.)
The list of time zones is by default the common\_timezones list from pytz. It is possible to override this list via the `WAGTAIL_USER_TIME_ZONES` setting. If there is zero or one time zone permitted, the account settings form will be hidden.
```
WAGTAIL_USER_TIME_ZONES = ['America/Chicago', 'Australia/Sydney', 'Europe/Rome']
```
### `WAGTAILADMIN_PERMITTED_LANGUAGES`
Users can choose between several languages for the admin interface in the account settings. The list of languages is by default all the available languages in Wagtail with at least 90% coverage. To change it, set `WAGTAILADMIN_PERMITTED_LANGUAGES`:
```
WAGTAILADMIN_PERMITTED_LANGUAGES = [('en', 'English'),
('pt', 'Portuguese')]
```
Since the syntax is the same as Django `LANGUAGES`, you can do this so users can only choose between front office languages:
```
LANGUAGES = WAGTAILADMIN_PERMITTED_LANGUAGES = [('en', 'English'), ('pt', 'Portuguese')]
```
Email notifications
-------------------
### `WAGTAILADMIN_NOTIFICATION_FROM_EMAIL`
```
WAGTAILADMIN_NOTIFICATION_FROM_EMAIL = '[email protected]'
```
Wagtail sends email notifications when content is submitted for moderation, and when the content is accepted or rejected. This setting lets you pick which email address these automatic notifications will come from. If omitted, Wagtail will fall back to using Django’s `DEFAULT_FROM_EMAIL` setting.
### `WAGTAILADMIN_NOTIFICATION_USE_HTML`
```
WAGTAILADMIN_NOTIFICATION_USE_HTML = True
```
Notification emails are sent in `text/plain` by default, change this to use HTML formatting.
### `WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS`
```
WAGTAILADMIN_NOTIFICATION_INCLUDE_SUPERUSERS = False
```
Notification emails are sent to moderators and superusers by default. You can change this to exclude superusers and only notify moderators.
Wagtail update notifications
----------------------------
### `WAGTAIL_ENABLE_UPDATE_CHECK`
```
WAGTAIL_ENABLE_UPDATE_CHECK = True
```
For admins only, Wagtail performs a check on the dashboard to see if newer releases are available. This also provides the Wagtail team with the hostname of your Wagtail site. If you’d rather not receive update notifications, or if you’d like your site to remain unknown, you can disable it with this setting.
If admins should only be informed of new long term support (LTS) versions, then set this setting to `"lts"` (the setting is case-insensitive).
### `WAGTAIL_ENABLE_WHATS_NEW_BANNER`
```
WAGTAIL_ENABLE_WHATS_NEW_BANNER = True
```
For new releases, Wagtail may show a notification banner on the dashboard that helps users learn more about the UI changes and new features in the release. Users are able to dismiss this banner, which will hide it until the next release. If you’d rather not show these banners, you can disable it with this setting.
Frontend authentication
-----------------------
### `PASSWORD_REQUIRED_TEMPLATE`
```
PASSWORD_REQUIRED_TEMPLATE = 'myapp/password_required.html'
```
This is the path to the Django template which will be used to display the “password required” form when a user accesses a private page. For more details, see the [Private pages](../advanced_topics/privacy#private-pages) documentation.
### `DOCUMENT_PASSWORD_REQUIRED_TEMPLATE`
```
DOCUMENT_PASSWORD_REQUIRED_TEMPLATE = 'myapp/document_password_required.html'
```
As above, but for password restrictions on documents. For more details, see the [Private pages](../advanced_topics/privacy#private-pages) documentation.
### `WAGTAIL_FRONTEND_LOGIN_TEMPLATE`
The basic login page can be customised with a custom template.
```
WAGTAIL_FRONTEND_LOGIN_TEMPLATE = 'myapp/login.html'
```
### `WAGTAIL_FRONTEND_LOGIN_URL`
Or the login page can be a redirect to an external or internal URL.
```
WAGTAIL_FRONTEND_LOGIN_URL = '/accounts/login/'
```
For more details, see the [Setting up a login page](../advanced_topics/privacy#login-page) documentation.
Tags
----
### `TAGGIT_CASE_INSENSITIVE`
```
TAGGIT_CASE_INSENSITIVE = True
```
Tags are case-sensitive by default (‘music’ and ‘Music’ are treated as distinct tags). In many cases the reverse behaviour is preferable.
### `TAG_SPACES_ALLOWED`
```
TAG_SPACES_ALLOWED = False
```
Tags can only consist of a single word, no spaces allowed. The default setting is `True` (spaces in tags are allowed).
### `TAG_LIMIT`
```
TAG_LIMIT = 5
```
Limit the number of tags that can be added to (django-taggit) Tag model. Default setting is `None`, meaning no limit on tags.
Static files
------------
### `WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS`
```
WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS = False
```
Static file URLs within the Wagtail admin are given a version-specific query string of the form `?v=1a2b3c4d`, to prevent outdated cached copies of JavaScript and CSS files from persisting after a Wagtail upgrade. To disable these, set `WAGTAILADMIN_STATIC_FILE_VERSION_STRINGS` to `False`.
API
---
For full documentation on API configuration, including these settings, see [Wagtail API v2 Configuration Guide](../advanced_topics/api/v2/configuration#api-v2-configuration) documentation.
### `WAGTAILAPI_BASE_URL`
```
WAGTAILAPI_BASE_URL = 'http://api.example.com/'
```
Required when using frontend cache invalidation, used to generate absolute URLs to document files and invalidating the cache.
### `WAGTAILAPI_LIMIT_MAX`
```
WAGTAILAPI_LIMIT_MAX = 500
```
Default is 20, used to change the maximum number of results a user can request at a time, set to `None` for no limit.
### `WAGTAILAPI_SEARCH_ENABLED`
```
WAGTAILAPI_SEARCH_ENABLED = False
```
Default is true, setting this to false will disable full text search on all endpoints.
### `WAGTAILAPI_USE_FRONTENDCACHE`
```
WAGTAILAPI_USE_FRONTENDCACHE = True
```
Requires `wagtailfrontendcache` app to be installed, indicates the API should use the frontend cache.
Frontend cache
--------------
For full documentation on frontend cache invalidation, including these settings, see [Frontend cache invalidator](contrib/frontendcache#frontend-cache-purging).
### `WAGTAILFRONTENDCACHE`
```
WAGTAILFRONTENDCACHE = {
'varnish': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.HTTPBackend',
'LOCATION': 'http://localhost:8000',
},
}
```
See documentation linked above for full options available.
Note
`WAGTAILFRONTENDCACHE_LOCATION` is no longer the preferred way to set the cache location, instead set the `LOCATION` within the `WAGTAILFRONTENDCACHE` item.
### `WAGTAILFRONTENDCACHE_LANGUAGES`
```
WAGTAILFRONTENDCACHE_LANGUAGES = [l[0] for l in settings.LANGUAGES]
```
Default is an empty list, must be a list of languages to also purge the urls for each language of a purging url. This setting needs `settings.USE_I18N` to be `True` to work.
Redirects
---------
### `WAGTAIL_REDIRECTS_FILE_STORAGE`
```
WAGTAIL_REDIRECTS_FILE_STORAGE = 'tmp_file'
```
By default the redirect importer keeps track of the uploaded file as a temp file, but on certain environments (load balanced/cloud environments), you cannot keep a shared file between environments. For those cases you can use the built-in cache to store the file instead.
```
WAGTAIL_REDIRECTS_FILE_STORAGE = 'cache'
```
Form builder
------------
### `WAGTAILFORMS_HELP_TEXT_ALLOW_HTML`
```
WAGTAILFORMS_HELP_TEXT_ALLOW_HTML = True
```
When true, HTML tags in form field help text will be rendered unescaped (default: False).
Warning
Enabling this option will allow editors to insert arbitrary HTML into the page, such as scripts that could allow the editor to acquire administrator privileges when another administrator views the page. Do not enable this setting unless your editors are fully trusted.
Workflow
--------
### `WAGTAIL_MODERATION_ENABLED`
```
WAGTAIL_MODERATION_ENABLED = True
```
Changes whether the Submit for Moderation button is displayed in the action menu.
### `WAGTAIL_WORKFLOW_ENABLED`
```
WAGTAIL_WORKFLOW_ENABLED = False
```
Specifies whether moderation workflows are enabled (default: True). When disabled, editors will no longer be given the option to submit pages to a workflow, and the settings areas for admins to configure workflows and tasks will be unavailable.
### `WAGTAIL_WORKFLOW_REQUIRE_REAPPROVAL_ON_EDIT`
```
WAGTAIL_WORKFLOW_REQUIRE_REAPPROVAL_ON_EDIT = True
```
Moderation workflows can be used in two modes. The first is to require that all tasks must approve a specific page revision for the workflow to complete. As a result, if edits are made to a page while it is in moderation, any approved tasks will need to be re-approved for the new revision before the workflow finishes. This is the default, `WAGTAIL_WORKFLOW_REQUIRE_REAPPROVAL_ON_EDIT = True` . The second mode does not require reapproval: if edits are made when tasks have already been approved, those tasks do not need to be reapproved. This is more suited to a hierarchical workflow system. To use workflows in this mode, set `WAGTAIL_WORKFLOW_REQUIRE_REAPPROVAL_ON_EDIT = False`.
### `WAGTAIL_FINISH_WORKFLOW_ACTION`
```
WAGTAIL_FINISH_WORKFLOW_ACTION = 'wagtail.workflows.publish_workflow_state'
```
This sets the function to be called when a workflow completes successfully - by default, `wagtail.workflows.publish_workflow_state`,which publishes the page. The function must accept a `WorkflowState` object as its only positional argument.
### `WAGTAIL_WORKFLOW_CANCEL_ON_PUBLISH`
```
WAGTAIL_WORKFLOW_CANCEL_ON_PUBLISH = True
```
This determines whether publishing a page with an ongoing workflow will cancel the workflow (if true) or leave the workflow unaffected (false). Disabling this could be useful if your site has long, multi-step workflows, and you want to be able to publish urgent page updates while the workflow continues to provide less urgent feedback.
| programming_docs |
wagtail Viewsets Viewsets
========
Viewsets are Wagtail’s mechanism for defining a group of related admin views with shared properties, as a single unit. See [Generic views](../extending/generic_views).
ViewSet
-------
ModelViewSet
------------
ChooserViewSet
--------------
SnippetViewSet
--------------
wagtail Sitemap generator Sitemap generator
=================
This document describes how to create XML sitemaps for your Wagtail website using the `wagtail.contrib.sitemaps` module.
Note
As of Wagtail 1.10 the Django contrib sitemap app is used to generate sitemaps. However since Wagtail requires the Site instance to be available during the sitemap generation you will have to use the views from the `wagtail.contrib.sitemaps.views` module instead of the views provided by Django (`django.contrib.sitemaps.views`).
The usage of these views is otherwise identical, which means that customisation and caching of the sitemaps are done using the default Django patterns. See the Django documentation for in-depth information.
Basic configuration
-------------------
You firstly need to add `"django.contrib.sitemaps"` to INSTALLED\_APPS in your Django settings file:
```
INSTALLED_APPS = [
...
"django.contrib.sitemaps",
]
```
Then, in `urls.py`, you need to add a link to the `wagtail.contrib.sitemaps.views.sitemap` view which generates the sitemap:
```
from wagtail.contrib.sitemaps.views import sitemap
urlpatterns = [
...
path('sitemap.xml', sitemap),
...
# Ensure that the 'sitemap' line appears above the default Wagtail page serving route
re_path(r'', include(wagtail_urls)),
]
```
You should now be able to browse to `/sitemap.xml` and see the sitemap working. By default, all published pages in your website will be added to the site map.
Setting the hostname
--------------------
By default, the sitemap uses the hostname defined in the Wagtail Admin’s `Sites` area. If your default site is called `localhost`, then URLs in the sitemap will look like:
```
<url>
<loc>http://localhost/about/</loc>
<lastmod>2015-09-26</lastmod>
</url>
```
For tools like Google Search Tools to properly index your site, you need to set a valid, crawlable hostname. If you change the site’s hostname from `localhost` to `mysite.com`, `sitemap.xml` will contain the correct URLs:
```
<url>
<loc>http://mysite.com/about/</loc>
<lastmod>2015-09-26</lastmod>
</url>
```
If you change the site’s port to `443`, the `https` scheme will be used. Find out more about [working with Sites](../pages/model_reference#site-model-ref).
Customising
-----------
### URLs
The `Page` class defines a `get_sitemap_urls` method which you can override to customise sitemaps per `Page` instance. This method must accept a request object and return a list of dictionaries, one dictionary per URL entry in the sitemap. You can exclude pages from the sitemap by returning an empty list.
Each dictionary can contain the following:
* **location** (required) - This is the full URL path to add into the sitemap.
* **lastmod** - A python date or datetime set to when the page was last modified.
* **changefreq**
* **priority**
You can add more but you will need to override the `sitemap.xml` template in order for them to be displayed in the sitemap.
Serving multiple sitemaps
-------------------------
If you want to support the sitemap indexes from Django then you will need to use the index view from `wagtail.contrib.sitemaps.views` instead of the index view from `django.contrib.sitemaps.views`. Please see the Django documentation for further details.
wagtail Typed table block Typed table block
=================
The `typed_table_block` module provides a StreamField block type for building tables consisting of mixed data types. Developers can specify a set of block types (such as `RichTextBlock` or `FloatBlock`) to be available as column types; page authors can then build up tables of any size by choosing column types from that list, in much the same way that they would insert blocks into a StreamField. Within each column, authors enter data using the standard editing control for that field (such as the Draftail editor for rich text cells).
Installation
------------
Add `"wagtail.contrib.typed_table_block"` to your `INSTALLED_APPS`:
```
INSTALLED_APPS = [
...
"wagtail.contrib.typed_table_block",
]
```
Usage
-----
`TypedTableBlock` can be imported from the module `wagtail.contrib.typed_table_block.blocks` and used within a StreamField definition. Just like `StructBlock` and `StreamBlock`, it accepts a list of `(name, block_type)` tuples to use as child blocks:
```
from wagtail.contrib.typed_table_block.blocks import TypedTableBlock
from wagtail import blocks
from wagtail.images.blocks import ImageChooserBlock
class DemoStreamBlock(blocks.StreamBlock):
title = blocks.CharBlock()
paragraph = blocks.RichTextBlock()
table = TypedTableBlock([
('text', blocks.CharBlock()),
('numeric', blocks.FloatBlock()),
('rich_text', blocks.RichTextBlock()),
('image', ImageChooserBlock())
])
```
To keep the UI as simple as possible for authors, it’s generally recommended to use Wagtail’s basic built-in block types as column types, as above. However, all custom block types and parameters are supported. For example, to define a ‘country’ column type consisting of a dropdown of country choices:
```
table = TypedTableBlock([
('text', blocks.CharBlock()),
('numeric', blocks.FloatBlock()),
('rich_text', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
('country', ChoiceBlock(choices=[
('be', 'Belgium'),
('fr', 'France'),
('de', 'Germany'),
('nl', 'Netherlands'),
('pl', 'Poland'),
('uk', 'United Kingdom'),
])),
])
```
On your page template, the `{% include_block %}` tag (called on either the individual block, or the StreamField value as a whole) will render any typed table blocks as an HTML `<table>` element.
```
{% load wagtailcore_tags %}
{% include_block page.body %}
```
Or:
```
{% load wagtailcore_tags %}
{% for block in page.body %}
{% if block.block_type == 'table' %}
{% include_block block %}
{% else %}
{# rendering for other block types #}
{% endif %}
{% endfor %}
```
wagtail Contrib modules Contrib modules
===============
Wagtail ships with a variety of extra optional modules.
* [Settings](settings)
+ [Installation](settings#installation)
+ [Defining settings](settings#defining-settings)
+ [Edit handlers](settings#edit-handlers)
+ [Appearance](settings#appearance)
+ [Using the settings](settings#using-the-settings)
+ [Utilising `select_related` to improve efficiency](settings#utilising-select-related-to-improve-efficiency)
+ [Utilising the `page_url` setting shortcut](settings#utilising-the-page-url-setting-shortcut)
* [Form builder](forms/index)
+ [Usage](forms/index#usage)
+ [Displaying form submission information](forms/index#displaying-form-submission-information)
+ [Index](forms/index#index)
* [Sitemap generator](sitemaps)
+ [Basic configuration](sitemaps#basic-configuration)
+ [Setting the hostname](sitemaps#setting-the-hostname)
+ [Customising](sitemaps#customising)
+ [Serving multiple sitemaps](sitemaps#serving-multiple-sitemaps)
* [Frontend cache invalidator](frontendcache)
+ [Setting it up](frontendcache#setting-it-up)
+ [Advanced usage](frontendcache#advanced-usage)
* [`RoutablePageMixin`](routablepage)
+ [Installation](routablepage#installation)
+ [The basics](routablepage#the-basics)
+ [The `RoutablePageMixin` class](routablepage#module-wagtail.contrib.routable_page.models)
+ [The `routablepageurl` template tag](routablepage#the-routablepageurl-template-tag)
* [`ModelAdmin`](modeladmin/index)
+ [Summary of features](modeladmin/index#summary-of-features)
+ [Want to know more about customising `ModelAdmin`?](modeladmin/index#want-to-know-more-about-customising-modeladmin)
* [Promoted search results](searchpromotions)
+ [Installation](searchpromotions#installation)
+ [Usage](searchpromotions#usage)
* [Simple translation](simple_translation)
+ [Basic configuration](simple_translation#basic-configuration)
+ [Page tree synchronisation](simple_translation#page-tree-synchronisation)
* [TableBlock](table_block)
+ [Installation](table_block#installation)
+ [Basic Usage](table_block#basic-usage)
+ [Advanced Usage](table_block#advanced-usage)
* [Typed table block](typed_table_block)
+ [Installation](typed_table_block#installation)
+ [Usage](typed_table_block#usage)
* [Redirects](redirects)
+ [Installation](redirects#installation)
+ [Usage](redirects#usage)
+ [Automatic redirect creation](redirects#automatic-redirect-creation)
+ [Management commands](redirects#management-commands)
+ [The `Redirect` class](redirects#module-wagtail.contrib.redirects.models)
* [Legacy richtext](legacy_richtext)
[Settings](settings)
--------------------
Settings that are editable by administrators within the Wagtail admin - either site-specific or generic across all sites.
[Form builder](forms/index)
---------------------------
Allows forms to be created by admins and provides an interface for browsing form submissions.
[Sitemap generator](sitemaps)
-----------------------------
Provides a view that generates a Google XML sitemap of your public Wagtail content.
[Frontend cache invalidator](frontendcache)
-------------------------------------------
A module for automatically purging pages from a cache (Varnish, Squid, Cloudflare or Cloudfront) when their content is changed.
[RoutablePageMixin](routablepage)
---------------------------------
Provides a way of embedding Django URLconfs into pages.
[ModelAdmin](modeladmin/index)
------------------------------
A module allowing for more customisable representation and management of custom models in Wagtail’s admin area.
[Promoted search results](searchpromotions)
-------------------------------------------
A module for managing “Promoted Search Results”
[Simple translation](simple_translation)
----------------------------------------
A module for copying translatables (pages and snippets) to another language.
[TableBlock](table_block)
-------------------------
Provides a TableBlock for adding HTML tables to pages.
[Typed table block](typed_table_block)
--------------------------------------
Provides a StreamField block for authoring tables, where cells can be any block type including rich text.
[Redirects](redirects)
----------------------
Provides a way to manage redirects.
[Legacy richtext](legacy_richtext)
----------------------------------
Provides the legacy richtext wrapper (`<div class="rich-text"></div>`).
wagtail TableBlock TableBlock
==========
The TableBlock module provides an HTML table block type for StreamField. This module uses [handsontable 6.2.2](https://handsontable.com/) to provide users with the ability to create and edit HTML tables in Wagtail. Table blocks provides a caption field for accessibility.
Installation
------------
Add `"wagtail.contrib.table_block"` to your INSTALLED\_APPS:
```
INSTALLED_APPS = [
...
"wagtail.contrib.table_block",
]
```
Basic Usage
-----------
After installation, the TableBlock module can be used in a similar fashion to other StreamField blocks in the Wagtail core.
Import the TableBlock `from wagtail.contrib.table_block.blocks import TableBlock` and add it to your StreamField declaration.
```
class DemoStreamBlock(StreamBlock):
...
table = TableBlock()
```
Then, on your page template, the `{% include_block %}` tag (called on either the individual block, or the StreamField value as a whole) will render any table blocks it encounters as an HTML `<table>` element:
```
{% load wagtailcore_tags %}
{% include_block page.body %}
```
Or:
```
{% load wagtailcore_tags %}
{% for block in page.body %}
{% if block.block_type == 'table' %}
{% include_block block %}
{% else %}
{# rendering for other block types #}
{% endif %}
{% endfor %}
```
Advanced Usage
--------------
### Default Configuration
When defining a TableBlock, Wagtail provides the ability to pass an optional `table_options` dictionary. The default TableBlock dictionary looks like this:
```
default_table_options = {
'minSpareRows': 0,
'startRows': 3,
'startCols': 3,
'colHeaders': False,
'rowHeaders': False,
'contextMenu': [
'row_above',
'row_below',
'---------',
'col_left',
'col_right',
'---------',
'remove_row',
'remove_col',
'---------',
'undo',
'redo'
],
'editor': 'text',
'stretchH': 'all',
'height': 108,
'language': language,
'renderer': 'text',
'autoColumnSize': False,
}
```
### Configuration Options
Every key in the `table_options` dictionary maps to a [handsontable](https://handsontable.com/) option. These settings can be changed to alter the behaviour of tables in Wagtail. The following options are available:
* [minSpareRows](https://handsontable.com/docs/6.2.2/Options.html#minSpareRows) - The number of rows to append to the end of an empty grid. The default setting is 0.
* [startRows](https://handsontable.com/docs/6.2.2/Options.html#startRows) - The default number of rows for a new table.
* [startCols](https://handsontable.com/docs/6.2.2/Options.html#startCols) - The default number of columns for new tables.
* [colHeaders](https://handsontable.com/docs/6.2.2/Options.html#colHeaders) - Can be set to `True` or `False`. This setting designates if new tables should be created with column headers. **Note:** this only sets the behaviour for newly created tables. Page editors can override this by checking the the “Column header” checkbox in the table editor in the Wagtail admin.
* [rowHeaders](https://handsontable.com/docs/6.2.2/Options.html#rowHeaders) - Operates the same as `colHeaders` to designate if new tables should be created with the first column as a row header. Just like `colHeaders` this option can be overridden by the page editor in the Wagtail admin.
* [contextMenu](https://handsontable.com/docs/6.2.2/Options.html#contextMenu) - Enables or disables the Handsontable right-click menu. By default this is set to `True`. Alternatively you can provide a list or a dictionary with [specific options](https://handsontable.com/docs/6.2.2/demo-context-menu.html#page-specific).
* [editor](https://handsontable.com/docs/6.2.2/Options.html#editor) - Defines the editor used for table cells. The default setting is text.
* [stretchH](https://handsontable.com/docs/6.2.2/Options.html#stretchH) - Sets the default horizontal resizing of tables. Options include, ‘none’, ‘last’, and ‘all’. By default TableBlock uses ‘all’ for the even resizing of columns.
* [height](https://handsontable.com/docs/6.2.2/Options.html#height) - The default height of the grid. By default TableBlock sets the height to `108` for the optimal appearance of new tables in the editor. This is optimized for tables with `startRows` set to `3`. If you change the number of `startRows` in the configuration, you might need to change the `height` setting to improve the default appearance in the editor.
* [language](https://handsontable.com/docs/6.2.2/Options.html#language) - The default language setting. By default TableBlock tries to get the language from `django.utils.translation.get_language`. If needed, this setting can be overridden here.
* [renderer](https://handsontable.com/docs/6.2.2/Options.html#renderer) - The default setting Handsontable uses to render the content of table cells.
* [autoColumnSize](https://handsontable.com/docs/6.2.2/Options.html#autoColumnSize) - Enables or disables the `autoColumnSize` plugin. The TableBlock default setting is `False`.
A [complete list of handsontable options](https://handsontable.com/docs/6.2.2/Options.html) can be found on the Handsontable website.
### Changing the default table\_options
To change the default table options just pass a new table\_options dictionary when a new TableBlock is declared.
```
new_table_options = {
'minSpareRows': 0,
'startRows': 6,
'startCols': 4,
'colHeaders': False,
'rowHeaders': False,
'contextMenu': True,
'editor': 'text',
'stretchH': 'all',
'height': 216,
'language': 'en',
'renderer': 'text',
'autoColumnSize': False,
}
class DemoStreamBlock(StreamBlock):
...
table = TableBlock(table_options=new_table_options)
```
### Supporting cell alignment
You can activate the `alignment` option by setting a custom `contextMenu` which allows you to set the alignment on a cell selection. HTML classes set by handsontable will be kept on the rendered block. You’ll then be able to apply your own custom CSS rules to preserve the style. Those class names are:
* Horizontal: `htLeft`, `htCenter`, `htRight`, `htJustify`
* Vertical: `htTop`, `htMiddle`, `htBottom`
```
new_table_options = {
'contextMenu': [
'row_above',
'row_below',
'---------',
'col_left',
'col_right',
'---------',
'remove_row',
'remove_col',
'---------',
'undo',
'redo',
'---------',
'copy',
'cut'
'---------',
'alignment',
],
}
class DemoStreamBlock(StreamBlock):
...
table = TableBlock(table_options=new_table_options)
```
wagtail Simple translation Simple translation
==================
The simple\_translation module provides a user interface that allows users to copy pages and translatable snippets into another language.
* Copies are created in the source language (not translated)
* Copies of pages are in draft status
Content editors need to translate the content and publish the pages.
Note
Simple Translation is optional. It can be switched out by third-party packages. Like the more advanced [`wagtail-localize`](https://github.com/wagtail/wagtail-localize).
Basic configuration
-------------------
Add `"wagtail.contrib.simple_translation"` to `INSTALLED_APPS` in your settings file:
```
INSTALLED_APPS = [
...
"wagtail.contrib.simple_translation",
]
```
Run `python manage.py migrate` to create the necessary permissions.
In the Wagtail admin, go to settings and give some users or groups the “Can submit translations” permission.
Page tree synchronisation
-------------------------
Depending on your use case, it may be useful to keep the page trees in sync between different locales.
You can enable this feature by setting `WAGTAILSIMPLETRANSLATION_SYNC_PAGE_TREE` to `True`.
```
WAGTAILSIMPLETRANSLATION_SYNC_PAGE_TREE = True
```
When this feature is turned on, every time an editor creates a page, Wagtail creates an alias for that page under the page trees of all the other locales.
For example, when an editor creates the page `"/en/blog/my-blog-post/"`, Wagtail creates an alias of that page at `"/fr/blog/my-blog-post/"` and `"/de/blog/my-blog-post/"`.
wagtail RoutablePageMixin RoutablePageMixin
=================
The `RoutablePageMixin` mixin provides a convenient way for a page to respond on multiple sub-URLs with different views. For example, a blog section on a site might provide several different types of index page at URLs like `/blog/2013/06/`, `/blog/authors/bob/`, `/blog/tagged/python/`, all served by the same page instance.
A `Page` using `RoutablePageMixin` exists within the page tree like any other page, but URL paths underneath it are checked against a list of patterns. If none of the patterns match, control is passed to subpages as usual (or failing that, a 404 error is thrown).
By default a route for `r'^$'` exists, which serves the content exactly like a normal `Page` would. It can be overridden by using `@re_path(r'^$')` or `@path('')` on any other method of the inheriting class.
Installation
------------
Add `"wagtail.contrib.routable_page"` to your `INSTALLED_APPS`:
```
INSTALLED_APPS = [
...
"wagtail.contrib.routable_page",
]
```
The basics
----------
To use `RoutablePageMixin`, you need to make your class inherit from both :class:`wagtail.contrib.routable_page.models.RoutablePageMixin` and [`wagtail.models.Page`](../pages/model_reference#wagtail.models.Page "wagtail.models.Page"), then define some view methods and decorate them with `path` or `re_path`.
These view methods behave like ordinary Django view functions, and must return an `HttpResponse` object; typically this is done through a call to `django.shortcuts.render`.
The `path` and `re_path` decorators from `wagtail.contrib.routable_page.models.path` are similar to [the Django `django.urls` `path` and `re_path` functions](https://docs.djangoproject.com/en/stable/topics/http/urls/ "(in Django v4.1)"). The former allows the use of plain paths and converters while the latter lets you specify your URL patterns as regular expressions.
Here’s an example of an `EventIndexPage` with three views, assuming that an `EventPage` model with an `event_date` field has been defined elsewhere:
```
import datetime
from django.http import JsonResponse
from wagtail.fields import RichTextField
from wagtail.models import Page
from wagtail.contrib.routable_page.models import RoutablePageMixin, path
class EventIndexPage(RoutablePageMixin, Page):
# Routable pages can have fields like any other - here we would
# render the intro text on a template with {{ page.intro|richtext }}
intro = RichTextField()
@path('') # will override the default Page serving mechanism
def current_events(self, request):
"""
View function for the current events page
"""
events = EventPage.objects.live().filter(event_date__gte=datetime.date.today())
# NOTE: We can use the RoutablePageMixin.render() method to render
# the page as normal, but with some of the context values overridden
return self.render(request, context_overrides={
'title': "Current events",
'events': events,
})
@path('past/')
def past_events(self, request):
"""
View function for the past events page
"""
events = EventPage.objects.live().filter(event_date__lt=datetime.date.today())
# NOTE: We are overriding the template here, as well as few context values
return self.render(
request,
context_overrides={
'title': "Past events",
'events': events,
},
template="events/event_index_historical.html",
)
# Multiple routes!
@path('year/<int:year>/')
@path('year/current/')
def events_for_year(self, request, year=None):
"""
View function for the events for year page
"""
if year is None:
year = datetime.date.today().year
events = EventPage.objects.live().filter(event_date__year=year)
return self.render(request, context_overrides={
'title': "Events for %d" % year,
'events': events,
})
@re_path(r'^year/(\d+)/count/$')
def count_for_year(self, request, year=None):
"""
View function that returns a simple JSON response that
includes the number of events scheduled for a specific year
"""
events = EventPage.objects.live().filter(event_date__year=year)
# NOTE: The usual template/context rendering process is irrelevant
# here, so we'll just return a HttpResponse directly
return JsonResponse({'count': events.count()})
```
### Rendering other pages
Another way of returning an `HttpResponse` is to call the `serve` method of another page. (Calling a page’s own `serve` method within a view method is not valid, as the view method is already being called within `serve`, and this would create a circular definition).
For example, `EventIndexPage` could be extended with a `next/` route that displays the page for the next event:
```
@path('next/')
def next_event(self, request):
"""
Display the page for the next event
"""
future_events = EventPage.objects.live().filter(event_date__gt=datetime.date.today())
next_event = future_events.order_by('event_date').first()
return next_event.serve(request)
```
### Reversing URLs
[`RoutablePageMixin`](#wagtail.contrib.routable_page.models.RoutablePageMixin "wagtail.contrib.routable_page.models.RoutablePageMixin") adds a [`reverse_subpage()`](#wagtail.contrib.routable_page.models.RoutablePageMixin.reverse_subpage "wagtail.contrib.routable_page.models.RoutablePageMixin.reverse_subpage") method to your page model which you can use for reversing URLs. For example:
```
# The URL name defaults to the view method name.
>>> event_page.reverse_subpage('events_for_year', args=(2015, ))
'year/2015/'
```
This method only returns the part of the URL within the page. To get the full URL, you must append it to the values of either the `url` or the [`full_url`](../pages/model_reference#wagtail.models.Page.full_url "wagtail.models.Page.full_url") attribute on your page:
```
>>> event_page.url + event_page.reverse_subpage('events_for_year', args=(2015, ))
'/events/year/2015/'
>>> event_page.full_url + event_page.reverse_subpage('events_for_year', args=(2015, ))
'http://example.com/events/year/2015/'
```
### Changing route names
The route name defaults to the name of the view. You can override this name with the `name` keyword argument on `@path` or `re_path`:
```
from wagtail.models import Page
from wagtail.contrib.routable_page.models import RoutablePageMixin, route
class EventPage(RoutablePageMixin, Page):
...
@re_path(r'^year/(\d+)/$', name='year')
def events_for_year(self, request, year):
"""
View function for the events for year page
"""
...
```
```
>>> event_page.url + event_page.reverse_subpage('year', args=(2015, ))
'/events/year/2015/'
```
The `RoutablePageMixin` class
-----------------------------
Example:
```
url = page.url + page.reverse_subpage('events_for_year', kwargs={'year': '2014'})
```
The `routablepageurl` template tag
----------------------------------
Example:
```
{% load wagtailroutablepage_tags %}
{% routablepageurl page "feed" %}
{% routablepageurl page "archive" 2014 08 14 %}
{% routablepageurl page "food" foo="bar" baz="quux" %}
```
| programming_docs |
wagtail Promoted search results Promoted search results
=======================
The `searchpromotions` module provides the models and user interface for managing “Promoted search results” and displaying them in a search results page.
“Promoted search results” allow editors to explicitly link relevant content to search terms, so results pages can contain curated content in addition to results from the search engine.
Installation
------------
The `searchpromotions` module is not enabled by default. To install it, add `wagtail.contrib.search_promotions` to `INSTALLED_APPS` in your project’s Django settings file.
```
INSTALLED_APPS = [
...
'wagtail.contrib.search_promotions',
]
```
This app contains migrations so make sure you run the `migrate` django-admin command after installing.
Usage
-----
Once installed, a new menu item called “Promoted search results” should appear in the “Settings” menu. This is where you can assign pages to popular search terms.
### Displaying on a search results page
To retrieve a list of promoted search results for a particular search query, you can use the `{% get_search_promotions %}` template tag from the `wagtailsearchpromotions_tags` templatetag library:
```
{% load wagtailcore_tags wagtailsearchpromotions_tags %}
...
{% get_search_promotions search_query as search_promotions %}
<ul>
{% for search_promotion in search_promotions %}
<li>
<a href="{% pageurl search_promotion.page %}">
<h2>{{ search_promotion.page.title }}</h2>
<p>{{ search_promotion.description }}</p>
</a>
</li>
{% endfor %}
</ul>
```
wagtail Legacy richtext Legacy richtext
===============
Provides the legacy richtext wrapper.
Place `wagtail.contrib.legacy.richtext` before `wagtail` in `INSTALLED_APPS`.
```
INSTALLED_APPS = [
...
"wagtail.contrib.legacy.richtext",
"wagtail",
...
]
```
The `{{ page.body|richtext }}` template filter will now render:
```
<div class="rich-text">...</div>
```
wagtail Frontend cache invalidator Frontend cache invalidator
==========================
Many websites use a frontend cache such as Varnish, Squid, Cloudflare or CloudFront to gain extra performance. The downside of using a frontend cache though is that they don’t respond well to updating content and will often keep an old version of a page cached after it has been updated.
This document describes how to configure Wagtail to purge old versions of pages from a frontend cache whenever a page gets updated.
Setting it up
-------------
Firstly, add `"wagtail.contrib.frontend_cache"` to your `INSTALLED_APPS`:
```
INSTALLED_APPS = [
...
"wagtail.contrib.frontend_cache"
]
```
The `wagtailfrontendcache` module provides a set of signal handlers which will automatically purge the cache whenever a page is published or deleted. These signal handlers are automatically registered when the `wagtail.contrib.frontend_cache` app is loaded.
### Varnish/Squid
Add a new item into the `WAGTAILFRONTENDCACHE` setting and set the `BACKEND` parameter to `wagtail.contrib.frontend_cache.backends.HTTPBackend`. This backend requires an extra parameter `LOCATION` which points to where the cache is running (this must be a direct connection to the server and cannot go through another proxy).
```
# settings.py
WAGTAILFRONTENDCACHE = {
'varnish': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.HTTPBackend',
'LOCATION': 'http://localhost:8000',
},
}
WAGTAILFRONTENDCACHE_LANGUAGES = []
```
Set `WAGTAILFRONTENDCACHE_LANGUAGES` to a list of languages (typically equal to `[l[0] for l in settings.LANGUAGES]`) to also purge the urls for each language of a purging url. This setting needs `settings.USE_I18N` to be `True` to work. Its default is an empty list.
Finally, make sure you have configured your frontend cache to accept PURGE requests:
* [Varnish](https://varnish-cache.org/docs/3.0/tutorial/purging.html)
* [Squid](https://wiki.squid-cache.org/SquidFaq/OperatingSquid#How_can_I_purge_an_object_from_my_cache.3F)
### Cloudflare
Firstly, you need to register an account with Cloudflare if you haven’t already got one. You can do this here: [Cloudflare Sign up](https://dash.cloudflare.com/sign-up).
Add an item into the `WAGTAILFRONTENDCACHE` and set the `BACKEND` parameter to `wagtail.contrib.frontend_cache.backends.CloudflareBackend`.
This backend can be configured to use an account-wide API key, or an API token with restricted access.
To use an account-wide API key, find the key [as described in the Cloudflare documentation](https://developers.cloudflare.com/api/get-started/keys/#view-your-api-key) and specify `EMAIL` and `API_KEY` parameters.
To use a limited API token, [create a token](https://developers.cloudflare.com/api/get-started/create-token/) configured with the ‘Zone, Cache Purge’ permission and specify the `BEARER_TOKEN` parameter.
A `ZONEID` parameter will need to be set for either option. To find the `ZONEID` for your domain, read the [Cloudflare API Documentation](https://developers.cloudflare.com/fundamentals/get-started/basic-tasks/find-account-and-zone-ids/).
With an API key:
```
# settings.py
WAGTAILFRONTENDCACHE = {
'cloudflare': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudflareBackend',
'EMAIL': '[email protected]',
'API_KEY': 'your cloudflare api key',
'ZONEID': 'your cloudflare domain zone id',
},
}
```
With an API token:
```
# settings.py
WAGTAILFRONTENDCACHE = {
'cloudflare': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudflareBackend',
'BEARER_TOKEN': 'your cloudflare bearer token',
'ZONEID': 'your cloudflare domain zone id',
},
}
```
### Amazon CloudFront
Within Amazon Web Services you will need at least one CloudFront web distribution. If you don’t have one, you can get one here: [CloudFront getting started](https://aws.amazon.com/cloudfront/)
Add an item into the `WAGTAILFRONTENDCACHE` and set the `BACKEND` parameter to `wagtail.contrib.frontend_cache.backends.CloudfrontBackend`. This backend requires one extra parameter, `DISTRIBUTION_ID` (your CloudFront generated distribution id).
```
WAGTAILFRONTENDCACHE = {
'cloudfront': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudfrontBackend',
'DISTRIBUTION_ID': 'your-distribution-id',
},
}
```
Configuration of credentials can done in multiple ways. You won’t need to store them in your Django settings file. You can read more about this here: [Boto 3 Docs](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html).
In case you run multiple sites with Wagtail and each site has its CloudFront distribution, provide a mapping instead of a single distribution. Make sure the mapping matches with the hostnames provided in your site settings.
```
WAGTAILFRONTENDCACHE = {
'cloudfront': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.CloudfrontBackend',
'DISTRIBUTION_ID': {
'www.wagtail.org': 'your-distribution-id',
'www.madewithwagtail.org': 'your-distribution-id',
},
},
}
```
Note
In most cases, absolute URLs with `www` prefixed domain names should be used in your mapping. Only drop the `www` prefix if you’re absolutely sure you’re not using it (for example a subdomain).
### Azure CDN
With [Azure CDN](https://azure.microsoft.com/en-gb/products/cdn/) you will need a CDN profile with an endpoint configured.
The third-party dependencies of this backend are:
| PyPI Package | Essential | Reason |
| --- | --- | --- |
| [`azure-mgmt-cdn`](https://pypi.org/project/azure-mgmt-cdn/) | Yes | Interacting with the CDN service. |
| [`azure-identity`](https://pypi.org/project/azure-identity/) | No | Obtaining credentials. It’s optional if you want to specify your own credential using a `CREDENTIALS` setting (more details below). |
| [`azure-mgmt-resource`](https://pypi.org/project/azure-mgmt-resource/) | No | For obtaining the subscription ID. Redundant if you want to explicitly specify a `SUBSCRIPTION_ID` setting (more details below). |
Add an item into the `WAGTAILFRONTENDCACHE` and set the `BACKEND` parameter to `wagtail.contrib.frontend_cache.backends.AzureCdnBackend`. This backend requires the following settings to be set:
* `RESOURCE_GROUP_NAME` - the resource group that your CDN profile is in.
* `CDN_PROFILE_NAME` - the profile name of the CDN service that you want to use.
* `CDN_ENDPOINT_NAME` - the name of the endpoint you want to be purged.
```
WAGTAILFRONTENDCACHE = {
'azure_cdn': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.AzureCdnBackend',
'RESOURCE_GROUP_NAME': 'MY-WAGTAIL-RESOURCE-GROUP',
'CDN_PROFILE_NAME': 'wagtailio',
'CDN_ENDPOINT_NAME': 'wagtailio-cdn-endpoint-123',
},
}
```
By default the credentials will use `azure.identity.DefaultAzureCredential`. To modify the credential object used, please use `CREDENTIALS` setting. Read about your options on the [Azure documentation](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-overview).
```
from azure.common.credentials import ServicePrincipalCredentials
WAGTAILFRONTENDCACHE = {
'azure_cdn': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.AzureCdnBackend',
'RESOURCE_GROUP_NAME': 'MY-WAGTAIL-RESOURCE-GROUP',
'CDN_PROFILE_NAME': 'wagtailio',
'CDN_ENDPOINT_NAME': 'wagtailio-cdn-endpoint-123',
'CREDENTIALS': ServicePrincipalCredentials(
client_id='your client id',
secret='your client secret',
)
},
}
```
Another option that can be set is `SUBSCRIPTION_ID`. By default the first encountered subscription will be used, but if your credential has access to more subscriptions, you should set this to an explicit value.
### Azure Front Door
With [Azure Front Door](https://azure.microsoft.com/en-gb/products/frontdoor/) you will need a Front Door instance with caching enabled.
The third-party dependencies of this backend are:
| PyPI Package | Essential | Reason |
| --- | --- | --- |
| [`azure-mgmt-frontdoor`](https://pypi.org/project/azure-mgmt-frontdoor/) | Yes | Interacting with the Front Door service. |
| [`azure-identity`](https://pypi.org/project/azure-identity/) | No | Obtaining credentials. It’s optional if you want to specify your own credential using a `CREDENTIALS` setting (more details below). |
| [`azure-mgmt-resource`](https://pypi.org/project/azure-mgmt-resource/) | No | For obtaining the subscription ID. Redundant if you want to explicitly specify a `SUBSCRIPTION_ID` setting (more details below). |
Add an item into the `WAGTAILFRONTENDCACHE` and set the `BACKEND` parameter to `wagtail.contrib.frontend_cache.backends.AzureFrontDoorBackend`. This backend requires the following settings to be set:
* `RESOURCE_GROUP_NAME` - the resource group that your Front Door instance is part of.
* `FRONT_DOOR_NAME` - your configured Front Door instance name.
```
WAGTAILFRONTENDCACHE = {
'azure_front_door': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.AzureFrontDoorBackend',
'RESOURCE_GROUP_NAME': 'MY-WAGTAIL-RESOURCE-GROUP',
'FRONT_DOOR_NAME': 'wagtail-io-front-door',
},
}
```
By default the credentials will use `azure.identity.DefaultAzureCredential`. To modify the credential object used, please use `CREDENTIALS` setting. Read about your options on the [Azure documentation](https://learn.microsoft.com/en-us/azure/developer/python/sdk/authentication-overview).
```
from azure.common.credentials import ServicePrincipalCredentials
WAGTAILFRONTENDCACHE = {
'azure_front_door': {
'BACKEND': 'wagtail.contrib.frontend_cache.backends.AzureFrontDoorBackend',
'RESOURCE_GROUP_NAME': 'MY-WAGTAIL-RESOURCE-GROUP',
'FRONT_DOOR_NAME': 'wagtail-io-front-door',
'CREDENTIALS': ServicePrincipalCredentials(
client_id='your client id',
secret='your client secret',
)
},
}
```
Another option that can be set is `SUBSCRIPTION_ID`. By default the first encountered subscription will be used, but if your credential has access to more subscriptions, you should set this to an explicit value.
Advanced usage
--------------
### Invalidating more than one URL per page
By default, Wagtail will only purge one URL per page. If your page has more than one URL to be purged, you will need to override the `get_cached_paths` method on your page type.
```
class BlogIndexPage(Page):
def get_blog_items(self):
# This returns a Django paginator of blog items in this section
return Paginator(self.get_children().live().type(BlogPage), 10)
def get_cached_paths(self):
# Yield the main URL
yield '/'
# Yield one URL per page in the paginator to make sure all pages are purged
for page_number in range(1, self.get_blog_items().num_pages + 1):
yield '/?page=' + str(page_number)
```
### Invalidating index pages
Pages that list other pages (such as a blog index) may need to be purged as well so any changes to a blog page are also reflected on the index (for example, a blog post was added, deleted or its title/thumbnail was changed).
To purge these pages, we need to write a signal handler that listens for Wagtail’s `page_published` and `page_unpublished` signals for blog pages (note, `page_published` is called both when a page is created and updated). This signal handler would trigger the invalidation of the index page using the `PurgeBatch` class which is used to construct and dispatch invalidation requests.
```
# models.py
from django.dispatch import receiver
from django.db.models.signals import pre_delete
from wagtail.signals import page_published
from wagtail.contrib.frontend_cache.utils import PurgeBatch
...
def blog_page_changed(blog_page):
# Find all the live BlogIndexPages that contain this blog_page
batch = PurgeBatch()
for blog_index in BlogIndexPage.objects.live():
if blog_page in blog_index.get_blog_items().object_list:
batch.add_page(blog_index)
# Purge all the blog indexes we found in a single request
batch.purge()
@receiver(page_published, sender=BlogPage)
def blog_published_handler(instance, **kwargs):
blog_page_changed(instance)
@receiver(pre_delete, sender=BlogPage)
def blog_deleted_handler(instance, **kwargs):
blog_page_changed(instance)
```
### Invalidating URLs
The `PurgeBatch` class provides a `.add_url(url)` and a `.add_urls(urls)` for adding individual URLs to the purge batch.
For example, this could be useful for purging a single page on a blog index:
```
from wagtail.contrib.frontend_cache.utils import PurgeBatch
# Purge the first page of the blog index
batch = PurgeBatch()
batch.add_url(blog_index.url + '?page=1')
batch.purge()
```
### The `PurgeBatch` class
All of the methods available on `PurgeBatch` are listed below:
wagtail Settings Settings
========
The `wagtail.contrib.settings` module allows you to define models that hold settings which are either common across all site records, or specific to each site.
Settings are editable by administrators within the Wagtail admin, and can be accessed in code as well as in templates.
Installation
------------
Add `wagtail.contrib.settings` to your `INSTALLED_APPS`:
```
INSTALLED_APPS += [
'wagtail.contrib.settings',
]
```
**Note:** If you are using `settings` within templates, you will also need to update your `TEMPLATES` settings (discussed later in this page).
Defining settings
-----------------
Create a model that inherits from either:
* `BaseGenericSetting` for generic settings across all sites
* `BaseSiteSetting` for site-specific settings
and register it using the `register_setting` decorator:
```
from django.db import models
from wagtail.contrib.settings.models import (
BaseGenericSetting,
BaseSiteSetting,
register_setting,
)
@register_setting
class GenericSocialMediaSettings(BaseGenericSetting):
facebook = models.URLField()
@register_setting
class SiteSpecificSocialMediaSettings(BaseSiteSetting):
facebook = models.URLField()
```
Links to your settings will appear in the Wagtail admin ‘Settings’ menu.
Edit handlers
-------------
Settings use edit handlers much like the rest of Wagtail. Add a `panels` setting to your model defining all the edit handlers required:
```
@register_setting
class GenericImportantPages(BaseGenericSetting):
donate_page = models.ForeignKey(
'wagtailcore.Page', null=True, on_delete=models.SET_NULL, related_name='+'
)
sign_up_page = models.ForeignKey(
'wagtailcore.Page', null=True, on_delete=models.SET_NULL, related_name='+'
)
panels = [
FieldPanel('donate_page'),
FieldPanel('sign_up_page'),
]
@register_setting
class SiteSpecificImportantPages(BaseSiteSetting):
donate_page = models.ForeignKey(
'wagtailcore.Page', null=True, on_delete=models.SET_NULL, related_name='+'
)
sign_up_page = models.ForeignKey(
'wagtailcore.Page', null=True, on_delete=models.SET_NULL, related_name='+'
)
panels = [
FieldPanel('donate_page'),
FieldPanel('sign_up_page'),
]
```
You can also customise the edit handlers [like you would do for `Page` model](../../advanced_topics/customisation/page_editing_interface#customising-the-tabbed-interface) with a custom `edit_handler` attribute:
```
from wagtail.admin.panels import TabbedInterface, ObjectList
@register_setting
class MySettings(BaseGenericSetting):
# ...
first_tab_panels = [
FieldPanel('field_1'),
]
second_tab_panels = [
FieldPanel('field_2'),
]
edit_handler = TabbedInterface([
ObjectList(first_tab_panels, heading='First tab'),
ObjectList(second_tab_panels, heading='Second tab'),
])
```
Appearance
----------
You can change the label used in the menu by changing the `verbose_name` of your model.
You can add an icon to the menu by passing an `icon` argument to the `register_setting` decorator:
```
@register_setting(icon='placeholder')
class GenericSocialMediaSettings(BaseGenericSetting):
...
class Meta:
verbose_name = "Social media settings for all sites"
@register_setting(icon='placeholder')
class SiteSpecificSocialMediaSettings(BaseSiteSetting):
...
class Meta:
verbose_name = "Site-specific social media settings"
```
For a list of all available icons, please see the [styleguide](../../contributing/styleguide#styleguide).
Using the settings
------------------
Settings can be used in both Python code and in templates.
### Using in Python
#### Generic settings
If you require access to a generic setting in a view, the `BaseGenericSetting.load()` method allows you to retrieve the generic settings:
```
def view(request):
social_media_settings = GenericSocialMediaSettings.load(request_or_site=request)
...
```
#### Site-specific settings
If you require access to a site-specific setting in a view, the `BaseSiteSetting.for_request()` method allows you to retrieve the site-specific settings for the current request:
```
def view(request):
social_media_settings = SiteSpecificSocialMediaSettings.for_request(request=request)
...
```
In places where the request is unavailable, but you know the `Site` you wish to retrieve settings for, you can use `BaseSiteSetting.for_site` instead:
```
def view(request):
social_media_settings = SiteSpecificSocialMediaSettings.for_site(site=user.origin_site)
...
```
### Using in Django templates
Add the `wagtail.contrib.settings.context_processors.settings` context processor to your settings:
```
TEMPLATES = [
{
...
'OPTIONS': {
'context_processors': [
...
'wagtail.contrib.settings.context_processors.settings',
]
}
}
]
```
Then access the generic settings through `{{ settings }}`:
```
{{ settings.app_label.GenericSocialMediaSettings.facebook }}
{{ settings.app_label.SiteSpecificSocialMediaSettings.facebook }}
```
**Note:** Replace `app_label` with the label of the app containing your settings model.
If you are not in a `RequestContext`, then context processors will not have run, and the `settings` variable will not be available. To get the `settings`, use the provided `{% get_settings %}` template tag.
```
{% load wagtailsettings_tags %}
{% get_settings %}
{{ settings.app_label.GenericSocialMediaSettings.facebook }}
{{ settings.app_label.SiteSpecificSocialMediaSettings.facebook }}
```
By default, the tag will create or update a `settings` variable in the context. If you want to assign to a different context variable instead, use `{% get_settings as other_variable_name %}`:
```
{% load wagtailsettings_tags %}
{% get_settings as wagtail_settings %}
{{ wagtail_settings.app_label.GenericSocialMediaSettings.facebook }}
{{ wagtail_settings.app_label.SiteSpecificSocialMediaSettings.facebook }}
```
### Using in Jinja2 templates
Add `wagtail.contrib.settings.jinja2tags.settings` extension to your Jinja2 settings:
```
TEMPLATES = [
...
{
'BACKEND': 'django.template.backends.jinja2.Jinja2',
'APP_DIRS': True,
'OPTIONS': {
'extensions': [
...
'wagtail.contrib.settings.jinja2tags.settings',
],
},
}
]
```
Then access the settings through the `settings()` template function:
```
{{ settings("app_label.GenericSocialMediaSettings").facebook }}
{{ settings("app_label.SiteSpecificSocialMediaSettings").facebook }}
```
**Note:** Replace `app_label` with the label of the app containing your settings model.
If there is no `request` available in the template at all, you can use the settings for the default site instead:
```
{{ settings("app_label.GenericSocialMediaSettings", use_default_site=True).facebook }}
{{ settings("app_label.SiteSpecificSocialMediaSettings", use_default_site=True).facebook }}
```
**Note:** You can not reliably get the correct settings instance for the current site from this template tag if the request object is not available. This is only relevant for multi-site instances of Wagtail.
You can store the settings instance in a variable to save some typing, if you have to use multiple values from one model:
```
{% with generic_social_settings=settings("app_label.GenericSocialMediaSettings") %}
Follow us on Twitter at @{{ generic_social_settings.facebook }},
or Instagram at @{{ generic_social_settings.instagram }}.
{% endwith %}
{% with site_social_settings=settings("app_label.SiteSpecificSocialMediaSettings") %}
Follow us on Twitter at @{{ site_social_settings.facebook }},
or Instagram at @{{ site_social_settings.instagram }}.
{% endwith %}
```
Or, alternately, using the `set` tag:
```
{% set generic_social_settings=settings("app_label.GenericSocialMediaSettings") %}
{% set site_social_settings=settings("app_label.SiteSpecificSocialMediaSettings") %}
```
Utilising `select_related` to improve efficiency
------------------------------------------------
For models with foreign key relationships to other objects (for example pages), which are very often needed to output values in templates, you can set the `select_related` attribute on your model to have Wagtail utilise Django’s [QuerySet.select\_related()](https://docs.djangoproject.com/en/stable/ref/models/querysets/#select-related) method to fetch the settings object and related objects in a single query. With this, the initial query is more complex, but you will be able to freely access the foreign key values without any additional queries, making things more efficient overall.
Building on the `GenericImportantPages` example from the previous section, the following shows how `select_related` can be set to improve efficiency:
```
@register_setting
class GenericImportantPages(BaseGenericSetting):
# Fetch these pages when looking up GenericImportantPages for or a site
select_related = ["donate_page", "sign_up_page"]
donate_page = models.ForeignKey(
'wagtailcore.Page', null=True, on_delete=models.SET_NULL, related_name='+'
)
sign_up_page = models.ForeignKey(
'wagtailcore.Page', null=True, on_delete=models.SET_NULL, related_name='+'
)
panels = [
FieldPanel('donate_page'),
FieldPanel('sign_up_page'),
]
```
With these additions, the following template code will now trigger a single database query instead of three (one to fetch the settings, and two more to fetch each page):
```
{% load wagtailcore_tags %}
{% pageurl settings.app_label.GenericImportantPages.donate_page %}
{% pageurl settings.app_label.GenericImportantPages.sign_up_page %}
```
Utilising the `page_url` setting shortcut
-----------------------------------------
If, like in the previous section, your settings model references pages, and you often need to output the URLs of those pages in your project, you can likely use the setting model’s `page_url` shortcut to do that more cleanly. For example, instead of doing the following:
```
{% load wagtailcore_tags %}
{% pageurl settings.app_label.GenericImportantPages.donate_page %}
{% pageurl settings.app_label.GenericImportantPages.sign_up_page %}
```
You could write:
```
{{ settings.app_label.GenericImportantPages.page_url.donate_page }}
{{ settings.app_label.GenericImportantPages.page_url.sign_up_page }}
```
Using the `page_url` shortcut has a few of advantages over using the tag:
1. The ‘specific’ page is automatically fetched to generate the URL, so you don’t have to worry about doing this (or forgetting to do this) yourself.
2. The results are cached, so if you need to access the same page URL in more than one place (for example in a form and in footer navigation), using the `page_url` shortcut will be more efficient.
3. It’s more concise, and the syntax is the same whether using it in templates or views (or other Python code), allowing you to write more consistent code.
When using the `page_url` shortcut, there are a couple of points worth noting:
1. The same limitations that apply to the `{% pageurl %}` tag apply to the shortcut: If the settings are accessed from a template context where the current request is not available, all URLs returned will include the site’s scheme/domain, and URL generation will not be quite as efficient.
2. If using the shortcut in views or other Python code, the method will raise an `AttributeError` if the attribute you request from `page_url` is not an attribute on the settings object.
3. If the settings object DOES have the attribute, but the attribute returns a value of `None` (or something that is not a `Page`), the shortcut will return an empty string.
| programming_docs |
wagtail Redirects Redirects
=========
The `redirects` module provides the models and user interface for managing arbitrary redirection between urls and `Pages` or other urls.
Installation
------------
The `redirects` module is not enabled by default. To install it, add `wagtail.contrib.redirects` to `INSTALLED_APPS` and `wagtail.contrib.redirects.middleware.RedirectMiddleware` to `MIDDLEWARE` in your project’s Django settings file.
```
INSTALLED_APPS = [
# ...
'wagtail.contrib.redirects',
]
MIDDLEWARE = [
# ...
# all other django middlware first
'wagtail.contrib.redirects.middleware.RedirectMiddleware',
]
```
This app contains migrations so make sure you run the `migrate` django-admin command after installing.
Usage
-----
Once installed, a new menu item called “Redirects” should appear in the “Settings” menu. This is where you can add arbitrary redirects to your site.
For an editor’s guide to the interface, see .
Automatic redirect creation
---------------------------
New in version 2.16.
Wagtail automatically creates permanent redirects for pages (and their descendants) when they are moved or their slug is changed. This helps to preserve SEO rankings of pages over time, and helps site visitors get to the right place when using bookmarks or using outdated links.
### Creating redirects for alternative page routes
If your project uses `RoutablePageMixin` to create pages with alternative routes, you might want to consider overriding the `get_route_paths()` method for those page types. Adding popular route paths to this list will result in the creation of additional redirects; helping visitors to alternative routes to get to the right place also.
For more information, please see :meth:`~wagtail.models.Page.get_route_paths`.
### Disabling automatic redirect creation
New in version 4.0: When generating redirects, custom field values are now fetched as part of the initial database query, so using custom field values in overridden url methods will no longer trigger additional per-object queries.
Wagtail’s default implementation works best for small-to-medium sized projects (5000 pages or fewer) that mostly use Wagtail’s built-in methods for URL generation.
Overrides to the following `Page` methods are respected when generating redirects, but use of specific page fields in those overrides will trigger additional database queries.
* [`get_url_parts()`](../pages/model_reference#wagtail.models.Page.get_url_parts "wagtail.models.Page.get_url_parts")
* [`get_route_paths()`](../pages/model_reference#wagtail.models.Page.get_route_paths "wagtail.models.Page.get_route_paths")
If you find the feature is not a good fit for your project, you can disable it by adding the following to your project settings:
```
WAGTAILREDIRECTS_AUTO_CREATE = False
```
Management commands
-------------------
### `import_redirects`
```
./manage.py import_redirects
```
This command imports and creates redirects from a file supplied by the user.
Options:
| Option | Description |
| --- | --- |
| **src** | This is the path to the file you wish to import redirects from. |
| **site** | This is the **site** for the site you wish to save redirects to. |
| **permanent** | If the redirects imported should be **permanent** (True) or not (False). It’s True by default. |
| **from** | The column index you want to use as redirect from value. |
| **to** | The column index you want to use as redirect to value. |
| **dry\_run** | Lets you run a import without doing any changes. |
| **ask** | Lets you inspect and approve each redirect before it is created. |
The `Redirect` class
--------------------
wagtail Form builder Form builder
============
The `wagtailforms` module allows you to set up single-page forms, such as a ‘Contact us’ form, as pages of a Wagtail site. It provides a set of base models that site implementers can extend to create their own `FormPage` type with their own site-specific templates. Once a page type has been set up in this way, editors can build forms within the usual page editor, consisting of any number of fields. Form submissions are stored for later retrieval through a new ‘Forms’ section within the Wagtail admin interface; in addition, they can be optionally e-mailed to an address specified by the editor.
Note
**wagtailforms is not a replacement for** [Django’s form support](https://docs.djangoproject.com/en/stable/topics/forms/ "(in Django v4.1)"). It is designed as a way for page authors to build general-purpose data collection forms without having to write code. If you intend to build a form that assigns specific behaviour to individual fields (such as creating user accounts), or needs a custom HTML layout, you will almost certainly be better served by a standard Django form, where the fields are fixed in code rather than defined on-the-fly by a page author. See the [wagtail-form-example project](https://github.com/gasman/wagtail-form-example/commits/master) for an example of integrating a Django form into a Wagtail page.
Usage
-----
Add `wagtail.contrib.forms` to your `INSTALLED_APPS`:
```
INSTALLED_APPS = [
...
'wagtail.contrib.forms',
]
```
Within the `models.py` of one of your apps, create a model that extends `wagtail.contrib.forms.models.AbstractEmailForm`:
```
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
class FormPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
```
`AbstractEmailForm` defines the fields `to_address`, `from_address` and `subject`, and expects `form_fields` to be defined. Any additional fields are treated as ordinary page content - note that `FormPage` is responsible for serving both the form page itself and the landing page after submission, so the model definition should include all necessary content fields for both of those views.
Date and datetime values in a form response will be formatted with the [SHORT\_DATE\_FORMAT](https://docs.djangoproject.com/en/3.0/ref/settings/#short-date-format) and [SHORT\_DATETIME\_FORMAT](https://docs.djangoproject.com/en/3.0/ref/settings/#short-datetime-format) respectively. (see [Custom render\_email method](customisation#form-builder-render-email) for how to customise the email content).
If you do not want your form page type to offer form-to-email functionality, you can inherit from AbstractForm instead of `AbstractEmailForm`, and omit the `to_address`, `from_address` and `subject` fields from the `content_panels` definition.
You now need to create two templates named `form_page.html` and `form_page_landing.html` (where `form_page` is the underscore-formatted version of the class name). `form_page.html` differs from a standard Wagtail template in that it is passed a variable `form`, containing a Django `Form` object, in addition to the usual `page` variable. A very basic template for the form would thus be:
```
{% load wagtailcore_tags %}
<html>
<head>
<title>{{ page.title }}</title>
</head>
<body>
<h1>{{ page.title }}</h1>
{{ page.intro|richtext }}
<form action="{% pageurl page %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>
</html>
```
`form_page_landing.html` is a standard Wagtail template, displayed after the user makes a successful form submission, `form_submission` will be available in this template. If you want to dynamically override the landing page template, you can do so with the `get_landing_page_template` method (in the same way that you would with `get_template`).
Displaying form submission information
--------------------------------------
`FormSubmissionsPanel` can be added to your page’s panel definitions to display the number of form submissions and the time of the most recent submission, along with a quick link to access the full submission data:
```
from wagtail.contrib.forms.panels import FormSubmissionsPanel
class FormPage(AbstractEmailForm):
# ...
content_panels = AbstractEmailForm.content_panels + [
FormSubmissionsPanel(),
FieldPanel('intro'),
# ...
]
```
Index
-----
* [Form builder customisation](customisation)
wagtail Form builder customisation Form builder customisation
==========================
For a basic usage example see [form builder usage](index#form-builder-usage).
Custom `related_name` for form fields
-------------------------------------
If you want to change `related_name` for form fields (by default `AbstractForm` and `AbstractEmailForm` expect `form_fields` to be defined), you will need to override the `get_form_fields` method. You can do this as shown below.
```
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='custom_form_fields')
class FormPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('custom_form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
def get_form_fields(self):
return self.custom_form_fields.all()
```
Custom form submission model
----------------------------
If you need to save additional data, you can use a custom form submission model. To do this, you need to:
* Define a model that extends `wagtail.contrib.forms.models.AbstractFormSubmission`.
* Override the `get_submission_class` and `process_form_submission` methods in your page model.
Example:
```
import json
from django.conf import settings
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField, AbstractFormSubmission
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
class FormPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
def get_submission_class(self):
return CustomFormSubmission
def process_form_submission(self, form):
self.get_submission_class().objects.create(
form_data=form.cleaned_data,
page=self, user=form.user
)
class CustomFormSubmission(AbstractFormSubmission):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
```
Add custom data to CSV export
-----------------------------
If you want to add custom data to the CSV export, you will need to:
* Override the `get_data_fields` method in page model.
* Override `get_data` in the submission model.
The example below shows how to add a username to the CSV export. Note that this code also changes the submissions list view.
```
import json
from django.conf import settings
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField, AbstractFormSubmission
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
class FormPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
def get_data_fields(self):
data_fields = [
('username', 'Username'),
]
data_fields += super().get_data_fields()
return data_fields
def get_submission_class(self):
return CustomFormSubmission
def process_form_submission(self, form):
self.get_submission_class().objects.create(
form_data=form.cleaned_data,
page=self, user=form.user
)
class CustomFormSubmission(AbstractFormSubmission):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
def get_data(self):
form_data = super().get_data()
form_data.update({
'username': self.user.username,
})
return form_data
```
Check that a submission already exists for a user
-------------------------------------------------
If you want to prevent users from filling in a form more than once, you need to override the `serve` method in your page model.
Example:
```
import json
from django.conf import settings
from django.db import models
from django.shortcuts import render
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField, AbstractFormSubmission
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
class FormPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
def serve(self, request, *args, **kwargs):
if self.get_submission_class().objects.filter(page=self, user__pk=request.user.pk).exists():
return render(
request,
self.template,
self.get_context(request)
)
return super().serve(request, *args, **kwargs)
def get_submission_class(self):
return CustomFormSubmission
def process_form_submission(self, form):
self.get_submission_class().objects.create(
form_data=form.cleaned_data,
page=self, user=form.user
)
class CustomFormSubmission(AbstractFormSubmission):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class Meta:
unique_together = ('page', 'user')
```
Your template should look like this:
```
{% load wagtailcore_tags %}
<html>
<head>
<title>{{ page.title }}</title>
</head>
<body>
<h1>{{ page.title }}</h1>
{% if user.is_authenticated and user.is_active or request.is_preview %}
{% if form %}
<div>{{ page.intro|richtext }}</div>
<form action="{% pageurl page %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
{% else %}
<div>You can fill in the from only one time.</div>
{% endif %}
{% else %}
<div>To fill in the form, you must to log in.</div>
{% endif %}
</body>
</html>
```
Multi-step form
---------------
The following example shows how to create a multi-step form.
```
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.shortcuts import render
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
class FormPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
def get_form_class_for_step(self, step):
return self.form_builder(step.object_list).get_form_class()
def serve(self, request, *args, **kwargs):
"""
Implements a simple multi-step form.
Stores each step into a session.
When the last step was submitted correctly, saves whole form into a DB.
"""
session_key_data = 'form_data-%s' % self.pk
is_last_step = False
step_number = request.GET.get('p', 1)
paginator = Paginator(self.get_form_fields(), per_page=1)
try:
step = paginator.page(step_number)
except PageNotAnInteger:
step = paginator.page(1)
except EmptyPage:
step = paginator.page(paginator.num_pages)
is_last_step = True
if request.method == 'POST':
# The first step will be submitted with step_number == 2,
# so we need to get a form from previous step
# Edge case - submission of the last step
prev_step = step if is_last_step else paginator.page(step.previous_page_number())
# Create a form only for submitted step
prev_form_class = self.get_form_class_for_step(prev_step)
prev_form = prev_form_class(request.POST, page=self, user=request.user)
if prev_form.is_valid():
# If data for step is valid, update the session
form_data = request.session.get(session_key_data, {})
form_data.update(prev_form.cleaned_data)
request.session[session_key_data] = form_data
if prev_step.has_next():
# Create a new form for a following step, if the following step is present
form_class = self.get_form_class_for_step(step)
form = form_class(page=self, user=request.user)
else:
# If there is no next step, create form for all fields
form = self.get_form(
request.session[session_key_data],
page=self, user=request.user
)
if form.is_valid():
# Perform validation again for whole form.
# After successful validation, save data into DB,
# and remove from the session.
form_submission = self.process_form_submission(form)
del request.session[session_key_data]
# render the landing page
return self.render_landing_page(request, form_submission, *args, **kwargs)
else:
# If data for step is invalid
# we will need to display form again with errors,
# so restore previous state.
form = prev_form
step = prev_step
else:
# Create empty form for non-POST requests
form_class = self.get_form_class_for_step(step)
form = form_class(page=self, user=request.user)
context = self.get_context(request)
context['form'] = form
context['fields_step'] = step
return render(
request,
self.template,
context
)
```
Your template for this form page should look like this:
```
{% load wagtailcore_tags %}
<html>
<head>
<title>{{ page.title }}</title>
</head>
<body>
<h1>{{ page.title }}</h1>
<div>{{ page.intro|richtext }}</div>
<form action="{% pageurl page %}?p={{ fields_step.number|add:"1" }}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>
</html>
```
Note that the example shown before allows the user to return to a previous step, or to open a second step without submitting the first step. Depending on your requirements, you may need to add extra checks.
Show results
------------
If you are implementing polls or surveys, you may want to show results after submission. The following example demonstrates how to do this.
First, you need to collect results as shown below:
```
from modelcluster.fields import ParentalKey
from wagtail.admin.panels import (
FieldPanel, FieldRowPanel,
InlinePanel, MultiFieldPanel
)
from wagtail.fields import RichTextField
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
class FormPage(AbstractEmailForm):
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields', label="Form fields"),
FieldPanel('thank_you_text'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname="col6"),
FieldPanel('to_address', classname="col6"),
]),
FieldPanel('subject'),
], "Email"),
]
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
# If you need to show results only on landing page,
# you may need check request.method
results = dict()
# Get information about form fields
data_fields = [
(field.clean_name, field.label)
for field in self.get_form_fields()
]
# Get all submissions for current page
submissions = self.get_submission_class().objects.filter(page=self)
for submission in submissions:
data = submission.get_data()
# Count results for each question
for name, label in data_fields:
answer = data.get(name)
if answer is None:
# Something wrong with data.
# Probably you have changed questions
# and now we are receiving answers for old questions.
# Just skip them.
continue
if type(answer) is list:
# Answer is a list if the field type is 'Checkboxes'
answer = u', '.join(answer)
question_stats = results.get(label, {})
question_stats[answer] = question_stats.get(answer, 0) + 1
results[label] = question_stats
context.update({
'results': results,
})
return context
```
Next, you need to transform your template to display the results:
```
{% load wagtailcore_tags %}
<html>
<head>
<title>{{ page.title }}</title>
</head>
<body>
<h1>{{ page.title }}</h1>
<h2>Results</h2>
{% for question, answers in results.items %}
<h3>{{ question }}</h3>
{% for answer, count in answers.items %}
<div>{{ answer }}: {{ count }}</div>
{% endfor %}
{% endfor %}
<div>{{ page.intro|richtext }}</div>
<form action="{% pageurl page %}" method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit">
</form>
</body>
</html>
```
You can also show the results on the landing page.
Custom landing page redirect
----------------------------
You can override the `render_landing_page` method on your `FormPage` to change what is rendered when a form submits.
In this example below we have added a `thank_you_page` field that enables custom redirects after a form submits to the selected page.
When overriding the `render_landing_page` method, we check if there is a linked `thank_you_page` and then redirect to it if it exists.
Finally, we add a URL param of `id` based on the `form_submission` if it exists.
```
from django.shortcuts import redirect
from wagtail.admin.panels import FieldPanel, FieldRowPanel, InlinePanel, MultiFieldPanel
from wagtail.contrib.forms.models import AbstractEmailForm
class FormPage(AbstractEmailForm):
# intro, thank_you_text, ...
thank_you_page = models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+',
)
def render_landing_page(self, request, form_submission=None, *args, **kwargs):
if self.thank_you_page:
url = self.thank_you_page.url
# if a form_submission instance is available, append the id to URL
# when previewing landing page, there will not be a form_submission instance
if form_submission:
url += '?id=%s' % form_submission.id
return redirect(url, permanent=False)
# if no thank_you_page is set, render default landing page
return super().render_landing_page(request, form_submission, *args, **kwargs)
content_panels = AbstractEmailForm.content_panels + [
FieldPanel('intro'),
InlinePanel('form_fields'),
FieldPanel('thank_you_text'),
FieldPanel('thank_you_page'),
MultiFieldPanel([
FieldRowPanel([
FieldPanel('from_address', classname='col6'),
FieldPanel('to_address', classname='col6'),
]),
FieldPanel('subject'),
], 'Email'),
]
```
Customise form submissions listing in Wagtail Admin
---------------------------------------------------
The Admin listing of form submissions can be customised by setting the attribute `submissions_list_view_class` on your FormPage model.
The list view class must be a subclass of `SubmissionsListView` from `wagtail.contrib.forms.views`, which is a child class of Django’s class based [`ListView`](https://docs.djangoproject.com/en/stable/ref/class-based-views/generic-display/#django.views.generic.list.ListView "(in Django v4.1)").
Example:
```
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
from wagtail.contrib.forms.views import SubmissionsListView
class CustomSubmissionsListView(SubmissionsListView):
paginate_by = 50 # show more submissions per page, default is 20
ordering = ('submit_time',) # order submissions by oldest first, normally newest first
ordering_csv = ('-submit_time',) # order csv export by newest first, normally oldest first
# override the method to generate csv filename
def get_csv_filename(self):
""" Returns the filename for CSV file with page slug at start"""
filename = super().get_csv_filename()
return self.form_page.slug + '-' + filename
class FormField(AbstractFormField):
page = ParentalKey('FormPage', related_name='form_fields')
class FormPage(AbstractEmailForm):
"""Form Page with customised submissions listing view"""
# set custom view class as class attribute
submissions_list_view_class = CustomSubmissionsListView
intro = RichTextField(blank=True)
thank_you_text = RichTextField(blank=True)
# content_panels = ...
```
Adding a custom field type
--------------------------
First, make the new field type available in the page editor by changing your `FormField` model.
* Create a new set of choices which includes the original `FORM_FIELD_CHOICES` along with new field types you want to make available.
* Each choice must contain a unique key and a human readable name of the field, for example `('slug', 'URL Slug')`
* Override the `field_type` field in your `FormField` model with `choices` attribute using these choices.
* You will need to run `./manage.py makemigrations` and `./manage.py migrate` after this step.
Then, create and use a new form builder class.
* Define a new form builder class that extends the `FormBuilder` class.
* Add a method that will return a created Django form field for the new field type.
* Its name must be in the format: `create_<field_type_key>_field`, for example `create_slug_field`
* Override the `form_builder` attribute in your form page model to use your new form builder class.
Example:
```
from django import forms
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.contrib.forms.forms import FormBuilder
from wagtail.contrib.forms.models import (
AbstractEmailForm, AbstractFormField, FORM_FIELD_CHOICES)
class FormField(AbstractFormField):
# extend the built in field type choices
# our field type key will be 'ipaddress'
CHOICES = FORM_FIELD_CHOICES + (('ipaddress', 'IP Address'),)
page = ParentalKey('FormPage', related_name='form_fields')
# override the field_type field with extended choices
field_type = models.CharField(
verbose_name='field type',
max_length=16,
# use the choices tuple defined above
choices=CHOICES
)
class CustomFormBuilder(FormBuilder):
# create a function that returns an instanced Django form field
# function name must match create_<field_type_key>_field
def create_ipaddress_field(self, field, options):
# return `forms.GenericIPAddressField(**options)` not `forms.SlugField`
# returns created a form field with the options passed in
return forms.GenericIPAddressField(**options)
class FormPage(AbstractEmailForm):
# intro, thank_you_text, edit_handlers, etc...
# use custom form builder defined above
form_builder = CustomFormBuilder
```
Custom `render_email` method
----------------------------
If you want to change the content of the email that is sent when a form submits you can override the `render_email` method.
To do this, you need to:
* Ensure you have your form model defined that extends `wagtail.contrib.forms.models.AbstractEmailForm`.
* Override the `render_email` method in your page model.
Example:
```
from datetime import date
# ... additional wagtail imports
from wagtail.contrib.forms.models import AbstractEmailForm
class FormPage(AbstractEmailForm):
# ... fields, content_panels, etc
def render_email(self, form):
# Get the original content (string)
email_content = super().render_email(form)
# Add a title (not part of original method)
title = '{}: {}'.format('Form', self.title)
content = [title, '', email_content, '']
# Add a link to the form page
content.append('{}: {}'.format('Submitted Via', self.full_url))
# Add the date the form was submitted
submitted_date_str = date.today().strftime('%x')
content.append('{}: {}'.format('Submitted on', submitted_date_str))
# Content is joined with a new line to separate each text line
content = '\n'.join(content)
return content
```
Custom `send_mail` method
-------------------------
If you want to change the subject or some other part of how an email is sent when a form submits you can override the `send_mail` method.
To do this, you need to:
* Ensure you have your form model defined that extends `wagtail.contrib.forms.models.AbstractEmailForm`.
* In your models.py file, import the `wagtail.admin.mail.send_mail` function.
* Override the `send_mail` method in your page model.
Example:
```
from datetime import date
# ... additional wagtail imports
from wagtail.admin.mail import send_mail
from wagtail.contrib.forms.models import AbstractEmailForm
class FormPage(AbstractEmailForm):
# ... fields, content_panels, etc
def send_mail(self, form):
# `self` is the FormPage, `form` is the form's POST data on submit
# Email addresses are parsed from the FormPage's addresses field
addresses = [x.strip() for x in self.to_address.split(',')]
# Subject can be adjusted (adding submitted date), be sure to include the form's defined subject field
submitted_date_str = date.today().strftime('%x')
subject = f"{self.subject} - {submitted_date_str}"
send_mail(subject, self.render_email(form), addresses, self.from_address,)
```
Custom `clean_name` generation
------------------------------
* Each time a new `FormField` is added a `clean_name` also gets generated based on the user entered `label`.
* `AbstractFormField` has a method `get_field_clean_name` to convert the label into a HTML valid `lower_snake_case` ASCII string using the [AnyAscii](https://pypi.org/project/anyascii/) library which can be overridden to generate a custom conversion.
* The resolved `clean_name` is also used as the form field name in rendered HTML forms.
* Ensure that any conversion will be unique enough to not create conflicts within your `FormPage` instance.
* This method gets called on creation of new fields only and as such will not have access to its own `Page` or `pk`. This does not get called when labels are edited as modifying the `clean_name` after any form responses are submitted will mean those field responses will not be retrieved.
* This method gets called for form previews and also validation of duplicate labels.
```
import uuid
from django.db import models
from modelcluster.fields import ParentalKey
# ... other field and edit_handler imports
from wagtail.contrib.forms.models import AbstractEmailForm, AbstractFormField
class FormField(AbstractFormField):
page = ParentalKey('FormPage', on_delete=models.CASCADE, related_name='form_fields')
def get_field_clean_name(self):
clean_name = super().get_field_clean_name()
id = str(uuid.uuid4())[:8] # short uuid
return f"{id}_{clean_name}"
class FormPage(AbstractEmailForm):
# ... page definitions
```
Using `FormMixin` or `EmailFormMixin` to use with other `Page` subclasses
-------------------------------------------------------------------------
If you need to add form behaviour while extending an additional class, you can use the base mixins instead of the abstract modals.
```
from wagtail.models import Page
from wagtail.contrib.forms.models import EmailFormMixin, FormMixin
class BasePage(Page):
"""
A shared base page used throughout the project.
"""
# ...
class FormPage(FormMixin, BasePage):
intro = RichTextField(blank=True)
# ...
class EmailFormPage(EmailFormMixin, FormMixin, BasePage):
intro = RichTextField(blank=True)
# ...
```
| programming_docs |
wagtail Customising IndexView - the listing view Customising IndexView - the listing view
========================================
For the sake of consistency, this section of the docs will refer to the listing view as `IndexView`, because that is the view class that does all the heavy lifting.
You can use the following attributes and methods on the `ModelAdmin` class to alter how your model data is treated and represented by the `IndexView`.
* [`ModelAdmin.list_display`](#modeladmin-list-display)
* [`ModelAdmin.list_export`](#modeladmin-list-export)
* [`ModelAdmin.list_filter`](#modeladmin-list-filter)
* [`ModelAdmin.export_filename`](#modeladmin-export-filename)
* [`ModelAdmin.search_fields`](#modeladmin-search-fields)
* [`ModelAdmin.search_handler_class`](#modeladmin-search-handler-class)
* [`ModelAdmin.extra_search_kwargs`](#modeladmin-extra-search-kwargs)
* [`ModelAdmin.ordering`](#modeladmin-ordering)
* [`ModelAdmin.list_per_page`](#modeladmin-list-per-page)
* [`ModelAdmin.get_queryset()`](#modeladmin-get-queryset)
* [`ModelAdmin.get_extra_attrs_for_row()`](#modeladmin-get-extra-attrs-for-row)
* [`ModelAdmin.get_extra_class_names_for_field_col()`](#modeladmin-get-extra-class-names-for-field-col)
* [`ModelAdmin.get_extra_attrs_for_field_col()`](#modeladmin-get-extra-attrs-for-field-col)
* [`wagtail.contrib.modeladmin.mixins.ThumbnailMixin`](#wagtail-contrib-modeladmin-mixins-thumbnailmixin)
* [`ModelAdmin.list_display_add_buttons`](#modeladmin-list-display-add-buttons)
* [`ModelAdmin.index_view_extra_css`](#modeladmin-index-view-extra-css)
* [`ModelAdmin.index_view_extra_js`](#modeladmin-index-view-extra-js)
* [`ModelAdmin.index_template_name`](#modeladmin-index-template-name)
* [`ModelAdmin.index_view_class`](#modeladmin-index-view-class)
`ModelAdmin.list_display`
-------------------------
**Expected value**: A list or tuple, where each item is the name of a field or single-argument callable on your model, or a similarly simple method defined on the `ModelAdmin` class itself.
Default value: `('__str__',)`
Set `list_display` to control which fields are displayed in the `IndexView` for your model.
You have three possible values that can be used in `list_display`:
* A field of the model. For example:
```
from wagtail.contrib.modeladmin.options import ModelAdmin
from .models import Person
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('first_name', 'last_name')
```
* The name of a custom method on your `ModelAdmin` class, that accepts a single parameter for the model instance. For example:
```
from wagtail.contrib.modeladmin.options import ModelAdmin
from .models import Person
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('upper_case_name',)
def upper_case_name(self, obj):
return ("%s %s" % (obj.first_name, obj.last_name)).upper()
upper_case_name.short_description = 'Name'
```
* The name of a method on your `Model` class that accepts only `self` as an argument. For example:
```
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
name = models.CharField(max_length=50)
birthday = models.DateField()
def decade_born_in(self):
return self.birthday.strftime('%Y')[:3] + "0's"
decade_born_in.short_description = 'Birth decade'
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('name', 'decade_born_in')
```
A few special cases to note about `list_display`:
* If the field is a `ForeignKey`, Django will display the output of `__str__()` of the related object.
* If the string provided is a method of the model or `ModelAdmin` class, Django will HTML-escape the output by default. To escape user input and allow your own unescaped tags, use `format_html()`. For example:
```
from django.db import models
from django.utils.html import format_html
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
def styled_name(self):
return format_html(
'<span style="color: #{};">{} {}</span>',
self.color_code,
self.first_name,
self.last_name,
)
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('first_name', 'last_name', 'styled_name')
```
* If the value of a field is `None`, an empty string, or an iterable without elements, Wagtail will display a dash (-) for that column. You can override this by setting `empty_value_display` on your `ModelAdmin` class. For example:
```
from wagtail.contrib.modeladmin.options import ModelAdmin
class PersonAdmin(ModelAdmin):
empty_value_display = 'N/A'
...
```
Or, if you’d like to change the value used depending on the field, you can override `ModelAdmin`’s `get_empty_value_display()` method, like so:
```
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
name = models.CharField(max_length=100)
nickname = models.CharField(blank=True, max_length=100)
likes_cat_gifs = models.NullBooleanField()
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('name', 'nickname', 'likes_cat_gifs')
def get_empty_value_display(self, field_name=None):
if field_name == 'nickname':
return 'None given'
if field_name == 'likes_cat_gifs':
return 'Unanswered'
return super().get_empty_value_display(field_name)
```
The `__str__()` method is just as valid in `list_display` as any other model method, so it’s perfectly OK to do this:
```
list_display = ('__str__', 'some_other_field')
```
By default, the ability to sort results by an item in `list_display` is only offered when it’s a field that has an actual database value (because sorting is done at the database level). However, if the output of the method is representative of a database field, you can indicate this fact by setting the `admin_order_field` attribute on that method, like so:
```
from django.db import models
from django.utils.html import format_html
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
color_code = models.CharField(max_length=6)
def styled_first_name(self):
return format_html(
'<span style="color: #{};">{}</span>',
self.color_code,
self.first_name,
)
styled_first_name.admin_order_field = 'first_name'
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('styled_first_name', 'last_name')
```
The above will tell Wagtail to order by the `first_name` field when trying to sort by `styled_first_name` in the index view.
The above will tell Wagtail to order by the `first_name` field when trying to sort by `styled_first_name` in the index view.
To indicate descending order with `admin_order_field` you can use a hyphen prefix on the field name. Using the above example, this would look like:
.. code-block:: python
```
styled_first_name.admin_order_field = '-first_name'
```
`admin_order_field` supports query lookups to sort by values on related models, too. This example includes an “author first name” column in the list display and allows sorting it by first name:
```
from django.db import models
class Blog(models.Model):
title = models.CharField(max_length=255)
author = models.ForeignKey(Person, on_delete=models.CASCADE)
def author_first_name(self, obj):
return obj.author.first_name
author_first_name.admin_order_field = 'author__first_name'
```
* Elements of `list_display` can also be properties. Please note however, that due to the way properties work in Python, setting `short_description` on a property is only possible when using the `property()` function and **not** with the `@property` decorator.
For example:
```
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
def full_name_property(self):
return self.first_name + ' ' + self.last_name
full_name_property.short_description = "Full name of the person"
full_name = property(full_name_property)
class PersonAdmin(ModelAdmin):
list_display = ('full_name',)
```
`ModelAdmin.list_export`
------------------------
**Expected value**: A list or tuple, where each item is the name of a field or single-argument callable on your model, or a similarly simple method defined on the `ModelAdmin` class itself.
Set `list_export` to set the fields you wish to be exported as columns when downloading a spreadsheet version of your index\_view
```
class PersonAdmin(ModelAdmin):
list_export = ('is_staff', 'company')
```
`ModelAdmin.list_filter`
------------------------
**Expected value**: A list or tuple, where each item is the name of model field of type `BooleanField`, `CharField`, `DateField`, `DateTimeField`, `IntegerField` or `ForeignKey`.
Set `list_filter` to activate filters in the right sidebar of the list page for your model. For example:
```
class PersonAdmin(ModelAdmin):
list_filter = ('is_staff', 'company')
```
`ModelAdmin.export_filename`
----------------------------
**Expected value**: A string specifying the filename of an exported spreadsheet, without file extensions.
```
class PersonAdmin(ModelAdmin):
export_filename = 'people_spreadsheet'
```
`ModelAdmin.search_fields`
--------------------------
**Expected value**: A list or tuple, where each item is the name of a model field of type `CharField`, `TextField`, `RichTextField` or `StreamField`.
Set `search_fields` to enable a search box at the top of the index page for your model. You should add names of any fields on the model that should be searched whenever somebody submits a search query using the search box.
Searching is handled via Django’s QuerySet API by default, see [ModelAdmin.search\_handler\_class](#modeladmin-search-handler-class) about changing this behaviour. This means by default it will work for all models, whatever search backend your project is using, and without any additional setup or configuration.
`ModelAdmin.search_handler_class`
---------------------------------
**Expected value**: A subclass of `wagtail.contrib.modeladmin.helpers.search.BaseSearchHandler`
The default value is `DjangoORMSearchHandler`, which uses the Django ORM to perform lookups on the fields specified by `search_fields`.
If you would prefer to use the built-in Wagtail search backend to search your models, you can use the `WagtailBackendSearchHandler` class instead. For example:
```
from wagtail.contrib.modeladmin.helpers import WagtailBackendSearchHandler
from .models import Person
class PersonAdmin(ModelAdmin):
model = Person
search_handler_class = WagtailBackendSearchHandler
```
### Extra considerations when using `WagtailBackendSearchHandler`
####
`ModelAdmin.search_fields` is used differently
The value of `search_fields` is passed to the underlying search backend to limit the fields used when matching. Each item in the list must be indexed on your model using [index.SearchField](../../../topics/search/indexing#wagtailsearch-index-searchfield).
To allow matching on **any** indexed field, set the `search_fields` attribute on your `ModelAdmin` class to `None`, or remove it completely.
#### Indexing extra fields using `index.FilterField`
The underlying search backend must be able to interpret all of the fields and relationships used in the queryset created by `IndexView`, including those used in `prefetch()` or `select_related()` queryset methods, or used in `list_display`, `list_filter` or `ordering`.
Be sure to test things thoroughly in a development environment (ideally using the same search backend as you use in production). Wagtail will raise an `IndexError` if the backend encounters something it does not understand, and will tell you what you need to change.
`ModelAdmin.extra_search_kwargs`
--------------------------------
**Expected value**: A dictionary of keyword arguments that will be passed on to the `search()` method of `search_handler_class`.
For example, to override the `WagtailBackendSearchHandler` default operator you could do the following:
```
from wagtail.contrib.modeladmin.helpers import WagtailBackendSearchHandler
from wagtail.search.utils import OR
from .models import IndexedModel
class DemoAdmin(ModelAdmin):
model = IndexedModel
search_handler_class = WagtailBackendSearchHandler
extra_search_kwargs = {'operator': OR}
```
`ModelAdmin.ordering`
---------------------
**Expected value**: A list or tuple in the same format as a model’s [ordering](https://docs.djangoproject.com/en/stable/ref/models/options/#django.db.models.Options.ordering "(in Django v4.1)") parameter.
Set `ordering` to specify the default ordering of objects when listed by IndexView. If not provided, the model’s default ordering will be respected.
If you need to specify a dynamic order (for example, depending on user or language) you can override the `get_ordering()` method instead.
`ModelAdmin.list_per_page`
--------------------------
**Expected value**: A positive integer
Set `list_per_page` to control how many items appear on each paginated page of the index view. By default, this is set to `100`.
`ModelAdmin.get_queryset()`
---------------------------
**Must return**: A QuerySet
The `get_queryset` method returns the ‘base’ QuerySet for your model, to which any filters and search queries are applied. By default, the `all()` method of your model’s default manager is used. But, if for any reason you only want a certain sub-set of objects to appear in the IndexView listing, overriding the `get_queryset` method on your `ModelAdmin` class can help you with that. The method takes an `HttpRequest` object as a parameter, so limiting objects by the current logged-in user is possible.
For example:
```
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
managed_by = models.ForeignKey('auth.User', on_delete=models.CASCADE)
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('first_name', 'last_name')
def get_queryset(self, request):
qs = super().get_queryset(request)
# Only show people managed by the current user
return qs.filter(managed_by=request.user)
```
`ModelAdmin.get_extra_attrs_for_row()`
--------------------------------------
**Must return**: A dictionary
The `get_extra_attrs_for_row` method allows you to add html attributes to the opening `<tr>` tag for each result, in addition to the `data-object_pk` and `class` attributes already added by the `result_row_display` template tag.
If you want to add additional CSS classes, simply provide those class names as a string value using the `'class'` key, and the `odd`/`even` will be appended to your custom class names when rendering.
For example, if you wanted to add some additional class names based on field values, you could do something like:
```
from decimal import Decimal
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class BankAccount(models.Model):
name = models.CharField(max_length=50)
account_number = models.CharField(max_length=50)
balance = models.DecimalField(max_digits=5, num_places=2)
class BankAccountAdmin(ModelAdmin):
list_display = ('name', 'account_number', 'balance')
def get_extra_attrs_for_row(self, obj, context):
if obj.balance < Decimal('0.00'):
classname = 'balance-negative'
else:
classname = 'balance-positive'
return {
'class': classname,
}
```
`ModelAdmin.get_extra_class_names_for_field_col()`
--------------------------------------------------
**Must return**: A list
The `get_extra_class_names_for_field_col` method allows you to add additional CSS class names to any of the columns defined by `list_display` for your model. The method takes two parameters:
* `obj`: the object being represented by the current row
* `field_name`: the item from `list_display` being represented by the current column
For example, if you’d like to apply some conditional formatting to a cell depending on the row’s value, you could do something like:
```
from decimal import Decimal
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class BankAccount(models.Model):
name = models.CharField(max_length=50)
account_number = models.CharField(max_length=50)
balance = models.DecimalField(max_digits=5, num_places=2)
class BankAccountAdmin(ModelAdmin):
list_display = ('name', 'account_number', 'balance')
def get_extra_class_names_for_field_col(self, obj, field_name):
if field_name == 'balance':
if obj.balance <= Decimal('-100.00'):
return ['brand-danger']
elif obj.balance <= Decimal('-0.00'):
return ['brand-warning']
elif obj.balance <= Decimal('50.00'):
return ['brand-info']
else:
return ['brand-success']
return []
```
`ModelAdmin.get_extra_attrs_for_field_col()`
--------------------------------------------
**Must return**: A dictionary
The `get_extra_attrs_for_field_col` method allows you to add additional HTML attributes to any of the columns defined in `list_display`. Like the `get_extra_class_names_for_field_col` method above, this method takes two parameters:
* `obj`: the object being represented by the current row
* `field_name`: the item from `list_display` being represented by the current column
For example, you might like to add some tooltip text to a certain column, to help give the value more context:
```
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
name = models.CharField(max_length=100)
likes_cat_gifs = models.NullBooleanField()
class PersonAdmin(ModelAdmin):
model = Person
list_display = ('name', 'likes_cat_gifs')
def get_extra_attrs_for_field_col(self, obj, field_name=None):
attrs = super().get_extra_attrs_for_field_col(obj, field_name)
if field_name == 'likes_cat_gifs' and obj.likes_cat_gifs is None:
attrs.update({
'title': (
'The person was shown several cat gifs, but failed to '
'indicate a preference.'
),
})
return attrs
```
Or you might like to add one or more data attributes to help implement some kind of interactivity using JavaScript:
```
from django.db import models
from wagtail.contrib.modeladmin.options import ModelAdmin
class Event(models.Model):
title = models.CharField(max_length=255)
start_date = models.DateField()
end_date = models.DateField()
start_time = models.TimeField()
end_time = models.TimeField()
class EventAdmin(ModelAdmin):
model = Event
list_display = ('title', 'start_date', 'end_date')
def get_extra_attrs_for_field_col(self, obj, field_name=None):
attrs = super().get_extra_attrs_for_field_col(obj, field_name)
if field_name == 'start_date':
# Add the start time as data to the 'start_date' cell
attrs.update({ 'data-time': obj.start_time.strftime('%H:%M') })
elif field_name == 'end_date':
# Add the end time as data to the 'end_date' cell
attrs.update({ 'data-time': obj.end_time.strftime('%H:%M') })
return attrs
```
`wagtail.contrib.modeladmin.mixins.ThumbnailMixin`
--------------------------------------------------
If you’re using `wagtailimages.Image` to define an image for each item in your model, `ThumbnailMixin` can help you add thumbnail versions of that image to each row in `IndexView`. To use it, simply extend `ThumbnailMixin` as well as `ModelAdmin` when defining your `ModelAdmin` class, and change a few attributes to change the thumbnail to your liking, like so:
```
from django.db import models
from wagtail.contrib.modeladmin.mixins import ThumbnailMixin
from wagtail.contrib.modeladmin.options import ModelAdmin
class Person(models.Model):
name = models.CharField(max_length=255)
avatar = models.ForeignKey('wagtailimages.Image', on_delete=models.SET_NULL, null=True)
likes_cat_gifs = models.NullBooleanField()
class PersonAdmin(ThumbnailMixin, ModelAdmin):
# Add 'admin_thumb' to list_display, where you want the thumbnail to appear
list_display = ('admin_thumb', 'name', 'likes_cat_gifs')
# Optionally tell IndexView to add buttons to a different column (if the
# first column contains the thumbnail, the buttons are likely better off
# displayed elsewhere)
list_display_add_buttons = 'name'
"""
Set 'thumb_image_field_name' to the name of the ForeignKey field that
links to 'wagtailimages.Image'
"""
thumb_image_field_name = 'avatar'
# Optionally override the filter spec used to create each thumb
thumb_image_filter_spec = 'fill-100x100' # this is the default
# Optionally override the 'width' attribute value added to each `<img>` tag
thumb_image_width = 50 # this is the default
# Optionally override the class name added to each `<img>` tag
thumb_classname = 'admin-thumb' # this is the default
# Optionally override the text that appears in the column header
thumb_col_header_text = 'image' # this is the default
# Optionally specify a fallback image to be used when the object doesn't
# have an image set, or the image has been deleted. It can an image from
# your static files folder, or an external URL.
thumb_default = 'https://lorempixel.com/100/100'
```
`ModelAdmin.list_display_add_buttons`
-------------------------------------
**Expected value**: A string matching one of the items in `list_display`.
If for any reason you’d like to change which column the action buttons appear in for each row, you can specify a different column using `list_display_add_buttons` on your `ModelAdmin` class. The value must match one of the items your class’s `list_display` attribute. By default, buttons are added to the first column of each row.
See the `ThumbnailMixin` example above to see how `list_display_add_buttons` can be used.
`ModelAdmin.index_view_extra_css`
---------------------------------
**Expected value**: A list of path names of additional stylesheets to be added to the `IndexView`
See the following part of the docs to find out more: [Adding additional stylesheets and/or JavaScript](primer#modeladmin-adding-css-and-js)
`ModelAdmin.index_view_extra_js`
--------------------------------
**Expected value**: A list of path names of additional js files to be added to the `IndexView`
See the following part of the docs to find out more: [Adding additional stylesheets and/or JavaScript](primer#modeladmin-adding-css-and-js)
`ModelAdmin.index_template_name`
--------------------------------
**Expected value**: The path to a custom template to use for `IndexView`
See the following part of the docs to find out more: [Overriding templates](primer#modeladmin-overriding-templates)
`ModelAdmin.index_view_class`
-----------------------------
**Expected value**: A custom `view` class to replace `modeladmin.views.IndexView`
See the following part of the docs to find out more: [Overriding views](primer#modeladmin-overriding-views)
| programming_docs |
wagtail ModelAdmin ModelAdmin
==========
The `modeladmin` module allows you to add any model in your project to the Wagtail admin. You can create customisable listing pages for a model, including plain Django models, and add navigation elements so that a model can be accessed directly from the Wagtail admin. Simply extend the `ModelAdmin` class, override a few attributes to suit your needs, register it with Wagtail using an easy one-line `modeladmin_register` method (you can copy and paste from the examples below), and you’re good to go. Your model doesn’t need to extend `Page` or be registered as a `Snippet`, and it won’t interfere with any of the existing admin functionality that Wagtail provides.
Summary of features
-------------------
* A customisable list view, allowing you to control what values are displayed for each row, available options for result filtering, default ordering, spreadsheet downloads and more.
* Access your list views from the Wagtail admin menu easily with automatically generated menu items, with automatic ‘active item’ highlighting. Control the label text and icons used with easy-to-change attributes on your class.
* An additional `ModelAdminGroup` class, that allows you to group your related models, and list them together in their own submenu, for a more logical user experience.
* Simple, robust **add** and **edit** views for your non-Page models that use the panel configurations defined on your model using Wagtail’s edit panels.
* For Page models, the system directs to Wagtail’s existing add and edit views, and returns you back to the correct list page, for a seamless experience.
* Full respect for permissions assigned to your Wagtail users and groups. Users will only be able to do what you want them to!
* All you need to easily hook your `ModelAdmin` classes into Wagtail, taking care of URL registration, menu changes, and registering any missing model permissions, so that you can assign them to Groups.
* **Built to be customisable** - While `modeladmin` provides a solid experience out of the box, you can easily use your own templates, and the `ModelAdmin` class has a large number of methods that you can override or extend, allowing you to customise the behaviour to a greater degree.
Want to know more about customising `ModelAdmin`?
-------------------------------------------------
* [`modeladmin` customisation primer](primer)
* [Customising the base URL path](base_url)
* [Customising the menu item](menu_item)
* [Customising `IndexView` - the listing view](indexview)
* [Customising `CreateView`, `EditView` and `DeleteView`](create_edit_delete_views)
* [Changing which fields appear in `CreateView` & `EditView`](create_edit_delete_views#changing-which-fields-appear-in-createview-editview)
* [Enabling & customising `InspectView`](inspectview)
* [Customising `ChooseParentView`](chooseparentview)
* [Additional tips and tricks](tips_and_tricks/index)
### Installation
Add `wagtail.contrib.modeladmin` to your `INSTALLED_APPS`:
```
INSTALLED_APPS = [
...
'wagtail.contrib.modeladmin',
]
```
### How to use
### A simple example
Let’s say your website is for a local library. They have a model called `Book` that appears across the site in many places. You can define a normal Django model for it, then use ModelAdmin to create a menu in Wagtail’s admin to create, view, and edit `Book` entries.
`models.py` looks like this:
```
from django.db import models
from wagtail.admin.panels import FieldPanel
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
cover_photo = models.ForeignKey(
'wagtailimages.Image',
null=True, blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
panels = [
FieldPanel('title'),
FieldPanel('author'),
FieldPanel('cover_photo')
]
```
Note
You can specify panels like `MultiFieldPanel` within the `panels` attribute of the model. This lets you use Wagtail-specific layouts in an otherwise traditional Django model.
`wagtail_hooks.py` in your app directory would look something like this:
```
from wagtail.contrib.modeladmin.options import (
ModelAdmin, modeladmin_register)
from .models import Book
class BookAdmin(ModelAdmin):
model = Book
base_url_path = 'bookadmin' # customise the URL from default to admin/bookadmin
menu_label = 'Book' # ditch this to use verbose_name_plural from model
menu_icon = 'pilcrow' # change as required
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
add_to_settings_menu = False # or True to add your model to the Settings sub-menu
exclude_from_explorer = False # or True to exclude pages of this type from Wagtail's explorer view
add_to_admin_menu = True # or False to exclude your model from the menu
list_display = ('title', 'author')
list_filter = ('author',)
search_fields = ('title', 'author')
# Now you just need to register your customised ModelAdmin class with Wagtail
modeladmin_register(BookAdmin)
```
### A more complicated example
In addition to `Book`, perhaps we also want to add `Author` and `Genre` models to our app and display a menu item for each of them, too. Creating lots of menus can add up quickly, so it might be a good idea to group related menus together. This section show you how to create one menu called *Library* which expands to show submenus for *Book*, *Author*, and *Genre*.
Assume we’ve defined `Book`, `Author`, and `Genre` models in `models.py`.
`wagtail_hooks.py` in your app directory would look something like this:
```
from wagtail.contrib.modeladmin.options import (
ModelAdmin, ModelAdminGroup, modeladmin_register)
from .models import (
Book, Author, Genre)
class BookAdmin(ModelAdmin):
model = Book
menu_label = 'Book' # ditch this to use verbose_name_plural from model
menu_icon = 'pilcrow' # change as required
list_display = ('title', 'author')
list_filter = ('genre', 'author')
search_fields = ('title', 'author')
class AuthorAdmin(ModelAdmin):
model = Author
menu_label = 'Author' # ditch this to use verbose_name_plural from model
menu_icon = 'user' # change as required
list_display = ('first_name', 'last_name')
list_filter = ('first_name', 'last_name')
search_fields = ('first_name', 'last_name')
class GenreAdmin(ModelAdmin):
model = Genre
menu_label = 'Genre' # ditch this to use verbose_name_plural from model
menu_icon = 'group' # change as required
list_display = ('name',)
list_filter = ('name',)
search_fields = ('name',)
class LibraryGroup(ModelAdminGroup):
menu_label = 'Library'
menu_icon = 'folder-open-inverse' # change as required
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
items = (BookAdmin, AuthorAdmin, GenreAdmin)
# When using a ModelAdminGroup class to group several ModelAdmin classes together,
# you only need to register the ModelAdminGroup class with Wagtail:
modeladmin_register(LibraryGroup)
```
### Registering multiple classes in one `wagtail_hooks.py` file
Each time you call `modeladmin_register(MyAdmin)` it creates a new top-level menu item in Wagtail’s left sidebar. You can call this multiple times within the same `wagtail_hooks.py` file if you want. The example below will create 3 top-level menus.
```
class BookAdmin(ModelAdmin):
model = Book
...
class MovieAdmin(ModelAdmin):
model = MovieModel
...
class MusicAdminGroup(ModelAdminGroup):
menu_label = _("Music")
items = (AlbumAdmin, ArtistAdmin)
...
modeladmin_register(BookAdmin)
modeladmin_register(MovieAdmin)
modeladmin_register(MusicAdminGroup)
```
wagtail Enabling & customising InspectView Enabling & customising InspectView
==================================
The `InspectView` is disabled by default, as it’s not often useful for most models. However, if you need a view that enables users to view more detailed information about an instance without the option to edit it, you can easily enable the inspect view by setting `inspect_view_enabled=True` on your `ModelAdmin` class.
When `InspectView` is enabled, an ‘Inspect’ button will automatically appear for each row in your index / listing view, linking to a new page that shows a list of field values for that particular object.
By default, all ‘concrete’ fields (where the field value is stored as a column in the database table for your model) will be shown. You can customise what values are displayed by adding the following attributes to your `ModelAdmin` class:
* [`ModelAdmin.inspect_view_fields`](#modeladmin-inspect-view-fields)
* [`ModelAdmin.inspect_view_fields_exclude`](#modeladmin-inspect-view-fields-exclude)
* [`ModelAdmin.inspect_view_extra_css`](#modeladmin-inspect-view-extra-css)
* [`ModelAdmin.inspect_view_extra_js`](#modeladmin-inspect-view-extra-js)
* [`ModelAdmin.inspect_template_name`](#modeladmin-inspect-template-name)
* [`ModelAdmin.inspect_view_class`](#modeladmin-inspect-view-class)
`ModelAdmin.inspect_view_fields`
--------------------------------
**Expected value:** A list or tuple, where each item is the name of a field or attribute on the instance that you’d like `InspectView` to render.
A sensible value will be rendered for most field types.
If you have `wagtail.images` installed, and the value happens to be an instance of `wagtailimages.models.Image` (or a custom model that subclasses `wagtailimages.models.AbstractImage`), a thumbnail of that image will be rendered.
If you have `wagtail.documents` installed, and the value happens to be an instance of `wagtaildocs.models.Document` (or a custom model that subclasses `wagtaildocs.models.AbstractDocument`), a link to that document will be rendered, along with the document title, file extension and size.
`ModelAdmin.inspect_view_fields_exclude`
----------------------------------------
**Expected value:** A list or tuple, where each item is the name of a field that you’d like to exclude from `InspectView`
**Note:** If both `inspect_view_fields` and `inspect_view_fields_exclude` are set, `inspect_view_fields_exclude` will be ignored.
`ModelAdmin.inspect_view_extra_css`
-----------------------------------
**Expected value**: A list of path names of additional stylesheets to be added to the `InspectView`
See the following part of the docs to find out more: [Adding additional stylesheets and/or JavaScript](primer#modeladmin-adding-css-and-js)
`ModelAdmin.inspect_view_extra_js`
----------------------------------
**Expected value**: A list of path names of additional js files to be added to the `InspectView`
See the following part of the docs to find out more: [Adding additional stylesheets and/or JavaScript](primer#modeladmin-adding-css-and-js)
`ModelAdmin.inspect_template_name`
----------------------------------
**Expected value**: The path to a custom template to use for `InspectView`
See the following part of the docs to find out more: [Overriding templates](primer#modeladmin-overriding-templates)
`ModelAdmin.inspect_view_class`
-------------------------------
**Expected value**: A custom `view` class to replace `modeladmin.views.InspectView`
See the following part of the docs to find out more: [Overriding views](primer#modeladmin-overriding-views)
wagtail Customising the base URL path Customising the base URL path
=============================
You can use the following attributes and methods on the `ModelAdmin` class to alter the base URL path used to represent your model in Wagtail’s admin area.
`ModelAdmin.base_url_path`
--------------------------
**Expected value**: A string.
Set this attribute to a string value to override the default base URL path used for the model to `admin/{base_url_path}`. If not set, the base URL path will be `admin/{app_label}/{model_name}`.
wagtail modeladmin customisation primer modeladmin customisation primer
===============================
The `modeladmin` app is designed to offer you as much flexibility as possible in how your model and its objects are represented in Wagtail’s CMS. This page aims to provide you with some background information to help you gain a better understanding of what the app can do, and to point you in the right direction, depending on the kind of customisations you’re looking to make.
* [Wagtail’s `ModelAdmin` class isn’t the same as Django’s](#wagtail-s-modeladmin-class-isn-t-the-same-as-django-s)
* [Changing what appears in the listing](#changing-what-appears-in-the-listing)
* [Adding additional stylesheets and/or JavaScript](#adding-additional-stylesheets-and-or-javascript)
* [Overriding templates](#overriding-templates)
* [Overriding views](#overriding-views)
* [Overriding helper classes](#overriding-helper-classes)
Wagtail’s `ModelAdmin` class isn’t the same as Django’s
-------------------------------------------------------
Wagtail’s `ModelAdmin` class is designed to be used in a similar way to Django’s class of the same name, and it often uses the same attribute and method names to achieve similar things. However, there are a few key differences:
### Add & edit forms are still defined by `panels` and `edit_handlers`
In Wagtail, controlling which fields appear in add/edit forms for your `Model`, and defining how they are grouped and ordered, is achieved by adding a `panels` attribute, or `edit_handler` to your `Model` class. This remains the same whether your model is a `Page` type, a snippet, or just a standard Django `Model`. Because of this, Wagtail’s `ModelAdmin` class is mostly concerned with ‘listing’ configuration. For example, `list_display`, `list_filter` and `search_fields` attributes are present and support largely the same values as Django’s ModelAdmin class, while `fields`, `fieldsets`, `exclude` and other attributes you may be used to using to configure Django’s add/edit views, simply aren’t supported by Wagtail’s version.
### ‘Page type’ models need to be treated differently from other models
While `modeladmin`’s listing view and it’s supported customisation options work in exactly the same way for all types of `Model`, when it comes to the other management views, the treatment differs depending on whether your ModelAdmin class is representing a page type model (that extends `wagtailcore.models.Page`) or not.
Pages in Wagtail have some unique properties, and require additional views, interface elements and general treatment in order to be managed effectively. For example, they have a tree structure that must be preserved properly as pages are added, deleted and moved around. They also have a revisions system, their own permission considerations, and the facility to preview changes before saving changes. Because of this added complexity, Wagtail provides its own specific views for managing any custom page types you might add to your project (whether you create a `ModelAdmin` class for them or not).
In order to deliver a consistent user experience, `modeladmin` simply redirects users to Wagtail’s existing page management views wherever possible. You should bear this in mind if you ever find yourself wanting to change what happens when pages of a certain type are added, deleted, published, or have some other action applied to them. Customising the `CreateView` or `EditView` for your page type `Model` (even if just to add an additional stylesheet or JavaScript), simply won’t have any effect, as those views are not used.
If you do find yourself needing to customise the add, edit or other behaviour for a page type model, you should take a look at the following part of the documentation: [Hooks](../../hooks#admin-hooks).
### Wagtail’s `ModelAdmin` class is ‘modular’
Unlike Django’s class of the same name, wagtailadmin’s `ModelAdmin` acts primarily as a ‘controller’ class. While it does have a set of attributes and methods to enable you to configure how various components should treat your model, it has been deliberately designed to do as little work as possible by itself; it designates all of the real work to a set of separate, swappable components.
The theory is: If you want to do something differently, or add some functionality that `modeladmin` doesn’t already have, you can create new classes (or extend the ones provided by `modeladmin`) and easily configure your `ModelAdmin` class to use them instead of the defaults.
* Learn more about [Overriding views](#modeladmin-overriding-views)
* Learn more about [Overriding helper classes](#modeladmin-overriding-helper-classes)
Changing what appears in the listing
------------------------------------
You should familiarise yourself with the attributes and methods supported by the `ModelAdmin` class, that allow you to change what is displayed in the `IndexView`. The following page should give you everything you need to get going: [Customising IndexView - the listing view](indexview)
Adding additional stylesheets and/or JavaScript
-----------------------------------------------
The `ModelAdmin` class provides several attributes to enable you to easily add additional stylesheets and JavaScript to the admin interface for your model. Each attribute simply needs to be a list of paths to the files you want to include. If the path is for a file in your project’s static directory, then Wagtail will automatically prepend the path with `STATIC_URL` so that you don’t need to repeat it each time in your list of paths.
If you’d like to add styles or scripts to the `IndexView`, you should set the following attributes:
* `index_view_extra_css` - Where each item is the path name of a pre-compiled stylesheet that you’d like to include.
* `index_view_extra_js` - Where each item is the path name of a JavaScript file that you’d like to include.
If you’d like to do the same for `CreateView` and `EditView`, you should set the following attributes:
* `form_view_extra_css` - Where each item is the path name of a pre-compiled stylesheet that you’d like to include.
* `form_view_extra_js` - Where each item is the path name of a JavaScript file that you’d like to include.
And if you’re using the `InspectView` for your model, and want to do the same for that view, you should set the following attributes:
* `inspect_view_extra_css` - Where each item is the path name of a pre-compiled stylesheet that you’d like to include.
* `inspect_view_extra_js` - Where each item is the path name of a JavaScript file that you’d like to include.
Overriding templates
--------------------
For all modeladmin views, Wagtail looks for templates in the following folders within your project or app, before resorting to the defaults:
1. `templates/modeladmin/app-name/model-name/`
2. `templates/modeladmin/app-name/`
3. `templates/modeladmin/`
So, to override the template used by `IndexView` for example, you’d create a new `index.html` template and put it in one of those locations. For example, if you wanted to do this for an `ArticlePage` model in a `news` app, you’d add your custom template as `news/templates/modeladmin/news/articlepage/index.html`.
For reference, `modeladmin` looks for templates with the following names for each view:
* `'index.html'` for `IndexView`
* `'inspect.html'` for `InspectView`
* `'create.html'` for `CreateView`
* `'edit.html'` for `EditView`
* `'delete.html'` for `DeleteView`
* `'choose_parent.html'` for `ChooseParentView`
To add extra information to a block within one of the above Wagtail templates, use Django’s `{{ block.super }}` within the `{% block ... %}` that you wish to extend. For example, if you wish to display an image in an edit form below the fields of the model that is being edited, you could do the following:
```
{% extends "modeladmin/edit.html" %}
{% load static %}
{% block content %}
{{ block.super }}
<div>
<img src="{% get_media_prefix %}{{ instance.image }}"/>
</div>
{% endblock %}
```
If for any reason you’d rather bypass the above behaviour and explicitly specify a template for a specific view, you can set either of the following attributes on your `ModelAdmin` class:
* `index_template_name` to specify a template for `IndexView`
* `inspect_template_name` to specify a template for `InspectView`
* `create_template_name` to specify a template for `CreateView`
* `edit_template_name` to specify a template for `EditView`
* `delete_template_name` to specify a template for `DeleteView`
* `choose_parent_template_name` to specify a template for `ChooseParentView`
Overriding views
----------------
For all of the views offered by `ModelAdmin`, the class provides an attribute that you can override in order to tell it which class you’d like to use:
* `index_view_class`
* `inspect_view_class`
* `create_view_class` (not used for ‘page type’ models)
* `edit_view_class` (not used for ‘page type’ models)
* `delete_view_class` (not used for ‘page type’ models)
* `choose_parent_view_class` (only used for ‘page type’ models)
For example, if you’d like to create your own view class and use it for the `IndexView`, you would do the following:
```
from wagtail.contrib.modeladmin.views import IndexView
from wagtail.contrib.modeladmin.options import ModelAdmin
from .models import MyModel
class MyCustomIndexView(IndexView):
# New functionality and existing method overrides added here
...
class MyModelAdmin(ModelAdmin):
model = MyModel
index_view_class = MyCustomIndexView
```
Or, if you have no need for any of `IndexView`’s existing functionality in your view and would rather create your own view from scratch, `modeladmin` will support that too. However, it’s highly recommended that you use `modeladmin.views.WMABaseView` as a base for your view. It’ll make integrating with your `ModelAdmin` class much easier and will provide a bunch of useful attributes and methods to get you started.
You can also use the url\_helper to easily reverse URLs for any ModelAdmin see [Reversing ModelAdmin URLs](tips_and_tricks/reversing_urls#modeladmin-reversing-urls).
Overriding helper classes
-------------------------
While ‘view classes’ are responsible for a lot of the work, there are also a number of other tasks that `modeladmin` must do regularly, that need to be handled in a consistent way, and in a number of different places. These tasks are designated to a set of simple classes (in `modeladmin`, these are termed ‘helper’ classes) and can be found in `wagtail.contrib.modeladmin.helpers`.
If you ever intend to write and use your own custom views with `modeladmin`, you should familiarise yourself with these helpers, as they are made available to views via the `modeladmin.views.WMABaseView` view.
There are three types of ‘helper class’:
* **URL helpers** - That help with the consistent generation, naming and referencing of urls.
* **Permission helpers** - That help with ensuring only users with sufficient permissions can perform certain actions, or see options to perform those actions.
* **Button helpers** - That, with the help of the other two, helps with the generation of buttons for use in a number of places.
The `ModelAdmin` class allows you to define and use your own helper classes by setting values on the following attributes:
### `ModelAdmin.url_helper_class`
By default, the `modeladmin.helpers.url.PageAdminURLHelper` class is used when your model extends `wagtailcore.models.Page`, otherwise `modeladmin.helpers.url.AdminURLHelper` is used.
If you find that the above helper classes don’t work for your needs, you can easily create your own helper class by sub-classing `AdminURLHelper` or `PageAdminURLHelper` (if your model extends Wagtail’s `Page` model), and making any necessary additions/overrides.
Once your class is defined, set the `url_helper_class` attribute on your `ModelAdmin` class to use your custom URLHelper, like so:
```
from wagtail.contrib.modeladmin.helpers import AdminURLHelper
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from .models import MyModel
class MyURLHelper(AdminURLHelper):
...
class MyModelAdmin(ModelAdmin):
model = MyModel
url_helper_class = MyURLHelper
modeladmin_register(MyModelAdmin)
```
Or, if you have a more complicated use case, where simply setting that attribute isn’t possible (due to circular imports, for example) or doesn’t meet your needs, you can override the `get_url_helper_class` method, like so:
```
class MyModelAdmin(ModelAdmin):
model = MyModel
def get_url_helper_class(self):
if self.some_attribute is True:
return MyURLHelper
return AdminURLHelper
```
### `ModelAdmin.permission_helper_class`
By default, the `modeladmin.helpers.permission.PagePermissionHelper` class is used when your model extends `wagtailcore.models.Page`, otherwise `modeladmin.helpers.permission.PermissionHelper` is used.
If you find that the above helper classes don’t work for your needs, you can easily create your own helper class, by sub-classing `PermissionHelper` (or `PagePermissionHelper` if your model extends Wagtail’s `Page` model), and making any necessary additions/overrides. Once defined, you set the `permission_helper_class` attribute on your `ModelAdmin` class to use your custom class instead of the default, like so:
```
from wagtail.contrib.modeladmin.helpers import PermissionHelper
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from .models import MyModel
class MyPermissionHelper(PermissionHelper):
...
class MyModelAdmin(ModelAdmin):
model = MyModel
permission_helper_class = MyPermissionHelper
modeladmin_register(MyModelAdmin)
```
Or, if you have a more complicated use case, where simply setting an attribute isn’t possible or doesn’t meet your needs, you can override the `get_permission_helper_class` method, like so:
```
class MyModelAdmin(ModelAdmin):
model = MyModel
def get_permission_helper_class(self):
if self.some_attribute is True:
return MyPermissionHelper
return PermissionHelper
```
### `ModelAdmin.button_helper_class`
By default, the `modeladmin.helpers.button.PageButtonHelper` class is used when your model extends `wagtailcore.models.Page`, otherwise `modeladmin.helpers.button.ButtonHelper` is used.
If you wish to add or change buttons for your model’s IndexView, you’ll need to create your own button helper class by sub-classing `ButtonHelper` or `PageButtonHelper` (if your model extend’s Wagtail’s `Page` model), and make any necessary additions/overrides. Once defined, you set the `button_helper_class` attribute on your `ModelAdmin` class to use your custom class instead of the default, like so:
```
from wagtail.contrib.modeladmin.helpers import ButtonHelper
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from .models import MyModel
class MyButtonHelper(ButtonHelper):
def add_button(self, classnames_add=None, classnames_exclude=None):
if classnames_add is None:
classnames_add = []
if classnames_exclude is None:
classnames_exclude = []
classnames = self.add_button_classnames + classnames_add
cn = self.finalise_classname(classnames, classnames_exclude)
return {
'url': self.url_helper.create_url,
'label': _('Add %s') % self.verbose_name,
'classname': cn,
'title': _('Add a new %s') % self.verbose_name,
}
def inspect_button(self, pk, classnames_add=None, classnames_exclude=None):
...
def edit_button(self, pk, classnames_add=None, classnames_exclude=None):
...
def delete_button(self, pk, classnames_add=None, classnames_exclude=None):
...
class MyModelAdmin(ModelAdmin):
model = MyModel
button_helper_class = MyButtonHelper
modeladmin_register(MyModelAdmin)
```
To customise the buttons found in the ModelAdmin List View you can change the returned dictionary in the `add_button`, `delete_button`, `edit_button` or `inspect_button` methods. For example if you wanted to change the `Delete` button you could modify the `delete_button` method in your `ButtonHelper` like so:
```
class MyButtonHelper(ButtonHelper):
...
def delete_button(self, pk, classnames_add=None, classnames_exclude=None):
...
return {
'url': reverse("your_custom_url"),
'label': _('Delete'),
'classname': "custom-css-class",
'title': _('Delete this item')
}
```
Or, if you have a more complicated use case, where simply setting an attribute isn’t possible or doesn’t meet your needs, you can override the `get_button_helper_class` method, like so:
```
class MyModelAdmin(ModelAdmin):
model = MyModel
def get_button_helper_class(self):
if self.some_attribute is True:
return MyButtonHelper
return ButtonHelper
```
### Using helpers in your custom views
As long as you sub-class `modeladmin.views.WMABaseView` (or one of the more ‘specific’ view classes) to create your custom view, instances of each helper should be available on instances of your class as:
* `self.url_helper`
* `self.permission_helper`
* `self.button_helper`
Unlike the other two, `self.button_helper` isn’t populated right away when the view is instantiated. In order to show the right buttons for the right users, ButtonHelper instances need to be ‘request aware’, so `self.button_helper` is only set once the view’s `dispatch()` method has run, which takes a `HttpRequest` object as an argument, from which the current user can be identified.
| programming_docs |
wagtail Customising ChooseParentView Customising ChooseParentView
============================
When adding a new page via Wagtail’s explorer view, you essentially choose where you want to add a new page by navigating the relevant part of the page tree and choosing to ‘add a child page’ to your chosen parent page. Wagtail then asks you to select what type of page you’d like to add.
When adding a page from a `ModelAdmin` list page, we know what type of page needs to be added, but we might not automatically know where in the page tree it should be added. If there’s only one possible choice of parent for a new page (as defined by setting `parent_page_types` and `subpage_types` attributes on your models), then we skip a step and use that as the parent. Otherwise, the user must specify a parent page using modeladmin’s `ChooseParentView`.
It should be very rare that you need to customise this view, but in case you do, modeladmin offers the following attributes that you can override:
* [`ModelAdmin.choose_parent_template_name`](#modeladmin-choose-parent-template-name)
* [`ModelAdmin.choose_parent_view_class`](#modeladmin-choose-parent-view-class)
`ModelAdmin.choose_parent_template_name`
----------------------------------------
**Expected value**: The path to a custom template to use for `ChooseParentView`
See the following part of the docs to find out more: [Overriding templates](primer#modeladmin-overriding-templates)
`ModelAdmin.choose_parent_view_class`
-------------------------------------
**Expected value**: A custom `view` class to replace `modeladmin.views.ChooseParentView`
See the following part of the docs to find out more: [Overriding views](primer#modeladmin-overriding-views)
wagtail Customising the menu item Customising the menu item
=========================
You can use the following attributes and methods on the `ModelAdmin` class to alter the menu item used to represent your model in Wagtail’s admin area.
* [`ModelAdmin.menu_label`](#modeladmin-menu-label)
* [`ModelAdmin.menu_icon`](#modeladmin-menu-icon)
* [`ModelAdmin.menu_order`](#modeladmin-menu-order)
* [`ModelAdmin.add_to_settings_menu`](#modeladmin-add-to-settings-menu)
* [`ModelAdmin.add_to_admin_menu`](#modeladmin-add-to-admin-menu)
* [`ModelAdmin.menu_item_name`](#modeladmin-menu-item-name)
`ModelAdmin.menu_label`
-----------------------
**Expected value**: A string.
Set this attribute to a string value to override the label used for the menu item that appears in Wagtail’s sidebar. If not set, the menu item will use `verbose_name_plural` from your model’s `Meta` data.
`ModelAdmin.menu_icon`
----------------------
**Expected value**: A string matching one of Wagtail’s icon class names.
If you want to change the icon used to represent your model, you can set the `menu_icon` attribute on your class to use one of the other icons available in Wagtail’s CMS. The same icon will be used for the menu item in Wagtail’s sidebar, and will also appear in the header on the list page and other views for your model. If not set, `'doc-full-inverse'` will be used for page-type models, and `'snippet'` for others.
If you’re using a `ModelAdminGroup` class to group together several `ModelAdmin` classes in their own sub-menu, and want to change the menu item used to represent the group, you should override the `menu_icon` attribute on your `ModelAdminGroup` class (`'folder-open-inverse'` is the default).
`ModelAdmin.menu_order`
-----------------------
**Expected value**: An integer between `1` and `999`.
If you want to change the position of the menu item for your model (or group of models) in Wagtail’s sidebar, you do that by setting `menu_order`. The value should be an integer between `1` and `999`. The lower the value, the higher up the menu item will appear.
Wagtail’s ‘Explorer’ menu item has an order value of `100`, so supply a value greater than that if you wish to keep the explorer menu item at the top.
`ModelAdmin.add_to_settings_menu`
---------------------------------
**Expected value**: `True` or `False`
If you’d like the menu item for your model to appear in Wagtail’s ‘Settings’ sub-menu instead of at the top level, add `add_to_settings_menu = True` to your `ModelAdmin` class.
This will only work for individual `ModelAdmin` classes registered with their own `modeladmin_register` call. It won’t work for members of a `ModelAdminGroup`.
`ModelAdmin.add_to_admin_menu`
------------------------------
**Expected value**: `True` or `False`
If you’d like this model admin to be excluded from the menu, set to `False`.
`ModelAdmin.menu_item_name`
---------------------------
**Expected value**: A string or `None`
Passed on as the `name` parameter when initialising the `MenuItem` for this class, becoming the `name` attribute value for that instance.
wagtail Customising CreateView, EditView and DeleteView Customising CreateView, EditView and DeleteView
===============================================
Note
**NOTE:** `modeladmin` only provides ‘create’, ‘edit’ and ‘delete’ functionality for non page type models (models that do not extend `wagtailcore.models.Page`). If your model is a ‘page type’ model, customising any of the following will not have any effect:
wagtail Additional tips and tricks Additional tips and tricks
==========================
This section explores some of modeladmin’s lesser-known features, and provides examples to help with modeladmin customisation. More pages will be added in future.
* [Adding a custom clean method to your ModelAdmin models](custom_clean)
* [Reversing ModelAdmin URLs](reversing_urls)
wagtail Reversing ModelAdmin URLs Reversing ModelAdmin URLs
=========================
It’s sometimes useful to be able to derive the `index` (listing) or `create` URLs for a model along with the `edit`, `delete` or `inspect` URL for a specific object in a model you have registered via the `modeladmin` app.
Wagtail itself does this by instantiating each `ModelAdmin` class you have registered, and using the `url_helper` attribute of each instance to determine what these URLs are.
You can take a similar approach in your own code too, by creating a `ModelAdmin` instance yourself, and using its `url_helper` to determine URLs.
See below for some examples:
* [Getting the `edit` or `delete` or `inspect` URL for an object](#getting-the-edit-or-delete-or-inspect-url-for-an-object)
* [Getting the `index` or `create` URL for a model](#getting-the-index-or-create-url-for-a-model)
Getting the `edit` or `delete` or `inspect` URL for an object
-------------------------------------------------------------
In this example, we will provide a quick way to `edit` the Author that is linked to a blog post from the admin page listing menu. We have defined an `AuthorModelAdmin` class and registered it with Wagtail to allow `Author` objects to be administered via the admin area. The `BlogPage` model has an `author` field (a `ForeignKey` to the `Author` model) to allow a single author to be specified for each post.
```
# file: wagtail_hooks.py
from wagtail.admin.widgets import PageListingButton
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from wagtail import hooks
# Author & BlogPage model not shown in this example
from models import Author
# ensure our modeladmin is created
class AuthorModelAdmin(ModelAdmin):
model = Author
menu_order = 200
# Creating an instance of `AuthorModelAdmin`
author_modeladmin = AuthorModelAdmin()
@hooks.register('register_page_listing_buttons')
def add_author_edit_buttons(page, page_perms, next_url=None):
"""
For pages that have an author, add an additional button to the page listing,
linking to the 'edit' page for that author.
"""
author_id = getattr(page, 'author_id', None)
if author_id:
# the url helper will return something like: /admin/my-app/author/edit/2/
author_edit_url = author_modeladmin.url_helper.get_action_url('edit', author_id)
yield PageListingButton('Edit Author', author_edit_url, priority=10)
modeladmin_register(AuthorModelAdmin)
```
As you can see from the example above, when using `get_action_url()` to generate object-specific URLs, the target object’s primary key value must be supplied so that it can be included in the resulting URL (for example `"/admin/my-app/author/edit/2/"`). The following object-specific action names are supported by `get_action_url()`:
* `'edit'` Returns a URL for updating a specific object.
* `'delete'` Returns a URL for deleting a specific object.
* `'inspect'` Returns a URL for viewing details of a specific object.
+ **NOTE:** This will only work if `inspect_view_enabled` is set to `True` on your `ModelAdmin` class.
Note
If you are using string values as primary keys for you model, you may need to handle cases where the key contains characters that are not URL safe. Only alphanumerics (`[0-9a-zA-Z]`), or the following special characters are safe: `$`, `-`, `_`, `.`, `+`, `!`, `*`, `'`, `(`, `)`.
`django.contrib.admin.utils.quote()` can be used to safely encode these primary key values before passing them to `get_action_url()`. Failure to do this may result in Wagtail not being able to recognise the primary key when the URL is visited, resulting in 404 errors.
Getting the `index` or `create` URL for a model
-----------------------------------------------
There are URLs available for the model listing view (action is `'index'`) and the create model view (action is `'create'`). Each of these has an equivalent shortcut available; `url_helper.index_url` and `url_helper.create_url`.
For example:
```
from .wagtail_hooks import AuthorModelAdmin
url_helper = AuthorModelAdmin().url_helper
index_url = url_helper.get_action_url('index')
# OR we can use the 'index_url' shortcut
also_index_url = url_helper.index_url # note: do not call this property as a function
# both will output /admin/my-app/author
create_url = url_helper.get_action_url('create')
# OR we can use the 'create_url' shortcut
also_create_url = url_helper.create_url # note: do not call this property as a function
# both will output /admin/my-app/author/create
```
Note
If you have registered a page type with `modeladmin` (for example `BlogPage`), and pages of that type can be added to more than one place in the page tree, when a user visits the `create` URL, they’ll be automatically redirected to another view to choose a parent for the new page. So, this isn’t something you need to check or cater for in your own code.
To customise `url_helper` behaviour, see [ModelAdmin.url\_helper\_class](../primer#modeladmin-url-helper-class).
wagtail Adding a custom clean method to your ModelAdmin models Adding a custom clean method to your ModelAdmin models
======================================================
The simplest way is to extend your ModelAdmin model and add a clean() model to it. For example:
```
from django import forms
from django.db import models
class ModelAdminModel(models.Model):
def clean(self):
if self.image.width < 1920 or self.image.height < 1080:
raise forms.ValidationError("The image must be at least 1920x1080 pixels in size.")
```
This will run the clean and raise the `ValidationError` whenever you save the model and the check fails. The error will be displayed at the top of the wagtail admin.
If you want more fine grained-control you can add a custom `clean()` method to the `WagtailAdminPageForm` of your model. You can override the form of your ModelAdmin in a similar matter as wagtail Pages.
So, create a custom `WagtailAdminPageForm`:
```
from wagtail.admin.forms import WagtailAdminPageForm
class ModelAdminModelForm(WagtailAdminPageForm):
def clean(self):
cleaned_data = super().clean()
image = cleaned_data.get("image")
if image and image.width < 1920 or image.height < 1080:
self.add_error("image", "The image must be at least 1920x1080px")
return cleaned_data
```
And then set the `base_form_class` of your model:
```
from django.db import models
class ModelAdminModel(models.Model):
base_form_class = ModelAdminModelForm
```
Using `self.add_error` will display the error to the particular field that has the error.
wagtail Pages Pages
=====
Wagtail requires a little careful setup to define the types of content that you want to present through your website. The basic unit of content in Wagtail is the :class:`~wagtail.models.Page`, and all of your page-level content will inherit basic webpage-related properties from it. But for the most part, you will be defining content yourself, through the construction of Django models using Wagtail’s `Page` as a base.
Wagtail organises content created from your models in a tree, which can have any structure and combination of model objects in it. Wagtail doesn’t prescribe ways to organise and interrelate your content, but here we’ve sketched out some strategies for organising your models.
The presentation of your content, the actual webpages, includes the normal use of the Django template system. We’ll cover additional functionality that Wagtail provides at the template level later on.
* [Theory](theory)
+ [Introduction to Trees](theory#introduction-to-trees)
+ [Anatomy of a Wagtail Request](theory#anatomy-of-a-wagtail-request)
+ [Scheduled Publishing](theory#scheduled-publishing)
* [Recipes](model_recipes)
+ [Overriding the `serve()` Method](model_recipes#overriding-the-serve-method)
+ [Tagging](model_recipes#tagging)
* [Panel types](panels)
+ [Built-in Fields and Choosers](panels#built-in-fields-and-choosers)
+ [Field Customisation](panels#field-customisation)
+ [Inline Panels and Model Clusters](panels#inline-panels-and-model-clusters)
* [Model Reference](model_reference)
+ [`Page`](model_reference#page)
+ [`Site`](model_reference#site)
+ [`Locale`](model_reference#locale)
+ [`TranslatableMixin`](model_reference#translatablemixin)
+ [`PreviewableMixin`](model_reference#previewablemixin)
+ [`RevisionMixin`](model_reference#revisionmixin)
+ [`DraftStateMixin`](model_reference#draftstatemixin)
+ [`Revision`](model_reference#revision)
+ [`GroupPagePermission`](model_reference#grouppagepermission)
+ [`PageViewRestriction`](model_reference#pageviewrestriction)
+ [`Orderable` (abstract)](model_reference#orderable-abstract)
+ [`Workflow`](model_reference#workflow)
+ [`WorkflowState`](model_reference#workflowstate)
+ [`Task`](model_reference#task)
+ [`TaskState`](model_reference#taskstate)
+ [`WorkflowTask`](model_reference#workflowtask)
+ [`WorkflowPage`](model_reference#workflowpage)
+ [`BaseLogEntry`](model_reference#baselogentry)
+ [`PageLogEntry`](model_reference#pagelogentry)
+ [`Comment`](model_reference#comment)
+ [`CommentReply`](model_reference#commentreply)
+ [`PageSubscription`](model_reference#pagesubscription)
* [Page QuerySet reference](queryset_reference)
+ [Examples](queryset_reference#examples)
+ [Reference](queryset_reference#module-wagtail.query)
wagtail Recipes Recipes
=======
Overriding the serve() Method
-----------------------------
Wagtail defaults to serving [`Page`](model_reference#wagtail.models.Page "wagtail.models.Page")-derived models by passing a reference to the page object to a Django HTML template matching the model’s name, but suppose you wanted to serve something other than HTML? You can override the [`serve()`](model_reference#wagtail.models.Page.serve "wagtail.models.Page.serve") method provided by the [`Page`](model_reference#wagtail.models.Page "wagtail.models.Page") class and handle the Django request and response more directly.
Consider this example of an `EventPage` object which is served as an iCal file if the `format` variable is set in the request:
```
class EventPage(Page):
...
def serve(self, request):
if "format" in request.GET:
if request.GET['format'] == 'ical':
# Export to ical format
response = HttpResponse(
export_event(self, 'ical'),
content_type='text/calendar',
)
response['Content-Disposition'] = 'attachment; filename=' + self.slug + '.ics'
return response
else:
# Unrecognised format error
message = 'Could not export event\n\nUnrecognised format: ' + request.GET['format']
return HttpResponse(message, content_type='text/plain')
else:
# Display event page as usual
return super().serve(request)
```
[`serve()`](model_reference#wagtail.models.Page.serve "wagtail.models.Page.serve") takes a Django request object and returns a Django response object. Wagtail returns a `TemplateResponse` object with the template and context which it generates, which allows middleware to function as intended, so keep in mind that a simpler response object like a `HttpResponse` will not receive these benefits.
With this strategy, you could use Django or Python utilities to render your model in JSON or XML or any other format you’d like.
### Adding Endpoints with Custom [`route()`](model_reference#wagtail.models.Page.route "wagtail.models.Page.route") Methods
Note
A much simpler way of adding more endpoints to pages is provided by the [RoutablePageMixin](../contrib/routablepage#routable-page-mixin) mixin.
Wagtail routes requests by iterating over the path components (separated with a forward slash `/`), finding matching objects based on their slug, and delegating further routing to that object’s model class. The Wagtail source is very instructive in figuring out what’s happening. This is the default `route()` method of the `Page` class:
```
class Page(...):
...
def route(self, request, path_components):
if path_components:
# request is for a child of this page
child_slug = path_components[0]
remaining_components = path_components[1:]
# find a matching child or 404
try:
subpage = self.get_children().get(slug=child_slug)
except Page.DoesNotExist:
raise Http404
# delegate further routing
return subpage.specific.route(request, remaining_components)
else:
# request is for this very page
if self.live:
# Return a RouteResult that will tell Wagtail to call
# this page's serve() method
return RouteResult(self)
else:
# the page matches the request, but isn't published, so 404
raise Http404
```
[`route()`](model_reference#wagtail.models.Page.route "wagtail.models.Page.route") takes the current object (`self`), the `request` object, and a list of the remaining `path_components` from the request URL. It either continues delegating routing by calling [`route()`](model_reference#wagtail.models.Page.route "wagtail.models.Page.route") again on one of its children in the Wagtail tree, or ends the routing process by returning a `RouteResult` object or raising a 404 error.
The `RouteResult` object (defined in wagtail.url\_routing) encapsulates all the information Wagtail needs to call a page’s [`serve()`](model_reference#wagtail.models.Page.serve "wagtail.models.Page.serve") method and return a final response: this information consists of the page object, and any additional `args`/`kwargs` to be passed to [`serve()`](model_reference#wagtail.models.Page.serve "wagtail.models.Page.serve").
By overriding the [`route()`](model_reference#wagtail.models.Page.route "wagtail.models.Page.route") method, we could create custom endpoints for each object in the Wagtail tree. One use case might be using an alternate template when encountering the `print/` endpoint in the path. Another might be a REST API which interacts with the current object. Just to see what’s involved, lets make a simple model which prints out all of its child path components.
First, `models.py`:
```
from django.shortcuts import render
from wagtail.url_routing import RouteResult
from django.http.response import Http404
from wagtail.models import Page
# ...
class Echoer(Page):
def route(self, request, path_components):
if path_components:
# tell Wagtail to call self.serve() with an additional 'path_components' kwarg
return RouteResult(self, kwargs={'path_components': path_components})
else:
if self.live:
# tell Wagtail to call self.serve() with no further args
return RouteResult(self)
else:
raise Http404
def serve(self, path_components=[]):
return render(request, self.template, {
'page': self,
'echo': ' '.join(path_components),
})
```
This model, `Echoer`, doesn’t define any properties, but does subclass `Page` so objects will be able to have a custom title and slug. The template just has to display our `{{ echo }}` property.
Now, once creating a new `Echoer` page in the Wagtail admin titled “Echo Base,” requests such as:
```
http://127.0.0.1:8000/echo-base/tauntaun/kennel/bed/and/breakfast/
```
Will return:
```
tauntaun kennel bed and breakfast
```
Be careful if you’re introducing new required arguments to the `serve()` method - Wagtail still needs to be able to display a default view of the page for previewing and moderation, and by default will attempt to do this by calling `serve()` with a request object and no further arguments. If your `serve()` method does not accept that as a method signature, you will need to override the page’s `serve_preview()` method to call `serve()` with suitable arguments:
```
def serve_preview(self, request, mode_name):
return self.serve(request, variant='radiant')
```
Tagging
-------
Wagtail provides tagging capabilities through the combination of two Django modules, [django-taggit](https://django-taggit.readthedocs.io/) (which provides a general-purpose tagging implementation) and [django-modelcluster](https://github.com/wagtail/django-modelcluster) (which extends django-taggit’s `TaggableManager` to allow tag relations to be managed in memory without writing to the database - necessary for handling previews and revisions). To add tagging to a page model, you’ll need to define a ‘through’ model inheriting from `TaggedItemBase` to set up the many-to-many relationship between django-taggit’s `Tag` model and your page model, and add a `ClusterTaggableManager` accessor to your page model to present this relation as a single tag field.
In this example, we set up tagging on `BlogPage` through a `BlogPageTag` model:
```
# models.py
from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase
class BlogPageTag(TaggedItemBase):
content_object = ParentalKey('demo.BlogPage', on_delete=models.CASCADE, related_name='tagged_items')
class BlogPage(Page):
...
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
promote_panels = Page.promote_panels + [
...
FieldPanel('tags'),
]
```
Wagtail’s admin provides a nice interface for inputting tags into your content, with typeahead tag completion and friendly tag icons.
We can now make use of the many-to-many tag relationship in our views and templates. For example, we can set up the blog’s index page to accept a `?tag=...` query parameter to filter the `BlogPage` listing by tag:
```
from django.shortcuts import render
class BlogIndexPage(Page):
...
def get_context(self, request):
context = super().get_context(request)
# Get blog entries
blog_entries = BlogPage.objects.child_of(self).live()
# Filter by tag
tag = request.GET.get('tag')
if tag:
blog_entries = blog_entries.filter(tags__name=tag)
context['blog_entries'] = blog_entries
return context
```
Here, `blog_entries.filter(tags__name=tag)` follows the `tags` relation on `BlogPage`, to filter the listing to only those pages with a matching tag name before passing this to the template for rendering. We can now update the `blog_page.html` template to show a list of tags associated with the page, with links back to the filtered index page:
```
{% for tag in page.tags.all %}
<a href="{% pageurl page.blog_index %}?tag={{ tag }}">{{ tag }}</a>
{% endfor %}
```
Iterating through `page.tags.all` will display each tag associated with `page`, while the links back to the index make use of the filter option added to the `BlogIndexPage` model. A Django query could also use the `tagged_items` related name field to get `BlogPage` objects associated with a tag.
The same approach can be used to add tagging to non-page models managed through [Snippets](../../topics/snippets#snippets) and [ModelAdmin](../contrib/modeladmin/index). In this case, the model must inherit from `modelcluster.models.ClusterableModel` to be compatible with `ClusterTaggableManager`.
### Custom tag models
In the above example, any newly-created tags will be added to django-taggit’s default `Tag` model, which will be shared by all other models using the same recipe as well as Wagtail’s image and document models. In particular, this means that the autocompletion suggestions on tag fields will include tags previously added to other models. To avoid this, you can set up a custom tag model inheriting from `TagBase`, along with a ‘through’ model inheriting from `ItemBase`, which will provide an independent pool of tags for that page model.
```
from django.db import models
from modelcluster.contrib.taggit import ClusterTaggableManager
from modelcluster.fields import ParentalKey
from taggit.models import TagBase, ItemBase
class BlogTag(TagBase):
class Meta:
verbose_name = "blog tag"
verbose_name_plural = "blog tags"
class TaggedBlog(ItemBase):
tag = models.ForeignKey(
BlogTag, related_name="tagged_blogs", on_delete=models.CASCADE
)
content_object = ParentalKey(
to='demo.BlogPage',
on_delete=models.CASCADE,
related_name='tagged_items'
)
class BlogPage(Page):
...
tags = ClusterTaggableManager(through='demo.TaggedBlog', blank=True)
```
Within the admin, the tag field will automatically recognise the custom tag model being used, and will offer autocomplete suggestions taken from that tag model.
### Disabling free tagging
By default, tag fields work on a “free tagging” basis: editors can enter anything into the field, and upon saving, any tag text not recognised as an existing tag will be created automatically. To disable this behaviour, and only allow editors to enter tags that already exist in the database, custom tag models accept a `free_tagging = False` option:
```
from taggit.models import TagBase
from wagtail.snippets.models import register_snippet
@register_snippet
class BlogTag(TagBase):
free_tagging = False
class Meta:
verbose_name = "blog tag"
verbose_name_plural = "blog tags"
```
Here we have registered `BlogTag` as a snippet, to provide an interface for administrators (and other users with the appropriate permissions) to manage the allowed set of tags. With the `free_tagging = False` option set, editors can no longer enter arbitrary text into the tag field, and must instead select existing tags from the autocomplete dropdown.
### Managing tags with Wagtail’s `ModelAdmin`
In order to manage all the tags used in a project, you can a use the `ModelAdmin` to add the `Tag` model to the Wagtail admin. This will allow you to have a tag admin interface within the main menu in which you can add, edit or delete your tags.
Tags that are removed from a content don’t get deleted from the `Tag` model and will still be shown in typeahead tag completion. So having a tag interface is a great way to completely get rid of tags you don’t need.
To add the tag interface, add the following block of code to a `wagtail_hooks.py` file within any your project’s apps:
```
from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register
from wagtail.admin.edit_handlers import FieldPanel
from taggit.models import Tag
class TagsModelAdmin(ModelAdmin):
Tag.panels = [FieldPanel("name")] # only show the name field
model = Tag
menu_label = "Tags"
menu_icon = "tag" # change as required
menu_order = 200 # will put in 3rd place (000 being 1st, 100 2nd)
list_display = ["name", "slug"]
search_fields = ("name",)
modeladmin_register(TagsModelAdmin)
```
A `Tag` model has a `name` and `slug` required fields. If you decide to add a tag, it is recommended to only display the `name` field panel as the slug field is autofilled when the `name` field is filled and you don’t need to enter the same name in both the fields.
| programming_docs |
wagtail Page QuerySet reference Page QuerySet reference
=======================
All models that inherit from [`Page`](model_reference#wagtail.models.Page "wagtail.models.Page") are given some extra QuerySet methods accessible from their `.objects` attribute.
Examples
--------
### Selecting only live pages
```
live_pages = Page.objects.live()
```
### Selecting published EventPages that are descendants of events\_index
```
events = EventPage.objects.live().descendant_of(events_index)
```
### Getting a list of menu items
```
# This gets a QuerySet of live children of the homepage with ``show_in_menus`` set
menu_items = homepage.get_children().live().in_menu()
```
Reference
---------
wagtail Theory Theory
======
Introduction to Trees
---------------------
If you’re unfamiliar with trees as an abstract data type, you might want to [review the concepts involved](https://en.wikipedia.org/wiki/Tree_(data_structure)).
As a web developer, though, you probably already have a good understanding of trees as filesystem directories or paths. Wagtail pages can create the same structure, as each page in the tree has its own URL path, like so:
```
/
people/
nien-nunb/
laura-roslin/
events/
captain-picard-day/
winter-wrap-up/
```
The Wagtail admin interface uses the tree to organise content for editing, letting you navigate up and down levels in the tree through its Explorer menu. This method of organisation is a good place to start in thinking about your own Wagtail models.
### Nodes and Leaves
It might be handy to think of the `Page`-derived models you want to create as being one of two node types: parents and leaves. Wagtail isn’t prescriptive in this approach, but it’s a good place to start if you’re not experienced in structuring your own content types.
#### Nodes
Parent nodes on the Wagtail tree probably want to organise and display a browse-able index of their descendants. A blog, for instance, needs a way to show a list of individual posts.
A Parent node could provide its own function returning its descendant objects.
```
class EventPageIndex(Page):
# ...
def events(self):
# Get list of live event pages that are descendants of this page
events = EventPage.objects.live().descendant_of(self)
# Filter events list to get ones that are either
# running now or start in the future
events = events.filter(date_from__gte=date.today())
# Order by date
events = events.order_by('date_from')
return events
```
This example makes sure to limit the returned objects to pieces of content which make sense, specifically ones which have been published through Wagtail’s admin interface (`live()`) and are children of this node (`descendant_of(self)`). By setting a `subpage_types` class property in your model, you can specify which models are allowed to be set as children, and by setting a `parent_page_types` class property, you can specify which models are allowed to be parents of this page model. Wagtail will allow any `Page`-derived model by default. Regardless, it’s smart for a parent model to provide an index filtered to make sense.
#### Leaves
Leaves are the pieces of content itself, a page which is consumable, and might just consist of a bunch of properties. A blog page leaf might have some body text and an image. A person page leaf might have a photo, a name, and an address.
It might be helpful for a leaf to provide a way to back up along the tree to a parent, such as in the case of breadcrumbs navigation. The tree might also be deep enough that a leaf’s parent won’t be included in general site navigation.
The model for the leaf could provide a function that traverses the tree in the opposite direction and returns an appropriate ancestor:
```
class EventPage(Page):
# ...
def event_index(self):
# Find closest ancestor which is an event index
return self.get_ancestors().type(EventIndexPage).last()
```
If defined, `subpage_types` and `parent_page_types` will also limit the parent models allowed to contain a leaf. If not, Wagtail will allow any combination of parents and leafs to be associated in the Wagtail tree. Like with index pages, it’s a good idea to make sure that the index is actually of the expected model to contain the leaf.
#### Other Relationships
Your `Page`-derived models might have other interrelationships which extend the basic Wagtail tree or depart from it entirely. You could provide functions to navigate between siblings, such as a “Next Post” link on a blog page (`post->post->post`). It might make sense for subtrees to interrelate, such as in a discussion forum (`forum->post->replies`) Skipping across the hierarchy might make sense, too, as all objects of a certain model class might interrelate regardless of their ancestors (`events = EventPage.objects.all`). It’s largely up to the models to define their interrelations, the possibilities are really endless.
Anatomy of a Wagtail Request
----------------------------
For going beyond the basics of model definition and interrelation, it might help to know how Wagtail handles requests and constructs responses. In short, it goes something like:
1. Django gets a request and routes through Wagtail’s URL dispatcher definitions
2. Wagtail checks the hostname of the request to determine which `Site` record will handle this request.
3. Starting from the root page of that site, Wagtail traverses the page tree, calling the `route()` method and letting each page model decide whether it will handle the request itself or pass it on to a child page.
4. The page responsible for handling the request returns a `RouteResult` object from `route()`, which identifies the page along with any additional `args`/`kwargs` to be passed to `serve()`.
5. Wagtail calls `serve()`, which constructs a context using `get_context()`
6. `serve()` finds a template to pass it to using `get_template()`
7. A response object is returned by `serve()` and Django responds to the requester.
You can apply custom behaviour to this process by overriding `Page` class methods such as `route()` and `serve()` in your own models. For examples, see [Recipes](model_recipes#page-model-recipes).
Scheduled Publishing
--------------------
Page publishing can be scheduled through the *Set schedule* feature in the *Status* side panel of the *Edit* page. This allows you to set up initial page publishing or a page update in advance. In order for pages to go live at the scheduled time, you should set up the [publish\_scheduled](../management_commands#publish-scheduled) management command.
The basic workflow is as follows:
* Scheduling is done by setting the *go-live at* field of the page and clicking *Publish*.
* Scheduling a revision for a page that is not currently live means that page will go live when the scheduled time comes.
* Scheduling a revision for a page that is already live means that revision will be published when the time comes.
* If the page has a scheduled revision and you set another revision to publish immediately (i.e. clicking *Publish* with the *go-live at* field unset), the scheduled revision will be unscheduled.
* If the page has a scheduled revision and you schedule another revision to publish (i.e. clicking *Publish* with the *go-live at* field set), the existing scheduled revision will be unscheduled and the new revision will be scheduled instead.
Note that you have to click *Publish* after setting the *go-live at* field for the revision to be scheduled. Saving a draft revision with the *go-live at* field without clicking *Publish* will not schedule it to be published.
The *History* view for a given page will show which revision is scheduled and when it is scheduled for. A scheduled revision in the list will also provide an *Unschedule* button to cancel it.
In addition to scheduling a page to be published, it is also possible to schedule a page to be unpublished by setting the *expire at* field. However, unlike with publishing, the unpublishing schedule is applied to the live page instance rather than a specific revision. This means that any change to the *expire at* field will only be effective once the associated revision is published (i.e. when the changes are applied to the live instance). To illustrate:
* Scheduling is done by setting the *expire at* field of the page and clicking *Publish*. If the *go-live at* field is also set, then the unpublishing schedule will only be applied after the revision goes live.
* Consider a live page that is scheduled to be unpublished on e.g. 14 June. Then sometime before the schedule, consider that a new revision is scheduled to be published on a date that’s **earlier** than the unpublishing schedule, e.g. 9 June. When the new revision goes live on 9 June, the *expire at* field contained in the new revision will replace the existing unpublishing schedule. This means:
+ If the new revision contains a different *expire at* field (e.g. 17 June), the new revision will go live on 9 June and the page will not be unpublished on 14 June but it will be unpublished on 17 June.
+ If the new revision has the *expire at* field unset, the new revision will go live on 9 June and the unpublishing schedule will be unset, thus the page will not be unpublished.
* Consider another live page that is scheduled to be unpublished on e.g. 14 June. Then sometime before the schedule, consider that a new revision is scheduled to be published on a date that’s **later** than the unpublishing schedule, e.g. 21 June. The new revision will not take effect until it goes live on 21 June, so the page will still be unpublished on 14 June. This means:
+ If the new revision contains a different *expire at* field (e.g. 25 June), the page will be unpublished on 14 June, the new revision will go live on 21 June and the page will be unpublished again on 25 June.
+ If the new revision has the *expire at* field unset, the page will be unpublished on 14 June and the new revision will go live on 21 June.
The same scheduling mechanism also applies to snippets with [`DraftStateMixin`](model_reference#wagtail.models.DraftStateMixin "wagtail.models.DraftStateMixin") applied. For more details, see [Saving draft changes of snippets](../../topics/snippets#wagtailsnippets-saving-draft-changes-of-snippets).
wagtail Panel types Panel types
===========
Built-in Fields and Choosers
----------------------------
Django’s field types are automatically recognised and provided with an appropriate widget for input. Just define that field the normal Django way and pass the field name into [`FieldPanel`](#wagtail.admin.panels.FieldPanel "wagtail.admin.panels.FieldPanel") when defining your panels. Wagtail will take care of the rest.
Here are some Wagtail-specific types that you might include as fields in your models.
### FieldPanel
### StreamFieldPanel
### MultiFieldPanel
### InlinePanel
This is a powerful but complex feature which will take some space to cover, so we’ll skip over it for now. For a full explanation on the usage of `InlinePanel`, see [Inline Panels and Model Clusters](#inline-panels).
#### Collapsing InlinePanels to save space
Note that you can use `classname="collapsed"` to load the panel collapsed under its heading in order to save space in the Wagtail admin.
### FieldRowPanel
### HelpPanel
### PageChooserPanel
### ImageChooserPanel
### FormSubmissionsPanel
### DocumentChooserPanel
### SnippetChooserPanel
Field Customisation
-------------------
By adding CSS classes to your panel definitions or adding extra parameters to your field definitions, you can control much of how your fields will display in the Wagtail page editing interface. Wagtail’s page editing interface takes much of its behaviour from Django’s admin, so you may find many options for customisation covered there. (See [Django model field reference](https://docs.djangoproject.com/en/stable/ref/models/fields/ "(in Django v4.1)")).
### Titles
Use `classname="title"` to make Page’s built-in title field stand out with more vertical padding.
### Collapsible
Changed in version 4.0: All panels are now collapsible by default.
Using `classname="collapsed"` will load the editor page with the panel collapsed under its heading.
```
content_panels = [
MultiFieldPanel(
[
FieldPanel('cover'),
FieldPanel('book_file'),
FieldPanel('publisher'),
],
heading="Collection of Book Fields",
classname="collapsed"
),
]
```
### Placeholder Text
By default, Wagtail uses the field’s label as placeholder text. To change it, pass to the FieldPanel a widget with a placeholder attribute set to your desired text. You can select widgets from [Django’s form widgets](https://docs.djangoproject.com/en/stable/ref/forms/widgets/ "(in Django v4.1)"), or any of the Wagtail’s widgets found in `wagtail.admin.widgets`.
For example, to customise placeholders for a Book model exposed via ModelAdmin:
```
# models.py
from django import forms # the default Django widgets live here
from wagtail.admin import widgets # to use Wagtail's special datetime widget
class Book(models.Model):
title = models.CharField(max_length=256)
release_date = models.DateField()
price = models.DecimalField(max_digits=5, decimal_places=2)
# you can create them separately
title_widget = forms.TextInput(
attrs = {
'placeholder': 'Enter Full Title'
}
)
# using the correct widget for your field type and desired effect
date_widget = widgets.AdminDateInput(
attrs = {
'placeholder': 'dd-mm-yyyy'
}
)
panels = [
FieldPanel('title', widget=title_widget), # then add them as a variable
FieldPanel('release_date', widget=date_widget),
FieldPanel('price', widget=forms.NumberInput(attrs={'placeholder': 'Retail price on release'})) # or directly inline
]
```
### Required Fields
To make input or chooser selection mandatory for a field, add [`blank=False`](https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.Field.blank "(in Django v4.1)") to its model definition.
### Hiding Fields
Without a panel definition, a default form field (without label) will be used to represent your fields. If you intend to hide a field on the Wagtail page editor, define the field with [`editable=False`](https://docs.djangoproject.com/en/stable/ref/models/fields/#django.db.models.Field.editable "(in Django v4.1)").
Inline Panels and Model Clusters
--------------------------------
The `django-modelcluster` module allows for streamlined relation of extra models to a Wagtail page via a ForeignKey-like relationship called `ParentalKey`. Normally, your related objects “cluster” would need to be created beforehand (or asynchronously) before being linked to a Page; however, objects related to a Wagtail page via `ParentalKey` can be created on-the-fly and saved to a draft revision of a `Page` object.
Let’s look at the example of adding related links to a [`Page`](model_reference#wagtail.models.Page "wagtail.models.Page")-derived model. We want to be able to add as many as we like, assign an order, and do all of this without leaving the page editing screen.
```
from wagtail.models import Orderable, Page
from modelcluster.fields import ParentalKey
# The abstract model for related links, complete with panels
class RelatedLink(models.Model):
title = models.CharField(max_length=255)
link_external = models.URLField("External link", blank=True)
panels = [
FieldPanel('title'),
FieldPanel('link_external'),
]
class Meta:
abstract = True
# The real model which combines the abstract model, an
# Orderable helper class, and what amounts to a ForeignKey link
# to the model we want to add related links to (BookPage)
class BookPageRelatedLinks(Orderable, RelatedLink):
page = ParentalKey('demo.BookPage', on_delete=models.CASCADE, related_name='related_links')
class BookPage(Page):
# ...
content_panels = Page.content_panels + [
InlinePanel('related_links', heading="Related Links", label="Related link"),
]
```
The `RelatedLink` class is a vanilla Django abstract model. The `BookPageRelatedLinks` model extends it with capability for being ordered in the Wagtail interface via the `Orderable` class as well as adding a `page` property which links the model to the `BookPage` model we’re adding the related links objects to. Finally, in the panel definitions for `BookPage`, we’ll add an [`InlinePanel`](#wagtail.admin.panels.InlinePanel "wagtail.admin.panels.InlinePanel") to provide an interface for it all. Let’s look again at the parameters that [`InlinePanel`](#wagtail.admin.panels.InlinePanel "wagtail.admin.panels.InlinePanel") accepts:
```
InlinePanel(relation_name, panels=None, heading='', label='', help_text='', min_num=None, max_num=None)
```
The `relation_name` is the `related_name` label given to the cluster’s `ParentalKey` relation. You can add the `panels` manually or make them part of the cluster model. `heading` and `help_text` provide a heading and caption, respectively, for the Wagtail editor. `label` sets the text on the add button and child panels, and is used as the heading when `heading` is not present. Finally, `min_num` and `max_num` allow you to set the minimum/maximum number of forms that the user must submit.
For another example of using model clusters, see [Tagging](model_recipes#tagging).
For more on `django-modelcluster`, visit [the django-modelcluster github project page](https://github.com/wagtail/django-modelcluster)
wagtail Model Reference Model Reference
===============
wagtail.models is split into submodules for maintainability. All definitions intended as public should be imported here (with ‘noqa’ comments as required) and outside code should continue to import them from wagtail.models (e.g. `from wagtail.models import Site`, not `from wagtail.models.sites import Site`.)
Submodules should take care to keep the direction of dependencies consistent; where possible they should implement low-level generic functionality which is then imported by higher-level models such as Page.
This document contains reference information for the model classes inside the `wagtailcore` module.
`Page`
------
### Database fields
### Methods and properties
In addition to the model fields provided, `Page` has many properties and methods that you may wish to reference, use, or override in creating your own models.
Note
See also [django-treebeard](https://django-treebeard.readthedocs.io/en/latest/index.html)’s `node API <https://django-treebeard.readthedocs.io/en/latest/api.html>. `Page` is a subclass of [materialized path tree](https://django-treebeard.readthedocs.io/en/latest/mp_tree.html) nodes.
`Site`
------
The `Site` model is useful for multi-site installations as it allows an administrator to configure which part of the tree to use for each hostname that the server responds on.
The [`find_for_request()`](#wagtail.models.Site.find_for_request "wagtail.models.Site.find_for_request") function returns the Site object that will handle the given HTTP request.
### Database fields
### Methods and properties
`Locale`
--------
The `Locale` model defines the set of languages and/or locales that can be used on a site. Each `Locale` record corresponds to a “language code” defined in the :ref:`wagtail_content_languages_setting` setting.
Wagtail will initially set up one `Locale` to act as the default language for all existing content. This first locale will automatically pick the value from `WAGTAIL_CONTENT_LANGUAGES` that most closely matches the site primary language code defined in `LANGUAGE_CODE`. If the primary language code is changed later, Wagtail will **not** automatically create a new `Locale` record or update an existing one.
Before internationalisation is enabled, all pages use this primary `Locale` record. This is to satisfy the database constraints, and makes it easier to switch internationalisation on at a later date.
### Changing `WAGTAIL_CONTENT_LANGUAGES`
Languages can be added or removed from `WAGTAIL_CONTENT_LANGUAGES` over time.
Before removing an option from `WAGTAIL_CONTENT_LANGUAGES`, it’s important that the `Locale` record is updated to a use a different content language or is deleted. Any `Locale` instances that have invalid content languages are automatically filtered out from all database queries making them unable to be edited or viewed.
### Methods and properties
`TranslatableMixin`
-------------------
`TranslatableMixin` is an abstract model that can be added to any non-page Django model to make it translatable. Pages already include this mixin, so there is no need to add it.
### Database fields
The `locale` and `translation_key` fields have a unique key constraint to prevent the object being translated into a language more than once.
### Methods and properties
`PreviewableMixin`
------------------
`PreviewableMixin` is a mixin class that can be added to any non-page Django model to allow previewing its instances. Pages already include this mixin, so there is no need to add it.
New in version 4.0: The class is added to allow snippets to have live preview in the editor. See [Making snippets previewable](../../topics/snippets#wagtailsnippets-making-snippets-previewable) for more details.
### Methods and properties
`RevisionMixin`
---------------
`RevisionMixin` is an abstract model that can be added to any non-page Django model to allow saving revisions of its instances. Pages already include this mixin, so there is no need to add it.
New in version 4.0: The model is added to allow snippets to save revisions, revert to a previous revision, and compare changes between revisions. See [Saving revisions of snippets](../../topics/snippets#wagtailsnippets-saving-revisions-of-snippets) for more details.
### Database fields
### Methods and properties
`DraftStateMixin`
-----------------
`DraftStateMixin` is an abstract model that can be added to any non-page Django model to allow its instances to have unpublished changes. This mixin requires [`RevisionMixin`](#wagtail.models.RevisionMixin "wagtail.models.RevisionMixin") to be applied. Pages already include this mixin, so there is no need to add it.
New in version 4.0: The model is added to allow snippets to have changes that are not immediately reflected to the instance. See [Saving draft changes of snippets](../../topics/snippets#wagtailsnippets-saving-draft-changes-of-snippets) for more details.
### Database fields
### Methods and properties
`Revision`
----------
Every time a page is edited, a new `Revision` is created and saved to the database. It can be used to find the full history of all changes that have been made to a page and it also provides a place for new changes to be kept before going live.
* Revisions can be created from any instance of [`RevisionMixin`](#wagtail.models.RevisionMixin "wagtail.models.RevisionMixin") by calling its [`save_revision()`](#wagtail.models.RevisionMixin.save_revision "wagtail.models.RevisionMixin.save_revision") method.
* The content of the page is JSON-serialisable and stored in the [`content`](#wagtail.models.Revision.content "wagtail.models.Revision.content") field.
* You can retrieve a `Revision` as an instance of the object’s model by calling the [`as_object()`](#wagtail.models.Revision.as_object "wagtail.models.Revision.as_object") method.
Changed in version 4.0: The model has been renamed from `PageRevision` to `Revision` and it now references the `Page` model using a [`GenericForeignKey`](https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericForeignKey "(in Django v4.1)").
### Database fields
### Managers
### Methods and properties
`GroupPagePermission`
---------------------
### Database fields
`PageViewRestriction`
---------------------
### Database fields
`Orderable` (abstract)
-----------------------
### Database fields
`Workflow`
----------
Workflows represent sequences of tasks which much be approved for an action to be performed on a page - typically publication.
### Database fields
### Methods and properties
`WorkflowState`
---------------
Workflow states represent the status of a started workflow on a page.
### Database fields
### Methods and properties
`Task`
------
Tasks represent stages in a workflow which must be approved for the workflow to complete successfully.
### Database fields
### Methods and properties
`TaskState`
-----------
Task states store state information about the progress of a task on a particular page revision.
### Database fields
### Methods and properties
`WorkflowTask`
--------------
Represents the ordering of a task in a specific workflow.
### Database fields
`WorkflowPage`
--------------
Represents the assignment of a workflow to a page and its descendants.
### Database fields
`BaseLogEntry`
--------------
An abstract base class that represents a record of an action performed on an object.
### Database fields
### Methods and properties
`PageLogEntry`
--------------
Represents a record of an action performed on an [`Page`](#wagtail.models.Page "wagtail.models.Page"), subclasses [`BaseLogEntry`](#wagtail.models.BaseLogEntry "wagtail.models.BaseLogEntry").
### Database fields
`Comment`
---------
Represents a comment on a page.
### Database fields
`CommentReply`
--------------
Represents a reply to a comment thread.
### Database fields
`PageSubscription`
------------------
Represents a user’s subscription to email notifications about page events. Currently only used for comment notifications.
### Database fields
| programming_docs |
wagtail StreamField reference StreamField reference
=====================
* [StreamField block reference](blocks)
+ [`wagtail.fields.StreamField`](blocks#wagtail.fields.StreamField)
+ [Block options](blocks#block-options)
+ [Field block types](blocks#field-block-types)
+ [Structural block types](blocks#structural-block-types)
* [Form widget client-side API](widget_api)
+ [`render()`](widget_api#render)
+ [`idForLabel`](widget_api#idForLabel)
+ [`getValue()`](widget_api#getValue)
+ [`getState()`](widget_api#getState)
+ [`setState()`](widget_api#setState)
+ [`focus()`](widget_api#focus)
[StreamField block reference](blocks#streamfield-block-reference)
-----------------------------------------------------------------
Details the block types provided by Wagtail for use in StreamField and how they can be combined into new block types.
[Form widget client-side API](widget_api#streamfield-widget-api)
----------------------------------------------------------------
Defines the JavaScript API that must be implemented for any form widget used within a StreamField block.
wagtail Form widget client-side API Form widget client-side API
===========================
In order for the StreamField editing interface to dynamically create form fields, any Django form widgets used within StreamField blocks must have an accompanying JavaScript implementation, defining how the widget is rendered client-side and populated with data, and how to extract data from that field. Wagtail provides this implementation for widgets inheriting from `django.forms.widgets.Input`, `django.forms.Textarea`, `django.forms.Select` and `django.forms.RadioSelect`. For any other widget types, or ones which require custom client-side behaviour, you will need to provide your own implementation.
The [telepath](https://wagtail.github.io/telepath/) library is used to set up mappings between Python widget classes and their corresponding JavaScript implementations. To create a mapping, define a subclass of `wagtail.widget_adapters.WidgetAdapter` and register it with `wagtail.telepath.register`.
```
from wagtail.telepath import register
from wagtail.widget_adapters import WidgetAdapter
class FancyInputAdapter(WidgetAdapter):
# Identifier matching the one registered on the client side
js_constructor = 'myapp.widgets.FancyInput'
# Arguments passed to the client-side object
def js_args(self, widget):
return [
# Arguments typically include the widget's HTML representation
# and label ID rendered with __NAME__ and __ID__ placeholders,
# for use in the client-side render() method
widget.render('__NAME__', None, attrs={'id': '__ID__'}),
widget.id_for_label('__ID__'),
widget.extra_options,
]
class Media:
# JS / CSS includes required in addition to the widget's own media;
# generally this will include the client-side adapter definition
js = ['myapp/js/fancy-input-adapter.js']
register(FancyInputAdapter(), FancyInput)
```
The JavaScript object associated with a widget instance should provide a single method:
A widget’s state will often be the same as the form field’s value, but may contain additional data beyond what is processed in the form submission. For example, a page chooser widget consists of a hidden form field containing the page ID, and a read-only label showing the page title: in this case, the page ID by itself does not provide enough information to render the widget, and so the state is defined as a dictionary with `id` and `title` items.
The value returned by `render` is a ‘bound widget’ object allowing this widget instance’s data to be accessed. This object should implement the following attributes and methods:
wagtail StreamField block reference StreamField block reference
===========================
This document details the block types provided by Wagtail for use in [StreamField](../../advanced_topics/testing#wagtail.test.utils.form_data.streamfield "wagtail.test.utils.form_data.streamfield"), and how they can be combined into new block types.
Changed in version 3.0: The required `use_json_field` argument is added.
```
body = StreamField([
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], block_counts={
'heading': {'min_num': 1},
'image': {'max_num': 5},
}, use_json_field=True)
```
Block options
-------------
All block definitions accept the following optional keyword arguments:
* `default`
+ The default value that a new ‘empty’ block should receive.
* `label`
+ The label to display in the editor interface when referring to this block - defaults to a prettified version of the block name (or, in a context where no name is assigned - such as within a `ListBlock` - the empty string).
* `icon`
+ The name of the icon to display for this block type in the menu of available block types. For a list of icon names, see the Wagtail style guide, which can be enabled by adding `wagtail.contrib.styleguide` to your project’s `INSTALLED_APPS`.
* `template`
+ The path to a Django template that will be used to render this block on the front end. See [Template rendering](../../topics/streamfield#streamfield-template-rendering)
* `group`
+ The group used to categorize this block. Any blocks with the same group name will be shown together in the editor interface with the group name as a heading.
Field block types
-----------------
Structural block types
----------------------
Since `StreamField` accepts an instance of `StreamBlock` as a parameter, in place of a list of block types, this makes it possible to re-use a common set of block types without repeating definitions:
```
class HomePage(Page):
carousel = StreamField(
CarouselBlock(max_num=10, block_counts={'video': {'max_num': 2}}),
use_json_field=True
)
```
`StreamBlock` accepts the following additional options as either keyword arguments or `Meta` properties:
```
body = StreamField([
# ...
('event_promotions', blocks.StreamBlock([
('hashtag', blocks.CharBlock()),
('post_date', blocks.DateBlock()),
], form_classname='event-promotions')),
], use_json_field=True)
```
```
class EventPromotionsBlock(blocks.StreamBlock):
hashtag = blocks.CharBlock()
post_date = blocks.DateBlock()
class Meta:
form_classname = 'event-promotions'
```
wagtail Page models Page models
===========
Each page type (a.k.a. content type) in Wagtail is represented by a Django model. All page models must inherit from the [`wagtail.models.Page`](../reference/pages/model_reference#wagtail.models.Page "wagtail.models.Page") class.
As all page types are Django models, you can use any field type that Django provides. See [Model field reference](https://docs.djangoproject.com/en/stable/ref/models/fields/) for a complete list of field types you can use. Wagtail also provides `wagtail.fields.RichTextField` which provides a WYSIWYG editor for editing rich-text content.
Note
If you’re not yet familiar with Django models, have a quick look at the following links to get you started:
* [Creating models](https://docs.djangoproject.com/en/stable/intro/tutorial02/#creating-models "(in Django v4.1)")
* [Model syntax](https://docs.djangoproject.com/en/stable/topics/db/models/ "(in Django v4.1)")
An example Wagtail page model
-----------------------------
This example represents a typical blog post:
```
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.models import Page, Orderable
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel, MultiFieldPanel, InlinePanel
from wagtail.search import index
class BlogPage(Page):
# Database fields
body = RichTextField()
date = models.DateField("Post date")
feed_image = models.ForeignKey(
'wagtailimages.Image',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
# Search index configuration
search_fields = Page.search_fields + [
index.SearchField('body'),
index.FilterField('date'),
]
# Editor panels configuration
content_panels = Page.content_panels + [
FieldPanel('date'),
FieldPanel('body'),
InlinePanel('related_links', heading="Related links", label="Related link"),
]
promote_panels = [
MultiFieldPanel(Page.promote_panels, "Common page configuration"),
FieldPanel('feed_image'),
]
# Parent page / subpage type rules
parent_page_types = ['blog.BlogIndex']
subpage_types = []
class BlogPageRelatedLink(Orderable):
page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='related_links')
name = models.CharField(max_length=255)
url = models.URLField()
panels = [
FieldPanel('name'),
FieldPanel('url'),
]
```
Note
Ensure that none of your field names are the same as your class names. This will cause errors due to the way Django handles relations ([read more](https://github.com/wagtail/wagtail/issues/503)). In our examples we have avoided this by appending “Page” to each model name.
Writing page models
-------------------
Here we’ll describe each section of the above example to help you create your own page models.
### Database fields
Each Wagtail page type is a Django model, represented in the database as a separate table.
Each page type can have its own set of fields. For example, a news article may have body text and a published date, whereas an event page may need separate fields for venue and start/finish times.
In Wagtail, you can use any Django field class. Most field classes provided by third party apps should work as well.
Wagtail also provides a couple of field classes of its own:
* `RichTextField` - For rich text content
* `StreamField` - A block-based content field (see: [Freeform page content using StreamField](streamfield))
For tagging, Wagtail fully supports [django-taggit](https://django-taggit.readthedocs.org/en/latest/) so we recommend using that.
### Search
The `search_fields` attribute defines which fields are added to the search index and how they are indexed.
This should be a list of `SearchField` and `FilterField` objects. `SearchField` adds a field for full-text search. `FilterField` adds a field for filtering the results. A field can be indexed with both `SearchField` and `FilterField` at the same time (but only one instance of each).
In the above example, we’ve indexed `body` for full-text search and `date` for filtering.
The arguments that these field types accept are documented in [indexing extra fields](search/indexing#wagtailsearch-indexing-fields).
### Editor panels
There are a few attributes for defining how the page’s fields will be arranged in the page editor interface:
* `content_panels` - For content, such as main body text
* `promote_panels` - For metadata, such as tags, thumbnail image and SEO title
* `settings_panels` - For settings, such as publish date
Each of these attributes is set to a list of `Panel` objects, which defines which fields appear on which tabs and how they are structured on each tab.
Here’s a summary of the `Panel` classes that Wagtail provides out of the box. See [Panel types](../reference/pages/panels) for full descriptions.
**Basic**
These allow editing of model fields. The `FieldPanel` class will choose the correct widget based on the type of the field, such as a rich text editor for `RichTextField`, or an image chooser for a `ForeignKey` to an image model. `FieldPanel` also provides a page chooser interface for `ForeignKey`s to page models, but for more fine-grained control over which page types can be chosen, `PageChooserPanel` provides additional configuration options.
* [`FieldPanel`](../reference/pages/panels#wagtail.admin.panels.FieldPanel "wagtail.admin.panels.FieldPanel")
* [`PageChooserPanel`](../reference/pages/panels#wagtail.admin.panels.PageChooserPanel "wagtail.admin.panels.PageChooserPanel")
Changed in version 3.0: Previously, certain field types required special-purpose panels: `StreamFieldPanel`, `ImageChooserPanel`, `DocumentChooserPanel` and `SnippetChooserPanel`. These are now all handled by `FieldPanel`.
**Structural**
These are used for structuring fields in the interface.
* [`MultiFieldPanel`](../reference/pages/panels#wagtail.admin.panels.MultiFieldPanel "wagtail.admin.panels.MultiFieldPanel")
* [`InlinePanel`](../reference/pages/panels#wagtail.admin.panels.InlinePanel "wagtail.admin.panels.InlinePanel")
* [`FieldRowPanel`](../reference/pages/panels#wagtail.admin.panels.FieldRowPanel "wagtail.admin.panels.FieldRowPanel")
#### Customising the page editor interface
The page editor can be customised further. See [Customising the editing interface](../advanced_topics/customisation/page_editing_interface).
### Parent page / subpage type rules
These two attributes allow you to control where page types may be used in your site. It allows you to define rules like “blog entries may only be created under a blog index”.
Both take a list of model classes or model names. Model names are of the format `app_label.ModelName`. If the `app_label` is omitted, the same app is assumed.
* `parent_page_types` limits which page types this type can be created under
* `subpage_types` limits which page types can be created under this type
By default, any page type can be created under any page type and it is not necessary to set these attributes if that’s the desired behaviour.
Setting `parent_page_types` to an empty list is a good way of preventing a particular page type from being created in the editor interface.
### Page descriptions
With every Wagtail Page you are able to add a helpful description text, similar to a `help_text` model attribute. By adding `page_description` to your Page model you’ll be adding a short description that can be seen when you create a new page, edit an existing page or when you’re prompted to select a child page type.
```
class LandingPage(Page):
page_description = "Use this page for converting users"
```
### Page URLs
The most common method of retrieving page URLs is by using the `{% pageurl %}` template tag. Since it’s called from a template, `pageurl` automatically includes the optimizations mentioned below. For more information, see [pageurl](writing_templates#pageurl-tag).
Page models also include several low-level methods for overriding or accessing page URLs.
#### Customising URL patterns for a page model
The `Page.get_url_parts(request)` method will not typically be called directly, but may be overridden to define custom URL routing for a given page model. It should return a tuple of `(site_id, root_url, page_path)`, which are used by `get_url` and `get_full_url` (see below) to construct the given type of page URL.
When overriding `get_url_parts()`, you should accept `*args, **kwargs`:
```
def get_url_parts(self, *args, **kwargs):
```
and pass those through at the point where you are calling `get_url_parts` on `super` (if applicable), for example:
```
super().get_url_parts(*args, **kwargs)
```
While you could pass only the `request` keyword argument, passing all arguments as-is ensures compatibility with any future changes to these method signatures.
For more information, please see [`wagtail.models.Page.get_url_parts()`](../reference/pages/model_reference#wagtail.models.Page.get_url_parts "wagtail.models.Page.get_url_parts").
#### Obtaining URLs for page instances
The `Page.get_url(request)` method can be called whenever a page URL is needed. It defaults to returning local URLs (not including the protocol or domain) if it determines that the page is on the current site (via the hostname in `request`); otherwise, a full URL including the protocol and domain is returned. Whenever possible, the optional `request` argument should be included to enable per-request caching of site-level URL information and facilitate the generation of local URLs.
A common use case for `get_url(request)` is in any custom template tag your project may include for generating navigation menus. When writing such a custom template tag, ensure that it includes `takes_context=True` and use `context.get('request')` to safely pass the request or `None` if no request exists in the context.
For more information, please see [`wagtail.models.Page.get_url()`](../reference/pages/model_reference#wagtail.models.Page.get_url "wagtail.models.Page.get_url").
In the event a full URL (including the protocol and domain) is needed, `Page.get_full_url(request)` can be used instead. Whenever possible, the optional `request` argument should be included to enable per-request caching of site-level URL information.
For more information, please see [`wagtail.models.Page.get_full_url()`](../reference/pages/model_reference#wagtail.models.Page.get_full_url "wagtail.models.Page.get_full_url").
Template rendering
------------------
Each page model can be given an HTML template which is rendered when a user browses to a page on the site frontend. This is the simplest and most common way to get Wagtail content to end users (but not the only way).
### Adding a template for a page model
Wagtail automatically chooses a name for the template based on the app label and model class name.
Format: `<app_label>/<model_name (snake cased)>.html`
For example, the template for the above blog page will be: `blog/blog_page.html`
You just need to create a template in a location where it can be accessed with this name.
### Template context
Wagtail renders templates with the `page` variable bound to the page instance being rendered. Use this to access the content of the page. For example, to get the title of the current page, use `{{ page.title }}`. All variables provided by [context processors](https://docs.djangoproject.com/en/stable/ref/templates/api/#subclassing-context-requestcontext) are also available.
#### Customising template context
All pages have a `get_context` method that is called whenever the template is rendered and returns a dictionary of variables to bind into the template.
To add more variables to the template context, you can override this method:
```
class BlogIndexPage(Page):
...
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
# Add extra variables and return the updated context
context['blog_entries'] = BlogPage.objects.child_of(self).live()
return context
```
The variables can then be used in the template:
```
{{ page.title }}
{% for entry in blog_entries %}
{{ entry.title }}
{% endfor %}
```
### Changing the template
Set the `template` attribute on the class to use a different template file:
```
class BlogPage(Page):
...
template = 'other_template.html'
```
#### Dynamically choosing the template
The template can be changed on a per-instance basis by defining a `get_template` method on the page class. This method is called every time the page is rendered:
```
class BlogPage(Page):
...
use_other_template = models.BooleanField()
def get_template(self, request, *args, **kwargs):
if self.use_other_template:
return 'blog/other_blog_page.html'
return 'blog/blog_page.html'
```
In this example, pages that have the `use_other_template` boolean field set will use the `blog/other_blog_page.html` template. All other pages will use the default `blog/blog_page.html`.
#### Ajax Templates
If you want to add AJAX functionality to a page, such as a paginated listing that updates in-place on the page rather than triggering a full page reload, you can set the `ajax_template` attribute to specify an alternative template to be used when the page is requested via an AJAX call (as indicated by the `X-Requested-With: XMLHttpRequest` HTTP header):
```
class BlogPage(Page):
...
ajax_template = 'other_template_fragment.html'
template = 'other_template.html'
```
### More control over page rendering
All page classes have a `serve()` method that internally calls the `get_context` and `get_template` methods and renders the template. This method is similar to a Django view function, taking a Django `Request` object and returning a Django `Response` object.
This method can also be overridden for complete control over page rendering.
For example, here’s a way to make a page respond with a JSON representation of itself:
```
from django.http import JsonResponse
class BlogPage(Page):
...
def serve(self, request):
return JsonResponse({
'title': self.title,
'body': self.body,
'date': self.date,
# Resizes the image to 300px width and gets a URL to it
'feed_image': self.feed_image.get_rendition('width-300').url,
})
```
Inline models
-------------
Wagtail can nest the content of other models within the page. This is useful for creating repeated fields, such as related links or items to display in a carousel. Inline model content is also versioned with the rest of the page content.
Each inline model requires the following:
* It must inherit from [`wagtail.models.Orderable`](../reference/pages/model_reference#wagtail.models.Orderable "wagtail.models.Orderable")
* It must have a `ParentalKey` to the parent model
Note
The model inlining feature is provided by [django-modelcluster](https://github.com/wagtail/django-modelcluster) and the `ParentalKey` field type must be imported from there:
```
from modelcluster.fields import ParentalKey
```
`ParentalKey` is a subclass of Django’s `ForeignKey`, and takes the same arguments.
For example, the following inline model can be used to add related links (a list of name, url pairs) to the `BlogPage` model:
```
from django.db import models
from modelcluster.fields import ParentalKey
from wagtail.models import Orderable
class BlogPageRelatedLink(Orderable):
page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='related_links')
name = models.CharField(max_length=255)
url = models.URLField()
panels = [
FieldPanel('name'),
FieldPanel('url'),
]
```
To add this to the admin interface, use the [`InlinePanel`](../reference/pages/panels#wagtail.admin.panels.InlinePanel "wagtail.admin.panels.InlinePanel") edit panel class:
```
content_panels = [
...
InlinePanel('related_links', label="Related links"),
]
```
The first argument must match the value of the `related_name` attribute of the `ParentalKey`.
Working with pages
------------------
Wagtail uses Django’s [multi-table inheritance](https://docs.djangoproject.com/en/3.1/topics/db/models/#multi-table-inheritance) feature to allow multiple page models to be used in the same tree.
Each page is added to both Wagtail’s built-in [`Page`](../reference/pages/model_reference#wagtail.models.Page "wagtail.models.Page") model as well as its user-defined model (such as the `BlogPage` model created earlier).
Pages can exist in Python code in two forms, an instance of `Page` or an instance of the page model.
When working with multiple page types together, you will typically use instances of Wagtail’s `Page` model, which don’t give you access to any fields specific to their type.
```
# Get all pages in the database
>>> from wagtail.models import Page
>>> Page.objects.all()
[<Page: Homepage>, <Page: About us>, <Page: Blog>, <Page: A Blog post>, <Page: Another Blog post>]
```
When working with a single page type, you can work with instances of the user-defined model. These give access to all the fields available in `Page`, along with any user-defined fields for that type.
```
# Get all blog entries in the database
>>> BlogPage.objects.all()
[<BlogPage: A Blog post>, <BlogPage: Another Blog post>]
```
You can convert a `Page` object to its more specific user-defined equivalent using the `.specific` property. This may cause an additional database lookup.
```
>>> page = Page.objects.get(title="A Blog post")
>>> page
<Page: A Blog post>
# Note: the blog post is an instance of Page so we cannot access body, date or feed_image
>>> page.specific
<BlogPage: A Blog post>
```
Tips
----
### Friendly model names
You can make your model names more friendly to users of Wagtail by using Django’s internal `Meta` class with a `verbose_name`, for example:
```
class HomePage(Page):
...
class Meta:
verbose_name = "homepage"
```
When users are given a choice of pages to create, the list of page types is generated by splitting your model names on each of their capital letters. Thus a `HomePage` model would be named “Home Page” which is a little clumsy. Defining `verbose_name` as in the example above would change this to read “Homepage”, which is slightly more conventional.
### Page QuerySet ordering
`Page`-derived models *cannot* be given a default ordering by using the standard Django approach of adding an `ordering` attribute to the internal `Meta` class.
```
class NewsItemPage(Page):
publication_date = models.DateField()
...
class Meta:
ordering = ('-publication_date', ) # will not work
```
This is because `Page` enforces ordering QuerySets by path. Instead, you must apply the ordering explicitly when constructing a QuerySet:
```
news_items = NewsItemPage.objects.live().order_by('-publication_date')
```
### Custom Page managers
You can add a custom `Manager` to your `Page` class. Any custom Managers should inherit from `wagtail.models.PageManager`:
```
from django.db import models
from wagtail.models import Page, PageManager
class EventPageManager(PageManager):
""" Custom manager for Event pages """
class EventPage(Page):
start_date = models.DateField()
objects = EventPageManager()
```
Alternately, if you only need to add extra `QuerySet` methods, you can inherit from `wagtail.models.PageQuerySet` to build a custom `Manager`:
```
from django.db import models
from django.utils import timezone
from wagtail.models import Page, PageManager, PageQuerySet
class EventPageQuerySet(PageQuerySet):
def future(self):
today = timezone.localtime(timezone.now()).date()
return self.filter(start_date__gte=today)
EventPageManager = PageManager.from_queryset(EventPageQuerySet)
class EventPage(Page):
start_date = models.DateField()
objects = EventPageManager()
```
| programming_docs |
wagtail Usage guide Usage guide
===========
* [Page models](pages)
* [Writing templates](writing_templates)
* [How to use images in templates](images)
* [Search](search/index)
+ [Indexing](search/indexing)
+ [Searching](search/searching)
+ [Backends](search/backends)
* [Snippets](snippets)
* [How to use StreamField for mixed content](streamfield)
* [Permissions](permissions)
wagtail Writing templates Writing templates
=================
Wagtail uses Django’s templating language. For developers new to Django, start with Django’s own template documentation: [Templates](https://docs.djangoproject.com/en/stable/topics/templates/ "(in Django v4.1)")
Python programmers new to Django/Wagtail may prefer more technical documentation: [The Django template language: for Python programmers](https://docs.djangoproject.com/en/stable/ref/templates/api/ "(in Django v4.1)")
You should be familiar with Django templating basics before continuing with this documentation.
Templates
---------
Every type of page or “content type” in Wagtail is defined as a “model” in a file called `models.py`. If your site has a blog, you might have a `BlogPage` model and another called `BlogPageListing`. The names of the models are up to the Django developer.
For each page model in `models.py`, Wagtail assumes an HTML template file exists of (almost) the same name. The Front End developer may need to create these templates themselves by referring to `models.py` to infer template names from the models defined therein.
To find a suitable template, Wagtail converts CamelCase names to snake\_case. So for a `BlogPage`, a template `blog_page.html` will be expected. The name of the template file can be overridden per model if necessary.
Template files are assumed to exist here:
```
name_of_project/
name_of_app/
templates/
name_of_app/
blog_page.html
models.py
```
For more information, see the Django documentation for the [application directories template loader](https://docs.djangoproject.com/en/stable/ref/templates/api/ "(in Django v4.1)").
### Page content
The data/content entered into each page is accessed/output through Django’s `{{ double-brace }}` notation. Each field from the model must be accessed by prefixing `page.`. For example the page title `{{ page.title }}` or another field `{{ page.author }}`.
A custom variable name can be configured on the page model [`wagtail.models.Page.context_object_name`](../reference/pages/model_reference#wagtail.models.Page.context_object_name "wagtail.models.Page.context_object_name"). If a custom name is defined, `page` is still available for use in shared templates.
Additionally `request.` is available and contains Django’s request object.
Static assets
-------------
Static files (such as CSS, JS and images) are typically stored here:
```
name_of_project/
name_of_app/
static/
name_of_app/
css/
js/
images/
models.py
```
(The names “css”, “js” etc aren’t important, only their position within the tree.)
Any file within the static folder should be inserted into your HTML using the `{% static %}` tag. More about it: [Static files (tag)](#static-tag).
### User images
Images uploaded to a Wagtail site by its users (as opposed to a developer’s static files, mentioned above) go into the image library and from there are added to pages via the page editor interface.
Unlike other CMSs, adding images to a page does not involve choosing a “version” of the image to use. Wagtail has no predefined image “formats” or “sizes”. Instead the template developer defines image manipulation to occur *on the fly* when the image is requested, via a special syntax within the template.
Images from the library must be requested using this syntax, but a developer’s static images can be added via conventional means like `img` tags. Only images from the library can be manipulated on the fly.
Read more about the image manipulation syntax here: [How to use images in templates](images#image-tag).
Template tags & filters
-----------------------
In addition to Django’s standard tags and filters, Wagtail provides some of its own, which can be `load`-ed [just like any other](https://docs.djangoproject.com/en/stable/howto/custom-template-tags/ "(in Django v4.1)").
Images (tag)
------------
The `image` tag inserts an XHTML-compatible `img` element into the page, setting its `src`, `width`, `height` and `alt`. See also [More control over the img tag](images#image-tag-alt).
The syntax for the `image` tag is thus:
```
{% image [image] [resize-rule] %}
```
For example:
```
{% load wagtailimages_tags %}
...
{% image page.photo width-400 %}
<!-- or a square thumbnail: -->
{% image page.photo fill-80x80 %}
```
See [How to use images in templates](images#image-tag) for full documentation.
Rich text (filter)
------------------
This filter takes a chunk of HTML content and renders it as safe HTML in the page. Importantly, it also expands internal shorthand references to embedded images, and links made in the Wagtail editor, into fully-baked HTML ready for display.
Only fields using `RichTextField` need this applied in the template.
```
{% load wagtailcore_tags %}
...
{{ page.body|richtext }}
```
### Responsive Embeds
As Wagtail does not impose any styling of its own on templates, images and embedded media will be displayed at a fixed width as determined by the HTML. Images can be made to resize to fit their container using a CSS rule such as the following:
```
.body img {
max-width: 100%;
height: auto;
}
```
where `body` is a container element in your template surrounding the images.
Making embedded media resizable is also possible, but typically requires custom style rules matching the media’s aspect ratio. To assist in this, Wagtail provides built-in support for responsive embeds, which can be enabled by setting `WAGTAILEMBEDS_RESPONSIVE_HTML = True` in your project settings. This adds a CSS class of `responsive-object` and an inline `padding-bottom` style to the embed, to be used in conjunction with the following CSS:
```
.responsive-object {
position: relative;
}
.responsive-object iframe,
.responsive-object object,
.responsive-object embed {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
```
Internal links (tag)
--------------------
### `pageurl`
Takes a Page object and returns a relative URL (`/foo/bar/`) if within the same Site as the current page, or absolute (`http://example.com/foo/bar/`) if not.
```
{% load wagtailcore_tags %}
...
<a href="{% pageurl page.get_parent %}">Back to index</a>
```
A `fallback` keyword argument can be provided - this can be a URL string, a named URL route that can be resolved with no parameters, or an object with a `get_absolute_url` method, and will be used as a substitute URL when the passed page is `None`.
```
{% load wagtailcore_tags %}
{% for publication in page.related_publications.all %}
<li>
<a href="{% pageurl publication.detail_page fallback='coming_soon' %}">
{{ publication.title }}
</a>
</li>
{% endfor %}
```
### `slugurl`
Takes any `slug` as defined in a page’s “Promote” tab and returns the URL for the matching Page. If multiple pages exist with the same slug, the page chosen is undetermined.
Like `pageurl`, this will try to provide a relative link if possible, but will default to an absolute link if the Page is on a different Site. This is most useful when creating shared page furniture, for example top level navigation or site-wide links.
```
{% load wagtailcore_tags %}
...
<a href="{% slugurl 'news' %}">News index</a>
```
Static files (tag)
------------------
Used to load anything from your static files directory. Use of this tag avoids rewriting all static paths if hosting arrangements change, as they might between development and live environments.
```
{% load static %}
...
<img src="{% static "name_of_app/myimage.jpg" %}" alt="My image"/>
```
Notice that the full path is not required - the path given here is relative to the app’s `static` directory. To avoid clashes with static files from other apps (including Wagtail itself), it’s recommended to place static files in a subdirectory of `static` with the same name as the app.
Multi-site support
------------------
### `wagtail_site`
Returns the Site object corresponding to the current request.
```
{% load wagtailcore_tags %}
{% wagtail_site as current_site %}
```
Wagtail User Bar
----------------
This tag provides a contextual flyout menu for logged-in users. The menu gives editors the ability to edit the current page or add a child page, besides the options to show the page in the Wagtail page explorer or jump to the Wagtail admin dashboard. Moderators are also given the ability to accept or reject a page being previewed as part of content moderation.
This tag may be used on standard Django views, without page object. The user bar will contain one item pointing to the admin.
We recommend putting the tag near the top of the `<body>` element so keyboard users can reach it. You should consider putting the tag after any `[skip links](https://webaim.org/techniques/skipnav/) but before the navigation and main content of your page.
```
{% load wagtailuserbar %}
...
<body>
<a id="#content">Skip to content</a>
{% wagtailuserbar %} {# This is a good place for the userbar #}
<nav>
...
</nav>
<main id="content">
...
</main>
</body>
```
By default the User Bar appears in the bottom right of the browser window, inset from the edge. If this conflicts with your design it can be moved by passing a parameter to the template tag. These examples show you how to position the userbar in each corner of the screen:
```
...
{% wagtailuserbar 'top-left' %}
{% wagtailuserbar 'top-right' %}
{% wagtailuserbar 'bottom-left' %}
{% wagtailuserbar 'bottom-right' %}
...
```
The userbar can be positioned where it works best with your design. Alternatively, you can position it with a CSS rule in your own CSS files, for example:
```
.wagtail-userbar {
top: 200px !important;
left: 10px !important;
}
```
Varying output between preview and live
---------------------------------------
Sometimes you may wish to vary the template output depending on whether the page is being previewed or viewed live. For example, if you have visitor tracking code such as Google Analytics in place on your site, it’s a good idea to leave this out when previewing, so that editor activity doesn’t appear in your analytics reports. Wagtail provides a `request.is_preview` variable to distinguish between preview and live:
```
{% if not request.is_preview %}
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
...
</script>
{% endif %}
```
If the page is being previewed, `request.preview_mode` can be used to determine the specific preview mode being used, if the page supports [multiple preview modes](../reference/pages/model_reference#wagtail.models.Page.preview_modes "wagtail.models.Page.preview_modes").
wagtail How to use images in templates How to use images in templates
==============================
The `image` tag inserts an XHTML-compatible `img` element into the page, setting its `src`, `width`, `height` and `alt`. See also [More control over the img tag](#image-tag-alt).
The syntax for the tag is thus:
```
{% image [image] [resize-rule] %}
```
**Both the image and resize rule must be passed to the template tag.**
For example:
```
{% load wagtailimages_tags %}
...
<!-- Display the image scaled to a width of 400 pixels: -->
{% image page.photo width-400 %}
<!-- Display it again, but this time as a square thumbnail: -->
{% image page.photo fill-80x80 %}
```
In the above syntax example `[image]` is the Django object referring to the image. If your page model defined a field called “photo” then `[image]` would probably be `page.photo`. The `[resize-rule]` defines how the image is to be resized when inserted into the page. Various resizing methods are supported, to cater to different use cases (for example lead images that span the whole width of the page, or thumbnails to be cropped to a fixed size).
Note that a space separates `[image]` and `[resize-rule]`, but the resize rule must not contain spaces. The width is always specified before the height. Resized images will maintain their original aspect ratio unless the `fill` rule is used, which may result in some pixels being cropped.
Available resizing methods
--------------------------
The available resizing methods are as follows:
### `max`
(takes two dimensions)
```
{% image page.photo max-1000x500 %}
```
Fit **within** the given dimensions.
The longest edge will be reduced to the matching dimension specified. For example, a portrait image of width 1000 and height 2000, treated with the `max-1000x500` rule (a landscape layout) would result in the image being shrunk so the *height* was 500 pixels and the width was 250.

Example: The image will keep its proportions but fit within the max (green line) dimensions provided.
### `min`
(takes two dimensions)
```
{% image page.photo min-500x200 %}
```
**Cover** the given dimensions.
This may result in an image slightly **larger** than the dimensions you specify. A square image of width 2000 and height 2000, treated with the `min-500x200` rule would have its height and width changed to 500, that is matching the *width* of the resize-rule, but greater than the height.

Example: The image will keep its proportions while filling at least the min (green line) dimensions provided.
### `width`
(takes one dimension)
```
{% image page.photo width-640 %}
```
Reduces the width of the image to the dimension specified.
### `height`
(takes one dimension)
```
{% image page.photo height-480 %}
```
Reduces the height of the image to the dimension specified.
### `scale`
(takes percentage)
```
{% image page.photo scale-50 %}
```
Resize the image to the percentage specified.
### `fill`
(takes two dimensions and an optional `-c` parameter)
```
{% image page.photo fill-200x200 %}
```
Resize and **crop** to fill the **exact** dimensions specified.
This can be particularly useful for websites requiring square thumbnails of arbitrary images. For example, a landscape image of width 2000 and height 1000 treated with the `fill-200x200` rule would have its height reduced to 200, then its width (ordinarily 400) cropped to 200.
This resize-rule will crop to the image’s focal point if it has been set. If not, it will crop to the centre of the image.

Example: The image is scaled and also cropped (red line) to fit as much of the image as possible within the provided dimensions.
**On images that won’t upscale**
It’s possible to request an image with `fill` dimensions that the image can’t support without upscaling. For example an image of width 400 and height 200 requested with `fill-400x400`. In this situation the *ratio of the requested fill* will be matched, but the dimension will not. So that example 400x200 image (a 2:1 ratio) could become 200x200 (a 1:1 ratio, matching the resize-rule).
**Cropping closer to the focal point**
By default, Wagtail will only crop enough to change the aspect ratio of the image to match the ratio in the resize-rule.
In some cases (for example thumbnails), it may be preferable to crop closer to the focal point, so that the subject of the image is more prominent.
You can do this by appending `-c<percentage>` at the end of the resize-rule. For example, if you would like the image to be cropped as closely as possible to its focal point, add `-c100`:
```
{% image page.photo fill-200x200-c100 %}
```
This will crop the image as much as it can, without cropping into the focal point.
If you find that `-c100` is too close, you can try `-c75` or `-c50`. Any whole number from 0 to 100 is accepted.

Example: The focal point is set off centre so the image is scaled and also cropped like fill, however the center point of the crop is positioned closer the focal point.

Example: With `-c75` set, the final crop will be closer to the focal point.
### `original`
(takes no dimensions)
```
{% image page.photo original %}
```
Renders the image at its original size.
Note
Wagtail does not allow deforming or stretching images. Image dimension ratios will always be kept. Wagtail also *does not support upscaling*. Small images forced to appear at larger sizes will “max out” at their native dimensions.
More control over the `img` tag
-------------------------------
Wagtail provides two shortcuts to give greater control over the `img` element:
### 1. Adding attributes to the {% image %} tag
Extra attributes can be specified with the syntax `attribute="value"`:
```
{% image page.photo width-400 class="foo" id="bar" %}
```
You can set a more relevant `alt` attribute this way, overriding the one automatically generated from the title of the image. The `src`, `width`, and `height` attributes can also be overridden, if necessary.
You can also add default attributes to all images (a default class or data attribute for example) - see [Adding default attributes to all images](#adding-default-attributes-to-images).
### 2. Generating the image “as foo” to access individual properties
Wagtail can assign the image data to another variable using Django’s `as` syntax:
```
{% image page.photo width-400 as tmp_photo %}
<img src="{{ tmp_photo.url }}" width="{{ tmp_photo.width }}"
height="{{ tmp_photo.height }}" alt="{{ tmp_photo.alt }}" class="my-custom-class" />
```
Note
The image property used for the `src` attribute is `image.url`, not `image.src`.
This syntax exposes the underlying image Rendition (`tmp_photo`) to the developer. A “Rendition” contains the information specific to the way you’ve requested to format the image using the resize-rule, dimensions and source URL. The following properties are available:
### `url`
URL to the resized version of the image. This may be a local URL (such as `/static/images/example.jpg`) or a full URL (such as `https://assets.example.com/images/example.jpg`), depending on how static files are configured.
### `width`
Image width after resizing.
### `height`
Image height after resizing.
### `alt`
Alternative text for the image, typically taken from the image title.
### `attrs`
A shorthand for outputting the attributes `src`, `width`, `height` and `alt` in one go:
```
<img {{ tmp_photo.attrs }} class="my-custom-class" />
```
### `full_url`
Same as `url`, but always returns a full absolute URL. This requires `WAGTAILADMIN_BASE_URL` to be set in the project settings.
This is useful for images that will be re-used outside of the current site, such as social share images:
```
<meta name="twitter:image" content="{{ tmp_photo.full_url }}">
```
If your site defines a custom image model using `AbstractImage`, any additional fields you add to an image (such as a copyright holder) are **not** included in the rendition.
Therefore, if you’d added the field `author` to your AbstractImage in the above example, you’d access it using `{{ page.photo.author }}` rather than `{{ tmp_photo.author }}`.
(Due to the links in the database between renditions and their parent image, you *could* access it as `{{ tmp_photo.image.author }}`, but that has reduced readability.)
Adding default attributes to all images
---------------------------------------
We can configure the `wagtail.images` application to specify additional attributes to add to images. This is done by setting up a custom `AppConfig` class within your project folder (i.e. the package containing the top-level settings and urls modules).
To do this, create or update your existing `apps.py` file with the following:
```
from wagtail.images.apps import WagtailImagesAppConfig
class CustomImagesAppConfig(WagtailImagesAppConfig):
default_attrs = {"decoding": "async", "loading": "lazy"}
```
Then, replace `wagtail.images` in `settings.INSTALLED_APPS` with the path to `CustomUsersAppConfig`:
```
INSTALLED_APPS = [
...,
"myapplication.apps.CustomImagesAppConfig",
# "wagtail.images",
...,
]
```
Now, images created with `{% image %}` will additionally have `decoding="async" loading="lazy"` attributes. This also goes for images added to Rich Text and `ImageBlock` blocks.
Alternative HTML tags
---------------------
The `as` keyword allows alternative HTML image tags (such as `<picture>` or `<amp-img>`) to be used. For example, to use the `<picture>` tag:
```
<picture>
{% image page.photo width-800 as wide_photo %}
<source srcset="{{ wide_photo.url }}" media="(min-width: 800px)">
{% image page.photo width-400 %}
</picture>
```
And to use the `<amp-img>` tag (based on the [Mountains example](https://amp.dev/documentation/components/amp-img/#example:-specifying-a-fallback-image) from the AMP docs):
```
{% image image width-550 format-webp as webp_image %}
{% image image width-550 format-jpeg as jpeg_image %}
<amp-img alt="{{ image.alt }}"
width="{{ webp_image.width }}"
height="{{ webp_image.height }}"
src="{{ webp_image.url }}">
<amp-img alt="{{ image.alt }}"
fallback
width="{{ jpeg_image.width }}"
height="{{ jpeg_image.height }}"
src="{{ jpeg_image.url }}"></amp-img>
</amp-img>
```
Images embedded in rich text
----------------------------
The information above relates to images defined via image-specific fields in your model. However, images can also be embedded arbitrarily in Rich Text fields by the page editor (see [Rich Text (HTML)](../advanced_topics/customisation/page_editing_interface#rich-text)).
Images embedded in Rich Text fields can’t be controlled by the template developer as easily. There are no image objects to work with, so the `{% image %}` template tag can’t be used. Instead, editors can choose from one of a number of image “Formats” at the point of inserting images into their text.
Wagtail comes with three pre-defined image formats, but more can be defined in Python by the developer. These formats are:
### `Full width`
Creates an image rendition using `width-800`, giving the ![]() tag the CSS class `full-width`.
### `Left-aligned`
Creates an image rendition using `width-500`, giving the ![]() tag the CSS class `left`.
### `Right-aligned`
Creates an image rendition using `width-500`, giving the ![]() tag the CSS class `right`.
Note
The CSS classes added to images do **not** come with any accompanying stylesheets, or inline styles. For example the `left` class will do nothing, by default. The developer is expected to add these classes to their front end CSS files, to define exactly what they want `left`, `right` or `full-width` to mean.
For more information about image formats, including creating your own, see [Image Formats in the Rich Text Editor](../advanced_topics/customisation/page_editing_interface#rich-text-image-formats).
Output image format
-------------------
Wagtail may automatically change the format of some images when they are resized:
* PNG and JPEG images don’t change format
* GIF images without animation are converted to PNGs
* BMP images are converted to PNGs
* WebP images are converted to PNGs
It is also possible to override the output format on a per-tag basis by using the `format` filter after the resize rule.
For example, to make the tag always convert the image to a JPEG, use `format-jpeg`:
```
{% image page.photo width-400 format-jpeg %}
```
You may also use `format-png` or `format-gif`.
### Lossless WebP
You can encode the image into lossless WebP format by using the `format-webp-lossless` filter:
```
{% image page.photo width-400 format-webp-lossless %}
```
Background colour
-----------------
The PNG and GIF image formats both support transparency, but if you want to convert images to JPEG format, the transparency will need to be replaced with a solid background colour.
By default, Wagtail will set the background to white. But if a white background doesn’t fit your design, you can specify a colour using the `bgcolor` filter.
This filter takes a single argument, which is a CSS 3 or 6 digit hex code representing the colour you would like to use:
```
{# Sets the image background to black #}
{% image page.photo width-400 bgcolor-000 format-jpeg %}
```
Image quality
-------------
Wagtail’s JPEG and WebP image quality settings default to 85 (which is quite high). This can be changed either globally or on a per-tag basis.
### Changing globally
Use the `WAGTAILIMAGES_JPEG_QUALITY` and `WAGTAILIMAGES_WEBP_QUALITY` settings to change the global defaults of JPEG and WebP quality:
```
# settings.py
# Make low-quality but small images
WAGTAILIMAGES_JPEG_QUALITY = 40
WAGTAILIMAGES_WEBP_QUALITY = 45
```
Note that this won’t affect any previously generated images so you may want to delete all renditions so they can regenerate with the new setting. This can be done from the Django shell:
```
# Replace this with your custom rendition model if you use one
>>> from wagtail.images.models import Rendition
>>> Rendition.objects.all().delete()
```
You can also directly use the image management command from the console for regenerating the renditions:
```
./manage.py wagtail_update_image_renditions --purge
```
You can read more about this command from [wagtail\_update\_image\_renditions](../reference/management_commands#wagtail-update-image-renditions)
### Changing per-tag
It’s also possible to have different JPEG and WebP qualities on individual tags by using `jpegquality` and `webpquality` filters. This will always override the default setting:
```
{% image page.photo_jpeg width-400 jpegquality-40 %}
{% image page.photo_webp width-400 webpquality-50 %}
```
Note that this will have no effect on PNG or GIF files. If you want all images to be low quality, you can use this filter with `format-jpeg` or `format-webp` (which forces all images to output in JPEG or WebP format):
```
{% image page.photo width-400 format-jpeg jpegquality-40 %}
{% image page.photo width-400 format-webp webpquality-50 %}
```
### Generating image renditions in Python
All of the image transformations mentioned above can also be used directly in Python code. See [Generating renditions in Python](../advanced_topics/images/renditions#image-renditions).
| programming_docs |
wagtail How to use StreamField for mixed content How to use StreamField for mixed content
========================================
StreamField provides a content editing model suitable for pages that do not follow a fixed structure – such as blog posts or news stories – where the text may be interspersed with subheadings, images, pull quotes and video. It’s also suitable for more specialised content types, such as maps and charts (or, for a programming blog, code snippets). In this model, these different content types are represented as a sequence of ‘blocks’, which can be repeated and arranged in any order.
For further background on StreamField, and why you would use it instead of a rich text field for the article body, see the blog post [Rich text fields and faster horses](https://torchbox.com/blog/rich-text-fields-and-faster-horses/).
StreamField also offers a rich API to define your own block types, ranging from simple collections of sub-blocks (such as a ‘person’ block consisting of first name, surname and photograph) to completely custom components with their own editing interface. Within the database, the StreamField content is stored as JSON, ensuring that the full informational content of the field is preserved, rather than just an HTML representation of it.
Using StreamField
-----------------
`StreamField` is a model field that can be defined within your page model like any other field:
```
from django.db import models
from wagtail.models import Page
from wagtail.fields import StreamField
from wagtail import blocks
from wagtail.admin.panels import FieldPanel
from wagtail.images.blocks import ImageChooserBlock
class BlogPage(Page):
author = models.CharField(max_length=255)
date = models.DateField("Post date")
body = StreamField([
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], use_json_field=True)
content_panels = Page.content_panels + [
FieldPanel('author'),
FieldPanel('date'),
FieldPanel('body'),
]
```
In this example, the body field of `BlogPage` is defined as a `StreamField` where authors can compose content from three different block types: headings, paragraphs, and images, which can be used and repeated in any order. The block types available to authors are defined as a list of `(name, block_type)` tuples: ‘name’ is used to identify the block type within templates, and should follow the standard Python conventions for variable names: lower-case and underscores, no spaces.
You can find the complete list of available block types in the [StreamField block reference](../reference/streamfield/blocks#streamfield-block-reference).
Note
StreamField is not a direct replacement for other field types such as RichTextField. If you need to migrate an existing field to StreamField, refer to [Migrating RichTextFields to StreamField](#streamfield-migrating-richtext).
Changed in version 3.0: The `use_json_field=True` argument was added. This indicates that the database’s native JSONField support should be used for this field, and is a temporary measure to assist in migrating StreamFields created on earlier Wagtail versions; it will become the default in a future release.
Template rendering
------------------
StreamField provides an HTML representation for the stream content as a whole, as well as for each individual block. To include this HTML into your page, use the `{% include_block %}` tag:
```
{% load wagtailcore_tags %}
...
{% include_block page.body %}
```
In the default rendering, each block of the stream is wrapped in a `<div class="block-my_block_name">` element (where `my_block_name` is the block name given in the StreamField definition). If you wish to provide your own HTML markup, you can instead iterate over the field’s value, and invoke `{% include_block %}` on each block in turn:
```
{% load wagtailcore_tags %}
...
<article>
{% for block in page.body %}
<section>{% include_block block %}</section>
{% endfor %}
</article>
```
For more control over the rendering of specific block types, each block object provides `block_type` and `value` properties:
```
{% load wagtailcore_tags %}
...
<article>
{% for block in page.body %}
{% if block.block_type == 'heading' %}
<h1>{{ block.value }}</h1>
{% else %}
<section class="block-{{ block.block_type }}">
{% include_block block %}
</section>
{% endif %}
{% endfor %}
</article>
```
Combining blocks
----------------
In addition to using the built-in block types directly within StreamField, it’s possible to construct new block types by combining sub-blocks in various ways. Examples of this could include:
* An “image with caption” block consisting of an image chooser and a text field
* A “related links” section, where an author can provide any number of links to other pages
* A slideshow block, where each slide may be an image, text or video, arranged in any order
Once a new block type has been built up in this way, you can use it anywhere where a built-in block type would be used - including using it as a component for yet another block type. For example, you could define an image gallery block where each item is an “image with caption” block.
### StructBlock
`StructBlock` allows you to group several ‘child’ blocks together to be presented as a single block. The child blocks are passed to `StructBlock` as a list of `(name, block_type)` tuples:
```
body = StreamField([
('person', blocks.StructBlock([
('first_name', blocks.CharBlock()),
('surname', blocks.CharBlock()),
('photo', ImageChooserBlock(required=False)),
('biography', blocks.RichTextBlock()),
])),
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], use_json_field=True)
```
When reading back the content of a StreamField (such as when rendering a template), the value of a StructBlock is a dict-like object with keys corresponding to the block names given in the definition:
```
<article>
{% for block in page.body %}
{% if block.block_type == 'person' %}
<div class="person">
{% image block.value.photo width-400 %}
<h2>{{ block.value.first_name }} {{ block.value.surname }}</h2>
{{ block.value.biography }}
</div>
{% else %}
(rendering for other block types)
{% endif %}
{% endfor %}
</article>
```
### Subclassing `StructBlock`
Placing a StructBlock’s list of child blocks inside a `StreamField` definition can often be hard to read, and makes it difficult for the same block to be reused in multiple places. As an alternative, `StructBlock` can be subclassed, with the child blocks defined as attributes on the subclass. The ‘person’ block in the above example could be rewritten as:
```
class PersonBlock(blocks.StructBlock):
first_name = blocks.CharBlock()
surname = blocks.CharBlock()
photo = ImageChooserBlock(required=False)
biography = blocks.RichTextBlock()
```
`PersonBlock` can then be used in a `StreamField` definition in the same way as the built-in block types:
```
body = StreamField([
('person', PersonBlock()),
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], use_json_field=True)
```
### Block icons
In the menu that content authors use to add new blocks to a StreamField, each block type has an associated icon. For StructBlock and other structural block types, a placeholder icon is used, since the purpose of these blocks is specific to your project. To set a custom icon, pass the option `icon` as either a keyword argument to `StructBlock`, or an attribute on a `Meta` class:
```
body = StreamField([
('person', blocks.StructBlock([
('first_name', blocks.CharBlock()),
('surname', blocks.CharBlock()),
('photo', ImageChooserBlock(required=False)),
('biography', blocks.RichTextBlock()),
], icon='user')),
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], use_json_field=True)
```
```
class PersonBlock(blocks.StructBlock):
first_name = blocks.CharBlock()
surname = blocks.CharBlock()
photo = ImageChooserBlock(required=False)
biography = blocks.RichTextBlock()
class Meta:
icon = 'user'
```
For a list of the recognised icon identifiers, see the [UI Styleguide](../contributing/styleguide#styleguide).
### ListBlock
`ListBlock` defines a repeating block, allowing content authors to insert as many instances of a particular block type as they like. For example, a ‘gallery’ block consisting of multiple images can be defined as follows:
```
body = StreamField([
('gallery', blocks.ListBlock(ImageChooserBlock())),
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], use_json_field=True)
```
When reading back the content of a StreamField (such as when rendering a template), the value of a ListBlock is a list of child values:
```
<article>
{% for block in page.body %}
{% if block.block_type == 'gallery' %}
<ul class="gallery">
{% for img in block.value %}
<li>{% image img width-400 %}</li>
{% endfor %}
</ul>
{% else %}
(rendering for other block types)
{% endif %}
{% endfor %}
</article>
```
### StreamBlock
`StreamBlock` defines a set of child block types that can be mixed and repeated in any sequence, via the same mechanism as StreamField itself. For example, a carousel that supports both image and video slides could be defined as follows:
```
body = StreamField([
('carousel', blocks.StreamBlock([
('image', ImageChooserBlock()),
('video', EmbedBlock()),
])),
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], use_json_field=True)
```
`StreamBlock` can also be subclassed in the same way as `StructBlock`, with the child blocks being specified as attributes on the class:
```
class CarouselBlock(blocks.StreamBlock):
image = ImageChooserBlock()
video = EmbedBlock()
class Meta:
icon = 'image'
```
A StreamBlock subclass defined in this way can also be passed to a `StreamField` definition, instead of passing a list of block types. This allows setting up a common set of block types to be used on multiple page types:
```
class CommonContentBlock(blocks.StreamBlock):
heading = blocks.CharBlock(form_classname="title")
paragraph = blocks.RichTextBlock()
image = ImageChooserBlock()
class BlogPage(Page):
body = StreamField(CommonContentBlock(), use_json_field=True)
```
When reading back the content of a StreamField, the value of a StreamBlock is a sequence of block objects with `block_type` and `value` properties, just like the top-level value of the StreamField itself.
```
<article>
{% for block in page.body %}
{% if block.block_type == 'carousel' %}
<ul class="carousel">
{% for slide in block.value %}
{% if slide.block_type == 'image' %}
<li class="image">{% image slide.value width-200 %}</li>
{% else %}
<li class="video">{% include_block slide %}</li>
{% endif %}
{% endfor %}
</ul>
{% else %}
(rendering for other block types)
{% endif %}
{% endfor %}
</article>
```
### Limiting block counts
By default, a StreamField can contain an unlimited number of blocks. The `min_num` and `max_num` options on `StreamField` or `StreamBlock` allow you to set a minimum or maximum number of blocks:
```
body = StreamField([
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], min_num=2, max_num=5, use_json_field=True)
```
Or equivalently:
```
class CommonContentBlock(blocks.StreamBlock):
heading = blocks.CharBlock(form_classname="title")
paragraph = blocks.RichTextBlock()
image = ImageChooserBlock()
class Meta:
min_num = 2
max_num = 5
```
The `block_counts` option can be used to set a minimum or maximum count for specific block types. This accepts a dict, mapping block names to a dict containing either or both of `min_num` and `max_num`. For example, to permit between 1 and 3 ‘heading’ blocks:
```
body = StreamField([
('heading', blocks.CharBlock(form_classname="title")),
('paragraph', blocks.RichTextBlock()),
('image', ImageChooserBlock()),
], block_counts={
'heading': {'min_num': 1, 'max_num': 3},
}, use_json_field=True)
```
Or equivalently:
```
class CommonContentBlock(blocks.StreamBlock):
heading = blocks.CharBlock(form_classname="title")
paragraph = blocks.RichTextBlock()
image = ImageChooserBlock()
class Meta:
block_counts = {
'heading': {'min_num': 1, 'max_num': 3},
}
```
Per-block templates
-------------------
By default, each block is rendered using simple, minimal HTML markup, or no markup at all. For example, a CharBlock value is rendered as plain text, while a ListBlock outputs its child blocks in a `<ul>` wrapper. To override this with your own custom HTML rendering, you can pass a `template` argument to the block, giving the filename of a template file to be rendered. This is particularly useful for custom block types derived from StructBlock:
```
('person', blocks.StructBlock(
[
('first_name', blocks.CharBlock()),
('surname', blocks.CharBlock()),
('photo', ImageChooserBlock(required=False)),
('biography', blocks.RichTextBlock()),
],
template='myapp/blocks/person.html',
icon='user'
))
```
Or, when defined as a subclass of StructBlock:
```
class PersonBlock(blocks.StructBlock):
first_name = blocks.CharBlock()
surname = blocks.CharBlock()
photo = ImageChooserBlock(required=False)
biography = blocks.RichTextBlock()
class Meta:
template = 'myapp/blocks/person.html'
icon = 'user'
```
Within the template, the block value is accessible as the variable `value`:
```
{% load wagtailimages_tags %}
<div class="person">
{% image value.photo width-400 %}
<h2>{{ value.first_name }} {{ value.surname }}</h2>
{{ value.biography }}
</div>
```
Since `first_name`, `surname`, `photo` and `biography` are defined as blocks in their own right, this could also be written as:
```
{% load wagtailcore_tags wagtailimages_tags %}
<div class="person">
{% image value.photo width-400 %}
<h2>{% include_block value.first_name %} {% include_block value.surname %}</h2>
{% include_block value.biography %}
</div>
```
Writing `{{ my_block }}` is roughly equivalent to `{% include_block my_block %}`, but the short form is more restrictive, as it does not pass variables from the calling template such as `request` or `page`; for this reason, it is recommended that you only use it for simple values that do not render HTML of their own. For example, if our PersonBlock used the template:
```
{% load wagtailimages_tags %}
<div class="person">
{% image value.photo width-400 %}
<h2>{{ value.first_name }} {{ value.surname }}</h2>
{% if request.user.is_authenticated %}
<a href="#">Contact this person</a>
{% endif %}
{{ value.biography }}
</div>
```
then the `request.user.is_authenticated` test would not work correctly when rendering the block through a `{{ ... }}` tag:
```
{# Incorrect: #}
{% for block in page.body %}
{% if block.block_type == 'person' %}
<div>
{{ block }}
</div>
{% endif %}
{% endfor %}
{# Correct: #}
{% for block in page.body %}
{% if block.block_type == 'person' %}
<div>
{% include_block block %}
</div>
{% endif %}
{% endfor %}
```
Like Django’s `{% include %}` tag, `{% include_block %}` also allows passing additional variables to the included template, through the syntax `{% include_block my_block with foo="bar" %}`:
```
{# In page template: #}
{% for block in page.body %}
{% if block.block_type == 'person' %}
{% include_block block with classname="important" %}
{% endif %}
{% endfor %}
{# In PersonBlock template: #}
<div class="{{ classname }}">
...
</div>
```
The syntax `{% include_block my_block with foo="bar" only %}` is also supported, to specify that no variables from the parent template other than `foo` will be passed to the child template.
As well as passing variables from the parent template, block subclasses can pass additional template variables of their own by overriding the `get_context` method:
```
import datetime
class EventBlock(blocks.StructBlock):
title = blocks.CharBlock()
date = blocks.DateBlock()
def get_context(self, value, parent_context=None):
context = super().get_context(value, parent_context=parent_context)
context['is_happening_today'] = (value['date'] == datetime.date.today())
return context
class Meta:
template = 'myapp/blocks/event.html'
```
In this example, the variable `is_happening_today` will be made available within the block template. The `parent_context` keyword argument is available when the block is rendered through an `{% include_block %}` tag, and is a dict of variables passed from the calling template.
All block types, not just `StructBlock`, support the `template` property. However, for blocks that handle basic Python data types, such as `CharBlock` and `IntegerBlock`, there are some limitations on where the template will take effect. For further details, see [About StreamField BoundBlocks and values](../advanced_topics/boundblocks_and_values#boundblocks-and-values).
Customisations
--------------
All block types implement a common API for rendering their front-end and form representations, and storing and retrieving values to and from the database. By subclassing the various block classes and overriding these methods, all kinds of customisations are possible, from modifying the layout of StructBlock form fields to implementing completely new ways of combining blocks. For further details, see [How to build custom StreamField blocks](../advanced_topics/customisation/streamfield_blocks#custom-streamfield-blocks).
Modifying StreamField data
--------------------------
A StreamField’s value behaves as a list, and blocks can be inserted, overwritten and deleted before saving the instance back to the database. A new item can be written to the list as a tuple of *(block\_type, value)* - when read back, it will be returned as a `BoundBlock` object.
```
# Replace the first block with a new block of type 'heading'
my_page.body[0] = ('heading', "My story")
# Delete the last block
del my_page.body[-1]
# Append a rich text block to the stream
from wagtail.rich_text import RichText
my_page.body.append(('paragraph', RichText("<p>And they all lived happily ever after.</p>")))
# Save the updated data back to the database
my_page.save()
```
Retrieving blocks by name
-------------------------
New in version 4.0: The `blocks_by_name` and `first_block_by_name` methods were added.
StreamField values provide a `blocks_by_name` method for retrieving all blocks of a given name:
```
my_page.body.blocks_by_name('heading') # returns a list of 'heading' blocks
```
Calling `blocks_by_name` with no arguments returns a `dict`-like object, mapping block names to the list of blocks of that name. This is particularly useful in template code, where passing arguments isn’t possible:
```
<h2>Table of contents</h2>
<ol>
{% for heading_block in page.body.blocks_by_name.heading %}
<li>{{ heading_block.value }}</li>
{% endfor %}
</ol>
```
The `first_block_by_name` method returns the first block of the given name in the stream, or `None` if no matching block is found:
```
hero_image = my_page.body.first_block_by_name('image')
```
`first_block_by_name` can also be called without arguments to return a `dict`-like mapping:
```
<div class="hero-image">{{ page.body.first_block_by_name.image }}</div>
```
Migrating RichTextFields to StreamField
---------------------------------------
If you change an existing RichTextField to a StreamField, the database migration will complete with no errors, since both fields use a text column within the database. However, StreamField uses a JSON representation for its data, so the existing text requires an extra conversion step in order to become accessible again. For this to work, the StreamField needs to include a RichTextBlock as one of the available block types. Create the migration as normal using `./manage.py makemigrations`, then edit it as follows (in this example, the ‘body’ field of the `demo.BlogPage` model is being converted to a StreamField with a RichTextBlock named `rich_text`):
Note
This migration cannot be used if the StreamField has the `use_json_field` argument set to `True`. To migrate, set the `use_json_field` argument to `False` first, migrate the data, then set it back to `True`.
```
# -*- coding: utf-8 -*-
from django.db import models, migrations
from wagtail.rich_text import RichText
def convert_to_streamfield(apps, schema_editor):
BlogPage = apps.get_model("demo", "BlogPage")
for page in BlogPage.objects.all():
if page.body.raw_text and not page.body:
page.body = [('rich_text', RichText(page.body.raw_text))]
page.save()
def convert_to_richtext(apps, schema_editor):
BlogPage = apps.get_model("demo", "BlogPage")
for page in BlogPage.objects.all():
if page.body.raw_text is None:
raw_text = ''.join([
child.value.source for child in page.body
if child.block_type == 'rich_text'
])
page.body = raw_text
page.save()
class Migration(migrations.Migration):
dependencies = [
# leave the dependency line from the generated migration intact!
('demo', '0001_initial'),
]
operations = [
# leave the generated AlterField intact!
migrations.AlterField(
model_name='BlogPage',
name='body',
field=wagtail.fields.StreamField([('rich_text', wagtail.blocks.RichTextBlock())]),
),
migrations.RunPython(
convert_to_streamfield,
convert_to_richtext,
),
]
```
Note that the above migration will work on published Page objects only. If you also need to migrate draft pages and page revisions, then edit the migration as in the following example instead:
```
# -*- coding: utf-8 -*-
import json
from django.core.serializers.json import DjangoJSONEncoder
from django.db import migrations, models
from wagtail.rich_text import RichText
def page_to_streamfield(page):
changed = False
if page.body.raw_text and not page.body:
page.body = [('rich_text', {'rich_text': RichText(page.body.raw_text)})]
changed = True
return page, changed
def pagerevision_to_streamfield(revision_data):
changed = False
body = revision_data.get('body')
if body:
try:
json.loads(body)
except ValueError:
revision_data['body'] = json.dumps(
[{
"value": {"rich_text": body},
"type": "rich_text"
}],
cls=DjangoJSONEncoder)
changed = True
else:
# It's already valid JSON. Leave it.
pass
return revision_data, changed
def page_to_richtext(page):
changed = False
if page.body.raw_text is None:
raw_text = ''.join([
child.value['rich_text'].source for child in page.body
if child.block_type == 'rich_text'
])
page.body = raw_text
changed = True
return page, changed
def pagerevision_to_richtext(revision_data):
changed = False
body = revision_data.get('body', 'definitely non-JSON string')
if body:
try:
body_data = json.loads(body)
except ValueError:
# It's not apparently a StreamField. Leave it.
pass
else:
raw_text = ''.join([
child['value']['rich_text'] for child in body_data
if child['type'] == 'rich_text'
])
revision_data['body'] = raw_text
changed = True
return revision_data, changed
def convert(apps, schema_editor, page_converter, pagerevision_converter):
BlogPage = apps.get_model("demo", "BlogPage")
for page in BlogPage.objects.all():
page, changed = page_converter(page)
if changed:
page.save()
for revision in page.revisions.all():
revision_data = revision.content
revision_data, changed = pagerevision_converter(revision_data)
if changed:
revision.content = revision_data
revision.save()
def convert_to_streamfield(apps, schema_editor):
return convert(apps, schema_editor, page_to_streamfield, pagerevision_to_streamfield)
def convert_to_richtext(apps, schema_editor):
return convert(apps, schema_editor, page_to_richtext, pagerevision_to_richtext)
class Migration(migrations.Migration):
dependencies = [
# leave the dependency line from the generated migration intact!
('demo', '0001_initial'),
]
operations = [
# leave the generated AlterField intact!
migrations.AlterField(
model_name='BlogPage',
name='body',
field=wagtail.fields.StreamField([('rich_text', wagtail.blocks.RichTextBlock())]),
),
migrations.RunPython(
convert_to_streamfield,
convert_to_richtext,
),
]
```
| programming_docs |
wagtail Snippets Snippets
========
Snippets are pieces of content which do not necessitate a full webpage to render. They could be used for making secondary content, such as headers, footers, and sidebars, editable in the Wagtail admin. Snippets are Django models which do not inherit the [`Page`](../reference/pages/model_reference#wagtail.models.Page "wagtail.models.Page") class and are thus not organised into the Wagtail tree. However, they can still be made editable by assigning panels and identifying the model as a snippet with the `register_snippet` class decorator.
Snippets lack many of the features of pages, such as being orderable in the Wagtail admin or having a defined URL. Decide carefully if the content type you would want to build into a snippet might be more suited to a page.
Snippet models
--------------
Here’s an example snippet model:
```
from django.db import models
from wagtail.admin.panels import FieldPanel
from wagtail.snippets.models import register_snippet
# ...
@register_snippet
class Advert(models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
panels = [
FieldPanel('url'),
FieldPanel('text'),
]
def __str__(self):
return self.text
```
The `Advert` model uses the basic Django model class and defines two properties: text and URL. The editing interface is very close to that provided for `Page`-derived models, with fields assigned in the `panels` property. Snippets do not use multiple tabs of fields, nor do they provide the “save as draft” or “submit for moderation” features.
`@register_snippet` tells Wagtail to treat the model as a snippet. The `panels` list defines the fields to show on the snippet editing page. It’s also important to provide a string representation of the class through `def __str__(self):` so that the snippet objects make sense when listed in the Wagtail admin.
Including snippets in template tags
-----------------------------------
The simplest way to make your snippets available to templates is with a template tag. This is mostly done with vanilla Django, so perhaps reviewing Django’s documentation for [custom template tags](https://docs.djangoproject.com/en/stable/howto/custom-template-tags/ "(in Django v4.1)") will be more helpful. We’ll go over the basics, though, and point out any considerations to make for Wagtail.
First, add a new python file to a `templatetags` folder within your app - for example, `myproject/demo/templatetags/demo_tags.py`. We’ll need to load some Django modules and our app’s models, and ready the `register` decorator:
```
from django import template
from demo.models import Advert
register = template.Library()
# ...
# Advert snippets
@register.inclusion_tag('demo/tags/adverts.html', takes_context=True)
def adverts(context):
return {
'adverts': Advert.objects.all(),
'request': context['request'],
}
```
`@register.inclusion_tag()` takes two variables: a template and a boolean on whether that template should be passed a request context. It’s a good idea to include request contexts in your custom template tags, since some Wagtail-specific template tags like `pageurl` need the context to work properly. The template tag function could take arguments and filter the adverts to return a specific instance of the model, but for brevity we’ll just use `Advert.objects.all()`.
Here’s what’s in the template used by this template tag:
```
{% for advert in adverts %}
<p>
<a href="{{ advert.url }}">
{{ advert.text }}
</a>
</p>
{% endfor %}
```
Then, in your own page templates, you can include your snippet template tag with:
```
{% load wagtailcore_tags demo_tags %}
...
{% block content %}
...
{% adverts %}
{% endblock %}
```
Binding pages to snippets
-------------------------
In the above example, the list of adverts is a fixed list that is displayed via the custom template tag independent of any other content on the page. This might be what you want for a common panel in a sidebar, but, in another scenario, you might wish to display just one specific instance of a snippet on a particular page. This can be accomplished by defining a foreign key to the snippet model within your page model and adding a [`FieldPanel`](../reference/pages/panels#wagtail.admin.panels.FieldPanel "wagtail.admin.panels.FieldPanel") to the page’s `content_panels` list. For example, if you wanted to display a specific advert on a `BookPage` instance:
```
# ...
class BookPage(Page):
advert = models.ForeignKey(
'demo.Advert',
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name='+'
)
content_panels = Page.content_panels + [
FieldPanel('advert'),
# ...
]
```
The snippet could then be accessed within your template as `page.advert`.
To attach multiple adverts to a page, the `FieldPanel` can be placed on an inline child object of `BookPage` rather than on `BookPage` itself. Here, this child model is named `BookPageAdvertPlacement` (so called because there is one such object for each time that an advert is placed on a BookPage):
```
from django.db import models
from wagtail.models import Page, Orderable
from modelcluster.fields import ParentalKey
# ...
class BookPageAdvertPlacement(Orderable, models.Model):
page = ParentalKey('demo.BookPage', on_delete=models.CASCADE, related_name='advert_placements')
advert = models.ForeignKey('demo.Advert', on_delete=models.CASCADE, related_name='+')
class Meta(Orderable.Meta):
verbose_name = "advert placement"
verbose_name_plural = "advert placements"
panels = [
FieldPanel('advert'),
]
def __str__(self):
return self.page.title + " -> " + self.advert.text
class BookPage(Page):
# ...
content_panels = Page.content_panels + [
InlinePanel('advert_placements', label="Adverts"),
# ...
]
```
These child objects are now accessible through the page’s `advert_placements` property, and from there we can access the linked `Advert` snippet as `advert`. In the template for `BookPage`, we could include the following:
```
{% for advert_placement in page.advert_placements.all %}
<p>
<a href="{{ advert_placement.advert.url }}">
{{ advert_placement.advert.text }}
</a>
</p>
{% endfor %}
```
Making snippets previewable
---------------------------
New in version 4.0: The `PreviewableMixin` class was introduced.
If a snippet model inherits from [`PreviewableMixin`](../reference/pages/model_reference#wagtail.models.PreviewableMixin "wagtail.models.PreviewableMixin"), Wagtail will automatically add a live preview panel in the editor. In addition to inheriting the mixin, the model must also override [`get_preview_template()`](../reference/pages/model_reference#wagtail.models.PreviewableMixin.get_preview_template "wagtail.models.PreviewableMixin.get_preview_template") or [`serve_preview()`](../reference/pages/model_reference#wagtail.models.PreviewableMixin.serve_preview "wagtail.models.PreviewableMixin.serve_preview"). For example, the `Advert` snippet could be made previewable as follows:
```
# ...
from wagtail.models import PreviewableMixin
# ...
@register_snippet
class Advert(PreviewableMixin, models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
panels = [
FieldPanel('url'),
FieldPanel('text'),
]
def get_preview_template(self, request, mode_name):
return "demo/previews/advert.html"
```
With the following `demo/previews/advert.html` template:
```
<!DOCTYPE html>
<html>
<head>
<title>{{ object.text }}</title>
</head>
<body>
<a href="{{ object.url }}">{{ object.text }}</a>
</body>
</html>
```
The variables available in the default context are `request` (a fake [`HttpRequest`](https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.HttpRequest "(in Django v4.1)") object) and `object` (the snippet instance). To customise the context, you can override the [`get_preview_context()`](../reference/pages/model_reference#wagtail.models.PreviewableMixin.get_preview_context "wagtail.models.PreviewableMixin.get_preview_context") method.
By default, the `serve_preview` method returns a [`TemplateResponse`](https://docs.djangoproject.com/en/stable/ref/template-response/#django.template.response.TemplateResponse "(in Django v4.1)") that is rendered using the request object, the template returned by `get_preview_template`, and the context object returned by `get_preview_context`. You can override the `serve_preview` method to customise the rendering and/or routing logic.
Similar to pages, you can define multiple preview modes by overriding the [`preview_modes`](../reference/pages/model_reference#wagtail.models.PreviewableMixin.preview_modes "wagtail.models.PreviewableMixin.preview_modes") property. For example, the following `Advert` snippet has two preview modes:
```
# ...
from wagtail.models import PreviewableMixin
# ...
@register_snippet
class Advert(PreviewableMixin, models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
panels = [
FieldPanel('url'),
FieldPanel('text'),
]
@property
def preview_modes(self):
return PreviewableMixin.DEFAULT_PREVIEW_MODES + [("alt", "Alternate")]
def get_preview_template(self, request, mode_name):
templates = {
"": "demo/previews/advert.html", # Default preview mode
"alt": "demo/previews/advert_alt.html", # Alternate preview mode
}
return templates.get(mode_name, templates[""])
def get_preview_context(self, request, mode_name):
context = super().get_preview_context(request, mode_name)
if mode_name == "alt":
context["extra_context"] = "Alternate preview mode"
return context
```
Making snippets searchable
--------------------------
If a snippet model inherits from `wagtail.search.index.Indexed`, as described in [Indexing custom models](search/indexing#wagtailsearch-indexing-models), Wagtail will automatically add a search box to the chooser interface for that snippet type. For example, the `Advert` snippet could be made searchable as follows:
```
# ...
from wagtail.search import index
# ...
@register_snippet
class Advert(index.Indexed, models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
panels = [
FieldPanel('url'),
FieldPanel('text'),
]
search_fields = [
index.SearchField('text', partial_match=True),
]
```
Saving revisions of snippets
----------------------------
New in version 4.0: The `RevisionMixin` class was introduced.
If a snippet model inherits from [`RevisionMixin`](../reference/pages/model_reference#wagtail.models.RevisionMixin "wagtail.models.RevisionMixin"), Wagtail will automatically save revisions when you save any changes in the snippets admin. In addition to inheriting the mixin, it is recommended to define a [`GenericRelation`](https://docs.djangoproject.com/en/stable/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericRelation "(in Django v4.1)") to the [`Revision`](../reference/pages/model_reference#wagtail.models.Revision "wagtail.models.Revision") model and override the [`revisions`](../reference/pages/model_reference#wagtail.models.RevisionMixin.revisions "wagtail.models.RevisionMixin.revisions") property to return the `GenericRelation`. For example, the `Advert` snippet could be made revisable as follows:
```
# ...
from django.contrib.contenttypes.fields import GenericRelation
from wagtail.models import RevisionMixin
# ...
@register_snippet
class Advert(RevisionMixin, models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
_revisions = GenericRelation("wagtailcore.Revision", related_query_name="advert")
panels = [
FieldPanel('url'),
FieldPanel('text'),
]
@property
def revisions(self):
return self._revisions
```
The `RevisionMixin` includes a `latest_revision` field that needs to be added to your database table. Make sure to run the `makemigrations` and `migrate` management commands after making the above changes to apply the changes to your database.
With the `RevisionMixin` applied, any changes made from the snippets admin will create an instance of the `Revision` model that contains the state of the snippet instance. The revision instance is attached to the [audit log](../extending/audit_log#audit-log) entry of the edit action, allowing you to revert to a previous revision or compare the changes between revisions from the snippet history page.
You can also save revisions programmatically by calling the [`save_revision()`](../reference/pages/model_reference#wagtail.models.RevisionMixin.save_revision "wagtail.models.RevisionMixin.save_revision") method. After applying the mixin, it is recommended to call this method (or save the snippet in the admin) at least once for each instance of the snippet that already exists (if any), so that the `latest_revision` field is populated in the database table.
Saving draft changes of snippets
--------------------------------
New in version 4.0: The `DraftStateMixin` class was introduced.
New in version 4.1: Support for scheduled publishing via `PublishingPanel` was introduced.
If a snippet model inherits from [`DraftStateMixin`](../reference/pages/model_reference#wagtail.models.DraftStateMixin "wagtail.models.DraftStateMixin"), Wagtail will automatically add a live/draft status column to the listing view, change the “Save” action menu to “Save draft”, and add a new “Publish” action menu in the editor. Any changes you save in the snippets admin will be saved as revisions and will not be reflected to the “live” snippet instance until you publish the changes.
Wagtail will also allow you to set publishing schedules for instances of the model if there is a `PublishingPanel` in the model’s panels definition.
For example, the `Advert` snippet could save draft changes and publishing schedules by defining it as follows:
```
# ...
from django.contrib.contenttypes.fields import GenericRelation
from wagtail.admin.panels import PublishingPanel
from wagtail.models import DraftStateMixin, RevisionMixin
# ...
@register_snippet
class Advert(DraftStateMixin, RevisionMixin, models.Model):
url = models.URLField(null=True, blank=True)
text = models.CharField(max_length=255)
_revisions = GenericRelation("wagtailcore.Revision", related_query_name="advert")
panels = [
FieldPanel('url'),
FieldPanel('text'),
PublishingPanel(),
]
@property
def revisions(self):
return self._revisions
```
The `DraftStateMixin` includes additional fields that need to be added to your database table. Make sure to run the `makemigrations` and `migrate` management commands after making the above changes to apply the changes to your database.
You can publish revisions programmatically by calling [`instance.publish(revision)`](../reference/pages/model_reference#wagtail.models.DraftStateMixin.publish "wagtail.models.DraftStateMixin.publish") or by calling [`revision.publish()`](../reference/pages/model_reference#wagtail.models.Revision.publish "wagtail.models.Revision.publish"). After applying the mixin, it is recommended to publish at least one revision for each instance of the snippet that already exists (if any), so that the `latest_revision` and `live_revision` fields are populated in the database table.
If you use the scheduled publishing feature, make sure that you run the [`publish_scheduled`](../reference/management_commands#publish-scheduled) management command periodically. For more details, see [Scheduled Publishing](../reference/pages/theory#scheduled-publishing).
Warning
Wagtail does not yet have a mechanism to prevent editors from including unpublished (“draft”) snippets in pages. When including a `DraftStateMixin`-enabled snippet in pages, make sure that you add necessary checks to handle how a draft snippet should be rendered (e.g. by checking its `live` field). We are planning to improve this in the future.
Tagging snippets
----------------
Adding tags to snippets is very similar to adding tags to pages. The only difference is that `taggit.manager.TaggableManager` should be used in the place of `ClusterTaggableManager`.
```
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
from taggit.models import TaggedItemBase
from taggit.managers import TaggableManager
class AdvertTag(TaggedItemBase):
content_object = ParentalKey('demo.Advert', on_delete=models.CASCADE, related_name='tagged_items')
@register_snippet
class Advert(ClusterableModel):
# ...
tags = TaggableManager(through=AdvertTag, blank=True)
panels = [
# ...
FieldPanel('tags'),
]
```
The [documentation on tagging pages](../reference/pages/model_recipes#tagging) has more information on how to use tags in views.
Customising snippets admin views
--------------------------------
You can customise the admin views for snippets by specifying a custom subclass of [`SnippetViewSet`](../reference/viewsets#wagtail.snippets.views.snippets.SnippetViewSet "wagtail.snippets.views.snippets.SnippetViewSet") to `register_snippet`.
This can be done by removing the `@register_snippet` decorator on your model class and calling `register_snippet` (as a function, not a decorator) in your `wagtail_hooks.py` file instead as follows:
```
register_snippet(MyModel, viewset=MyModelViewSet)
```
For example, with the following `Member` model and a `MemberFilterSet` class:
```
# models.py
from django.db import models
from wagtail.admin.filters import WagtailFilterSet
class Member(models.Model):
class ShirtSize(models.TextChoices):
SMALL = "S", "Small"
MEDIUM = "M", "Medium"
LARGE = "L", "Large"
EXTRA_LARGE = "XL", "Extra Large"
name = models.CharField(max_length=255)
shirt_size = models.CharField(max_length=5, choices=ShirtSize.choices, default=ShirtSize.MEDIUM)
def get_shirt_size_display(self):
return self.ShirtSize(self.shirt_size).label
get_shirt_size_display.admin_order_field = "shirt_size"
get_shirt_size_display.short_description = "Size description"
class MemberFilterSet(WagtailFilterSet):
class Meta:
model = Member
fields = ["shirt_size"]
```
You can define a [`list_display`](../reference/viewsets#wagtail.snippets.views.snippets.SnippetViewSet.list_display "wagtail.snippets.views.snippets.SnippetViewSet.list_display") attribute to specify the columns shown on the listing view. You can also add the ability to filter the listing view by defining a [`filterset_class`](../reference/viewsets#wagtail.snippets.views.snippets.SnippetViewSet.filterset_class "wagtail.snippets.views.snippets.SnippetViewSet.filterset_class") attribute on a subclass of `SnippetViewSet`. For example:
```
# views.py
from wagtail.admin.ui.tables import UpdatedAtColumn
from wagtail.snippets.views.snippets import SnippetViewSet
from myapp.models import MemberFilterSet
class MemberViewSet(SnippetViewSet):
list_display = ["name", "shirt_size", "get_shirt_size_display", UpdatedAtColumn()]
filterset_class = MemberFilterSet
```
Then, pass the viewset to the `register_snippet` call.
```
# wagtail_hooks.py
from wagtail.snippets.models import register_snippet
from myapp.models import Member
from myapp.views import MemberViewSet
register_snippet(Member, viewset=MemberViewSet)
```
The `viewset` parameter of `register_snippet` also accepts a dotted module path to the subclass, e.g. `"myapp.views.MemberViewSet"`.
Various additional attributes are available to customise the viewset - see [`SnippetViewSet`](../reference/viewsets#wagtail.snippets.views.snippets.SnippetViewSet "wagtail.snippets.views.snippets.SnippetViewSet").
| programming_docs |
wagtail Permissions Permissions
===========
Wagtail adapts and extends [the Django permission system](https://docs.djangoproject.com/en/stable/topics/auth/default/#topic-authorization) to cater for the needs of website content creation, such as moderation workflows, and multiple teams working on different areas of a site (or multiple sites within the same Wagtail installation). Permissions can be configured through the ‘Groups’ area of the Wagtail admin interface, under ‘Settings’.
Page permissions
----------------
Permissions can be attached at any point in the page tree, and propagate down the tree. For example, if a site had the page tree:
```
MegaCorp/
About us
Offices/
UK
France
Germany
```
then a group with ‘edit’ permissions on the ‘Offices’ page would automatically receive the ability to edit the ‘UK’, ‘France’ and ‘Germany’ pages. Permissions can be set globally for the entire tree by assigning them on the ‘root’ page - since all pages must exist underneath the root node, and the root cannot be deleted, this permission will cover all pages that exist now and in future.
Whenever a user creates a page through the Wagtail admin, that user is designated as the owner of that page. Any user with ‘add’ permission has the ability to edit pages they own, as well as adding new ones. This is in recognition of the fact that creating pages is typically an iterative process involving creating a number of draft versions - giving a user the ability to create a draft but not letting them subsequently edit it would not be very useful. Ability to edit a page also implies the ability to delete it; unlike Django’s standard permission model, there is no distinct ‘delete’ permission.
The full set of available permission types is as follows:
* **Add** - grants the ability to create new subpages underneath this page (provided the page model permits this - see [Parent page / subpage type rules](pages#page-type-business-rules)), and to edit and delete pages owned by the current user. Published pages cannot be deleted unless the user also has ‘publish’ permission.
* **Edit** - grants the ability to edit and delete this page, and any pages underneath it, regardless of ownership. A user with only ‘edit’ permission may not create new pages, only edit existing ones. Published pages cannot be deleted unless the user also has ‘publish’ permission.
* **Publish** - grants the ability to publish and unpublish this page and/or its children. A user without publish permission cannot directly make changes that are visible to visitors of the website; instead, they must submit their changes for moderation. Publish permission is independent of edit permission; a user with only publish permission will not be able to make any edits of their own.
* **Bulk delete** - allows a user to delete pages that have descendants, in a single operation. Without this permission, a user has to delete the descendant pages individually before deleting the parent. This is a safeguard against accidental deletion. This permission must be used in conjunction with ‘add’ / ‘edit’ permission, as it does not provide any deletion rights of its own; it only provides a ‘shortcut’ for the permissions the user has already. For example, a user with just ‘add’ and ‘bulk delete’ permissions will only be able to bulk-delete if all the affected pages are owned by that user, and are unpublished.
* **Lock** - grants the ability to lock or unlock this page (and any pages underneath it) for editing, preventing users from making any further edits to it.
Drafts can be viewed only if the user has either Edit or Publish permission.
Image / document permissions
----------------------------
The permission rules for images and documents work on a similar basis to pages. Images and documents are considered to be ‘owned’ by the user who uploaded them; a user with ‘add’ permission also has the ability to edit items they own; and deletion is considered equivalent to editing rather than having a specific permission type.
Access to specific sets of images and documents can be controlled by setting up *collections*. By default all images and documents belong to the ‘root’ collection, but users with appropriate permissions can create new collections the Settings -> Collections area of the admin interface. Permissions set on ‘root’ apply to all collections, so a user with ‘edit’ permission for images in the root collection can edit all images; permissions set on other collections only apply to that collection and any of its sub-collections.
The ‘choose’ permission for images and documents determines which collections are visible within the chooser interface used to select images and document links for insertion into pages (and other models, such as snippets). Typically, all users are granted choose permission for all collections, allowing them to use any uploaded image or document on pages they create, but this permission can be limited to allow creating collections that are only visible to specific groups.
Collection management permissions
---------------------------------
Permission for managing collections themselves can be attached at any point in the collection tree. The available collection management permissions are as follows:
* **Add** - grants the ability to create new collections underneath this collection.
* **Edit** - grants the ability to edit the name of the collection, change its location in the collection tree, and to change the privacy settings for documents within this collection.
* **Delete** - grants the ability to delete collections that were added below this collection. *Note:* a collection must have no subcollections under it and the collection itself must be empty before it can be deleted.
Note
Users are not allowed to move or delete the collection that is used to assign them permission to manage collections.
Displaying custom permissions in the admin
------------------------------------------
Most permissions will automatically show up in the wagtail admin Group edit form, however, you can also add them using the `register_permissions` hook (see [register\_permissions](../reference/hooks#register-permissions)).
`FieldPanel` permissions
-------------------------
Permissions can be used to restrict access to fields within the editor interface. See `permission` on [FieldPanel](../reference/pages/panels#field-panel).
wagtail Search Search
======
Wagtail provides a comprehensive and extensible search interface. In addition, it provides ways to promote search results through “Editor’s Picks”. Wagtail also collects simple statistics on queries made through the search interface.
* [Indexing](indexing)
+ [Updating the index](indexing#updating-the-index)
+ [Indexing extra fields](indexing#indexing-extra-fields)
+ [Indexing custom models](indexing#indexing-custom-models)
* [Searching](searching)
+ [Searching QuerySets](searching#searching-querysets)
+ [Changing search behaviour](searching#changing-search-behaviour)
+ [An example page search view](searching#an-example-page-search-view)
+ [Promoted search results](searching#promoted-search-results)
* [Backends](backends)
+ [`AUTO_UPDATE`](backends#auto-update)
+ [`ATOMIC_REBUILD`](backends#atomic-rebuild)
+ [`BACKEND`](backends#backend)
+ [Rolling Your Own](backends#rolling-your-own)
Indexing
--------
To make objects searchable, they must first be added to the search index. This involves configuring the models and fields that you would like to index (which is done for you for Pages, Images and Documents), and then actually inserting them into the index.
See [Updating the index](indexing#wagtailsearch-indexing-update) for information on how to keep the objects in your search index in sync with the objects in your database.
If you have created some extra fields in a subclass of `Page` or `Image`, you may want to add these new fields to the search index, so a user’s search query can match the Page or Image’s extra content. See [Indexing extra fields](indexing#wagtailsearch-indexing-fields).
If you have a custom model which doesn’t derive from `Page` or `Image` that you would like to make searchable, see [Indexing custom models](indexing#wagtailsearch-indexing-models).
Searching
---------
Wagtail provides an API for performing search queries on your models. You can also perform search queries on Django QuerySets.
See [Searching](searching#wagtailsearch-searching).
Backends
--------
Wagtail provides two backends for storing the search index and performing search queries: one using the database’s full-text search capabilities, and another using Elasticsearch. It’s also possible to roll your own search backend.
See [Backends](backends#wagtailsearch-backends).
wagtail Searching Searching
=========
Searching QuerySets
-------------------
Wagtail search is built on Django’s [QuerySet API](https://docs.djangoproject.com/en/stable/ref/models/querysets/ "(in Django v4.1)"). You should be able to search any Django QuerySet provided the model and the fields being filtered on have been added to the search index.
### Searching Pages
Wagtail provides a shortcut for searching pages: the `.search()` `QuerySet` method. You can call this on any `PageQuerySet`. For example:
```
# Search future EventPages
>>> from wagtail.models import EventPage
>>> EventPage.objects.filter(date__gt=timezone.now()).search("Hello world!")
```
All other methods of `PageQuerySet` can be used with `search()`. For example:
```
# Search all live EventPages that are under the events index
>>> EventPage.objects.live().descendant_of(events_index).search("Event")
[<EventPage: Event 1>, <EventPage: Event 2>]
```
Note
The `search()` method will convert your `QuerySet` into an instance of one of Wagtail’s `SearchResults` classes (depending on backend). This means that you must perform filtering before calling `search()`.
Before the `autocomplete()` method was introduced, the search method also did partial matching. This behaviour is will be deprecated and you should either switch to the new `autocomplete()` method or pass `partial_match=False` into the search method to opt-in to the new behaviour. The partial matching in `search()` will be completely removed in a future release.
### Autocomplete searches
Wagtail provides a separate method which performs partial matching on specific autocomplete fields. This is useful for suggesting pages to the user in real-time as they type their query.
```
>>> EventPage.objects.live().autocomplete("Eve")
[<EventPage: Event 1>, <EventPage: Event 2>]
```
Note
This method should only be used for real-time autocomplete and actual search requests should always use the `search()` method.
### Searching Images, Documents and custom models
Wagtail’s document and image models provide a `search` method on their QuerySets, just as pages do:
```
>>> from wagtail.images.models import Image
>>> Image.objects.filter(uploaded_by_user=user).search("Hello")
[<Image: Hello>, <Image: Hello world!>]
```
[Custom models](indexing#wagtailsearch-indexing-models) can be searched by using the `search` method on the search backend directly:
```
>>> from myapp.models import Book
>>> from wagtail.search.backends import get_search_backend
# Search books
>>> s = get_search_backend()
>>> s.search("Great", Book)
[<Book: Great Expectations>, <Book: The Great Gatsby>]
```
You can also pass a QuerySet into the `search` method which allows you to add filters to your search results:
```
>>> from myapp.models import Book
>>> from wagtail.search.backends import get_search_backend
# Search books
>>> s = get_search_backend()
>>> s.search("Great", Book.objects.filter(published_date__year__lt=1900))
[<Book: Great Expectations>]
```
### Specifying the fields to search
By default, Wagtail will search all fields that have been indexed using `index.SearchField`.
This can be limited to a certain set of fields by using the `fields` keyword argument:
```
# Search just the title field
>>> EventPage.objects.search("Event", fields=["title"])
[<EventPage: Event 1>, <EventPage: Event 2>]
```
### Faceted search
Wagtail supports faceted search which is a kind of filtering based on a taxonomy field (such as category or page type).
The `.facet(field_name)` method returns an `OrderedDict`. The keys are the IDs of the related objects that have been referenced by the specified field, and the values are the number of references found for each ID. The results are ordered by number of references descending.
For example, to find the most common page types in the search results:
```
>>> Page.objects.search("Test").facet("content_type_id")
# Note: The keys correspond to the ID of a ContentType object; the values are the
# number of pages returned for that type
OrderedDict([
('2', 4), # 4 pages have content_type_id == 2
('1', 2), # 2 pages have content_type_id == 1
])
```
Changing search behaviour
-------------------------
### Search operator
The search operator specifies how search should behave when the user has typed in multiple search terms. There are two possible values:
* “or” - The results must match at least one term (default for Elasticsearch)
* “and” - The results must match all terms (default for database search)
Both operators have benefits and drawbacks. The “or” operator will return many more results but will likely contain a lot of results that aren’t relevant. The “and” operator only returns results that contain all search terms, but require the user to be more precise with their query.
We recommend using the “or” operator when ordering by relevance and the “and” operator when ordering by anything else (note: the database backend doesn’t currently support ordering by relevance).
Here’s an example of using the `operator` keyword argument:
```
# The database contains a "Thing" model with the following items:
# - Hello world
# - Hello
# - World
# Search with the "or" operator
>>> s = get_search_backend()
>>> s.search("Hello world", Things, operator="or")
# All records returned as they all contain either "hello" or "world"
[<Thing: Hello World>, <Thing: Hello>, <Thing: World>]
# Search with the "and" operator
>>> s = get_search_backend()
>>> s.search("Hello world", Things, operator="and")
# Only "hello world" returned as that's the only item that contains both terms
[<Thing: Hello world>]
```
For page, image and document models, the `operator` keyword argument is also supported on the QuerySet’s `search` method:
```
>>> Page.objects.search("Hello world", operator="or")
# All pages containing either "hello" or "world" are returned
[<Page: Hello World>, <Page: Hello>, <Page: World>]
```
### Phrase searching
Phrase searching is used for finding whole sentence or phrase rather than individual terms. The terms must appear together and in the same order.
For example:
```
>>> from wagtail.search.query import Phrase
>>> Page.objects.search(Phrase("Hello world"))
[<Page: Hello World>]
>>> Page.objects.search(Phrase("World hello"))
[<Page: World Hello day>]
```
If you are looking to implement phrase queries using the double-quote syntax, see [Query string parsing](#wagtailsearch-query-string-parsing).
### Fuzzy matching
New in version 4.0.
Fuzzy matching will return documents which contain terms similar to the search term, as measured by a [Levenshtein edit distance](https://en.wikipedia.org/wiki/Levenshtein_distance).
A maximum of one edit (transposition, insertion, or removal of a character) is permitted for three to five letter terms, two edits for longer terms, and shorter terms must match exactly.
For example:
```
>>> from wagtail.search.query import Fuzzy
>>> Page.objects.search(Fuzzy("Hallo"))
[<Page: Hello World>]
```
Fuzzy matching is supported by the Elasticsearch search backend only.
### Complex search queries
Through the use of search query classes, Wagtail also supports building search queries as Python objects which can be wrapped by and combined with other search queries. The following classes are available:
`PlainText(query_string, operator=None, boost=1.0)`
This class wraps a string of separate terms. This is the same as searching without query classes.
It takes a query string, operator and boost.
For example:
```
>>> from wagtail.search.query import PlainText
>>> Page.objects.search(PlainText("Hello world"))
# Multiple plain text queries can be combined. This example will match both "hello world" and "Hello earth"
>>> Page.objects.search(PlainText("Hello") & (PlainText("world") | PlainText("earth")))
```
`Phrase(query_string)`
This class wraps a string containing a phrase. See previous section for how this works.
For example:
```
# This example will match both the phrases "hello world" and "Hello earth"
>>> Page.objects.search(Phrase("Hello world") | Phrase("Hello earth"))
```
`Boost(query, boost)`
This class boosts the score of another query.
For example:
```
>>> from wagtail.search.query import PlainText, Boost
# This example will match both the phrases "hello world" and "Hello earth" but matches for "hello world" will be ranked higher
>>> Page.objects.search(Boost(Phrase("Hello world"), 10.0) | Phrase("Hello earth"))
```
Note that this isn’t supported by the PostgreSQL or database search backends.
### Query string parsing
The previous sections show how to construct a phrase search query manually, but a lot of search engines (Wagtail admin included, try it!) support writing phrase queries by wrapping the phrase with double-quotes. In addition to phrases, you might also want to allow users to add filters into the query using the colon syntax (`hello world published:yes`).
These two features can be implemented using the `parse_query_string` utility function. This function takes a query string that a user typed and returns a query object and dictionary of filters:
For example:
```
>>> from wagtail.search.utils import parse_query_string
>>> filters, query = parse_query_string('my query string "this is a phrase" this-is-a:filter', operator='and')
>>> filters
{
'this-is-a': 'filter',
}
>>> query
And([
PlainText("my query string", operator='and'),
Phrase("this is a phrase"),
])
```
Here’s an example of how this function can be used in a search view:
```
from wagtail.search.utils import parse_query_string
def search(request):
query_string = request.GET['query']
# Parse query
filters, query = parse_query_string(query_string, operator='and')
# Published filter
# An example filter that accepts either `published:yes` or `published:no` and filters the pages accordingly
published_filter = filters.get('published')
published_filter = published_filter and published_filter.lower()
if published_filter in ['yes', 'true']:
pages = pages.filter(live=True)
elif published_filter in ['no', 'false']:
pages = pages.filter(live=False)
# Search
pages = pages.search(query)
return render(request, 'search_results.html', {'pages': pages})
```
### Custom ordering
By default, search results are ordered by relevance, if the backend supports it. To preserve the QuerySet’s existing ordering, the `order_by_relevance` keyword argument needs to be set to `False` on the `search()` method.
For example:
```
# Get a list of events ordered by date
>>> EventPage.objects.order_by('date').search("Event", order_by_relevance=False)
# Events ordered by date
[<EventPage: Easter>, <EventPage: Halloween>, <EventPage: Christmas>]
```
### Annotating results with score
For each matched result, Elasticsearch calculates a “score”, which is a number that represents how relevant the result is based on the user’s query. The results are usually ordered based on the score.
There are some cases where having access to the score is useful (such as programmatically combining two queries for different models). You can add the score to each result by calling the `.annotate_score(field)` method on the `SearchQuerySet`.
For example:
```
>>> events = EventPage.objects.search("Event").annotate_score("_score")
>>> for event in events:
... print(event.title, event._score)
...
("Easter", 2.5),
("Halloween", 1.7),
("Christmas", 1.5),
```
Note that the score itself is arbitrary and it is only useful for comparison of results for the same query.
An example page search view
---------------------------
Here’s an example Django view that could be used to add a “search” page to your site:
```
# views.py
from django.shortcuts import render
from wagtail.models import Page
from wagtail.search.models import Query
def search(request):
# Search
search_query = request.GET.get('query', None)
if search_query:
search_results = Page.objects.live().search(search_query)
# Log the query so Wagtail can suggest promoted results
Query.get(search_query).add_hit()
else:
search_results = Page.objects.none()
# Render template
return render(request, 'search_results.html', {
'search_query': search_query,
'search_results': search_results,
})
```
And here’s a template to go with it:
```
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% block title %}Search{% endblock %}
{% block content %}
<form action="{% url 'search' %}" method="get">
<input type="text" name="query" value="{{ search_query }}">
<input type="submit" value="Search">
</form>
{% if search_results %}
<ul>
{% for result in search_results %}
<li>
<h4><a href="{% pageurl result %}">{{ result }}</a></h4>
{% if result.search_description %}
{{ result.search_description|safe }}
{% endif %}
</li>
{% endfor %}
</ul>
{% elif search_query %}
No results found
{% else %}
Please type something into the search box
{% endif %}
{% endblock %}
```
Promoted search results
-----------------------
“Promoted search results” allow editors to explicitly link relevant content to search terms, so results pages can contain curated content in addition to results from the search engine.
This functionality is provided by the [`search_promotions`](../../reference/contrib/searchpromotions#module-wagtail.contrib.search_promotions "wagtail.contrib.search_promotions") contrib module.
| programming_docs |
wagtail Indexing Indexing
========
To make a model searchable, you’ll need to add it into the search index. All pages, images and documents are indexed for you, so you can start searching them right away.
If you have created some extra fields in a subclass of Page or Image, you may want to add these new fields to the search index too so that a user’s search query will match on their content. See [Indexing extra fields](#wagtailsearch-indexing-fields) for info on how to do this.
If you have a custom model that you would like to make searchable, see [Indexing custom models](#wagtailsearch-indexing-models).
Updating the index
------------------
If the search index is kept separate from the database (when using Elasticsearch for example), you need to keep them both in sync. There are two ways to do this: using the search signal handlers, or calling the `update_index` command periodically. For best speed and reliability, it’s best to use both if possible.
### Signal handlers
`wagtailsearch` provides some signal handlers which bind to the save/delete signals of all indexed models. This would automatically add and delete them from all backends you have registered in `WAGTAILSEARCH_BACKENDS`. These signal handlers are automatically registered when the `wagtail.search` app is loaded.
In some cases, you may not want your content to be automatically reindexed and instead rely on the `update_index` command for indexing. If you need to disable these signal handlers, use one of the following methods:
#### Disabling auto update signal handlers for a model
You can disable the signal handlers for an individual model by adding `search_auto_update = False` as an attribute on the model class.
#### Disabling auto update signal handlers for a search backend/whole site
You can disable the signal handlers for a whole search backend by setting the `AUTO_UPDATE` setting on the backend to `False`.
If all search backends have `AUTO_UPDATE` set to `False`, the signal handlers will be completely disabled for the whole site.
For documentation on the `AUTO_UPDATE` setting, see [AUTO\_UPDATE](backends#wagtailsearch-backends-auto-update).
### The `update_index` command
Wagtail also provides a command for rebuilding the index from scratch.
`./manage.py update_index`
It is recommended to run this command once a week and at the following times:
* whenever any pages have been created through a script (after an import, for example)
* whenever any changes have been made to models or search configuration
The search may not return any results while this command is running, so avoid running it at peak times.
Note
The `update_index` command is also aliased as `wagtail_update_index`, for use when another installed package (such as [Haystack](https://haystacksearch.org/)) provides a conflicting `update_index` command. In this case, the other package’s entry in `INSTALLED_APPS` should appear above `wagtail.search` so that its `update_index` command takes precedence over Wagtail’s.
Indexing extra fields
---------------------
Fields must be explicitly added to the `search_fields` property of your `Page`-derived model, in order for you to be able to search/filter on them. This is done by overriding `search_fields` to append a list of extra `SearchField`/`FilterField` objects to it.
### Example
This creates an `EventPage` model with two fields: `description` and `date`. `description` is indexed as a `SearchField` and `date` is indexed as a `FilterField`.
```
from wagtail.search import index
from django.utils import timezone
class EventPage(Page):
description = models.TextField()
date = models.DateField()
search_fields = Page.search_fields + [ # Inherit search_fields from Page
index.SearchField('description'),
index.FilterField('date'),
]
# Get future events which contain the string "Christmas" in the title or description
>>> EventPage.objects.filter(date__gt=timezone.now()).search("Christmas")
```
### `index.SearchField`
These are used for performing full-text searches on your models, usually for text fields.
#### Options
* **partial\_match** (`boolean`) - Setting this to true allows results to be matched on parts of words. For example, this is set on the title field by default, so a page titled `Hello World!` will be found if the user only types `Hel` into the search box.
* **boost** (`int/float`) - This allows you to set fields as being more important than others. Setting this to a high number on a field will cause pages with matches in that field to be ranked higher. By default, this is set to 2 on the Page title field and 1 on all other fields.
Note
The PostgresSQL full text search only supports [four weight levels (A, B, C, D)](https://www.postgresql.org/docs/current/textsearch-features.html). When the database search backend `wagtail.search.backends.database` is used on a PostgreSQL database, it will take all boost values in the project into consideration and group them into the four available weights.
This means that in this configuration there are effectively only four boost levels used for ranking the search results, even if more boost values have been used.
You can find out roughly which boost thresholds map to which weight in PostgresSQL by starting an new Django shell with `./manage.py shell` and inspecting `wagtail.search.backends.database.postgres.weights.BOOST_WEIGHTS`. You should see something like `[(10.0, 'A'), (7.166666666666666, 'B'), (4.333333333333333, 'C'), (1.5, 'D')]`. Boost values above each threshold will be treated with the respective weight.
* **es\_extra** (`dict`) - This field is to allow the developer to set or override any setting on the field in the Elasticsearch mapping. Use this if you want to make use of any Elasticsearch features that are not yet supported in Wagtail.
### `index.AutocompleteField`
These are used for autocomplete queries which match partial words. For example, a page titled `Hello World!` will be found if the user only types `Hel` into the search box.
This takes the exact same options as `index.SearchField` (with the exception of `partial_match`, which has no effect).
Note
Only index fields that are displayed in the search results with `index.AutocompleteField`. This allows users to see any words that were partial-matched on.
### `index.FilterField`
These are added to the search index but are not used for full-text searches. Instead, they allow you to run filters on your search results.
### `index.RelatedFields`
This allows you to index fields from related objects. It works on all types of related fields, including their reverse accessors.
For example, if we have a book that has a `ForeignKey` to its author, we can nest the author’s `name` and `date_of_birth` fields inside the book:
```
from wagtail.search import index
class Book(models.Model, index.Indexed):
...
search_fields = [
index.SearchField('title'),
index.FilterField('published_date'),
index.RelatedFields('author', [
index.SearchField('name'),
index.FilterField('date_of_birth'),
]),
]
```
This will allow you to search for books by their author’s name.
It works the other way around as well. You can index an author’s books, allowing an author to be searched for by the titles of books they’ve published:
```
from wagtail.search import index
class Author(models.Model, index.Indexed):
...
search_fields = [
index.SearchField('name'),
index.FilterField('date_of_birth'),
index.RelatedFields('books', [
index.SearchField('title'),
index.FilterField('published_date'),
]),
]
```
#### Filtering on `index.RelatedFields`
It’s not possible to filter on any `index.FilterFields` within `index.RelatedFields` using the `QuerySet` API. However, the fields are indexed, so it should be possible to use them by querying Elasticsearch manually.
Filtering on `index.RelatedFields` with the `QuerySet` API is planned for a future release of Wagtail.
### Indexing callables and other attributes
Search/filter fields do not need to be Django model fields. They can also be any method or attribute on your model class.
One use for this is indexing the `get_*_display` methods Django creates automatically for fields with choices.
```
from wagtail.search import index
class EventPage(Page):
IS_PRIVATE_CHOICES = (
(False, "Public"),
(True, "Private"),
)
is_private = models.BooleanField(choices=IS_PRIVATE_CHOICES)
search_fields = Page.search_fields + [
# Index the human-readable string for searching.
index.SearchField('get_is_private_display'),
# Index the boolean value for filtering.
index.FilterField('is_private'),
]
```
Callables also provide a way to index fields from related models. In the example from [Inline Panels and Model Clusters](../../reference/pages/panels#inline-panels), to index each BookPage by the titles of its related\_links:
```
class BookPage(Page):
# ...
def get_related_link_titles(self):
# Get list of titles and concatenate them
return '\n'.join(self.related_links.all().values_list('name', flat=True))
search_fields = Page.search_fields + [
# ...
index.SearchField('get_related_link_titles'),
]
```
Indexing custom models
----------------------
Any Django model can be indexed and searched.
To do this, inherit from `index.Indexed` and add some `search_fields` to the model.
```
from wagtail.search import index
class Book(index.Indexed, models.Model):
title = models.CharField(max_length=255)
genre = models.CharField(max_length=255, choices=GENRE_CHOICES)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
published_date = models.DateTimeField()
search_fields = [
index.SearchField('title', partial_match=True, boost=10),
index.SearchField('get_genre_display'),
index.FilterField('genre'),
index.FilterField('author'),
index.FilterField('published_date'),
]
# As this model doesn't have a search method in its QuerySet, we have to call search directly on the backend
>>> from wagtail.search.backends import get_search_backend
>>> s = get_search_backend()
# Run a search for a book by Roald Dahl
>>> roald_dahl = Author.objects.get(name="Roald Dahl")
>>> s.search("chocolate factory", Book.objects.filter(author=roald_dahl))
[<Book: Charlie and the chocolate factory>]
```
wagtail Backends Backends
========
Wagtailsearch has support for multiple backends, giving you the choice between using the database for search or an external service such as Elasticsearch.
You can configure which backend to use with the `WAGTAILSEARCH_BACKENDS` setting:
```
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.search.backends.database',
}
}
```
`AUTO_UPDATE`
-------------
By default, Wagtail will automatically keep all indexes up to date. This could impact performance when editing content, especially if your index is hosted on an external service.
The `AUTO_UPDATE` setting allows you to disable this on a per-index basis:
```
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': ...,
'AUTO_UPDATE': False,
}
}
```
If you have disabled auto update, you must run the [update\_index](../../reference/management_commands#update-index) command on a regular basis to keep the index in sync with the database.
`ATOMIC_REBUILD`
----------------
Warning
This option may not work on Elasticsearch version 5.4.x, due to [a bug in the handling of aliases](https://github.com/elastic/elasticsearch/issues/24644) - please upgrade to 5.5 or later.
By default (when using the Elasticsearch backend), when the `update_index` command is run, Wagtail deletes the index and rebuilds it from scratch. This causes the search engine to not return results until the rebuild is complete and is also risky as you can’t rollback if an error occurs.
Setting the `ATOMIC_REBUILD` setting to `True` makes Wagtail rebuild into a separate index while keep the old index active until the new one is fully built. When the rebuild is finished, the indexes are swapped atomically and the old index is deleted.
`BACKEND`
---------
Here’s a list of backends that Wagtail supports out of the box.
### Database Backend (default)
`wagtail.search.backends.database`
The database search backend searches content in the database using the full text search features of the database backend in use (such as PostgreSQL FTS, SQLite FTS5). This backend is intended to be used for development and also should be good enough to use in production on sites that don’t require any Elasticsearch specific features.
### Elasticsearch Backend
Elasticsearch versions 5, 6 and 7 are supported. Use the appropriate backend for your version:
* `wagtail.search.backends.elasticsearch5` (Elasticsearch 5.x)
* `wagtail.search.backends.elasticsearch6` (Elasticsearch 6.x)
* `wagtail.search.backends.elasticsearch7` (Elasticsearch 7.x)
Prerequisites are the [Elasticsearch](https://www.elastic.co/downloads/elasticsearch) service itself and, via pip, the [elasticsearch-py](https://elasticsearch-py.readthedocs.io/) package. The major version of the package must match the installed version of Elasticsearch:
```
pip install "elasticsearch>=5.0.0,<6.0.0" # for Elasticsearch 5.x
```
```
pip install "elasticsearch>=6.4.0,<7.0.0" # for Elasticsearch 6.x
```
```
pip install "elasticsearch>=7.0.0,<8.0.0" # for Elasticsearch 7.x
```
Warning
Version 6.3.1 of the Elasticsearch client library is incompatible with Wagtail. Use 6.4.0 or above.
The backend is configured in settings:
```
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.search.backends.elasticsearch5',
'URLS': ['http://localhost:9200'],
'INDEX': 'wagtail',
'TIMEOUT': 5,
'OPTIONS': {},
'INDEX_SETTINGS': {},
}
}
```
Other than `BACKEND`, the keys are optional and default to the values shown. Any defined key in `OPTIONS` is passed directly to the Elasticsearch constructor as case-sensitive keyword argument (for example `'max_retries': 1`).
A username and password may be optionally be supplied to the `URL` field to provide authentication credentials for the Elasticsearch service:
```
WAGTAILSEARCH_BACKENDS = {
'default': {
...
'URLS': ['http://username:password@localhost:9200'],
...
}
}
```
`INDEX_SETTINGS` is a dictionary used to override the default settings to create the index. The default settings are defined inside the `ElasticsearchSearchBackend` class in the module `wagtail/wagtail/search/backends/elasticsearch7.py`. Any new key is added, any existing key, if not a dictionary, is replaced with the new value. Here’s a sample on how to configure the number of shards and setting the Italian LanguageAnalyzer as the default analyzer:
```
WAGTAILSEARCH_BACKENDS = {
'default': {
...,
'INDEX_SETTINGS': {
'settings': {
'index': {
'number_of_shards': 1,
},
'analysis': {
'analyzer': {
'default': {
'type': 'italian'
}
}
}
}
}
}
```
If you prefer not to run an Elasticsearch server in development or production, there are many hosted services available, including [Bonsai](https://bonsai.io/), who offer a free account suitable for testing and development. To use Bonsai:
* Sign up for an account at `Bonsai`
* Use your Bonsai dashboard to create a Cluster.
* Configure `URLS` in the Elasticsearch entry in `WAGTAILSEARCH_BACKENDS` using the Cluster URL from your Bonsai dashboard
* Run `./manage.py update_index`
### Amazon AWS Elasticsearch
The Elasticsearch backend is compatible with [Amazon Elasticsearch Service](https://aws.amazon.com/opensearch-service/), but requires additional configuration to handle IAM based authentication. This can be done with the [requests-aws4auth](https://pypi.org/project/requests-aws4auth/) package along with the following configuration:
```
from elasticsearch import RequestsHttpConnection
from requests_aws4auth import AWS4Auth
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.search.backends.elasticsearch5',
'INDEX': 'wagtail',
'TIMEOUT': 5,
'HOSTS': [{
'host': 'YOURCLUSTER.REGION.es.amazonaws.com',
'port': 443,
'use_ssl': True,
'verify_certs': True,
'http_auth': AWS4Auth('ACCESS_KEY', 'SECRET_KEY', 'REGION', 'es'),
}],
'OPTIONS': {
'connection_class': RequestsHttpConnection,
},
}
}
```
Rolling Your Own
----------------
Wagtail search backends implement the interface defined in `wagtail/wagtail/wagtailsearch/backends/base.py`. At a minimum, the backend’s `search()` method must return a collection of objects or `model.objects.none()`. For a fully-featured search backend, examine the Elasticsearch backend code in `elasticsearch.py`.
wagtail Your first Wagtail site Your first Wagtail site
=======================
Note
This tutorial covers setting up a brand new Wagtail project. If you’d like to add Wagtail to an existing Django project instead, see [Integrating Wagtail into a Django project](integrating_into_django).
Install and run Wagtail
-----------------------
### Install dependencies
Wagtail supports Python 3.7, 3.8, 3.9, 3.10, and 3.11.
To check whether you have an appropriate version of Python 3:
```
python --version
```
**On Windows** (cmd.exe, with the Python Launcher for Windows):
```
py --version
```
If this does not return a version number or returns a version lower than 3.7, you will need to [install Python 3](https://www.python.org/downloads/).
Note
Before installing Wagtail, it is necessary to install the **libjpeg** and **zlib** libraries, which provide support for working with JPEG, PNG and GIF images (via the Python **Pillow** library). The way to do this varies by platform—see Pillow’s [platform-specific installation instructions](https://pillow.readthedocs.io/en/stable/installation.html#external-libraries).
### Create and activate a virtual environment
We recommend using a virtual environment, which isolates installed dependencies from other projects. This tutorial uses [`venv`](https://docs.python.org/3/tutorial/venv.html), which is packaged with Python 3.
**On Windows** (cmd.exe):
```
py -m venv mysite\env
mysite\env\Scripts\activate.bat
# or:
mysite\env\Scripts\activate
```
**On GNU/Linux or MacOS** (bash):
```
python -m venv mysite/env
source mysite/env/bin/activate
```
**For other shells** see the [`venv` documentation](https://docs.python.org/3/library/venv.html).
Note
If you’re using version control (such as git), `mysite` will be the directory for your project. The `env` directory inside of it should be excluded from any version control.
### Install Wagtail
Use pip, which is packaged with Python, to install Wagtail and its dependencies:
```
pip install wagtail
```
### Generate your site
Wagtail provides a `start` command similar to `django-admin startproject`. Running `wagtail start mysite` in your project will generate a new `mysite` folder with a few Wagtail-specific extras, including the required project settings, a “home” app with a blank `HomePage` model and basic templates, and a sample “search” app.
Because the folder `mysite` was already created by `venv`, run `wagtail start` with an additional argument to specify the destination directory:
```
wagtail start mysite mysite
```
Note
Generally, in Wagtail, each page type, or content type, is represented by a single app. However, different apps can be aware of each other and access each other’s data. All of the apps need to be registered within the `INSTALLED_APPS` section of the `settings.py` file. Look at this file to see how the `start` command has listed them in there.
### Install project dependencies
```
cd mysite
pip install -r requirements.txt
```
This ensures that you have the relevant versions of Wagtail, Django, and any other dependencies for the project you have just created. The `requirements.txt` file contains all the dependencies needed in order to run the project.
### Create the database
If you haven’t updated the project settings, this will be a SQLite database file in the project directory.
```
python manage.py migrate
```
This command ensures that the tables in your database are matched to the models in your project. Every time you alter your model (for example you may add a field to a model) you will need to run this command in order to update the database.
### Create an admin user
```
python manage.py createsuperuser
```
When logged into the admin site, a superuser has full permissions and is able to view/create/manage the database.
### Start the server
```
python manage.py runserver
```
If everything worked, <http://127.0.0.1:8000> will show you a welcome page:
Note
Throughout this tutorial we will use `http://127.0.0.1:8000` but depending on your setup, this could be `http://localhost:8000/` or a different IP address or port. Please read the console output of `manage.py runserver` to determine the correct url for your local site.
You can now access the administrative area at <http://127.0.0.1:8000/admin>
Extend the HomePage model
-------------------------
Out of the box, the “home” app defines a blank `HomePage` model in `models.py`, along with a migration that creates a homepage and configures Wagtail to use it.
Edit `home/models.py` as follows, to add a `body` field to the model:
```
from django.db import models
from wagtail.models import Page
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel
class HomePage(Page):
body = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('body'),
]
```
`body` is defined as `RichTextField`, a special Wagtail field. When `blank=True`, it means that this field is not required and can be empty. You can use any of the [Django core fields](https://docs.djangoproject.com/en/stable/ref/models/fields). `content_panels` define the capabilities and the layout of the editing interface. When you add fields to `content_panels`, it enables them to be edited on the Wagtail interface. [More on creating Page models](../topics/pages).
Run `python manage.py makemigrations` (this will create the migrations file), then `python manage.py migrate` (this executes the migrations and updates the database with your model changes). You must run the above commands each time you make changes to the model definition.
You can now edit the homepage within the Wagtail admin area (go to Pages, Homepage, then Edit) to see the new body field. Enter some text into the body field, and publish the page by selecting *Publish* at the bottom of the page editor, rather than *Save Draft*.
The page template now needs to be updated to reflect the changes made to the model. Wagtail uses normal Django templates to render each page type. By default, it will look for a template filename formed from the app and model name, separating capital letters with underscores (for example HomePage within the ‘home’ app becomes `home/home_page.html`). This template file can exist in any location recognised by [Django’s template rules](https://docs.djangoproject.com/en/stable/intro/tutorial03/#write-views-that-actually-do-something); conventionally it is placed under a `templates` folder within the app.
Edit `home/templates/home/home_page.html` to contain the following:
```
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% block body_class %}template-homepage{% endblock %}
{% block content %}
{{ page.body|richtext }}
{% endblock %}
```
`base.html` refers to a parent template and must always be the first template tag used in a template. Extending from this template saves you from rewriting code and allows pages across your app to share a similar frame (by using block tags in the child template, you are able to override specific content within the parent template).
`wagtailcore_tags` must also be loaded at the top of the template and provide additional tags to those provided by Django.
### Wagtail template tags
In addition to Django’s [template tags and filters](https://docs.djangoproject.com/en/3.1/ref/templates/builtins/), Wagtail provides a number of its own [template tags & filters](../topics/writing_templates#template-tags-and-filters) which can be loaded by including `{% load wagtailcore_tags %}` at the top of your template file.
In this tutorial, we use the *richtext* filter to escape and print the contents of a `RichTextField`:
```
{% load wagtailcore_tags %}
{{ page.body|richtext }}
```
Produces:
```
<p><b>Welcome</b> to our new site!</p>
```
**Note:** You’ll need to include `{% load wagtailcore_tags %}` in each template that uses Wagtail’s tags. Django will throw a `TemplateSyntaxError` if the tags aren’t loaded.
A basic blog
------------
We are now ready to create a blog. To do so, run `python manage.py startapp blog` to create a new app in your Wagtail site.
Add the new `blog` app to `INSTALLED_APPS` in `mysite/settings/base.py`.
### Blog Index and Posts
Lets start with a simple index page for our blog. In `blog/models.py`:
```
from wagtail.models import Page
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel
class BlogIndexPage(Page):
intro = RichTextField(blank=True)
content_panels = Page.content_panels + [
FieldPanel('intro')
]
```
Run `python manage.py makemigrations` and `python manage.py migrate`.
Since the model is called `BlogIndexPage`, the default template name (unless we override it) will be `blog_index_page.html`. Django will look for a template whose name matches the name of your Page model within the templates directory in your blog app folder. This default behaviour can be overridden if needed.
To create a template for the `BlogIndexPage` model, create a file at the location `blog/templates/blog/blog_index_page.html`.
Note
You may need to create the folders `templates/blog` within your `blog` app folder
In your `blog_index_page.html` file enter the following content:
```
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% block body_class %}template-blogindexpage{% endblock %}
{% block content %}
<h1>{{ page.title }}</h1>
<div class="intro">{{ page.intro|richtext }}</div>
{% for post in page.get_children %}
<h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
{{ post.specific.intro }}
{{ post.specific.body|richtext }}
{% endfor %}
{% endblock %}
```
Most of this should be familiar, but we’ll explain `get_children` a bit later. Note the `pageurl` tag, which is similar to Django’s `url` tag but takes a Wagtail Page object as an argument.
In the Wagtail admin, go to Pages, then Home. Add a child page to the Home page by clicking on the “Actions” icon and selecting the option “Add child page”. Choose “Blog index page” from the list of the page types. Use “Our Blog” as your page title, make sure it has the slug “blog” on the Promote tab, and publish it. You should now be able to access the url `http://127.0.0.1:8000/blog` on your site (note how the slug from the Promote tab defines the page URL).
Now we need a model and template for our blog posts. In `blog/models.py`:
```
from django.db import models
from wagtail.models import Page
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel
from wagtail.search import index
# Keep the definition of BlogIndexPage, and add:
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = Page.content_panels + [
FieldPanel('date'),
FieldPanel('intro'),
FieldPanel('body'),
]
```
In the model above, we import `index` as this makes the model searchable. You can then list fields that you want to be searchable for the user.
Run `python manage.py makemigrations` and `python manage.py migrate`.
Create a new template file at the location `blog/templates/blog/blog_page.html`. Now add the following content to your newly created `blog_page.html` file:
```
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% block body_class %}template-blogpage{% endblock %}
{% block content %}
<h1>{{ page.title }}</h1>
<p class="meta">{{ page.date }}</p>
<div class="intro">{{ page.intro }}</div>
{{ page.body|richtext }}
<p><a href="{{ page.get_parent.url }}">Return to blog</a></p>
{% endblock %}
```
Note the use of Wagtail’s built-in `get_parent()` method to obtain the URL of the blog this post is a part of.
Now create a few blog posts as children of `BlogIndexPage`. Be sure to select type “Blog Page” when creating your posts.
Wagtail gives you full control over what kinds of content can be created under various parent content types. By default, any page type can be a child of any other page type.
Publish each blog post when you are done editing.
You should now have the very beginnings of a working blog. Access the `/blog` URL and you should see something like this:
Titles should link to post pages, and a link back to the blog’s homepage should appear in the footer of each post page.
### Parents and Children
Much of the work you’ll be doing in Wagtail revolves around the concept of hierarchical “tree” structures consisting of nodes and leaves (see [Theory](../reference/pages/theory)). In this case, the `BlogIndexPage` is a “node” and individual `BlogPage` instances are the “leaves”.
Take another look at the guts of `blog_index_page.html`:
```
{% for post in page.get_children %}
<h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
{{ post.specific.intro }}
{{ post.specific.body|richtext }}
{% endfor %}
```
Every “page” in Wagtail can call out to its parent or children from its own position in the hierarchy. But why do we have to specify `post.specific.intro` rather than `post.intro`? This has to do with the way we defined our model:
`class BlogPage(Page):`
The `get_children()` method gets us a list of instances of the `Page` base class. When we want to reference properties of the instances that inherit from the base class, Wagtail provides the `specific` method that retrieves the actual `BlogPage` record. While the “title” field is present on the base `Page` model, “intro” is only present on the `BlogPage` model, so we need `.specific` to access it.
To tighten up template code like this, we could use Django’s `with` tag:
```
{% for post in page.get_children %}
{% with post=post.specific %}
<h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
<p>{{ post.intro }}</p>
{{ post.body|richtext }}
{% endwith %}
{% endfor %}
```
When you start writing more customised Wagtail code, you’ll find a whole set of QuerySet modifiers to help you navigate the hierarchy.
```
# Given a page object 'somepage':
MyModel.objects.descendant_of(somepage)
child_of(page) / not_child_of(somepage)
ancestor_of(somepage) / not_ancestor_of(somepage)
parent_of(somepage) / not_parent_of(somepage)
sibling_of(somepage) / not_sibling_of(somepage)
# ... and ...
somepage.get_children()
somepage.get_ancestors()
somepage.get_descendants()
somepage.get_siblings()
```
For more information, see: [Page QuerySet reference](../reference/pages/queryset_reference)
### Overriding Context
There are a couple of problems with our blog index view:
1. Blogs generally display content in *reverse* chronological order
2. We want to make sure we’re only displaying *published* content.
To accomplish these things, we need to do more than just grab the index page’s children in the template. Instead, we’ll want to modify the QuerySet in the model definition. Wagtail makes this possible via the overridable `get_context()` method. Modify your `BlogIndexPage` model like this:
```
class BlogIndexPage(Page):
intro = RichTextField(blank=True)
def get_context(self, request):
# Update context to include only published posts, ordered by reverse-chron
context = super().get_context(request)
blogpages = self.get_children().live().order_by('-first_published_at')
context['blogpages'] = blogpages
return context
```
All we’ve done here is retrieve the original context, create a custom QuerySet, add it to the retrieved context, and return the modified context back to the view. You’ll also need to modify your `blog_index_page.html` template slightly. Change:
`{% for post in page.get_children %}` to `{% for post in blogpages %}`
Now try unpublishing one of your posts - it should disappear from the blog index page. The remaining posts should now be sorted with the most recently published posts first.
### Images
Let’s add the ability to attach an image gallery to our blog posts. While it’s possible to simply insert images into the `body` rich text field, there are several advantages to setting up our gallery images as a new dedicated object type within the database - this way, you have full control of the layout and styling of the images on the template, rather than having to lay them out in a particular way within the rich text field. It also makes it possible for the images to be used elsewhere, independently of the blog text - for example, displaying a thumbnail on the blog index page.
Add a new `BlogPageGalleryImage` model to `models.py`:
```
from django.db import models
# New imports added for ParentalKey, Orderable, InlinePanel
from modelcluster.fields import ParentalKey
from wagtail.models import Page, Orderable
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel, InlinePanel
from wagtail.search import index
# ... (Keep the definition of BlogIndexPage, and update BlogPage:)
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = Page.content_panels + [
FieldPanel('date'),
FieldPanel('intro'),
FieldPanel('body'),
InlinePanel('gallery_images', label="Gallery images"),
]
class BlogPageGalleryImage(Orderable):
page = ParentalKey(BlogPage, on_delete=models.CASCADE, related_name='gallery_images')
image = models.ForeignKey(
'wagtailimages.Image', on_delete=models.CASCADE, related_name='+'
)
caption = models.CharField(blank=True, max_length=250)
panels = [
FieldPanel('image'),
FieldPanel('caption'),
]
```
Run `python manage.py makemigrations` and `python manage.py migrate`.
There are a few new concepts here, so let’s take them one at a time:
Inheriting from `Orderable` adds a `sort_order` field to the model, to keep track of the ordering of images in the gallery.
The `ParentalKey` to `BlogPage` is what attaches the gallery images to a specific page. A `ParentalKey` works similarly to a `ForeignKey`, but also defines `BlogPageGalleryImage` as a “child” of the `BlogPage` model, so that it’s treated as a fundamental part of the page in operations like submitting for moderation, and tracking revision history.
`image` is a `ForeignKey` to Wagtail’s built-in `Image` model, where the images themselves are stored. This appears in the page editor as a pop-up interface for choosing an existing image or uploading a new one. This way, we allow an image to exist in multiple galleries - effectively, we’ve created a many-to-many relationship between pages and images.
Specifying `on_delete=models.CASCADE` on the foreign key means that if the image is deleted from the system, the gallery entry is deleted as well. (In other situations, it might be appropriate to leave the entry in place - for example, if an “our staff” page included a list of people with headshots, and one of those photos was deleted, we’d rather leave the person in place on the page without a photo. In this case, we’d set the foreign key to `blank=True, null=True, on_delete=models.SET_NULL`.)
Finally, adding the `InlinePanel` to `BlogPage.content_panels` makes the gallery images available on the editing interface for `BlogPage`.
Adjust your blog page template to include the images:
```
{% extends "base.html" %}
{% load wagtailcore_tags wagtailimages_tags %}
{% block body_class %}template-blogpage{% endblock %}
{% block content %}
<h1>{{ page.title }}</h1>
<p class="meta">{{ page.date }}</p>
<div class="intro">{{ page.intro }}</div>
{{ page.body|richtext }}
{% for item in page.gallery_images.all %}
<div style="float: left; margin: 10px">
{% image item.image fill-320x240 %}
<p>{{ item.caption }}</p>
</div>
{% endfor %}
<p><a href="{{ page.get_parent.url }}">Return to blog</a></p>
{% endblock %}
```
Here we use the `{% image %}` tag (which exists in the `wagtailimages_tags` library, imported at the top of the template) to insert an `<img>` element, with a `fill-320x240` parameter to indicate that the image should be resized and cropped to fill a 320x240 rectangle. You can read more about using images in templates in the [docs](../topics/images).
Since our gallery images are database objects in their own right, we can now query and re-use them independently of the blog post body. Let’s define a `main_image` method, which returns the image from the first gallery item (or `None` if no gallery items exist):
```
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
def main_image(self):
gallery_item = self.gallery_images.first()
if gallery_item:
return gallery_item.image
else:
return None
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = Page.content_panels + [
FieldPanel('date'),
FieldPanel('intro'),
FieldPanel('body'),
InlinePanel('gallery_images', label="Gallery images"),
]
```
This method is now available from our templates. Update `blog_index_page.html` to include the main image as a thumbnail alongside each post:
```
{% load wagtailcore_tags wagtailimages_tags %}
...
{% for post in blogpages %}
{% with post=post.specific %}
<h2><a href="{% pageurl post %}">{{ post.title }}</a></h2>
{% with post.main_image as main_image %}
{% if main_image %}{% image main_image fill-160x100 %}{% endif %}
{% endwith %}
<p>{{ post.intro }}</p>
{{ post.body|richtext }}
{% endwith %}
{% endfor %}
```
### Tagging Posts
Let’s say we want to let editors “tag” their posts, so that readers can, for example, view all bicycle-related content together. For this, we’ll need to invoke the tagging system bundled with Wagtail, attach it to the `BlogPage` model and content panels, and render linked tags on the blog post template. Of course, we’ll need a working tag-specific URL view as well.
First, alter `models.py` once more:
```
from django.db import models
# New imports added for ClusterTaggableManager, TaggedItemBase, MultiFieldPanel
from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase
from wagtail.models import Page, Orderable
from wagtail.fields import RichTextField
from wagtail.admin.panels import FieldPanel, InlinePanel, MultiFieldPanel
from wagtail.search import index
# ... (Keep the definition of BlogIndexPage)
class BlogPageTag(TaggedItemBase):
content_object = ParentalKey(
'BlogPage',
related_name='tagged_items',
on_delete=models.CASCADE
)
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
# ... (Keep the main_image method and search_fields definition)
content_panels = Page.content_panels + [
MultiFieldPanel([
FieldPanel('date'),
FieldPanel('tags'),
], heading="Blog information"),
FieldPanel('intro'),
FieldPanel('body'),
InlinePanel('gallery_images', label="Gallery images"),
]
```
Run `python manage.py makemigrations` and `python manage.py migrate`.
Note the new `modelcluster` and `taggit` imports, the addition of a new `BlogPageTag` model, and the addition of a `tags` field on `BlogPage`. We’ve also taken the opportunity to use a `MultiFieldPanel` in `content_panels` to group the date and tags fields together for readability.
Edit one of your `BlogPage` instances, and you should now be able to tag posts:
To render tags on a `BlogPage`, add this to `blog_page.html`:
```
{% if page.tags.all.count %}
<div class="tags">
<h3>Tags</h3>
{% for tag in page.tags.all %}
<a href="{% slugurl 'tags' %}?tag={{ tag }}"><button type="button">{{ tag }}</button></a>
{% endfor %}
</div>
{% endif %}
```
Notice that we’re linking to pages here with the builtin `slugurl` tag rather than `pageurl`, which we used earlier. The difference is that `slugurl` takes a Page slug (from the Promote tab) as an argument. `pageurl` is more commonly used because it is unambiguous and avoids extra database lookups. But in the case of this loop, the Page object isn’t readily available, so we fall back on the less-preferred `slugurl` tag.
Visiting a blog post with tags should now show a set of linked buttons at the bottom - one for each tag. However, clicking a button will get you a 404, since we haven’t yet defined a “tags” view. Add to `models.py`:
```
class BlogTagIndexPage(Page):
def get_context(self, request):
# Filter by tag
tag = request.GET.get('tag')
blogpages = BlogPage.objects.filter(tags__name=tag)
# Update template context
context = super().get_context(request)
context['blogpages'] = blogpages
return context
```
Note that this Page-based model defines no fields of its own. Even without fields, subclassing `Page` makes it a part of the Wagtail ecosystem, so that you can give it a title and URL in the admin, and so that you can manipulate its contents by returning a QuerySet from its `get_context()` method.
Migrate this in, then create a new `BlogTagIndexPage` in the admin. You’ll probably want to create the new page/view as a child of Homepage, parallel to your Blog index. Give it the slug “tags” on the Promote tab.
Access `/tags` and Django will tell you what you probably already knew: you need to create a template `blog/blog_tag_index_page.html`:
```
{% extends "base.html" %}
{% load wagtailcore_tags %}
{% block content %}
{% if request.GET.tag %}
<h4>Showing pages tagged "{{ request.GET.tag }}"</h4>
{% endif %}
{% for blogpage in blogpages %}
<p>
<strong><a href="{% pageurl blogpage %}">{{ blogpage.title }}</a></strong><br />
<small>Revised: {{ blogpage.latest_revision_created_at }}</small><br />
{% if blogpage.author %}
<p>By {{ blogpage.author.profile }}</p>
{% endif %}
</p>
{% empty %}
No pages found with that tag.
{% endfor %}
{% endblock %}
```
We’re calling the built-in `latest_revision_created_at` field on the `Page` model - handy to know this is always available.
We haven’t yet added an “author” field to our `BlogPage` model, nor do we have a Profile model for authors - we’ll leave those as an exercise for the reader.
Clicking the tag button at the bottom of a BlogPost should now render a page something like this:
### Categories
Let’s add a category system to our blog. Unlike tags, where a page author can bring a tag into existence simply by using it on a page, our categories will be a fixed list, managed by the site owner through a separate area of the admin interface.
First, we define a `BlogCategory` model. A category is not a page in its own right, and so we define it as a standard Django `models.Model` rather than inheriting from `Page`. Wagtail introduces the concept of “snippets” for reusable pieces of content that need to be managed through the admin interface, but do not exist as part of the page tree themselves; a model can be registered as a snippet by adding the `@register_snippet` decorator. All the field types we’ve used so far on pages can be used on snippets too - here we’ll give each category an icon image as well as a name. Add to `blog/models.py`:
```
from wagtail.snippets.models import register_snippet
@register_snippet
class BlogCategory(models.Model):
name = models.CharField(max_length=255)
icon = models.ForeignKey(
'wagtailimages.Image', null=True, blank=True,
on_delete=models.SET_NULL, related_name='+'
)
panels = [
FieldPanel('name'),
FieldPanel('icon'),
]
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'blog categories'
```
Note
Note that we are using `panels` rather than `content_panels` here - since snippets generally have no need for fields such as slug or publish date, the editing interface for them is not split into separate ‘content’ / ‘promote’ / ‘settings’ tabs as standard, and so there is no need to distinguish between ‘content panels’ and ‘promote panels’.
Migrate this change by running `python manage.py makemigrations` and `python manage.py migrate`. Create a few categories through the Snippets area which now appears in the admin menu.
We can now add categories to the `BlogPage` model, as a many-to-many field. The field type we use for this is `ParentalManyToManyField` - this is a variant of the standard Django `ManyToManyField` which ensures that the chosen objects are correctly stored against the page record in the revision history, in much the same way that `ParentalKey` replaces `ForeignKey` for one-to-many relations.To add categories to the `BlogPage`, modify `models.py` in your blog app folder:
```
# New imports added for forms and ParentalManyToManyField
from django import forms
from django.db import models
from modelcluster.fields import ParentalKey, ParentalManyToManyField
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase
# ...
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
categories = ParentalManyToManyField('blog.BlogCategory', blank=True)
# ... (Keep the main_image method and search_fields definition)
content_panels = Page.content_panels + [
MultiFieldPanel([
FieldPanel('date'),
FieldPanel('tags'),
FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
], heading="Blog information"),
FieldPanel('intro'),
FieldPanel('body'),
InlinePanel('gallery_images', label="Gallery images"),
]
```
Here we’re making use of the `widget` keyword argument on the `FieldPanel` definition to specify a checkbox-based widget instead of the default multiple select box, as this is often considered more user-friendly.
Finally, we can update the `blog_page.html` template to display the categories:
```
<h1>{{ page.title }}</h1>
<p class="meta">{{ page.date }}</p>
{% with categories=page.categories.all %}
{% if categories %}
<h3>Posted in:</h3>
<ul>
{% for category in categories %}
<li style="display: inline">
{% image category.icon fill-32x32 style="vertical-align: middle" %}
{{ category.name }}
</li>
{% endfor %}
</ul>
{% endif %}
{% endwith %}
```
Where next
----------
* Read the Wagtail [topics](../topics/index) and [reference](../reference/index) documentation
* Learn how to implement [StreamField](../topics/streamfield) for freeform page content
* Browse through the [advanced topics](../advanced_topics/index) section and read [third-party tutorials](../advanced_topics/third_party_tutorials)
| programming_docs |
wagtail Getting started Getting started
===============
Note
These instructions assume familiarity with virtual environments and the [Django web framework](https://www.djangoproject.com/). For more detailed instructions, see [Your first Wagtail site](tutorial). To add Wagtail to an existing Django project, see [Integrating Wagtail into a Django project](integrating_into_django).
Dependencies needed for installation
------------------------------------
* [Python 3](https://www.python.org/downloads/)
* **libjpeg** and **zlib**, libraries required for Django’s **Pillow** library. See Pillow’s [platform-specific installation instructions](https://pillow.readthedocs.io/en/stable/installation.html#external-libraries).
Quick install
-------------
Run the following commands in a virtual environment of your choice:
```
pip install wagtail
```
(Installing wagtail outside a virtual environment may require `sudo`. sudo is a program to run other programs with the security privileges of another user, by default the superuser)
Once installed, Wagtail provides a command similar to Django’s `django-admin startproject` to generate a new site/project:
```
wagtail start mysite
```
This will create a new folder `mysite`, based on a template containing everything you need to get started. More information on that template is available in [the project template reference](../reference/project_template).
Inside your `mysite` folder, run the setup steps necessary for any Django project:
```
pip install -r requirements.txt
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver
```
Your site is now accessible at `http://localhost:8000`, with the admin backend available at `http://localhost:8000/admin/`.
This will set you up with a new stand-alone Wagtail project. If you’d like to add Wagtail to an existing Django project instead, see [Integrating Wagtail into a Django project](integrating_into_django).
There are a few optional packages which are not installed by default but are recommended to improve performance or add features to Wagtail, including:
* [Elasticsearch](../advanced_topics/performance).
* [Feature Detection](../advanced_topics/images/feature_detection#image-feature-detection).
* [Your first Wagtail site](tutorial)
* [Demo site](demo_site)
* [Integrating Wagtail into a Django project](integrating_into_django)
* [The Zen of Wagtail](the_zen_of_wagtail)
wagtail Demo site Demo site
=========
To create a new site on Wagtail, we recommend the `wagtail start` command in [Getting started](index). We also have a demo site, The Wagtail Bakery, which contains example page types and models. We recommend you use the demo site for testing during development of Wagtail itself.
The source code and installation instructions can be found at <https://github.com/wagtail/bakerydemo>
wagtail The Zen of Wagtail The Zen of Wagtail
==================
Wagtail has been born out of many years of experience building websites, learning approaches that work and ones that don’t, and striking a balance between power and simplicity, structure and flexibility. We hope you’ll find that Wagtail is in that sweet spot. However, as a piece of software, Wagtail can only take that mission so far - it’s now up to you to create a site that’s beautiful and a joy to work with. So, while it’s tempting to rush ahead and start building, it’s worth taking a moment to understand the design principles that Wagtail is built on.
In the spirit of [“The Zen of Python”](https://www.python.org/dev/peps/pep-0020/), The Zen of Wagtail is a set of guiding principles, both for building websites in Wagtail, and for the ongoing development of Wagtail itself.
Wagtail is not an instant website in a box.
-------------------------------------------
You can’t make a beautiful website by plugging off-the-shelf modules together - expect to write code.
Always wear the right hat.
--------------------------
The key to using Wagtail effectively is to recognise that there are multiple roles involved in creating a website: the content author, site administrator, developer and designer. These may well be different people, but they don’t have to be - if you’re using Wagtail to build your personal blog, you’ll probably find yourself hopping between those different roles. Either way, it’s important to be aware of which of those hats you’re wearing at any moment, and to use the right tools for that job. A content author or site administrator will do the bulk of their work through the Wagtail admin interface; a developer or designer will spend most of their time writing Python, HTML or CSS code. This is a good thing: Wagtail isn’t designed to replace the job of programming. Maybe one day someone will come up with a drag-and-drop UI for building websites that’s as powerful as writing code, but Wagtail is not that tool, and does not try to be.
A common mistake is to push too much power and responsibility into the hands of the content author and site administrator - indeed, if those people are your clients, they’ll probably be loudly clamouring for exactly that. The success of your site depends on your ability to say no. The real power of content management comes not from handing control over to CMS users, but from setting clear boundaries between the different roles. Amongst other things, this means not having editors doing design and layout within the content editing interface, and not having site administrators building complex interaction workflows that would be better achieved in code.
A CMS should get information out of an editor’s head and into a database, as efficiently and directly as possible.
------------------------------------------------------------------------------------------------------------------
Whether your site is about cars, cats, cakes or conveyancing, your content authors will be arriving at the Wagtail admin interface with some domain-specific information they want to put up on the website. Your aim as a site builder is to extract and store this information in its raw form - not one particular author’s idea of how that information should look.
Keeping design concerns out of page content has numerous advantages. It ensures that the design remains consistent across the whole site, not subject to the whims of editors from one day to the next. It allows you to make full use of the informational content of the pages - for example, if your pages are about events, then having a dedicated “Event” page type with data fields for the event date and location will let you present the events in a calendar view or filtered listing, which wouldn’t be possible if those were just implemented as different styles of heading on a generic page. Finally, if you redesign the site at some point in the future, or move it to a different platform entirely, you can be confident that the site content will work in its new setting, and not be reliant on being formatted a particular way.
Suppose a content author comes to you with a request: “We need this text to be in bright pink Comic Sans”. Your question to them should be “Why? What’s special about this particular bit of text?” If the reply is “I just like the look of it”, then you’ll have to gently persuade them that it’s not up to them to make design choices. (Sorry.) But if the answer is “it’s for our Children’s section”, then that gives you a way to divide the editorial and design concerns: give your editors the ability to designate certain pages as being “the Children’s section” (through tagging, different page models, or the site hierarchy) and let designers decide how to apply styles based on that.
The best user interface for a programmer is usually a programming language.
---------------------------------------------------------------------------
A common sight in content management systems is a point-and-click interface to let you define the data model that makes up a page:
It looks nice in the sales pitch, but in reality, no CMS end-user can realistically make that kind of fundamental change - on a live site, no less - unless they have a programmer’s insight into how the site is built, and what impact the change will have. As such, it will always be the programmer’s job to negotiate that point-and-click interface - all you’ve done is taken them away from the comfortable world of writing code, where they have a whole ecosystem of tools, from text editors to version control systems, to help them develop, test and deploy their code changes.
Wagtail recognises that most programming tasks are best done by writing code, and does not try to turn them into box-filling exercises when there’s no good reason to. Likewise, when building functionality for your site, you should keep in mind that some features are destined to be maintained by the programmer rather than a content editor, and consider whether making them configurable through the Wagtail admin is going to be more of a hindrance than a convenience. For example, Wagtail provides a form builder to allow content authors to create general-purpose data collection forms. You might be tempted to use this as the basis for more complex forms that integrate with (for example) a CRM system or payment processor - however, in this case there’s no way to edit the form fields without rewriting the backend logic, so making them editable through Wagtail has limited value. More likely, you’d be better off building these using Django’s form framework, where the form fields are defined entirely in code.
wagtail Integrating Wagtail into a Django project Integrating Wagtail into a Django project
=========================================
Wagtail provides the `wagtail start` command and project template to get you started with a new Wagtail project as quickly as possible, but it’s easy to integrate Wagtail into an existing Django project too.
Wagtail is currently compatible with Django 3.2, 4.0 and 4.1. First, install the `wagtail` package from PyPI:
```
pip install wagtail
```
or add the package to your existing requirements file. This will also install the **Pillow** library as a dependency, which requires libjpeg and zlib - see Pillow’s [platform-specific installation instructions](https://pillow.readthedocs.io/en/stable/installation.html#external-libraries).
Settings
--------
In your settings.py file, add the following apps to `INSTALLED_APPS`:
```
'wagtail.contrib.forms',
'wagtail.contrib.redirects',
'wagtail.embeds',
'wagtail.sites',
'wagtail.users',
'wagtail.snippets',
'wagtail.documents',
'wagtail.images',
'wagtail.search',
'wagtail.admin',
'wagtail',
'modelcluster',
'taggit',
```
Add the following entry to `MIDDLEWARE`:
```
'wagtail.contrib.redirects.middleware.RedirectMiddleware',
```
Add a `STATIC_ROOT` setting, if your project does not have one already:
```
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
```
Add `MEDIA_ROOT` and `MEDIA_URL` settings, if your project does not have these already:
```
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
```
Add a `WAGTAIL_SITE_NAME` - this will be displayed on the main dashboard of the Wagtail admin backend:
```
WAGTAIL_SITE_NAME = 'My Example Site'
```
Various other settings are available to configure Wagtail’s behaviour - see [Settings](../reference/settings).
URL configuration
-----------------
Now make the following additions to your `urls.py` file:
```
from django.urls import path, include
from wagtail.admin import urls as wagtailadmin_urls
from wagtail import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
urlpatterns = [
...
path('cms/', include(wagtailadmin_urls)),
path('documents/', include(wagtaildocs_urls)),
path('pages/', include(wagtail_urls)),
...
]
```
The URL paths here can be altered as necessary to fit your project’s URL scheme.
`wagtailadmin_urls` provides the admin interface for Wagtail. This is separate from the Django admin interface (`django.contrib.admin`); Wagtail-only projects typically host the Wagtail admin at `/admin/`, but if this would clash with your project’s existing admin backend then an alternative path can be used, such as `/cms/` here.
`wagtaildocs_urls` is the location from where document files will be served. This can be omitted if you do not intend to use Wagtail’s document management features.
`wagtail_urls` is the base location from where the pages of your Wagtail site will be served. In the above example, Wagtail will handle URLs under `/pages/`, leaving the root URL and other paths to be handled as normal by your Django project. If you want Wagtail to handle the entire URL space including the root URL, this can be replaced with:
```
path('', include(wagtail_urls)),
```
In this case, this should be placed at the end of the `urlpatterns` list, so that it does not override more specific URL patterns.
Finally, your project needs to be set up to serve user-uploaded files from `MEDIA_ROOT`. Your Django project may already have this in place, but if not, add the following snippet to `urls.py`:
```
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
```
Note that this only works in development mode (`DEBUG = True`); in production, you will need to configure your web server to serve files from `MEDIA_ROOT`. For further details, see the Django documentation: [Serving files uploaded by a user during development](https://docs.djangoproject.com/en/stable/howto/static-files/#serving-files-uploaded-by-a-user-during-development) and [Deploying static files](https://docs.djangoproject.com/en/stable/howto/static-files/deployment/).
With this configuration in place, you are ready to run `python manage.py migrate` to create the database tables used by Wagtail.
User accounts
-------------
Superuser accounts receive automatic access to the Wagtail admin interface; use `python manage.py createsuperuser` if you don’t already have one. Custom user models are supported, with some restrictions; Wagtail uses an extension of Django’s permissions framework, so your user model must at minimum inherit from `AbstractBaseUser` and `PermissionsMixin`.
Start developing
----------------
You’re now ready to add a new app to your Django project (via `python manage.py startapp` - remember to add it to `INSTALLED_APPS` in your settings.py file) and set up page models, as described in [Your first Wagtail site](tutorial).
Note that there’s one small difference when not using the Wagtail project template: Wagtail creates an initial homepage of the basic type `Page`, which does not include any content fields beyond the title. You’ll probably want to replace this with your own `HomePage` class - when you do so, ensure that you set up a site record (under Settings / Sites in the Wagtail admin) to point to the new homepage.
markdown Markdown Markdown
========
* [Overview](#overview)
+ [Philosophy](#philosophy)
+ [Inline HTML](#html)
+ [Automatic Escaping for Special Characters](#autoescape)
* [Block Elements](#block)
+ [Paragraphs and Line Breaks](#p)
+ [Headers](#header)
+ [Blockquotes](#blockquote)
+ [Lists](#list)
+ [Code Blocks](#precode)
+ [Horizontal Rules](#hr)
* [Span Elements](#span)
+ [Links](#link)
+ [Emphasis](#em)
+ [Code](#code)
+ [Images](#img)
* [Miscellaneous](#misc)
+ [Backslash Escapes](#backslash)
+ [Automatic Links](#autolink)
**Note:** This document is itself written using Markdown; you can [see the source for it by adding ‘.text’ to the URL](https://daringfireball.net/projects/markdown/syntax.text).
Overview
--------
### Philosophy
Markdown is intended to be as easy-to-read and easy-to-write as is feasible.
Readability, however, is emphasized above all else. A Markdown-formatted document should be publishable as-is, as plain text, without looking like it’s been marked up with tags or formatting instructions. While Markdown’s syntax has been influenced by several existing text-to-HTML filters — including [Setext](http://docutils.sourceforge.net/mirror/setext.html), [atx](http://www.aaronsw.com/2002/atx/), [Textile](http://textism.com/tools/textile/), [reStructuredText](http://docutils.sourceforge.net/rst.html), [Grutatext](http://www.triptico.com/software/grutatxt.html), and [EtText](http://ettext.taint.org/doc/) — the single biggest source of inspiration for Markdown’s syntax is the format of plain text email.
To this end, Markdown’s syntax is comprised entirely of punctuation characters, which punctuation characters have been carefully chosen so as to look like what they mean. E.g., asterisks around a word actually look like \*emphasis\*. Markdown lists look like, well, lists. Even blockquotes look like quoted passages of text, assuming you’ve ever used email.
### Inline HTML
Markdown’s syntax is intended for one purpose: to be used as a format for *writing* for the web.
Markdown is not a replacement for HTML, or even close to it. Its syntax is very small, corresponding only to a very small subset of HTML tags. The idea is *not* to create a syntax that makes it easier to insert HTML tags. In my opinion, HTML tags are already easy to insert. The idea for Markdown is to make it easy to read, write, and edit prose. HTML is a *publishing* format; Markdown is a *writing* format. Thus, Markdown’s formatting syntax only addresses issues that can be conveyed in plain text.
For any markup that is not covered by Markdown’s syntax, you simply use HTML itself. There’s no need to preface it or delimit it to indicate that you’re switching from Markdown to HTML; you just use the tags.
The only restrictions are that block-level HTML elements — e.g. `<div>`, `<table>`, `<pre>`, `<p>`, etc. — must be separated from surrounding content by blank lines, and the start and end tags of the block should not be indented with tabs or spaces. Markdown is smart enough not to add extra (unwanted) `<p>` tags around HTML block-level tags.
For example, to add an HTML table to a Markdown article:
```
This is a regular paragraph.
<table>
<tr>
<td>Foo</td>
</tr>
</table>
This is another regular paragraph.
```
Note that Markdown formatting syntax is not processed within block-level HTML tags. E.g., you can’t use Markdown-style `*emphasis*` inside an HTML block.
Span-level HTML tags — e.g. `<span>`, `<cite>`, or `<del>` — can be used anywhere in a Markdown paragraph, list item, or header. If you want, you can even use HTML tags instead of Markdown formatting; e.g. if you’d prefer to use HTML `<a>` or `<img>` tags instead of Markdown’s link or image syntax, go right ahead.
Unlike block-level HTML tags, Markdown syntax *is* processed within span-level tags.
### Automatic Escaping for Special Characters
In HTML, there are two characters that demand special treatment: `<` and `&`. Left angle brackets are used to start tags; ampersands are used to denote HTML entities. If you want to use them as literal characters, you must escape them as entities, e.g. `<`, and `&`.
Ampersands in particular are bedeviling for web writers. If you want to write about ‘AT&T’, you need to write ‘`AT&T`’. You even need to escape ampersands within URLs. Thus, if you want to link to:
```
http://images.google.com/images?num=30&q=larry+bird
```
you need to encode the URL as:
```
http://images.google.com/images?num=30&q=larry+bird
```
in your anchor tag `href` attribute. Needless to say, this is easy to forget, and is probably the single most common source of HTML validation errors in otherwise well-marked-up web sites.
Markdown allows you to use these characters naturally, taking care of all the necessary escaping for you. If you use an ampersand as part of an HTML entity, it remains unchanged; otherwise it will be translated into `&`.
So, if you want to include a copyright symbol in your article, you can write:
```
©
```
and Markdown will leave it alone. But if you write:
```
AT&T
```
Markdown will translate it to:
```
AT&T
```
Similarly, because Markdown supports [inline HTML](#html), if you use angle brackets as delimiters for HTML tags, Markdown will treat them as such. But if you write:
```
4 < 5
```
Markdown will translate it to:
```
4 < 5
```
However, inside Markdown code spans and blocks, angle brackets and ampersands are *always* encoded automatically. This makes it easy to use Markdown to write about HTML code. (As opposed to raw HTML, which is a terrible format for writing about HTML syntax, because every single `<` and `&` in your example code needs to be escaped.)
Block Elements
--------------
### Paragraphs and Line Breaks
A paragraph is simply one or more consecutive lines of text, separated by one or more blank lines. (A blank line is any line that looks like a blank line — a line containing nothing but spaces or tabs is considered blank.) Normal paragraphs should not be indented with spaces or tabs.
The implication of the “one or more consecutive lines of text” rule is that Markdown supports “hard-wrapped” text paragraphs. This differs significantly from most other text-to-HTML formatters (including Movable Type’s “Convert Line Breaks” option) which translate every line break character in a paragraph into a `<br />` tag.
When you *do* want to insert a `<br />` break tag using Markdown, you end a line with two or more spaces, then type return.
Yes, this takes a tad more effort to create a `<br />`, but a simplistic “every line break is a `<br />`” rule wouldn’t work for Markdown. Markdown’s email-style [blockquoting](#blockquote) and multi-paragraph [list items](#list) work best — and look better — when you format them with hard breaks.
### Headers
Markdown supports two styles of headers, [Setext](http://docutils.sourceforge.net/mirror/setext.html) and [atx](http://www.aaronsw.com/2002/atx/).
Setext-style headers are “underlined” using equal signs (for first-level headers) and dashes (for second-level headers). For example:
```
This is an H1
=============
This is an H2
-------------
```
Any number of underlining `=`’s or `-`’s will work.
Atx-style headers use 1-6 hash characters at the start of the line, corresponding to header levels 1-6. For example:
```
# This is an H1
## This is an H2
###### This is an H6
```
Optionally, you may “close” atx-style headers. This is purely cosmetic — you can use this if you think it looks better. The closing hashes don’t even need to match the number of hashes used to open the header. (The number of opening hashes determines the header level.) :
```
# This is an H1 #
## This is an H2 ##
### This is an H3 ######
```
### Blockquotes
Markdown uses email-style `>` characters for blockquoting. If you’re familiar with quoting passages of text in an email message, then you know how to create a blockquote in Markdown. It looks best if you hard wrap the text and put a `>` before every line:
```
> This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
> consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
> Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
>
> Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
> id sem consectetuer libero luctus adipiscing.
```
Markdown allows you to be lazy and only put the `>` before the first line of a hard-wrapped paragraph:
```
> This is a blockquote with two paragraphs. Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Aliquam hendrerit mi posuere lectus.
Vestibulum enim wisi, viverra nec, fringilla in, laoreet vitae, risus.
> Donec sit amet nisl. Aliquam semper ipsum sit amet velit. Suspendisse
id sem consectetuer libero luctus adipiscing.
```
Blockquotes can be nested (i.e. a blockquote-in-a-blockquote) by adding additional levels of `>`:
```
> This is the first level of quoting.
>
> > This is nested blockquote.
>
> Back to the first level.
```
Blockquotes can contain other Markdown elements, including headers, lists, and code blocks:
```
> ## This is a header.
>
> 1. This is the first list item.
> 2. This is the second list item.
>
> Here's some example code:
>
> return shell_exec("echo $input | $markdown_script");
```
Any decent text editor should make email-style quoting easy. For example, with BBEdit, you can make a selection and choose Increase Quote Level from the Text menu.
### Lists
Markdown supports ordered (numbered) and unordered (bulleted) lists.
Unordered lists use asterisks, pluses, and hyphens — interchangably — as list markers:
```
* Red
* Green
* Blue
```
is equivalent to:
```
+ Red
+ Green
+ Blue
```
and:
```
- Red
- Green
- Blue
```
Ordered lists use numbers followed by periods:
```
1. Bird
2. McHale
3. Parish
```
It’s important to note that the actual numbers you use to mark the list have no effect on the HTML output Markdown produces. The HTML Markdown produces from the above list is:
```
<ol>
<li>Bird</li>
<li>McHale</li>
<li>Parish</li>
</ol>
```
If you instead wrote the list in Markdown like this:
```
1. Bird
1. McHale
1. Parish
```
or even:
```
3. Bird
1. McHale
8. Parish
```
you’d get the exact same HTML output. The point is, if you want to, you can use ordinal numbers in your ordered Markdown lists, so that the numbers in your source match the numbers in your published HTML. But if you want to be lazy, you don’t have to.
If you do use lazy list numbering, however, you should still start the list with the number 1. At some point in the future, Markdown may support starting ordered lists at an arbitrary number.
List markers typically start at the left margin, but may be indented by up to three spaces. List markers must be followed by one or more spaces or a tab.
To make lists look nice, you can wrap items with hanging indents:
```
* Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
viverra nec, fringilla in, laoreet vitae, risus.
* Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
Suspendisse id sem consectetuer libero luctus adipiscing.
```
But if you want to be lazy, you don’t have to:
```
* Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Aliquam hendrerit mi posuere lectus. Vestibulum enim wisi,
viverra nec, fringilla in, laoreet vitae, risus.
* Donec sit amet nisl. Aliquam semper ipsum sit amet velit.
Suspendisse id sem consectetuer libero luctus adipiscing.
```
If list items are separated by blank lines, Markdown will wrap the items in `<p>` tags in the HTML output. For example, this input:
```
* Bird
* Magic
```
will turn into:
```
<ul>
<li>Bird</li>
<li>Magic</li>
</ul>
```
But this:
```
* Bird
* Magic
```
will turn into:
```
<ul>
<li><p>Bird</p></li>
<li><p>Magic</p></li>
</ul>
```
List items may consist of multiple paragraphs. Each subsequent paragraph in a list item must be indented by either 4 spaces or one tab:
```
1. This is a list item with two paragraphs. Lorem ipsum dolor
sit amet, consectetuer adipiscing elit. Aliquam hendrerit
mi posuere lectus.
Vestibulum enim wisi, viverra nec, fringilla in, laoreet
vitae, risus. Donec sit amet nisl. Aliquam semper ipsum
sit amet velit.
2. Suspendisse id sem consectetuer libero luctus adipiscing.
```
It looks nice if you indent every line of the subsequent paragraphs, but here again, Markdown will allow you to be lazy:
```
* This is a list item with two paragraphs.
This is the second paragraph in the list item. You're
only required to indent the first line. Lorem ipsum dolor
sit amet, consectetuer adipiscing elit.
* Another item in the same list.
```
To put a blockquote within a list item, the blockquote’s `>` delimiters need to be indented:
```
* A list item with a blockquote:
> This is a blockquote
> inside a list item.
```
To put a code block within a list item, the code block needs to be indented *twice* — 8 spaces or two tabs:
```
* A list item with a code block:
<code goes here>
```
It’s worth noting that it’s possible to trigger an ordered list by accident, by writing something like this:
```
1986. What a great season.
```
In other words, a *number-period-space* sequence at the beginning of a line. To avoid this, you can backslash-escape the period:
```
1986\. What a great season.
```
### Code Blocks
Pre-formatted code blocks are used for writing about programming or markup source code. Rather than forming normal paragraphs, the lines of a code block are interpreted literally. Markdown wraps a code block in both `<pre>` and `<code>` tags.
To produce a code block in Markdown, simply indent every line of the block by at least 4 spaces or 1 tab. For example, given this input:
```
This is a normal paragraph:
This is a code block.
```
Markdown will generate:
```
<p>This is a normal paragraph:</p>
<pre><code>This is a code block.
</code></pre>
```
One level of indentation — 4 spaces or 1 tab — is removed from each line of the code block. For example, this:
```
Here is an example of AppleScript:
tell application "Foo"
beep
end tell
```
will turn into:
```
<p>Here is an example of AppleScript:</p>
<pre><code>tell application "Foo"
beep
end tell
</code></pre>
```
A code block continues until it reaches a line that is not indented (or the end of the article).
Within a code block, ampersands (`&`) and angle brackets (`<` and `>`) are automatically converted into HTML entities. This makes it very easy to include example HTML source code using Markdown — just paste it and indent it, and Markdown will handle the hassle of encoding the ampersands and angle brackets. For example, this:
```
<div class="footer">
© 2004 Foo Corporation
</div>
```
will turn into:
```
<pre><code><div class="footer">
&copy; 2004 Foo Corporation
</div>
</code></pre>
```
Regular Markdown syntax is not processed within code blocks. E.g., asterisks are just literal asterisks within a code block. This means it’s also easy to use Markdown to write about Markdown’s own syntax.
### Horizontal Rules
You can produce a horizontal rule tag (`<hr />`) by placing three or more hyphens, asterisks, or underscores on a line by themselves. If you wish, you may use spaces between the hyphens or asterisks. Each of the following lines will produce a horizontal rule:
```
* * *
***
*****
- - -
---------------------------------------
```
Span Elements
-------------
### Links
Markdown supports two style of links: *inline* and *reference*.
In both styles, the link text is delimited by [square brackets].
To create an inline link, use a set of regular parentheses immediately after the link text’s closing square bracket. Inside the parentheses, put the URL where you want the link to point, along with an *optional* title for the link, surrounded in quotes. For example:
```
This is [an example](http://example.com/ "Title") inline link.
[This link](http://example.net/) has no title attribute.
```
Will produce:
```
<p>This is <a href="http://example.com/" title="Title">
an example</a> inline link.</p>
<p><a href="http://example.net/">This link</a> has no
title attribute.</p>
```
If you’re referring to a local resource on the same server, you can use relative paths:
```
See my [About](/about/) page for details.
```
Reference-style links use a second set of square brackets, inside which you place a label of your choosing to identify the link:
```
This is [an example][id] reference-style link.
```
You can optionally use a space to separate the sets of brackets:
```
This is [an example] [id] reference-style link.
```
Then, anywhere in the document, you define your link label like this, on a line by itself:
```
[id]: http://example.com/ "Optional Title Here"
```
That is:
* Square brackets containing the link identifier (optionally indented from the left margin using up to three spaces);
* followed by a colon;
* followed by one or more spaces (or tabs);
* followed by the URL for the link;
* optionally followed by a title attribute for the link, enclosed in double or single quotes, or enclosed in parentheses.
The following three link definitions are equivalent:
```
[foo]: http://example.com/ "Optional Title Here"
[foo]: http://example.com/ 'Optional Title Here'
[foo]: http://example.com/ (Optional Title Here)
```
**Note:** There is a known bug in Markdown.pl 1.0.1 which prevents single quotes from being used to delimit link titles.
The link URL may, optionally, be surrounded by angle brackets:
```
[id]: <http://example.com/> "Optional Title Here"
```
You can put the title attribute on the next line and use extra spaces or tabs for padding, which tends to look better with longer URLs:
```
[id]: http://example.com/longish/path/to/resource/here
"Optional Title Here"
```
Link definitions are only used for creating links during Markdown processing, and are stripped from your document in the HTML output.
Link definition names may consist of letters, numbers, spaces, and punctuation — but they are *not* case sensitive. E.g. these two links:
```
[link text][a]
[link text][A]
```
are equivalent.
The *implicit link name* shortcut allows you to omit the name of the link, in which case the link text itself is used as the name. Just use an empty set of square brackets — e.g., to link the word “Google” to the google.com web site, you could simply write:
```
[Google][]
```
And then define the link:
```
[Google]: http://google.com/
```
Because link names may contain spaces, this shortcut even works for multiple words in the link text:
```
Visit [Daring Fireball][] for more information.
```
And then define the link:
```
[Daring Fireball]: http://daringfireball.net/
```
Link definitions can be placed anywhere in your Markdown document. I tend to put them immediately after each paragraph in which they’re used, but if you want, you can put them all at the end of your document, sort of like footnotes.
Here’s an example of reference links in action:
```
I get 10 times more traffic from [Google] [1] than from
[Yahoo] [2] or [MSN] [3].
[1]: http://google.com/ "Google"
[2]: http://search.yahoo.com/ "Yahoo Search"
[3]: http://search.msn.com/ "MSN Search"
```
Using the implicit link name shortcut, you could instead write:
```
I get 10 times more traffic from [Google][] than from
[Yahoo][] or [MSN][].
[google]: http://google.com/ "Google"
[yahoo]: http://search.yahoo.com/ "Yahoo Search"
[msn]: http://search.msn.com/ "MSN Search"
```
Both of the above examples will produce the following HTML output:
```
<p>I get 10 times more traffic from <a href="http://google.com/"
title="Google">Google</a> than from
<a href="http://search.yahoo.com/" title="Yahoo Search">Yahoo</a>
or <a href="http://search.msn.com/" title="MSN Search">MSN</a>.</p>
```
For comparison, here is the same paragraph written using Markdown’s inline link style:
```
I get 10 times more traffic from [Google](http://google.com/ "Google")
than from [Yahoo](http://search.yahoo.com/ "Yahoo Search") or
[MSN](http://search.msn.com/ "MSN Search").
```
The point of reference-style links is not that they’re easier to write. The point is that with reference-style links, your document source is vastly more readable. Compare the above examples: using reference-style links, the paragraph itself is only 81 characters long; with inline-style links, it’s 176 characters; and as raw HTML, it’s 234 characters. In the raw HTML, there’s more markup than there is text.
With Markdown’s reference-style links, a source document much more closely resembles the final output, as rendered in a browser. By allowing you to move the markup-related metadata out of the paragraph, you can add links without interrupting the narrative flow of your prose.
### Emphasis
Markdown treats asterisks (`*`) and underscores (`_`) as indicators of emphasis. Text wrapped with one `*` or `_` will be wrapped with an HTML `<em>` tag; double `*`’s or `_`’s will be wrapped with an HTML `<strong>` tag. E.g., this input:
```
*single asterisks*
_single underscores_
**double asterisks**
__double underscores__
```
will produce:
```
<em>single asterisks</em>
<em>single underscores</em>
<strong>double asterisks</strong>
<strong>double underscores</strong>
```
You can use whichever style you prefer; the lone restriction is that the same character must be used to open and close an emphasis span.
Emphasis can be used in the middle of a word:
```
un*frigging*believable
```
But if you surround an `*` or `_` with spaces, it’ll be treated as a literal asterisk or underscore.
To produce a literal asterisk or underscore at a position where it would otherwise be used as an emphasis delimiter, you can backslash escape it:
```
\*this text is surrounded by literal asterisks\*
```
### Code
To indicate a span of code, wrap it with backtick quotes (```). Unlike a pre-formatted code block, a code span indicates code within a normal paragraph. For example:
```
Use the `printf()` function.
```
will produce:
```
<p>Use the <code>printf()</code> function.</p>
```
To include a literal backtick character within a code span, you can use multiple backticks as the opening and closing delimiters:
```
``There is a literal backtick (`) here.``
```
which will produce this:
```
<p><code>There is a literal backtick (`) here.</code></p>
```
The backtick delimiters surrounding a code span may include spaces — one after the opening, one before the closing. This allows you to place literal backtick characters at the beginning or end of a code span:
```
A single backtick in a code span: `` ` ``
A backtick-delimited string in a code span: `` `foo` ``
```
will produce:
```
<p>A single backtick in a code span: <code>`</code></p>
<p>A backtick-delimited string in a code span: <code>`foo`</code></p>
```
With a code span, ampersands and angle brackets are encoded as HTML entities automatically, which makes it easy to include example HTML tags. Markdown will turn this:
```
Please don't use any `<blink>` tags.
```
into:
```
<p>Please don't use any <code><blink></code> tags.</p>
```
You can write this:
```
`—` is the decimal-encoded equivalent of `—`.
```
to produce:
```
<p><code>&#8212;</code> is the decimal-encoded
equivalent of <code>&mdash;</code>.</p>
```
### Images
Admittedly, it’s fairly difficult to devise a “natural” syntax for placing images into a plain text document format.
Markdown uses an image syntax that is intended to resemble the syntax for links, allowing for two styles: *inline* and *reference*.
Inline image syntax looks like this:
```


```
That is:
* An exclamation mark: `!`;
* followed by a set of square brackets, containing the `alt` attribute text for the image;
* followed by a set of parentheses, containing the URL or path to the image, and an optional `title` attribute enclosed in double or single quotes.
Reference-style image syntax looks like this:
```
![Alt text][id]
```
Where “id” is the name of a defined image reference. Image references are defined using syntax identical to link references:
```
[id]: url/to/image "Optional title attribute"
```
As of this writing, Markdown has no syntax for specifying the dimensions of an image; if this is important to you, you can simply use regular HTML `<img>` tags.
Miscellaneous
-------------
### Automatic Links
Markdown supports a shortcut style for creating “automatic” links for URLs and email addresses: simply surround the URL or email address with angle brackets. What this means is that if you want to show the actual text of a URL or email address, and also have it be a clickable link, you can do this:
```
<http://example.com/>
```
Markdown will turn this into:
```
<a href="http://example.com/">http://example.com/</a>
```
Automatic links for email addresses work similarly, except that Markdown will also perform a bit of randomized decimal and hex entity-encoding to help obscure your address from address-harvesting spambots. For example, Markdown will turn this:
```
<[email protected]>
```
into something like this:
```
<a href="mailto:addre
ss@example.co
m">address@exa
mple.com</a>
```
which will render in a browser as a clickable link to “[email protected]”.
(This sort of entity-encoding trick will indeed fool many, if not most, address-harvesting bots, but it definitely won’t fool all of them. It’s better than nothing, but an address published in this way will probably eventually start receiving spam.)
### Backslash Escapes
Markdown allows you to use backslash escapes to generate literal characters which would otherwise have special meaning in Markdown’s formatting syntax. For example, if you wanted to surround a word with literal asterisks (instead of an HTML `<em>` tag), you can use backslashes before the asterisks, like this:
```
\*literal asterisks\*
```
Markdown provides backslash escapes for the following characters:
```
\ backslash
` backtick
* asterisk
_ underscore
{} curly braces
[] square brackets
() parentheses
# hash mark
+ plus sign
- minus sign (hyphen)
. dot
! exclamation mark
```
| programming_docs |
godot Godot Engine Godot Engine
============
Welcome to the official documentation of [Godot Engine](https://godotengine.org), the free and open source community-driven 2D and 3D game engine! If you are new to this documentation, we recommend that you read the [introduction page](https://docs.godotengine.org/en/3.5/about/introduction.html#doc-about-intro) to get an overview of what this documentation has to offer.
The table of contents below and in the sidebar should let you easily access the documentation for your topic of interest. You can also use the search function in the top left corner.
You can also [download an HTML copy](https://nightly.link/godotengine/godot-docs/workflows/build_offline_docs/master/godot-docs-html-stable.zip) for offline reading (updated every Monday). Extract the ZIP archive then open the top-level `index.html` in a web browser.
Note
Godot Engine is an open source project developed by a community of volunteers. The documentation team can always use your feedback and help to improve the tutorials and class reference. If you don't understand something, or cannot find what you are looking for in the docs, help us make the documentation better by letting us know!
Submit an issue or pull request on the [GitHub repository](https://github.com/godotengine/godot-docs/issues), help us [translate the documentation](https://hosted.weblate.org/engage/godot-engine/) into your language, or talk to us on the `#documentation` channel on the [Godot Contributors Chat](https://chat.godotengine.org/)!
**[](https://hosted.weblate.org/engage/godot-engine/?utm_source=widget)**
The main documentation for the site is organized into the following sections:
General
* [About](https://docs.godotengine.org/en/3.5/about/index.html)
Getting started
* [Introduction](getting_started/introduction/index)
* [Step by step](getting_started/step_by_step/index)
* [Your first 2D game](getting_started/first_2d_game/index)
* [Your first 3D game](getting_started/first_3d_game/index)
Tutorials
* [2D](https://docs.godotengine.org/en/3.5/tutorials/2d/index.html)
* [3D](https://docs.godotengine.org/en/3.5/tutorials/3d/index.html)
* [Animation](https://docs.godotengine.org/en/3.5/tutorials/animation/index.html)
* [Assets pipeline](https://docs.godotengine.org/en/3.5/tutorials/assets_pipeline/index.html)
* [Audio](https://docs.godotengine.org/en/3.5/tutorials/audio/index.html)
* [Best practices](https://docs.godotengine.org/en/3.5/tutorials/best_practices/index.html)
* [Editor manual](https://docs.godotengine.org/en/3.5/tutorials/editor/index.html)
* [Export](https://docs.godotengine.org/en/3.5/tutorials/export/index.html)
* [Internationalization](https://docs.godotengine.org/en/3.5/tutorials/i18n/index.html)
* [Inputs](https://docs.godotengine.org/en/3.5/tutorials/inputs/index.html)
* [Input and Output (I/O)](https://docs.godotengine.org/en/3.5/tutorials/io/index.html)
* [Math](https://docs.godotengine.org/en/3.5/tutorials/math/index.html)
* [Navigation](https://docs.godotengine.org/en/3.5/tutorials/navigation/index.html)
* [Networking](https://docs.godotengine.org/en/3.5/tutorials/networking/index.html)
* [Optimization](https://docs.godotengine.org/en/3.5/tutorials/performance/index.html)
* [Physics](https://docs.godotengine.org/en/3.5/tutorials/physics/index.html)
* [Platform-specific](https://docs.godotengine.org/en/3.5/tutorials/platform/index.html)
* [Plugins](https://docs.godotengine.org/en/3.5/tutorials/plugins/index.html)
* [Rendering](https://docs.godotengine.org/en/3.5/tutorials/rendering/index.html)
* [Scripting](https://docs.godotengine.org/en/3.5/tutorials/scripting/index.html)
* [Shaders](https://docs.godotengine.org/en/3.5/tutorials/shaders/index.html)
* [User Interface (UI)](https://docs.godotengine.org/en/3.5/tutorials/ui/index.html)
* [XR (AR/VR)](https://docs.godotengine.org/en/3.5/tutorials/vr/index.html)
Development
* [Compiling](https://docs.godotengine.org/en/3.5/development/compiling/index.html)
* [Engine development](https://docs.godotengine.org/en/3.5/development/cpp/index.html)
* [Editor development](https://docs.godotengine.org/en/3.5/development/editor/index.html)
* [Godot file formats](https://docs.godotengine.org/en/3.5/development/file_formats/index.html)
Community
* [Contributing](https://docs.godotengine.org/en/3.5/community/contributing/index.html)
* [Asset Library](https://docs.godotengine.org/en/3.5/community/asset_library/index.html)
* [Community channels](https://docs.godotengine.org/en/3.5/community/channels.html)
* [Tutorials and resources](https://docs.godotengine.org/en/3.5/community/tutorials.html)
Class reference
* [Godot API](classes/index)
godot Camera Camera
======
**Inherits:** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
**Inherited By:** [ARVRCamera](class_arvrcamera#class-arvrcamera), [ClippedCamera](class_clippedcamera#class-clippedcamera), [InterpolatedCamera](class_interpolatedcamera#class-interpolatedcamera)
Camera node, displays from a point of view.
Description
-----------
Camera is a special node that displays what is visible from its current location. Cameras register themselves in the nearest [Viewport](class_viewport#class-viewport) node (when ascending the tree). Only one camera can be active per viewport. If no viewport is available ascending the tree, the camera will register in the global viewport. In other words, a camera just provides 3D display capabilities to a [Viewport](class_viewport#class-viewport), and, without one, a scene registered in that [Viewport](class_viewport#class-viewport) (or higher viewports) can't be displayed.
Tutorials
---------
* [Third Person Shooter Demo](https://godotengine.org/asset-library/asset/678)
Properties
----------
| | | |
| --- | --- | --- |
| [int](class_int#class-int) | [cull\_mask](#class-camera-property-cull-mask) | `1048575` |
| [bool](class_bool#class-bool) | [current](#class-camera-property-current) | `false` |
| [DopplerTracking](#enum-camera-dopplertracking) | [doppler\_tracking](#class-camera-property-doppler-tracking) | `0` |
| [Environment](class_environment#class-environment) | [environment](#class-camera-property-environment) | |
| [float](class_float#class-float) | [far](#class-camera-property-far) | `100.0` |
| [float](class_float#class-float) | [fov](#class-camera-property-fov) | `70.0` |
| [Vector2](class_vector2#class-vector2) | [frustum\_offset](#class-camera-property-frustum-offset) | `Vector2( 0, 0 )` |
| [float](class_float#class-float) | [h\_offset](#class-camera-property-h-offset) | `0.0` |
| [KeepAspect](#enum-camera-keepaspect) | [keep\_aspect](#class-camera-property-keep-aspect) | `1` |
| [float](class_float#class-float) | [near](#class-camera-property-near) | `0.05` |
| [Projection](#enum-camera-projection) | [projection](#class-camera-property-projection) | `0` |
| [float](class_float#class-float) | [size](#class-camera-property-size) | `1.0` |
| [float](class_float#class-float) | [v\_offset](#class-camera-property-v-offset) | `0.0` |
Methods
-------
| | |
| --- | --- |
| void | [clear\_current](#class-camera-method-clear-current) **(** [bool](class_bool#class-bool) enable\_next=true **)** |
| [RID](class_rid#class-rid) | [get\_camera\_rid](#class-camera-method-get-camera-rid) **(** **)** const |
| [Transform](class_transform#class-transform) | [get\_camera\_transform](#class-camera-method-get-camera-transform) **(** **)** const |
| [bool](class_bool#class-bool) | [get\_cull\_mask\_bit](#class-camera-method-get-cull-mask-bit) **(** [int](class_int#class-int) layer **)** const |
| [Array](class_array#class-array) | [get\_frustum](#class-camera-method-get-frustum) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_position\_behind](#class-camera-method-is-position-behind) **(** [Vector3](class_vector3#class-vector3) world\_point **)** const |
| void | [make\_current](#class-camera-method-make-current) **(** **)** |
| [Vector3](class_vector3#class-vector3) | [project\_local\_ray\_normal](#class-camera-method-project-local-ray-normal) **(** [Vector2](class_vector2#class-vector2) screen\_point **)** const |
| [Vector3](class_vector3#class-vector3) | [project\_position](#class-camera-method-project-position) **(** [Vector2](class_vector2#class-vector2) screen\_point, [float](class_float#class-float) z\_depth **)** const |
| [Vector3](class_vector3#class-vector3) | [project\_ray\_normal](#class-camera-method-project-ray-normal) **(** [Vector2](class_vector2#class-vector2) screen\_point **)** const |
| [Vector3](class_vector3#class-vector3) | [project\_ray\_origin](#class-camera-method-project-ray-origin) **(** [Vector2](class_vector2#class-vector2) screen\_point **)** const |
| void | [set\_cull\_mask\_bit](#class-camera-method-set-cull-mask-bit) **(** [int](class_int#class-int) layer, [bool](class_bool#class-bool) enable **)** |
| void | [set\_frustum](#class-camera-method-set-frustum) **(** [float](class_float#class-float) size, [Vector2](class_vector2#class-vector2) offset, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far **)** |
| void | [set\_orthogonal](#class-camera-method-set-orthogonal) **(** [float](class_float#class-float) size, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far **)** |
| void | [set\_perspective](#class-camera-method-set-perspective) **(** [float](class_float#class-float) fov, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far **)** |
| [Vector2](class_vector2#class-vector2) | [unproject\_position](#class-camera-method-unproject-position) **(** [Vector3](class_vector3#class-vector3) world\_point **)** const |
Enumerations
------------
enum **Projection**:
* **PROJECTION\_PERSPECTIVE** = **0** --- Perspective projection. Objects on the screen becomes smaller when they are far away.
* **PROJECTION\_ORTHOGONAL** = **1** --- Orthogonal projection, also known as orthographic projection. Objects remain the same size on the screen no matter how far away they are.
* **PROJECTION\_FRUSTUM** = **2** --- Frustum projection. This mode allows adjusting [frustum\_offset](#class-camera-property-frustum-offset) to create "tilted frustum" effects.
enum **KeepAspect**:
* **KEEP\_WIDTH** = **0** --- Preserves the horizontal aspect ratio; also known as Vert- scaling. This is usually the best option for projects running in portrait mode, as taller aspect ratios will benefit from a wider vertical FOV.
* **KEEP\_HEIGHT** = **1** --- Preserves the vertical aspect ratio; also known as Hor+ scaling. This is usually the best option for projects running in landscape mode, as wider aspect ratios will automatically benefit from a wider horizontal FOV.
enum **DopplerTracking**:
* **DOPPLER\_TRACKING\_DISABLED** = **0** --- Disables [Doppler effect](https://en.wikipedia.org/wiki/Doppler_effect) simulation (default).
* **DOPPLER\_TRACKING\_IDLE\_STEP** = **1** --- Simulate [Doppler effect](https://en.wikipedia.org/wiki/Doppler_effect) by tracking positions of objects that are changed in `_process`. Changes in the relative velocity of this camera compared to those objects affect how audio is perceived (changing the audio's [AudioStreamPlayer3D.pitch\_scale](class_audiostreamplayer3d#class-audiostreamplayer3d-property-pitch-scale)).
* **DOPPLER\_TRACKING\_PHYSICS\_STEP** = **2** --- Simulate [Doppler effect](https://en.wikipedia.org/wiki/Doppler_effect) by tracking positions of objects that are changed in `_physics_process`. Changes in the relative velocity of this camera compared to those objects affect how audio is perceived (changing the audio's [AudioStreamPlayer3D.pitch\_scale](class_audiostreamplayer3d#class-audiostreamplayer3d-property-pitch-scale)).
Property Descriptions
---------------------
### [int](class_int#class-int) cull\_mask
| | |
| --- | --- |
| *Default* | `1048575` |
| *Setter* | set\_cull\_mask(value) |
| *Getter* | get\_cull\_mask() |
The culling mask that describes which 3D render layers are rendered by this camera.
### [bool](class_bool#class-bool) current
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_current(value) |
| *Getter* | is\_current() |
If `true`, the ancestor [Viewport](class_viewport#class-viewport) is currently using this camera.
If multiple cameras are in the scene, one will always be made current. For example, if two `Camera` nodes are present in the scene and only one is current, setting one camera's [current](#class-camera-property-current) to `false` will cause the other camera to be made current.
### [DopplerTracking](#enum-camera-dopplertracking) doppler\_tracking
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_doppler\_tracking(value) |
| *Getter* | get\_doppler\_tracking() |
If not [DOPPLER\_TRACKING\_DISABLED](#class-camera-constant-doppler-tracking-disabled), this camera will simulate the [Doppler effect](https://en.wikipedia.org/wiki/Doppler_effect) for objects changed in particular `_process` methods. The Doppler effect is only simulated for [AudioStreamPlayer3D](class_audiostreamplayer3d#class-audiostreamplayer3d) nodes that have [AudioStreamPlayer3D.doppler\_tracking](class_audiostreamplayer3d#class-audiostreamplayer3d-property-doppler-tracking) set to a value other than [AudioStreamPlayer3D.DOPPLER\_TRACKING\_DISABLED](class_audiostreamplayer3d#class-audiostreamplayer3d-constant-doppler-tracking-disabled).
**Note:** To toggle the Doppler effect preview in the editor, use the Perspective menu in the top-left corner of the 3D viewport and toggle **Enable Doppler**.
### [Environment](class_environment#class-environment) environment
| | |
| --- | --- |
| *Setter* | set\_environment(value) |
| *Getter* | get\_environment() |
The [Environment](class_environment#class-environment) to use for this camera.
### [float](class_float#class-float) far
| | |
| --- | --- |
| *Default* | `100.0` |
| *Setter* | set\_zfar(value) |
| *Getter* | get\_zfar() |
The distance to the far culling boundary for this camera relative to its local Z axis.
### [float](class_float#class-float) fov
| | |
| --- | --- |
| *Default* | `70.0` |
| *Setter* | set\_fov(value) |
| *Getter* | get\_fov() |
The camera's field of view angle (in degrees). Only applicable in perspective mode. Since [keep\_aspect](#class-camera-property-keep-aspect) locks one axis, `fov` sets the other axis' field of view angle.
For reference, the default vertical field of view value (`70.0`) is equivalent to a horizontal FOV of:
* ~86.07 degrees in a 4:3 viewport
* ~96.50 degrees in a 16:10 viewport
* ~102.45 degrees in a 16:9 viewport
* ~117.06 degrees in a 21:9 viewport
### [Vector2](class_vector2#class-vector2) frustum\_offset
| | |
| --- | --- |
| *Default* | `Vector2( 0, 0 )` |
| *Setter* | set\_frustum\_offset(value) |
| *Getter* | get\_frustum\_offset() |
The camera's frustum offset. This can be changed from the default to create "tilted frustum" effects such as [Y-shearing](https://zdoom.org/wiki/Y-shearing).
**Note:** Only effective if [projection](#class-camera-property-projection) is [PROJECTION\_FRUSTUM](#class-camera-constant-projection-frustum).
### [float](class_float#class-float) h\_offset
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_h\_offset(value) |
| *Getter* | get\_h\_offset() |
The horizontal (X) offset of the camera viewport.
### [KeepAspect](#enum-camera-keepaspect) keep\_aspect
| | |
| --- | --- |
| *Default* | `1` |
| *Setter* | set\_keep\_aspect\_mode(value) |
| *Getter* | get\_keep\_aspect\_mode() |
The axis to lock during [fov](#class-camera-property-fov)/[size](#class-camera-property-size) adjustments. Can be either [KEEP\_WIDTH](#class-camera-constant-keep-width) or [KEEP\_HEIGHT](#class-camera-constant-keep-height).
### [float](class_float#class-float) near
| | |
| --- | --- |
| *Default* | `0.05` |
| *Setter* | set\_znear(value) |
| *Getter* | get\_znear() |
The distance to the near culling boundary for this camera relative to its local Z axis.
### [Projection](#enum-camera-projection) projection
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_projection(value) |
| *Getter* | get\_projection() |
The camera's projection mode. In [PROJECTION\_PERSPECTIVE](#class-camera-constant-projection-perspective) mode, objects' Z distance from the camera's local space scales their perceived size.
### [float](class_float#class-float) size
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_size(value) |
| *Getter* | get\_size() |
The camera's size in meters measured as the diameter of the width or height, depending on [keep\_aspect](#class-camera-property-keep-aspect). Only applicable in orthogonal and frustum modes.
### [float](class_float#class-float) v\_offset
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_v\_offset(value) |
| *Getter* | get\_v\_offset() |
The vertical (Y) offset of the camera viewport.
Method Descriptions
-------------------
### void clear\_current ( [bool](class_bool#class-bool) enable\_next=true )
If this is the current camera, remove it from being current. If `enable_next` is `true`, request to make the next camera current, if any.
### [RID](class_rid#class-rid) get\_camera\_rid ( ) const
Returns the camera's RID from the [VisualServer](class_visualserver#class-visualserver).
### [Transform](class_transform#class-transform) get\_camera\_transform ( ) const
Returns the transform of the camera plus the vertical ([v\_offset](#class-camera-property-v-offset)) and horizontal ([h\_offset](#class-camera-property-h-offset)) offsets; and any other adjustments made to the position and orientation of the camera by subclassed cameras such as [ClippedCamera](class_clippedcamera#class-clippedcamera), [InterpolatedCamera](class_interpolatedcamera#class-interpolatedcamera) and [ARVRCamera](class_arvrcamera#class-arvrcamera).
### [bool](class_bool#class-bool) get\_cull\_mask\_bit ( [int](class_int#class-int) layer ) const
Returns `true` if the given `layer` in the [cull\_mask](#class-camera-property-cull-mask) is enabled, `false` otherwise.
### [Array](class_array#class-array) get\_frustum ( ) const
Returns the camera's frustum planes in world space units as an array of [Plane](class_plane#class-plane)s in the following order: near, far, left, top, right, bottom. Not to be confused with [frustum\_offset](#class-camera-property-frustum-offset).
### [bool](class_bool#class-bool) is\_position\_behind ( [Vector3](class_vector3#class-vector3) world\_point ) const
Returns `true` if the given position is behind the camera.
**Note:** A position which returns `false` may still be outside the camera's field of view.
### void make\_current ( )
Makes this camera the current camera for the [Viewport](class_viewport#class-viewport) (see class description). If the camera node is outside the scene tree, it will attempt to become current once it's added.
### [Vector3](class_vector3#class-vector3) project\_local\_ray\_normal ( [Vector2](class_vector2#class-vector2) screen\_point ) const
Returns a normal vector from the screen point location directed along the camera. Orthogonal cameras are normalized. Perspective cameras account for perspective, screen width/height, etc.
### [Vector3](class_vector3#class-vector3) project\_position ( [Vector2](class_vector2#class-vector2) screen\_point, [float](class_float#class-float) z\_depth ) const
Returns the 3D point in world space that maps to the given 2D coordinate in the [Viewport](class_viewport#class-viewport) rectangle on a plane that is the given `z_depth` distance into the scene away from the camera.
### [Vector3](class_vector3#class-vector3) project\_ray\_normal ( [Vector2](class_vector2#class-vector2) screen\_point ) const
Returns a normal vector in world space, that is the result of projecting a point on the [Viewport](class_viewport#class-viewport) rectangle by the inverse camera projection. This is useful for casting rays in the form of (origin, normal) for object intersection or picking.
### [Vector3](class_vector3#class-vector3) project\_ray\_origin ( [Vector2](class_vector2#class-vector2) screen\_point ) const
Returns a 3D position in world space, that is the result of projecting a point on the [Viewport](class_viewport#class-viewport) rectangle by the inverse camera projection. This is useful for casting rays in the form of (origin, normal) for object intersection or picking.
### void set\_cull\_mask\_bit ( [int](class_int#class-int) layer, [bool](class_bool#class-bool) enable )
Enables or disables the given `layer` in the [cull\_mask](#class-camera-property-cull-mask).
### void set\_frustum ( [float](class_float#class-float) size, [Vector2](class_vector2#class-vector2) offset, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far )
Sets the camera projection to frustum mode (see [PROJECTION\_FRUSTUM](#class-camera-constant-projection-frustum)), by specifying a `size`, an `offset`, and the `z_near` and `z_far` clip planes in world space units. See also [frustum\_offset](#class-camera-property-frustum-offset).
### void set\_orthogonal ( [float](class_float#class-float) size, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far )
Sets the camera projection to orthogonal mode (see [PROJECTION\_ORTHOGONAL](#class-camera-constant-projection-orthogonal)), by specifying a `size`, and the `z_near` and `z_far` clip planes in world space units. (As a hint, 2D games often use this projection, with values specified in pixels.)
### void set\_perspective ( [float](class_float#class-float) fov, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far )
Sets the camera projection to perspective mode (see [PROJECTION\_PERSPECTIVE](#class-camera-constant-projection-perspective)), by specifying a `fov` (field of view) angle in degrees, and the `z_near` and `z_far` clip planes in world space units.
### [Vector2](class_vector2#class-vector2) unproject\_position ( [Vector3](class_vector3#class-vector3) world\_point ) const
Returns the 2D coordinate in the [Viewport](class_viewport#class-viewport) rectangle that maps to the given 3D point in world space.
**Note:** When using this to position GUI elements over a 3D viewport, use [is\_position\_behind](#class-camera-method-is-position-behind) to prevent them from appearing if the 3D point is behind the camera:
```
# This code block is part of a script that inherits from Spatial.
# `control` is a reference to a node inheriting from Control.
control.visible = not get_viewport().get_camera().is_position_behind(global_transform.origin)
control.rect_position = get_viewport().get_camera().unproject_position(global_transform.origin)
```
| programming_docs |
godot CubeMesh CubeMesh
========
**Inherits:** [PrimitiveMesh](class_primitivemesh#class-primitivemesh) **<** [Mesh](class_mesh#class-mesh) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Generate an axis-aligned cuboid [PrimitiveMesh](class_primitivemesh#class-primitivemesh).
Description
-----------
Generate an axis-aligned cuboid [PrimitiveMesh](class_primitivemesh#class-primitivemesh).
The cube's UV layout is arranged in a 3×2 layout that allows texturing each face individually. To apply the same texture on all faces, change the material's UV property to `Vector3(3, 2, 1)`.
**Note:** When using a large textured `CubeMesh` (e.g. as a floor), you may stumble upon UV jittering issues depending on the camera angle. To solve this, increase [subdivide\_depth](#class-cubemesh-property-subdivide-depth), [subdivide\_height](#class-cubemesh-property-subdivide-height) and [subdivide\_width](#class-cubemesh-property-subdivide-width) until you no longer notice UV jittering.
Properties
----------
| | | |
| --- | --- | --- |
| [Vector3](class_vector3#class-vector3) | [size](#class-cubemesh-property-size) | `Vector3( 2, 2, 2 )` |
| [int](class_int#class-int) | [subdivide\_depth](#class-cubemesh-property-subdivide-depth) | `0` |
| [int](class_int#class-int) | [subdivide\_height](#class-cubemesh-property-subdivide-height) | `0` |
| [int](class_int#class-int) | [subdivide\_width](#class-cubemesh-property-subdivide-width) | `0` |
Property Descriptions
---------------------
### [Vector3](class_vector3#class-vector3) size
| | |
| --- | --- |
| *Default* | `Vector3( 2, 2, 2 )` |
| *Setter* | set\_size(value) |
| *Getter* | get\_size() |
Size of the cuboid mesh.
### [int](class_int#class-int) subdivide\_depth
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_subdivide\_depth(value) |
| *Getter* | get\_subdivide\_depth() |
Number of extra edge loops inserted along the Z axis.
### [int](class_int#class-int) subdivide\_height
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_subdivide\_height(value) |
| *Getter* | get\_subdivide\_height() |
Number of extra edge loops inserted along the Y axis.
### [int](class_int#class-int) subdivide\_width
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_subdivide\_width(value) |
| *Getter* | get\_subdivide\_width() |
Number of extra edge loops inserted along the X axis.
godot VisualScriptGlobalConstant VisualScriptGlobalConstant
==========================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A Visual Script node returning a constant from [@GlobalScope](class_%40globalscope#class-globalscope).
Description
-----------
A Visual Script node returning a constant from [@GlobalScope](class_%40globalscope#class-globalscope).
Properties
----------
| | | |
| --- | --- | --- |
| [int](class_int#class-int) | [constant](#class-visualscriptglobalconstant-property-constant) | `0` |
Property Descriptions
---------------------
### [int](class_int#class-int) constant
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_global\_constant(value) |
| *Getter* | get\_global\_constant() |
The constant to be used.
godot bool bool
====
Boolean built-in type.
Description
-----------
Boolean is a built-in type. There are two boolean values: `true` and `false`. You can think of it as a switch with on or off (1 or 0) setting. Booleans are used in programming for logic in condition statements, like `if` statements.
Booleans can be directly used in `if` statements. The code below demonstrates this on the `if can_shoot:` line. You don't need to use `== true`, you only need `if can_shoot:`. Similarly, use `if not can_shoot:` rather than `== false`.
```
var can_shoot = true
func shoot():
if can_shoot:
pass # Perform shooting actions here.
```
The following code will only create a bullet if both conditions are met: action "shoot" is pressed and if `can_shoot` is `true`.
**Note:** `Input.is_action_pressed("shoot")` is also a boolean that is `true` when "shoot" is pressed and `false` when "shoot" isn't pressed.
```
var can_shoot = true
func shoot():
if can_shoot and Input.is_action_pressed("shoot"):
create_bullet()
```
The following code will set `can_shoot` to `false` and start a timer. This will prevent player from shooting until the timer runs out. Next `can_shoot` will be set to `true` again allowing player to shoot once again.
```
var can_shoot = true
onready var cool_down = $CoolDownTimer
func shoot():
if can_shoot and Input.is_action_pressed("shoot"):
create_bullet()
can_shoot = false
cool_down.start()
func _on_CoolDownTimer_timeout():
can_shoot = true
```
Methods
-------
| | |
| --- | --- |
| [bool](#class-bool) | [bool](#class-bool-method-bool) **(** [int](class_int#class-int) from **)** |
| [bool](#class-bool) | [bool](#class-bool-method-bool) **(** [float](class_float#class-float) from **)** |
| [bool](#class-bool) | [bool](#class-bool-method-bool) **(** [String](class_string#class-string) from **)** |
Method Descriptions
-------------------
### [bool](#class-bool) bool ( [int](class_int#class-int) from )
Cast an [int](class_int#class-int) value to a boolean value, this method will return `false` if `0` is passed in, and `true` for all other ints.
* [bool](#class-bool) **bool** **(** [float](class_float#class-float) from **)**
Cast a [float](class_float#class-float) value to a boolean value, this method will return `false` if `0.0` is passed in, and `true` for all other floats.
* [bool](#class-bool) **bool** **(** [String](class_string#class-string) from **)**
Cast a [String](class_string#class-string) value to a boolean value, this method will return `false` if `""` is passed in, and `true` for all non-empty strings.
Examples: `bool("False")` returns `true`, `bool("")` returns `false`.
godot ScriptEditor ScriptEditor
============
**Inherits:** [PanelContainer](class_panelcontainer#class-panelcontainer) **<** [Container](class_container#class-container) **<** [Control](class_control#class-control) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Godot editor's script editor.
Description
-----------
**Note:** This class shouldn't be instantiated directly. Instead, access the singleton using [EditorInterface.get\_script\_editor](class_editorinterface#class-editorinterface-method-get-script-editor).
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [can\_drop\_data\_fw](#class-scripteditor-method-can-drop-data-fw) **(** [Vector2](class_vector2#class-vector2) point, [Variant](class_variant#class-variant) data, [Control](class_control#class-control) from **)** const |
| void | [drop\_data\_fw](#class-scripteditor-method-drop-data-fw) **(** [Vector2](class_vector2#class-vector2) point, [Variant](class_variant#class-variant) data, [Control](class_control#class-control) from **)** |
| [Script](class_script#class-script) | [get\_current\_script](#class-scripteditor-method-get-current-script) **(** **)** |
| [Variant](class_variant#class-variant) | [get\_drag\_data\_fw](#class-scripteditor-method-get-drag-data-fw) **(** [Vector2](class_vector2#class-vector2) point, [Control](class_control#class-control) from **)** |
| [Array](class_array#class-array) | [get\_open\_scripts](#class-scripteditor-method-get-open-scripts) **(** **)** const |
| void | [goto\_line](#class-scripteditor-method-goto-line) **(** [int](class_int#class-int) line\_number **)** |
| void | [open\_script\_create\_dialog](#class-scripteditor-method-open-script-create-dialog) **(** [String](class_string#class-string) base\_name, [String](class_string#class-string) base\_path **)** |
| void | [reload\_scripts](#class-scripteditor-method-reload-scripts) **(** **)** |
Signals
-------
### editor\_script\_changed ( [Script](class_script#class-script) script )
Emitted when user changed active script. Argument is a freshly activated [Script](class_script#class-script).
### script\_close ( [Script](class_script#class-script) script )
Emitted when editor is about to close the active script. Argument is a [Script](class_script#class-script) that is going to be closed.
Method Descriptions
-------------------
### [bool](class_bool#class-bool) can\_drop\_data\_fw ( [Vector2](class_vector2#class-vector2) point, [Variant](class_variant#class-variant) data, [Control](class_control#class-control) from ) const
### void drop\_data\_fw ( [Vector2](class_vector2#class-vector2) point, [Variant](class_variant#class-variant) data, [Control](class_control#class-control) from )
### [Script](class_script#class-script) get\_current\_script ( )
Returns a [Script](class_script#class-script) that is currently active in editor.
### [Variant](class_variant#class-variant) get\_drag\_data\_fw ( [Vector2](class_vector2#class-vector2) point, [Control](class_control#class-control) from )
### [Array](class_array#class-array) get\_open\_scripts ( ) const
Returns an array with all [Script](class_script#class-script) objects which are currently open in editor.
### void goto\_line ( [int](class_int#class-int) line\_number )
Goes to the specified line in the current script.
### void open\_script\_create\_dialog ( [String](class_string#class-string) base\_name, [String](class_string#class-string) base\_path )
Opens the script create dialog. The script will extend `base_name`. The file extension can be omitted from `base_path`. It will be added based on the selected scripting language.
### void reload\_scripts ( )
Reload all currently opened scripts from disk in case the file contents are newer.
godot PhysicalBone PhysicalBone
============
**Inherits:** [PhysicsBody](class_physicsbody#class-physicsbody) **<** [CollisionObject](class_collisionobject#class-collisionobject) **<** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Properties
----------
| | | |
| --- | --- | --- |
| [Transform](class_transform#class-transform) | [body\_offset](#class-physicalbone-property-body-offset) | `Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )` |
| [float](class_float#class-float) | [bounce](#class-physicalbone-property-bounce) | `0.0` |
| [float](class_float#class-float) | [friction](#class-physicalbone-property-friction) | `1.0` |
| [float](class_float#class-float) | [gravity\_scale](#class-physicalbone-property-gravity-scale) | `1.0` |
| [Transform](class_transform#class-transform) | [joint\_offset](#class-physicalbone-property-joint-offset) | `Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )` |
| [JointType](#enum-physicalbone-jointtype) | [joint\_type](#class-physicalbone-property-joint-type) | `0` |
| [float](class_float#class-float) | [mass](#class-physicalbone-property-mass) | `1.0` |
| [float](class_float#class-float) | [weight](#class-physicalbone-property-weight) | `9.8` |
Methods
-------
| | |
| --- | --- |
| void | [apply\_central\_impulse](#class-physicalbone-method-apply-central-impulse) **(** [Vector3](class_vector3#class-vector3) impulse **)** |
| void | [apply\_impulse](#class-physicalbone-method-apply-impulse) **(** [Vector3](class_vector3#class-vector3) position, [Vector3](class_vector3#class-vector3) impulse **)** |
| [int](class_int#class-int) | [get\_bone\_id](#class-physicalbone-method-get-bone-id) **(** **)** const |
| [bool](class_bool#class-bool) | [get\_simulate\_physics](#class-physicalbone-method-get-simulate-physics) **(** **)** |
| [bool](class_bool#class-bool) | [is\_simulating\_physics](#class-physicalbone-method-is-simulating-physics) **(** **)** |
| [bool](class_bool#class-bool) | [is\_static\_body](#class-physicalbone-method-is-static-body) **(** **)** |
Enumerations
------------
enum **JointType**:
* **JOINT\_TYPE\_NONE** = **0**
* **JOINT\_TYPE\_PIN** = **1**
* **JOINT\_TYPE\_CONE** = **2**
* **JOINT\_TYPE\_HINGE** = **3**
* **JOINT\_TYPE\_SLIDER** = **4**
* **JOINT\_TYPE\_6DOF** = **5**
Property Descriptions
---------------------
### [Transform](class_transform#class-transform) body\_offset
| | |
| --- | --- |
| *Default* | `Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )` |
| *Setter* | set\_body\_offset(value) |
| *Getter* | get\_body\_offset() |
### [float](class_float#class-float) bounce
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_bounce(value) |
| *Getter* | get\_bounce() |
### [float](class_float#class-float) friction
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_friction(value) |
| *Getter* | get\_friction() |
### [float](class_float#class-float) gravity\_scale
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_gravity\_scale(value) |
| *Getter* | get\_gravity\_scale() |
### [Transform](class_transform#class-transform) joint\_offset
| | |
| --- | --- |
| *Default* | `Transform( 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0 )` |
| *Setter* | set\_joint\_offset(value) |
| *Getter* | get\_joint\_offset() |
### [JointType](#enum-physicalbone-jointtype) joint\_type
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_joint\_type(value) |
| *Getter* | get\_joint\_type() |
### [float](class_float#class-float) mass
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_mass(value) |
| *Getter* | get\_mass() |
### [float](class_float#class-float) weight
| | |
| --- | --- |
| *Default* | `9.8` |
| *Setter* | set\_weight(value) |
| *Getter* | get\_weight() |
Method Descriptions
-------------------
### void apply\_central\_impulse ( [Vector3](class_vector3#class-vector3) impulse )
### void apply\_impulse ( [Vector3](class_vector3#class-vector3) position, [Vector3](class_vector3#class-vector3) impulse )
### [int](class_int#class-int) get\_bone\_id ( ) const
### [bool](class_bool#class-bool) get\_simulate\_physics ( )
### [bool](class_bool#class-bool) is\_simulating\_physics ( )
### [bool](class_bool#class-bool) is\_static\_body ( )
godot NavigationPolygon NavigationPolygon
=================
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A node that has methods to draw outlines or use indices of vertices to create navigation polygons.
Description
-----------
There are two ways to create polygons. Either by using the [add\_outline](#class-navigationpolygon-method-add-outline) method, or using the [add\_polygon](#class-navigationpolygon-method-add-polygon) method.
Using [add\_outline](#class-navigationpolygon-method-add-outline):
```
var polygon = NavigationPolygon.new()
var outline = PoolVector2Array([Vector2(0, 0), Vector2(0, 50), Vector2(50, 50), Vector2(50, 0)])
polygon.add_outline(outline)
polygon.make_polygons_from_outlines()
$NavigationPolygonInstance.navpoly = polygon
```
Using [add\_polygon](#class-navigationpolygon-method-add-polygon) and indices of the vertices array.
```
var polygon = NavigationPolygon.new()
var vertices = PoolVector2Array([Vector2(0, 0), Vector2(0, 50), Vector2(50, 50), Vector2(50, 0)])
polygon.set_vertices(vertices)
var indices = PoolIntArray([0, 1, 2, 3])
polygon.add_polygon(indices)
$NavigationPolygonInstance.navpoly = polygon
```
Tutorials
---------
* [2D Navigation Demo](https://godotengine.org/asset-library/asset/117)
Methods
-------
| | |
| --- | --- |
| void | [add\_outline](#class-navigationpolygon-method-add-outline) **(** [PoolVector2Array](class_poolvector2array#class-poolvector2array) outline **)** |
| void | [add\_outline\_at\_index](#class-navigationpolygon-method-add-outline-at-index) **(** [PoolVector2Array](class_poolvector2array#class-poolvector2array) outline, [int](class_int#class-int) index **)** |
| void | [add\_polygon](#class-navigationpolygon-method-add-polygon) **(** [PoolIntArray](class_poolintarray#class-poolintarray) polygon **)** |
| void | [clear\_outlines](#class-navigationpolygon-method-clear-outlines) **(** **)** |
| void | [clear\_polygons](#class-navigationpolygon-method-clear-polygons) **(** **)** |
| [NavigationMesh](class_navigationmesh#class-navigationmesh) | [get\_mesh](#class-navigationpolygon-method-get-mesh) **(** **)** |
| [PoolVector2Array](class_poolvector2array#class-poolvector2array) | [get\_outline](#class-navigationpolygon-method-get-outline) **(** [int](class_int#class-int) idx **)** const |
| [int](class_int#class-int) | [get\_outline\_count](#class-navigationpolygon-method-get-outline-count) **(** **)** const |
| [PoolIntArray](class_poolintarray#class-poolintarray) | [get\_polygon](#class-navigationpolygon-method-get-polygon) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_polygon\_count](#class-navigationpolygon-method-get-polygon-count) **(** **)** const |
| [PoolVector2Array](class_poolvector2array#class-poolvector2array) | [get\_vertices](#class-navigationpolygon-method-get-vertices) **(** **)** const |
| void | [make\_polygons\_from\_outlines](#class-navigationpolygon-method-make-polygons-from-outlines) **(** **)** |
| void | [remove\_outline](#class-navigationpolygon-method-remove-outline) **(** [int](class_int#class-int) idx **)** |
| void | [set\_outline](#class-navigationpolygon-method-set-outline) **(** [int](class_int#class-int) idx, [PoolVector2Array](class_poolvector2array#class-poolvector2array) outline **)** |
| void | [set\_vertices](#class-navigationpolygon-method-set-vertices) **(** [PoolVector2Array](class_poolvector2array#class-poolvector2array) vertices **)** |
Method Descriptions
-------------------
### void add\_outline ( [PoolVector2Array](class_poolvector2array#class-poolvector2array) outline )
Appends a [PoolVector2Array](class_poolvector2array#class-poolvector2array) that contains the vertices of an outline to the internal array that contains all the outlines. You have to call [make\_polygons\_from\_outlines](#class-navigationpolygon-method-make-polygons-from-outlines) in order for this array to be converted to polygons that the engine will use.
### void add\_outline\_at\_index ( [PoolVector2Array](class_poolvector2array#class-poolvector2array) outline, [int](class_int#class-int) index )
Adds a [PoolVector2Array](class_poolvector2array#class-poolvector2array) that contains the vertices of an outline to the internal array that contains all the outlines at a fixed position. You have to call [make\_polygons\_from\_outlines](#class-navigationpolygon-method-make-polygons-from-outlines) in order for this array to be converted to polygons that the engine will use.
### void add\_polygon ( [PoolIntArray](class_poolintarray#class-poolintarray) polygon )
Adds a polygon using the indices of the vertices you get when calling [get\_vertices](#class-navigationpolygon-method-get-vertices).
### void clear\_outlines ( )
Clears the array of the outlines, but it doesn't clear the vertices and the polygons that were created by them.
### void clear\_polygons ( )
Clears the array of polygons, but it doesn't clear the array of outlines and vertices.
### [NavigationMesh](class_navigationmesh#class-navigationmesh) get\_mesh ( )
Returns the [NavigationMesh](class_navigationmesh#class-navigationmesh) resulting from this navigation polygon. This navmesh can be used to update the navmesh of a region with the [NavigationServer.region\_set\_navmesh](class_navigationserver#class-navigationserver-method-region-set-navmesh) API directly (as 2D uses the 3D server behind the scene).
### [PoolVector2Array](class_poolvector2array#class-poolvector2array) get\_outline ( [int](class_int#class-int) idx ) const
Returns a [PoolVector2Array](class_poolvector2array#class-poolvector2array) containing the vertices of an outline that was created in the editor or by script.
### [int](class_int#class-int) get\_outline\_count ( ) const
Returns the number of outlines that were created in the editor or by script.
### [PoolIntArray](class_poolintarray#class-poolintarray) get\_polygon ( [int](class_int#class-int) idx )
Returns a [PoolIntArray](class_poolintarray#class-poolintarray) containing the indices of the vertices of a created polygon.
### [int](class_int#class-int) get\_polygon\_count ( ) const
Returns the count of all polygons.
### [PoolVector2Array](class_poolvector2array#class-poolvector2array) get\_vertices ( ) const
Returns a [PoolVector2Array](class_poolvector2array#class-poolvector2array) containing all the vertices being used to create the polygons.
### void make\_polygons\_from\_outlines ( )
Creates polygons from the outlines added in the editor or by script.
### void remove\_outline ( [int](class_int#class-int) idx )
Removes an outline created in the editor or by script. You have to call [make\_polygons\_from\_outlines](#class-navigationpolygon-method-make-polygons-from-outlines) for the polygons to update.
### void set\_outline ( [int](class_int#class-int) idx, [PoolVector2Array](class_poolvector2array#class-poolvector2array) outline )
Changes an outline created in the editor or by script. You have to call [make\_polygons\_from\_outlines](#class-navigationpolygon-method-make-polygons-from-outlines) for the polygons to update.
### void set\_vertices ( [PoolVector2Array](class_poolvector2array#class-poolvector2array) vertices )
Sets the vertices that can be then indexed to create polygons with the [add\_polygon](#class-navigationpolygon-method-add-polygon) method.
| programming_docs |
godot InputEventMouseButton InputEventMouseButton
=====================
**Inherits:** [InputEventMouse](class_inputeventmouse#class-inputeventmouse) **<** [InputEventWithModifiers](class_inputeventwithmodifiers#class-inputeventwithmodifiers) **<** [InputEvent](class_inputevent#class-inputevent) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Input event type for mouse button events.
Description
-----------
Contains mouse click information. See [Node.\_input](class_node#class-node-method-input).
Tutorials
---------
* [Mouse and input coordinates](https://docs.godotengine.org/en/3.5/tutorials/inputs/mouse_and_input_coordinates.html)
Properties
----------
| | | |
| --- | --- | --- |
| [int](class_int#class-int) | [button\_index](#class-inputeventmousebutton-property-button-index) | `0` |
| [bool](class_bool#class-bool) | [doubleclick](#class-inputeventmousebutton-property-doubleclick) | `false` |
| [float](class_float#class-float) | [factor](#class-inputeventmousebutton-property-factor) | `1.0` |
| [bool](class_bool#class-bool) | [pressed](#class-inputeventmousebutton-property-pressed) | `false` |
Property Descriptions
---------------------
### [int](class_int#class-int) button\_index
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_button\_index(value) |
| *Getter* | get\_button\_index() |
The mouse button identifier, one of the [ButtonList](class_%40globalscope#enum-globalscope-buttonlist) button or button wheel constants.
### [bool](class_bool#class-bool) doubleclick
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_doubleclick(value) |
| *Getter* | is\_doubleclick() |
If `true`, the mouse button's state is a double-click.
### [float](class_float#class-float) factor
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_factor(value) |
| *Getter* | get\_factor() |
The amount (or delta) of the event. When used for high-precision scroll events, this indicates the scroll amount (vertical or horizontal). This is only supported on some platforms; the reported sensitivity varies depending on the platform. May be `0` if not supported.
### [bool](class_bool#class-bool) pressed
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_pressed(value) |
| *Getter* | is\_pressed() |
If `true`, the mouse button's state is pressed. If `false`, the mouse button's state is released.
godot PinJoint PinJoint
========
**Inherits:** [Joint](class_joint#class-joint) **<** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Pin joint for 3D PhysicsBodies.
Description
-----------
Pin joint for 3D rigid bodies. It pins 2 bodies (rigid or static) together. See also [Generic6DOFJoint](class_generic6dofjoint#class-generic6dofjoint).
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [params/bias](#class-pinjoint-property-params-bias) | `0.3` |
| [float](class_float#class-float) | [params/damping](#class-pinjoint-property-params-damping) | `1.0` |
| [float](class_float#class-float) | [params/impulse\_clamp](#class-pinjoint-property-params-impulse-clamp) | `0.0` |
Methods
-------
| | |
| --- | --- |
| [float](class_float#class-float) | [get\_param](#class-pinjoint-method-get-param) **(** [Param](#enum-pinjoint-param) param **)** const |
| void | [set\_param](#class-pinjoint-method-set-param) **(** [Param](#enum-pinjoint-param) param, [float](class_float#class-float) value **)** |
Enumerations
------------
enum **Param**:
* **PARAM\_BIAS** = **0** --- The force with which the pinned objects stay in positional relation to each other. The higher, the stronger.
* **PARAM\_DAMPING** = **1** --- The force with which the pinned objects stay in velocity relation to each other. The higher, the stronger.
* **PARAM\_IMPULSE\_CLAMP** = **2** --- If above 0, this value is the maximum value for an impulse that this Joint produces.
Property Descriptions
---------------------
### [float](class_float#class-float) params/bias
| | |
| --- | --- |
| *Default* | `0.3` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
The force with which the pinned objects stay in positional relation to each other. The higher, the stronger.
### [float](class_float#class-float) params/damping
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
The force with which the pinned objects stay in velocity relation to each other. The higher, the stronger.
### [float](class_float#class-float) params/impulse\_clamp
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
If above 0, this value is the maximum value for an impulse that this Joint produces.
Method Descriptions
-------------------
### [float](class_float#class-float) get\_param ( [Param](#enum-pinjoint-param) param ) const
Returns the value of the specified parameter.
### void set\_param ( [Param](#enum-pinjoint-param) param, [float](class_float#class-float) value )
Sets the value of the specified parameter.
godot VisualShaderNodeScalarInterp VisualShaderNodeScalarInterp
============================
**Inherits:** [VisualShaderNode](class_visualshadernode#class-visualshadernode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Linearly interpolates between two scalars within the visual shader graph.
Description
-----------
Translates to `mix(a, b, weight)` in the shader language.
godot AnimationNodeAdd3 AnimationNodeAdd3
=================
**Inherits:** [AnimationNode](class_animationnode#class-animationnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Blends two of three animations additively inside of an [AnimationNodeBlendTree](class_animationnodeblendtree#class-animationnodeblendtree).
Description
-----------
A resource to add to an [AnimationNodeBlendTree](class_animationnodeblendtree#class-animationnodeblendtree). Blends two animations together additively out of three based on a value in the `[-1.0, 1.0]` range.
This node has three inputs:
* The base animation to add to
* A -add animation to blend with when the blend amount is in the `[-1.0, 0.0]` range.
* A +add animation to blend with when the blend amount is in the `[0.0, 1.0]` range
Tutorials
---------
* [AnimationTree](https://docs.godotengine.org/en/3.5/tutorials/animation/animation_tree.html)
* [Third Person Shooter Demo](https://godotengine.org/asset-library/asset/678)
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | [sync](#class-animationnodeadd3-property-sync) | `false` |
Property Descriptions
---------------------
### [bool](class_bool#class-bool) sync
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_use\_sync(value) |
| *Getter* | is\_using\_sync() |
If `true`, sets the `optimization` to `false` when calling [AnimationNode.blend\_input](class_animationnode#class-animationnode-method-blend-input), forcing the blended animations to update every frame.
godot VisualScriptSelect VisualScriptSelect
==================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Chooses between two input values.
Description
-----------
Chooses between two input values based on a Boolean condition.
**Input Ports:**
* Data (boolean): `cond`
* Data (variant): `a`
* Data (variant): `b`
**Output Ports:**
* Data (variant): `out`
Properties
----------
| | | |
| --- | --- | --- |
| [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) | [type](#class-visualscriptselect-property-type) | `0` |
Property Descriptions
---------------------
### [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) type
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_typed(value) |
| *Getter* | get\_typed() |
The input variables' type.
godot MultiplayerAPI MultiplayerAPI
==============
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
High-level multiplayer API.
Description
-----------
This class implements most of the logic behind the high-level multiplayer API. See also [NetworkedMultiplayerPeer](class_networkedmultiplayerpeer#class-networkedmultiplayerpeer).
By default, [SceneTree](class_scenetree#class-scenetree) has a reference to this class that is used to provide multiplayer capabilities (i.e. RPC/RSET) across the whole scene.
It is possible to override the MultiplayerAPI instance used by specific Nodes by setting the [Node.custom\_multiplayer](class_node#class-node-property-custom-multiplayer) property, effectively allowing to run both client and server in the same scene.
**Note:** The high-level multiplayer API protocol is an implementation detail and isn't meant to be used by non-Godot servers. It may change without notice.
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | [allow\_object\_decoding](#class-multiplayerapi-property-allow-object-decoding) | `false` |
| [NetworkedMultiplayerPeer](class_networkedmultiplayerpeer#class-networkedmultiplayerpeer) | [network\_peer](#class-multiplayerapi-property-network-peer) | |
| [bool](class_bool#class-bool) | [refuse\_new\_network\_connections](#class-multiplayerapi-property-refuse-new-network-connections) | `false` |
| [Node](class_node#class-node) | [root\_node](#class-multiplayerapi-property-root-node) | |
Methods
-------
| | |
| --- | --- |
| void | [clear](#class-multiplayerapi-method-clear) **(** **)** |
| [PoolIntArray](class_poolintarray#class-poolintarray) | [get\_network\_connected\_peers](#class-multiplayerapi-method-get-network-connected-peers) **(** **)** const |
| [int](class_int#class-int) | [get\_network\_unique\_id](#class-multiplayerapi-method-get-network-unique-id) **(** **)** const |
| [int](class_int#class-int) | [get\_rpc\_sender\_id](#class-multiplayerapi-method-get-rpc-sender-id) **(** **)** const |
| [bool](class_bool#class-bool) | [has\_network\_peer](#class-multiplayerapi-method-has-network-peer) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_network\_server](#class-multiplayerapi-method-is-network-server) **(** **)** const |
| void | [poll](#class-multiplayerapi-method-poll) **(** **)** |
| [Error](class_%40globalscope#enum-globalscope-error) | [send\_bytes](#class-multiplayerapi-method-send-bytes) **(** [PoolByteArray](class_poolbytearray#class-poolbytearray) bytes, [int](class_int#class-int) id=0, [TransferMode](class_networkedmultiplayerpeer#enum-networkedmultiplayerpeer-transfermode) mode=2 **)** |
Signals
-------
### connected\_to\_server ( )
Emitted when this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) successfully connected to a server. Only emitted on clients.
### connection\_failed ( )
Emitted when this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) fails to establish a connection to a server. Only emitted on clients.
### network\_peer\_connected ( [int](class_int#class-int) id )
Emitted when this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) connects with a new peer. ID is the peer ID of the new peer. Clients get notified when other clients connect to the same server. Upon connecting to a server, a client also receives this signal for the server (with ID being 1).
### network\_peer\_disconnected ( [int](class_int#class-int) id )
Emitted when this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) disconnects from a peer. Clients get notified when other clients disconnect from the same server.
### network\_peer\_packet ( [int](class_int#class-int) id, [PoolByteArray](class_poolbytearray#class-poolbytearray) packet )
Emitted when this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) receive a `packet` with custom data (see [send\_bytes](#class-multiplayerapi-method-send-bytes)). ID is the peer ID of the peer that sent the packet.
### server\_disconnected ( )
Emitted when this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) disconnects from server. Only emitted on clients.
Enumerations
------------
enum **RPCMode**:
* **RPC\_MODE\_DISABLED** = **0** --- Used with [Node.rpc\_config](class_node#class-node-method-rpc-config) or [Node.rset\_config](class_node#class-node-method-rset-config) to disable a method or property for all RPC calls, making it unavailable. Default for all methods.
* **RPC\_MODE\_REMOTE** = **1** --- Used with [Node.rpc\_config](class_node#class-node-method-rpc-config) or [Node.rset\_config](class_node#class-node-method-rset-config) to set a method to be called or a property to be changed only on the remote end, not locally. Analogous to the `remote` keyword. Calls and property changes are accepted from all remote peers, no matter if they are node's master or puppets.
* **RPC\_MODE\_MASTER** = **2** --- Used with [Node.rpc\_config](class_node#class-node-method-rpc-config) or [Node.rset\_config](class_node#class-node-method-rset-config) to set a method to be called or a property to be changed only on the network master for this node. Analogous to the `master` keyword. Only accepts calls or property changes from the node's network puppets, see [Node.set\_network\_master](class_node#class-node-method-set-network-master).
* **RPC\_MODE\_PUPPET** = **3** --- Used with [Node.rpc\_config](class_node#class-node-method-rpc-config) or [Node.rset\_config](class_node#class-node-method-rset-config) to set a method to be called or a property to be changed only on puppets for this node. Analogous to the `puppet` keyword. Only accepts calls or property changes from the node's network master, see [Node.set\_network\_master](class_node#class-node-method-set-network-master).
* **RPC\_MODE\_SLAVE** = **3** --- *Deprecated.* Use [RPC\_MODE\_PUPPET](#class-multiplayerapi-constant-rpc-mode-puppet) instead. Analogous to the `slave` keyword.
* **RPC\_MODE\_REMOTESYNC** = **4** --- Behave like [RPC\_MODE\_REMOTE](#class-multiplayerapi-constant-rpc-mode-remote) but also make the call or property change locally. Analogous to the `remotesync` keyword.
* **RPC\_MODE\_SYNC** = **4** --- *Deprecated.* Use [RPC\_MODE\_REMOTESYNC](#class-multiplayerapi-constant-rpc-mode-remotesync) instead. Analogous to the `sync` keyword.
* **RPC\_MODE\_MASTERSYNC** = **5** --- Behave like [RPC\_MODE\_MASTER](#class-multiplayerapi-constant-rpc-mode-master) but also make the call or property change locally. Analogous to the `mastersync` keyword.
* **RPC\_MODE\_PUPPETSYNC** = **6** --- Behave like [RPC\_MODE\_PUPPET](#class-multiplayerapi-constant-rpc-mode-puppet) but also make the call or property change locally. Analogous to the `puppetsync` keyword.
Property Descriptions
---------------------
### [bool](class_bool#class-bool) allow\_object\_decoding
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_allow\_object\_decoding(value) |
| *Getter* | is\_object\_decoding\_allowed() |
If `true` (or if the [network\_peer](#class-multiplayerapi-property-network-peer) has [PacketPeer.allow\_object\_decoding](class_packetpeer#class-packetpeer-property-allow-object-decoding) set to `true`), the MultiplayerAPI will allow encoding and decoding of object during RPCs/RSETs.
**Warning:** Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.
### [NetworkedMultiplayerPeer](class_networkedmultiplayerpeer#class-networkedmultiplayerpeer) network\_peer
| | |
| --- | --- |
| *Setter* | set\_network\_peer(value) |
| *Getter* | get\_network\_peer() |
The peer object to handle the RPC system (effectively enabling networking when set). Depending on the peer itself, the MultiplayerAPI will become a network server (check with [is\_network\_server](#class-multiplayerapi-method-is-network-server)) and will set root node's network mode to master, or it will become a regular peer with root node set to puppet. All child nodes are set to inherit the network mode by default. Handling of networking-related events (connection, disconnection, new clients) is done by connecting to MultiplayerAPI's signals.
### [bool](class_bool#class-bool) refuse\_new\_network\_connections
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_refuse\_new\_network\_connections(value) |
| *Getter* | is\_refusing\_new\_network\_connections() |
If `true`, the MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) refuses new incoming connections.
### [Node](class_node#class-node) root\_node
| | |
| --- | --- |
| *Setter* | set\_root\_node(value) |
| *Getter* | get\_root\_node() |
The root node to use for RPCs. Instead of an absolute path, a relative path will be used to find the node upon which the RPC should be executed.
This effectively allows to have different branches of the scene tree to be managed by different MultiplayerAPI, allowing for example to run both client and server in the same scene.
Method Descriptions
-------------------
### void clear ( )
Clears the current MultiplayerAPI network state (you shouldn't call this unless you know what you are doing).
### [PoolIntArray](class_poolintarray#class-poolintarray) get\_network\_connected\_peers ( ) const
Returns the peer IDs of all connected peers of this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer).
### [int](class_int#class-int) get\_network\_unique\_id ( ) const
Returns the unique peer ID of this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer).
### [int](class_int#class-int) get\_rpc\_sender\_id ( ) const
Returns the sender's peer ID for the RPC currently being executed.
**Note:** If not inside an RPC this method will return 0.
### [bool](class_bool#class-bool) has\_network\_peer ( ) const
Returns `true` if there is a [network\_peer](#class-multiplayerapi-property-network-peer) set.
### [bool](class_bool#class-bool) is\_network\_server ( ) const
Returns `true` if this MultiplayerAPI's [network\_peer](#class-multiplayerapi-property-network-peer) is in server mode (listening for connections).
### void poll ( )
Method used for polling the MultiplayerAPI. You only need to worry about this if you are using [Node.custom\_multiplayer](class_node#class-node-property-custom-multiplayer) override or you set [SceneTree.multiplayer\_poll](class_scenetree#class-scenetree-property-multiplayer-poll) to `false`. By default, [SceneTree](class_scenetree#class-scenetree) will poll its MultiplayerAPI for you.
**Note:** This method results in RPCs and RSETs being called, so they will be executed in the same context of this function (e.g. `_process`, `physics`, [Thread](class_thread#class-thread)).
### [Error](class_%40globalscope#enum-globalscope-error) send\_bytes ( [PoolByteArray](class_poolbytearray#class-poolbytearray) bytes, [int](class_int#class-int) id=0, [TransferMode](class_networkedmultiplayerpeer#enum-networkedmultiplayerpeer-transfermode) mode=2 )
Sends the given raw `bytes` to a specific peer identified by `id` (see [NetworkedMultiplayerPeer.set\_target\_peer](class_networkedmultiplayerpeer#class-networkedmultiplayerpeer-method-set-target-peer)). Default ID is `0`, i.e. broadcast to all peers.
| programming_docs |
godot StreamPeer StreamPeer
==========
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [StreamPeerBuffer](class_streampeerbuffer#class-streampeerbuffer), [StreamPeerGDNative](class_streampeergdnative#class-streampeergdnative), [StreamPeerSSL](class_streampeerssl#class-streampeerssl), [StreamPeerTCP](class_streampeertcp#class-streampeertcp)
Abstraction and base class for stream-based protocols.
Description
-----------
StreamPeer is an abstraction and base class for stream-based protocols (such as TCP). It provides an API for sending and receiving data through streams as raw data or strings.
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | [big\_endian](#class-streampeer-property-big-endian) | `false` |
Methods
-------
| | |
| --- | --- |
| [int](class_int#class-int) | [get\_16](#class-streampeer-method-get-16) **(** **)** |
| [int](class_int#class-int) | [get\_32](#class-streampeer-method-get-32) **(** **)** |
| [int](class_int#class-int) | [get\_64](#class-streampeer-method-get-64) **(** **)** |
| [int](class_int#class-int) | [get\_8](#class-streampeer-method-get-8) **(** **)** |
| [int](class_int#class-int) | [get\_available\_bytes](#class-streampeer-method-get-available-bytes) **(** **)** const |
| [Array](class_array#class-array) | [get\_data](#class-streampeer-method-get-data) **(** [int](class_int#class-int) bytes **)** |
| [float](class_float#class-float) | [get\_double](#class-streampeer-method-get-double) **(** **)** |
| [float](class_float#class-float) | [get\_float](#class-streampeer-method-get-float) **(** **)** |
| [Array](class_array#class-array) | [get\_partial\_data](#class-streampeer-method-get-partial-data) **(** [int](class_int#class-int) bytes **)** |
| [String](class_string#class-string) | [get\_string](#class-streampeer-method-get-string) **(** [int](class_int#class-int) bytes=-1 **)** |
| [int](class_int#class-int) | [get\_u16](#class-streampeer-method-get-u16) **(** **)** |
| [int](class_int#class-int) | [get\_u32](#class-streampeer-method-get-u32) **(** **)** |
| [int](class_int#class-int) | [get\_u64](#class-streampeer-method-get-u64) **(** **)** |
| [int](class_int#class-int) | [get\_u8](#class-streampeer-method-get-u8) **(** **)** |
| [String](class_string#class-string) | [get\_utf8\_string](#class-streampeer-method-get-utf8-string) **(** [int](class_int#class-int) bytes=-1 **)** |
| [Variant](class_variant#class-variant) | [get\_var](#class-streampeer-method-get-var) **(** [bool](class_bool#class-bool) allow\_objects=false **)** |
| void | [put\_16](#class-streampeer-method-put-16) **(** [int](class_int#class-int) value **)** |
| void | [put\_32](#class-streampeer-method-put-32) **(** [int](class_int#class-int) value **)** |
| void | [put\_64](#class-streampeer-method-put-64) **(** [int](class_int#class-int) value **)** |
| void | [put\_8](#class-streampeer-method-put-8) **(** [int](class_int#class-int) value **)** |
| [Error](class_%40globalscope#enum-globalscope-error) | [put\_data](#class-streampeer-method-put-data) **(** [PoolByteArray](class_poolbytearray#class-poolbytearray) data **)** |
| void | [put\_double](#class-streampeer-method-put-double) **(** [float](class_float#class-float) value **)** |
| void | [put\_float](#class-streampeer-method-put-float) **(** [float](class_float#class-float) value **)** |
| [Array](class_array#class-array) | [put\_partial\_data](#class-streampeer-method-put-partial-data) **(** [PoolByteArray](class_poolbytearray#class-poolbytearray) data **)** |
| void | [put\_string](#class-streampeer-method-put-string) **(** [String](class_string#class-string) value **)** |
| void | [put\_u16](#class-streampeer-method-put-u16) **(** [int](class_int#class-int) value **)** |
| void | [put\_u32](#class-streampeer-method-put-u32) **(** [int](class_int#class-int) value **)** |
| void | [put\_u64](#class-streampeer-method-put-u64) **(** [int](class_int#class-int) value **)** |
| void | [put\_u8](#class-streampeer-method-put-u8) **(** [int](class_int#class-int) value **)** |
| void | [put\_utf8\_string](#class-streampeer-method-put-utf8-string) **(** [String](class_string#class-string) value **)** |
| void | [put\_var](#class-streampeer-method-put-var) **(** [Variant](class_variant#class-variant) value, [bool](class_bool#class-bool) full\_objects=false **)** |
Property Descriptions
---------------------
### [bool](class_bool#class-bool) big\_endian
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_big\_endian(value) |
| *Getter* | is\_big\_endian\_enabled() |
If `true`, this `StreamPeer` will using big-endian format for encoding and decoding.
Method Descriptions
-------------------
### [int](class_int#class-int) get\_16 ( )
Gets a signed 16-bit value from the stream.
### [int](class_int#class-int) get\_32 ( )
Gets a signed 32-bit value from the stream.
### [int](class_int#class-int) get\_64 ( )
Gets a signed 64-bit value from the stream.
### [int](class_int#class-int) get\_8 ( )
Gets a signed byte from the stream.
### [int](class_int#class-int) get\_available\_bytes ( ) const
Returns the amount of bytes this `StreamPeer` has available.
### [Array](class_array#class-array) get\_data ( [int](class_int#class-int) bytes )
Returns a chunk data with the received bytes. The amount of bytes to be received can be requested in the `bytes` argument. If not enough bytes are available, the function will block until the desired amount is received. This function returns two values, an [Error](class_%40globalscope#enum-globalscope-error) code and a data array.
### [float](class_float#class-float) get\_double ( )
Gets a double-precision float from the stream.
### [float](class_float#class-float) get\_float ( )
Gets a single-precision float from the stream.
### [Array](class_array#class-array) get\_partial\_data ( [int](class_int#class-int) bytes )
Returns a chunk data with the received bytes. The amount of bytes to be received can be requested in the "bytes" argument. If not enough bytes are available, the function will return how many were actually received. This function returns two values, an [Error](class_%40globalscope#enum-globalscope-error) code, and a data array.
### [String](class_string#class-string) get\_string ( [int](class_int#class-int) bytes=-1 )
Gets an ASCII string with byte-length `bytes` from the stream. If `bytes` is negative (default) the length will be read from the stream using the reverse process of [put\_string](#class-streampeer-method-put-string).
### [int](class_int#class-int) get\_u16 ( )
Gets an unsigned 16-bit value from the stream.
### [int](class_int#class-int) get\_u32 ( )
Gets an unsigned 32-bit value from the stream.
### [int](class_int#class-int) get\_u64 ( )
Gets an unsigned 64-bit value from the stream.
### [int](class_int#class-int) get\_u8 ( )
Gets an unsigned byte from the stream.
### [String](class_string#class-string) get\_utf8\_string ( [int](class_int#class-int) bytes=-1 )
Gets an UTF-8 string with byte-length `bytes` from the stream (this decodes the string sent as UTF-8). If `bytes` is negative (default) the length will be read from the stream using the reverse process of [put\_utf8\_string](#class-streampeer-method-put-utf8-string).
### [Variant](class_variant#class-variant) get\_var ( [bool](class_bool#class-bool) allow\_objects=false )
Gets a Variant from the stream. If `allow_objects` is `true`, decoding objects is allowed.
**Warning:** Deserialized objects can contain code which gets executed. Do not use this option if the serialized object comes from untrusted sources to avoid potential security threats such as remote code execution.
### void put\_16 ( [int](class_int#class-int) value )
Puts a signed 16-bit value into the stream.
### void put\_32 ( [int](class_int#class-int) value )
Puts a signed 32-bit value into the stream.
### void put\_64 ( [int](class_int#class-int) value )
Puts a signed 64-bit value into the stream.
### void put\_8 ( [int](class_int#class-int) value )
Puts a signed byte into the stream.
### [Error](class_%40globalscope#enum-globalscope-error) put\_data ( [PoolByteArray](class_poolbytearray#class-poolbytearray) data )
Sends a chunk of data through the connection, blocking if necessary until the data is done sending. This function returns an [Error](class_%40globalscope#enum-globalscope-error) code.
### void put\_double ( [float](class_float#class-float) value )
Puts a double-precision float into the stream.
### void put\_float ( [float](class_float#class-float) value )
Puts a single-precision float into the stream.
### [Array](class_array#class-array) put\_partial\_data ( [PoolByteArray](class_poolbytearray#class-poolbytearray) data )
Sends a chunk of data through the connection. If all the data could not be sent at once, only part of it will. This function returns two values, an [Error](class_%40globalscope#enum-globalscope-error) code and an integer, describing how much data was actually sent.
### void put\_string ( [String](class_string#class-string) value )
Puts a zero-terminated ASCII string into the stream prepended by a 32-bit unsigned integer representing its size.
**Note:** To put an ASCII string without prepending its size, you can use [put\_data](#class-streampeer-method-put-data):
```
put_data("Hello world".to_ascii())
```
### void put\_u16 ( [int](class_int#class-int) value )
Puts an unsigned 16-bit value into the stream.
### void put\_u32 ( [int](class_int#class-int) value )
Puts an unsigned 32-bit value into the stream.
### void put\_u64 ( [int](class_int#class-int) value )
Puts an unsigned 64-bit value into the stream.
### void put\_u8 ( [int](class_int#class-int) value )
Puts an unsigned byte into the stream.
### void put\_utf8\_string ( [String](class_string#class-string) value )
Puts a zero-terminated UTF-8 string into the stream prepended by a 32 bits unsigned integer representing its size.
**Note:** To put an UTF-8 string without prepending its size, you can use [put\_data](#class-streampeer-method-put-data):
```
put_data("Hello world".to_utf8())
```
### void put\_var ( [Variant](class_variant#class-variant) value, [bool](class_bool#class-bool) full\_objects=false )
Puts a Variant into the stream. If `full_objects` is `true` encoding objects is allowed (and can potentially include code).
godot VisualShaderNodeVectorScalarStep VisualShaderNodeVectorScalarStep
================================
**Inherits:** [VisualShaderNode](class_visualshadernode#class-visualshadernode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Calculates a vector Step function within the visual shader graph.
Description
-----------
Translates to `step(edge, x)` in the shader language.
Returns `0.0` if `x` is smaller than `edge` and `1.0` otherwise.
godot BaseButton BaseButton
==========
**Inherits:** [Control](class_control#class-control) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
**Inherited By:** [Button](class_button#class-button), [LinkButton](class_linkbutton#class-linkbutton), [TextureButton](class_texturebutton#class-texturebutton)
Base class for different kinds of buttons.
Description
-----------
BaseButton is the abstract base class for buttons, so it shouldn't be used directly (it doesn't display anything). Other types of buttons inherit from it.
Properties
----------
| | | |
| --- | --- | --- |
| [ActionMode](#enum-basebutton-actionmode) | [action\_mode](#class-basebutton-property-action-mode) | `1` |
| [int](class_int#class-int) | [button\_mask](#class-basebutton-property-button-mask) | `1` |
| [bool](class_bool#class-bool) | [disabled](#class-basebutton-property-disabled) | `false` |
| [FocusMode](class_control#enum-control-focusmode) | [enabled\_focus\_mode](#class-basebutton-property-enabled-focus-mode) | `2` |
| [FocusMode](class_control#enum-control-focusmode) | focus\_mode | `2` (overrides [Control](class_control#class-control-property-focus-mode)) |
| [ButtonGroup](class_buttongroup#class-buttongroup) | [group](#class-basebutton-property-group) | |
| [bool](class_bool#class-bool) | [keep\_pressed\_outside](#class-basebutton-property-keep-pressed-outside) | `false` |
| [bool](class_bool#class-bool) | [pressed](#class-basebutton-property-pressed) | `false` |
| [ShortCut](class_shortcut#class-shortcut) | [shortcut](#class-basebutton-property-shortcut) | |
| [bool](class_bool#class-bool) | [shortcut\_in\_tooltip](#class-basebutton-property-shortcut-in-tooltip) | `true` |
| [bool](class_bool#class-bool) | [toggle\_mode](#class-basebutton-property-toggle-mode) | `false` |
Methods
-------
| | |
| --- | --- |
| void | [\_pressed](#class-basebutton-method-pressed) **(** **)** virtual |
| void | [\_toggled](#class-basebutton-method-toggled) **(** [bool](class_bool#class-bool) button\_pressed **)** virtual |
| [DrawMode](#enum-basebutton-drawmode) | [get\_draw\_mode](#class-basebutton-method-get-draw-mode) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_hovered](#class-basebutton-method-is-hovered) **(** **)** const |
| void | [set\_pressed\_no\_signal](#class-basebutton-method-set-pressed-no-signal) **(** [bool](class_bool#class-bool) pressed **)** |
Signals
-------
### button\_down ( )
Emitted when the button starts being held down.
### button\_up ( )
Emitted when the button stops being held down.
### pressed ( )
Emitted when the button is toggled or pressed. This is on [button\_down](#class-basebutton-signal-button-down) if [action\_mode](#class-basebutton-property-action-mode) is [ACTION\_MODE\_BUTTON\_PRESS](#class-basebutton-constant-action-mode-button-press) and on [button\_up](#class-basebutton-signal-button-up) otherwise.
If you need to know the button's pressed state (and [toggle\_mode](#class-basebutton-property-toggle-mode) is active), use [toggled](#class-basebutton-signal-toggled) instead.
### toggled ( [bool](class_bool#class-bool) button\_pressed )
Emitted when the button was just toggled between pressed and normal states (only if [toggle\_mode](#class-basebutton-property-toggle-mode) is active). The new state is contained in the `button_pressed` argument.
Enumerations
------------
enum **DrawMode**:
* **DRAW\_NORMAL** = **0** --- The normal state (i.e. not pressed, not hovered, not toggled and enabled) of buttons.
* **DRAW\_PRESSED** = **1** --- The state of buttons are pressed.
* **DRAW\_HOVER** = **2** --- The state of buttons are hovered.
* **DRAW\_DISABLED** = **3** --- The state of buttons are disabled.
* **DRAW\_HOVER\_PRESSED** = **4** --- The state of buttons are both hovered and pressed.
enum **ActionMode**:
* **ACTION\_MODE\_BUTTON\_PRESS** = **0** --- Require just a press to consider the button clicked.
* **ACTION\_MODE\_BUTTON\_RELEASE** = **1** --- Require a press and a subsequent release before considering the button clicked.
Property Descriptions
---------------------
### [ActionMode](#enum-basebutton-actionmode) action\_mode
| | |
| --- | --- |
| *Default* | `1` |
| *Setter* | set\_action\_mode(value) |
| *Getter* | get\_action\_mode() |
Determines when the button is considered clicked, one of the [ActionMode](#enum-basebutton-actionmode) constants.
### [int](class_int#class-int) button\_mask
| | |
| --- | --- |
| *Default* | `1` |
| *Setter* | set\_button\_mask(value) |
| *Getter* | get\_button\_mask() |
Binary mask to choose which mouse buttons this button will respond to.
To allow both left-click and right-click, use `BUTTON_MASK_LEFT | BUTTON_MASK_RIGHT`.
### [bool](class_bool#class-bool) disabled
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_disabled(value) |
| *Getter* | is\_disabled() |
If `true`, the button is in disabled state and can't be clicked or toggled.
### [FocusMode](class_control#enum-control-focusmode) enabled\_focus\_mode
| | |
| --- | --- |
| *Default* | `2` |
| *Setter* | set\_enabled\_focus\_mode(value) |
| *Getter* | get\_enabled\_focus\_mode() |
*Deprecated.* This property has been deprecated due to redundancy and will be removed in Godot 4.0. This property no longer has any effect when set. Please use [Control.focus\_mode](class_control#class-control-property-focus-mode) instead.
### [ButtonGroup](class_buttongroup#class-buttongroup) group
| | |
| --- | --- |
| *Setter* | set\_button\_group(value) |
| *Getter* | get\_button\_group() |
[ButtonGroup](class_buttongroup#class-buttongroup) associated to the button.
### [bool](class_bool#class-bool) keep\_pressed\_outside
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_keep\_pressed\_outside(value) |
| *Getter* | is\_keep\_pressed\_outside() |
If `true`, the button stays pressed when moving the cursor outside the button while pressing it.
**Note:** This property only affects the button's visual appearance. Signals will be emitted at the same moment regardless of this property's value.
### [bool](class_bool#class-bool) pressed
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_pressed(value) |
| *Getter* | is\_pressed() |
If `true`, the button's state is pressed. Means the button is pressed down or toggled (if [toggle\_mode](#class-basebutton-property-toggle-mode) is active). Only works if [toggle\_mode](#class-basebutton-property-toggle-mode) is `true`.
**Note:** Setting [pressed](#class-basebutton-property-pressed) will result in [toggled](#class-basebutton-signal-toggled) to be emitted. If you want to change the pressed state without emitting that signal, use [set\_pressed\_no\_signal](#class-basebutton-method-set-pressed-no-signal).
### [ShortCut](class_shortcut#class-shortcut) shortcut
| | |
| --- | --- |
| *Setter* | set\_shortcut(value) |
| *Getter* | get\_shortcut() |
[ShortCut](class_shortcut#class-shortcut) associated to the button.
### [bool](class_bool#class-bool) shortcut\_in\_tooltip
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_shortcut\_in\_tooltip(value) |
| *Getter* | is\_shortcut\_in\_tooltip\_enabled() |
If `true`, the button will add information about its shortcut in the tooltip.
### [bool](class_bool#class-bool) toggle\_mode
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_toggle\_mode(value) |
| *Getter* | is\_toggle\_mode() |
If `true`, the button is in toggle mode. Makes the button flip state between pressed and unpressed each time its area is clicked.
Method Descriptions
-------------------
### void \_pressed ( ) virtual
Called when the button is pressed. If you need to know the button's pressed state (and [toggle\_mode](#class-basebutton-property-toggle-mode) is active), use [\_toggled](#class-basebutton-method-toggled) instead.
### void \_toggled ( [bool](class_bool#class-bool) button\_pressed ) virtual
Called when the button is toggled (only if [toggle\_mode](#class-basebutton-property-toggle-mode) is active).
### [DrawMode](#enum-basebutton-drawmode) get\_draw\_mode ( ) const
Returns the visual state used to draw the button. This is useful mainly when implementing your own draw code by either overriding \_draw() or connecting to "draw" signal. The visual state of the button is defined by the [DrawMode](#enum-basebutton-drawmode) enum.
### [bool](class_bool#class-bool) is\_hovered ( ) const
Returns `true` if the mouse has entered the button and has not left it yet.
### void set\_pressed\_no\_signal ( [bool](class_bool#class-bool) pressed )
Changes the [pressed](#class-basebutton-property-pressed) state of the button, without emitting [toggled](#class-basebutton-signal-toggled). Use when you just want to change the state of the button without sending the pressed event (e.g. when initializing scene). Only works if [toggle\_mode](#class-basebutton-property-toggle-mode) is `true`.
**Note:** This method doesn't unpress other buttons in its button [group](#class-basebutton-property-group).
| programming_docs |
godot EditorResourcePreviewGenerator EditorResourcePreviewGenerator
==============================
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Custom generator of previews.
Description
-----------
Custom code to generate previews. Please check `file_dialog/thumbnail_size` in [EditorSettings](class_editorsettings#class-editorsettings) to find out the right size to do previews at.
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [can\_generate\_small\_preview](#class-editorresourcepreviewgenerator-method-can-generate-small-preview) **(** **)** virtual |
| [Texture](class_texture#class-texture) | [generate](#class-editorresourcepreviewgenerator-method-generate) **(** [Resource](class_resource#class-resource) from, [Vector2](class_vector2#class-vector2) size **)** virtual |
| [Texture](class_texture#class-texture) | [generate\_from\_path](#class-editorresourcepreviewgenerator-method-generate-from-path) **(** [String](class_string#class-string) path, [Vector2](class_vector2#class-vector2) size **)** virtual |
| [bool](class_bool#class-bool) | [generate\_small\_preview\_automatically](#class-editorresourcepreviewgenerator-method-generate-small-preview-automatically) **(** **)** virtual |
| [bool](class_bool#class-bool) | [handles](#class-editorresourcepreviewgenerator-method-handles) **(** [String](class_string#class-string) type **)** virtual |
Method Descriptions
-------------------
### [bool](class_bool#class-bool) can\_generate\_small\_preview ( ) virtual
If this function returns `true`, the generator will call [generate](#class-editorresourcepreviewgenerator-method-generate) or [generate\_from\_path](#class-editorresourcepreviewgenerator-method-generate-from-path) for small previews as well.
By default, it returns `false`.
### [Texture](class_texture#class-texture) generate ( [Resource](class_resource#class-resource) from, [Vector2](class_vector2#class-vector2) size ) virtual
Generate a preview from a given resource with the specified size. This must always be implemented.
Returning an empty texture is an OK way to fail and let another generator take care.
Care must be taken because this function is always called from a thread (not the main thread).
### [Texture](class_texture#class-texture) generate\_from\_path ( [String](class_string#class-string) path, [Vector2](class_vector2#class-vector2) size ) virtual
Generate a preview directly from a path with the specified size. Implementing this is optional, as default code will load and call [generate](#class-editorresourcepreviewgenerator-method-generate).
Returning an empty texture is an OK way to fail and let another generator take care.
Care must be taken because this function is always called from a thread (not the main thread).
### [bool](class_bool#class-bool) generate\_small\_preview\_automatically ( ) virtual
If this function returns `true`, the generator will automatically generate the small previews from the normal preview texture generated by the methods [generate](#class-editorresourcepreviewgenerator-method-generate) or [generate\_from\_path](#class-editorresourcepreviewgenerator-method-generate-from-path).
By default, it returns `false`.
### [bool](class_bool#class-bool) handles ( [String](class_string#class-string) type ) virtual
Returns `true` if your generator supports the resource of type `type`.
godot Theme Theme
=====
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Theme for controls.
Description
-----------
A theme for skinning controls. Controls can be skinned individually, but for complex applications, it's more practical to just create a global theme that defines everything. This theme can be applied to any [Control](class_control#class-control); the Control and its children will automatically use it.
Theme resources can alternatively be loaded by writing them in a `.theme` file, see the documentation for more information.
Tutorials
---------
* [Introduction to GUI skinning](https://docs.godotengine.org/en/3.5/tutorials/ui/gui_skinning.html)
Properties
----------
| | |
| --- | --- |
| [Font](class_font#class-font) | [default\_font](#class-theme-property-default-font) |
Methods
-------
| | |
| --- | --- |
| void | [add\_type](#class-theme-method-add-type) **(** [String](class_string#class-string) theme\_type **)** |
| void | [clear](#class-theme-method-clear) **(** **)** |
| void | [clear\_color](#class-theme-method-clear-color) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [clear\_constant](#class-theme-method-clear-constant) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [clear\_font](#class-theme-method-clear-font) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [clear\_icon](#class-theme-method-clear-icon) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [clear\_stylebox](#class-theme-method-clear-stylebox) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [clear\_theme\_item](#class-theme-method-clear-theme-item) **(** [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [clear\_type\_variation](#class-theme-method-clear-type-variation) **(** [String](class_string#class-string) theme\_type **)** |
| void | [copy\_default\_theme](#class-theme-method-copy-default-theme) **(** **)** |
| void | [copy\_theme](#class-theme-method-copy-theme) **(** [Theme](#class-theme) other **)** |
| [Color](class_color#class-color) | [get\_color](#class-theme-method-get-color) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_color\_list](#class-theme-method-get-color-list) **(** [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_color\_types](#class-theme-method-get-color-types) **(** **)** const |
| [int](class_int#class-int) | [get\_constant](#class-theme-method-get-constant) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_constant\_list](#class-theme-method-get-constant-list) **(** [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_constant\_types](#class-theme-method-get-constant-types) **(** **)** const |
| [Font](class_font#class-font) | [get\_font](#class-theme-method-get-font) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_font\_list](#class-theme-method-get-font-list) **(** [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_font\_types](#class-theme-method-get-font-types) **(** **)** const |
| [Texture](class_texture#class-texture) | [get\_icon](#class-theme-method-get-icon) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_icon\_list](#class-theme-method-get-icon-list) **(** [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_icon\_types](#class-theme-method-get-icon-types) **(** **)** const |
| [StyleBox](class_stylebox#class-stylebox) | [get\_stylebox](#class-theme-method-get-stylebox) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_stylebox\_list](#class-theme-method-get-stylebox-list) **(** [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_stylebox\_types](#class-theme-method-get-stylebox-types) **(** **)** const |
| [Variant](class_variant#class-variant) | [get\_theme\_item](#class-theme-method-get-theme-item) **(** [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_theme\_item\_list](#class-theme-method-get-theme-item-list) **(** [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_theme\_item\_types](#class-theme-method-get-theme-item-types) **(** [DataType](#enum-theme-datatype) data\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_type\_list](#class-theme-method-get-type-list) **(** [String](class_string#class-string) theme\_type **)** const |
| [String](class_string#class-string) | [get\_type\_variation\_base](#class-theme-method-get-type-variation-base) **(** [String](class_string#class-string) theme\_type **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_type\_variation\_list](#class-theme-method-get-type-variation-list) **(** [String](class_string#class-string) base\_type **)** const |
| [bool](class_bool#class-bool) | [has\_color](#class-theme-method-has-color) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [bool](class_bool#class-bool) | [has\_constant](#class-theme-method-has-constant) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [bool](class_bool#class-bool) | [has\_default\_font](#class-theme-method-has-default-font) **(** **)** const |
| [bool](class_bool#class-bool) | [has\_font](#class-theme-method-has-font) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [bool](class_bool#class-bool) | [has\_icon](#class-theme-method-has-icon) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [bool](class_bool#class-bool) | [has\_stylebox](#class-theme-method-has-stylebox) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [bool](class_bool#class-bool) | [has\_theme\_item](#class-theme-method-has-theme-item) **(** [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** const |
| [bool](class_bool#class-bool) | [is\_type\_variation](#class-theme-method-is-type-variation) **(** [String](class_string#class-string) theme\_type, [String](class_string#class-string) base\_type **)** const |
| void | [merge\_with](#class-theme-method-merge-with) **(** [Theme](#class-theme) other **)** |
| void | [remove\_type](#class-theme-method-remove-type) **(** [String](class_string#class-string) theme\_type **)** |
| void | [rename\_color](#class-theme-method-rename-color) **(** [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [rename\_constant](#class-theme-method-rename-constant) **(** [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [rename\_font](#class-theme-method-rename-font) **(** [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [rename\_icon](#class-theme-method-rename-icon) **(** [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [rename\_stylebox](#class-theme-method-rename-stylebox) **(** [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [rename\_theme\_item](#class-theme-method-rename-theme-item) **(** [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type **)** |
| void | [set\_color](#class-theme-method-set-color) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Color](class_color#class-color) color **)** |
| void | [set\_constant](#class-theme-method-set-constant) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [int](class_int#class-int) constant **)** |
| void | [set\_font](#class-theme-method-set-font) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Font](class_font#class-font) font **)** |
| void | [set\_icon](#class-theme-method-set-icon) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Texture](class_texture#class-texture) texture **)** |
| void | [set\_stylebox](#class-theme-method-set-stylebox) **(** [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [StyleBox](class_stylebox#class-stylebox) texture **)** |
| void | [set\_theme\_item](#class-theme-method-set-theme-item) **(** [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Variant](class_variant#class-variant) value **)** |
| void | [set\_type\_variation](#class-theme-method-set-type-variation) **(** [String](class_string#class-string) theme\_type, [String](class_string#class-string) base\_type **)** |
Enumerations
------------
enum **DataType**:
* **DATA\_TYPE\_COLOR** = **0** --- Theme's [Color](class_color#class-color) item type.
* **DATA\_TYPE\_CONSTANT** = **1** --- Theme's constant item type.
* **DATA\_TYPE\_FONT** = **2** --- Theme's [Font](class_font#class-font) item type.
* **DATA\_TYPE\_ICON** = **3** --- Theme's icon [Texture](class_texture#class-texture) item type.
* **DATA\_TYPE\_STYLEBOX** = **4** --- Theme's [StyleBox](class_stylebox#class-stylebox) item type.
* **DATA\_TYPE\_MAX** = **5** --- Maximum value for the DataType enum.
Property Descriptions
---------------------
### [Font](class_font#class-font) default\_font
| | |
| --- | --- |
| *Setter* | set\_default\_font(value) |
| *Getter* | get\_default\_font() |
The default font of this `Theme` resource. Used as a fallback value for font items defined in this theme, but having invalid values. If this value is also invalid, the global default value is used.
Use [has\_default\_font](#class-theme-method-has-default-font) to check if this value is valid.
Method Descriptions
-------------------
### void add\_type ( [String](class_string#class-string) theme\_type )
Adds an empty theme type for every valid data type.
**Note:** Empty types are not saved with the theme. This method only exists to perform in-memory changes to the resource. Use available `set_*` methods to add theme items.
### void clear ( )
Clears all values on the theme.
### void clear\_color ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Clears the [Color](class_color#class-color) at `name` if the theme has `theme_type`.
### void clear\_constant ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Clears the constant at `name` if the theme has `theme_type`.
### void clear\_font ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Clears the [Font](class_font#class-font) at `name` if the theme has `theme_type`.
### void clear\_icon ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Clears the icon at `name` if the theme has `theme_type`.
### void clear\_stylebox ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Clears [StyleBox](class_stylebox#class-stylebox) at `name` if the theme has `theme_type`.
### void clear\_theme\_item ( [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Clears the theme item of `data_type` at `name` if the theme has `theme_type`.
### void clear\_type\_variation ( [String](class_string#class-string) theme\_type )
Unmarks `theme_type` as being a variation of another theme type. See [set\_type\_variation](#class-theme-method-set-type-variation).
### void copy\_default\_theme ( )
Sets the theme's values to a copy of the default theme values.
### void copy\_theme ( [Theme](#class-theme) other )
Sets the theme's values to a copy of a given theme.
### [Color](class_color#class-color) get\_color ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns the [Color](class_color#class-color) at `name` if the theme has `theme_type`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_color\_list ( [String](class_string#class-string) theme\_type ) const
Returns all the [Color](class_color#class-color)s as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with each [Color](class_color#class-color)'s name, for use in [get\_color](#class-theme-method-get-color), if the theme has `theme_type`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_color\_types ( ) const
Returns all the [Color](class_color#class-color) types as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with unique type names, for use in [get\_color](#class-theme-method-get-color) and/or [get\_color\_list](#class-theme-method-get-color-list).
### [int](class_int#class-int) get\_constant ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns the constant at `name` if the theme has `theme_type`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_constant\_list ( [String](class_string#class-string) theme\_type ) const
Returns all the constants as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with each constant's name, for use in [get\_constant](#class-theme-method-get-constant), if the theme has `theme_type`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_constant\_types ( ) const
Returns all the constant types as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with unique type names, for use in [get\_constant](#class-theme-method-get-constant) and/or [get\_constant\_list](#class-theme-method-get-constant-list).
### [Font](class_font#class-font) get\_font ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns the [Font](class_font#class-font) at `name` if the theme has `theme_type`. If such item does not exist and [default\_font](#class-theme-property-default-font) is set on the theme, the default font will be returned.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_font\_list ( [String](class_string#class-string) theme\_type ) const
Returns all the [Font](class_font#class-font)s as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with each [Font](class_font#class-font)'s name, for use in [get\_font](#class-theme-method-get-font), if the theme has `theme_type`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_font\_types ( ) const
Returns all the [Font](class_font#class-font) types as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with unique type names, for use in [get\_font](#class-theme-method-get-font) and/or [get\_font\_list](#class-theme-method-get-font-list).
### [Texture](class_texture#class-texture) get\_icon ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns the icon [Texture](class_texture#class-texture) at `name` if the theme has `theme_type`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_icon\_list ( [String](class_string#class-string) theme\_type ) const
Returns all the icons as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with each [Texture](class_texture#class-texture)'s name, for use in [get\_icon](#class-theme-method-get-icon), if the theme has `theme_type`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_icon\_types ( ) const
Returns all the icon types as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with unique type names, for use in [get\_icon](#class-theme-method-get-icon) and/or [get\_icon\_list](#class-theme-method-get-icon-list).
### [StyleBox](class_stylebox#class-stylebox) get\_stylebox ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns the [StyleBox](class_stylebox#class-stylebox) at `name` if the theme has `theme_type`.
Valid `name`s may be found using [get\_stylebox\_list](#class-theme-method-get-stylebox-list). Valid `theme_type`s may be found using [get\_stylebox\_types](#class-theme-method-get-stylebox-types).
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_stylebox\_list ( [String](class_string#class-string) theme\_type ) const
Returns all the [StyleBox](class_stylebox#class-stylebox)s as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with each [StyleBox](class_stylebox#class-stylebox)'s name, for use in [get\_stylebox](#class-theme-method-get-stylebox), if the theme has `theme_type`.
Valid `theme_type`s may be found using [get\_stylebox\_types](#class-theme-method-get-stylebox-types).
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_stylebox\_types ( ) const
Returns all the [StyleBox](class_stylebox#class-stylebox) types as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with unique type names, for use in [get\_stylebox](#class-theme-method-get-stylebox) and/or [get\_stylebox\_list](#class-theme-method-get-stylebox-list).
### [Variant](class_variant#class-variant) get\_theme\_item ( [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns the theme item of `data_type` at `name` if the theme has `theme_type`.
Valid `name`s may be found using [get\_theme\_item\_list](#class-theme-method-get-theme-item-list) or a data type specific method. Valid `theme_type`s may be found using [get\_theme\_item\_types](#class-theme-method-get-theme-item-types) or a data type specific method.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_theme\_item\_list ( [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) theme\_type ) const
Returns all the theme items of `data_type` as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with each theme items's name, for use in [get\_theme\_item](#class-theme-method-get-theme-item) or a data type specific method, if the theme has `theme_type`.
Valid `theme_type`s may be found using [get\_theme\_item\_types](#class-theme-method-get-theme-item-types) or a data type specific method.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_theme\_item\_types ( [DataType](#enum-theme-datatype) data\_type ) const
Returns all the theme items of `data_type` types as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with unique type names, for use in [get\_theme\_item](#class-theme-method-get-theme-item), [get\_theme\_item\_list](#class-theme-method-get-theme-item-list) or data type specific methods.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_type\_list ( [String](class_string#class-string) theme\_type ) const
Returns all the theme types as a [PoolStringArray](class_poolstringarray#class-poolstringarray) filled with unique type names, for use in other `get_*` functions of this theme.
**Note:** `theme_type` has no effect and will be removed in future version.
### [String](class_string#class-string) get\_type\_variation\_base ( [String](class_string#class-string) theme\_type ) const
Returns the name of the base theme type if `theme_type` is a valid variation type. Returns an empty string otherwise.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_type\_variation\_list ( [String](class_string#class-string) base\_type ) const
Returns a list of all type variations for the given `base_type`.
### [bool](class_bool#class-bool) has\_color ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns `true` if [Color](class_color#class-color) with `name` is in `theme_type`.
Returns `false` if the theme does not have `theme_type`.
### [bool](class_bool#class-bool) has\_constant ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns `true` if constant with `name` is in `theme_type`.
Returns `false` if the theme does not have `theme_type`.
### [bool](class_bool#class-bool) has\_default\_font ( ) const
Returns `true` if this theme has a valid [default\_font](#class-theme-property-default-font) value.
### [bool](class_bool#class-bool) has\_font ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns `true` if [Font](class_font#class-font) with `name` is in `theme_type`.
Returns `false` if the theme does not have `theme_type`.
### [bool](class_bool#class-bool) has\_icon ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns `true` if icon [Texture](class_texture#class-texture) with `name` is in `theme_type`.
Returns `false` if the theme does not have `theme_type`.
### [bool](class_bool#class-bool) has\_stylebox ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns `true` if [StyleBox](class_stylebox#class-stylebox) with `name` is in `theme_type`.
Returns `false` if the theme does not have `theme_type`.
### [bool](class_bool#class-bool) has\_theme\_item ( [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type ) const
Returns `true` if a theme item of `data_type` with `name` is in `theme_type`.
Returns `false` if the theme does not have `theme_type`.
### [bool](class_bool#class-bool) is\_type\_variation ( [String](class_string#class-string) theme\_type, [String](class_string#class-string) base\_type ) const
Returns `true` if `theme_type` is marked as a variation of `base_type`.
### void merge\_with ( [Theme](#class-theme) other )
Adds missing and overrides existing definitions with values from the `other` `Theme`.
**Note:** This modifies the current theme. If you want to merge two themes together without modifying either one, create a new empty theme and merge the other two into it one after another.
### void remove\_type ( [String](class_string#class-string) theme\_type )
Removes the theme type, gracefully discarding defined theme items. If the type is a variation, this information is also erased. If the type is a base for type variations, those variations lose their base.
### void rename\_color ( [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Renames the [Color](class_color#class-color) at `old_name` to `name` if the theme has `theme_type`. If `name` is already taken, this method fails.
### void rename\_constant ( [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Renames the constant at `old_name` to `name` if the theme has `theme_type`. If `name` is already taken, this method fails.
### void rename\_font ( [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Renames the [Font](class_font#class-font) at `old_name` to `name` if the theme has `theme_type`. If `name` is already taken, this method fails.
### void rename\_icon ( [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Renames the icon at `old_name` to `name` if the theme has `theme_type`. If `name` is already taken, this method fails.
### void rename\_stylebox ( [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Renames [StyleBox](class_stylebox#class-stylebox) at `old_name` to `name` if the theme has `theme_type`. If `name` is already taken, this method fails.
### void rename\_theme\_item ( [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) old\_name, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type )
Renames the theme item of `data_type` at `old_name` to `name` if the theme has `theme_type`. If `name` is already taken, this method fails.
### void set\_color ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Color](class_color#class-color) color )
Sets the theme's [Color](class_color#class-color) to `color` at `name` in `theme_type`.
Creates `theme_type` if the theme does not have it.
### void set\_constant ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [int](class_int#class-int) constant )
Sets the theme's constant to `constant` at `name` in `theme_type`.
Creates `theme_type` if the theme does not have it.
### void set\_font ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Font](class_font#class-font) font )
Sets the theme's [Font](class_font#class-font) to `font` at `name` in `theme_type`.
Creates `theme_type` if the theme does not have it.
### void set\_icon ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Texture](class_texture#class-texture) texture )
Sets the theme's icon [Texture](class_texture#class-texture) to `texture` at `name` in `theme_type`.
Creates `theme_type` if the theme does not have it.
### void set\_stylebox ( [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [StyleBox](class_stylebox#class-stylebox) texture )
Sets theme's [StyleBox](class_stylebox#class-stylebox) to `stylebox` at `name` in `theme_type`.
Creates `theme_type` if the theme does not have it.
### void set\_theme\_item ( [DataType](#enum-theme-datatype) data\_type, [String](class_string#class-string) name, [String](class_string#class-string) theme\_type, [Variant](class_variant#class-variant) value )
Sets the theme item of `data_type` to `value` at `name` in `theme_type`.
Does nothing if the `value` type does not match `data_type`.
Creates `theme_type` if the theme does not have it.
### void set\_type\_variation ( [String](class_string#class-string) theme\_type, [String](class_string#class-string) base\_type )
Marks `theme_type` as a variation of `base_type`.
This adds `theme_type` as a suggested option for [Control.theme\_type\_variation](class_control#class-control-property-theme-type-variation) on a [Control](class_control#class-control) that is of the `base_type` class.
Variations can also be nested, i.e. `base_type` can be another variation. If a chain of variations ends with a `base_type` matching the class of the [Control](class_control#class-control), the whole chain is going to be suggested as options.
**Note:** Suggestions only show up if this theme resource is set as the project default theme. See [ProjectSettings.gui/theme/custom](class_projectsettings#class-projectsettings-property-gui-theme-custom).
| programming_docs |
godot VisibilityNotifier VisibilityNotifier
==================
**Inherits:** [CullInstance](class_cullinstance#class-cullinstance) **<** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
**Inherited By:** [VisibilityEnabler](class_visibilityenabler#class-visibilityenabler)
Detects approximately when the node is visible on screen.
Description
-----------
The VisibilityNotifier detects when it is visible on the screen. It also notifies when its bounding rectangle enters or exits the screen or a [Camera](class_camera#class-camera)'s view.
If you want nodes to be disabled automatically when they exit the screen, use [VisibilityEnabler](class_visibilityenabler#class-visibilityenabler) instead.
**Note:** VisibilityNotifier uses an approximate heuristic for performance reasons. It doesn't take walls and other occlusion into account (unless you are using [Portal](class_portal#class-portal)s). The heuristic is an implementation detail and may change in future versions. If you need precise visibility checking, use another method such as adding an [Area](class_area#class-area) node as a child of a [Camera](class_camera#class-camera) node and/or [Vector3.dot](class_vector3#class-vector3-method-dot).
Properties
----------
| | | |
| --- | --- | --- |
| [AABB](class_aabb#class-aabb) | [aabb](#class-visibilitynotifier-property-aabb) | `AABB( -1, -1, -1, 2, 2, 2 )` |
| [float](class_float#class-float) | [max\_distance](#class-visibilitynotifier-property-max-distance) | `0.0` |
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [is\_on\_screen](#class-visibilitynotifier-method-is-on-screen) **(** **)** const |
Signals
-------
### camera\_entered ( [Camera](class_camera#class-camera) camera )
Emitted when the VisibilityNotifier enters a [Camera](class_camera#class-camera)'s view.
### camera\_exited ( [Camera](class_camera#class-camera) camera )
Emitted when the VisibilityNotifier exits a [Camera](class_camera#class-camera)'s view.
### screen\_entered ( )
Emitted when the VisibilityNotifier enters the screen.
### screen\_exited ( )
Emitted when the VisibilityNotifier exits the screen.
Property Descriptions
---------------------
### [AABB](class_aabb#class-aabb) aabb
| | |
| --- | --- |
| *Default* | `AABB( -1, -1, -1, 2, 2, 2 )` |
| *Setter* | set\_aabb(value) |
| *Getter* | get\_aabb() |
The VisibilityNotifier's bounding box.
### [float](class_float#class-float) max\_distance
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_max\_distance(value) |
| *Getter* | get\_max\_distance() |
In addition to checking whether a node is on screen or within a [Camera](class_camera#class-camera)'s view, VisibilityNotifier can also optionally check whether a node is within a specified maximum distance when using a [Camera](class_camera#class-camera) with perspective projection. This is useful for throttling the performance requirements of nodes that are far away.
**Note:** This feature will be disabled if set to 0.0.
Method Descriptions
-------------------
### [bool](class_bool#class-bool) is\_on\_screen ( ) const
If `true`, the bounding box is on the screen.
**Note:** It takes one frame for the node's visibility to be assessed once added to the scene tree, so this method will return `false` right after it is instantiated, even if it will be on screen in the draw pass.
godot Thread Thread
======
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A unit of execution in a process.
Description
-----------
A unit of execution in a process. Can run methods on [Object](class_object#class-object)s simultaneously. The use of synchronization via [Mutex](class_mutex#class-mutex) or [Semaphore](class_semaphore#class-semaphore) is advised if working with shared objects.
**Note:** Breakpoints won't break on code if it's running in a thread. This is a current limitation of the GDScript debugger.
Tutorials
---------
* [Using multiple threads](https://docs.godotengine.org/en/3.5/tutorials/performance/threads/using_multiple_threads.html)
* [Thread-safe APIs](https://docs.godotengine.org/en/3.5/tutorials/performance/threads/thread_safe_apis.html)
* [3D Voxel Demo](https://godotengine.org/asset-library/asset/676)
Methods
-------
| | |
| --- | --- |
| [String](class_string#class-string) | [get\_id](#class-thread-method-get-id) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_active](#class-thread-method-is-active) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_alive](#class-thread-method-is-alive) **(** **)** const |
| [Error](class_%40globalscope#enum-globalscope-error) | [start](#class-thread-method-start) **(** [Object](class_object#class-object) instance, [String](class_string#class-string) method, [Variant](class_variant#class-variant) userdata=null, [Priority](#enum-thread-priority) priority=1 **)** |
| [Variant](class_variant#class-variant) | [wait\_to\_finish](#class-thread-method-wait-to-finish) **(** **)** |
Enumerations
------------
enum **Priority**:
* **PRIORITY\_LOW** = **0** --- A thread running with lower priority than normally.
* **PRIORITY\_NORMAL** = **1** --- A thread with a standard priority.
* **PRIORITY\_HIGH** = **2** --- A thread running with higher priority than normally.
Method Descriptions
-------------------
### [String](class_string#class-string) get\_id ( ) const
Returns the current `Thread`'s ID, uniquely identifying it among all threads. If the `Thread` is not running this returns an empty string.
### [bool](class_bool#class-bool) is\_active ( ) const
Returns `true` if this `Thread` has been started. Once started, this will return `true` until it is joined using [wait\_to\_finish](#class-thread-method-wait-to-finish). For checking if a `Thread` is still executing its task, use [is\_alive](#class-thread-method-is-alive).
### [bool](class_bool#class-bool) is\_alive ( ) const
Returns `true` if this `Thread` is currently running. This is useful for determining if [wait\_to\_finish](#class-thread-method-wait-to-finish) can be called without blocking the calling thread.
To check if a `Thread` is joinable, use [is\_active](#class-thread-method-is-active).
### [Error](class_%40globalscope#enum-globalscope-error) start ( [Object](class_object#class-object) instance, [String](class_string#class-string) method, [Variant](class_variant#class-variant) userdata=null, [Priority](#enum-thread-priority) priority=1 )
Starts a new `Thread` that runs `method` on object `instance` with `userdata` passed as an argument. Even if no userdata is passed, `method` must accept one argument and it will be null. The `priority` of the `Thread` can be changed by passing a value from the [Priority](#enum-thread-priority) enum.
Returns [@GlobalScope.OK](class_%40globalscope#class-globalscope-constant-ok) on success, or [@GlobalScope.ERR\_CANT\_CREATE](class_%40globalscope#class-globalscope-constant-err-cant-create) on failure.
### [Variant](class_variant#class-variant) wait\_to\_finish ( )
Joins the `Thread` and waits for it to finish. Returns the output of the method passed to [start](#class-thread-method-start).
Should either be used when you want to retrieve the value returned from the method called by the `Thread` or before freeing the instance that contains the `Thread`.
To determine if this can be called without blocking the calling thread, check if [is\_alive](#class-thread-method-is-alive) is `false`.
**Note:** After the `Thread` finishes joining it will be disposed. If you want to use it again you will have to create a new instance of it.
godot GLTFAccessor GLTFAccessor
============
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Description
-----------
**Note:** This class is only compiled in editor builds. Run-time glTF loading and saving is *not* available in exported projects. References to `GLTFAccessor` within a script will cause an error in an exported project.
Properties
----------
| | | |
| --- | --- | --- |
| [int](class_int#class-int) | [buffer\_view](#class-gltfaccessor-property-buffer-view) | `0` |
| [int](class_int#class-int) | [byte\_offset](#class-gltfaccessor-property-byte-offset) | `0` |
| [int](class_int#class-int) | [component\_type](#class-gltfaccessor-property-component-type) | `0` |
| [int](class_int#class-int) | [count](#class-gltfaccessor-property-count) | `0` |
| [PoolRealArray](class_poolrealarray#class-poolrealarray) | [max](#class-gltfaccessor-property-max) | `PoolRealArray( )` |
| [PoolRealArray](class_poolrealarray#class-poolrealarray) | [min](#class-gltfaccessor-property-min) | `PoolRealArray( )` |
| [bool](class_bool#class-bool) | [normalized](#class-gltfaccessor-property-normalized) | `false` |
| [int](class_int#class-int) | [sparse\_count](#class-gltfaccessor-property-sparse-count) | `0` |
| [int](class_int#class-int) | [sparse\_indices\_buffer\_view](#class-gltfaccessor-property-sparse-indices-buffer-view) | `0` |
| [int](class_int#class-int) | [sparse\_indices\_byte\_offset](#class-gltfaccessor-property-sparse-indices-byte-offset) | `0` |
| [int](class_int#class-int) | [sparse\_indices\_component\_type](#class-gltfaccessor-property-sparse-indices-component-type) | `0` |
| [int](class_int#class-int) | [sparse\_values\_buffer\_view](#class-gltfaccessor-property-sparse-values-buffer-view) | `0` |
| [int](class_int#class-int) | [sparse\_values\_byte\_offset](#class-gltfaccessor-property-sparse-values-byte-offset) | `0` |
| [int](class_int#class-int) | [type](#class-gltfaccessor-property-type) | `0` |
Property Descriptions
---------------------
### [int](class_int#class-int) buffer\_view
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_buffer\_view(value) |
| *Getter* | get\_buffer\_view() |
### [int](class_int#class-int) byte\_offset
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_byte\_offset(value) |
| *Getter* | get\_byte\_offset() |
### [int](class_int#class-int) component\_type
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_component\_type(value) |
| *Getter* | get\_component\_type() |
### [int](class_int#class-int) count
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_count(value) |
| *Getter* | get\_count() |
### [PoolRealArray](class_poolrealarray#class-poolrealarray) max
| | |
| --- | --- |
| *Default* | `PoolRealArray( )` |
| *Setter* | set\_max(value) |
| *Getter* | get\_max() |
### [PoolRealArray](class_poolrealarray#class-poolrealarray) min
| | |
| --- | --- |
| *Default* | `PoolRealArray( )` |
| *Setter* | set\_min(value) |
| *Getter* | get\_min() |
### [bool](class_bool#class-bool) normalized
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_normalized(value) |
| *Getter* | get\_normalized() |
### [int](class_int#class-int) sparse\_count
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_sparse\_count(value) |
| *Getter* | get\_sparse\_count() |
### [int](class_int#class-int) sparse\_indices\_buffer\_view
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_sparse\_indices\_buffer\_view(value) |
| *Getter* | get\_sparse\_indices\_buffer\_view() |
### [int](class_int#class-int) sparse\_indices\_byte\_offset
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_sparse\_indices\_byte\_offset(value) |
| *Getter* | get\_sparse\_indices\_byte\_offset() |
### [int](class_int#class-int) sparse\_indices\_component\_type
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_sparse\_indices\_component\_type(value) |
| *Getter* | get\_sparse\_indices\_component\_type() |
### [int](class_int#class-int) sparse\_values\_buffer\_view
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_sparse\_values\_buffer\_view(value) |
| *Getter* | get\_sparse\_values\_buffer\_view() |
### [int](class_int#class-int) sparse\_values\_byte\_offset
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_sparse\_values\_byte\_offset(value) |
| *Getter* | get\_sparse\_values\_byte\_offset() |
### [int](class_int#class-int) type
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_type(value) |
| *Getter* | get\_type() |
godot Mesh Mesh
====
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [ArrayMesh](class_arraymesh#class-arraymesh), [PrimitiveMesh](class_primitivemesh#class-primitivemesh)
A [Resource](class_resource#class-resource) that contains vertex array-based geometry.
Description
-----------
Mesh is a type of [Resource](class_resource#class-resource) that contains vertex array-based geometry, divided in *surfaces*. Each surface contains a completely separate array and a material used to draw it. Design wise, a mesh with multiple surfaces is preferred to a single surface, because objects created in 3D editing software commonly contain multiple materials.
Tutorials
---------
* [3D Material Testers Demo](https://godotengine.org/asset-library/asset/123)
* [3D Kinematic Character Demo](https://godotengine.org/asset-library/asset/126)
* [3D Platformer Demo](https://godotengine.org/asset-library/asset/125)
* [Third Person Shooter Demo](https://godotengine.org/asset-library/asset/678)
Properties
----------
| | | |
| --- | --- | --- |
| [Vector2](class_vector2#class-vector2) | [lightmap\_size\_hint](#class-mesh-property-lightmap-size-hint) | `Vector2( 0, 0 )` |
Methods
-------
| | |
| --- | --- |
| [Shape](class_shape#class-shape) | [create\_convex\_shape](#class-mesh-method-create-convex-shape) **(** [bool](class_bool#class-bool) clean=true, [bool](class_bool#class-bool) simplify=false **)** const |
| [Mesh](#class-mesh) | [create\_outline](#class-mesh-method-create-outline) **(** [float](class_float#class-float) margin **)** const |
| [Shape](class_shape#class-shape) | [create\_trimesh\_shape](#class-mesh-method-create-trimesh-shape) **(** **)** const |
| [TriangleMesh](class_trianglemesh#class-trianglemesh) | [generate\_triangle\_mesh](#class-mesh-method-generate-triangle-mesh) **(** **)** const |
| [AABB](class_aabb#class-aabb) | [get\_aabb](#class-mesh-method-get-aabb) **(** **)** const |
| [PoolVector3Array](class_poolvector3array#class-poolvector3array) | [get\_faces](#class-mesh-method-get-faces) **(** **)** const |
| [int](class_int#class-int) | [get\_surface\_count](#class-mesh-method-get-surface-count) **(** **)** const |
| [Array](class_array#class-array) | [surface\_get\_arrays](#class-mesh-method-surface-get-arrays) **(** [int](class_int#class-int) surf\_idx **)** const |
| [Array](class_array#class-array) | [surface\_get\_blend\_shape\_arrays](#class-mesh-method-surface-get-blend-shape-arrays) **(** [int](class_int#class-int) surf\_idx **)** const |
| [Material](class_material#class-material) | [surface\_get\_material](#class-mesh-method-surface-get-material) **(** [int](class_int#class-int) surf\_idx **)** const |
| void | [surface\_set\_material](#class-mesh-method-surface-set-material) **(** [int](class_int#class-int) surf\_idx, [Material](class_material#class-material) material **)** |
Enumerations
------------
enum **PrimitiveType**:
* **PRIMITIVE\_POINTS** = **0** --- Render array as points (one vertex equals one point).
* **PRIMITIVE\_LINES** = **1** --- Render array as lines (every two vertices a line is created).
* **PRIMITIVE\_LINE\_STRIP** = **2** --- Render array as line strip.
* **PRIMITIVE\_LINE\_LOOP** = **3** --- Render array as line loop (like line strip, but closed).
* **PRIMITIVE\_TRIANGLES** = **4** --- Render array as triangles (every three vertices a triangle is created).
* **PRIMITIVE\_TRIANGLE\_STRIP** = **5** --- Render array as triangle strips.
* **PRIMITIVE\_TRIANGLE\_FAN** = **6** --- Render array as triangle fans.
enum **BlendShapeMode**:
* **BLEND\_SHAPE\_MODE\_NORMALIZED** = **0** --- Blend shapes are normalized.
* **BLEND\_SHAPE\_MODE\_RELATIVE** = **1** --- Blend shapes are relative to base weight.
enum **ArrayFormat**:
* **ARRAY\_FORMAT\_VERTEX** = **1** --- Mesh array contains vertices. All meshes require a vertex array so this should always be present.
* **ARRAY\_FORMAT\_NORMAL** = **2** --- Mesh array contains normals.
* **ARRAY\_FORMAT\_TANGENT** = **4** --- Mesh array contains tangents.
* **ARRAY\_FORMAT\_COLOR** = **8** --- Mesh array contains colors.
* **ARRAY\_FORMAT\_TEX\_UV** = **16** --- Mesh array contains UVs.
* **ARRAY\_FORMAT\_TEX\_UV2** = **32** --- Mesh array contains second UV.
* **ARRAY\_FORMAT\_BONES** = **64** --- Mesh array contains bones.
* **ARRAY\_FORMAT\_WEIGHTS** = **128** --- Mesh array contains bone weights.
* **ARRAY\_FORMAT\_INDEX** = **256** --- Mesh array uses indices.
* **ARRAY\_COMPRESS\_BASE** = **9** --- Used internally to calculate other `ARRAY_COMPRESS_*` enum values. Do not use.
* **ARRAY\_COMPRESS\_VERTEX** = **512** --- Flag used to mark a compressed (half float) vertex array.
* **ARRAY\_COMPRESS\_NORMAL** = **1024** --- Flag used to mark a compressed (half float) normal array.
* **ARRAY\_COMPRESS\_TANGENT** = **2048** --- Flag used to mark a compressed (half float) tangent array.
* **ARRAY\_COMPRESS\_COLOR** = **4096** --- Flag used to mark a compressed (half float) color array.
**Note:** If this flag is enabled, vertex colors will be stored as 8-bit unsigned integers. This will clamp overbright colors to `Color(1, 1, 1, 1)` and reduce colors' precision.
* **ARRAY\_COMPRESS\_TEX\_UV** = **8192** --- Flag used to mark a compressed (half float) UV coordinates array.
* **ARRAY\_COMPRESS\_TEX\_UV2** = **16384** --- Flag used to mark a compressed (half float) UV coordinates array for the second UV coordinates.
* **ARRAY\_COMPRESS\_BONES** = **32768** --- Flag used to mark a compressed bone array.
* **ARRAY\_COMPRESS\_WEIGHTS** = **65536** --- Flag used to mark a compressed (half float) weight array.
* **ARRAY\_COMPRESS\_INDEX** = **131072** --- Flag used to mark a compressed index array.
* **ARRAY\_FLAG\_USE\_2D\_VERTICES** = **262144** --- Flag used to mark that the array contains 2D vertices.
* **ARRAY\_FLAG\_USE\_16\_BIT\_BONES** = **524288** --- Flag used to mark that the array uses 16-bit bones instead of 8-bit.
* **ARRAY\_FLAG\_USE\_OCTAHEDRAL\_COMPRESSION** = **2097152** --- Flag used to mark that the array uses an octahedral representation of normal and tangent vectors rather than cartesian.
* **ARRAY\_COMPRESS\_DEFAULT** = **2194432** --- Used to set flags [ARRAY\_COMPRESS\_VERTEX](#class-mesh-constant-array-compress-vertex), [ARRAY\_COMPRESS\_NORMAL](#class-mesh-constant-array-compress-normal), [ARRAY\_COMPRESS\_TANGENT](#class-mesh-constant-array-compress-tangent), [ARRAY\_COMPRESS\_COLOR](#class-mesh-constant-array-compress-color), [ARRAY\_COMPRESS\_TEX\_UV](#class-mesh-constant-array-compress-tex-uv), [ARRAY\_COMPRESS\_TEX\_UV2](#class-mesh-constant-array-compress-tex-uv2), [ARRAY\_COMPRESS\_WEIGHTS](#class-mesh-constant-array-compress-weights), and [ARRAY\_FLAG\_USE\_OCTAHEDRAL\_COMPRESSION](#class-mesh-constant-array-flag-use-octahedral-compression) quickly.
**Note:** Since this flag enables [ARRAY\_COMPRESS\_COLOR](#class-mesh-constant-array-compress-color), vertex colors will be stored as 8-bit unsigned integers. This will clamp overbright colors to `Color(1, 1, 1, 1)` and reduce colors' precision.
enum **ArrayType**:
* **ARRAY\_VERTEX** = **0** --- Array of vertices.
* **ARRAY\_NORMAL** = **1** --- Array of normals.
* **ARRAY\_TANGENT** = **2** --- Array of tangents as an array of floats, 4 floats per tangent.
* **ARRAY\_COLOR** = **3** --- Array of colors.
* **ARRAY\_TEX\_UV** = **4** --- Array of UV coordinates.
* **ARRAY\_TEX\_UV2** = **5** --- Array of second set of UV coordinates.
* **ARRAY\_BONES** = **6** --- Array of bone data.
* **ARRAY\_WEIGHTS** = **7** --- Array of weights.
* **ARRAY\_INDEX** = **8** --- Array of indices.
* **ARRAY\_MAX** = **9** --- Represents the size of the [ArrayType](#enum-mesh-arraytype) enum.
Property Descriptions
---------------------
### [Vector2](class_vector2#class-vector2) lightmap\_size\_hint
| | |
| --- | --- |
| *Default* | `Vector2( 0, 0 )` |
| *Setter* | set\_lightmap\_size\_hint(value) |
| *Getter* | get\_lightmap\_size\_hint() |
Sets a hint to be used for lightmap resolution in [BakedLightmap](class_bakedlightmap#class-bakedlightmap). Overrides [BakedLightmap.default\_texels\_per\_unit](class_bakedlightmap#class-bakedlightmap-property-default-texels-per-unit).
Method Descriptions
-------------------
### [Shape](class_shape#class-shape) create\_convex\_shape ( [bool](class_bool#class-bool) clean=true, [bool](class_bool#class-bool) simplify=false ) const
Calculate a [ConvexPolygonShape](class_convexpolygonshape#class-convexpolygonshape) from the mesh.
If `clean` is `true` (default), duplicate and interior vertices are removed automatically. You can set it to `false` to make the process faster if not needed.
If `simplify` is `true`, the geometry can be further simplified to reduce the amount of vertices. Disabled by default.
### [Mesh](#class-mesh) create\_outline ( [float](class_float#class-float) margin ) const
Calculate an outline mesh at a defined offset (margin) from the original mesh.
**Note:** This method typically returns the vertices in reverse order (e.g. clockwise to counterclockwise).
### [Shape](class_shape#class-shape) create\_trimesh\_shape ( ) const
Calculate a [ConcavePolygonShape](class_concavepolygonshape#class-concavepolygonshape) from the mesh.
### [TriangleMesh](class_trianglemesh#class-trianglemesh) generate\_triangle\_mesh ( ) const
Generate a [TriangleMesh](class_trianglemesh#class-trianglemesh) from the mesh.
### [AABB](class_aabb#class-aabb) get\_aabb ( ) const
Returns the smallest [AABB](class_aabb#class-aabb) enclosing this mesh in local space. Not affected by `custom_aabb`. See also [VisualInstance.get\_transformed\_aabb](class_visualinstance#class-visualinstance-method-get-transformed-aabb).
**Note:** This is only implemented for [ArrayMesh](class_arraymesh#class-arraymesh) and [PrimitiveMesh](class_primitivemesh#class-primitivemesh).
### [PoolVector3Array](class_poolvector3array#class-poolvector3array) get\_faces ( ) const
Returns all the vertices that make up the faces of the mesh. Each three vertices represent one triangle.
### [int](class_int#class-int) get\_surface\_count ( ) const
Returns the amount of surfaces that the `Mesh` holds.
### [Array](class_array#class-array) surface\_get\_arrays ( [int](class_int#class-int) surf\_idx ) const
Returns the arrays for the vertices, normals, uvs, etc. that make up the requested surface (see [ArrayMesh.add\_surface\_from\_arrays](class_arraymesh#class-arraymesh-method-add-surface-from-arrays)).
### [Array](class_array#class-array) surface\_get\_blend\_shape\_arrays ( [int](class_int#class-int) surf\_idx ) const
Returns the blend shape arrays for the requested surface.
### [Material](class_material#class-material) surface\_get\_material ( [int](class_int#class-int) surf\_idx ) const
Returns a [Material](class_material#class-material) in a given surface. Surface is rendered using this material.
### void surface\_set\_material ( [int](class_int#class-int) surf\_idx, [Material](class_material#class-material) material )
Sets a [Material](class_material#class-material) for a given surface. Surface will be rendered using this material.
| programming_docs |
godot VisualShaderNodeVectorDecompose VisualShaderNodeVectorDecompose
===============================
**Inherits:** [VisualShaderNode](class_visualshadernode#class-visualshadernode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Decomposes a [Vector3](class_vector3#class-vector3) into three scalars within the visual shader graph.
Description
-----------
Takes a `vec3` and decomposes it into three scalar values that can be used as separate inputs.
godot YSort YSort
=====
**Inherits:** [Node2D](class_node2d#class-node2d) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Sort all child nodes based on their Y positions.
Description
-----------
Sort all child nodes based on their Y positions. The child node must inherit from [CanvasItem](class_canvasitem#class-canvasitem) for it to be sorted. Nodes that have a higher Y position will be drawn later, so they will appear on top of nodes that have a lower Y position.
Nesting of YSort nodes is possible. Children YSort nodes will be sorted in the same space as the parent YSort, allowing to better organize a scene or divide it in multiple ones, yet keep the unique sorting.
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | [sort\_enabled](#class-ysort-property-sort-enabled) | `true` |
Property Descriptions
---------------------
### [bool](class_bool#class-bool) sort\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_sort\_enabled(value) |
| *Getter* | is\_sort\_enabled() |
If `true`, child nodes are sorted, otherwise sorting is disabled.
godot ShaderMaterial ShaderMaterial
==============
**Inherits:** [Material](class_material#class-material) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A material that uses a custom [Shader](class_shader#class-shader) program.
Description
-----------
A material that uses a custom [Shader](class_shader#class-shader) program to render either items to screen or process particles. You can create multiple materials for the same shader but configure different values for the uniforms defined in the shader.
**Note:** Due to a renderer limitation, emissive `ShaderMaterial`s cannot emit light when used in a [GIProbe](class_giprobe#class-giprobe). Only emissive [SpatialMaterial](class_spatialmaterial#class-spatialmaterial)s can emit light in a [GIProbe](class_giprobe#class-giprobe).
Tutorials
---------
* [Shaders](https://docs.godotengine.org/en/3.5/tutorials/shaders/index.html)
Properties
----------
| | |
| --- | --- |
| [Shader](class_shader#class-shader) | [shader](#class-shadermaterial-property-shader) |
Methods
-------
| | |
| --- | --- |
| [Variant](class_variant#class-variant) | [get\_shader\_param](#class-shadermaterial-method-get-shader-param) **(** [String](class_string#class-string) param **)** const |
| [bool](class_bool#class-bool) | [property\_can\_revert](#class-shadermaterial-method-property-can-revert) **(** [String](class_string#class-string) name **)** |
| [Variant](class_variant#class-variant) | [property\_get\_revert](#class-shadermaterial-method-property-get-revert) **(** [String](class_string#class-string) name **)** |
| void | [set\_shader\_param](#class-shadermaterial-method-set-shader-param) **(** [String](class_string#class-string) param, [Variant](class_variant#class-variant) value **)** |
Property Descriptions
---------------------
### [Shader](class_shader#class-shader) shader
| | |
| --- | --- |
| *Setter* | set\_shader(value) |
| *Getter* | get\_shader() |
The [Shader](class_shader#class-shader) program used to render this material.
Method Descriptions
-------------------
### [Variant](class_variant#class-variant) get\_shader\_param ( [String](class_string#class-string) param ) const
Returns the current value set for this material of a uniform in the shader.
### [bool](class_bool#class-bool) property\_can\_revert ( [String](class_string#class-string) name )
Returns `true` if the property identified by `name` can be reverted to a default value.
### [Variant](class_variant#class-variant) property\_get\_revert ( [String](class_string#class-string) name )
Returns the default value of the material property with given `name`.
### void set\_shader\_param ( [String](class_string#class-string) param, [Variant](class_variant#class-variant) value )
Changes the value set for this material of a uniform in the shader.
**Note:** `param` must match the name of the uniform in the code exactly.
godot ARVRInterfaceGDNative ARVRInterfaceGDNative
=====================
**Inherits:** [ARVRInterface](class_arvrinterface#class-arvrinterface) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
GDNative wrapper for an ARVR interface.
Description
-----------
This is a wrapper class for GDNative implementations of the ARVR interface. To use a GDNative ARVR interface, simply instantiate this object and set your GDNative library containing the ARVR interface implementation.
godot AudioEffectPhaser AudioEffectPhaser
=================
**Inherits:** [AudioEffect](class_audioeffect#class-audioeffect) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Adds a phaser audio effect to an Audio bus.
Combines the original signal with a copy that is slightly out of phase with the original.
Description
-----------
Combines phase-shifted signals with the original signal. The movement of the phase-shifted signals is controlled using a low-frequency oscillator.
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [depth](#class-audioeffectphaser-property-depth) | `1.0` |
| [float](class_float#class-float) | [feedback](#class-audioeffectphaser-property-feedback) | `0.7` |
| [float](class_float#class-float) | [range\_max\_hz](#class-audioeffectphaser-property-range-max-hz) | `1600.0` |
| [float](class_float#class-float) | [range\_min\_hz](#class-audioeffectphaser-property-range-min-hz) | `440.0` |
| [float](class_float#class-float) | [rate\_hz](#class-audioeffectphaser-property-rate-hz) | `0.5` |
Property Descriptions
---------------------
### [float](class_float#class-float) depth
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_depth(value) |
| *Getter* | get\_depth() |
Governs how high the filter frequencies sweep. Low value will primarily affect bass frequencies. High value can sweep high into the treble. Value can range from 0.1 to 4.
### [float](class_float#class-float) feedback
| | |
| --- | --- |
| *Default* | `0.7` |
| *Setter* | set\_feedback(value) |
| *Getter* | get\_feedback() |
Output percent of modified sound. Value can range from 0.1 to 0.9.
### [float](class_float#class-float) range\_max\_hz
| | |
| --- | --- |
| *Default* | `1600.0` |
| *Setter* | set\_range\_max\_hz(value) |
| *Getter* | get\_range\_max\_hz() |
Determines the maximum frequency affected by the LFO modulations, in Hz. Value can range from 10 to 10000.
### [float](class_float#class-float) range\_min\_hz
| | |
| --- | --- |
| *Default* | `440.0` |
| *Setter* | set\_range\_min\_hz(value) |
| *Getter* | get\_range\_min\_hz() |
Determines the minimum frequency affected by the LFO modulations, in Hz. Value can range from 10 to 10000.
### [float](class_float#class-float) rate\_hz
| | |
| --- | --- |
| *Default* | `0.5` |
| *Setter* | set\_rate\_hz(value) |
| *Getter* | get\_rate\_hz() |
Adjusts the rate in Hz at which the effect sweeps up and down across the frequency range.
godot ProjectSettings ProjectSettings
===============
**Inherits:** [Object](class_object#class-object)
Contains global variables accessible from everywhere.
Description
-----------
Contains global variables accessible from everywhere. Use [get\_setting](#class-projectsettings-method-get-setting), [set\_setting](#class-projectsettings-method-set-setting) or [has\_setting](#class-projectsettings-method-has-setting) to access them. Variables stored in `project.godot` are also loaded into ProjectSettings, making this object very useful for reading custom game configuration options.
When naming a Project Settings property, use the full path to the setting including the category. For example, `"application/config/name"` for the project name. Category and property names can be viewed in the Project Settings dialog.
**Feature tags:** Project settings can be overridden for specific platforms and configurations (debug, release, ...) using [feature tags](https://docs.godotengine.org/en/3.5/tutorials/export/feature_tags.html).
**Overriding:** Any project setting can be overridden by creating a file named `override.cfg` in the project's root directory. This can also be used in exported projects by placing this file in the same directory as the project binary. Overriding will still take the base project settings' [feature tags](https://docs.godotengine.org/en/3.5/tutorials/export/feature_tags.html) in account. Therefore, make sure to *also* override the setting with the desired feature tags if you want them to override base project settings on all platforms and configurations.
Tutorials
---------
* [3D Physics Tests Demo](https://godotengine.org/asset-library/asset/675)
* [3D Platformer Demo](https://godotengine.org/asset-library/asset/125)
* [OS Test Demo](https://godotengine.org/asset-library/asset/677)
Properties
----------
| | | |
| --- | --- | --- |
| [String](class_string#class-string) | [android/modules](#class-projectsettings-property-android-modules) | `""` |
| [Color](class_color#class-color) | [application/boot\_splash/bg\_color](#class-projectsettings-property-application-boot-splash-bg-color) | `Color( 0.14, 0.14, 0.14, 1 )` |
| [bool](class_bool#class-bool) | [application/boot\_splash/fullsize](#class-projectsettings-property-application-boot-splash-fullsize) | `true` |
| [String](class_string#class-string) | [application/boot\_splash/image](#class-projectsettings-property-application-boot-splash-image) | `""` |
| [bool](class_bool#class-bool) | [application/boot\_splash/show\_image](#class-projectsettings-property-application-boot-splash-show-image) | `true` |
| [bool](class_bool#class-bool) | [application/boot\_splash/use\_filter](#class-projectsettings-property-application-boot-splash-use-filter) | `true` |
| [String](class_string#class-string) | [application/config/custom\_user\_dir\_name](#class-projectsettings-property-application-config-custom-user-dir-name) | `""` |
| [String](class_string#class-string) | [application/config/description](#class-projectsettings-property-application-config-description) | `""` |
| [String](class_string#class-string) | [application/config/icon](#class-projectsettings-property-application-config-icon) | `""` |
| [String](class_string#class-string) | [application/config/macos\_native\_icon](#class-projectsettings-property-application-config-macos-native-icon) | `""` |
| [String](class_string#class-string) | [application/config/name](#class-projectsettings-property-application-config-name) | `""` |
| [String](class_string#class-string) | [application/config/project\_settings\_override](#class-projectsettings-property-application-config-project-settings-override) | `""` |
| [bool](class_bool#class-bool) | [application/config/use\_custom\_user\_dir](#class-projectsettings-property-application-config-use-custom-user-dir) | `false` |
| [bool](class_bool#class-bool) | [application/config/use\_hidden\_project\_data\_directory](#class-projectsettings-property-application-config-use-hidden-project-data-directory) | `true` |
| [String](class_string#class-string) | [application/config/windows\_native\_icon](#class-projectsettings-property-application-config-windows-native-icon) | `""` |
| [bool](class_bool#class-bool) | [application/run/delta\_smoothing](#class-projectsettings-property-application-run-delta-smoothing) | `true` |
| [bool](class_bool#class-bool) | [application/run/delta\_sync\_after\_draw](#class-projectsettings-property-application-run-delta-sync-after-draw) | `false` |
| [bool](class_bool#class-bool) | [application/run/disable\_stderr](#class-projectsettings-property-application-run-disable-stderr) | `false` |
| [bool](class_bool#class-bool) | [application/run/disable\_stdout](#class-projectsettings-property-application-run-disable-stdout) | `false` |
| [bool](class_bool#class-bool) | [application/run/flush\_stdout\_on\_print](#class-projectsettings-property-application-run-flush-stdout-on-print) | `false` |
| [bool](class_bool#class-bool) | [application/run/flush\_stdout\_on\_print.debug](#class-projectsettings-property-application-run-flush-stdout-on-print-debug) | `true` |
| [int](class_int#class-int) | [application/run/frame\_delay\_msec](#class-projectsettings-property-application-run-frame-delay-msec) | `0` |
| [bool](class_bool#class-bool) | [application/run/low\_processor\_mode](#class-projectsettings-property-application-run-low-processor-mode) | `false` |
| [int](class_int#class-int) | [application/run/low\_processor\_mode\_sleep\_usec](#class-projectsettings-property-application-run-low-processor-mode-sleep-usec) | `6900` |
| [String](class_string#class-string) | [application/run/main\_scene](#class-projectsettings-property-application-run-main-scene) | `""` |
| [float](class_float#class-float) | [audio/channel\_disable\_threshold\_db](#class-projectsettings-property-audio-channel-disable-threshold-db) | `-60.0` |
| [float](class_float#class-float) | [audio/channel\_disable\_time](#class-projectsettings-property-audio-channel-disable-time) | `2.0` |
| [String](class_string#class-string) | [audio/default\_bus\_layout](#class-projectsettings-property-audio-default-bus-layout) | `"res://default_bus_layout.tres"` |
| [String](class_string#class-string) | [audio/driver](#class-projectsettings-property-audio-driver) | |
| [bool](class_bool#class-bool) | [audio/enable\_audio\_input](#class-projectsettings-property-audio-enable-audio-input) | `false` |
| [int](class_int#class-int) | [audio/mix\_rate](#class-projectsettings-property-audio-mix-rate) | `44100` |
| [int](class_int#class-int) | [audio/mix\_rate.web](#class-projectsettings-property-audio-mix-rate-web) | `0` |
| [int](class_int#class-int) | [audio/output\_latency](#class-projectsettings-property-audio-output-latency) | `15` |
| [int](class_int#class-int) | [audio/output\_latency.web](#class-projectsettings-property-audio-output-latency-web) | `50` |
| [int](class_int#class-int) | [audio/video\_delay\_compensation\_ms](#class-projectsettings-property-audio-video-delay-compensation-ms) | `0` |
| [int](class_int#class-int) | [compression/formats/gzip/compression\_level](#class-projectsettings-property-compression-formats-gzip-compression-level) | `-1` |
| [int](class_int#class-int) | [compression/formats/zlib/compression\_level](#class-projectsettings-property-compression-formats-zlib-compression-level) | `-1` |
| [int](class_int#class-int) | [compression/formats/zstd/compression\_level](#class-projectsettings-property-compression-formats-zstd-compression-level) | `3` |
| [bool](class_bool#class-bool) | [compression/formats/zstd/long\_distance\_matching](#class-projectsettings-property-compression-formats-zstd-long-distance-matching) | `false` |
| [int](class_int#class-int) | [compression/formats/zstd/window\_log\_size](#class-projectsettings-property-compression-formats-zstd-window-log-size) | `27` |
| [bool](class_bool#class-bool) | [debug/gdscript/completion/autocomplete\_setters\_and\_getters](#class-projectsettings-property-debug-gdscript-completion-autocomplete-setters-and-getters) | `false` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/constant\_used\_as\_function](#class-projectsettings-property-debug-gdscript-warnings-constant-used-as-function) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/deprecated\_keyword](#class-projectsettings-property-debug-gdscript-warnings-deprecated-keyword) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/enable](#class-projectsettings-property-debug-gdscript-warnings-enable) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/exclude\_addons](#class-projectsettings-property-debug-gdscript-warnings-exclude-addons) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/export\_hint\_type\_mistmatch](#class-projectsettings-property-debug-gdscript-warnings-export-hint-type-mistmatch) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/function\_conflicts\_constant](#class-projectsettings-property-debug-gdscript-warnings-function-conflicts-constant) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/function\_conflicts\_variable](#class-projectsettings-property-debug-gdscript-warnings-function-conflicts-variable) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/function\_may\_yield](#class-projectsettings-property-debug-gdscript-warnings-function-may-yield) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/function\_used\_as\_property](#class-projectsettings-property-debug-gdscript-warnings-function-used-as-property) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/incompatible\_ternary](#class-projectsettings-property-debug-gdscript-warnings-incompatible-ternary) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/integer\_division](#class-projectsettings-property-debug-gdscript-warnings-integer-division) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/narrowing\_conversion](#class-projectsettings-property-debug-gdscript-warnings-narrowing-conversion) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/property\_used\_as\_function](#class-projectsettings-property-debug-gdscript-warnings-property-used-as-function) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/return\_value\_discarded](#class-projectsettings-property-debug-gdscript-warnings-return-value-discarded) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/shadowed\_variable](#class-projectsettings-property-debug-gdscript-warnings-shadowed-variable) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/standalone\_expression](#class-projectsettings-property-debug-gdscript-warnings-standalone-expression) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/standalone\_ternary](#class-projectsettings-property-debug-gdscript-warnings-standalone-ternary) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/treat\_warnings\_as\_errors](#class-projectsettings-property-debug-gdscript-warnings-treat-warnings-as-errors) | `false` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unassigned\_variable](#class-projectsettings-property-debug-gdscript-warnings-unassigned-variable) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unassigned\_variable\_op\_assign](#class-projectsettings-property-debug-gdscript-warnings-unassigned-variable-op-assign) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unreachable\_code](#class-projectsettings-property-debug-gdscript-warnings-unreachable-code) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unsafe\_call\_argument](#class-projectsettings-property-debug-gdscript-warnings-unsafe-call-argument) | `false` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unsafe\_cast](#class-projectsettings-property-debug-gdscript-warnings-unsafe-cast) | `false` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unsafe\_method\_access](#class-projectsettings-property-debug-gdscript-warnings-unsafe-method-access) | `false` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unsafe\_property\_access](#class-projectsettings-property-debug-gdscript-warnings-unsafe-property-access) | `false` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unused\_argument](#class-projectsettings-property-debug-gdscript-warnings-unused-argument) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unused\_class\_variable](#class-projectsettings-property-debug-gdscript-warnings-unused-class-variable) | `false` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unused\_signal](#class-projectsettings-property-debug-gdscript-warnings-unused-signal) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/unused\_variable](#class-projectsettings-property-debug-gdscript-warnings-unused-variable) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/variable\_conflicts\_function](#class-projectsettings-property-debug-gdscript-warnings-variable-conflicts-function) | `true` |
| [bool](class_bool#class-bool) | [debug/gdscript/warnings/void\_assignment](#class-projectsettings-property-debug-gdscript-warnings-void-assignment) | `true` |
| [String](class_string#class-string) | [debug/settings/crash\_handler/message](#class-projectsettings-property-debug-settings-crash-handler-message) | `"Please include this when reporting the bug to the project developer."` |
| [String](class_string#class-string) | [debug/settings/crash\_handler/message.editor](#class-projectsettings-property-debug-settings-crash-handler-message-editor) | `"Please include this when reporting the bug on: https://github.com/godotengine/godot/issues"` |
| [int](class_int#class-int) | [debug/settings/fps/force\_fps](#class-projectsettings-property-debug-settings-fps-force-fps) | `0` |
| [int](class_int#class-int) | [debug/settings/gdscript/max\_call\_stack](#class-projectsettings-property-debug-settings-gdscript-max-call-stack) | `1024` |
| [bool](class_bool#class-bool) | [debug/settings/physics\_interpolation/enable\_warnings](#class-projectsettings-property-debug-settings-physics-interpolation-enable-warnings) | `true` |
| [int](class_int#class-int) | [debug/settings/profiler/max\_functions](#class-projectsettings-property-debug-settings-profiler-max-functions) | `16384` |
| [bool](class_bool#class-bool) | [debug/settings/stdout/print\_fps](#class-projectsettings-property-debug-settings-stdout-print-fps) | `false` |
| [bool](class_bool#class-bool) | [debug/settings/stdout/verbose\_stdout](#class-projectsettings-property-debug-settings-stdout-verbose-stdout) | `false` |
| [int](class_int#class-int) | [debug/settings/visual\_script/max\_call\_stack](#class-projectsettings-property-debug-settings-visual-script-max-call-stack) | `1024` |
| [Color](class_color#class-color) | [debug/shapes/collision/contact\_color](#class-projectsettings-property-debug-shapes-collision-contact-color) | `Color( 1, 0.2, 0.1, 0.8 )` |
| [bool](class_bool#class-bool) | [debug/shapes/collision/draw\_2d\_outlines](#class-projectsettings-property-debug-shapes-collision-draw-2d-outlines) | `true` |
| [int](class_int#class-int) | [debug/shapes/collision/max\_contacts\_displayed](#class-projectsettings-property-debug-shapes-collision-max-contacts-displayed) | `10000` |
| [Color](class_color#class-color) | [debug/shapes/collision/shape\_color](#class-projectsettings-property-debug-shapes-collision-shape-color) | `Color( 0, 0.6, 0.7, 0.42 )` |
| [Color](class_color#class-color) | [debug/shapes/navigation/disabled\_geometry\_color](#class-projectsettings-property-debug-shapes-navigation-disabled-geometry-color) | `Color( 1, 0.7, 0.1, 0.4 )` |
| [Color](class_color#class-color) | [debug/shapes/navigation/geometry\_color](#class-projectsettings-property-debug-shapes-navigation-geometry-color) | `Color( 0.1, 1, 0.7, 0.4 )` |
| [String](class_string#class-string) | [display/mouse\_cursor/custom\_image](#class-projectsettings-property-display-mouse-cursor-custom-image) | `""` |
| [Vector2](class_vector2#class-vector2) | [display/mouse\_cursor/custom\_image\_hotspot](#class-projectsettings-property-display-mouse-cursor-custom-image-hotspot) | `Vector2( 0, 0 )` |
| [Vector2](class_vector2#class-vector2) | [display/mouse\_cursor/tooltip\_position\_offset](#class-projectsettings-property-display-mouse-cursor-tooltip-position-offset) | `Vector2( 10, 10 )` |
| [bool](class_bool#class-bool) | [display/window/dpi/allow\_hidpi](#class-projectsettings-property-display-window-dpi-allow-hidpi) | `false` |
| [bool](class_bool#class-bool) | [display/window/energy\_saving/keep\_screen\_on](#class-projectsettings-property-display-window-energy-saving-keep-screen-on) | `true` |
| [String](class_string#class-string) | [display/window/handheld/orientation](#class-projectsettings-property-display-window-handheld-orientation) | `"landscape"` |
| [bool](class_bool#class-bool) | [display/window/ios/hide\_home\_indicator](#class-projectsettings-property-display-window-ios-hide-home-indicator) | `true` |
| [bool](class_bool#class-bool) | [display/window/per\_pixel\_transparency/allowed](#class-projectsettings-property-display-window-per-pixel-transparency-allowed) | `false` |
| [bool](class_bool#class-bool) | [display/window/per\_pixel\_transparency/enabled](#class-projectsettings-property-display-window-per-pixel-transparency-enabled) | `false` |
| [bool](class_bool#class-bool) | [display/window/size/always\_on\_top](#class-projectsettings-property-display-window-size-always-on-top) | `false` |
| [bool](class_bool#class-bool) | [display/window/size/borderless](#class-projectsettings-property-display-window-size-borderless) | `false` |
| [bool](class_bool#class-bool) | [display/window/size/fullscreen](#class-projectsettings-property-display-window-size-fullscreen) | `false` |
| [int](class_int#class-int) | [display/window/size/height](#class-projectsettings-property-display-window-size-height) | `600` |
| [bool](class_bool#class-bool) | [display/window/size/resizable](#class-projectsettings-property-display-window-size-resizable) | `true` |
| [int](class_int#class-int) | [display/window/size/test\_height](#class-projectsettings-property-display-window-size-test-height) | `0` |
| [int](class_int#class-int) | [display/window/size/test\_width](#class-projectsettings-property-display-window-size-test-width) | `0` |
| [int](class_int#class-int) | [display/window/size/width](#class-projectsettings-property-display-window-size-width) | `1024` |
| [String](class_string#class-string) | [display/window/tablet\_driver](#class-projectsettings-property-display-window-tablet-driver) | |
| [bool](class_bool#class-bool) | [display/window/vsync/use\_vsync](#class-projectsettings-property-display-window-vsync-use-vsync) | `true` |
| [bool](class_bool#class-bool) | [display/window/vsync/vsync\_via\_compositor](#class-projectsettings-property-display-window-vsync-vsync-via-compositor) | `false` |
| [String](class_string#class-string) | [editor/main\_run\_args](#class-projectsettings-property-editor-main-run-args) | `""` |
| [int](class_int#class-int) | [editor/scene\_naming](#class-projectsettings-property-editor-scene-naming) | `0` |
| [String](class_string#class-string) | [editor/script\_templates\_search\_path](#class-projectsettings-property-editor-script-templates-search-path) | `"res://script_templates"` |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [editor/search\_in\_file\_extensions](#class-projectsettings-property-editor-search-in-file-extensions) | `PoolStringArray( "gd", "gdshader", "shader" )` |
| [bool](class_bool#class-bool) | [editor/version\_control\_autoload\_on\_startup](#class-projectsettings-property-editor-version-control-autoload-on-startup) | `false` |
| [String](class_string#class-string) | [editor/version\_control\_plugin\_name](#class-projectsettings-property-editor-version-control-plugin-name) | `""` |
| [int](class_int#class-int) | [gui/common/default\_scroll\_deadzone](#class-projectsettings-property-gui-common-default-scroll-deadzone) | `0` |
| [bool](class_bool#class-bool) | [gui/common/drop\_mouse\_on\_gui\_input\_disabled](#class-projectsettings-property-gui-common-drop-mouse-on-gui-input-disabled) | `false` |
| [bool](class_bool#class-bool) | [gui/common/swap\_ok\_cancel](#class-projectsettings-property-gui-common-swap-ok-cancel) | |
| [int](class_int#class-int) | [gui/common/text\_edit\_undo\_stack\_max\_size](#class-projectsettings-property-gui-common-text-edit-undo-stack-max-size) | `1024` |
| [String](class_string#class-string) | [gui/theme/custom](#class-projectsettings-property-gui-theme-custom) | `""` |
| [String](class_string#class-string) | [gui/theme/custom\_font](#class-projectsettings-property-gui-theme-custom-font) | `""` |
| [bool](class_bool#class-bool) | [gui/theme/use\_hidpi](#class-projectsettings-property-gui-theme-use-hidpi) | `false` |
| [int](class_int#class-int) | [gui/timers/incremental\_search\_max\_interval\_msec](#class-projectsettings-property-gui-timers-incremental-search-max-interval-msec) | `2000` |
| [float](class_float#class-float) | [gui/timers/text\_edit\_idle\_detect\_sec](#class-projectsettings-property-gui-timers-text-edit-idle-detect-sec) | `3` |
| [float](class_float#class-float) | [gui/timers/tooltip\_delay\_sec](#class-projectsettings-property-gui-timers-tooltip-delay-sec) | `0.5` |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_accept](#class-projectsettings-property-input-ui-accept) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_cancel](#class-projectsettings-property-input-ui-cancel) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_down](#class-projectsettings-property-input-ui-down) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_end](#class-projectsettings-property-input-ui-end) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_focus\_next](#class-projectsettings-property-input-ui-focus-next) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_focus\_prev](#class-projectsettings-property-input-ui-focus-prev) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_home](#class-projectsettings-property-input-ui-home) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_left](#class-projectsettings-property-input-ui-left) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_page\_down](#class-projectsettings-property-input-ui-page-down) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_page\_up](#class-projectsettings-property-input-ui-page-up) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_right](#class-projectsettings-property-input-ui-right) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_select](#class-projectsettings-property-input-ui-select) | |
| [Dictionary](class_dictionary#class-dictionary) | [input/ui\_up](#class-projectsettings-property-input-ui-up) | |
| [bool](class_bool#class-bool) | [input\_devices/buffering/agile\_event\_flushing](#class-projectsettings-property-input-devices-buffering-agile-event-flushing) | `false` |
| [bool](class_bool#class-bool) | [input\_devices/pointing/emulate\_mouse\_from\_touch](#class-projectsettings-property-input-devices-pointing-emulate-mouse-from-touch) | `true` |
| [bool](class_bool#class-bool) | [input\_devices/pointing/emulate\_touch\_from\_mouse](#class-projectsettings-property-input-devices-pointing-emulate-touch-from-mouse) | `false` |
| [float](class_float#class-float) | [input\_devices/pointing/ios/touch\_delay](#class-projectsettings-property-input-devices-pointing-ios-touch-delay) | `0.15` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_1](#class-projectsettings-property-layer-names-2d-navigation-layer-1) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_10](#class-projectsettings-property-layer-names-2d-navigation-layer-10) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_11](#class-projectsettings-property-layer-names-2d-navigation-layer-11) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_12](#class-projectsettings-property-layer-names-2d-navigation-layer-12) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_13](#class-projectsettings-property-layer-names-2d-navigation-layer-13) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_14](#class-projectsettings-property-layer-names-2d-navigation-layer-14) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_15](#class-projectsettings-property-layer-names-2d-navigation-layer-15) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_16](#class-projectsettings-property-layer-names-2d-navigation-layer-16) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_17](#class-projectsettings-property-layer-names-2d-navigation-layer-17) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_18](#class-projectsettings-property-layer-names-2d-navigation-layer-18) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_19](#class-projectsettings-property-layer-names-2d-navigation-layer-19) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_2](#class-projectsettings-property-layer-names-2d-navigation-layer-2) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_20](#class-projectsettings-property-layer-names-2d-navigation-layer-20) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_21](#class-projectsettings-property-layer-names-2d-navigation-layer-21) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_22](#class-projectsettings-property-layer-names-2d-navigation-layer-22) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_23](#class-projectsettings-property-layer-names-2d-navigation-layer-23) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_24](#class-projectsettings-property-layer-names-2d-navigation-layer-24) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_25](#class-projectsettings-property-layer-names-2d-navigation-layer-25) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_26](#class-projectsettings-property-layer-names-2d-navigation-layer-26) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_27](#class-projectsettings-property-layer-names-2d-navigation-layer-27) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_28](#class-projectsettings-property-layer-names-2d-navigation-layer-28) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_29](#class-projectsettings-property-layer-names-2d-navigation-layer-29) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_3](#class-projectsettings-property-layer-names-2d-navigation-layer-3) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_30](#class-projectsettings-property-layer-names-2d-navigation-layer-30) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_31](#class-projectsettings-property-layer-names-2d-navigation-layer-31) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_32](#class-projectsettings-property-layer-names-2d-navigation-layer-32) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_4](#class-projectsettings-property-layer-names-2d-navigation-layer-4) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_5](#class-projectsettings-property-layer-names-2d-navigation-layer-5) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_6](#class-projectsettings-property-layer-names-2d-navigation-layer-6) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_7](#class-projectsettings-property-layer-names-2d-navigation-layer-7) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_8](#class-projectsettings-property-layer-names-2d-navigation-layer-8) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_navigation/layer\_9](#class-projectsettings-property-layer-names-2d-navigation-layer-9) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_1](#class-projectsettings-property-layer-names-2d-physics-layer-1) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_10](#class-projectsettings-property-layer-names-2d-physics-layer-10) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_11](#class-projectsettings-property-layer-names-2d-physics-layer-11) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_12](#class-projectsettings-property-layer-names-2d-physics-layer-12) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_13](#class-projectsettings-property-layer-names-2d-physics-layer-13) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_14](#class-projectsettings-property-layer-names-2d-physics-layer-14) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_15](#class-projectsettings-property-layer-names-2d-physics-layer-15) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_16](#class-projectsettings-property-layer-names-2d-physics-layer-16) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_17](#class-projectsettings-property-layer-names-2d-physics-layer-17) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_18](#class-projectsettings-property-layer-names-2d-physics-layer-18) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_19](#class-projectsettings-property-layer-names-2d-physics-layer-19) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_2](#class-projectsettings-property-layer-names-2d-physics-layer-2) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_20](#class-projectsettings-property-layer-names-2d-physics-layer-20) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_21](#class-projectsettings-property-layer-names-2d-physics-layer-21) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_22](#class-projectsettings-property-layer-names-2d-physics-layer-22) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_23](#class-projectsettings-property-layer-names-2d-physics-layer-23) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_24](#class-projectsettings-property-layer-names-2d-physics-layer-24) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_25](#class-projectsettings-property-layer-names-2d-physics-layer-25) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_26](#class-projectsettings-property-layer-names-2d-physics-layer-26) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_27](#class-projectsettings-property-layer-names-2d-physics-layer-27) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_28](#class-projectsettings-property-layer-names-2d-physics-layer-28) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_29](#class-projectsettings-property-layer-names-2d-physics-layer-29) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_3](#class-projectsettings-property-layer-names-2d-physics-layer-3) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_30](#class-projectsettings-property-layer-names-2d-physics-layer-30) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_31](#class-projectsettings-property-layer-names-2d-physics-layer-31) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_32](#class-projectsettings-property-layer-names-2d-physics-layer-32) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_4](#class-projectsettings-property-layer-names-2d-physics-layer-4) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_5](#class-projectsettings-property-layer-names-2d-physics-layer-5) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_6](#class-projectsettings-property-layer-names-2d-physics-layer-6) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_7](#class-projectsettings-property-layer-names-2d-physics-layer-7) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_8](#class-projectsettings-property-layer-names-2d-physics-layer-8) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_physics/layer\_9](#class-projectsettings-property-layer-names-2d-physics-layer-9) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_1](#class-projectsettings-property-layer-names-2d-render-layer-1) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_10](#class-projectsettings-property-layer-names-2d-render-layer-10) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_11](#class-projectsettings-property-layer-names-2d-render-layer-11) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_12](#class-projectsettings-property-layer-names-2d-render-layer-12) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_13](#class-projectsettings-property-layer-names-2d-render-layer-13) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_14](#class-projectsettings-property-layer-names-2d-render-layer-14) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_15](#class-projectsettings-property-layer-names-2d-render-layer-15) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_16](#class-projectsettings-property-layer-names-2d-render-layer-16) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_17](#class-projectsettings-property-layer-names-2d-render-layer-17) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_18](#class-projectsettings-property-layer-names-2d-render-layer-18) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_19](#class-projectsettings-property-layer-names-2d-render-layer-19) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_2](#class-projectsettings-property-layer-names-2d-render-layer-2) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_20](#class-projectsettings-property-layer-names-2d-render-layer-20) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_3](#class-projectsettings-property-layer-names-2d-render-layer-3) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_4](#class-projectsettings-property-layer-names-2d-render-layer-4) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_5](#class-projectsettings-property-layer-names-2d-render-layer-5) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_6](#class-projectsettings-property-layer-names-2d-render-layer-6) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_7](#class-projectsettings-property-layer-names-2d-render-layer-7) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_8](#class-projectsettings-property-layer-names-2d-render-layer-8) | `""` |
| [String](class_string#class-string) | [layer\_names/2d\_render/layer\_9](#class-projectsettings-property-layer-names-2d-render-layer-9) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_1](#class-projectsettings-property-layer-names-3d-navigation-layer-1) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_10](#class-projectsettings-property-layer-names-3d-navigation-layer-10) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_11](#class-projectsettings-property-layer-names-3d-navigation-layer-11) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_12](#class-projectsettings-property-layer-names-3d-navigation-layer-12) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_13](#class-projectsettings-property-layer-names-3d-navigation-layer-13) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_14](#class-projectsettings-property-layer-names-3d-navigation-layer-14) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_15](#class-projectsettings-property-layer-names-3d-navigation-layer-15) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_16](#class-projectsettings-property-layer-names-3d-navigation-layer-16) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_17](#class-projectsettings-property-layer-names-3d-navigation-layer-17) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_18](#class-projectsettings-property-layer-names-3d-navigation-layer-18) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_19](#class-projectsettings-property-layer-names-3d-navigation-layer-19) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_2](#class-projectsettings-property-layer-names-3d-navigation-layer-2) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_20](#class-projectsettings-property-layer-names-3d-navigation-layer-20) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_21](#class-projectsettings-property-layer-names-3d-navigation-layer-21) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_22](#class-projectsettings-property-layer-names-3d-navigation-layer-22) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_23](#class-projectsettings-property-layer-names-3d-navigation-layer-23) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_24](#class-projectsettings-property-layer-names-3d-navigation-layer-24) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_25](#class-projectsettings-property-layer-names-3d-navigation-layer-25) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_26](#class-projectsettings-property-layer-names-3d-navigation-layer-26) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_27](#class-projectsettings-property-layer-names-3d-navigation-layer-27) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_28](#class-projectsettings-property-layer-names-3d-navigation-layer-28) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_29](#class-projectsettings-property-layer-names-3d-navigation-layer-29) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_3](#class-projectsettings-property-layer-names-3d-navigation-layer-3) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_30](#class-projectsettings-property-layer-names-3d-navigation-layer-30) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_31](#class-projectsettings-property-layer-names-3d-navigation-layer-31) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_32](#class-projectsettings-property-layer-names-3d-navigation-layer-32) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_4](#class-projectsettings-property-layer-names-3d-navigation-layer-4) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_5](#class-projectsettings-property-layer-names-3d-navigation-layer-5) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_6](#class-projectsettings-property-layer-names-3d-navigation-layer-6) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_7](#class-projectsettings-property-layer-names-3d-navigation-layer-7) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_8](#class-projectsettings-property-layer-names-3d-navigation-layer-8) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_navigation/layer\_9](#class-projectsettings-property-layer-names-3d-navigation-layer-9) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_1](#class-projectsettings-property-layer-names-3d-physics-layer-1) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_10](#class-projectsettings-property-layer-names-3d-physics-layer-10) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_11](#class-projectsettings-property-layer-names-3d-physics-layer-11) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_12](#class-projectsettings-property-layer-names-3d-physics-layer-12) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_13](#class-projectsettings-property-layer-names-3d-physics-layer-13) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_14](#class-projectsettings-property-layer-names-3d-physics-layer-14) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_15](#class-projectsettings-property-layer-names-3d-physics-layer-15) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_16](#class-projectsettings-property-layer-names-3d-physics-layer-16) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_17](#class-projectsettings-property-layer-names-3d-physics-layer-17) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_18](#class-projectsettings-property-layer-names-3d-physics-layer-18) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_19](#class-projectsettings-property-layer-names-3d-physics-layer-19) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_2](#class-projectsettings-property-layer-names-3d-physics-layer-2) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_20](#class-projectsettings-property-layer-names-3d-physics-layer-20) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_21](#class-projectsettings-property-layer-names-3d-physics-layer-21) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_22](#class-projectsettings-property-layer-names-3d-physics-layer-22) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_23](#class-projectsettings-property-layer-names-3d-physics-layer-23) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_24](#class-projectsettings-property-layer-names-3d-physics-layer-24) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_25](#class-projectsettings-property-layer-names-3d-physics-layer-25) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_26](#class-projectsettings-property-layer-names-3d-physics-layer-26) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_27](#class-projectsettings-property-layer-names-3d-physics-layer-27) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_28](#class-projectsettings-property-layer-names-3d-physics-layer-28) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_29](#class-projectsettings-property-layer-names-3d-physics-layer-29) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_3](#class-projectsettings-property-layer-names-3d-physics-layer-3) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_30](#class-projectsettings-property-layer-names-3d-physics-layer-30) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_31](#class-projectsettings-property-layer-names-3d-physics-layer-31) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_32](#class-projectsettings-property-layer-names-3d-physics-layer-32) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_4](#class-projectsettings-property-layer-names-3d-physics-layer-4) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_5](#class-projectsettings-property-layer-names-3d-physics-layer-5) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_6](#class-projectsettings-property-layer-names-3d-physics-layer-6) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_7](#class-projectsettings-property-layer-names-3d-physics-layer-7) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_8](#class-projectsettings-property-layer-names-3d-physics-layer-8) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_physics/layer\_9](#class-projectsettings-property-layer-names-3d-physics-layer-9) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_1](#class-projectsettings-property-layer-names-3d-render-layer-1) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_10](#class-projectsettings-property-layer-names-3d-render-layer-10) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_11](#class-projectsettings-property-layer-names-3d-render-layer-11) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_12](#class-projectsettings-property-layer-names-3d-render-layer-12) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_13](#class-projectsettings-property-layer-names-3d-render-layer-13) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_14](#class-projectsettings-property-layer-names-3d-render-layer-14) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_15](#class-projectsettings-property-layer-names-3d-render-layer-15) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_16](#class-projectsettings-property-layer-names-3d-render-layer-16) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_17](#class-projectsettings-property-layer-names-3d-render-layer-17) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_18](#class-projectsettings-property-layer-names-3d-render-layer-18) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_19](#class-projectsettings-property-layer-names-3d-render-layer-19) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_2](#class-projectsettings-property-layer-names-3d-render-layer-2) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_20](#class-projectsettings-property-layer-names-3d-render-layer-20) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_3](#class-projectsettings-property-layer-names-3d-render-layer-3) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_4](#class-projectsettings-property-layer-names-3d-render-layer-4) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_5](#class-projectsettings-property-layer-names-3d-render-layer-5) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_6](#class-projectsettings-property-layer-names-3d-render-layer-6) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_7](#class-projectsettings-property-layer-names-3d-render-layer-7) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_8](#class-projectsettings-property-layer-names-3d-render-layer-8) | `""` |
| [String](class_string#class-string) | [layer\_names/3d\_render/layer\_9](#class-projectsettings-property-layer-names-3d-render-layer-9) | `""` |
| [String](class_string#class-string) | [locale/fallback](#class-projectsettings-property-locale-fallback) | `"en"` |
| [String](class_string#class-string) | [locale/test](#class-projectsettings-property-locale-test) | `""` |
| [bool](class_bool#class-bool) | [logging/file\_logging/enable\_file\_logging](#class-projectsettings-property-logging-file-logging-enable-file-logging) | `false` |
| [bool](class_bool#class-bool) | [logging/file\_logging/enable\_file\_logging.pc](#class-projectsettings-property-logging-file-logging-enable-file-logging-pc) | `true` |
| [String](class_string#class-string) | [logging/file\_logging/log\_path](#class-projectsettings-property-logging-file-logging-log-path) | `"user://logs/godot.log"` |
| [int](class_int#class-int) | [logging/file\_logging/max\_log\_files](#class-projectsettings-property-logging-file-logging-max-log-files) | `5` |
| [int](class_int#class-int) | [memory/limits/command\_queue/multithreading\_queue\_size\_kb](#class-projectsettings-property-memory-limits-command-queue-multithreading-queue-size-kb) | `256` |
| [int](class_int#class-int) | [memory/limits/message\_queue/max\_size\_kb](#class-projectsettings-property-memory-limits-message-queue-max-size-kb) | `4096` |
| [int](class_int#class-int) | [memory/limits/multithreaded\_server/rid\_pool\_prealloc](#class-projectsettings-property-memory-limits-multithreaded-server-rid-pool-prealloc) | `60` |
| [int](class_int#class-int) | [mono/debugger\_agent/port](#class-projectsettings-property-mono-debugger-agent-port) | `23685` |
| [bool](class_bool#class-bool) | [mono/debugger\_agent/wait\_for\_debugger](#class-projectsettings-property-mono-debugger-agent-wait-for-debugger) | `false` |
| [int](class_int#class-int) | [mono/debugger\_agent/wait\_timeout](#class-projectsettings-property-mono-debugger-agent-wait-timeout) | `3000` |
| [String](class_string#class-string) | [mono/profiler/args](#class-projectsettings-property-mono-profiler-args) | `"log:calls,alloc,sample,output=output.mlpd"` |
| [bool](class_bool#class-bool) | [mono/profiler/enabled](#class-projectsettings-property-mono-profiler-enabled) | `false` |
| [int](class_int#class-int) | [mono/runtime/unhandled\_exception\_policy](#class-projectsettings-property-mono-runtime-unhandled-exception-policy) | `0` |
| [float](class_float#class-float) | [navigation/2d/default\_cell\_height](#class-projectsettings-property-navigation-2d-default-cell-height) | `1.0` |
| [float](class_float#class-float) | [navigation/2d/default\_cell\_size](#class-projectsettings-property-navigation-2d-default-cell-size) | `1.0` |
| [float](class_float#class-float) | [navigation/2d/default\_edge\_connection\_margin](#class-projectsettings-property-navigation-2d-default-edge-connection-margin) | `1.0` |
| [float](class_float#class-float) | [navigation/3d/default\_cell\_height](#class-projectsettings-property-navigation-3d-default-cell-height) | `0.25` |
| [float](class_float#class-float) | [navigation/3d/default\_cell\_size](#class-projectsettings-property-navigation-3d-default-cell-size) | `0.25` |
| [float](class_float#class-float) | [navigation/3d/default\_edge\_connection\_margin](#class-projectsettings-property-navigation-3d-default-edge-connection-margin) | `0.25` |
| [Vector3](class_vector3#class-vector3) | [navigation/3d/default\_map\_up](#class-projectsettings-property-navigation-3d-default-map-up) | `Vector3( 0, 1, 0 )` |
| [int](class_int#class-int) | [network/limits/debugger\_stdout/max\_chars\_per\_second](#class-projectsettings-property-network-limits-debugger-stdout-max-chars-per-second) | `2048` |
| [int](class_int#class-int) | [network/limits/debugger\_stdout/max\_errors\_per\_second](#class-projectsettings-property-network-limits-debugger-stdout-max-errors-per-second) | `100` |
| [int](class_int#class-int) | [network/limits/debugger\_stdout/max\_messages\_per\_frame](#class-projectsettings-property-network-limits-debugger-stdout-max-messages-per-frame) | `10` |
| [int](class_int#class-int) | [network/limits/debugger\_stdout/max\_warnings\_per\_second](#class-projectsettings-property-network-limits-debugger-stdout-max-warnings-per-second) | `100` |
| [int](class_int#class-int) | [network/limits/packet\_peer\_stream/max\_buffer\_po2](#class-projectsettings-property-network-limits-packet-peer-stream-max-buffer-po2) | `16` |
| [int](class_int#class-int) | [network/limits/tcp/connect\_timeout\_seconds](#class-projectsettings-property-network-limits-tcp-connect-timeout-seconds) | `30` |
| [int](class_int#class-int) | [network/limits/webrtc/max\_channel\_in\_buffer\_kb](#class-projectsettings-property-network-limits-webrtc-max-channel-in-buffer-kb) | `64` |
| [int](class_int#class-int) | [network/limits/websocket\_client/max\_in\_buffer\_kb](#class-projectsettings-property-network-limits-websocket-client-max-in-buffer-kb) | `64` |
| [int](class_int#class-int) | [network/limits/websocket\_client/max\_in\_packets](#class-projectsettings-property-network-limits-websocket-client-max-in-packets) | `1024` |
| [int](class_int#class-int) | [network/limits/websocket\_client/max\_out\_buffer\_kb](#class-projectsettings-property-network-limits-websocket-client-max-out-buffer-kb) | `64` |
| [int](class_int#class-int) | [network/limits/websocket\_client/max\_out\_packets](#class-projectsettings-property-network-limits-websocket-client-max-out-packets) | `1024` |
| [int](class_int#class-int) | [network/limits/websocket\_server/max\_in\_buffer\_kb](#class-projectsettings-property-network-limits-websocket-server-max-in-buffer-kb) | `64` |
| [int](class_int#class-int) | [network/limits/websocket\_server/max\_in\_packets](#class-projectsettings-property-network-limits-websocket-server-max-in-packets) | `1024` |
| [int](class_int#class-int) | [network/limits/websocket\_server/max\_out\_buffer\_kb](#class-projectsettings-property-network-limits-websocket-server-max-out-buffer-kb) | `64` |
| [int](class_int#class-int) | [network/limits/websocket\_server/max\_out\_packets](#class-projectsettings-property-network-limits-websocket-server-max-out-packets) | `1024` |
| [int](class_int#class-int) | [network/remote\_fs/page\_read\_ahead](#class-projectsettings-property-network-remote-fs-page-read-ahead) | `4` |
| [int](class_int#class-int) | [network/remote\_fs/page\_size](#class-projectsettings-property-network-remote-fs-page-size) | `65536` |
| [String](class_string#class-string) | [network/ssl/certificates](#class-projectsettings-property-network-ssl-certificates) | `""` |
| [int](class_int#class-int) | [node/name\_casing](#class-projectsettings-property-node-name-casing) | `0` |
| [int](class_int#class-int) | [node/name\_num\_separator](#class-projectsettings-property-node-name-num-separator) | `0` |
| [int](class_int#class-int) | [physics/2d/bp\_hash\_table\_size](#class-projectsettings-property-physics-2d-bp-hash-table-size) | `4096` |
| [float](class_float#class-float) | [physics/2d/bvh\_collision\_margin](#class-projectsettings-property-physics-2d-bvh-collision-margin) | `1.0` |
| [int](class_int#class-int) | [physics/2d/cell\_size](#class-projectsettings-property-physics-2d-cell-size) | `128` |
| [float](class_float#class-float) | [physics/2d/default\_angular\_damp](#class-projectsettings-property-physics-2d-default-angular-damp) | `1.0` |
| [int](class_int#class-int) | [physics/2d/default\_gravity](#class-projectsettings-property-physics-2d-default-gravity) | `98` |
| [Vector2](class_vector2#class-vector2) | [physics/2d/default\_gravity\_vector](#class-projectsettings-property-physics-2d-default-gravity-vector) | `Vector2( 0, 1 )` |
| [float](class_float#class-float) | [physics/2d/default\_linear\_damp](#class-projectsettings-property-physics-2d-default-linear-damp) | `0.1` |
| [int](class_int#class-int) | [physics/2d/large\_object\_surface\_threshold\_in\_cells](#class-projectsettings-property-physics-2d-large-object-surface-threshold-in-cells) | `512` |
| [String](class_string#class-string) | [physics/2d/physics\_engine](#class-projectsettings-property-physics-2d-physics-engine) | `"DEFAULT"` |
| [float](class_float#class-float) | [physics/2d/sleep\_threshold\_angular](#class-projectsettings-property-physics-2d-sleep-threshold-angular) | `0.139626` |
| [float](class_float#class-float) | [physics/2d/sleep\_threshold\_linear](#class-projectsettings-property-physics-2d-sleep-threshold-linear) | `2.0` |
| [int](class_int#class-int) | [physics/2d/thread\_model](#class-projectsettings-property-physics-2d-thread-model) | `1` |
| [float](class_float#class-float) | [physics/2d/time\_before\_sleep](#class-projectsettings-property-physics-2d-time-before-sleep) | `0.5` |
| [bool](class_bool#class-bool) | [physics/2d/use\_bvh](#class-projectsettings-property-physics-2d-use-bvh) | `true` |
| [bool](class_bool#class-bool) | [physics/3d/active\_soft\_world](#class-projectsettings-property-physics-3d-active-soft-world) | `true` |
| [float](class_float#class-float) | [physics/3d/default\_angular\_damp](#class-projectsettings-property-physics-3d-default-angular-damp) | `0.1` |
| [float](class_float#class-float) | [physics/3d/default\_gravity](#class-projectsettings-property-physics-3d-default-gravity) | `9.8` |
| [Vector3](class_vector3#class-vector3) | [physics/3d/default\_gravity\_vector](#class-projectsettings-property-physics-3d-default-gravity-vector) | `Vector3( 0, -1, 0 )` |
| [float](class_float#class-float) | [physics/3d/default\_linear\_damp](#class-projectsettings-property-physics-3d-default-linear-damp) | `0.1` |
| [float](class_float#class-float) | [physics/3d/godot\_physics/bvh\_collision\_margin](#class-projectsettings-property-physics-3d-godot-physics-bvh-collision-margin) | `0.1` |
| [bool](class_bool#class-bool) | [physics/3d/godot\_physics/use\_bvh](#class-projectsettings-property-physics-3d-godot-physics-use-bvh) | `true` |
| [String](class_string#class-string) | [physics/3d/physics\_engine](#class-projectsettings-property-physics-3d-physics-engine) | `"DEFAULT"` |
| [bool](class_bool#class-bool) | [physics/3d/smooth\_trimesh\_collision](#class-projectsettings-property-physics-3d-smooth-trimesh-collision) | `false` |
| [bool](class_bool#class-bool) | [physics/common/enable\_object\_picking](#class-projectsettings-property-physics-common-enable-object-picking) | `true` |
| [bool](class_bool#class-bool) | [physics/common/enable\_pause\_aware\_picking](#class-projectsettings-property-physics-common-enable-pause-aware-picking) | `false` |
| [int](class_int#class-int) | [physics/common/physics\_fps](#class-projectsettings-property-physics-common-physics-fps) | `60` |
| [bool](class_bool#class-bool) | [physics/common/physics\_interpolation](#class-projectsettings-property-physics-common-physics-interpolation) | `false` |
| [float](class_float#class-float) | [physics/common/physics\_jitter\_fix](#class-projectsettings-property-physics-common-physics-jitter-fix) | `0.5` |
| [int](class_int#class-int) | [rendering/2d/opengl/batching\_send\_null](#class-projectsettings-property-rendering-2d-opengl-batching-send-null) | `0` |
| [int](class_int#class-int) | [rendering/2d/opengl/batching\_stream](#class-projectsettings-property-rendering-2d-opengl-batching-stream) | `0` |
| [int](class_int#class-int) | [rendering/2d/opengl/legacy\_orphan\_buffers](#class-projectsettings-property-rendering-2d-opengl-legacy-orphan-buffers) | `0` |
| [int](class_int#class-int) | [rendering/2d/opengl/legacy\_stream](#class-projectsettings-property-rendering-2d-opengl-legacy-stream) | `0` |
| [int](class_int#class-int) | [rendering/2d/options/ninepatch\_mode](#class-projectsettings-property-rendering-2d-options-ninepatch-mode) | `1` |
| [bool](class_bool#class-bool) | [rendering/2d/options/use\_nvidia\_rect\_flicker\_workaround](#class-projectsettings-property-rendering-2d-options-use-nvidia-rect-flicker-workaround) | `false` |
| [bool](class_bool#class-bool) | [rendering/2d/options/use\_software\_skinning](#class-projectsettings-property-rendering-2d-options-use-software-skinning) | `true` |
| [bool](class_bool#class-bool) | [rendering/2d/snapping/use\_gpu\_pixel\_snap](#class-projectsettings-property-rendering-2d-snapping-use-gpu-pixel-snap) | `false` |
| [bool](class_bool#class-bool) | [rendering/batching/debug/diagnose\_frame](#class-projectsettings-property-rendering-batching-debug-diagnose-frame) | `false` |
| [bool](class_bool#class-bool) | [rendering/batching/debug/flash\_batching](#class-projectsettings-property-rendering-batching-debug-flash-batching) | `false` |
| [int](class_int#class-int) | [rendering/batching/lights/max\_join\_items](#class-projectsettings-property-rendering-batching-lights-max-join-items) | `32` |
| [float](class_float#class-float) | [rendering/batching/lights/scissor\_area\_threshold](#class-projectsettings-property-rendering-batching-lights-scissor-area-threshold) | `1.0` |
| [bool](class_bool#class-bool) | [rendering/batching/options/single\_rect\_fallback](#class-projectsettings-property-rendering-batching-options-single-rect-fallback) | `false` |
| [bool](class_bool#class-bool) | [rendering/batching/options/use\_batching](#class-projectsettings-property-rendering-batching-options-use-batching) | `true` |
| [bool](class_bool#class-bool) | [rendering/batching/options/use\_batching\_in\_editor](#class-projectsettings-property-rendering-batching-options-use-batching-in-editor) | `true` |
| [int](class_int#class-int) | [rendering/batching/parameters/batch\_buffer\_size](#class-projectsettings-property-rendering-batching-parameters-batch-buffer-size) | `16384` |
| [float](class_float#class-float) | [rendering/batching/parameters/colored\_vertex\_format\_threshold](#class-projectsettings-property-rendering-batching-parameters-colored-vertex-format-threshold) | `0.25` |
| [int](class_int#class-int) | [rendering/batching/parameters/item\_reordering\_lookahead](#class-projectsettings-property-rendering-batching-parameters-item-reordering-lookahead) | `4` |
| [int](class_int#class-int) | [rendering/batching/parameters/max\_join\_item\_commands](#class-projectsettings-property-rendering-batching-parameters-max-join-item-commands) | `16` |
| [bool](class_bool#class-bool) | [rendering/batching/precision/uv\_contract](#class-projectsettings-property-rendering-batching-precision-uv-contract) | `false` |
| [int](class_int#class-int) | [rendering/batching/precision/uv\_contract\_amount](#class-projectsettings-property-rendering-batching-precision-uv-contract-amount) | `100` |
| [int](class_int#class-int) | [rendering/cpu\_lightmapper/quality/high\_quality\_ray\_count](#class-projectsettings-property-rendering-cpu-lightmapper-quality-high-quality-ray-count) | `512` |
| [int](class_int#class-int) | [rendering/cpu\_lightmapper/quality/low\_quality\_ray\_count](#class-projectsettings-property-rendering-cpu-lightmapper-quality-low-quality-ray-count) | `64` |
| [int](class_int#class-int) | [rendering/cpu\_lightmapper/quality/medium\_quality\_ray\_count](#class-projectsettings-property-rendering-cpu-lightmapper-quality-medium-quality-ray-count) | `256` |
| [int](class_int#class-int) | [rendering/cpu\_lightmapper/quality/ultra\_quality\_ray\_count](#class-projectsettings-property-rendering-cpu-lightmapper-quality-ultra-quality-ray-count) | `1024` |
| [Color](class_color#class-color) | [rendering/environment/default\_clear\_color](#class-projectsettings-property-rendering-environment-default-clear-color) | `Color( 0.3, 0.3, 0.3, 1 )` |
| [String](class_string#class-string) | [rendering/environment/default\_environment](#class-projectsettings-property-rendering-environment-default-environment) | `""` |
| [bool](class_bool#class-bool) | [rendering/gles2/compatibility/disable\_half\_float](#class-projectsettings-property-rendering-gles2-compatibility-disable-half-float) | `false` |
| [bool](class_bool#class-bool) | [rendering/gles2/compatibility/disable\_half\_float.iOS](#class-projectsettings-property-rendering-gles2-compatibility-disable-half-float-ios) | `true` |
| [bool](class_bool#class-bool) | [rendering/gles2/compatibility/enable\_high\_float.Android](#class-projectsettings-property-rendering-gles2-compatibility-enable-high-float-android) | `false` |
| [bool](class_bool#class-bool) | [rendering/gles3/shaders/log\_active\_async\_compiles\_count](#class-projectsettings-property-rendering-gles3-shaders-log-active-async-compiles-count) | `false` |
| [int](class_int#class-int) | [rendering/gles3/shaders/max\_simultaneous\_compiles](#class-projectsettings-property-rendering-gles3-shaders-max-simultaneous-compiles) | `2` |
| [int](class_int#class-int) | [rendering/gles3/shaders/max\_simultaneous\_compiles.mobile](#class-projectsettings-property-rendering-gles3-shaders-max-simultaneous-compiles-mobile) | `1` |
| [int](class_int#class-int) | [rendering/gles3/shaders/max\_simultaneous\_compiles.web](#class-projectsettings-property-rendering-gles3-shaders-max-simultaneous-compiles-web) | `1` |
| [int](class_int#class-int) | [rendering/gles3/shaders/shader\_cache\_size\_mb](#class-projectsettings-property-rendering-gles3-shaders-shader-cache-size-mb) | `512` |
| [int](class_int#class-int) | [rendering/gles3/shaders/shader\_cache\_size\_mb.mobile](#class-projectsettings-property-rendering-gles3-shaders-shader-cache-size-mb-mobile) | `128` |
| [int](class_int#class-int) | [rendering/gles3/shaders/shader\_cache\_size\_mb.web](#class-projectsettings-property-rendering-gles3-shaders-shader-cache-size-mb-web) | `128` |
| [int](class_int#class-int) | [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode) | `0` |
| [int](class_int#class-int) | [rendering/gles3/shaders/shader\_compilation\_mode.mobile](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode-mobile) | `0` |
| [int](class_int#class-int) | [rendering/gles3/shaders/shader\_compilation\_mode.web](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode-web) | `0` |
| [int](class_int#class-int) | [rendering/limits/buffers/blend\_shape\_max\_buffer\_size\_kb](#class-projectsettings-property-rendering-limits-buffers-blend-shape-max-buffer-size-kb) | `4096` |
| [int](class_int#class-int) | [rendering/limits/buffers/canvas\_polygon\_buffer\_size\_kb](#class-projectsettings-property-rendering-limits-buffers-canvas-polygon-buffer-size-kb) | `128` |
| [int](class_int#class-int) | [rendering/limits/buffers/canvas\_polygon\_index\_buffer\_size\_kb](#class-projectsettings-property-rendering-limits-buffers-canvas-polygon-index-buffer-size-kb) | `128` |
| [int](class_int#class-int) | [rendering/limits/buffers/immediate\_buffer\_size\_kb](#class-projectsettings-property-rendering-limits-buffers-immediate-buffer-size-kb) | `2048` |
| [int](class_int#class-int) | [rendering/limits/rendering/max\_lights\_per\_object](#class-projectsettings-property-rendering-limits-rendering-max-lights-per-object) | `32` |
| [int](class_int#class-int) | [rendering/limits/rendering/max\_renderable\_elements](#class-projectsettings-property-rendering-limits-rendering-max-renderable-elements) | `65536` |
| [int](class_int#class-int) | [rendering/limits/rendering/max\_renderable\_lights](#class-projectsettings-property-rendering-limits-rendering-max-renderable-lights) | `4096` |
| [int](class_int#class-int) | [rendering/limits/rendering/max\_renderable\_reflections](#class-projectsettings-property-rendering-limits-rendering-max-renderable-reflections) | `1024` |
| [float](class_float#class-float) | [rendering/limits/time/time\_rollover\_secs](#class-projectsettings-property-rendering-limits-time-time-rollover-secs) | `3600` |
| [bool](class_bool#class-bool) | [rendering/misc/lossless\_compression/force\_png](#class-projectsettings-property-rendering-misc-lossless-compression-force-png) | `false` |
| [int](class_int#class-int) | [rendering/misc/lossless\_compression/webp\_compression\_level](#class-projectsettings-property-rendering-misc-lossless-compression-webp-compression-level) | `2` |
| [bool](class_bool#class-bool) | [rendering/misc/mesh\_storage/split\_stream](#class-projectsettings-property-rendering-misc-mesh-storage-split-stream) | `false` |
| [int](class_int#class-int) | [rendering/misc/occlusion\_culling/max\_active\_polygons](#class-projectsettings-property-rendering-misc-occlusion-culling-max-active-polygons) | `8` |
| [int](class_int#class-int) | [rendering/misc/occlusion\_culling/max\_active\_spheres](#class-projectsettings-property-rendering-misc-occlusion-culling-max-active-spheres) | `8` |
| [bool](class_bool#class-bool) | [rendering/portals/advanced/flip\_imported\_portals](#class-projectsettings-property-rendering-portals-advanced-flip-imported-portals) | `false` |
| [bool](class_bool#class-bool) | [rendering/portals/debug/logging](#class-projectsettings-property-rendering-portals-debug-logging) | `true` |
| [bool](class_bool#class-bool) | [rendering/portals/gameplay/use\_signals](#class-projectsettings-property-rendering-portals-gameplay-use-signals) | `true` |
| [bool](class_bool#class-bool) | [rendering/portals/optimize/remove\_danglers](#class-projectsettings-property-rendering-portals-optimize-remove-danglers) | `true` |
| [bool](class_bool#class-bool) | [rendering/portals/pvs/pvs\_logging](#class-projectsettings-property-rendering-portals-pvs-pvs-logging) | `false` |
| [bool](class_bool#class-bool) | [rendering/portals/pvs/use\_simple\_pvs](#class-projectsettings-property-rendering-portals-pvs-use-simple-pvs) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/depth/hdr](#class-projectsettings-property-rendering-quality-depth-hdr) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/depth/hdr.mobile](#class-projectsettings-property-rendering-quality-depth-hdr-mobile) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/depth/use\_32\_bpc\_depth](#class-projectsettings-property-rendering-quality-depth-use-32-bpc-depth) | `false` |
| [String](class_string#class-string) | [rendering/quality/depth\_prepass/disable\_for\_vendors](#class-projectsettings-property-rendering-quality-depth-prepass-disable-for-vendors) | `"PowerVR,Mali,Adreno,Apple"` |
| [bool](class_bool#class-bool) | [rendering/quality/depth\_prepass/enable](#class-projectsettings-property-rendering-quality-depth-prepass-enable) | `true` |
| [int](class_int#class-int) | [rendering/quality/directional\_shadow/size](#class-projectsettings-property-rendering-quality-directional-shadow-size) | `4096` |
| [int](class_int#class-int) | [rendering/quality/directional\_shadow/size.mobile](#class-projectsettings-property-rendering-quality-directional-shadow-size-mobile) | `2048` |
| [String](class_string#class-string) | [rendering/quality/driver/driver\_name](#class-projectsettings-property-rendering-quality-driver-driver-name) | `"GLES3"` |
| [bool](class_bool#class-bool) | [rendering/quality/driver/fallback\_to\_gles2](#class-projectsettings-property-rendering-quality-driver-fallback-to-gles2) | `false` |
| [int](class_int#class-int) | [rendering/quality/filters/anisotropic\_filter\_level](#class-projectsettings-property-rendering-quality-filters-anisotropic-filter-level) | `4` |
| [int](class_int#class-int) | [rendering/quality/filters/msaa](#class-projectsettings-property-rendering-quality-filters-msaa) | `0` |
| [float](class_float#class-float) | [rendering/quality/filters/sharpen\_intensity](#class-projectsettings-property-rendering-quality-filters-sharpen-intensity) | `0.0` |
| [bool](class_bool#class-bool) | [rendering/quality/filters/use\_debanding](#class-projectsettings-property-rendering-quality-filters-use-debanding) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/filters/use\_fxaa](#class-projectsettings-property-rendering-quality-filters-use-fxaa) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/filters/use\_nearest\_mipmap\_filter](#class-projectsettings-property-rendering-quality-filters-use-nearest-mipmap-filter) | `false` |
| [int](class_int#class-int) | [rendering/quality/intended\_usage/framebuffer\_allocation](#class-projectsettings-property-rendering-quality-intended-usage-framebuffer-allocation) | `2` |
| [int](class_int#class-int) | [rendering/quality/intended\_usage/framebuffer\_allocation.mobile](#class-projectsettings-property-rendering-quality-intended-usage-framebuffer-allocation-mobile) | `3` |
| [bool](class_bool#class-bool) | [rendering/quality/lightmapping/use\_bicubic\_sampling](#class-projectsettings-property-rendering-quality-lightmapping-use-bicubic-sampling) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/lightmapping/use\_bicubic\_sampling.mobile](#class-projectsettings-property-rendering-quality-lightmapping-use-bicubic-sampling-mobile) | `false` |
| [int](class_int#class-int) | [rendering/quality/reflections/atlas\_size](#class-projectsettings-property-rendering-quality-reflections-atlas-size) | `2048` |
| [int](class_int#class-int) | [rendering/quality/reflections/atlas\_subdiv](#class-projectsettings-property-rendering-quality-reflections-atlas-subdiv) | `8` |
| [bool](class_bool#class-bool) | [rendering/quality/reflections/high\_quality\_ggx](#class-projectsettings-property-rendering-quality-reflections-high-quality-ggx) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/reflections/high\_quality\_ggx.mobile](#class-projectsettings-property-rendering-quality-reflections-high-quality-ggx-mobile) | `false` |
| [int](class_int#class-int) | [rendering/quality/reflections/irradiance\_max\_size](#class-projectsettings-property-rendering-quality-reflections-irradiance-max-size) | `128` |
| [bool](class_bool#class-bool) | [rendering/quality/reflections/texture\_array\_reflections](#class-projectsettings-property-rendering-quality-reflections-texture-array-reflections) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/reflections/texture\_array\_reflections.mobile](#class-projectsettings-property-rendering-quality-reflections-texture-array-reflections-mobile) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/shading/force\_blinn\_over\_ggx](#class-projectsettings-property-rendering-quality-shading-force-blinn-over-ggx) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/shading/force\_blinn\_over\_ggx.mobile](#class-projectsettings-property-rendering-quality-shading-force-blinn-over-ggx-mobile) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/shading/force\_lambert\_over\_burley](#class-projectsettings-property-rendering-quality-shading-force-lambert-over-burley) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/shading/force\_lambert\_over\_burley.mobile](#class-projectsettings-property-rendering-quality-shading-force-lambert-over-burley-mobile) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/shading/force\_vertex\_shading](#class-projectsettings-property-rendering-quality-shading-force-vertex-shading) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/shading/force\_vertex\_shading.mobile](#class-projectsettings-property-rendering-quality-shading-force-vertex-shading-mobile) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/shading/use\_physical\_light\_attenuation](#class-projectsettings-property-rendering-quality-shading-use-physical-light-attenuation) | `false` |
| [int](class_int#class-int) | [rendering/quality/shadow\_atlas/cubemap\_size](#class-projectsettings-property-rendering-quality-shadow-atlas-cubemap-size) | `512` |
| [int](class_int#class-int) | [rendering/quality/shadow\_atlas/quadrant\_0\_subdiv](#class-projectsettings-property-rendering-quality-shadow-atlas-quadrant-0-subdiv) | `1` |
| [int](class_int#class-int) | [rendering/quality/shadow\_atlas/quadrant\_1\_subdiv](#class-projectsettings-property-rendering-quality-shadow-atlas-quadrant-1-subdiv) | `2` |
| [int](class_int#class-int) | [rendering/quality/shadow\_atlas/quadrant\_2\_subdiv](#class-projectsettings-property-rendering-quality-shadow-atlas-quadrant-2-subdiv) | `3` |
| [int](class_int#class-int) | [rendering/quality/shadow\_atlas/quadrant\_3\_subdiv](#class-projectsettings-property-rendering-quality-shadow-atlas-quadrant-3-subdiv) | `4` |
| [int](class_int#class-int) | [rendering/quality/shadow\_atlas/size](#class-projectsettings-property-rendering-quality-shadow-atlas-size) | `4096` |
| [int](class_int#class-int) | [rendering/quality/shadow\_atlas/size.mobile](#class-projectsettings-property-rendering-quality-shadow-atlas-size-mobile) | `2048` |
| [int](class_int#class-int) | [rendering/quality/shadows/filter\_mode](#class-projectsettings-property-rendering-quality-shadows-filter-mode) | `1` |
| [int](class_int#class-int) | [rendering/quality/shadows/filter\_mode.mobile](#class-projectsettings-property-rendering-quality-shadows-filter-mode-mobile) | `0` |
| [bool](class_bool#class-bool) | [rendering/quality/skinning/force\_software\_skinning](#class-projectsettings-property-rendering-quality-skinning-force-software-skinning) | `false` |
| [bool](class_bool#class-bool) | [rendering/quality/skinning/software\_skinning\_fallback](#class-projectsettings-property-rendering-quality-skinning-software-skinning-fallback) | `true` |
| [float](class_float#class-float) | [rendering/quality/spatial\_partitioning/bvh\_collision\_margin](#class-projectsettings-property-rendering-quality-spatial-partitioning-bvh-collision-margin) | `0.1` |
| [float](class_float#class-float) | [rendering/quality/spatial\_partitioning/render\_tree\_balance](#class-projectsettings-property-rendering-quality-spatial-partitioning-render-tree-balance) | `0.0` |
| [bool](class_bool#class-bool) | [rendering/quality/spatial\_partitioning/use\_bvh](#class-projectsettings-property-rendering-quality-spatial-partitioning-use-bvh) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/subsurface\_scattering/follow\_surface](#class-projectsettings-property-rendering-quality-subsurface-scattering-follow-surface) | `false` |
| [int](class_int#class-int) | [rendering/quality/subsurface\_scattering/quality](#class-projectsettings-property-rendering-quality-subsurface-scattering-quality) | `1` |
| [int](class_int#class-int) | [rendering/quality/subsurface\_scattering/scale](#class-projectsettings-property-rendering-quality-subsurface-scattering-scale) | `1.0` |
| [bool](class_bool#class-bool) | [rendering/quality/subsurface\_scattering/weight\_samples](#class-projectsettings-property-rendering-quality-subsurface-scattering-weight-samples) | `true` |
| [bool](class_bool#class-bool) | [rendering/quality/voxel\_cone\_tracing/high\_quality](#class-projectsettings-property-rendering-quality-voxel-cone-tracing-high-quality) | `false` |
| [int](class_int#class-int) | [rendering/threads/thread\_model](#class-projectsettings-property-rendering-threads-thread-model) | `1` |
| [bool](class_bool#class-bool) | [rendering/threads/thread\_safe\_bvh](#class-projectsettings-property-rendering-threads-thread-safe-bvh) | `false` |
| [bool](class_bool#class-bool) | [rendering/vram\_compression/import\_bptc](#class-projectsettings-property-rendering-vram-compression-import-bptc) | `false` |
| [bool](class_bool#class-bool) | [rendering/vram\_compression/import\_etc](#class-projectsettings-property-rendering-vram-compression-import-etc) | `false` |
| [bool](class_bool#class-bool) | [rendering/vram\_compression/import\_etc2](#class-projectsettings-property-rendering-vram-compression-import-etc2) | `true` |
| [bool](class_bool#class-bool) | [rendering/vram\_compression/import\_pvrtc](#class-projectsettings-property-rendering-vram-compression-import-pvrtc) | `false` |
| [bool](class_bool#class-bool) | [rendering/vram\_compression/import\_s3tc](#class-projectsettings-property-rendering-vram-compression-import-s3tc) | `true` |
| [int](class_int#class-int) | [world/2d/cell\_size](#class-projectsettings-property-world-2d-cell-size) | `100` |
Methods
-------
| | |
| --- | --- |
| void | [add\_property\_info](#class-projectsettings-method-add-property-info) **(** [Dictionary](class_dictionary#class-dictionary) hint **)** |
| void | [clear](#class-projectsettings-method-clear) **(** [String](class_string#class-string) name **)** |
| [int](class_int#class-int) | [get\_order](#class-projectsettings-method-get-order) **(** [String](class_string#class-string) name **)** const |
| [Variant](class_variant#class-variant) | [get\_setting](#class-projectsettings-method-get-setting) **(** [String](class_string#class-string) name **)** const |
| [String](class_string#class-string) | [globalize\_path](#class-projectsettings-method-globalize-path) **(** [String](class_string#class-string) path **)** const |
| [bool](class_bool#class-bool) | [has\_setting](#class-projectsettings-method-has-setting) **(** [String](class_string#class-string) name **)** const |
| [bool](class_bool#class-bool) | [load\_resource\_pack](#class-projectsettings-method-load-resource-pack) **(** [String](class_string#class-string) pack, [bool](class_bool#class-bool) replace\_files=true, [int](class_int#class-int) offset=0 **)** |
| [String](class_string#class-string) | [localize\_path](#class-projectsettings-method-localize-path) **(** [String](class_string#class-string) path **)** const |
| [bool](class_bool#class-bool) | [property\_can\_revert](#class-projectsettings-method-property-can-revert) **(** [String](class_string#class-string) name **)** |
| [Variant](class_variant#class-variant) | [property\_get\_revert](#class-projectsettings-method-property-get-revert) **(** [String](class_string#class-string) name **)** |
| [Error](class_%40globalscope#enum-globalscope-error) | [save](#class-projectsettings-method-save) **(** **)** |
| [Error](class_%40globalscope#enum-globalscope-error) | [save\_custom](#class-projectsettings-method-save-custom) **(** [String](class_string#class-string) file **)** |
| void | [set\_initial\_value](#class-projectsettings-method-set-initial-value) **(** [String](class_string#class-string) name, [Variant](class_variant#class-variant) value **)** |
| void | [set\_order](#class-projectsettings-method-set-order) **(** [String](class_string#class-string) name, [int](class_int#class-int) position **)** |
| void | [set\_setting](#class-projectsettings-method-set-setting) **(** [String](class_string#class-string) name, [Variant](class_variant#class-variant) value **)** |
Signals
-------
### project\_settings\_changed ( )
Objects can use this signal to restrict reading of settings only to situations where a change has been made.
Property Descriptions
---------------------
### [String](class_string#class-string) android/modules
| | |
| --- | --- |
| *Default* | `""` |
Comma-separated list of custom Android modules (which must have been built in the Android export templates) using their Java package path, e.g. `"org/godotengine/godot/MyCustomSingleton,com/example/foo/FrenchFriesFactory"`.
**Note:** Since Godot 3.2.2, the `org/godotengine/godot/GodotPaymentV3` module was deprecated and replaced by the `GodotPayment` plugin which should be enabled in the Android export preset under `Plugins` section. The singleton to access in code was also renamed to `GodotPayment`.
### [Color](class_color#class-color) application/boot\_splash/bg\_color
| | |
| --- | --- |
| *Default* | `Color( 0.14, 0.14, 0.14, 1 )` |
Background color for the boot splash.
### [bool](class_bool#class-bool) application/boot\_splash/fullsize
| | |
| --- | --- |
| *Default* | `true` |
If `true`, scale the boot splash image to the full window size (preserving the aspect ratio) when the engine starts. If `false`, the engine will leave it at the default pixel size.
### [String](class_string#class-string) application/boot\_splash/image
| | |
| --- | --- |
| *Default* | `""` |
Path to an image used as the boot splash. If left empty, the default Godot Engine splash will be displayed instead.
**Note:** Only effective if [application/boot\_splash/show\_image](#class-projectsettings-property-application-boot-splash-show-image) is `true`.
### [bool](class_bool#class-bool) application/boot\_splash/show\_image
| | |
| --- | --- |
| *Default* | `true` |
If `true`, displays the image specified in [application/boot\_splash/image](#class-projectsettings-property-application-boot-splash-image) when the engine starts. If `false`, only displays the plain color specified in [application/boot\_splash/bg\_color](#class-projectsettings-property-application-boot-splash-bg-color).
### [bool](class_bool#class-bool) application/boot\_splash/use\_filter
| | |
| --- | --- |
| *Default* | `true` |
If `true`, applies linear filtering when scaling the image (recommended for high-resolution artwork). If `false`, uses nearest-neighbor interpolation (recommended for pixel art).
### [String](class_string#class-string) application/config/custom\_user\_dir\_name
| | |
| --- | --- |
| *Default* | `""` |
This user directory is used for storing persistent data (`user://` filesystem). If left empty, `user://` resolves to a project-specific folder in Godot's own configuration folder (see [OS.get\_user\_data\_dir](class_os#class-os-method-get-user-data-dir)). If a custom directory name is defined, this name will be used instead and appended to the system-specific user data directory (same parent folder as the Godot configuration folder documented in [OS.get\_user\_data\_dir](class_os#class-os-method-get-user-data-dir)).
The [application/config/use\_custom\_user\_dir](#class-projectsettings-property-application-config-use-custom-user-dir) setting must be enabled for this to take effect.
### [String](class_string#class-string) application/config/description
| | |
| --- | --- |
| *Default* | `""` |
The project's description, displayed as a tooltip in the Project Manager when hovering the project.
### [String](class_string#class-string) application/config/icon
| | |
| --- | --- |
| *Default* | `""` |
Icon used for the project, set when project loads. Exporters will also use this icon when possible.
### [String](class_string#class-string) application/config/macos\_native\_icon
| | |
| --- | --- |
| *Default* | `""` |
Icon set in `.icns` format used on macOS to set the game's icon. This is done automatically on start by calling [OS.set\_native\_icon](class_os#class-os-method-set-native-icon).
### [String](class_string#class-string) application/config/name
| | |
| --- | --- |
| *Default* | `""` |
The project's name. It is used both by the Project Manager and by exporters. The project name can be translated by translating its value in localization files. The window title will be set to match the project name automatically on startup.
**Note:** Changing this value will also change the user data folder's path if [application/config/use\_custom\_user\_dir](#class-projectsettings-property-application-config-use-custom-user-dir) is `false`. After renaming the project, you will no longer be able to access existing data in `user://` unless you rename the old folder to match the new project name. See [Data paths](https://docs.godotengine.org/en/3.5/tutorials/io/data_paths.html) in the documentation for more information.
### [String](class_string#class-string) application/config/project\_settings\_override
| | |
| --- | --- |
| *Default* | `""` |
Specifies a file to override project settings. For example: `user://custom_settings.cfg`. See "Overriding" in the `ProjectSettings` class description at the top for more information.
**Note:** Regardless of this setting's value, `res://override.cfg` will still be read to override the project settings.
### [bool](class_bool#class-bool) application/config/use\_custom\_user\_dir
| | |
| --- | --- |
| *Default* | `false` |
If `true`, the project will save user data to its own user directory (see [application/config/custom\_user\_dir\_name](#class-projectsettings-property-application-config-custom-user-dir-name)). This setting is only effective on desktop platforms. A name must be set in the [application/config/custom\_user\_dir\_name](#class-projectsettings-property-application-config-custom-user-dir-name) setting for this to take effect. If `false`, the project will save user data to `(OS user data directory)/Godot/app_userdata/(project name)`.
### [bool](class_bool#class-bool) application/config/use\_hidden\_project\_data\_directory
| | |
| --- | --- |
| *Default* | `true` |
If `true`, the project will use a hidden directory (`.import`) for storing project-specific data (metadata, shader cache, etc.).
If `false`, a non-hidden directory (`import`) will be used instead.
**Note:** Restart the application after changing this setting.
**Note:** Changing this value can help on platforms or with third-party tools where hidden directory patterns are disallowed. Only modify this setting if you know that your environment requires it, as changing the default can impact compatibility with some external tools or plugins which expect the default `.import` folder.
### [String](class_string#class-string) application/config/windows\_native\_icon
| | |
| --- | --- |
| *Default* | `""` |
Icon set in `.ico` format used on Windows to set the game's icon. This is done automatically on start by calling [OS.set\_native\_icon](class_os#class-os-method-set-native-icon).
### [bool](class_bool#class-bool) application/run/delta\_smoothing
| | |
| --- | --- |
| *Default* | `true` |
Time samples for frame deltas are subject to random variation introduced by the platform, even when frames are displayed at regular intervals thanks to V-Sync. This can lead to jitter. Delta smoothing can often give a better result by filtering the input deltas to correct for minor fluctuations from the refresh rate.
**Note:** Delta smoothing is only attempted when [display/window/vsync/use\_vsync](#class-projectsettings-property-display-window-vsync-use-vsync) is switched on, as it does not work well without V-Sync.
It may take several seconds at a stable frame rate before the smoothing is initially activated. It will only be active on machines where performance is adequate to render frames at the refresh rate.
### [bool](class_bool#class-bool) application/run/delta\_sync\_after\_draw
| | |
| --- | --- |
| *Default* | `false` |
**Experimental.** Shifts the measurement of delta time for each frame to just after the drawing has taken place. This may lead to more consistent deltas and a reduction in frame stutters.
### [bool](class_bool#class-bool) application/run/disable\_stderr
| | |
| --- | --- |
| *Default* | `false` |
If `true`, disables printing to standard error. If `true`, this also hides error and warning messages printed by [@GDScript.push\_error](class_%40gdscript#class-gdscript-method-push-error) and [@GDScript.push\_warning](class_%40gdscript#class-gdscript-method-push-warning). See also [application/run/disable\_stdout](#class-projectsettings-property-application-run-disable-stdout).
Changes to this setting will only be applied upon restarting the application.
### [bool](class_bool#class-bool) application/run/disable\_stdout
| | |
| --- | --- |
| *Default* | `false` |
If `true`, disables printing to standard output. This is equivalent to starting the editor or project with the `--quiet` command line argument. See also [application/run/disable\_stderr](#class-projectsettings-property-application-run-disable-stderr).
Changes to this setting will only be applied upon restarting the application.
### [bool](class_bool#class-bool) application/run/flush\_stdout\_on\_print
| | |
| --- | --- |
| *Default* | `false` |
If `true`, flushes the standard output stream every time a line is printed. This affects both terminal logging and file logging.
When running a project, this setting must be enabled if you want logs to be collected by service managers such as systemd/journalctl. This setting is disabled by default on release builds, since flushing on every printed line will negatively affect performance if lots of lines are printed in a rapid succession. Also, if this setting is enabled, logged files will still be written successfully if the application crashes or is otherwise killed by the user (without being closed "normally").
**Note:** Regardless of this setting, the standard error stream (`stderr`) is always flushed when a line is printed to it.
Changes to this setting will only be applied upon restarting the application.
### [bool](class_bool#class-bool) application/run/flush\_stdout\_on\_print.debug
| | |
| --- | --- |
| *Default* | `true` |
Debug build override for [application/run/flush\_stdout\_on\_print](#class-projectsettings-property-application-run-flush-stdout-on-print), as performance is less important during debugging.
Changes to this setting will only be applied upon restarting the application.
### [int](class_int#class-int) application/run/frame\_delay\_msec
| | |
| --- | --- |
| *Default* | `0` |
Forces a delay between frames in the main loop (in milliseconds). This may be useful if you plan to disable vertical synchronization.
### [bool](class_bool#class-bool) application/run/low\_processor\_mode
| | |
| --- | --- |
| *Default* | `false` |
If `true`, enables low-processor usage mode. This setting only works on desktop platforms. The screen is not redrawn if nothing changes visually. This is meant for writing applications and editors, but is pretty useless (and can hurt performance) in most games.
### [int](class_int#class-int) application/run/low\_processor\_mode\_sleep\_usec
| | |
| --- | --- |
| *Default* | `6900` |
Amount of sleeping between frames when the low-processor usage mode is enabled (in microseconds). Higher values will result in lower CPU usage.
### [String](class_string#class-string) application/run/main\_scene
| | |
| --- | --- |
| *Default* | `""` |
Path to the main scene file that will be loaded when the project runs.
### [float](class_float#class-float) audio/channel\_disable\_threshold\_db
| | |
| --- | --- |
| *Default* | `-60.0` |
Audio buses will disable automatically when sound goes below a given dB threshold for a given time. This saves CPU as effects assigned to that bus will no longer do any processing.
### [float](class_float#class-float) audio/channel\_disable\_time
| | |
| --- | --- |
| *Default* | `2.0` |
Audio buses will disable automatically when sound goes below a given dB threshold for a given time. This saves CPU as effects assigned to that bus will no longer do any processing.
### [String](class_string#class-string) audio/default\_bus\_layout
| | |
| --- | --- |
| *Default* | `"res://default_bus_layout.tres"` |
Default [AudioBusLayout](class_audiobuslayout#class-audiobuslayout) resource file to use in the project, unless overridden by the scene.
### [String](class_string#class-string) audio/driver
Specifies the audio driver to use. This setting is platform-dependent as each platform supports different audio drivers. If left empty, the default audio driver will be used.
### [bool](class_bool#class-bool) audio/enable\_audio\_input
| | |
| --- | --- |
| *Default* | `false` |
If `true`, microphone input will be allowed. This requires appropriate permissions to be set when exporting to Android or iOS.
**Note:** If the operating system blocks access to audio input devices (due to the user's privacy settings), audio capture will only return silence. On Windows 10 and later, make sure that apps are allowed to access the microphone in the OS' privacy settings.
### [int](class_int#class-int) audio/mix\_rate
| | |
| --- | --- |
| *Default* | `44100` |
The mixing rate used for audio (in Hz). In general, it's better to not touch this and leave it to the host operating system.
### [int](class_int#class-int) audio/mix\_rate.web
| | |
| --- | --- |
| *Default* | `0` |
Safer override for [audio/mix\_rate](#class-projectsettings-property-audio-mix-rate) in the Web platform. Here `0` means "let the browser choose" (since some browsers do not like forcing the mix rate).
### [int](class_int#class-int) audio/output\_latency
| | |
| --- | --- |
| *Default* | `15` |
Specifies the preferred output latency in milliseconds for audio. Lower values will result in lower audio latency at the cost of increased CPU usage. Low values may result in audible cracking on slower hardware.
Audio output latency may be constrained by the host operating system and audio hardware drivers. If the host can not provide the specified audio output latency then Godot will attempt to use the nearest latency allowed by the host. As such you should always use [AudioServer.get\_output\_latency](class_audioserver#class-audioserver-method-get-output-latency) to determine the actual audio output latency.
**Note:** This setting is ignored on Windows.
### [int](class_int#class-int) audio/output\_latency.web
| | |
| --- | --- |
| *Default* | `50` |
Safer override for [audio/output\_latency](#class-projectsettings-property-audio-output-latency) in the Web platform, to avoid audio issues especially on mobile devices.
### [int](class_int#class-int) audio/video\_delay\_compensation\_ms
| | |
| --- | --- |
| *Default* | `0` |
Setting to hardcode audio delay when playing video. Best to leave this untouched unless you know what you are doing.
### [int](class_int#class-int) compression/formats/gzip/compression\_level
| | |
| --- | --- |
| *Default* | `-1` |
The default compression level for gzip. Affects compressed scenes and resources. Higher levels result in smaller files at the cost of compression speed. Decompression speed is mostly unaffected by the compression level. `-1` uses the default gzip compression level, which is identical to `6` but could change in the future due to underlying zlib updates.
### [int](class_int#class-int) compression/formats/zlib/compression\_level
| | |
| --- | --- |
| *Default* | `-1` |
The default compression level for Zlib. Affects compressed scenes and resources. Higher levels result in smaller files at the cost of compression speed. Decompression speed is mostly unaffected by the compression level. `-1` uses the default gzip compression level, which is identical to `6` but could change in the future due to underlying zlib updates.
### [int](class_int#class-int) compression/formats/zstd/compression\_level
| | |
| --- | --- |
| *Default* | `3` |
The default compression level for Zstandard. Affects compressed scenes and resources. Higher levels result in smaller files at the cost of compression speed. Decompression speed is mostly unaffected by the compression level.
### [bool](class_bool#class-bool) compression/formats/zstd/long\_distance\_matching
| | |
| --- | --- |
| *Default* | `false` |
Enables [long-distance matching](https://github.com/facebook/zstd/releases/tag/v1.3.2) in Zstandard.
### [int](class_int#class-int) compression/formats/zstd/window\_log\_size
| | |
| --- | --- |
| *Default* | `27` |
Largest size limit (in power of 2) allowed when compressing using long-distance matching with Zstandard. Higher values can result in better compression, but will require more memory when compressing and decompressing.
### [bool](class_bool#class-bool) debug/gdscript/completion/autocomplete\_setters\_and\_getters
| | |
| --- | --- |
| *Default* | `false` |
If `true`, displays getters and setters in autocompletion results in the script editor. This setting is meant to be used when porting old projects (Godot 2), as using member variables is the preferred style from Godot 3 onwards.
### [bool](class_bool#class-bool) debug/gdscript/warnings/constant\_used\_as\_function
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a constant is used as a function.
### [bool](class_bool#class-bool) debug/gdscript/warnings/deprecated\_keyword
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when deprecated keywords such as `slave` are used.
### [bool](class_bool#class-bool) debug/gdscript/warnings/enable
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables specific GDScript warnings (see `debug/gdscript/warnings/*` settings). If `false`, disables all GDScript warnings.
### [bool](class_bool#class-bool) debug/gdscript/warnings/exclude\_addons
| | |
| --- | --- |
| *Default* | `true` |
If `true`, scripts in the `res://addons` folder will not generate warnings.
### [bool](class_bool#class-bool) debug/gdscript/warnings/export\_hint\_type\_mistmatch
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when the type of the default value set to an exported variable is different than the specified export type.
### [bool](class_bool#class-bool) debug/gdscript/warnings/function\_conflicts\_constant
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a function is declared with the same name as a constant.
### [bool](class_bool#class-bool) debug/gdscript/warnings/function\_conflicts\_variable
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a function is declared with the same name as a variable. This will turn into an error in a future version when first-class functions become supported in GDScript.
### [bool](class_bool#class-bool) debug/gdscript/warnings/function\_may\_yield
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a function assigned to a variable may yield and return a function state instead of a value.
### [bool](class_bool#class-bool) debug/gdscript/warnings/function\_used\_as\_property
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when using a function as if it was a property.
### [bool](class_bool#class-bool) debug/gdscript/warnings/incompatible\_ternary
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a ternary operator may emit values with incompatible types.
### [bool](class_bool#class-bool) debug/gdscript/warnings/integer\_division
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when dividing an integer by another integer (the decimal part will be discarded).
### [bool](class_bool#class-bool) debug/gdscript/warnings/narrowing\_conversion
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when passing a floating-point value to a function that expects an integer (it will be converted and lose precision).
### [bool](class_bool#class-bool) debug/gdscript/warnings/property\_used\_as\_function
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when using a property as if it was a function.
### [bool](class_bool#class-bool) debug/gdscript/warnings/return\_value\_discarded
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when calling a function without using its return value (by assigning it to a variable or using it as a function argument). Such return values are sometimes used to denote possible errors using the [Error](class_%40globalscope#enum-globalscope-error) enum.
### [bool](class_bool#class-bool) debug/gdscript/warnings/shadowed\_variable
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when defining a local or subclass member variable that would shadow a variable at an upper level (such as a member variable).
### [bool](class_bool#class-bool) debug/gdscript/warnings/standalone\_expression
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when calling an expression that has no effect on the surrounding code, such as writing `2 + 2` as a statement.
### [bool](class_bool#class-bool) debug/gdscript/warnings/standalone\_ternary
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when calling a ternary expression that has no effect on the surrounding code, such as writing `42 if active else 0` as a statement.
### [bool](class_bool#class-bool) debug/gdscript/warnings/treat\_warnings\_as\_errors
| | |
| --- | --- |
| *Default* | `false` |
If `true`, all warnings will be reported as if they were errors.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unassigned\_variable
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when using a variable that wasn't previously assigned.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unassigned\_variable\_op\_assign
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when assigning a variable using an assignment operator like `+=` if the variable wasn't previously assigned.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unreachable\_code
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when unreachable code is detected (such as after a `return` statement that will always be executed).
### [bool](class_bool#class-bool) debug/gdscript/warnings/unsafe\_call\_argument
| | |
| --- | --- |
| *Default* | `false` |
If `true`, enables warnings when using an expression whose type may not be compatible with the function parameter expected.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unsafe\_cast
| | |
| --- | --- |
| *Default* | `false` |
If `true`, enables warnings when performing an unsafe cast.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unsafe\_method\_access
| | |
| --- | --- |
| *Default* | `false` |
If `true`, enables warnings when calling a method whose presence is not guaranteed at compile-time in the class.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unsafe\_property\_access
| | |
| --- | --- |
| *Default* | `false` |
If `true`, enables warnings when accessing a property whose presence is not guaranteed at compile-time in the class.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unused\_argument
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a function parameter is unused.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unused\_class\_variable
| | |
| --- | --- |
| *Default* | `false` |
If `true`, enables warnings when a member variable is unused.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unused\_signal
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a signal is unused.
### [bool](class_bool#class-bool) debug/gdscript/warnings/unused\_variable
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a local variable is unused.
### [bool](class_bool#class-bool) debug/gdscript/warnings/variable\_conflicts\_function
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when a variable is declared with the same name as a function. This will turn into an error in a future version when first-class functions become supported in GDScript.
### [bool](class_bool#class-bool) debug/gdscript/warnings/void\_assignment
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings when assigning the result of a function that returns `void` to a variable.
### [String](class_string#class-string) debug/settings/crash\_handler/message
| | |
| --- | --- |
| *Default* | `"Please include this when reporting the bug to the project developer."` |
Message to be displayed before the backtrace when the engine crashes. By default, this message is only used in exported projects due to the editor-only override applied to this setting.
### [String](class_string#class-string) debug/settings/crash\_handler/message.editor
| | |
| --- | --- |
| *Default* | `"Please include this when reporting the bug on: https://github.com/godotengine/godot/issues"` |
Editor-only override for [debug/settings/crash\_handler/message](#class-projectsettings-property-debug-settings-crash-handler-message). Does not affect exported projects in debug or release mode.
### [int](class_int#class-int) debug/settings/fps/force\_fps
| | |
| --- | --- |
| *Default* | `0` |
Maximum number of frames per second allowed. The actual number of frames per second may still be below this value if the game is lagging. See also [physics/common/physics\_fps](#class-projectsettings-property-physics-common-physics-fps).
If [display/window/vsync/use\_vsync](#class-projectsettings-property-display-window-vsync-use-vsync) is enabled, it takes precedence and the forced FPS number cannot exceed the monitor's refresh rate.
This setting is therefore mostly relevant for lowering the maximum FPS below VSync, e.g. to perform non-real-time rendering of static frames, or test the project under lag conditions.
**Note:** This property is only read when the project starts. To change the rendering FPS cap at runtime, set [Engine.target\_fps](class_engine#class-engine-property-target-fps) instead.
### [int](class_int#class-int) debug/settings/gdscript/max\_call\_stack
| | |
| --- | --- |
| *Default* | `1024` |
Maximum call stack allowed for debugging GDScript.
### [bool](class_bool#class-bool) debug/settings/physics\_interpolation/enable\_warnings
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables warnings which can help pinpoint where nodes are being incorrectly updated, which will result in incorrect interpolation and visual glitches.
When a node is being interpolated, it is essential that the transform is set during [Node.\_physics\_process](class_node#class-node-method-physics-process) (during a physics tick) rather than [Node.\_process](class_node#class-node-method-process) (during a frame).
### [int](class_int#class-int) debug/settings/profiler/max\_functions
| | |
| --- | --- |
| *Default* | `16384` |
Maximum amount of functions per frame allowed when profiling.
### [bool](class_bool#class-bool) debug/settings/stdout/print\_fps
| | |
| --- | --- |
| *Default* | `false` |
Print frames per second to standard output every second.
### [bool](class_bool#class-bool) debug/settings/stdout/verbose\_stdout
| | |
| --- | --- |
| *Default* | `false` |
Print more information to standard output when running. It displays information such as memory leaks, which scenes and resources are being loaded, etc.
### [int](class_int#class-int) debug/settings/visual\_script/max\_call\_stack
| | |
| --- | --- |
| *Default* | `1024` |
Maximum call stack in visual scripting, to avoid infinite recursion.
### [Color](class_color#class-color) debug/shapes/collision/contact\_color
| | |
| --- | --- |
| *Default* | `Color( 1, 0.2, 0.1, 0.8 )` |
Color of the contact points between collision shapes, visible when "Visible Collision Shapes" is enabled in the Debug menu.
### [bool](class_bool#class-bool) debug/shapes/collision/draw\_2d\_outlines
| | |
| --- | --- |
| *Default* | `true` |
Sets whether 2D physics will display collision outlines in game when "Visible Collision Shapes" is enabled in the Debug menu.
### [int](class_int#class-int) debug/shapes/collision/max\_contacts\_displayed
| | |
| --- | --- |
| *Default* | `10000` |
Maximum number of contact points between collision shapes to display when "Visible Collision Shapes" is enabled in the Debug menu.
### [Color](class_color#class-color) debug/shapes/collision/shape\_color
| | |
| --- | --- |
| *Default* | `Color( 0, 0.6, 0.7, 0.42 )` |
Color of the collision shapes, visible when "Visible Collision Shapes" is enabled in the Debug menu.
### [Color](class_color#class-color) debug/shapes/navigation/disabled\_geometry\_color
| | |
| --- | --- |
| *Default* | `Color( 1, 0.7, 0.1, 0.4 )` |
Color of the disabled navigation geometry, visible when "Visible Navigation" is enabled in the Debug menu.
### [Color](class_color#class-color) debug/shapes/navigation/geometry\_color
| | |
| --- | --- |
| *Default* | `Color( 0.1, 1, 0.7, 0.4 )` |
Color of the navigation geometry, visible when "Visible Navigation" is enabled in the Debug menu.
### [String](class_string#class-string) display/mouse\_cursor/custom\_image
| | |
| --- | --- |
| *Default* | `""` |
Custom image for the mouse cursor (limited to 256×256).
### [Vector2](class_vector2#class-vector2) display/mouse\_cursor/custom\_image\_hotspot
| | |
| --- | --- |
| *Default* | `Vector2( 0, 0 )` |
Hotspot for the custom mouse cursor image.
### [Vector2](class_vector2#class-vector2) display/mouse\_cursor/tooltip\_position\_offset
| | |
| --- | --- |
| *Default* | `Vector2( 10, 10 )` |
Position offset for tooltips, relative to the mouse cursor's hotspot.
### [bool](class_bool#class-bool) display/window/dpi/allow\_hidpi
| | |
| --- | --- |
| *Default* | `false` |
If `true`, allows HiDPI display on Windows, macOS, and the HTML5 platform. This setting has no effect on desktop Linux, as DPI-awareness fallbacks are not supported there.
### [bool](class_bool#class-bool) display/window/energy\_saving/keep\_screen\_on
| | |
| --- | --- |
| *Default* | `true` |
If `true`, keeps the screen on (even in case of inactivity), so the screensaver does not take over. Works on desktop and mobile platforms.
### [String](class_string#class-string) display/window/handheld/orientation
| | |
| --- | --- |
| *Default* | `"landscape"` |
The default screen orientation to use on mobile devices.
**Note:** When set to a portrait orientation, this project setting does not flip the project resolution's width and height automatically. Instead, you have to set [display/window/size/width](#class-projectsettings-property-display-window-size-width) and [display/window/size/height](#class-projectsettings-property-display-window-size-height) accordingly.
### [bool](class_bool#class-bool) display/window/ios/hide\_home\_indicator
| | |
| --- | --- |
| *Default* | `true` |
If `true`, the home indicator is hidden automatically. This only affects iOS devices without a physical home button.
### [bool](class_bool#class-bool) display/window/per\_pixel\_transparency/allowed
| | |
| --- | --- |
| *Default* | `false` |
If `true`, allows per-pixel transparency for the window background. This affects performance, so leave it on `false` unless you need it.
See [OS.window\_per\_pixel\_transparency\_enabled](class_os#class-os-property-window-per-pixel-transparency-enabled) for more details.
**Note:** This feature is implemented on HTML5, Linux, macOS, Windows, and Android.
### [bool](class_bool#class-bool) display/window/per\_pixel\_transparency/enabled
| | |
| --- | --- |
| *Default* | `false` |
Sets the window background to transparent when it starts.
See [OS.window\_per\_pixel\_transparency\_enabled](class_os#class-os-property-window-per-pixel-transparency-enabled) for more details.
**Note:** This feature is implemented on HTML5, Linux, macOS, Windows, and Android.
### [bool](class_bool#class-bool) display/window/size/always\_on\_top
| | |
| --- | --- |
| *Default* | `false` |
Forces the main window to be always on top.
**Note:** This setting is ignored on iOS, Android, and HTML5.
### [bool](class_bool#class-bool) display/window/size/borderless
| | |
| --- | --- |
| *Default* | `false` |
Forces the main window to be borderless.
**Note:** This setting is ignored on iOS, Android, and HTML5.
### [bool](class_bool#class-bool) display/window/size/fullscreen
| | |
| --- | --- |
| *Default* | `false` |
Sets the main window to full screen when the project starts. Note that this is not *exclusive* fullscreen. On Windows and Linux, a borderless window is used to emulate fullscreen. On macOS, a new desktop is used to display the running project.
Regardless of the platform, enabling fullscreen will change the window size to match the monitor's size. Therefore, make sure your project supports [multiple resolutions](https://docs.godotengine.org/en/3.5/tutorials/rendering/multiple_resolutions.html) when enabling fullscreen mode.
**Note:** This setting is ignored on iOS, Android, and HTML5.
### [int](class_int#class-int) display/window/size/height
| | |
| --- | --- |
| *Default* | `600` |
Sets the game's main viewport height. On desktop platforms, this is the default window size. Stretch mode settings also use this as a reference when enabled.
### [bool](class_bool#class-bool) display/window/size/resizable
| | |
| --- | --- |
| *Default* | `true` |
Allows the window to be resizable by default.
**Note:** This setting is ignored on iOS.
### [int](class_int#class-int) display/window/size/test\_height
| | |
| --- | --- |
| *Default* | `0` |
If greater than zero, overrides the window height when running the game. Useful for testing stretch modes.
### [int](class_int#class-int) display/window/size/test\_width
| | |
| --- | --- |
| *Default* | `0` |
If greater than zero, overrides the window width when running the game. Useful for testing stretch modes.
### [int](class_int#class-int) display/window/size/width
| | |
| --- | --- |
| *Default* | `1024` |
Sets the game's main viewport width. On desktop platforms, this is the default window size. Stretch mode settings also use this as a reference when enabled.
### [String](class_string#class-string) display/window/tablet\_driver
Specifies the tablet driver to use. If left empty, the default driver will be used.
### [bool](class_bool#class-bool) display/window/vsync/use\_vsync
| | |
| --- | --- |
| *Default* | `true` |
If `true`, enables vertical synchronization. This eliminates tearing that may appear in moving scenes, at the cost of higher input latency and stuttering at lower framerates. If `false`, vertical synchronization will be disabled, however, many platforms will enforce it regardless (such as mobile platforms and HTML5).
### [bool](class_bool#class-bool) display/window/vsync/vsync\_via\_compositor
| | |
| --- | --- |
| *Default* | `false` |
If `Use Vsync` is enabled and this setting is `true`, enables vertical synchronization via the operating system's window compositor when in windowed mode and the compositor is enabled. This will prevent stutter in certain situations. (Windows only.)
**Note:** This option is experimental and meant to alleviate stutter experienced by some users. However, some users have experienced a Vsync framerate halving (e.g. from 60 FPS to 30 FPS) when using it.
### [String](class_string#class-string) editor/main\_run\_args
| | |
| --- | --- |
| *Default* | `""` |
The command-line arguments to append to Godot's own command line when running the project. This doesn't affect the editor itself.
It is possible to make another executable run Godot by using the `%command%` placeholder. The placeholder will be replaced with Godot's own command line. Program-specific arguments should be placed *before* the placeholder, whereas Godot-specific arguments should be placed *after* the placeholder.
For example, this can be used to force the project to run on the dedicated GPU in a NVIDIA Optimus system on Linux:
```
prime-run %command%
```
### [int](class_int#class-int) editor/scene\_naming
| | |
| --- | --- |
| *Default* | `0` |
Default naming style for scene files to infer from their root nodes. Possible options are:
* `0` (Auto): Uses the scene root name as is without changing its casing.
* `1` (PascalCase): Converts the scene root name to PascalCase casing.
* `2` (snake\_case): Converts the scene root name to snake\_case casing.
### [String](class_string#class-string) editor/script\_templates\_search\_path
| | |
| --- | --- |
| *Default* | `"res://script_templates"` |
Search path for project-specific script templates. Godot will search for script templates both in the editor-specific path and in this project-specific path.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) editor/search\_in\_file\_extensions
| | |
| --- | --- |
| *Default* | `PoolStringArray( "gd", "gdshader", "shader" )` |
Text-based file extensions to include in the script editor's "Find in Files" feature. You can add e.g. `tscn` if you wish to also parse your scene files, especially if you use built-in scripts which are serialized in the scene files.
### [bool](class_bool#class-bool) editor/version\_control\_autoload\_on\_startup
| | |
| --- | --- |
| *Default* | `false` |
Load the previously opened VCS plugin when the editor starts up. This is set to `true` whenever a new VCS plugin is initialized.
### [String](class_string#class-string) editor/version\_control\_plugin\_name
| | |
| --- | --- |
| *Default* | `""` |
Last loaded VCS plugin name. Used to autoload the plugin when the editor starts up.
### [int](class_int#class-int) gui/common/default\_scroll\_deadzone
| | |
| --- | --- |
| *Default* | `0` |
Default value for [ScrollContainer.scroll\_deadzone](class_scrollcontainer#class-scrollcontainer-property-scroll-deadzone), which will be used for all [ScrollContainer](class_scrollcontainer#class-scrollcontainer)s unless overridden.
### [bool](class_bool#class-bool) gui/common/drop\_mouse\_on\_gui\_input\_disabled
| | |
| --- | --- |
| *Default* | `false` |
If enabled, the moment [Viewport.gui\_disable\_input](class_viewport#class-viewport-property-gui-disable-input) is set to `false` to disable GUI input in a viewport, current mouse over and mouse focus will be dropped.
That behavior helps to keep a robust GUI state, with no surprises when input is resumed regardless what has happened in the meantime.
If disabled, the legacy behavior is used, which consists in just not doing anything besides the GUI input disable itself.
**Note:** This is set to `true` by default for new projects and is the recommended setting.
### [bool](class_bool#class-bool) gui/common/swap\_ok\_cancel
If `true`, swaps OK and Cancel buttons in dialogs on Windows and UWP to follow interface conventions.
### [int](class_int#class-int) gui/common/text\_edit\_undo\_stack\_max\_size
| | |
| --- | --- |
| *Default* | `1024` |
### [String](class_string#class-string) gui/theme/custom
| | |
| --- | --- |
| *Default* | `""` |
Path to a custom [Theme](class_theme#class-theme) resource file to use for the project (`theme` or generic `tres`/`res` extension).
### [String](class_string#class-string) gui/theme/custom\_font
| | |
| --- | --- |
| *Default* | `""` |
Path to a custom [Font](class_font#class-font) resource to use as default for all GUI elements of the project.
### [bool](class_bool#class-bool) gui/theme/use\_hidpi
| | |
| --- | --- |
| *Default* | `false` |
If `true`, makes sure the theme used works with HiDPI.
### [int](class_int#class-int) gui/timers/incremental\_search\_max\_interval\_msec
| | |
| --- | --- |
| *Default* | `2000` |
Timer setting for incremental search in [Tree](class_tree#class-tree), [ItemList](class_itemlist#class-itemlist), etc. controls (in milliseconds).
### [float](class_float#class-float) gui/timers/text\_edit\_idle\_detect\_sec
| | |
| --- | --- |
| *Default* | `3` |
Timer for detecting idle in [TextEdit](class_textedit#class-textedit) (in seconds).
### [float](class_float#class-float) gui/timers/tooltip\_delay\_sec
| | |
| --- | --- |
| *Default* | `0.5` |
Default delay for tooltips (in seconds).
### [Dictionary](class_dictionary#class-dictionary) input/ui\_accept
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to confirm a focused button, menu or list item, or validate input.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_cancel
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to discard a modal or pending input.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_down
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to move down in the UI.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_end
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to go to the end position of a [Control](class_control#class-control) (e.g. last item in an [ItemList](class_itemlist#class-itemlist) or a [Tree](class_tree#class-tree)), matching the behavior of [@GlobalScope.KEY\_END](class_%40globalscope#class-globalscope-constant-key-end) on typical desktop UI systems.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_focus\_next
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to focus the next [Control](class_control#class-control) in the scene. The focus behavior can be configured via [Control.focus\_next](class_control#class-control-property-focus-next).
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_focus\_prev
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to focus the previous [Control](class_control#class-control) in the scene. The focus behavior can be configured via [Control.focus\_previous](class_control#class-control-property-focus-previous).
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_home
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to go to the start position of a [Control](class_control#class-control) (e.g. first item in an [ItemList](class_itemlist#class-itemlist) or a [Tree](class_tree#class-tree)), matching the behavior of [@GlobalScope.KEY\_HOME](class_%40globalscope#class-globalscope-constant-key-home) on typical desktop UI systems.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_left
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to move left in the UI.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_page\_down
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to go down a page in a [Control](class_control#class-control) (e.g. in an [ItemList](class_itemlist#class-itemlist) or a [Tree](class_tree#class-tree)), matching the behavior of [@GlobalScope.KEY\_PAGEDOWN](class_%40globalscope#class-globalscope-constant-key-pagedown) on typical desktop UI systems.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_page\_up
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to go up a page in a [Control](class_control#class-control) (e.g. in an [ItemList](class_itemlist#class-itemlist) or a [Tree](class_tree#class-tree)), matching the behavior of [@GlobalScope.KEY\_PAGEUP](class_%40globalscope#class-globalscope-constant-key-pageup) on typical desktop UI systems.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_right
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to move right in the UI.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_select
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to select an item in a [Control](class_control#class-control) (e.g. in an [ItemList](class_itemlist#class-itemlist) or a [Tree](class_tree#class-tree)).
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [Dictionary](class_dictionary#class-dictionary) input/ui\_up
Default [InputEventAction](class_inputeventaction#class-inputeventaction) to move up in the UI.
**Note:** Default `ui_*` actions cannot be removed as they are necessary for the internal logic of several [Control](class_control#class-control)s. The events assigned to the action can however be modified.
### [bool](class_bool#class-bool) input\_devices/buffering/agile\_event\_flushing
| | |
| --- | --- |
| *Default* | `false` |
If `true`, key/touch/joystick events will be flushed just before every idle and physics frame.
If `false`, such events will be flushed only once per idle frame, between iterations of the engine.
Enabling this can greatly improve the responsiveness to input, specially in devices that need to run multiple physics frames per visible (idle) frame, because they can't run at the target frame rate.
**Note:** Currently implemented only in Android.
### [bool](class_bool#class-bool) input\_devices/pointing/emulate\_mouse\_from\_touch
| | |
| --- | --- |
| *Default* | `true` |
If `true`, sends mouse input events when tapping or swiping on the touchscreen.
### [bool](class_bool#class-bool) input\_devices/pointing/emulate\_touch\_from\_mouse
| | |
| --- | --- |
| *Default* | `false` |
If `true`, sends touch input events when clicking or dragging the mouse.
### [float](class_float#class-float) input\_devices/pointing/ios/touch\_delay
| | |
| --- | --- |
| *Default* | `0.15` |
Default delay for touch events. This only affects iOS devices.
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_1
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 1. If left empty, the layer will display as "Layer 1".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_10
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 10. If left empty, the layer will display as "Layer 10".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_11
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 11. If left empty, the layer will display as "Layer 11".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_12
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 12. If left empty, the layer will display as "Layer 12".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_13
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 13. If left empty, the layer will display as "Layer 13".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_14
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 14. If left empty, the layer will display as "Layer 14".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_15
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 15. If left empty, the layer will display as "Layer 15".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_16
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 16. If left empty, the layer will display as "Layer 16".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_17
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 17. If left empty, the layer will display as "Layer 17".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_18
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 18. If left empty, the layer will display as "Layer 18".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_19
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 19. If left empty, the layer will display as "Layer 19".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_2
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 2. If left empty, the layer will display as "Layer 2".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_20
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 20. If left empty, the layer will display as "Layer 20".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_21
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 21. If left empty, the layer will display as "Layer 21".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_22
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 22. If left empty, the layer will display as "Layer 22".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_23
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 23. If left empty, the layer will display as "Layer 23".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_24
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 24. If left empty, the layer will display as "Layer 24".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_25
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 25. If left empty, the layer will display as "Layer 25".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_26
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 26. If left empty, the layer will display as "Layer 26".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_27
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 27. If left empty, the layer will display as "Layer 27".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_28
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 28. If left empty, the layer will display as "Layer 28".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_29
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 29. If left empty, the layer will display as "Layer 29".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_3
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 3. If left empty, the layer will display as "Layer 3".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_30
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 30. If left empty, the layer will display as "Layer 30".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_31
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 31. If left empty, the layer will display as "Layer 31".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_32
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 32. If left empty, the layer will display as "Layer 32".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_4
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 4. If left empty, the layer will display as "Layer 4".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_5
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 5. If left empty, the layer will display as "Layer 5".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_6
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 6. If left empty, the layer will display as "Layer 6".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_7
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 7. If left empty, the layer will display as "Layer 7".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_8
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 8. If left empty, the layer will display as "Layer 8".
### [String](class_string#class-string) layer\_names/2d\_navigation/layer\_9
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D navigation layer 9. If left empty, the layer will display as "Layer 9".
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_1
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 1.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_10
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 10.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_11
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 11.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_12
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 12.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_13
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 13.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_14
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 14.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_15
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 15.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_16
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 16.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_17
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 17.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_18
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 18.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_19
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 19.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_2
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 2.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_20
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 20.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_21
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 21.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_22
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 22.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_23
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 23.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_24
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 24.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_25
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 25.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_26
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 26.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_27
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 27.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_28
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 28.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_29
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 29.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_3
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 3.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_30
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 30.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_31
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 31.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_32
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 32.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_4
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 4.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_5
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 5.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_6
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 6.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_7
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 7.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_8
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 8.
### [String](class_string#class-string) layer\_names/2d\_physics/layer\_9
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D physics layer 9.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_1
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 1.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_10
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 10.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_11
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 11.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_12
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 12.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_13
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 13.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_14
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 14.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_15
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 15.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_16
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 16.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_17
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 17.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_18
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 18.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_19
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 19.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_2
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 2.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_20
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 20.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_3
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 3.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_4
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 4.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_5
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 5.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_6
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 6.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_7
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 7.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_8
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 8.
### [String](class_string#class-string) layer\_names/2d\_render/layer\_9
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 2D render layer 9.
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_1
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 1. If left empty, the layer will display as "Layer 1".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_10
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 10. If left empty, the layer will display as "Layer 10".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_11
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 11. If left empty, the layer will display as "Layer 11".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_12
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 12. If left empty, the layer will display as "Layer 12".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_13
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 13. If left empty, the layer will display as "Layer 13".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_14
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 14. If left empty, the layer will display as "Layer 14".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_15
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 15. If left empty, the layer will display as "Layer 15".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_16
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 16. If left empty, the layer will display as "Layer 16".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_17
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 17. If left empty, the layer will display as "Layer 17".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_18
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 18. If left empty, the layer will display as "Layer 18".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_19
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 19. If left empty, the layer will display as "Layer 19".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_2
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 2. If left empty, the layer will display as "Layer 2".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_20
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 20. If left empty, the layer will display as "Layer 20".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_21
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 21. If left empty, the layer will display as "Layer 21".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_22
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 22. If left empty, the layer will display as "Layer 22".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_23
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 23. If left empty, the layer will display as "Layer 23".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_24
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 24. If left empty, the layer will display as "Layer 24".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_25
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 25. If left empty, the layer will display as "Layer 25".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_26
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 26. If left empty, the layer will display as "Layer 26".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_27
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 27. If left empty, the layer will display as "Layer 27".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_28
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 28. If left empty, the layer will display as "Layer 28".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_29
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 29. If left empty, the layer will display as "Layer 29".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_3
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 3. If left empty, the layer will display as "Layer 3".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_30
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 30. If left empty, the layer will display as "Layer 30".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_31
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 31. If left empty, the layer will display as "Layer 31".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_32
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 32. If left empty, the layer will display as "Layer 32".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_4
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 4. If left empty, the layer will display as "Layer 4".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_5
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 5. If left empty, the layer will display as "Layer 5".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_6
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 6. If left empty, the layer will display as "Layer 6".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_7
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 7. If left empty, the layer will display as "Layer 7".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_8
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 8. If left empty, the layer will display as "Layer 8".
### [String](class_string#class-string) layer\_names/3d\_navigation/layer\_9
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D navigation layer 9. If left empty, the layer will display as "Layer 9".
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_1
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 1.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_10
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 10.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_11
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 11.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_12
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 12.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_13
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 13.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_14
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 14.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_15
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 15.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_16
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 16.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_17
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 17.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_18
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 18.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_19
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 19.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_2
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 2.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_20
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 20.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_21
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 21.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_22
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 22.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_23
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 23.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_24
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 24.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_25
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 25.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_26
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 26.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_27
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 27.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_28
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 28.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_29
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 29.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_3
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 3.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_30
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 30.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_31
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 31.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_32
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 32.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_4
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 4.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_5
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 5.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_6
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 6.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_7
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 7.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_8
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 8.
### [String](class_string#class-string) layer\_names/3d\_physics/layer\_9
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D physics layer 9.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_1
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 1.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_10
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 10.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_11
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 11.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_12
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 12.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_13
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 13.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_14
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 14.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_15
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 15.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_16
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 16.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_17
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 17.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_18
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 18.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_19
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 19.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_2
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 2.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_20
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 20.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_3
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 3.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_4
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 4.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_5
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 5.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_6
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 6.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_7
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 7.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_8
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 8.
### [String](class_string#class-string) layer\_names/3d\_render/layer\_9
| | |
| --- | --- |
| *Default* | `""` |
Optional name for the 3D render layer 9.
### [String](class_string#class-string) locale/fallback
| | |
| --- | --- |
| *Default* | `"en"` |
The locale to fall back to if a translation isn't available in a given language. If left empty, `en` (English) will be used.
### [String](class_string#class-string) locale/test
| | |
| --- | --- |
| *Default* | `""` |
If non-empty, this locale will be used when running the project from the editor.
### [bool](class_bool#class-bool) logging/file\_logging/enable\_file\_logging
| | |
| --- | --- |
| *Default* | `false` |
If `true`, logs all output to files.
### [bool](class_bool#class-bool) logging/file\_logging/enable\_file\_logging.pc
| | |
| --- | --- |
| *Default* | `true` |
Desktop override for [logging/file\_logging/enable\_file\_logging](#class-projectsettings-property-logging-file-logging-enable-file-logging), as log files are not readily accessible on mobile/Web platforms.
### [String](class_string#class-string) logging/file\_logging/log\_path
| | |
| --- | --- |
| *Default* | `"user://logs/godot.log"` |
Path to logs within the project. Using an `user://` path is recommended.
### [int](class_int#class-int) logging/file\_logging/max\_log\_files
| | |
| --- | --- |
| *Default* | `5` |
Specifies the maximum amount of log files allowed (used for rotation).
### [int](class_int#class-int) memory/limits/command\_queue/multithreading\_queue\_size\_kb
| | |
| --- | --- |
| *Default* | `256` |
### [int](class_int#class-int) memory/limits/message\_queue/max\_size\_kb
| | |
| --- | --- |
| *Default* | `4096` |
Godot uses a message queue to defer some function calls. If you run out of space on it (you will see an error), you can increase the size here.
### [int](class_int#class-int) memory/limits/multithreaded\_server/rid\_pool\_prealloc
| | |
| --- | --- |
| *Default* | `60` |
This is used by servers when used in multi-threading mode (servers and visual). RIDs are preallocated to avoid stalling the server requesting them on threads. If servers get stalled too often when loading resources in a thread, increase this number.
### [int](class_int#class-int) mono/debugger\_agent/port
| | |
| --- | --- |
| *Default* | `23685` |
### [bool](class_bool#class-bool) mono/debugger\_agent/wait\_for\_debugger
| | |
| --- | --- |
| *Default* | `false` |
### [int](class_int#class-int) mono/debugger\_agent/wait\_timeout
| | |
| --- | --- |
| *Default* | `3000` |
### [String](class_string#class-string) mono/profiler/args
| | |
| --- | --- |
| *Default* | `"log:calls,alloc,sample,output=output.mlpd"` |
### [bool](class_bool#class-bool) mono/profiler/enabled
| | |
| --- | --- |
| *Default* | `false` |
### [int](class_int#class-int) mono/runtime/unhandled\_exception\_policy
| | |
| --- | --- |
| *Default* | `0` |
The policy to use for unhandled Mono (C#) exceptions. The default "Terminate Application" exits the project as soon as an unhandled exception is thrown. "Log Error" logs an error message to the console instead, and will not interrupt the project execution when an unhandled exception is thrown.
**Note:** The unhandled exception policy is always set to "Log Error" in the editor, which also includes C# `tool` scripts running within the editor as well as editor plugin code.
### [float](class_float#class-float) navigation/2d/default\_cell\_height
| | |
| --- | --- |
| *Default* | `1.0` |
Default cell height for 2D navigation maps. See [Navigation2DServer.map\_set\_cell\_height](class_navigation2dserver#class-navigation2dserver-method-map-set-cell-height).
**Note:** Currently not implemented.
### [float](class_float#class-float) navigation/2d/default\_cell\_size
| | |
| --- | --- |
| *Default* | `1.0` |
Default cell size for 2D navigation maps. See [Navigation2DServer.map\_set\_cell\_size](class_navigation2dserver#class-navigation2dserver-method-map-set-cell-size).
### [float](class_float#class-float) navigation/2d/default\_edge\_connection\_margin
| | |
| --- | --- |
| *Default* | `1.0` |
Default edge connection margin for 2D navigation maps. See [Navigation2DServer.map\_set\_edge\_connection\_margin](class_navigation2dserver#class-navigation2dserver-method-map-set-edge-connection-margin).
### [float](class_float#class-float) navigation/3d/default\_cell\_height
| | |
| --- | --- |
| *Default* | `0.25` |
Default cell height for 3D navigation maps. See [NavigationServer.map\_set\_cell\_height](class_navigationserver#class-navigationserver-method-map-set-cell-height).
### [float](class_float#class-float) navigation/3d/default\_cell\_size
| | |
| --- | --- |
| *Default* | `0.25` |
Default cell size for 3D navigation maps. See [NavigationServer.map\_set\_cell\_size](class_navigationserver#class-navigationserver-method-map-set-cell-size).
### [float](class_float#class-float) navigation/3d/default\_edge\_connection\_margin
| | |
| --- | --- |
| *Default* | `0.25` |
Default edge connection margin for 3D navigation maps. See [NavigationServer.map\_set\_edge\_connection\_margin](class_navigationserver#class-navigationserver-method-map-set-edge-connection-margin).
### [Vector3](class_vector3#class-vector3) navigation/3d/default\_map\_up
| | |
| --- | --- |
| *Default* | `Vector3( 0, 1, 0 )` |
Default map up vector for 3D navigation maps. See [NavigationServer.map\_set\_up](class_navigationserver#class-navigationserver-method-map-set-up).
### [int](class_int#class-int) network/limits/debugger\_stdout/max\_chars\_per\_second
| | |
| --- | --- |
| *Default* | `2048` |
Maximum amount of characters allowed to send as output from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
### [int](class_int#class-int) network/limits/debugger\_stdout/max\_errors\_per\_second
| | |
| --- | --- |
| *Default* | `100` |
Maximum number of errors allowed to be sent as output from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
### [int](class_int#class-int) network/limits/debugger\_stdout/max\_messages\_per\_frame
| | |
| --- | --- |
| *Default* | `10` |
Maximum amount of messages allowed to send as output from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
### [int](class_int#class-int) network/limits/debugger\_stdout/max\_warnings\_per\_second
| | |
| --- | --- |
| *Default* | `100` |
Maximum number of warnings allowed to be sent as output from the debugger. Over this value, content is dropped. This helps not to stall the debugger connection.
### [int](class_int#class-int) network/limits/packet\_peer\_stream/max\_buffer\_po2
| | |
| --- | --- |
| *Default* | `16` |
Default size of packet peer stream for deserializing Godot data (in bytes, specified as a power of two). The default value `16` is equal to 65,536 bytes. Over this size, data is dropped.
### [int](class_int#class-int) network/limits/tcp/connect\_timeout\_seconds
| | |
| --- | --- |
| *Default* | `30` |
Timeout (in seconds) for connection attempts using TCP.
### [int](class_int#class-int) network/limits/webrtc/max\_channel\_in\_buffer\_kb
| | |
| --- | --- |
| *Default* | `64` |
Maximum size (in kiB) for the [WebRTCDataChannel](class_webrtcdatachannel#class-webrtcdatachannel) input buffer.
### [int](class_int#class-int) network/limits/websocket\_client/max\_in\_buffer\_kb
| | |
| --- | --- |
| *Default* | `64` |
Maximum size (in kiB) for the [WebSocketClient](class_websocketclient#class-websocketclient) input buffer.
### [int](class_int#class-int) network/limits/websocket\_client/max\_in\_packets
| | |
| --- | --- |
| *Default* | `1024` |
Maximum number of concurrent input packets for [WebSocketClient](class_websocketclient#class-websocketclient).
### [int](class_int#class-int) network/limits/websocket\_client/max\_out\_buffer\_kb
| | |
| --- | --- |
| *Default* | `64` |
Maximum size (in kiB) for the [WebSocketClient](class_websocketclient#class-websocketclient) output buffer.
### [int](class_int#class-int) network/limits/websocket\_client/max\_out\_packets
| | |
| --- | --- |
| *Default* | `1024` |
Maximum number of concurrent output packets for [WebSocketClient](class_websocketclient#class-websocketclient).
### [int](class_int#class-int) network/limits/websocket\_server/max\_in\_buffer\_kb
| | |
| --- | --- |
| *Default* | `64` |
Maximum size (in kiB) for the [WebSocketServer](class_websocketserver#class-websocketserver) input buffer.
### [int](class_int#class-int) network/limits/websocket\_server/max\_in\_packets
| | |
| --- | --- |
| *Default* | `1024` |
Maximum number of concurrent input packets for [WebSocketServer](class_websocketserver#class-websocketserver).
### [int](class_int#class-int) network/limits/websocket\_server/max\_out\_buffer\_kb
| | |
| --- | --- |
| *Default* | `64` |
Maximum size (in kiB) for the [WebSocketServer](class_websocketserver#class-websocketserver) output buffer.
### [int](class_int#class-int) network/limits/websocket\_server/max\_out\_packets
| | |
| --- | --- |
| *Default* | `1024` |
Maximum number of concurrent output packets for [WebSocketServer](class_websocketserver#class-websocketserver).
### [int](class_int#class-int) network/remote\_fs/page\_read\_ahead
| | |
| --- | --- |
| *Default* | `4` |
Amount of read ahead used by remote filesystem. Higher values decrease the effects of latency at the cost of higher bandwidth usage.
### [int](class_int#class-int) network/remote\_fs/page\_size
| | |
| --- | --- |
| *Default* | `65536` |
Page size used by remote filesystem (in bytes).
### [String](class_string#class-string) network/ssl/certificates
| | |
| --- | --- |
| *Default* | `""` |
The CA certificates bundle to use for SSL connections. If this is set to a non-empty value, this will *override* Godot's default [Mozilla certificate bundle](https://github.com/godotengine/godot/blob/master/thirdparty/certs/ca-certificates.crt). If left empty, the default certificate bundle will be used.
If in doubt, leave this setting empty.
### [int](class_int#class-int) node/name\_casing
| | |
| --- | --- |
| *Default* | `0` |
When creating node names automatically, set the type of casing in this project. This is mostly an editor setting.
### [int](class_int#class-int) node/name\_num\_separator
| | |
| --- | --- |
| *Default* | `0` |
What to use to separate node name from number. This is mostly an editor setting.
### [int](class_int#class-int) physics/2d/bp\_hash\_table\_size
| | |
| --- | --- |
| *Default* | `4096` |
Size of the hash table used for the broad-phase 2D hash grid algorithm.
**Note:** Not used if [physics/2d/use\_bvh](#class-projectsettings-property-physics-2d-use-bvh) is enabled.
### [float](class_float#class-float) physics/2d/bvh\_collision\_margin
| | |
| --- | --- |
| *Default* | `1.0` |
Additional expansion applied to object bounds in the 2D physics bounding volume hierarchy. This can reduce BVH processing at the cost of a slightly coarser broadphase, which can stress the physics more in some situations.
The default value will work well in most situations. A value of 0.0 will turn this optimization off, and larger values may work better for larger, faster moving objects.
**Note:** Used only if [physics/2d/use\_bvh](#class-projectsettings-property-physics-2d-use-bvh) is enabled.
### [int](class_int#class-int) physics/2d/cell\_size
| | |
| --- | --- |
| *Default* | `128` |
Cell size used for the broad-phase 2D hash grid algorithm (in pixels).
**Note:** Not used if [physics/2d/use\_bvh](#class-projectsettings-property-physics-2d-use-bvh) is enabled.
### [float](class_float#class-float) physics/2d/default\_angular\_damp
| | |
| --- | --- |
| *Default* | `1.0` |
The default angular damp in 2D.
**Note:** Good values are in the range `0` to `1`. At value `0` objects will keep moving with the same velocity. Values greater than `1` will aim to reduce the velocity to `0` in less than a second e.g. a value of `2` will aim to reduce the velocity to `0` in half a second. A value equal to or greater than the physics frame rate ([physics/common/physics\_fps](#class-projectsettings-property-physics-common-physics-fps), `60` by default) will bring the object to a stop in one iteration.
### [int](class_int#class-int) physics/2d/default\_gravity
| | |
| --- | --- |
| *Default* | `98` |
The default gravity strength in 2D (in pixels per second squared).
**Note:** This property is only read when the project starts. To change the default gravity at runtime, use the following code sample:
```
# Set the default gravity strength to 98.
Physics2DServer.area_set_param(get_viewport().find_world_2d().get_space(), Physics2DServer.AREA_PARAM_GRAVITY, 98)
```
### [Vector2](class_vector2#class-vector2) physics/2d/default\_gravity\_vector
| | |
| --- | --- |
| *Default* | `Vector2( 0, 1 )` |
The default gravity direction in 2D.
**Note:** This property is only read when the project starts. To change the default gravity vector at runtime, use the following code sample:
```
# Set the default gravity direction to `Vector2(0, 1)`.
Physics2DServer.area_set_param(get_viewport().find_world_2d().get_space(), Physics2DServer.AREA_PARAM_GRAVITY_VECTOR, Vector2(0, 1))
```
### [float](class_float#class-float) physics/2d/default\_linear\_damp
| | |
| --- | --- |
| *Default* | `0.1` |
The default linear damp in 2D.
**Note:** Good values are in the range `0` to `1`. At value `0` objects will keep moving with the same velocity. Values greater than `1` will aim to reduce the velocity to `0` in less than a second e.g. a value of `2` will aim to reduce the velocity to `0` in half a second. A value equal to or greater than the physics frame rate ([physics/common/physics\_fps](#class-projectsettings-property-physics-common-physics-fps), `60` by default) will bring the object to a stop in one iteration.
### [int](class_int#class-int) physics/2d/large\_object\_surface\_threshold\_in\_cells
| | |
| --- | --- |
| *Default* | `512` |
Threshold defining the surface size that constitutes a large object with regard to cells in the broad-phase 2D hash grid algorithm.
**Note:** Not used if [physics/2d/use\_bvh](#class-projectsettings-property-physics-2d-use-bvh) is enabled.
### [String](class_string#class-string) physics/2d/physics\_engine
| | |
| --- | --- |
| *Default* | `"DEFAULT"` |
Sets which physics engine to use for 2D physics.
"DEFAULT" and "GodotPhysics" are the same, as there is currently no alternative 2D physics server implemented.
### [float](class_float#class-float) physics/2d/sleep\_threshold\_angular
| | |
| --- | --- |
| *Default* | `0.139626` |
Threshold angular velocity under which a 2D physics body will be considered inactive. See [Physics2DServer.SPACE\_PARAM\_BODY\_ANGULAR\_VELOCITY\_SLEEP\_THRESHOLD](class_physics2dserver#class-physics2dserver-constant-space-param-body-angular-velocity-sleep-threshold).
### [float](class_float#class-float) physics/2d/sleep\_threshold\_linear
| | |
| --- | --- |
| *Default* | `2.0` |
Threshold linear velocity under which a 2D physics body will be considered inactive. See [Physics2DServer.SPACE\_PARAM\_BODY\_LINEAR\_VELOCITY\_SLEEP\_THRESHOLD](class_physics2dserver#class-physics2dserver-constant-space-param-body-linear-velocity-sleep-threshold).
### [int](class_int#class-int) physics/2d/thread\_model
| | |
| --- | --- |
| *Default* | `1` |
Sets whether physics is run on the main thread or a separate one. Running the server on a thread increases performance, but restricts API access to only physics process.
**Warning:** As of Godot 3.2, there are mixed reports about the use of a Multi-Threaded thread model for physics. Be sure to assess whether it does give you extra performance and no regressions when using it.
### [float](class_float#class-float) physics/2d/time\_before\_sleep
| | |
| --- | --- |
| *Default* | `0.5` |
Time (in seconds) of inactivity before which a 2D physics body will put to sleep. See [Physics2DServer.SPACE\_PARAM\_BODY\_TIME\_TO\_SLEEP](class_physics2dserver#class-physics2dserver-constant-space-param-body-time-to-sleep).
### [bool](class_bool#class-bool) physics/2d/use\_bvh
| | |
| --- | --- |
| *Default* | `true` |
Enables the use of bounding volume hierarchy instead of hash grid for 2D physics spatial partitioning. This may give better performance.
### [bool](class_bool#class-bool) physics/3d/active\_soft\_world
| | |
| --- | --- |
| *Default* | `true` |
Sets whether the 3D physics world will be created with support for [SoftBody](class_softbody#class-softbody) physics. Only applies to the Bullet physics engine.
### [float](class_float#class-float) physics/3d/default\_angular\_damp
| | |
| --- | --- |
| *Default* | `0.1` |
The default angular damp in 3D.
**Note:** Good values are in the range `0` to `1`. At value `0` objects will keep moving with the same velocity. Values greater than `1` will aim to reduce the velocity to `0` in less than a second e.g. a value of `2` will aim to reduce the velocity to `0` in half a second. A value equal to or greater than the physics frame rate ([physics/common/physics\_fps](#class-projectsettings-property-physics-common-physics-fps), `60` by default) will bring the object to a stop in one iteration.
### [float](class_float#class-float) physics/3d/default\_gravity
| | |
| --- | --- |
| *Default* | `9.8` |
The default gravity strength in 3D (in meters per second squared).
**Note:** This property is only read when the project starts. To change the default gravity at runtime, use the following code sample:
```
# Set the default gravity strength to 9.8.
PhysicsServer.area_set_param(get_viewport().find_world().get_space(), PhysicsServer.AREA_PARAM_GRAVITY, 9.8)
```
### [Vector3](class_vector3#class-vector3) physics/3d/default\_gravity\_vector
| | |
| --- | --- |
| *Default* | `Vector3( 0, -1, 0 )` |
The default gravity direction in 3D.
**Note:** This property is only read when the project starts. To change the default gravity vector at runtime, use the following code sample:
```
# Set the default gravity direction to `Vector3(0, -1, 0)`.
PhysicsServer.area_set_param(get_viewport().find_world().get_space(), PhysicsServer.AREA_PARAM_GRAVITY_VECTOR, Vector3(0, -1, 0))
```
### [float](class_float#class-float) physics/3d/default\_linear\_damp
| | |
| --- | --- |
| *Default* | `0.1` |
The default linear damp in 3D.
**Note:** Good values are in the range `0` to `1`. At value `0` objects will keep moving with the same velocity. Values greater than `1` will aim to reduce the velocity to `0` in less than a second e.g. a value of `2` will aim to reduce the velocity to `0` in half a second. A value equal to or greater than the physics frame rate ([physics/common/physics\_fps](#class-projectsettings-property-physics-common-physics-fps), `60` by default) will bring the object to a stop in one iteration.
### [float](class_float#class-float) physics/3d/godot\_physics/bvh\_collision\_margin
| | |
| --- | --- |
| *Default* | `0.1` |
Additional expansion applied to object bounds in the 3D physics bounding volume hierarchy. This can reduce BVH processing at the cost of a slightly coarser broadphase, which can stress the physics more in some situations.
The default value will work well in most situations. A value of 0.0 will turn this optimization off, and larger values may work better for larger, faster moving objects.
**Note:** Used only if [physics/3d/godot\_physics/use\_bvh](#class-projectsettings-property-physics-3d-godot-physics-use-bvh) is enabled.
### [bool](class_bool#class-bool) physics/3d/godot\_physics/use\_bvh
| | |
| --- | --- |
| *Default* | `true` |
Enables the use of bounding volume hierarchy instead of octree for 3D physics spatial partitioning. This may give better performance.
### [String](class_string#class-string) physics/3d/physics\_engine
| | |
| --- | --- |
| *Default* | `"DEFAULT"` |
Sets which physics engine to use for 3D physics.
"DEFAULT" is currently the [Bullet](https://bulletphysics.org) physics engine. The "GodotPhysics" engine is still supported as an alternative.
### [bool](class_bool#class-bool) physics/3d/smooth\_trimesh\_collision
| | |
| --- | --- |
| *Default* | `false` |
If `true`, smooths out collision with trimesh shapes ([ConcavePolygonShape](class_concavepolygonshape#class-concavepolygonshape)) by telling the Bullet physics engine to generate internal edge information for every trimesh shape created.
**Note:** Only effective if [physics/3d/physics\_engine](#class-projectsettings-property-physics-3d-physics-engine) is set to `DEFAULT` or `Bullet`, *not* `GodotPhysics`.
### [bool](class_bool#class-bool) physics/common/enable\_object\_picking
| | |
| --- | --- |
| *Default* | `true` |
Enables [Viewport.physics\_object\_picking](class_viewport#class-viewport-property-physics-object-picking) on the root viewport.
### [bool](class_bool#class-bool) physics/common/enable\_pause\_aware\_picking
| | |
| --- | --- |
| *Default* | `false` |
If enabled, 2D and 3D physics picking behaves this way in relation to pause:
* When pause is started, every collision object that is hovered or captured (3D only) is released from that condition, getting the relevant mouse-exit callback, unless its pause mode makes it immune to pause.
* During pause, picking only considers collision objects immune to pause, sending input events and enter/exit callbacks to them as expected.
If disabled, the legacy behavior is used, which consists in queuing the picking input events during pause (so nodes won't get them) and flushing that queue on resume, against the state of the 2D/3D world at that point.
### [int](class_int#class-int) physics/common/physics\_fps
| | |
| --- | --- |
| *Default* | `60` |
The number of fixed iterations per second. This controls how often physics simulation and [Node.\_physics\_process](class_node#class-node-method-physics-process) methods are run. See also [debug/settings/fps/force\_fps](#class-projectsettings-property-debug-settings-fps-force-fps).
**Note:** This property is only read when the project starts. To change the physics FPS at runtime, set [Engine.iterations\_per\_second](class_engine#class-engine-property-iterations-per-second) instead.
**Note:** Only 8 physics ticks may be simulated per rendered frame at most. If more than 8 physics ticks have to be simulated per rendered frame to keep up with rendering, the game will appear to slow down (even if `delta` is used consistently in physics calculations). Therefore, it is recommended not to increase [physics/common/physics\_fps](#class-projectsettings-property-physics-common-physics-fps) above 240. Otherwise, the game will slow down when the rendering framerate goes below 30 FPS.
### [bool](class_bool#class-bool) physics/common/physics\_interpolation
| | |
| --- | --- |
| *Default* | `false` |
If `true`, the renderer will interpolate the transforms of physics objects between the last two transforms, such that smooth motion is seen when physics ticks do not coincide with rendered frames.
**Note:** When moving objects to new positions (rather than the usual physics motion) you may want to temporarily turn off interpolation to prevent a visible glitch. You can do this using the [Node.reset\_physics\_interpolation](class_node#class-node-method-reset-physics-interpolation) function.
### [float](class_float#class-float) physics/common/physics\_jitter\_fix
| | |
| --- | --- |
| *Default* | `0.5` |
Controls how much physics ticks are synchronized with real time. For 0 or less, the ticks are synchronized. Such values are recommended for network games, where clock synchronization matters. Higher values cause higher deviation of in-game clock and real clock, but allows smoothing out framerate jitters. The default value of 0.5 should be fine for most; values above 2 could cause the game to react to dropped frames with a noticeable delay and are not recommended.
**Note:** For best results, when using a custom physics interpolation solution, the physics jitter fix should be disabled by setting [physics/common/physics\_jitter\_fix](#class-projectsettings-property-physics-common-physics-jitter-fix) to `0`.
**Note:** Jitter fix is automatically disabled at runtime when [physics/common/physics\_interpolation](#class-projectsettings-property-physics-common-physics-interpolation) is enabled.
**Note:** This property is only read when the project starts. To change the value at runtime, set [Engine.physics\_jitter\_fix](class_engine#class-engine-property-physics-jitter-fix) instead.
### [int](class_int#class-int) rendering/2d/opengl/batching\_send\_null
| | |
| --- | --- |
| *Default* | `0` |
**Experimental.** Calls `glBufferData` with NULL data prior to uploading batching data. This may not be necessary but can be used for safety.
**Note:** Use with care. You are advised to leave this as default for exports. A non-default setting that works better on your machine may adversely affect performance for end users.
### [int](class_int#class-int) rendering/2d/opengl/batching\_stream
| | |
| --- | --- |
| *Default* | `0` |
**Experimental.** If set to on, uses the `GL_STREAM_DRAW` flag for batching buffer uploads. If off, uses the `GL_DYNAMIC_DRAW` flag.
**Note:** Use with care. You are advised to leave this as default for exports. A non-default setting that works better on your machine may adversely affect performance for end users.
### [int](class_int#class-int) rendering/2d/opengl/legacy\_orphan\_buffers
| | |
| --- | --- |
| *Default* | `0` |
**Experimental.** If set to on, this applies buffer orphaning - `glBufferData` is called with NULL data and the full buffer size prior to uploading new data. This can be important to avoid stalling on some hardware.
**Note:** Use with care. You are advised to leave this as default for exports. A non-default setting that works better on your machine may adversely affect performance for end users.
### [int](class_int#class-int) rendering/2d/opengl/legacy\_stream
| | |
| --- | --- |
| *Default* | `0` |
**Experimental.** If set to on, uses the `GL_STREAM_DRAW` flag for legacy buffer uploads. If off, uses the `GL_DYNAMIC_DRAW` flag.
**Note:** Use with care. You are advised to leave this as default for exports. A non-default setting that works better on your machine may adversely affect performance for end users.
### [int](class_int#class-int) rendering/2d/options/ninepatch\_mode
| | |
| --- | --- |
| *Default* | `1` |
Choose between fixed mode where corner scalings are preserved matching the artwork, and scaling mode.
Not available in GLES3 when [rendering/batching/options/use\_batching](#class-projectsettings-property-rendering-batching-options-use-batching) is off.
### [bool](class_bool#class-bool) rendering/2d/options/use\_nvidia\_rect\_flicker\_workaround
| | |
| --- | --- |
| *Default* | `false` |
Some NVIDIA GPU drivers have a bug which produces flickering issues for the `draw_rect` method, especially as used in [TileMap](class_tilemap#class-tilemap). Refer to [GitHub issue 9913](https://github.com/godotengine/godot/issues/9913) for details.
If `true`, this option enables a "safe" code path for such NVIDIA GPUs at the cost of performance. This option affects GLES2 and GLES3 rendering, but only on desktop platforms.
### [bool](class_bool#class-bool) rendering/2d/options/use\_software\_skinning
| | |
| --- | --- |
| *Default* | `true` |
If `true`, performs 2D skinning on the CPU rather than the GPU. This provides greater compatibility with a wide range of hardware, and also may be faster in some circumstances.
Currently only available when [rendering/batching/options/use\_batching](#class-projectsettings-property-rendering-batching-options-use-batching) is active.
**Note:** Antialiased software skinned polys are not supported, and will be rendered without antialiasing.
**Note:** Custom shaders that use the `VERTEX` built-in operate with `VERTEX` position *after* skinning, whereas with hardware skinning, `VERTEX` is the position *before* skinning.
### [bool](class_bool#class-bool) rendering/2d/snapping/use\_gpu\_pixel\_snap
| | |
| --- | --- |
| *Default* | `false` |
If `true`, forces snapping of vertices to pixels in 2D rendering. May help in some pixel art styles.
This snapping is performed on the GPU in the vertex shader.
Consider using the project setting [rendering/batching/precision/uv\_contract](#class-projectsettings-property-rendering-batching-precision-uv-contract) to prevent artifacts.
### [bool](class_bool#class-bool) rendering/batching/debug/diagnose\_frame
| | |
| --- | --- |
| *Default* | `false` |
When batching is on, this regularly prints a frame diagnosis log. Note that this will degrade performance.
### [bool](class_bool#class-bool) rendering/batching/debug/flash\_batching
| | |
| --- | --- |
| *Default* | `false` |
**Experimental.** For regression testing against the old renderer. If this is switched on, and `use_batching` is set, the renderer will swap alternately between using the old renderer, and the batched renderer, on each frame. This makes it easy to identify visual differences. Performance will be degraded.
### [int](class_int#class-int) rendering/batching/lights/max\_join\_items
| | |
| --- | --- |
| *Default* | `32` |
Lights have the potential to prevent joining items, and break many of the performance benefits of batching. This setting enables some complex logic to allow joining items if their lighting is similar, and overlap tests pass. This can significantly improve performance in some games. Set to 0 to switch off. With large values the cost of overlap tests may lead to diminishing returns.
### [float](class_float#class-float) rendering/batching/lights/scissor\_area\_threshold
| | |
| --- | --- |
| *Default* | `1.0` |
Sets the proportion of the total screen area (in pixels) that must be saved by a scissor operation in order to activate light scissoring. This can prevent parts of items being rendered outside the light area. Lower values scissor more aggressively. A value of 1 scissors none of the items, a value of 0 scissors every item. The power of 4 of the value is used, in order to emphasize the lower range, and multiplied by the total screen area in pixels to give the threshold. This can reduce fill rate requirements in scenes with a lot of lighting.
### [bool](class_bool#class-bool) rendering/batching/options/single\_rect\_fallback
| | |
| --- | --- |
| *Default* | `false` |
Enabling this setting uses the legacy method to draw batches containing only one rect. The legacy method is faster (approx twice as fast), but can cause flicker on some systems. In order to directly compare performance with the non-batching renderer you can set this to true, but it is recommended to turn this off unless you can guarantee your target hardware will work with this method.
### [bool](class_bool#class-bool) rendering/batching/options/use\_batching
| | |
| --- | --- |
| *Default* | `true` |
Turns 2D batching on and off. Batching increases performance by reducing the amount of graphics API drawcalls.
### [bool](class_bool#class-bool) rendering/batching/options/use\_batching\_in\_editor
| | |
| --- | --- |
| *Default* | `true` |
Switches on 2D batching within the editor.
### [int](class_int#class-int) rendering/batching/parameters/batch\_buffer\_size
| | |
| --- | --- |
| *Default* | `16384` |
Size of buffer reserved for batched vertices. Larger size enables larger batches, but there are diminishing returns for the memory used. This should only have a minor effect on performance.
### [float](class_float#class-float) rendering/batching/parameters/colored\_vertex\_format\_threshold
| | |
| --- | --- |
| *Default* | `0.25` |
Including color in the vertex format has a cost, however, not including color prevents batching across color changes. This threshold determines the ratio of `number of vertex color changes / total number of vertices` above which vertices will be translated to colored format. A value of 0 will always use colored vertices, 1 will never use colored vertices.
### [int](class_int#class-int) rendering/batching/parameters/item\_reordering\_lookahead
| | |
| --- | --- |
| *Default* | `4` |
In certain circumstances, the batcher can reorder items in order to better join them. This may result in better performance. An overlap test is needed however for each item lookahead, so there is a trade off, with diminishing returns. If you are getting no benefit, setting this to 0 will switch it off.
### [int](class_int#class-int) rendering/batching/parameters/max\_join\_item\_commands
| | |
| --- | --- |
| *Default* | `16` |
Sets the number of commands to lookahead to determine whether to batch render items. A value of 1 can join items consisting of single commands, 0 turns off joining. Higher values are in theory more likely to join, however this has diminishing returns and has a runtime cost so a small value is recommended.
### [bool](class_bool#class-bool) rendering/batching/precision/uv\_contract
| | |
| --- | --- |
| *Default* | `false` |
On some platforms (especially mobile), precision issues in shaders can lead to reading 1 texel outside of bounds, particularly where rects are scaled. This can particularly lead to border artifacts around tiles in tilemaps.
This adjustment corrects for this by making a small contraction to the UV coordinates used. Note that this can result in a slight squashing of border texels.
### [int](class_int#class-int) rendering/batching/precision/uv\_contract\_amount
| | |
| --- | --- |
| *Default* | `100` |
The amount of UV contraction. This figure is divided by 1000000, and is a proportion of the total texture dimensions, where the width and height are both ranged from 0.0 to 1.0.
Use the default unless correcting for a problem on particular hardware.
### [int](class_int#class-int) rendering/cpu\_lightmapper/quality/high\_quality\_ray\_count
| | |
| --- | --- |
| *Default* | `512` |
Amount of light samples taken when using [BakedLightmap.BAKE\_QUALITY\_HIGH](class_bakedlightmap#class-bakedlightmap-constant-bake-quality-high).
### [int](class_int#class-int) rendering/cpu\_lightmapper/quality/low\_quality\_ray\_count
| | |
| --- | --- |
| *Default* | `64` |
Amount of light samples taken when using [BakedLightmap.BAKE\_QUALITY\_LOW](class_bakedlightmap#class-bakedlightmap-constant-bake-quality-low).
### [int](class_int#class-int) rendering/cpu\_lightmapper/quality/medium\_quality\_ray\_count
| | |
| --- | --- |
| *Default* | `256` |
Amount of light samples taken when using [BakedLightmap.BAKE\_QUALITY\_MEDIUM](class_bakedlightmap#class-bakedlightmap-constant-bake-quality-medium).
### [int](class_int#class-int) rendering/cpu\_lightmapper/quality/ultra\_quality\_ray\_count
| | |
| --- | --- |
| *Default* | `1024` |
Amount of light samples taken when using [BakedLightmap.BAKE\_QUALITY\_ULTRA](class_bakedlightmap#class-bakedlightmap-constant-bake-quality-ultra).
### [Color](class_color#class-color) rendering/environment/default\_clear\_color
| | |
| --- | --- |
| *Default* | `Color( 0.3, 0.3, 0.3, 1 )` |
Default background clear color. Overridable per [Viewport](class_viewport#class-viewport) using its [Environment](class_environment#class-environment). See [Environment.background\_mode](class_environment#class-environment-property-background-mode) and [Environment.background\_color](class_environment#class-environment-property-background-color) in particular. To change this default color programmatically, use [VisualServer.set\_default\_clear\_color](class_visualserver#class-visualserver-method-set-default-clear-color).
### [String](class_string#class-string) rendering/environment/default\_environment
| | |
| --- | --- |
| *Default* | `""` |
[Environment](class_environment#class-environment) that will be used as a fallback environment in case a scene does not specify its own environment. The default environment is loaded in at scene load time regardless of whether you have set an environment or not. If you do not rely on the fallback environment, it is best to delete `default_env.tres`, or to specify a different default environment here.
### [bool](class_bool#class-bool) rendering/gles2/compatibility/disable\_half\_float
| | |
| --- | --- |
| *Default* | `false` |
The use of half-float vertex compression may be producing rendering errors on some platforms (especially iOS). These have been seen particularly in particles. Disabling half-float may resolve these problems.
### [bool](class_bool#class-bool) rendering/gles2/compatibility/disable\_half\_float.iOS
| | |
| --- | --- |
| *Default* | `true` |
iOS specific override for [rendering/gles2/compatibility/disable\_half\_float](#class-projectsettings-property-rendering-gles2-compatibility-disable-half-float), due to poor support for half-float vertex compression on many devices.
### [bool](class_bool#class-bool) rendering/gles2/compatibility/enable\_high\_float.Android
| | |
| --- | --- |
| *Default* | `false` |
If `true` and available on the target Android device, enables high floating point precision for all shader computations in GLES2.
**Warning:** High floating point precision can be extremely slow on older devices and is often not available at all. Use with caution.
### [bool](class_bool#class-bool) rendering/gles3/shaders/log\_active\_async\_compiles\_count
| | |
| --- | --- |
| *Default* | `false` |
If `true`, every time an asynchronous shader compilation or an asynchronous shader reconstruction from cache starts or finishes, a line will be logged telling how many of those are happening.
If the platform doesn't support parallel shader compile, but only the compile queue via a secondary GL context, what the message will tell is the number of shader compiles currently queued.
**Note:** This setting is only meaningful if `rendering/gles3/shaders/shader_compilation_mode` is **not** `Synchronous`.
### [int](class_int#class-int) rendering/gles3/shaders/max\_simultaneous\_compiles
| | |
| --- | --- |
| *Default* | `2` |
This is the maximum number of shaders that can be compiled (or reconstructed from cache) at the same time.
At runtime, while that count is reached, other shaders that can be asynchronously compiled will just use their fallback, without their setup being started until the count gets lower.
This is a way to balance the CPU work between running the game and compiling the shaders. The goal is to have as many asynchronous compiles in flight as possible without impacting the responsiveness of the game, which beyond some point would destroy the benefits of asynchronous compilation. In other words, you may be able to afford that the FPS lowers a bit, and that will already be better than the stalling that synchronous compilation could cause.
The default value is a conservative one, so you are advised to tweak it according to the hardware you are targeting.
**Note:** This setting is only meaningful if [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode) is **not** `Synchronous`.
### [int](class_int#class-int) rendering/gles3/shaders/max\_simultaneous\_compiles.mobile
| | |
| --- | --- |
| *Default* | `1` |
The default is a very conservative override for [rendering/gles3/shaders/max\_simultaneous\_compiles](#class-projectsettings-property-rendering-gles3-shaders-max-simultaneous-compiles).
Depending on the specific devices you are targeting, you may want to raise it.
**Note:** This setting is only meaningful if [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode) is **not** `Synchronous`.
### [int](class_int#class-int) rendering/gles3/shaders/max\_simultaneous\_compiles.web
| | |
| --- | --- |
| *Default* | `1` |
The default is a very conservative override for [rendering/gles3/shaders/max\_simultaneous\_compiles](#class-projectsettings-property-rendering-gles3-shaders-max-simultaneous-compiles).
Depending on the specific browsers you are targeting, you may want to raise it.
**Note:** This setting is only meaningful if [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode) is **not** `Synchronous`.
### [int](class_int#class-int) rendering/gles3/shaders/shader\_cache\_size\_mb
| | |
| --- | --- |
| *Default* | `512` |
The maximum size, in megabytes, that the ubershader cache can grow up to. On startup, the least recently used entries will be deleted until the total size is within bounds.
**Note:** This setting is only meaningful if [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode) is set to `Asynchronous + Cache`.
### [int](class_int#class-int) rendering/gles3/shaders/shader\_cache\_size\_mb.mobile
| | |
| --- | --- |
| *Default* | `128` |
An override for [rendering/gles3/shaders/shader\_cache\_size\_mb](#class-projectsettings-property-rendering-gles3-shaders-shader-cache-size-mb), so a smaller maximum size can be configured for mobile platforms, where storage space is more limited.
**Note:** This setting is only meaningful if [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode) is set to `Asynchronous + Cache`.
### [int](class_int#class-int) rendering/gles3/shaders/shader\_cache\_size\_mb.web
| | |
| --- | --- |
| *Default* | `128` |
An override for [rendering/gles3/shaders/shader\_cache\_size\_mb](#class-projectsettings-property-rendering-gles3-shaders-shader-cache-size-mb), so a smaller maximum size can be configured for web platforms, where storage space is more limited.
**Note:** Currently, shader caching is generally unavailable on web platforms.
**Note:** This setting is only meaningful if [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode) is set to `Asynchronous + Cache`.
### [int](class_int#class-int) rendering/gles3/shaders/shader\_compilation\_mode
| | |
| --- | --- |
| *Default* | `0` |
If set to `Asynchronous` and available on the target device, asynchronous compilation of shaders is enabled (in contrast to `Asynchronous`).
That means that when a shader is first used under some new rendering situation, the game won't stall while such shader is being compiled. Instead, a fallback will be used and the real shader will be compiled in the background. Once the actual shader is compiled, it will be used the next times it's used to draw a frame.
Depending on the async mode configured for a given material/shader, the fallback will be an "ubershader" (the default) or just skip rendering any item it is applied to.
An ubershader is a very complex shader, slow but suited to any rendering situation, that the engine generates internally so it can be used from the beginning while the traditional conditioned, optimized version of it is being compiled.
To reduce loading times after the project has been launched at least once, you can use `Asynchronous + Cache`. This also causes the ubershaders to be cached into storage so they can be ready faster next time they are used (provided the platform provides support for it).
**Note:** Asynchronous compilation is currently only supported for spatial (3D) and particle materials/shaders. CanvasItem (2D) shaders will not use asynchronous compilation even if this setting is set to `Asynchronous` or `Asynchronous + Cache`.
### [int](class_int#class-int) rendering/gles3/shaders/shader\_compilation\_mode.mobile
| | |
| --- | --- |
| *Default* | `0` |
An override for [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode), so asynchronous compilation can be disabled on mobile platforms.
You may want to do that since mobile GPUs generally won't support ubershaders due to their complexity.
### [int](class_int#class-int) rendering/gles3/shaders/shader\_compilation\_mode.web
| | |
| --- | --- |
| *Default* | `0` |
An override for [rendering/gles3/shaders/shader\_compilation\_mode](#class-projectsettings-property-rendering-gles3-shaders-shader-compilation-mode), so asynchronous compilation can be disabled on web platforms.
You may want to do that since certain browsers (especially on mobile platforms) generally won't support ubershaders due to their complexity.
### [int](class_int#class-int) rendering/limits/buffers/blend\_shape\_max\_buffer\_size\_kb
| | |
| --- | --- |
| *Default* | `4096` |
Max buffer size for blend shapes. Any blend shape bigger than this will not work.
### [int](class_int#class-int) rendering/limits/buffers/canvas\_polygon\_buffer\_size\_kb
| | |
| --- | --- |
| *Default* | `128` |
Max buffer size for drawing polygons. Any polygon bigger than this will not work.
### [int](class_int#class-int) rendering/limits/buffers/canvas\_polygon\_index\_buffer\_size\_kb
| | |
| --- | --- |
| *Default* | `128` |
Max index buffer size for drawing polygons. Any polygon bigger than this will not work.
### [int](class_int#class-int) rendering/limits/buffers/immediate\_buffer\_size\_kb
| | |
| --- | --- |
| *Default* | `2048` |
Max buffer size for drawing immediate objects (ImmediateGeometry nodes). Nodes using more than this size will not work.
### [int](class_int#class-int) rendering/limits/rendering/max\_lights\_per\_object
| | |
| --- | --- |
| *Default* | `32` |
Max number of lights renderable per object. This is further limited by hardware support. Most devices only support 409 lights, while many devices (especially mobile) only support 102. Setting this low will slightly reduce memory usage and may decrease shader compile times.
### [int](class_int#class-int) rendering/limits/rendering/max\_renderable\_elements
| | |
| --- | --- |
| *Default* | `65536` |
Max amount of elements renderable in a frame. If more elements than this are visible per frame, they will not be drawn. Keep in mind elements refer to mesh surfaces and not meshes themselves. Setting this low will slightly reduce memory usage and may decrease shader compile times, particularly on web. For most uses, the default value is suitable, but consider lowering as much as possible on web export.
### [int](class_int#class-int) rendering/limits/rendering/max\_renderable\_lights
| | |
| --- | --- |
| *Default* | `4096` |
Max number of lights renderable in a frame. If more lights than this number are used, they will be ignored. Setting this low will slightly reduce memory usage and may decrease shader compile times, particularly on web. For most uses, the default value is suitable, but consider lowering as much as possible on web export.
### [int](class_int#class-int) rendering/limits/rendering/max\_renderable\_reflections
| | |
| --- | --- |
| *Default* | `1024` |
Max number of reflection probes renderable in a frame. If more reflection probes than this number are used, they will be ignored. Setting this low will slightly reduce memory usage and may decrease shader compile times, particularly on web. For most uses, the default value is suitable, but consider lowering as much as possible on web export.
### [float](class_float#class-float) rendering/limits/time/time\_rollover\_secs
| | |
| --- | --- |
| *Default* | `3600` |
Shaders have a time variable that constantly increases. At some point, it needs to be rolled back to zero to avoid precision errors on shader animations. This setting specifies when (in seconds).
### [bool](class_bool#class-bool) rendering/misc/lossless\_compression/force\_png
| | |
| --- | --- |
| *Default* | `false` |
If `true`, the texture importer will import lossless textures using the PNG format. Otherwise, it will default to using WebP.
### [int](class_int#class-int) rendering/misc/lossless\_compression/webp\_compression\_level
| | |
| --- | --- |
| *Default* | `2` |
The default compression level for lossless WebP. Higher levels result in smaller files at the cost of compression speed. Decompression speed is mostly unaffected by the compression level. Supported values are 0 to 9. Note that compression levels above 6 are very slow and offer very little savings.
### [bool](class_bool#class-bool) rendering/misc/mesh\_storage/split\_stream
| | |
| --- | --- |
| *Default* | `false` |
On import, mesh vertex data will be split into two streams within a single vertex buffer, one for position data and the other for interleaved attributes data. Recommended to be enabled if targeting mobile devices. Requires manual reimport of meshes after toggling.
### [int](class_int#class-int) rendering/misc/occlusion\_culling/max\_active\_polygons
| | |
| --- | --- |
| *Default* | `8` |
Determines the maximum number of polygon occluders that will be used at any one time.
Although you can have many occluders in a scene, each frame the system will choose from these the most relevant based on a screen space metric, in order to give the best overall performance.
A greater number of polygons can potentially cull more objects, however the cost of culling calculations scales with the number of occluders.
### [int](class_int#class-int) rendering/misc/occlusion\_culling/max\_active\_spheres
| | |
| --- | --- |
| *Default* | `8` |
Determines the maximum number of sphere occluders that will be used at any one time.
Although you can have many occluders in a scene, each frame the system will choose from these the most relevant based on a screen space metric, in order to give the best overall performance.
### [bool](class_bool#class-bool) rendering/portals/advanced/flip\_imported\_portals
| | |
| --- | --- |
| *Default* | `false` |
The default convention is for portal normals to point outward (face outward) from the source room.
If you accidentally build your level with portals facing the wrong way, this setting can fix the problem.
It will flip named portal meshes (i.e. `-portal`) on the initial conversion to [Portal](class_portal#class-portal) nodes.
### [bool](class_bool#class-bool) rendering/portals/debug/logging
| | |
| --- | --- |
| *Default* | `true` |
Show conversion logs.
**Note:** This will automatically be disabled in exports.
### [bool](class_bool#class-bool) rendering/portals/gameplay/use\_signals
| | |
| --- | --- |
| *Default* | `true` |
If `true`, gameplay callbacks will be sent as `signals`. If `false`, they will be sent as `notifications`.
### [bool](class_bool#class-bool) rendering/portals/optimize/remove\_danglers
| | |
| --- | --- |
| *Default* | `true` |
If enabled, while merging meshes, the system will also attempt to remove [Spatial](class_spatial#class-spatial) nodes that no longer have any children.
Reducing the number of [Node](class_node#class-node)s in the scene tree can make traversal more efficient, but can be switched off in case you wish to use empty [Spatial](class_spatial#class-spatial)s for markers or some other purpose.
### [bool](class_bool#class-bool) rendering/portals/pvs/pvs\_logging
| | |
| --- | --- |
| *Default* | `false` |
Show logs during PVS generation.
**Note:** This will automatically be disabled in exports.
### [bool](class_bool#class-bool) rendering/portals/pvs/use\_simple\_pvs
| | |
| --- | --- |
| *Default* | `false` |
Uses a simplified method of generating PVS (potentially visible set) data. The results may not be accurate where more than one portal join adjacent rooms.
**Note:** Generally you should only use this option if you encounter bugs when it is set to `false`, i.e. there are problems with the default method.
### [bool](class_bool#class-bool) rendering/quality/depth/hdr
| | |
| --- | --- |
| *Default* | `true` |
If `true`, allocates the root [Viewport](class_viewport#class-viewport)'s framebuffer with high dynamic range. High dynamic range allows the use of [Color](class_color#class-color) values greater than 1. This must be set to `true` for glow rendering to work if [Environment.glow\_hdr\_threshold](class_environment#class-environment-property-glow-hdr-threshold) is greater than or equal to `1.0`.
**Note:** Only available on the GLES3 backend.
### [bool](class_bool#class-bool) rendering/quality/depth/hdr.mobile
| | |
| --- | --- |
| *Default* | `false` |
Lower-end override for [rendering/quality/depth/hdr](#class-projectsettings-property-rendering-quality-depth-hdr) on mobile devices, due to performance concerns or driver support. This must be set to `true` for glow rendering to work if [Environment.glow\_hdr\_threshold](class_environment#class-environment-property-glow-hdr-threshold) is greater than or equal to `1.0`.
**Note:** Only available on the GLES3 backend.
### [bool](class_bool#class-bool) rendering/quality/depth/use\_32\_bpc\_depth
| | |
| --- | --- |
| *Default* | `false` |
If `true`, allocates the root [Viewport](class_viewport#class-viewport)'s framebuffer with full floating-point precision (32-bit) instead of half floating-point precision (16-bit). Only effective when [rendering/quality/depth/hdr](#class-projectsettings-property-rendering-quality-depth-hdr) is also enabled.
**Note:** Enabling this setting does not improve rendering quality. Using full floating-point precision is slower, and is generally only needed for advanced shaders that require a high level of precision. To reduce banding, enable [rendering/quality/filters/use\_debanding](#class-projectsettings-property-rendering-quality-filters-use-debanding) instead.
**Note:** Only available on the GLES3 backend.
### [String](class_string#class-string) rendering/quality/depth\_prepass/disable\_for\_vendors
| | |
| --- | --- |
| *Default* | `"PowerVR,Mali,Adreno,Apple"` |
Disables depth pre-pass for some GPU vendors (usually mobile), as their architecture already does this.
### [bool](class_bool#class-bool) rendering/quality/depth\_prepass/enable
| | |
| --- | --- |
| *Default* | `true` |
If `true`, performs a previous depth pass before rendering materials. This increases performance in scenes with high overdraw, when complex materials and lighting are used.
### [int](class_int#class-int) rendering/quality/directional\_shadow/size
| | |
| --- | --- |
| *Default* | `4096` |
The directional shadow's size in pixels. Higher values will result in sharper shadows, at the cost of performance. The value will be rounded up to the nearest power of 2. This setting can be changed at run-time; the change will be applied immediately.
### [int](class_int#class-int) rendering/quality/directional\_shadow/size.mobile
| | |
| --- | --- |
| *Default* | `2048` |
Lower-end override for [rendering/quality/directional\_shadow/size](#class-projectsettings-property-rendering-quality-directional-shadow-size) on mobile devices, due to performance concerns or driver support.
### [String](class_string#class-string) rendering/quality/driver/driver\_name
| | |
| --- | --- |
| *Default* | `"GLES3"` |
The video driver to use ("GLES2" or "GLES3").
**Note:** The backend in use can be overridden at runtime via the `--video-driver` command line argument, or by the [rendering/quality/driver/fallback\_to\_gles2](#class-projectsettings-property-rendering-quality-driver-fallback-to-gles2) option if the target system does not support GLES3 and falls back to GLES2. In such cases, this property is not updated, so use [OS.get\_current\_video\_driver](class_os#class-os-method-get-current-video-driver) to query it at run-time.
### [bool](class_bool#class-bool) rendering/quality/driver/fallback\_to\_gles2
| | |
| --- | --- |
| *Default* | `false` |
If `true`, allows falling back to the GLES2 driver if the GLES3 driver is not supported.
**Note:** The two video drivers are not drop-in replacements for each other, so a game designed for GLES3 might not work properly when falling back to GLES2. In particular, some features of the GLES3 backend are not available in GLES2. Enabling this setting also means that both ETC and ETC2 VRAM-compressed textures will be exported on Android and iOS, increasing the data pack's size.
### [int](class_int#class-int) rendering/quality/filters/anisotropic\_filter\_level
| | |
| --- | --- |
| *Default* | `4` |
Maximum anisotropic filter level used for textures with anisotropy enabled. Higher values will result in sharper textures when viewed from oblique angles, at the cost of performance. With the exception of `1`, only power-of-two values are valid (`2`, `4`, `8`, `16`). A value of `1` forcibly disables anisotropic filtering, even on textures where it is enabled.
**Note:** For performance reasons, anisotropic filtering *is not enabled by default* on textures. For this setting to have an effect, anisotropic texture filtering can be enabled by selecting a texture in the FileSystem dock, going to the Import dock, checking the **Anisotropic** checkbox then clicking **Reimport**. However, anisotropic filtering is rarely useful in 2D, so only enable it for textures in 2D if it makes a meaningful visual difference.
**Note:** This property is only read when the project starts. There is currently no way to change this setting at run-time.
### [int](class_int#class-int) rendering/quality/filters/msaa
| | |
| --- | --- |
| *Default* | `0` |
Sets the number of MSAA samples to use. MSAA is used to reduce aliasing around the edges of polygons. A higher MSAA value results in smoother edges but can be significantly slower on some hardware.
**Note:** MSAA is not available on HTML5 export using the GLES2 backend.
### [float](class_float#class-float) rendering/quality/filters/sharpen\_intensity
| | |
| --- | --- |
| *Default* | `0.0` |
If set to a value greater than `0.0`, contrast-adaptive sharpening will be applied to the 3D viewport. This has a low performance cost and can be used to recover some of the sharpness lost from using FXAA. Values around `0.5` generally give the best results. See also [rendering/quality/filters/use\_fxaa](#class-projectsettings-property-rendering-quality-filters-use-fxaa).
### [bool](class_bool#class-bool) rendering/quality/filters/use\_debanding
| | |
| --- | --- |
| *Default* | `false` |
If `true`, uses a fast post-processing filter to make banding significantly less visible. In some cases, debanding may introduce a slightly noticeable dithering pattern. It's recommended to enable debanding only when actually needed since the dithering pattern will make lossless-compressed screenshots larger.
**Note:** Only available on the GLES3 backend. [rendering/quality/depth/hdr](#class-projectsettings-property-rendering-quality-depth-hdr) must also be `true` for debanding to be effective.
**Note:** There are known issues with debanding breaking rendering on mobile platforms. Due to this, it is recommended to leave this option disabled when targeting mobile platforms.
### [bool](class_bool#class-bool) rendering/quality/filters/use\_fxaa
| | |
| --- | --- |
| *Default* | `false` |
Enables FXAA in the root Viewport. FXAA is a popular screen-space antialiasing method, which is fast but will make the image look blurry, especially at lower resolutions. It can still work relatively well at large resolutions such as 1440p and 4K. Some of the lost sharpness can be recovered by enabling contrast-adaptive sharpening (see [rendering/quality/filters/sharpen\_intensity](#class-projectsettings-property-rendering-quality-filters-sharpen-intensity)).
### [bool](class_bool#class-bool) rendering/quality/filters/use\_nearest\_mipmap\_filter
| | |
| --- | --- |
| *Default* | `false` |
If `true`, uses nearest-neighbor mipmap filtering when using mipmaps (also called "bilinear filtering"), which will result in visible seams appearing between mipmap stages. This may increase performance in mobile as less memory bandwidth is used. If `false`, linear mipmap filtering (also called "trilinear filtering") is used.
### [int](class_int#class-int) rendering/quality/intended\_usage/framebuffer\_allocation
| | |
| --- | --- |
| *Default* | `2` |
Strategy used for framebuffer allocation. The simpler it is, the less resources it uses (but the less features it supports). If set to "2D Without Sampling" or "3D Without Effects", sample buffers will not be allocated. This means `SCREEN_TEXTURE` and `DEPTH_TEXTURE` will not be available in shaders and post-processing effects such as glow will not be available in [Environment](class_environment#class-environment).
### [int](class_int#class-int) rendering/quality/intended\_usage/framebuffer\_allocation.mobile
| | |
| --- | --- |
| *Default* | `3` |
Lower-end override for [rendering/quality/intended\_usage/framebuffer\_allocation](#class-projectsettings-property-rendering-quality-intended-usage-framebuffer-allocation) on mobile devices, due to performance concerns or driver support.
### [bool](class_bool#class-bool) rendering/quality/lightmapping/use\_bicubic\_sampling
| | |
| --- | --- |
| *Default* | `true` |
Enable usage of bicubic sampling in baked lightmaps. This results in smoother looking lighting at the expense of more bandwidth usage. On GLES2, changes to this setting will only be applied upon restarting the application.
### [bool](class_bool#class-bool) rendering/quality/lightmapping/use\_bicubic\_sampling.mobile
| | |
| --- | --- |
| *Default* | `false` |
Lower-end override for [rendering/quality/lightmapping/use\_bicubic\_sampling](#class-projectsettings-property-rendering-quality-lightmapping-use-bicubic-sampling) on mobile devices, in order to reduce bandwidth usage.
### [int](class_int#class-int) rendering/quality/reflections/atlas\_size
| | |
| --- | --- |
| *Default* | `2048` |
Size of the atlas used by reflection probes. A larger size can result in higher visual quality, while a smaller size will be faster and take up less memory.
### [int](class_int#class-int) rendering/quality/reflections/atlas\_subdiv
| | |
| --- | --- |
| *Default* | `8` |
Number of subdivisions to use for the reflection atlas. A higher number lowers the quality of each atlas, but allows you to use more.
### [bool](class_bool#class-bool) rendering/quality/reflections/high\_quality\_ggx
| | |
| --- | --- |
| *Default* | `true` |
If `true`, uses a high amount of samples to create blurred variants of reflection probes and panorama backgrounds (sky). Those blurred variants are used by rough materials.
### [bool](class_bool#class-bool) rendering/quality/reflections/high\_quality\_ggx.mobile
| | |
| --- | --- |
| *Default* | `false` |
Lower-end override for [rendering/quality/reflections/high\_quality\_ggx](#class-projectsettings-property-rendering-quality-reflections-high-quality-ggx) on mobile devices, due to performance concerns or driver support.
### [int](class_int#class-int) rendering/quality/reflections/irradiance\_max\_size
| | |
| --- | --- |
| *Default* | `128` |
Limits the size of the irradiance map which is normally determined by [Sky.radiance\_size](class_sky#class-sky-property-radiance-size). A higher size results in a higher quality irradiance map similarly to [rendering/quality/reflections/high\_quality\_ggx](#class-projectsettings-property-rendering-quality-reflections-high-quality-ggx). Use a higher value when using high-frequency HDRI maps, otherwise keep this as low as possible.
**Note:** Low and mid range hardware do not support complex irradiance maps well and may crash if this is set too high.
### [bool](class_bool#class-bool) rendering/quality/reflections/texture\_array\_reflections
| | |
| --- | --- |
| *Default* | `true` |
If `true`, uses texture arrays instead of mipmaps for reflection probes and panorama backgrounds (sky). This reduces jitter noise on reflections, but costs more performance and memory.
### [bool](class_bool#class-bool) rendering/quality/reflections/texture\_array\_reflections.mobile
| | |
| --- | --- |
| *Default* | `false` |
Lower-end override for [rendering/quality/reflections/texture\_array\_reflections](#class-projectsettings-property-rendering-quality-reflections-texture-array-reflections) on mobile devices, due to performance concerns or driver support.
### [bool](class_bool#class-bool) rendering/quality/shading/force\_blinn\_over\_ggx
| | |
| --- | --- |
| *Default* | `false` |
If `true`, uses faster but lower-quality Blinn model to generate blurred reflections instead of the GGX model.
### [bool](class_bool#class-bool) rendering/quality/shading/force\_blinn\_over\_ggx.mobile
| | |
| --- | --- |
| *Default* | `true` |
Lower-end override for [rendering/quality/shading/force\_blinn\_over\_ggx](#class-projectsettings-property-rendering-quality-shading-force-blinn-over-ggx) on mobile devices, due to performance concerns or driver support.
### [bool](class_bool#class-bool) rendering/quality/shading/force\_lambert\_over\_burley
| | |
| --- | --- |
| *Default* | `false` |
If `true`, uses faster but lower-quality Lambert material lighting model instead of Burley.
### [bool](class_bool#class-bool) rendering/quality/shading/force\_lambert\_over\_burley.mobile
| | |
| --- | --- |
| *Default* | `true` |
Lower-end override for [rendering/quality/shading/force\_lambert\_over\_burley](#class-projectsettings-property-rendering-quality-shading-force-lambert-over-burley) on mobile devices, due to performance concerns or driver support.
### [bool](class_bool#class-bool) rendering/quality/shading/force\_vertex\_shading
| | |
| --- | --- |
| *Default* | `false` |
If `true`, forces vertex shading for all 3D [SpatialMaterial](class_spatialmaterial#class-spatialmaterial) and [ShaderMaterial](class_shadermaterial#class-shadermaterial) rendering. This can be used to improve performance on low-end mobile devices. The downside is that shading becomes much less accurate, with visible linear interpolation between vertices that are joined together. This can be compensated by ensuring meshes have a sufficient level of subdivision (but not too much, to avoid reducing performance). Some material features are also not supported when vertex shading is enabled.
See also [SpatialMaterial.flags\_vertex\_lighting](class_spatialmaterial#class-spatialmaterial-property-flags-vertex-lighting) which can be used to enable vertex shading on specific materials only.
**Note:** This setting does not affect unshaded materials.
### [bool](class_bool#class-bool) rendering/quality/shading/force\_vertex\_shading.mobile
| | |
| --- | --- |
| *Default* | `true` |
Lower-end override for [rendering/quality/shading/force\_vertex\_shading](#class-projectsettings-property-rendering-quality-shading-force-vertex-shading) on mobile devices, due to performance concerns or driver support. If lighting looks broken after exporting the project to a mobile platform, try disabling this setting.
### [bool](class_bool#class-bool) rendering/quality/shading/use\_physical\_light\_attenuation
| | |
| --- | --- |
| *Default* | `false` |
If `true`, enables new physical light attenuation for [OmniLight](class_omnilight#class-omnilight)s and [SpotLight](class_spotlight#class-spotlight)s. This results in more realistic lighting appearance with a very small performance cost. When physical light attenuation is enabled, lights will appear to be darker as a result of the new attenuation formula. This can be compensated by adjusting the lights' energy or attenuation values.
Changes to this setting will only be applied upon restarting the application.
### [int](class_int#class-int) rendering/quality/shadow\_atlas/cubemap\_size
| | |
| --- | --- |
| *Default* | `512` |
Size for cubemap into which the shadow is rendered before being copied into the shadow atlas. A higher number can result in higher resolution shadows when used with a higher [rendering/quality/shadow\_atlas/size](#class-projectsettings-property-rendering-quality-shadow-atlas-size). Setting higher than a quarter of the [rendering/quality/shadow\_atlas/size](#class-projectsettings-property-rendering-quality-shadow-atlas-size) will not result in a perceptible increase in visual quality.
### [int](class_int#class-int) rendering/quality/shadow\_atlas/quadrant\_0\_subdiv
| | |
| --- | --- |
| *Default* | `1` |
Subdivision quadrant size for shadow mapping. See shadow mapping documentation.
### [int](class_int#class-int) rendering/quality/shadow\_atlas/quadrant\_1\_subdiv
| | |
| --- | --- |
| *Default* | `2` |
Subdivision quadrant size for shadow mapping. See shadow mapping documentation.
### [int](class_int#class-int) rendering/quality/shadow\_atlas/quadrant\_2\_subdiv
| | |
| --- | --- |
| *Default* | `3` |
Subdivision quadrant size for shadow mapping. See shadow mapping documentation.
### [int](class_int#class-int) rendering/quality/shadow\_atlas/quadrant\_3\_subdiv
| | |
| --- | --- |
| *Default* | `4` |
Subdivision quadrant size for shadow mapping. See shadow mapping documentation.
### [int](class_int#class-int) rendering/quality/shadow\_atlas/size
| | |
| --- | --- |
| *Default* | `4096` |
Size for shadow atlas (used for OmniLights and SpotLights). The value will be rounded up to the nearest power of 2. See shadow mapping documentation.
### [int](class_int#class-int) rendering/quality/shadow\_atlas/size.mobile
| | |
| --- | --- |
| *Default* | `2048` |
Lower-end override for [rendering/quality/shadow\_atlas/size](#class-projectsettings-property-rendering-quality-shadow-atlas-size) on mobile devices, due to performance concerns or driver support.
### [int](class_int#class-int) rendering/quality/shadows/filter\_mode
| | |
| --- | --- |
| *Default* | `1` |
Shadow filter mode. Higher-quality settings result in smoother shadows that flicker less when moving. "Disabled" is the fastest option, but also has the lowest quality. "PCF5" is smoother but is also slower. "PCF13" is the smoothest option, but is also the slowest.
**Note:** When using the GLES2 backend, the "PCF13" option actually uses 16 samples to emulate linear filtering in the shader. This results in a shadow appearance similar to the one produced by the GLES3 backend.
### [int](class_int#class-int) rendering/quality/shadows/filter\_mode.mobile
| | |
| --- | --- |
| *Default* | `0` |
Lower-end override for [rendering/quality/shadows/filter\_mode](#class-projectsettings-property-rendering-quality-shadows-filter-mode) on mobile devices, due to performance concerns or driver support.
### [bool](class_bool#class-bool) rendering/quality/skinning/force\_software\_skinning
| | |
| --- | --- |
| *Default* | `false` |
Forces [MeshInstance](class_meshinstance#class-meshinstance) to always perform skinning on the CPU (applies to both GLES2 and GLES3).
See also [rendering/quality/skinning/software\_skinning\_fallback](#class-projectsettings-property-rendering-quality-skinning-software-skinning-fallback).
### [bool](class_bool#class-bool) rendering/quality/skinning/software\_skinning\_fallback
| | |
| --- | --- |
| *Default* | `true` |
Allows [MeshInstance](class_meshinstance#class-meshinstance) to perform skinning on the CPU when the hardware doesn't support the default GPU skinning process with GLES2.
If `false`, an alternative skinning process on the GPU is used in this case (slower in most cases).
See also [rendering/quality/skinning/force\_software\_skinning](#class-projectsettings-property-rendering-quality-skinning-force-software-skinning).
**Note:** When the software skinning fallback is triggered, custom vertex shaders will behave in a different way, because the bone transform will be already applied to the modelview matrix.
### [float](class_float#class-float) rendering/quality/spatial\_partitioning/bvh\_collision\_margin
| | |
| --- | --- |
| *Default* | `0.1` |
Additional expansion applied to object bounds in the 3D rendering bounding volume hierarchy. This can reduce BVH processing at the cost of a slightly reduced accuracy.
The default value will work well in most situations. A value of 0.0 will turn this optimization off, and larger values may work better for larger, faster moving objects.
**Note:** Used only if [rendering/quality/spatial\_partitioning/use\_bvh](#class-projectsettings-property-rendering-quality-spatial-partitioning-use-bvh) is enabled.
### [float](class_float#class-float) rendering/quality/spatial\_partitioning/render\_tree\_balance
| | |
| --- | --- |
| *Default* | `0.0` |
The rendering octree balance can be changed to favor smaller (`0`), or larger (`1`) branches.
Larger branches can increase performance significantly in some projects.
**Note:** Not used if [rendering/quality/spatial\_partitioning/use\_bvh](#class-projectsettings-property-rendering-quality-spatial-partitioning-use-bvh) is enabled.
### [bool](class_bool#class-bool) rendering/quality/spatial\_partitioning/use\_bvh
| | |
| --- | --- |
| *Default* | `true` |
Enables the use of bounding volume hierarchy instead of octree for rendering spatial partitioning. This may give better performance.
### [bool](class_bool#class-bool) rendering/quality/subsurface\_scattering/follow\_surface
| | |
| --- | --- |
| *Default* | `false` |
Improves quality of subsurface scattering, but cost significantly increases.
### [int](class_int#class-int) rendering/quality/subsurface\_scattering/quality
| | |
| --- | --- |
| *Default* | `1` |
Quality setting for subsurface scattering (samples taken).
### [int](class_int#class-int) rendering/quality/subsurface\_scattering/scale
| | |
| --- | --- |
| *Default* | `1.0` |
Max radius used for subsurface scattering samples.
### [bool](class_bool#class-bool) rendering/quality/subsurface\_scattering/weight\_samples
| | |
| --- | --- |
| *Default* | `true` |
Weight subsurface scattering samples. Helps to avoid reading samples from unrelated parts of the screen.
### [bool](class_bool#class-bool) rendering/quality/voxel\_cone\_tracing/high\_quality
| | |
| --- | --- |
| *Default* | `false` |
Use high-quality voxel cone tracing. This results in better-looking reflections, but is much more expensive on the GPU.
### [int](class_int#class-int) rendering/threads/thread\_model
| | |
| --- | --- |
| *Default* | `1` |
Thread model for rendering. Rendering on a thread can vastly improve performance, but synchronizing to the main thread can cause a bit more jitter.
### [bool](class_bool#class-bool) rendering/threads/thread\_safe\_bvh
| | |
| --- | --- |
| *Default* | `false` |
If `true`, a thread safe version of BVH (bounding volume hierarchy) will be used in rendering and Godot physics.
Try enabling this option if you see any visual anomalies in 3D (such as incorrect object visibility).
### [bool](class_bool#class-bool) rendering/vram\_compression/import\_bptc
| | |
| --- | --- |
| *Default* | `false` |
If `true`, the texture importer will import VRAM-compressed textures using the BPTC algorithm. This texture compression algorithm is only supported on desktop platforms, and only when using the GLES3 renderer.
**Note:** Changing this setting does *not* impact textures that were already imported before. To make this setting apply to textures that were already imported, exit the editor, remove the `.import/` folder located inside the project folder then restart the editor (see [application/config/use\_hidden\_project\_data\_directory](#class-projectsettings-property-application-config-use-hidden-project-data-directory)).
### [bool](class_bool#class-bool) rendering/vram\_compression/import\_etc
| | |
| --- | --- |
| *Default* | `false` |
If `true`, the texture importer will import VRAM-compressed textures using the Ericsson Texture Compression algorithm. This algorithm doesn't support alpha channels in textures.
**Note:** Changing this setting does *not* impact textures that were already imported before. To make this setting apply to textures that were already imported, exit the editor, remove the `.import/` folder located inside the project folder then restart the editor (see [application/config/use\_hidden\_project\_data\_directory](#class-projectsettings-property-application-config-use-hidden-project-data-directory)).
### [bool](class_bool#class-bool) rendering/vram\_compression/import\_etc2
| | |
| --- | --- |
| *Default* | `true` |
If `true`, the texture importer will import VRAM-compressed textures using the Ericsson Texture Compression 2 algorithm. This texture compression algorithm is only supported when using the GLES3 renderer.
**Note:** Changing this setting does *not* impact textures that were already imported before. To make this setting apply to textures that were already imported, exit the editor, remove the `.import/` folder located inside the project folder then restart the editor (see [application/config/use\_hidden\_project\_data\_directory](#class-projectsettings-property-application-config-use-hidden-project-data-directory)).
### [bool](class_bool#class-bool) rendering/vram\_compression/import\_pvrtc
| | |
| --- | --- |
| *Default* | `false` |
If `true`, the texture importer will import VRAM-compressed textures using the PowerVR Texture Compression algorithm. This texture compression algorithm is only supported on iOS.
**Note:** Changing this setting does *not* impact textures that were already imported before. To make this setting apply to textures that were already imported, exit the editor, remove the `.import/` folder located inside the project folder then restart the editor (see [application/config/use\_hidden\_project\_data\_directory](#class-projectsettings-property-application-config-use-hidden-project-data-directory)).
### [bool](class_bool#class-bool) rendering/vram\_compression/import\_s3tc
| | |
| --- | --- |
| *Default* | `true` |
If `true`, the texture importer will import VRAM-compressed textures using the S3 Texture Compression algorithm. This algorithm is only supported on desktop platforms and consoles.
**Note:** Changing this setting does *not* impact textures that were already imported before. To make this setting apply to textures that were already imported, exit the editor, remove the `.import/` folder located inside the project folder then restart the editor (see [application/config/use\_hidden\_project\_data\_directory](#class-projectsettings-property-application-config-use-hidden-project-data-directory)).
### [int](class_int#class-int) world/2d/cell\_size
| | |
| --- | --- |
| *Default* | `100` |
Cell size used for the 2D hash grid that [VisibilityNotifier2D](class_visibilitynotifier2d#class-visibilitynotifier2d) uses (in pixels).
Method Descriptions
-------------------
### void add\_property\_info ( [Dictionary](class_dictionary#class-dictionary) hint )
Adds a custom property info to a property. The dictionary must contain:
* `name`: [String](class_string#class-string) (the property's name)
* `type`: [int](class_int#class-int) (see [Variant.Type](class_%40globalscope#enum-globalscope-variant-type))
* optionally `hint`: [int](class_int#class-int) (see [PropertyHint](class_%40globalscope#enum-globalscope-propertyhint)) and `hint_string`: [String](class_string#class-string)
**Example:**
```
ProjectSettings.set("category/property_name", 0)
var property_info = {
"name": "category/property_name",
"type": TYPE_INT,
"hint": PROPERTY_HINT_ENUM,
"hint_string": "one,two,three"
}
ProjectSettings.add_property_info(property_info)
```
### void clear ( [String](class_string#class-string) name )
Clears the whole configuration (not recommended, may break things).
### [int](class_int#class-int) get\_order ( [String](class_string#class-string) name ) const
Returns the order of a configuration value (influences when saved to the config file).
### [Variant](class_variant#class-variant) get\_setting ( [String](class_string#class-string) name ) const
Returns the value of a setting.
**Example:**
```
print(ProjectSettings.get_setting("application/config/name"))
```
### [String](class_string#class-string) globalize\_path ( [String](class_string#class-string) path ) const
Returns the absolute, native OS path corresponding to the localized `path` (starting with `res://` or `user://`). The returned path will vary depending on the operating system and user preferences. See [File paths in Godot projects](https://docs.godotengine.org/en/3.5/tutorials/io/data_paths.html) to see what those paths convert to. See also [localize\_path](#class-projectsettings-method-localize-path).
**Note:** [globalize\_path](#class-projectsettings-method-globalize-path) with `res://` will not work in an exported project. Instead, prepend the executable's base directory to the path when running from an exported project:
```
var path = ""
if OS.has_feature("editor"):
# Running from an editor binary.
# `path` will contain the absolute path to `hello.txt` located in the project root.
path = ProjectSettings.globalize_path("res://hello.txt")
else:
# Running from an exported project.
# `path` will contain the absolute path to `hello.txt` next to the executable.
# This is *not* identical to using `ProjectSettings.globalize_path()` with a `res://` path,
# but is close enough in spirit.
path = OS.get_executable_path().get_base_dir().plus_file("hello.txt")
```
### [bool](class_bool#class-bool) has\_setting ( [String](class_string#class-string) name ) const
Returns `true` if a configuration value is present.
### [bool](class_bool#class-bool) load\_resource\_pack ( [String](class_string#class-string) pack, [bool](class_bool#class-bool) replace\_files=true, [int](class_int#class-int) offset=0 )
Loads the contents of the .pck or .zip file specified by `pack` into the resource filesystem (`res://`). Returns `true` on success.
**Note:** If a file from `pack` shares the same path as a file already in the resource filesystem, any attempts to load that file will use the file from `pack` unless `replace_files` is set to `false`.
**Note:** The optional `offset` parameter can be used to specify the offset in bytes to the start of the resource pack. This is only supported for .pck files.
### [String](class_string#class-string) localize\_path ( [String](class_string#class-string) path ) const
Returns the localized path (starting with `res://`) corresponding to the absolute, native OS `path`. See also [globalize\_path](#class-projectsettings-method-globalize-path).
### [bool](class_bool#class-bool) property\_can\_revert ( [String](class_string#class-string) name )
Returns `true` if the specified property exists and its initial value differs from the current value.
### [Variant](class_variant#class-variant) property\_get\_revert ( [String](class_string#class-string) name )
Returns the specified property's initial value. Returns `null` if the property does not exist.
### [Error](class_%40globalscope#enum-globalscope-error) save ( )
Saves the configuration to the `project.godot` file.
**Note:** This method is intended to be used by editor plugins, as modified `ProjectSettings` can't be loaded back in the running app. If you want to change project settings in exported projects, use [save\_custom](#class-projectsettings-method-save-custom) to save `override.cfg` file.
### [Error](class_%40globalscope#enum-globalscope-error) save\_custom ( [String](class_string#class-string) file )
Saves the configuration to a custom file. The file extension must be `.godot` (to save in text-based [ConfigFile](class_configfile#class-configfile) format) or `.binary` (to save in binary format). You can also save `override.cfg` file, which is also text, but can be used in exported projects unlike other formats.
### void set\_initial\_value ( [String](class_string#class-string) name, [Variant](class_variant#class-variant) value )
Sets the specified property's initial value. This is the value the property reverts to.
### void set\_order ( [String](class_string#class-string) name, [int](class_int#class-int) position )
Sets the order of a configuration value (influences when saved to the config file).
### void set\_setting ( [String](class_string#class-string) name, [Variant](class_variant#class-variant) value )
Sets the value of a setting.
**Example:**
```
ProjectSettings.set_setting("application/config/name", "Example")
```
This can also be used to erase custom project settings. To do this change the setting value to `null`.
| programming_docs |
godot VisualShaderNodeOuterProduct VisualShaderNodeOuterProduct
============================
**Inherits:** [VisualShaderNode](class_visualshadernode#class-visualshadernode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Calculates an outer product of two vectors within the visual shader graph.
Description
-----------
`OuterProduct` treats the first parameter `c` as a column vector (matrix with one column) and the second parameter `r` as a row vector (matrix with one row) and does a linear algebraic matrix multiply `c * r`, yielding a matrix whose number of rows is the number of components in `c` and whose number of columns is the number of components in `r`.
godot VisualScriptClassConstant VisualScriptClassConstant
=========================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Gets a constant from a given class.
Description
-----------
This node returns a constant from a given class, such as [@GlobalScope.TYPE\_INT](class_%40globalscope#class-globalscope-constant-type-int). See the given class' documentation for available constants.
**Input Ports:**
none
**Output Ports:**
* Data (variant): `value`
Properties
----------
| | | |
| --- | --- | --- |
| [String](class_string#class-string) | [base\_type](#class-visualscriptclassconstant-property-base-type) | `"Object"` |
| [String](class_string#class-string) | [constant](#class-visualscriptclassconstant-property-constant) | `""` |
Property Descriptions
---------------------
### [String](class_string#class-string) base\_type
| | |
| --- | --- |
| *Default* | `"Object"` |
| *Setter* | set\_base\_type(value) |
| *Getter* | get\_base\_type() |
The constant's parent class.
### [String](class_string#class-string) constant
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_class\_constant(value) |
| *Getter* | get\_class\_constant() |
The constant to return. See the given class for its available constants.
godot BoneAttachment BoneAttachment
==============
**Inherits:** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
A node that will attach to a bone.
Description
-----------
This node must be the child of a [Skeleton](class_skeleton#class-skeleton) node. You can then select a bone for this node to attach to. The BoneAttachment node will copy the transform of the selected bone.
Properties
----------
| | | |
| --- | --- | --- |
| [String](class_string#class-string) | [bone\_name](#class-boneattachment-property-bone-name) | `""` |
Property Descriptions
---------------------
### [String](class_string#class-string) bone\_name
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_bone\_name(value) |
| *Getter* | get\_bone\_name() |
The name of the attached bone.
godot HMACContext HMACContext
===========
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Used to create an HMAC for a message using a key.
Description
-----------
The HMACContext class is useful for advanced HMAC use cases, such as streaming the message as it supports creating the message over time rather than providing it all at once.
```
extends Node
var ctx = HMACContext.new()
func _ready():
var key = "supersecret".to_utf8()
var err = ctx.start(HashingContext.HASH_SHA256, key)
assert(err == OK)
var msg1 = "this is ".to_utf8()
var msg2 = "super duper secret".to_utf8()
err = ctx.update(msg1)
assert(err == OK)
err = ctx.update(msg2)
assert(err == OK)
var hmac = ctx.finish()
print(hmac.hex_encode())
```
And in C# we can use the following.
```
using Godot;
using System;
using System.Diagnostics;
public class CryptoNode : Node
{
private HMACContext ctx = new HMACContext();
public override void _Ready()
{
PoolByteArray key = String("supersecret").to_utf8();
Error err = ctx.Start(HashingContext.HASH_SHA256, key);
GD.Assert(err == OK);
PoolByteArray msg1 = String("this is ").to_utf8();
PoolByteArray msg2 = String("super duper secret").to_utf8();
err = ctx.Update(msg1);
GD.Assert(err == OK);
err = ctx.Update(msg2);
GD.Assert(err == OK);
PoolByteArray hmac = ctx.Finish();
GD.Print(hmac.HexEncode());
}
}
```
**Note:** Not available in HTML5 exports.
Methods
-------
| | |
| --- | --- |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [finish](#class-hmaccontext-method-finish) **(** **)** |
| [Error](class_%40globalscope#enum-globalscope-error) | [start](#class-hmaccontext-method-start) **(** [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) key **)** |
| [Error](class_%40globalscope#enum-globalscope-error) | [update](#class-hmaccontext-method-update) **(** [PoolByteArray](class_poolbytearray#class-poolbytearray) data **)** |
Method Descriptions
-------------------
### [PoolByteArray](class_poolbytearray#class-poolbytearray) finish ( )
Returns the resulting HMAC. If the HMAC failed, an empty [PoolByteArray](class_poolbytearray#class-poolbytearray) is returned.
### [Error](class_%40globalscope#enum-globalscope-error) start ( [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) key )
Initializes the HMACContext. This method cannot be called again on the same HMACContext until [finish](#class-hmaccontext-method-finish) has been called.
### [Error](class_%40globalscope#enum-globalscope-error) update ( [PoolByteArray](class_poolbytearray#class-poolbytearray) data )
Updates the message to be HMACed. This can be called multiple times before [finish](#class-hmaccontext-method-finish) is called to append `data` to the message, but cannot be called until [start](#class-hmaccontext-method-start) has been called.
godot VisualScriptFunction VisualScriptFunction
====================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A Visual Script node representing a function.
Description
-----------
`VisualScriptFunction` represents a function header. It is the starting point for the function body and can be used to tweak the function's properties (e.g. RPC mode).
godot Script Script
======
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [CSharpScript](class_csharpscript#class-csharpscript), [GDScript](class_gdscript#class-gdscript), [NativeScript](class_nativescript#class-nativescript), [PluginScript](class_pluginscript#class-pluginscript), [VisualScript](class_visualscript#class-visualscript)
A class stored as a resource.
Description
-----------
A class stored as a resource. A script extends the functionality of all objects that instance it.
The `new` method of a script subclass creates a new instance. [Object.set\_script](class_object#class-object-method-set-script) extends an existing object, if that object's class matches one of the script's base classes.
Tutorials
---------
* [Scripting](https://docs.godotengine.org/en/3.5/tutorials/scripting/index.html)
Properties
----------
| | |
| --- | --- |
| [String](class_string#class-string) | [source\_code](#class-script-property-source-code) |
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [can\_instance](#class-script-method-can-instance) **(** **)** const |
| [Script](#class-script) | [get\_base\_script](#class-script-method-get-base-script) **(** **)** const |
| [String](class_string#class-string) | [get\_instance\_base\_type](#class-script-method-get-instance-base-type) **(** **)** const |
| [Variant](class_variant#class-variant) | [get\_property\_default\_value](#class-script-method-get-property-default-value) **(** [String](class_string#class-string) property **)** |
| [Dictionary](class_dictionary#class-dictionary) | [get\_script\_constant\_map](#class-script-method-get-script-constant-map) **(** **)** |
| [Array](class_array#class-array) | [get\_script\_method\_list](#class-script-method-get-script-method-list) **(** **)** |
| [Array](class_array#class-array) | [get\_script\_property\_list](#class-script-method-get-script-property-list) **(** **)** |
| [Array](class_array#class-array) | [get\_script\_signal\_list](#class-script-method-get-script-signal-list) **(** **)** |
| [bool](class_bool#class-bool) | [has\_script\_signal](#class-script-method-has-script-signal) **(** [String](class_string#class-string) signal\_name **)** const |
| [bool](class_bool#class-bool) | [has\_source\_code](#class-script-method-has-source-code) **(** **)** const |
| [bool](class_bool#class-bool) | [instance\_has](#class-script-method-instance-has) **(** [Object](class_object#class-object) base\_object **)** const |
| [bool](class_bool#class-bool) | [is\_tool](#class-script-method-is-tool) **(** **)** const |
| [Error](class_%40globalscope#enum-globalscope-error) | [reload](#class-script-method-reload) **(** [bool](class_bool#class-bool) keep\_state=false **)** |
Property Descriptions
---------------------
### [String](class_string#class-string) source\_code
| | |
| --- | --- |
| *Setter* | set\_source\_code(value) |
| *Getter* | get\_source\_code() |
The script source code or an empty string if source code is not available. When set, does not reload the class implementation automatically.
Method Descriptions
-------------------
### [bool](class_bool#class-bool) can\_instance ( ) const
Returns `true` if the script can be instanced.
### [Script](#class-script) get\_base\_script ( ) const
Returns the script directly inherited by this script.
### [String](class_string#class-string) get\_instance\_base\_type ( ) const
Returns the script's base type.
### [Variant](class_variant#class-variant) get\_property\_default\_value ( [String](class_string#class-string) property )
Returns the default value of the specified property.
### [Dictionary](class_dictionary#class-dictionary) get\_script\_constant\_map ( )
Returns a dictionary containing constant names and their values.
### [Array](class_array#class-array) get\_script\_method\_list ( )
Returns the list of methods in this `Script`.
### [Array](class_array#class-array) get\_script\_property\_list ( )
Returns the list of properties in this `Script`.
### [Array](class_array#class-array) get\_script\_signal\_list ( )
Returns the list of user signals defined in this `Script`.
### [bool](class_bool#class-bool) has\_script\_signal ( [String](class_string#class-string) signal\_name ) const
Returns `true` if the script, or a base class, defines a signal with the given name.
### [bool](class_bool#class-bool) has\_source\_code ( ) const
Returns `true` if the script contains non-empty source code.
### [bool](class_bool#class-bool) instance\_has ( [Object](class_object#class-object) base\_object ) const
Returns `true` if `base_object` is an instance of this script.
### [bool](class_bool#class-bool) is\_tool ( ) const
Returns `true` if the script is a tool script. A tool script can run in the editor.
### [Error](class_%40globalscope#enum-globalscope-error) reload ( [bool](class_bool#class-bool) keep\_state=false )
Reloads the script's class implementation. Returns an error code.
godot VisualScriptExpression VisualScriptExpression
======================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A Visual Script node that can execute a custom expression.
Description
-----------
A Visual Script node that can execute a custom expression. Values can be provided for the input and the expression result can be retrieved from the output.
godot VisualScriptEmitSignal VisualScriptEmitSignal
======================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Emits a specified signal.
Description
-----------
Emits a specified signal when it is executed.
**Input Ports:**
* Sequence: `emit`
**Output Ports:**
* Sequence
Properties
----------
| | | |
| --- | --- | --- |
| [String](class_string#class-string) | [signal](#class-visualscriptemitsignal-property-signal) | `""` |
Property Descriptions
---------------------
### [String](class_string#class-string) signal
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_signal(value) |
| *Getter* | get\_signal() |
The signal to emit.
godot OpenSimplexNoise OpenSimplexNoise
================
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Noise generator based on Open Simplex.
Description
-----------
This resource allows you to configure and sample a fractal noise space. Here is a brief usage example that configures an OpenSimplexNoise and gets samples at various positions and dimensions:
```
var noise = OpenSimplexNoise.new()
# Configure
noise.seed = randi()
noise.octaves = 4
noise.period = 20.0
noise.persistence = 0.8
# Sample
print("Values:")
print(noise.get_noise_2d(1.0, 1.0))
print(noise.get_noise_3d(0.5, 3.0, 15.0))
print(noise.get_noise_4d(0.5, 1.9, 4.7, 0.0))
```
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [lacunarity](#class-opensimplexnoise-property-lacunarity) | `2.0` |
| [int](class_int#class-int) | [octaves](#class-opensimplexnoise-property-octaves) | `3` |
| [float](class_float#class-float) | [period](#class-opensimplexnoise-property-period) | `64.0` |
| [float](class_float#class-float) | [persistence](#class-opensimplexnoise-property-persistence) | `0.5` |
| [int](class_int#class-int) | [seed](#class-opensimplexnoise-property-seed) | `0` |
Methods
-------
| | |
| --- | --- |
| [Image](class_image#class-image) | [get\_image](#class-opensimplexnoise-method-get-image) **(** [int](class_int#class-int) width, [int](class_int#class-int) height, [Vector2](class_vector2#class-vector2) noise\_offset=Vector2( 0, 0 ) **)** const |
| [float](class_float#class-float) | [get\_noise\_1d](#class-opensimplexnoise-method-get-noise-1d) **(** [float](class_float#class-float) x **)** const |
| [float](class_float#class-float) | [get\_noise\_2d](#class-opensimplexnoise-method-get-noise-2d) **(** [float](class_float#class-float) x, [float](class_float#class-float) y **)** const |
| [float](class_float#class-float) | [get\_noise\_2dv](#class-opensimplexnoise-method-get-noise-2dv) **(** [Vector2](class_vector2#class-vector2) pos **)** const |
| [float](class_float#class-float) | [get\_noise\_3d](#class-opensimplexnoise-method-get-noise-3d) **(** [float](class_float#class-float) x, [float](class_float#class-float) y, [float](class_float#class-float) z **)** const |
| [float](class_float#class-float) | [get\_noise\_3dv](#class-opensimplexnoise-method-get-noise-3dv) **(** [Vector3](class_vector3#class-vector3) pos **)** const |
| [float](class_float#class-float) | [get\_noise\_4d](#class-opensimplexnoise-method-get-noise-4d) **(** [float](class_float#class-float) x, [float](class_float#class-float) y, [float](class_float#class-float) z, [float](class_float#class-float) w **)** const |
| [Image](class_image#class-image) | [get\_seamless\_image](#class-opensimplexnoise-method-get-seamless-image) **(** [int](class_int#class-int) size **)** const |
Property Descriptions
---------------------
### [float](class_float#class-float) lacunarity
| | |
| --- | --- |
| *Default* | `2.0` |
| *Setter* | set\_lacunarity(value) |
| *Getter* | get\_lacunarity() |
Difference in period between [octaves](#class-opensimplexnoise-property-octaves).
### [int](class_int#class-int) octaves
| | |
| --- | --- |
| *Default* | `3` |
| *Setter* | set\_octaves(value) |
| *Getter* | get\_octaves() |
Number of OpenSimplex noise layers that are sampled to get the fractal noise. Higher values result in more detailed noise but take more time to generate.
**Note:** The maximum allowed value is 9.
### [float](class_float#class-float) period
| | |
| --- | --- |
| *Default* | `64.0` |
| *Setter* | set\_period(value) |
| *Getter* | get\_period() |
Period of the base octave. A lower period results in a higher-frequency noise (more value changes across the same distance).
### [float](class_float#class-float) persistence
| | |
| --- | --- |
| *Default* | `0.5` |
| *Setter* | set\_persistence(value) |
| *Getter* | get\_persistence() |
Contribution factor of the different octaves. A `persistence` value of 1 means all the octaves have the same contribution, a value of 0.5 means each octave contributes half as much as the previous one.
### [int](class_int#class-int) seed
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_seed(value) |
| *Getter* | get\_seed() |
Seed used to generate random values, different seeds will generate different noise maps.
Method Descriptions
-------------------
### [Image](class_image#class-image) get\_image ( [int](class_int#class-int) width, [int](class_int#class-int) height, [Vector2](class_vector2#class-vector2) noise\_offset=Vector2( 0, 0 ) ) const
Generate a noise image in [Image.FORMAT\_L8](class_image#class-image-constant-format-l8) format with the requested `width` and `height`, based on the current noise parameters. If `noise_offset` is specified, then the offset value is used as the coordinates of the top-left corner of the generated noise.
### [float](class_float#class-float) get\_noise\_1d ( [float](class_float#class-float) x ) const
Returns the 1D noise value `[-1,1]` at the given x-coordinate.
**Note:** This method actually returns the 2D noise value `[-1,1]` with fixed y-coordinate value 0.0.
### [float](class_float#class-float) get\_noise\_2d ( [float](class_float#class-float) x, [float](class_float#class-float) y ) const
Returns the 2D noise value `[-1,1]` at the given position.
### [float](class_float#class-float) get\_noise\_2dv ( [Vector2](class_vector2#class-vector2) pos ) const
Returns the 2D noise value `[-1,1]` at the given position.
### [float](class_float#class-float) get\_noise\_3d ( [float](class_float#class-float) x, [float](class_float#class-float) y, [float](class_float#class-float) z ) const
Returns the 3D noise value `[-1,1]` at the given position.
### [float](class_float#class-float) get\_noise\_3dv ( [Vector3](class_vector3#class-vector3) pos ) const
Returns the 3D noise value `[-1,1]` at the given position.
### [float](class_float#class-float) get\_noise\_4d ( [float](class_float#class-float) x, [float](class_float#class-float) y, [float](class_float#class-float) z, [float](class_float#class-float) w ) const
Returns the 4D noise value `[-1,1]` at the given position.
### [Image](class_image#class-image) get\_seamless\_image ( [int](class_int#class-int) size ) const
Generate a tileable noise image in [Image.FORMAT\_L8](class_image#class-image-constant-format-l8) format, based on the current noise parameters. Generated seamless images are always square (`size` × `size`).
**Note:** Seamless noise has a lower contrast compared to non-seamless noise. This is due to the way noise uses higher dimensions for generating seamless noise.
| programming_docs |
godot Material Material
========
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [CanvasItemMaterial](class_canvasitemmaterial#class-canvasitemmaterial), [ParticlesMaterial](class_particlesmaterial#class-particlesmaterial), [ShaderMaterial](class_shadermaterial#class-shadermaterial), [SpatialMaterial](class_spatialmaterial#class-spatialmaterial)
Abstract base [Resource](class_resource#class-resource) for coloring and shading geometry.
Description
-----------
Material is a base [Resource](class_resource#class-resource) used for coloring and shading geometry. All materials inherit from it and almost all [VisualInstance](class_visualinstance#class-visualinstance) derived nodes carry a Material. A few flags and parameters are shared between all material types and are configured here.
Tutorials
---------
* [3D Material Testers Demo](https://godotengine.org/asset-library/asset/123)
* [Third Person Shooter Demo](https://godotengine.org/asset-library/asset/678)
Properties
----------
| | | |
| --- | --- | --- |
| [Material](#class-material) | [next\_pass](#class-material-property-next-pass) | |
| [int](class_int#class-int) | [render\_priority](#class-material-property-render-priority) | `0` |
Constants
---------
* **RENDER\_PRIORITY\_MAX** = **127** --- Maximum value for the [render\_priority](#class-material-property-render-priority) parameter.
* **RENDER\_PRIORITY\_MIN** = **-128** --- Minimum value for the [render\_priority](#class-material-property-render-priority) parameter.
Property Descriptions
---------------------
### [Material](#class-material) next\_pass
| | |
| --- | --- |
| *Setter* | set\_next\_pass(value) |
| *Getter* | get\_next\_pass() |
Sets the `Material` to be used for the next pass. This renders the object again using a different material.
**Note:** This only applies to [SpatialMaterial](class_spatialmaterial#class-spatialmaterial)s and [ShaderMaterial](class_shadermaterial#class-shadermaterial)s with type "Spatial".
### [int](class_int#class-int) render\_priority
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_render\_priority(value) |
| *Getter* | get\_render\_priority() |
Sets the render priority for transparent objects in 3D scenes. Higher priority objects will be sorted in front of lower priority objects.
**Note:** This only applies to sorting of transparent objects. This will not impact how transparent objects are sorted relative to opaque objects. This is because opaque objects are not sorted, while transparent objects are sorted from back to front (subject to priority).
godot Area2D Area2D
======
**Inherits:** [CollisionObject2D](class_collisionobject2d#class-collisionobject2d) **<** [Node2D](class_node2d#class-node2d) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
2D area for detection and physics and audio influence.
Description
-----------
2D area that detects [CollisionObject2D](class_collisionobject2d#class-collisionobject2d) nodes overlapping, entering, or exiting. Can also alter or override local physics parameters (gravity, damping) and route audio to a custom audio bus.
To give the area its shape, add a [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) or a [CollisionPolygon2D](class_collisionpolygon2d#class-collisionpolygon2d) node as a *direct* child (or add multiple such nodes as direct children) of the area.
**Warning:** See [ConcavePolygonShape2D](class_concavepolygonshape2d#class-concavepolygonshape2d) for a warning about possibly unexpected behavior when using that shape for an area.
Tutorials
---------
* [Using Area2D](https://docs.godotengine.org/en/3.5/tutorials/physics/using_area_2d.html)
* [2D Dodge The Creeps Demo](https://godotengine.org/asset-library/asset/515)
* [2D Pong Demo](https://godotengine.org/asset-library/asset/121)
* [2D Platformer Demo](https://godotengine.org/asset-library/asset/120)
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [angular\_damp](#class-area2d-property-angular-damp) | `1.0` |
| [String](class_string#class-string) | [audio\_bus\_name](#class-area2d-property-audio-bus-name) | `"Master"` |
| [bool](class_bool#class-bool) | [audio\_bus\_override](#class-area2d-property-audio-bus-override) | `false` |
| [float](class_float#class-float) | [gravity](#class-area2d-property-gravity) | `98.0` |
| [float](class_float#class-float) | [gravity\_distance\_scale](#class-area2d-property-gravity-distance-scale) | `0.0` |
| [bool](class_bool#class-bool) | [gravity\_point](#class-area2d-property-gravity-point) | `false` |
| [Vector2](class_vector2#class-vector2) | [gravity\_vec](#class-area2d-property-gravity-vec) | `Vector2( 0, 1 )` |
| [float](class_float#class-float) | [linear\_damp](#class-area2d-property-linear-damp) | `0.1` |
| [bool](class_bool#class-bool) | [monitorable](#class-area2d-property-monitorable) | `true` |
| [bool](class_bool#class-bool) | [monitoring](#class-area2d-property-monitoring) | `true` |
| [float](class_float#class-float) | [priority](#class-area2d-property-priority) | `0.0` |
| [SpaceOverride](#enum-area2d-spaceoverride) | [space\_override](#class-area2d-property-space-override) | `0` |
Methods
-------
| | |
| --- | --- |
| [Array](class_array#class-array) | [get\_overlapping\_areas](#class-area2d-method-get-overlapping-areas) **(** **)** const |
| [Array](class_array#class-array) | [get\_overlapping\_bodies](#class-area2d-method-get-overlapping-bodies) **(** **)** const |
| [bool](class_bool#class-bool) | [overlaps\_area](#class-area2d-method-overlaps-area) **(** [Node](class_node#class-node) area **)** const |
| [bool](class_bool#class-bool) | [overlaps\_body](#class-area2d-method-overlaps-body) **(** [Node](class_node#class-node) body **)** const |
Signals
-------
### area\_entered ( [Area2D](#class-area2d) area )
Emitted when another Area2D enters this Area2D. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`.
`area` the other Area2D.
### area\_exited ( [Area2D](#class-area2d) area )
Emitted when another Area2D exits this Area2D. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`.
`area` the other Area2D.
### area\_shape\_entered ( [RID](class_rid#class-rid) area\_rid, [Area2D](#class-area2d) area, [int](class_int#class-int) area\_shape\_index, [int](class_int#class-int) local\_shape\_index )
Emitted when one of another Area2D's [Shape2D](class_shape2d#class-shape2d)s enters one of this Area2D's [Shape2D](class_shape2d#class-shape2d)s. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`.
`area_rid` the [RID](class_rid#class-rid) of the other Area2D's [CollisionObject2D](class_collisionobject2d#class-collisionobject2d) used by the [Physics2DServer](class_physics2dserver#class-physics2dserver).
`area` the other Area2D.
`area_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of the other Area2D used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `area.shape_owner_get_owner(area_shape_index)`.
`local_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of this Area2D used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `self.shape_owner_get_owner(local_shape_index)`.
### area\_shape\_exited ( [RID](class_rid#class-rid) area\_rid, [Area2D](#class-area2d) area, [int](class_int#class-int) area\_shape\_index, [int](class_int#class-int) local\_shape\_index )
Emitted when one of another Area2D's [Shape2D](class_shape2d#class-shape2d)s exits one of this Area2D's [Shape2D](class_shape2d#class-shape2d)s. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`.
`area_rid` the [RID](class_rid#class-rid) of the other Area2D's [CollisionObject2D](class_collisionobject2d#class-collisionobject2d) used by the [Physics2DServer](class_physics2dserver#class-physics2dserver).
`area` the other Area2D.
`area_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of the other Area2D used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `area.shape_owner_get_owner(area_shape_index)`.
`local_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of this Area2D used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `self.shape_owner_get_owner(local_shape_index)`.
### body\_entered ( [Node](class_node#class-node) body )
Emitted when a [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap) enters this Area2D. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`. [TileMap](class_tilemap#class-tilemap)s are detected if the [TileSet](class_tileset#class-tileset) has Collision [Shape2D](class_shape2d#class-shape2d)s.
`body` the [Node](class_node#class-node), if it exists in the tree, of the other [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap).
### body\_exited ( [Node](class_node#class-node) body )
Emitted when a [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap) exits this Area2D. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`. [TileMap](class_tilemap#class-tilemap)s are detected if the [TileSet](class_tileset#class-tileset) has Collision [Shape2D](class_shape2d#class-shape2d)s.
`body` the [Node](class_node#class-node), if it exists in the tree, of the other [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap).
### body\_shape\_entered ( [RID](class_rid#class-rid) body\_rid, [Node](class_node#class-node) body, [int](class_int#class-int) body\_shape\_index, [int](class_int#class-int) local\_shape\_index )
Emitted when one of a [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap)'s [Shape2D](class_shape2d#class-shape2d)s enters one of this Area2D's [Shape2D](class_shape2d#class-shape2d)s. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`. [TileMap](class_tilemap#class-tilemap)s are detected if the [TileSet](class_tileset#class-tileset) has Collision [Shape2D](class_shape2d#class-shape2d)s.
`body_rid` the [RID](class_rid#class-rid) of the [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileSet](class_tileset#class-tileset)'s [CollisionObject2D](class_collisionobject2d#class-collisionobject2d) used by the [Physics2DServer](class_physics2dserver#class-physics2dserver).
`body` the [Node](class_node#class-node), if it exists in the tree, of the [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap).
`body_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of the [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap) used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `body.shape_owner_get_owner(body_shape_index)`.
`local_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of this Area2D used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `self.shape_owner_get_owner(local_shape_index)`.
### body\_shape\_exited ( [RID](class_rid#class-rid) body\_rid, [Node](class_node#class-node) body, [int](class_int#class-int) body\_shape\_index, [int](class_int#class-int) local\_shape\_index )
Emitted when one of a [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap)'s [Shape2D](class_shape2d#class-shape2d)s exits one of this Area2D's [Shape2D](class_shape2d#class-shape2d)s. Requires [monitoring](#class-area2d-property-monitoring) to be set to `true`. [TileMap](class_tilemap#class-tilemap)s are detected if the [TileSet](class_tileset#class-tileset) has Collision [Shape2D](class_shape2d#class-shape2d)s.
`body_rid` the [RID](class_rid#class-rid) of the [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileSet](class_tileset#class-tileset)'s [CollisionObject2D](class_collisionobject2d#class-collisionobject2d) used by the [Physics2DServer](class_physics2dserver#class-physics2dserver).
`body` the [Node](class_node#class-node), if it exists in the tree, of the [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap).
`body_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of the [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or [TileMap](class_tilemap#class-tilemap) used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `body.shape_owner_get_owner(body_shape_index)`.
`local_shape_index` the index of the [Shape2D](class_shape2d#class-shape2d) of this Area2D used by the [Physics2DServer](class_physics2dserver#class-physics2dserver). Get the [CollisionShape2D](class_collisionshape2d#class-collisionshape2d) node with `self.shape_owner_get_owner(local_shape_index)`.
Enumerations
------------
enum **SpaceOverride**:
* **SPACE\_OVERRIDE\_DISABLED** = **0** --- This area does not affect gravity/damping.
* **SPACE\_OVERRIDE\_COMBINE** = **1** --- This area adds its gravity/damping values to whatever has been calculated so far (in [priority](#class-area2d-property-priority) order).
* **SPACE\_OVERRIDE\_COMBINE\_REPLACE** = **2** --- This area adds its gravity/damping values to whatever has been calculated so far (in [priority](#class-area2d-property-priority) order), ignoring any lower priority areas.
* **SPACE\_OVERRIDE\_REPLACE** = **3** --- This area replaces any gravity/damping, even the defaults, ignoring any lower priority areas.
* **SPACE\_OVERRIDE\_REPLACE\_COMBINE** = **4** --- This area replaces any gravity/damping calculated so far (in [priority](#class-area2d-property-priority) order), but keeps calculating the rest of the areas.
Property Descriptions
---------------------
### [float](class_float#class-float) angular\_damp
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_angular\_damp(value) |
| *Getter* | get\_angular\_damp() |
The rate at which objects stop spinning in this area. Represents the angular velocity lost per second.
See [ProjectSettings.physics/2d/default\_angular\_damp](class_projectsettings#class-projectsettings-property-physics-2d-default-angular-damp) for more details about damping.
### [String](class_string#class-string) audio\_bus\_name
| | |
| --- | --- |
| *Default* | `"Master"` |
| *Setter* | set\_audio\_bus\_name(value) |
| *Getter* | get\_audio\_bus\_name() |
The name of the area's audio bus.
### [bool](class_bool#class-bool) audio\_bus\_override
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_audio\_bus\_override(value) |
| *Getter* | is\_overriding\_audio\_bus() |
If `true`, the area's audio bus overrides the default audio bus.
### [float](class_float#class-float) gravity
| | |
| --- | --- |
| *Default* | `98.0` |
| *Setter* | set\_gravity(value) |
| *Getter* | get\_gravity() |
The area's gravity intensity (in pixels per second squared). This value multiplies the gravity vector. This is useful to alter the force of gravity without altering its direction.
### [float](class_float#class-float) gravity\_distance\_scale
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_gravity\_distance\_scale(value) |
| *Getter* | get\_gravity\_distance\_scale() |
The falloff factor for point gravity. The greater the value, the faster gravity decreases with distance.
### [bool](class_bool#class-bool) gravity\_point
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_gravity\_is\_point(value) |
| *Getter* | is\_gravity\_a\_point() |
If `true`, gravity is calculated from a point (set via [gravity\_vec](#class-area2d-property-gravity-vec)). See also [space\_override](#class-area2d-property-space-override).
### [Vector2](class_vector2#class-vector2) gravity\_vec
| | |
| --- | --- |
| *Default* | `Vector2( 0, 1 )` |
| *Setter* | set\_gravity\_vector(value) |
| *Getter* | get\_gravity\_vector() |
The area's gravity vector (not normalized). If gravity is a point (see [gravity\_point](#class-area2d-property-gravity-point)), this will be the point of attraction.
### [float](class_float#class-float) linear\_damp
| | |
| --- | --- |
| *Default* | `0.1` |
| *Setter* | set\_linear\_damp(value) |
| *Getter* | get\_linear\_damp() |
The rate at which objects stop moving in this area. Represents the linear velocity lost per second.
See [ProjectSettings.physics/2d/default\_linear\_damp](class_projectsettings#class-projectsettings-property-physics-2d-default-linear-damp) for more details about damping.
### [bool](class_bool#class-bool) monitorable
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_monitorable(value) |
| *Getter* | is\_monitorable() |
If `true`, other monitoring areas can detect this area.
### [bool](class_bool#class-bool) monitoring
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_monitoring(value) |
| *Getter* | is\_monitoring() |
If `true`, the area detects bodies or areas entering and exiting it.
### [float](class_float#class-float) priority
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_priority(value) |
| *Getter* | get\_priority() |
The area's priority. Higher priority areas are processed first.
### [SpaceOverride](#enum-area2d-spaceoverride) space\_override
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_space\_override\_mode(value) |
| *Getter* | get\_space\_override\_mode() |
Override mode for gravity and damping calculations within this area. See [SpaceOverride](#enum-area2d-spaceoverride) for possible values.
Method Descriptions
-------------------
### [Array](class_array#class-array) get\_overlapping\_areas ( ) const
Returns a list of intersecting `Area2D`s. The overlapping area's [CollisionObject2D.collision\_layer](class_collisionobject2d#class-collisionobject2d-property-collision-layer) must be part of this area's [CollisionObject2D.collision\_mask](class_collisionobject2d#class-collisionobject2d-property-collision-mask) in order to be detected.
For performance reasons (collisions are all processed at the same time) this list is modified once during the physics step, not immediately after objects are moved. Consider using signals instead.
### [Array](class_array#class-array) get\_overlapping\_bodies ( ) const
Returns a list of intersecting [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d)s. The overlapping body's [CollisionObject2D.collision\_layer](class_collisionobject2d#class-collisionobject2d-property-collision-layer) must be part of this area's [CollisionObject2D.collision\_mask](class_collisionobject2d#class-collisionobject2d-property-collision-mask) in order to be detected.
For performance reasons (collisions are all processed at the same time) this list is modified once during the physics step, not immediately after objects are moved. Consider using signals instead.
### [bool](class_bool#class-bool) overlaps\_area ( [Node](class_node#class-node) area ) const
If `true`, the given area overlaps the Area2D.
**Note:** The result of this test is not immediate after moving objects. For performance, the list of overlaps is updated once per frame and before the physics step. Consider using signals instead.
### [bool](class_bool#class-bool) overlaps\_body ( [Node](class_node#class-node) body ) const
If `true`, the given physics body overlaps the Area2D.
**Note:** The result of this test is not immediate after moving objects. For performance, list of overlaps is updated once per frame and before the physics step. Consider using signals instead.
The `body` argument can either be a [PhysicsBody2D](class_physicsbody2d#class-physicsbody2d) or a [TileMap](class_tilemap#class-tilemap) instance (while TileMaps are not physics bodies themselves, they register their tiles with collision shapes as a virtual physics body).
| programming_docs |
godot GDScriptFunctionState GDScriptFunctionState
=====================
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
State of a function call after yielding.
Description
-----------
Calling [@GDScript.yield](class_%40gdscript#class-gdscript-method-yield) within a function will cause that function to yield and return its current state as an object of this type. The yielded function call can then be resumed later by calling [resume](#class-gdscriptfunctionstate-method-resume) on this state object.
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [is\_valid](#class-gdscriptfunctionstate-method-is-valid) **(** [bool](class_bool#class-bool) extended\_check=false **)** const |
| [Variant](class_variant#class-variant) | [resume](#class-gdscriptfunctionstate-method-resume) **(** [Variant](class_variant#class-variant) arg=null **)** |
Signals
-------
### completed ( [Variant](class_variant#class-variant) result )
Method Descriptions
-------------------
### [bool](class_bool#class-bool) is\_valid ( [bool](class_bool#class-bool) extended\_check=false ) const
Check whether the function call may be resumed. This is not the case if the function state was already resumed.
If `extended_check` is enabled, it also checks if the associated script and object still exist. The extended check is done in debug mode as part of [resume](#class-gdscriptfunctionstate-method-resume), but you can use this if you know you may be trying to resume without knowing for sure the object and/or script have survived up to that point.
### [Variant](class_variant#class-variant) resume ( [Variant](class_variant#class-variant) arg=null )
Resume execution of the yielded function call.
If handed an argument, return the argument from the [@GDScript.yield](class_%40gdscript#class-gdscript-method-yield) call in the yielded function call. You can pass e.g. an [Array](class_array#class-array) to hand multiple arguments.
This function returns what the resumed function call returns, possibly another function state if yielded again.
godot AABB AABB
====
Axis-Aligned Bounding Box.
Description
-----------
`AABB` consists of a position, a size, and several utility functions. It is typically used for fast overlap tests.
It uses floating-point coordinates. The 2D counterpart to `AABB` is [Rect2](class_rect2#class-rect2).
**Note:** Unlike [Rect2](class_rect2#class-rect2), `AABB` does not have a variant that uses integer coordinates.
Tutorials
---------
* [Math tutorial index](https://docs.godotengine.org/en/3.5/tutorials/math/index.html)
* [Vector math](https://docs.godotengine.org/en/3.5/tutorials/math/vector_math.html)
* [Advanced vector math](https://docs.godotengine.org/en/3.5/tutorials/math/vectors_advanced.html)
Properties
----------
| | | |
| --- | --- | --- |
| [Vector3](class_vector3#class-vector3) | [end](#class-aabb-property-end) | `Vector3( 0, 0, 0 )` |
| [Vector3](class_vector3#class-vector3) | [position](#class-aabb-property-position) | `Vector3( 0, 0, 0 )` |
| [Vector3](class_vector3#class-vector3) | [size](#class-aabb-property-size) | `Vector3( 0, 0, 0 )` |
Methods
-------
| | |
| --- | --- |
| [AABB](#class-aabb) | [AABB](#class-aabb-method-aabb) **(** [Vector3](class_vector3#class-vector3) position, [Vector3](class_vector3#class-vector3) size **)** |
| [AABB](#class-aabb) | [abs](#class-aabb-method-abs) **(** **)** |
| [bool](class_bool#class-bool) | [encloses](#class-aabb-method-encloses) **(** [AABB](#class-aabb) with **)** |
| [AABB](#class-aabb) | [expand](#class-aabb-method-expand) **(** [Vector3](class_vector3#class-vector3) to\_point **)** |
| [float](class_float#class-float) | [get\_area](#class-aabb-method-get-area) **(** **)** |
| [Vector3](class_vector3#class-vector3) | [get\_center](#class-aabb-method-get-center) **(** **)** |
| [Vector3](class_vector3#class-vector3) | [get\_endpoint](#class-aabb-method-get-endpoint) **(** [int](class_int#class-int) idx **)** |
| [Vector3](class_vector3#class-vector3) | [get\_longest\_axis](#class-aabb-method-get-longest-axis) **(** **)** |
| [int](class_int#class-int) | [get\_longest\_axis\_index](#class-aabb-method-get-longest-axis-index) **(** **)** |
| [float](class_float#class-float) | [get\_longest\_axis\_size](#class-aabb-method-get-longest-axis-size) **(** **)** |
| [Vector3](class_vector3#class-vector3) | [get\_shortest\_axis](#class-aabb-method-get-shortest-axis) **(** **)** |
| [int](class_int#class-int) | [get\_shortest\_axis\_index](#class-aabb-method-get-shortest-axis-index) **(** **)** |
| [float](class_float#class-float) | [get\_shortest\_axis\_size](#class-aabb-method-get-shortest-axis-size) **(** **)** |
| [Vector3](class_vector3#class-vector3) | [get\_support](#class-aabb-method-get-support) **(** [Vector3](class_vector3#class-vector3) dir **)** |
| [AABB](#class-aabb) | [grow](#class-aabb-method-grow) **(** [float](class_float#class-float) by **)** |
| [bool](class_bool#class-bool) | [has\_no\_area](#class-aabb-method-has-no-area) **(** **)** |
| [bool](class_bool#class-bool) | [has\_no\_surface](#class-aabb-method-has-no-surface) **(** **)** |
| [bool](class_bool#class-bool) | [has\_point](#class-aabb-method-has-point) **(** [Vector3](class_vector3#class-vector3) point **)** |
| [AABB](#class-aabb) | [intersection](#class-aabb-method-intersection) **(** [AABB](#class-aabb) with **)** |
| [bool](class_bool#class-bool) | [intersects](#class-aabb-method-intersects) **(** [AABB](#class-aabb) with **)** |
| [bool](class_bool#class-bool) | [intersects\_plane](#class-aabb-method-intersects-plane) **(** [Plane](class_plane#class-plane) plane **)** |
| [bool](class_bool#class-bool) | [intersects\_segment](#class-aabb-method-intersects-segment) **(** [Vector3](class_vector3#class-vector3) from, [Vector3](class_vector3#class-vector3) to **)** |
| [bool](class_bool#class-bool) | [is\_equal\_approx](#class-aabb-method-is-equal-approx) **(** [AABB](#class-aabb) aabb **)** |
| [AABB](#class-aabb) | [merge](#class-aabb-method-merge) **(** [AABB](#class-aabb) with **)** |
Property Descriptions
---------------------
### [Vector3](class_vector3#class-vector3) end
| | |
| --- | --- |
| *Default* | `Vector3( 0, 0, 0 )` |
Ending corner. This is calculated as `position + size`. Setting this value will change the size.
### [Vector3](class_vector3#class-vector3) position
| | |
| --- | --- |
| *Default* | `Vector3( 0, 0, 0 )` |
Beginning corner. Typically has values lower than [end](#class-aabb-property-end).
### [Vector3](class_vector3#class-vector3) size
| | |
| --- | --- |
| *Default* | `Vector3( 0, 0, 0 )` |
Size from [position](#class-aabb-property-position) to [end](#class-aabb-property-end). Typically, all components are positive.
If the size is negative, you can use [abs](#class-aabb-method-abs) to fix it.
Method Descriptions
-------------------
### [AABB](#class-aabb) AABB ( [Vector3](class_vector3#class-vector3) position, [Vector3](class_vector3#class-vector3) size )
Constructs an `AABB` from a position and size.
### [AABB](#class-aabb) abs ( )
Returns an AABB with equivalent position and size, modified so that the most-negative corner is the origin and the size is positive.
### [bool](class_bool#class-bool) encloses ( [AABB](#class-aabb) with )
Returns `true` if this `AABB` completely encloses another one.
### [AABB](#class-aabb) expand ( [Vector3](class_vector3#class-vector3) to\_point )
Returns a copy of this `AABB` expanded to include a given point.
**Example:**
```
# position (-3, 2, 0), size (1, 1, 1)
var box = AABB(Vector3(-3, 2, 0), Vector3(1, 1, 1))
# position (-3, -1, 0), size (3, 4, 2), so we fit both the original AABB and Vector3(0, -1, 2)
var box2 = box.expand(Vector3(0, -1, 2))
```
### [float](class_float#class-float) get\_area ( )
Returns the volume of the `AABB`.
### [Vector3](class_vector3#class-vector3) get\_center ( )
Returns the center of the `AABB`, which is equal to [position](#class-aabb-property-position) + ([size](#class-aabb-property-size) / 2).
### [Vector3](class_vector3#class-vector3) get\_endpoint ( [int](class_int#class-int) idx )
Gets the position of the 8 endpoints of the `AABB` in space.
### [Vector3](class_vector3#class-vector3) get\_longest\_axis ( )
Returns the normalized longest axis of the `AABB`.
### [int](class_int#class-int) get\_longest\_axis\_index ( )
Returns the index of the longest axis of the `AABB` (according to [Vector3](class_vector3#class-vector3)'s `AXIS_*` constants).
### [float](class_float#class-float) get\_longest\_axis\_size ( )
Returns the scalar length of the longest axis of the `AABB`.
### [Vector3](class_vector3#class-vector3) get\_shortest\_axis ( )
Returns the normalized shortest axis of the `AABB`.
### [int](class_int#class-int) get\_shortest\_axis\_index ( )
Returns the index of the shortest axis of the `AABB` (according to [Vector3](class_vector3#class-vector3)::AXIS\* enum).
### [float](class_float#class-float) get\_shortest\_axis\_size ( )
Returns the scalar length of the shortest axis of the `AABB`.
### [Vector3](class_vector3#class-vector3) get\_support ( [Vector3](class_vector3#class-vector3) dir )
Returns the support point in a given direction. This is useful for collision detection algorithms.
### [AABB](#class-aabb) grow ( [float](class_float#class-float) by )
Returns a copy of the `AABB` grown a given amount of units towards all the sides.
### [bool](class_bool#class-bool) has\_no\_area ( )
Returns `true` if the `AABB` is flat or empty.
### [bool](class_bool#class-bool) has\_no\_surface ( )
Returns `true` if the `AABB` is empty.
### [bool](class_bool#class-bool) has\_point ( [Vector3](class_vector3#class-vector3) point )
Returns `true` if the `AABB` contains a point.
### [AABB](#class-aabb) intersection ( [AABB](#class-aabb) with )
Returns the intersection between two `AABB`. An empty AABB (size 0,0,0) is returned on failure.
### [bool](class_bool#class-bool) intersects ( [AABB](#class-aabb) with )
Returns `true` if the `AABB` overlaps with another.
### [bool](class_bool#class-bool) intersects\_plane ( [Plane](class_plane#class-plane) plane )
Returns `true` if the `AABB` is on both sides of a plane.
### [bool](class_bool#class-bool) intersects\_segment ( [Vector3](class_vector3#class-vector3) from, [Vector3](class_vector3#class-vector3) to )
Returns `true` if the `AABB` intersects the line segment between `from` and `to`.
### [bool](class_bool#class-bool) is\_equal\_approx ( [AABB](#class-aabb) aabb )
Returns `true` if this `AABB` and `aabb` are approximately equal, by calling [@GDScript.is\_equal\_approx](class_%40gdscript#class-gdscript-method-is-equal-approx) on each component.
### [AABB](#class-aabb) merge ( [AABB](#class-aabb) with )
Returns a larger `AABB` that contains both this `AABB` and `with`.
godot VisualScriptPropertyGet VisualScriptPropertyGet
=======================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A Visual Script node returning a value of a property from an [Object](class_object#class-object).
Description
-----------
`VisualScriptPropertyGet` can return a value of any property from the current object or other objects.
Properties
----------
| | | |
| --- | --- | --- |
| [String](class_string#class-string) | [base\_script](#class-visualscriptpropertyget-property-base-script) | |
| [String](class_string#class-string) | [base\_type](#class-visualscriptpropertyget-property-base-type) | `"Object"` |
| [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) | [basic\_type](#class-visualscriptpropertyget-property-basic-type) | |
| [String](class_string#class-string) | [index](#class-visualscriptpropertyget-property-index) | |
| [NodePath](class_nodepath#class-nodepath) | [node\_path](#class-visualscriptpropertyget-property-node-path) | |
| [String](class_string#class-string) | [property](#class-visualscriptpropertyget-property-property) | `""` |
| [CallMode](#enum-visualscriptpropertyget-callmode) | [set\_mode](#class-visualscriptpropertyget-property-set-mode) | `0` |
Enumerations
------------
enum **CallMode**:
* **CALL\_MODE\_SELF** = **0** --- The property will be retrieved from this [Object](class_object#class-object).
* **CALL\_MODE\_NODE\_PATH** = **1** --- The property will be retrieved from the given [Node](class_node#class-node) in the scene tree.
* **CALL\_MODE\_INSTANCE** = **2** --- The property will be retrieved from an instanced node with the given type and script.
* **CALL\_MODE\_BASIC\_TYPE** = **3** --- The property will be retrieved from a GDScript basic type (e.g. [Vector2](class_vector2#class-vector2)).
Property Descriptions
---------------------
### [String](class_string#class-string) base\_script
| | |
| --- | --- |
| *Setter* | set\_base\_script(value) |
| *Getter* | get\_base\_script() |
The script to be used when [set\_mode](#class-visualscriptpropertyget-property-set-mode) is set to [CALL\_MODE\_INSTANCE](#class-visualscriptpropertyget-constant-call-mode-instance).
### [String](class_string#class-string) base\_type
| | |
| --- | --- |
| *Default* | `"Object"` |
| *Setter* | set\_base\_type(value) |
| *Getter* | get\_base\_type() |
The base type to be used when [set\_mode](#class-visualscriptpropertyget-property-set-mode) is set to [CALL\_MODE\_INSTANCE](#class-visualscriptpropertyget-constant-call-mode-instance).
### [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) basic\_type
| | |
| --- | --- |
| *Setter* | set\_basic\_type(value) |
| *Getter* | get\_basic\_type() |
The type to be used when [set\_mode](#class-visualscriptpropertyget-property-set-mode) is set to [CALL\_MODE\_BASIC\_TYPE](#class-visualscriptpropertyget-constant-call-mode-basic-type).
### [String](class_string#class-string) index
| | |
| --- | --- |
| *Setter* | set\_index(value) |
| *Getter* | get\_index() |
The indexed name of the property to retrieve. See [Object.get\_indexed](class_object#class-object-method-get-indexed) for details.
### [NodePath](class_nodepath#class-nodepath) node\_path
| | |
| --- | --- |
| *Setter* | set\_base\_path(value) |
| *Getter* | get\_base\_path() |
The node path to use when [set\_mode](#class-visualscriptpropertyget-property-set-mode) is set to [CALL\_MODE\_NODE\_PATH](#class-visualscriptpropertyget-constant-call-mode-node-path).
### [String](class_string#class-string) property
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_property(value) |
| *Getter* | get\_property() |
The name of the property to retrieve. Changing this will clear [index](#class-visualscriptpropertyget-property-index).
### [CallMode](#enum-visualscriptpropertyget-callmode) set\_mode
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_call\_mode(value) |
| *Getter* | get\_call\_mode() |
`set_mode` determines the target object from which the property will be retrieved. See [CallMode](#enum-visualscriptpropertyget-callmode) for options.
godot NavigationMeshGenerator NavigationMeshGenerator
=======================
**Inherits:** [Object](class_object#class-object)
Helper class for creating and clearing navigation meshes.
Description
-----------
This class is responsible for creating and clearing 3D navigation meshes used as [NavigationMesh](class_navigationmesh#class-navigationmesh) resources inside [NavigationMeshInstance](class_navigationmeshinstance#class-navigationmeshinstance). The `NavigationMeshGenerator` has very limited to no use for 2D as the navigation mesh baking process expects 3D node types and 3D source geometry to parse.
The entire navigation mesh baking is best done in a separate thread as the voxelization, collision tests and mesh optimization steps involved are very performance and time hungry operations.
Navigation mesh baking happens in multiple steps and the result depends on 3D source geometry and properties of the [NavigationMesh](class_navigationmesh#class-navigationmesh) resource. In the first step, starting from a root node and depending on [NavigationMesh](class_navigationmesh#class-navigationmesh) properties all valid 3D source geometry nodes are collected from the [SceneTree](class_scenetree#class-scenetree). Second, all collected nodes are parsed for their relevant 3D geometry data and a combined 3D mesh is build. Due to the many different types of parsable objects, from normal [MeshInstance](class_meshinstance#class-meshinstance)s to [CSGShape](class_csgshape#class-csgshape)s or various [CollisionObject](class_collisionobject#class-collisionobject)s, some operations to collect geometry data can trigger [VisualServer](class_visualserver#class-visualserver) and [PhysicsServer](class_physicsserver#class-physicsserver) synchronizations. Server synchronization can have a negative effect on baking time or framerate as it often involves [Mutex](class_mutex#class-mutex) locking for thread security. Many parsable objects and the continuous synchronization with other threaded Servers can increase the baking time significantly. On the other hand only a few but very large and complex objects will take some time to prepare for the Servers which can noticeably stall the next frame render. As a general rule the total amount of parsable objects and their individual size and complexity should be balanced to avoid framerate issues or very long baking times. The combined mesh is then passed to the Recast Navigation Object to test the source geometry for walkable terrain suitable to [NavigationMesh](class_navigationmesh#class-navigationmesh) agent properties by creating a voxel world around the meshes bounding area.
The finalized navigation mesh is then returned and stored inside the [NavigationMesh](class_navigationmesh#class-navigationmesh) for use as a resource inside [NavigationMeshInstance](class_navigationmeshinstance#class-navigationmeshinstance) nodes.
**Note:** Using meshes to not only define walkable surfaces but also obstruct navigation baking does not always work. The navigation baking has no concept of what is a geometry "inside" when dealing with mesh source geometry and this is intentional. Depending on current baking parameters, as soon as the obstructing mesh is large enough to fit a navigation mesh area inside, the baking will generate navigation mesh areas that are inside the obstructing source geometry mesh.
Methods
-------
| | |
| --- | --- |
| void | [bake](#class-navigationmeshgenerator-method-bake) **(** [NavigationMesh](class_navigationmesh#class-navigationmesh) nav\_mesh, [Node](class_node#class-node) root\_node **)** |
| void | [clear](#class-navigationmeshgenerator-method-clear) **(** [NavigationMesh](class_navigationmesh#class-navigationmesh) nav\_mesh **)** |
Method Descriptions
-------------------
### void bake ( [NavigationMesh](class_navigationmesh#class-navigationmesh) nav\_mesh, [Node](class_node#class-node) root\_node )
Bakes navigation data to the provided `nav_mesh` by parsing child nodes under the provided `root_node` or a specific group of nodes for potential source geometry. The parse behavior can be controlled with the [NavigationMesh.geometry\_parsed\_geometry\_type](class_navigationmesh#class-navigationmesh-property-geometry-parsed-geometry-type) and [NavigationMesh.geometry\_source\_geometry\_mode](class_navigationmesh#class-navigationmesh-property-geometry-source-geometry-mode) properties on the [NavigationMesh](class_navigationmesh#class-navigationmesh) resource.
### void clear ( [NavigationMesh](class_navigationmesh#class-navigationmesh) nav\_mesh )
Removes all polygons and vertices from the provided `nav_mesh` resource.
| programming_docs |
godot Texture3D Texture3D
=========
**Inherits:** [TextureLayered](class_texturelayered#class-texturelayered) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Texture with 3 dimensions.
Description
-----------
Texture3D is a 3-dimensional [Texture](class_texture#class-texture) that has a width, height, and depth. See also [TextureArray](class_texturearray#class-texturearray).
**Note:** `Texture3D`s can only be sampled in shaders in the GLES3 backend. In GLES2, their data can be accessed via scripting, but there is no way to render them in a hardware-accelerated manner.
Properties
----------
| | | |
| --- | --- | --- |
| [Dictionary](class_dictionary#class-dictionary) | data | `{"depth": 0,"flags": 4,"format": 37,"height": 0,"layers": [ ],"width": 0}` (overrides [TextureLayered](class_texturelayered#class-texturelayered-property-data)) |
| [int](class_int#class-int) | flags | `4` (overrides [TextureLayered](class_texturelayered#class-texturelayered-property-flags)) |
Methods
-------
| | |
| --- | --- |
| void | [create](#class-texture3d-method-create) **(** [int](class_int#class-int) width, [int](class_int#class-int) height, [int](class_int#class-int) depth, [Format](class_image#enum-image-format) format, [int](class_int#class-int) flags=4 **)** |
Method Descriptions
-------------------
### void create ( [int](class_int#class-int) width, [int](class_int#class-int) height, [int](class_int#class-int) depth, [Format](class_image#enum-image-format) format, [int](class_int#class-int) flags=4 )
Creates the Texture3D with specified `width`, `height`, and `depth`. See [Format](class_image#enum-image-format) for `format` options. See [Flags](class_texturelayered#enum-texturelayered-flags) enumerator for `flags` options.
godot AudioEffectEQ AudioEffectEQ
=============
**Inherits:** [AudioEffect](class_audioeffect#class-audioeffect) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [AudioEffectEQ10](class_audioeffecteq10#class-audioeffecteq10), [AudioEffectEQ21](class_audioeffecteq21#class-audioeffecteq21), [AudioEffectEQ6](class_audioeffecteq6#class-audioeffecteq6)
Base class for audio equalizers. Gives you control over frequencies.
Use it to create a custom equalizer if [AudioEffectEQ6](class_audioeffecteq6#class-audioeffecteq6), [AudioEffectEQ10](class_audioeffecteq10#class-audioeffecteq10) or [AudioEffectEQ21](class_audioeffecteq21#class-audioeffecteq21) don't fit your needs.
Description
-----------
AudioEffectEQ gives you control over frequencies. Use it to compensate for existing deficiencies in audio. AudioEffectEQs are useful on the Master bus to completely master a mix and give it more character. They are also useful when a game is run on a mobile device, to adjust the mix to that kind of speakers (it can be added but disabled when headphones are plugged).
Methods
-------
| | |
| --- | --- |
| [int](class_int#class-int) | [get\_band\_count](#class-audioeffecteq-method-get-band-count) **(** **)** const |
| [float](class_float#class-float) | [get\_band\_gain\_db](#class-audioeffecteq-method-get-band-gain-db) **(** [int](class_int#class-int) band\_idx **)** const |
| void | [set\_band\_gain\_db](#class-audioeffecteq-method-set-band-gain-db) **(** [int](class_int#class-int) band\_idx, [float](class_float#class-float) volume\_db **)** |
Method Descriptions
-------------------
### [int](class_int#class-int) get\_band\_count ( ) const
Returns the number of bands of the equalizer.
### [float](class_float#class-float) get\_band\_gain\_db ( [int](class_int#class-int) band\_idx ) const
Returns the band's gain at the specified index, in dB.
### void set\_band\_gain\_db ( [int](class_int#class-int) band\_idx, [float](class_float#class-float) volume\_db )
Sets band's gain at the specified index, in dB.
godot Crypto Crypto
======
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Access to advanced cryptographic functionalities.
Description
-----------
The Crypto class allows you to access some more advanced cryptographic functionalities in Godot.
For now, this includes generating cryptographically secure random bytes, RSA keys and self-signed X509 certificates generation, asymmetric key encryption/decryption, and signing/verification.
```
extends Node
var crypto = Crypto.new()
var key = CryptoKey.new()
var cert = X509Certificate.new()
func _ready():
# Generate new RSA key.
key = crypto.generate_rsa(4096)
# Generate new self-signed certificate with the given key.
cert = crypto.generate_self_signed_certificate(key, "CN=mydomain.com,O=My Game Company,C=IT")
# Save key and certificate in the user folder.
key.save("user://generated.key")
cert.save("user://generated.crt")
# Encryption
var data = "Some data"
var encrypted = crypto.encrypt(key, data.to_utf8())
# Decryption
var decrypted = crypto.decrypt(key, encrypted)
# Signing
var signature = crypto.sign(HashingContext.HASH_SHA256, data.sha256_buffer(), key)
# Verifying
var verified = crypto.verify(HashingContext.HASH_SHA256, data.sha256_buffer(), signature, key)
# Checks
assert(verified)
assert(data.to_utf8() == decrypted)
```
**Note:** Not available in HTML5 exports.
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [constant\_time\_compare](#class-crypto-method-constant-time-compare) **(** [PoolByteArray](class_poolbytearray#class-poolbytearray) trusted, [PoolByteArray](class_poolbytearray#class-poolbytearray) received **)** |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [decrypt](#class-crypto-method-decrypt) **(** [CryptoKey](class_cryptokey#class-cryptokey) key, [PoolByteArray](class_poolbytearray#class-poolbytearray) ciphertext **)** |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [encrypt](#class-crypto-method-encrypt) **(** [CryptoKey](class_cryptokey#class-cryptokey) key, [PoolByteArray](class_poolbytearray#class-poolbytearray) plaintext **)** |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [generate\_random\_bytes](#class-crypto-method-generate-random-bytes) **(** [int](class_int#class-int) size **)** |
| [CryptoKey](class_cryptokey#class-cryptokey) | [generate\_rsa](#class-crypto-method-generate-rsa) **(** [int](class_int#class-int) size **)** |
| [X509Certificate](class_x509certificate#class-x509certificate) | [generate\_self\_signed\_certificate](#class-crypto-method-generate-self-signed-certificate) **(** [CryptoKey](class_cryptokey#class-cryptokey) key, [String](class_string#class-string) issuer\_name="CN=myserver,O=myorganisation,C=IT", [String](class_string#class-string) not\_before="20140101000000", [String](class_string#class-string) not\_after="20340101000000" **)** |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [hmac\_digest](#class-crypto-method-hmac-digest) **(** [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) key, [PoolByteArray](class_poolbytearray#class-poolbytearray) msg **)** |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [sign](#class-crypto-method-sign) **(** [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) hash, [CryptoKey](class_cryptokey#class-cryptokey) key **)** |
| [bool](class_bool#class-bool) | [verify](#class-crypto-method-verify) **(** [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) hash, [PoolByteArray](class_poolbytearray#class-poolbytearray) signature, [CryptoKey](class_cryptokey#class-cryptokey) key **)** |
Method Descriptions
-------------------
### [bool](class_bool#class-bool) constant\_time\_compare ( [PoolByteArray](class_poolbytearray#class-poolbytearray) trusted, [PoolByteArray](class_poolbytearray#class-poolbytearray) received )
Compares two [PoolByteArray](class_poolbytearray#class-poolbytearray)s for equality without leaking timing information in order to prevent timing attacks.
See [this blog post](https://paragonie.com/blog/2015/11/preventing-timing-attacks-on-string-comparison-with-double-hmac-strategy) for more information.
### [PoolByteArray](class_poolbytearray#class-poolbytearray) decrypt ( [CryptoKey](class_cryptokey#class-cryptokey) key, [PoolByteArray](class_poolbytearray#class-poolbytearray) ciphertext )
Decrypt the given `ciphertext` with the provided private `key`.
**Note:** The maximum size of accepted ciphertext is limited by the key size.
### [PoolByteArray](class_poolbytearray#class-poolbytearray) encrypt ( [CryptoKey](class_cryptokey#class-cryptokey) key, [PoolByteArray](class_poolbytearray#class-poolbytearray) plaintext )
Encrypt the given `plaintext` with the provided public `key`.
**Note:** The maximum size of accepted plaintext is limited by the key size.
### [PoolByteArray](class_poolbytearray#class-poolbytearray) generate\_random\_bytes ( [int](class_int#class-int) size )
Generates a [PoolByteArray](class_poolbytearray#class-poolbytearray) of cryptographically secure random bytes with given `size`.
### [CryptoKey](class_cryptokey#class-cryptokey) generate\_rsa ( [int](class_int#class-int) size )
Generates an RSA [CryptoKey](class_cryptokey#class-cryptokey) that can be used for creating self-signed certificates and passed to [StreamPeerSSL.accept\_stream](class_streampeerssl#class-streampeerssl-method-accept-stream).
### [X509Certificate](class_x509certificate#class-x509certificate) generate\_self\_signed\_certificate ( [CryptoKey](class_cryptokey#class-cryptokey) key, [String](class_string#class-string) issuer\_name="CN=myserver,O=myorganisation,C=IT", [String](class_string#class-string) not\_before="20140101000000", [String](class_string#class-string) not\_after="20340101000000" )
Generates a self-signed [X509Certificate](class_x509certificate#class-x509certificate) from the given [CryptoKey](class_cryptokey#class-cryptokey) and `issuer_name`. The certificate validity will be defined by `not_before` and `not_after` (first valid date and last valid date). The `issuer_name` must contain at least "CN=" (common name, i.e. the domain name), "O=" (organization, i.e. your company name), "C=" (country, i.e. 2 lettered ISO-3166 code of the country the organization is based in).
A small example to generate an RSA key and a X509 self-signed certificate.
```
var crypto = Crypto.new()
# Generate 4096 bits RSA key.
var key = crypto.generate_rsa(4096)
# Generate self-signed certificate using the given key.
var cert = crypto.generate_self_signed_certificate(key, "CN=example.com,O=A Game Company,C=IT")
```
### [PoolByteArray](class_poolbytearray#class-poolbytearray) hmac\_digest ( [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) key, [PoolByteArray](class_poolbytearray#class-poolbytearray) msg )
Generates an [HMAC](https://en.wikipedia.org/wiki/HMAC) digest of `msg` using `key`. The `hash_type` parameter is the hashing algorithm that is used for the inner and outer hashes.
Currently, only [HashingContext.HASH\_SHA256](class_hashingcontext#class-hashingcontext-constant-hash-sha256) and [HashingContext.HASH\_SHA1](class_hashingcontext#class-hashingcontext-constant-hash-sha1) are supported.
### [PoolByteArray](class_poolbytearray#class-poolbytearray) sign ( [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) hash, [CryptoKey](class_cryptokey#class-cryptokey) key )
Sign a given `hash` of type `hash_type` with the provided private `key`.
### [bool](class_bool#class-bool) verify ( [HashType](class_hashingcontext#enum-hashingcontext-hashtype) hash\_type, [PoolByteArray](class_poolbytearray#class-poolbytearray) hash, [PoolByteArray](class_poolbytearray#class-poolbytearray) signature, [CryptoKey](class_cryptokey#class-cryptokey) key )
Verify that a given `signature` for `hash` of type `hash_type` against the provided public `key`.
godot GradientTexture2D GradientTexture2D
=================
**Inherits:** [Texture](class_texture#class-texture) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Gradient-filled 2D texture.
Description
-----------
The texture uses a [Gradient](class_gradient#class-gradient) to fill the texture data in 2D space. The gradient is filled according to the specified [fill](#class-gradienttexture2d-property-fill) and [repeat](#class-gradienttexture2d-property-repeat) types using colors obtained from the gradient. The texture does not necessarily represent an exact copy of the gradient, but instead an interpolation of samples obtained from the gradient at fixed steps (see [width](#class-gradienttexture2d-property-width) and [height](#class-gradienttexture2d-property-height)). See also [GradientTexture](class_gradienttexture#class-gradienttexture) and [CurveTexture](class_curvetexture#class-curvetexture).
Properties
----------
| | | |
| --- | --- | --- |
| [Fill](#enum-gradienttexture2d-fill) | [fill](#class-gradienttexture2d-property-fill) | `0` |
| [Vector2](class_vector2#class-vector2) | [fill\_from](#class-gradienttexture2d-property-fill-from) | `Vector2( 0, 0 )` |
| [Vector2](class_vector2#class-vector2) | [fill\_to](#class-gradienttexture2d-property-fill-to) | `Vector2( 1, 0 )` |
| [int](class_int#class-int) | flags | `7` (overrides [Texture](class_texture#class-texture-property-flags)) |
| [Gradient](class_gradient#class-gradient) | [gradient](#class-gradienttexture2d-property-gradient) | |
| [int](class_int#class-int) | [height](#class-gradienttexture2d-property-height) | `64` |
| [Repeat](#enum-gradienttexture2d-repeat) | [repeat](#class-gradienttexture2d-property-repeat) | `0` |
| [bool](class_bool#class-bool) | [use\_hdr](#class-gradienttexture2d-property-use-hdr) | `false` |
| [int](class_int#class-int) | [width](#class-gradienttexture2d-property-width) | `64` |
Enumerations
------------
enum **Fill**:
* **FILL\_LINEAR** = **0** --- The colors are linearly interpolated in a straight line.
* **FILL\_RADIAL** = **1** --- The colors are linearly interpolated in a circular pattern.
enum **Repeat**:
* **REPEAT\_NONE** = **0** --- The gradient fill is restricted to the range defined by [fill\_from](#class-gradienttexture2d-property-fill-from) to [fill\_to](#class-gradienttexture2d-property-fill-to) offsets.
* **REPEAT** = **1** --- The texture is filled starting from [fill\_from](#class-gradienttexture2d-property-fill-from) to [fill\_to](#class-gradienttexture2d-property-fill-to) offsets, repeating the same pattern in both directions.
* **REPEAT\_MIRROR** = **2** --- The texture is filled starting from [fill\_from](#class-gradienttexture2d-property-fill-from) to [fill\_to](#class-gradienttexture2d-property-fill-to) offsets, mirroring the pattern in both directions.
Property Descriptions
---------------------
### [Fill](#enum-gradienttexture2d-fill) fill
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_fill(value) |
| *Getter* | get\_fill() |
The gradient fill type, one of the [Fill](#enum-gradienttexture2d-fill) values. The texture is filled by interpolating colors starting from [fill\_from](#class-gradienttexture2d-property-fill-from) to [fill\_to](#class-gradienttexture2d-property-fill-to) offsets.
### [Vector2](class_vector2#class-vector2) fill\_from
| | |
| --- | --- |
| *Default* | `Vector2( 0, 0 )` |
| *Setter* | set\_fill\_from(value) |
| *Getter* | get\_fill\_from() |
The initial offset used to fill the texture specified in UV coordinates.
### [Vector2](class_vector2#class-vector2) fill\_to
| | |
| --- | --- |
| *Default* | `Vector2( 1, 0 )` |
| *Setter* | set\_fill\_to(value) |
| *Getter* | get\_fill\_to() |
The final offset used to fill the texture specified in UV coordinates.
### [Gradient](class_gradient#class-gradient) gradient
| | |
| --- | --- |
| *Setter* | set\_gradient(value) |
| *Getter* | get\_gradient() |
The [Gradient](class_gradient#class-gradient) used to fill the texture.
### [int](class_int#class-int) height
| | |
| --- | --- |
| *Default* | `64` |
| *Setter* | set\_height(value) |
| *Getter* | get\_height() |
The number of vertical color samples that will be obtained from the [Gradient](class_gradient#class-gradient), which also represents the texture's height.
### [Repeat](#enum-gradienttexture2d-repeat) repeat
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_repeat(value) |
| *Getter* | get\_repeat() |
The gradient repeat type, one of the [Repeat](#enum-gradienttexture2d-repeat) values. The texture is filled starting from [fill\_from](#class-gradienttexture2d-property-fill-from) to [fill\_to](#class-gradienttexture2d-property-fill-to) offsets by default, but the gradient fill can be repeated to cover the entire texture.
### [bool](class_bool#class-bool) use\_hdr
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_use\_hdr(value) |
| *Getter* | is\_using\_hdr() |
If `true`, the generated texture will support high dynamic range ([Image.FORMAT\_RGBAF](class_image#class-image-constant-format-rgbaf) format). This allows for glow effects to work if [Environment.glow\_enabled](class_environment#class-environment-property-glow-enabled) is `true`. If `false`, the generated texture will use low dynamic range; overbright colors will be clamped ([Image.FORMAT\_RGBA8](class_image#class-image-constant-format-rgba8) format).
### [int](class_int#class-int) width
| | |
| --- | --- |
| *Default* | `64` |
| *Setter* | set\_width(value) |
| *Getter* | get\_width() |
The number of horizontal color samples that will be obtained from the [Gradient](class_gradient#class-gradient), which also represents the texture's width.
godot VisualShaderNodeBooleanUniform VisualShaderNodeBooleanUniform
==============================
**Inherits:** [VisualShaderNodeUniform](class_visualshadernodeuniform#class-visualshadernodeuniform) **<** [VisualShaderNode](class_visualshadernode#class-visualshadernode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A boolean uniform to be used within the visual shader graph.
Description
-----------
Translated to `uniform bool` in the shader language.
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | [default\_value](#class-visualshadernodebooleanuniform-property-default-value) | `false` |
| [bool](class_bool#class-bool) | [default\_value\_enabled](#class-visualshadernodebooleanuniform-property-default-value-enabled) | `false` |
Property Descriptions
---------------------
### [bool](class_bool#class-bool) default\_value
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_default\_value(value) |
| *Getter* | get\_default\_value() |
A default value to be assigned within the shader.
### [bool](class_bool#class-bool) default\_value\_enabled
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_default\_value\_enabled(value) |
| *Getter* | is\_default\_value\_enabled() |
Enables usage of the [default\_value](#class-visualshadernodebooleanuniform-property-default-value).
godot SphereMesh SphereMesh
==========
**Inherits:** [PrimitiveMesh](class_primitivemesh#class-primitivemesh) **<** [Mesh](class_mesh#class-mesh) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Class representing a spherical [PrimitiveMesh](class_primitivemesh#class-primitivemesh).
Description
-----------
Class representing a spherical [PrimitiveMesh](class_primitivemesh#class-primitivemesh).
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [height](#class-spheremesh-property-height) | `2.0` |
| [bool](class_bool#class-bool) | [is\_hemisphere](#class-spheremesh-property-is-hemisphere) | `false` |
| [int](class_int#class-int) | [radial\_segments](#class-spheremesh-property-radial-segments) | `64` |
| [float](class_float#class-float) | [radius](#class-spheremesh-property-radius) | `1.0` |
| [int](class_int#class-int) | [rings](#class-spheremesh-property-rings) | `32` |
Property Descriptions
---------------------
### [float](class_float#class-float) height
| | |
| --- | --- |
| *Default* | `2.0` |
| *Setter* | set\_height(value) |
| *Getter* | get\_height() |
Full height of the sphere.
### [bool](class_bool#class-bool) is\_hemisphere
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_is\_hemisphere(value) |
| *Getter* | get\_is\_hemisphere() |
If `true`, a hemisphere is created rather than a full sphere.
**Note:** To get a regular hemisphere, the height and radius of the sphere must be equal.
### [int](class_int#class-int) radial\_segments
| | |
| --- | --- |
| *Default* | `64` |
| *Setter* | set\_radial\_segments(value) |
| *Getter* | get\_radial\_segments() |
Number of radial segments on the sphere.
### [float](class_float#class-float) radius
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_radius(value) |
| *Getter* | get\_radius() |
Radius of sphere.
### [int](class_int#class-int) rings
| | |
| --- | --- |
| *Default* | `32` |
| *Setter* | set\_rings(value) |
| *Getter* | get\_rings() |
Number of segments along the height of the sphere.
| programming_docs |
godot VisualScriptLocalVar VisualScriptLocalVar
====================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Gets a local variable's value.
Description
-----------
Returns a local variable's value. "Var Name" must be supplied, with an optional type.
**Input Ports:**
none
**Output Ports:**
* Data (variant): `get`
Properties
----------
| | | |
| --- | --- | --- |
| [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) | [type](#class-visualscriptlocalvar-property-type) | `0` |
| [String](class_string#class-string) | [var\_name](#class-visualscriptlocalvar-property-var-name) | `"new_local"` |
Property Descriptions
---------------------
### [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) type
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_var\_type(value) |
| *Getter* | get\_var\_type() |
The local variable's type.
### [String](class_string#class-string) var\_name
| | |
| --- | --- |
| *Default* | `"new_local"` |
| *Setter* | set\_var\_name(value) |
| *Getter* | get\_var\_name() |
The local variable's name.
godot VisualShaderNodeVectorDerivativeFunc VisualShaderNodeVectorDerivativeFunc
====================================
**Inherits:** [VisualShaderNode](class_visualshadernode#class-visualshadernode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Calculates a vector derivative within the visual shader graph.
Description
-----------
This node is only available in `Fragment` and `Light` visual shaders.
Properties
----------
| | | |
| --- | --- | --- |
| [Function](#enum-visualshadernodevectorderivativefunc-function) | [function](#class-visualshadernodevectorderivativefunc-property-function) | `0` |
Enumerations
------------
enum **Function**:
* **FUNC\_SUM** = **0** --- Sum of absolute derivative in `x` and `y`.
* **FUNC\_X** = **1** --- Derivative in `x` using local differencing.
* **FUNC\_Y** = **2** --- Derivative in `y` using local differencing.
Property Descriptions
---------------------
### [Function](#enum-visualshadernodevectorderivativefunc-function) function
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_function(value) |
| *Getter* | get\_function() |
A derivative type. See [Function](#enum-visualshadernodevectorderivativefunc-function) for options.
godot AnimationTrackEditPlugin AnimationTrackEditPlugin
========================
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
godot ParallaxLayer ParallaxLayer
=============
**Inherits:** [Node2D](class_node2d#class-node2d) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
A parallax scrolling layer to be used with [ParallaxBackground](class_parallaxbackground#class-parallaxbackground).
Description
-----------
A ParallaxLayer must be the child of a [ParallaxBackground](class_parallaxbackground#class-parallaxbackground) node. Each ParallaxLayer can be set to move at different speeds relative to the camera movement or the [ParallaxBackground.scroll\_offset](class_parallaxbackground#class-parallaxbackground-property-scroll-offset) value.
This node's children will be affected by its scroll offset.
**Note:** Any changes to this node's position and scale made after it enters the scene will be ignored.
Properties
----------
| | | |
| --- | --- | --- |
| [Vector2](class_vector2#class-vector2) | [motion\_mirroring](#class-parallaxlayer-property-motion-mirroring) | `Vector2( 0, 0 )` |
| [Vector2](class_vector2#class-vector2) | [motion\_offset](#class-parallaxlayer-property-motion-offset) | `Vector2( 0, 0 )` |
| [Vector2](class_vector2#class-vector2) | [motion\_scale](#class-parallaxlayer-property-motion-scale) | `Vector2( 1, 1 )` |
Property Descriptions
---------------------
### [Vector2](class_vector2#class-vector2) motion\_mirroring
| | |
| --- | --- |
| *Default* | `Vector2( 0, 0 )` |
| *Setter* | set\_mirroring(value) |
| *Getter* | get\_mirroring() |
The ParallaxLayer's [Texture](class_texture#class-texture) mirroring. Useful for creating an infinite scrolling background. If an axis is set to `0`, the [Texture](class_texture#class-texture) will not be mirrored.
### [Vector2](class_vector2#class-vector2) motion\_offset
| | |
| --- | --- |
| *Default* | `Vector2( 0, 0 )` |
| *Setter* | set\_motion\_offset(value) |
| *Getter* | get\_motion\_offset() |
The ParallaxLayer's offset relative to the parent ParallaxBackground's [ParallaxBackground.scroll\_offset](class_parallaxbackground#class-parallaxbackground-property-scroll-offset).
### [Vector2](class_vector2#class-vector2) motion\_scale
| | |
| --- | --- |
| *Default* | `Vector2( 1, 1 )` |
| *Setter* | set\_motion\_scale(value) |
| *Getter* | get\_motion\_scale() |
Multiplies the ParallaxLayer's motion. If an axis is set to `0`, it will not scroll.
godot ShortCut ShortCut
========
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A shortcut for binding input.
Description
-----------
A shortcut for binding input.
Shortcuts are commonly used for interacting with a [Control](class_control#class-control) element from a [InputEvent](class_inputevent#class-inputevent).
Properties
----------
| | |
| --- | --- |
| [InputEvent](class_inputevent#class-inputevent) | [shortcut](#class-shortcut-property-shortcut) |
Methods
-------
| | |
| --- | --- |
| [String](class_string#class-string) | [get\_as\_text](#class-shortcut-method-get-as-text) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_shortcut](#class-shortcut-method-is-shortcut) **(** [InputEvent](class_inputevent#class-inputevent) event **)** const |
| [bool](class_bool#class-bool) | [is\_valid](#class-shortcut-method-is-valid) **(** **)** const |
Property Descriptions
---------------------
### [InputEvent](class_inputevent#class-inputevent) shortcut
| | |
| --- | --- |
| *Setter* | set\_shortcut(value) |
| *Getter* | get\_shortcut() |
The shortcut's [InputEvent](class_inputevent#class-inputevent).
Generally the [InputEvent](class_inputevent#class-inputevent) is a keyboard key, though it can be any [InputEvent](class_inputevent#class-inputevent).
Method Descriptions
-------------------
### [String](class_string#class-string) get\_as\_text ( ) const
Returns the shortcut's [InputEvent](class_inputevent#class-inputevent) as a [String](class_string#class-string).
### [bool](class_bool#class-bool) is\_shortcut ( [InputEvent](class_inputevent#class-inputevent) event ) const
Returns `true` if the shortcut's [InputEvent](class_inputevent#class-inputevent) equals `event`.
### [bool](class_bool#class-bool) is\_valid ( ) const
If `true`, this shortcut is valid.
godot NodePath NodePath
========
Pre-parsed scene tree path.
Description
-----------
A pre-parsed relative or absolute path in a scene tree, for use with [Node.get\_node](class_node#class-node-method-get-node) and similar functions. It can reference a node, a resource within a node, or a property of a node or resource. For instance, `"Path2D/PathFollow2D/Sprite:texture:size"` would refer to the `size` property of the `texture` resource on the node named `"Sprite"` which is a child of the other named nodes in the path.
You will usually just pass a string to [Node.get\_node](class_node#class-node-method-get-node) and it will be automatically converted, but you may occasionally want to parse a path ahead of time with `NodePath` or the literal syntax `@"path"`. Exporting a `NodePath` variable will give you a node selection widget in the properties panel of the editor, which can often be useful.
A `NodePath` is composed of a list of slash-separated node names (like a filesystem path) and an optional colon-separated list of "subnames" which can be resources or properties.
Some examples of NodePaths include the following:
```
# No leading slash means it is relative to the current node.
@"A" # Immediate child A
@"A/B" # A's child B
@"." # The current node.
@".." # The parent node.
@"../C" # A sibling node C.
# A leading slash means it is absolute from the SceneTree.
@"/root" # Equivalent to get_tree().get_root().
@"/root/Main" # If your main scene's root node were named "Main".
@"/root/MyAutoload" # If you have an autoloaded node or scene.
```
**Note:** In the editor, `NodePath` properties are automatically updated when moving, renaming or deleting a node in the scene tree, but they are never updated at runtime.
Tutorials
---------
* [2D Role Playing Game Demo](https://godotengine.org/asset-library/asset/520)
Methods
-------
| | |
| --- | --- |
| [NodePath](#class-nodepath) | [NodePath](#class-nodepath-method-nodepath) **(** [String](class_string#class-string) from **)** |
| [NodePath](#class-nodepath) | [get\_as\_property\_path](#class-nodepath-method-get-as-property-path) **(** **)** |
| [String](class_string#class-string) | [get\_concatenated\_subnames](#class-nodepath-method-get-concatenated-subnames) **(** **)** |
| [String](class_string#class-string) | [get\_name](#class-nodepath-method-get-name) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_name\_count](#class-nodepath-method-get-name-count) **(** **)** |
| [String](class_string#class-string) | [get\_subname](#class-nodepath-method-get-subname) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_subname\_count](#class-nodepath-method-get-subname-count) **(** **)** |
| [bool](class_bool#class-bool) | [is\_absolute](#class-nodepath-method-is-absolute) **(** **)** |
| [bool](class_bool#class-bool) | [is\_empty](#class-nodepath-method-is-empty) **(** **)** |
Method Descriptions
-------------------
### [NodePath](#class-nodepath) NodePath ( [String](class_string#class-string) from )
Creates a NodePath from a string, e.g. `"Path2D/PathFollow2D/Sprite:texture:size"`. A path is absolute if it starts with a slash. Absolute paths are only valid in the global scene tree, not within individual scenes. In a relative path, `"."` and `".."` indicate the current node and its parent.
The "subnames" optionally included after the path to the target node can point to resources or properties, and can also be nested.
Examples of valid NodePaths (assuming that those nodes exist and have the referenced resources or properties):
```
# Points to the Sprite node
"Path2D/PathFollow2D/Sprite"
# Points to the Sprite node and its "texture" resource.
# get_node() would retrieve "Sprite", while get_node_and_resource()
# would retrieve both the Sprite node and the "texture" resource.
"Path2D/PathFollow2D/Sprite:texture"
# Points to the Sprite node and its "position" property.
"Path2D/PathFollow2D/Sprite:position"
# Points to the Sprite node and the "x" component of its "position" property.
"Path2D/PathFollow2D/Sprite:position:x"
# Absolute path (from "root")
"/root/Level/Path2D"
```
### [NodePath](#class-nodepath) get\_as\_property\_path ( )
Returns a node path with a colon character (`:`) prepended, transforming it to a pure property path with no node name (defaults to resolving from the current node).
```
# This will be parsed as a node path to the "x" property in the "position" node
var node_path = NodePath("position:x")
# This will be parsed as a node path to the "x" component of the "position" property in the current node
var property_path = node_path.get_as_property_path()
print(property_path) # :position:x
```
### [String](class_string#class-string) get\_concatenated\_subnames ( )
Returns all subnames concatenated with a colon character (`:`) as separator, i.e. the right side of the first colon in a node path.
```
var nodepath = NodePath("Path2D/PathFollow2D/Sprite:texture:load_path")
print(nodepath.get_concatenated_subnames()) # texture:load_path
```
### [String](class_string#class-string) get\_name ( [int](class_int#class-int) idx )
Gets the node name indicated by `idx` (0 to [get\_name\_count](#class-nodepath-method-get-name-count) - 1).
```
var node_path = NodePath("Path2D/PathFollow2D/Sprite")
print(node_path.get_name(0)) # Path2D
print(node_path.get_name(1)) # PathFollow2D
print(node_path.get_name(2)) # Sprite
```
### [int](class_int#class-int) get\_name\_count ( )
Gets the number of node names which make up the path. Subnames (see [get\_subname\_count](#class-nodepath-method-get-subname-count)) are not included.
For example, `"Path2D/PathFollow2D/Sprite"` has 3 names.
### [String](class_string#class-string) get\_subname ( [int](class_int#class-int) idx )
Gets the resource or property name indicated by `idx` (0 to [get\_subname\_count](#class-nodepath-method-get-subname-count)).
```
var node_path = NodePath("Path2D/PathFollow2D/Sprite:texture:load_path")
print(node_path.get_subname(0)) # texture
print(node_path.get_subname(1)) # load_path
```
### [int](class_int#class-int) get\_subname\_count ( )
Gets the number of resource or property names ("subnames") in the path. Each subname is listed after a colon character (`:`) in the node path.
For example, `"Path2D/PathFollow2D/Sprite:texture:load_path"` has 2 subnames.
### [bool](class_bool#class-bool) is\_absolute ( )
Returns `true` if the node path is absolute (as opposed to relative), which means that it starts with a slash character (`/`). Absolute node paths can be used to access the root node (`"/root"`) or autoloads (e.g. `"/global"` if a "global" autoload was registered).
### [bool](class_bool#class-bool) is\_empty ( )
Returns `true` if the node path is empty.
godot ResourceLoader ResourceLoader
==============
**Inherits:** [Object](class_object#class-object)
Singleton used to load resource files.
Description
-----------
Singleton used to load resource files from the filesystem.
It uses the many [ResourceFormatLoader](class_resourceformatloader#class-resourceformatloader) classes registered in the engine (either built-in or from a plugin) to load files into memory and convert them to a format that can be used by the engine.
Tutorials
---------
* [OS Test Demo](https://godotengine.org/asset-library/asset/677)
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [exists](#class-resourceloader-method-exists) **(** [String](class_string#class-string) path, [String](class_string#class-string) type\_hint="" **)** |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_dependencies](#class-resourceloader-method-get-dependencies) **(** [String](class_string#class-string) path **)** |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_recognized\_extensions\_for\_type](#class-resourceloader-method-get-recognized-extensions-for-type) **(** [String](class_string#class-string) type **)** |
| [bool](class_bool#class-bool) | [has](#class-resourceloader-method-has) **(** [String](class_string#class-string) path **)** |
| [bool](class_bool#class-bool) | [has\_cached](#class-resourceloader-method-has-cached) **(** [String](class_string#class-string) path **)** |
| [Resource](class_resource#class-resource) | [load](#class-resourceloader-method-load) **(** [String](class_string#class-string) path, [String](class_string#class-string) type\_hint="", [bool](class_bool#class-bool) no\_cache=false **)** |
| [ResourceInteractiveLoader](class_resourceinteractiveloader#class-resourceinteractiveloader) | [load\_interactive](#class-resourceloader-method-load-interactive) **(** [String](class_string#class-string) path, [String](class_string#class-string) type\_hint="" **)** |
| void | [set\_abort\_on\_missing\_resources](#class-resourceloader-method-set-abort-on-missing-resources) **(** [bool](class_bool#class-bool) abort **)** |
Method Descriptions
-------------------
### [bool](class_bool#class-bool) exists ( [String](class_string#class-string) path, [String](class_string#class-string) type\_hint="" )
Returns whether a recognized resource exists for the given `path`.
An optional `type_hint` can be used to further specify the [Resource](class_resource#class-resource) type that should be handled by the [ResourceFormatLoader](class_resourceformatloader#class-resourceformatloader).
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_dependencies ( [String](class_string#class-string) path )
Returns the dependencies for the resource at the given `path`.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_recognized\_extensions\_for\_type ( [String](class_string#class-string) type )
Returns the list of recognized extensions for a resource type.
### [bool](class_bool#class-bool) has ( [String](class_string#class-string) path )
*Deprecated method.* Use [has\_cached](#class-resourceloader-method-has-cached) or [exists](#class-resourceloader-method-exists) instead.
### [bool](class_bool#class-bool) has\_cached ( [String](class_string#class-string) path )
Returns whether a cached resource is available for the given `path`.
Once a resource has been loaded by the engine, it is cached in memory for faster access, and future calls to the [load](#class-resourceloader-method-load) or [load\_interactive](#class-resourceloader-method-load-interactive) methods will use the cached version. The cached resource can be overridden by using [Resource.take\_over\_path](class_resource#class-resource-method-take-over-path) on a new resource for that same path.
### [Resource](class_resource#class-resource) load ( [String](class_string#class-string) path, [String](class_string#class-string) type\_hint="", [bool](class_bool#class-bool) no\_cache=false )
Loads a resource at the given `path`, caching the result for further access.
The registered [ResourceFormatLoader](class_resourceformatloader#class-resourceformatloader)s are queried sequentially to find the first one which can handle the file's extension, and then attempt loading. If loading fails, the remaining ResourceFormatLoaders are also attempted.
An optional `type_hint` can be used to further specify the [Resource](class_resource#class-resource) type that should be handled by the [ResourceFormatLoader](class_resourceformatloader#class-resourceformatloader). Anything that inherits from [Resource](class_resource#class-resource) can be used as a type hint, for example [Image](class_image#class-image).
If `no_cache` is `true`, the resource cache will be bypassed and the resource will be loaded anew. Otherwise, the cached resource will be returned if it exists.
Returns an empty resource if no [ResourceFormatLoader](class_resourceformatloader#class-resourceformatloader) could handle the file.
GDScript has a simplified [@GDScript.load](class_%40gdscript#class-gdscript-method-load) built-in method which can be used in most situations, leaving the use of `ResourceLoader` for more advanced scenarios.
### [ResourceInteractiveLoader](class_resourceinteractiveloader#class-resourceinteractiveloader) load\_interactive ( [String](class_string#class-string) path, [String](class_string#class-string) type\_hint="" )
Starts loading a resource interactively. The returned [ResourceInteractiveLoader](class_resourceinteractiveloader#class-resourceinteractiveloader) object allows to load with high granularity, calling its [ResourceInteractiveLoader.poll](class_resourceinteractiveloader#class-resourceinteractiveloader-method-poll) method successively to load chunks.
An optional `type_hint` can be used to further specify the [Resource](class_resource#class-resource) type that should be handled by the [ResourceFormatLoader](class_resourceformatloader#class-resourceformatloader). Anything that inherits from [Resource](class_resource#class-resource) can be used as a type hint, for example [Image](class_image#class-image).
### void set\_abort\_on\_missing\_resources ( [bool](class_bool#class-bool) abort )
Changes the behavior on missing sub-resources. The default behavior is to abort loading.
| programming_docs |
godot VisualShaderNodeVectorClamp VisualShaderNodeVectorClamp
===========================
**Inherits:** [VisualShaderNode](class_visualshadernode#class-visualshadernode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Clamps a vector value within the visual shader graph.
Description
-----------
Constrains a value to lie between `min` and `max` values. The operation is performed on each component of the vector individually.
godot ConcavePolygonShape ConcavePolygonShape
===================
**Inherits:** [Shape](class_shape#class-shape) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Concave polygon shape.
Description
-----------
Concave polygon shape resource, which can be set into a [PhysicsBody](class_physicsbody#class-physicsbody) or area. This shape is created by feeding a list of triangles.
**Note:** When used for collision, `ConcavePolygonShape` is intended to work with static [PhysicsBody](class_physicsbody#class-physicsbody) nodes like [StaticBody](class_staticbody#class-staticbody) and will not work with [KinematicBody](class_kinematicbody#class-kinematicbody) or [RigidBody](class_rigidbody#class-rigidbody) with a mode other than Static.
**Warning:** Using this shape for an [Area](class_area#class-area) (via a [CollisionShape](class_collisionshape#class-collisionshape) node, created e.g. by using the *Create Trimesh Collision Sibling* option in the *Mesh* menu that appears when selecting a [MeshInstance](class_meshinstance#class-meshinstance) node) may give unexpected results: when using Godot Physics, the area will only detect collisions with the triangle faces in the `ConcavePolygonShape` (and not with any "inside" of the shape, for example), and when using Bullet Physics the area will not detect any collisions with the concave shape at all (this is a known bug).
Tutorials
---------
* [3D Physics Tests Demo](https://godotengine.org/asset-library/asset/675)
Methods
-------
| | |
| --- | --- |
| [PoolVector3Array](class_poolvector3array#class-poolvector3array) | [get\_faces](#class-concavepolygonshape-method-get-faces) **(** **)** const |
| void | [set\_faces](#class-concavepolygonshape-method-set-faces) **(** [PoolVector3Array](class_poolvector3array#class-poolvector3array) faces **)** |
Method Descriptions
-------------------
### [PoolVector3Array](class_poolvector3array#class-poolvector3array) get\_faces ( ) const
Returns the faces (an array of triangles).
### void set\_faces ( [PoolVector3Array](class_poolvector3array#class-poolvector3array) faces )
Sets the faces (an array of triangles).
godot AudioStreamGenerator AudioStreamGenerator
====================
**Inherits:** [AudioStream](class_audiostream#class-audiostream) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Audio stream that generates sounds procedurally.
Description
-----------
This audio stream does not play back sounds, but expects a script to generate audio data for it instead. See also [AudioStreamGeneratorPlayback](class_audiostreamgeneratorplayback#class-audiostreamgeneratorplayback).
See also [AudioEffectSpectrumAnalyzer](class_audioeffectspectrumanalyzer#class-audioeffectspectrumanalyzer) for performing real-time audio spectrum analysis.
**Note:** Due to performance constraints, this class is best used from C# or from a compiled language via GDNative. If you still want to use this class from GDScript, consider using a lower [mix\_rate](#class-audiostreamgenerator-property-mix-rate) such as 11,025 Hz or 22,050 Hz.
Tutorials
---------
* [Audio Generator Demo](https://godotengine.org/asset-library/asset/526)
* [Godot 3.2 will get new audio features](https://godotengine.org/article/godot-32-will-get-new-audio-features)
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [buffer\_length](#class-audiostreamgenerator-property-buffer-length) | `0.5` |
| [float](class_float#class-float) | [mix\_rate](#class-audiostreamgenerator-property-mix-rate) | `44100.0` |
Property Descriptions
---------------------
### [float](class_float#class-float) buffer\_length
| | |
| --- | --- |
| *Default* | `0.5` |
| *Setter* | set\_buffer\_length(value) |
| *Getter* | get\_buffer\_length() |
The length of the buffer to generate (in seconds). Lower values result in less latency, but require the script to generate audio data faster, resulting in increased CPU usage and more risk for audio cracking if the CPU can't keep up.
### [float](class_float#class-float) mix\_rate
| | |
| --- | --- |
| *Default* | `44100.0` |
| *Setter* | set\_mix\_rate(value) |
| *Getter* | get\_mix\_rate() |
The sample rate to use (in Hz). Higher values are more demanding for the CPU to generate, but result in better quality.
In games, common sample rates in use are `11025`, `16000`, `22050`, `32000`, `44100`, and `48000`.
According to the [Nyquist-Shannon sampling theorem](https://en.wikipedia.org/wiki/Nyquist%E2%80%93Shannon_sampling_theorem), there is no quality difference to human hearing when going past 40,000 Hz (since most humans can only hear up to ~20,000 Hz, often less). If you are generating lower-pitched sounds such as voices, lower sample rates such as `32000` or `22050` may be usable with no loss in quality.
godot WebSocketPeer WebSocketPeer
=============
**Inherits:** [PacketPeer](class_packetpeer#class-packetpeer) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A class representing a specific WebSocket connection.
Description
-----------
This class represents a specific WebSocket connection, allowing you to do lower level operations with it.
You can choose to write to the socket in binary or text mode, and you can recognize the mode used for writing by the other peer.
Methods
-------
| | |
| --- | --- |
| void | [close](#class-websocketpeer-method-close) **(** [int](class_int#class-int) code=1000, [String](class_string#class-string) reason="" **)** |
| [String](class_string#class-string) | [get\_connected\_host](#class-websocketpeer-method-get-connected-host) **(** **)** const |
| [int](class_int#class-int) | [get\_connected\_port](#class-websocketpeer-method-get-connected-port) **(** **)** const |
| [int](class_int#class-int) | [get\_current\_outbound\_buffered\_amount](#class-websocketpeer-method-get-current-outbound-buffered-amount) **(** **)** const |
| [WriteMode](#enum-websocketpeer-writemode) | [get\_write\_mode](#class-websocketpeer-method-get-write-mode) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_connected\_to\_host](#class-websocketpeer-method-is-connected-to-host) **(** **)** const |
| void | [set\_no\_delay](#class-websocketpeer-method-set-no-delay) **(** [bool](class_bool#class-bool) enabled **)** |
| void | [set\_write\_mode](#class-websocketpeer-method-set-write-mode) **(** [WriteMode](#enum-websocketpeer-writemode) mode **)** |
| [bool](class_bool#class-bool) | [was\_string\_packet](#class-websocketpeer-method-was-string-packet) **(** **)** const |
Enumerations
------------
enum **WriteMode**:
* **WRITE\_MODE\_TEXT** = **0** --- Specifies that WebSockets messages should be transferred as text payload (only valid UTF-8 is allowed).
* **WRITE\_MODE\_BINARY** = **1** --- Specifies that WebSockets messages should be transferred as binary payload (any byte combination is allowed).
Method Descriptions
-------------------
### void close ( [int](class_int#class-int) code=1000, [String](class_string#class-string) reason="" )
Closes this WebSocket connection. `code` is the status code for the closure (see RFC 6455 section 7.4 for a list of valid status codes). `reason` is the human readable reason for closing the connection (can be any UTF-8 string that's smaller than 123 bytes).
**Note:** To achieve a clean close, you will need to keep polling until either [WebSocketClient.connection\_closed](class_websocketclient#class-websocketclient-signal-connection-closed) or [WebSocketServer.client\_disconnected](class_websocketserver#class-websocketserver-signal-client-disconnected) is received.
**Note:** The HTML5 export might not support all status codes. Please refer to browser-specific documentation for more details.
### [String](class_string#class-string) get\_connected\_host ( ) const
Returns the IP address of the connected peer.
**Note:** Not available in the HTML5 export.
### [int](class_int#class-int) get\_connected\_port ( ) const
Returns the remote port of the connected peer.
**Note:** Not available in the HTML5 export.
### [int](class_int#class-int) get\_current\_outbound\_buffered\_amount ( ) const
Returns the current amount of data in the outbound websocket buffer. **Note:** HTML5 exports use WebSocket.bufferedAmount, while other platforms use an internal buffer.
### [WriteMode](#enum-websocketpeer-writemode) get\_write\_mode ( ) const
Gets the current selected write mode. See [WriteMode](#enum-websocketpeer-writemode).
### [bool](class_bool#class-bool) is\_connected\_to\_host ( ) const
Returns `true` if this peer is currently connected.
### void set\_no\_delay ( [bool](class_bool#class-bool) enabled )
Disable Nagle's algorithm on the underling TCP socket (default). See [StreamPeerTCP.set\_no\_delay](class_streampeertcp#class-streampeertcp-method-set-no-delay) for more information.
**Note:** Not available in the HTML5 export.
### void set\_write\_mode ( [WriteMode](#enum-websocketpeer-writemode) mode )
Sets the socket to use the given [WriteMode](#enum-websocketpeer-writemode).
### [bool](class_bool#class-bool) was\_string\_packet ( ) const
Returns `true` if the last received packet was sent as a text payload. See [WriteMode](#enum-websocketpeer-writemode).
godot EditorPlugin EditorPlugin
============
**Inherits:** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Used by the editor to extend its functionality.
Description
-----------
Plugins are used by the editor to extend functionality. The most common types of plugins are those which edit a given node or resource type, import plugins and export plugins. See also [EditorScript](class_editorscript#class-editorscript) to add functions to the editor.
Tutorials
---------
* [Editor plugins](https://docs.godotengine.org/en/3.5/tutorials/plugins/editor/index.html)
Methods
-------
| | |
| --- | --- |
| void | [add\_autoload\_singleton](#class-editorplugin-method-add-autoload-singleton) **(** [String](class_string#class-string) name, [String](class_string#class-string) path **)** |
| [ToolButton](class_toolbutton#class-toolbutton) | [add\_control\_to\_bottom\_panel](#class-editorplugin-method-add-control-to-bottom-panel) **(** [Control](class_control#class-control) control, [String](class_string#class-string) title **)** |
| void | [add\_control\_to\_container](#class-editorplugin-method-add-control-to-container) **(** [CustomControlContainer](#enum-editorplugin-customcontrolcontainer) container, [Control](class_control#class-control) control **)** |
| void | [add\_control\_to\_dock](#class-editorplugin-method-add-control-to-dock) **(** [DockSlot](#enum-editorplugin-dockslot) slot, [Control](class_control#class-control) control **)** |
| void | [add\_custom\_type](#class-editorplugin-method-add-custom-type) **(** [String](class_string#class-string) type, [String](class_string#class-string) base, [Script](class_script#class-script) script, [Texture](class_texture#class-texture) icon **)** |
| void | [add\_export\_plugin](#class-editorplugin-method-add-export-plugin) **(** [EditorExportPlugin](class_editorexportplugin#class-editorexportplugin) plugin **)** |
| void | [add\_import\_plugin](#class-editorplugin-method-add-import-plugin) **(** [EditorImportPlugin](class_editorimportplugin#class-editorimportplugin) importer **)** |
| void | [add\_inspector\_plugin](#class-editorplugin-method-add-inspector-plugin) **(** [EditorInspectorPlugin](class_editorinspectorplugin#class-editorinspectorplugin) plugin **)** |
| void | [add\_scene\_import\_plugin](#class-editorplugin-method-add-scene-import-plugin) **(** [EditorSceneImporter](class_editorsceneimporter#class-editorsceneimporter) scene\_importer **)** |
| void | [add\_spatial\_gizmo\_plugin](#class-editorplugin-method-add-spatial-gizmo-plugin) **(** [EditorSpatialGizmoPlugin](class_editorspatialgizmoplugin#class-editorspatialgizmoplugin) plugin **)** |
| void | [add\_tool\_menu\_item](#class-editorplugin-method-add-tool-menu-item) **(** [String](class_string#class-string) name, [Object](class_object#class-object) handler, [String](class_string#class-string) callback, [Variant](class_variant#class-variant) ud=null **)** |
| void | [add\_tool\_submenu\_item](#class-editorplugin-method-add-tool-submenu-item) **(** [String](class_string#class-string) name, [Object](class_object#class-object) submenu **)** |
| void | [apply\_changes](#class-editorplugin-method-apply-changes) **(** **)** virtual |
| [bool](class_bool#class-bool) | [build](#class-editorplugin-method-build) **(** **)** virtual |
| void | [clear](#class-editorplugin-method-clear) **(** **)** virtual |
| void | [disable\_plugin](#class-editorplugin-method-disable-plugin) **(** **)** virtual |
| void | [edit](#class-editorplugin-method-edit) **(** [Object](class_object#class-object) object **)** virtual |
| void | [enable\_plugin](#class-editorplugin-method-enable-plugin) **(** **)** virtual |
| void | [forward\_canvas\_draw\_over\_viewport](#class-editorplugin-method-forward-canvas-draw-over-viewport) **(** [Control](class_control#class-control) overlay **)** virtual |
| void | [forward\_canvas\_force\_draw\_over\_viewport](#class-editorplugin-method-forward-canvas-force-draw-over-viewport) **(** [Control](class_control#class-control) overlay **)** virtual |
| [bool](class_bool#class-bool) | [forward\_canvas\_gui\_input](#class-editorplugin-method-forward-canvas-gui-input) **(** [InputEvent](class_inputevent#class-inputevent) event **)** virtual |
| void | [forward\_spatial\_draw\_over\_viewport](#class-editorplugin-method-forward-spatial-draw-over-viewport) **(** [Control](class_control#class-control) overlay **)** virtual |
| void | [forward\_spatial\_force\_draw\_over\_viewport](#class-editorplugin-method-forward-spatial-force-draw-over-viewport) **(** [Control](class_control#class-control) overlay **)** virtual |
| [bool](class_bool#class-bool) | [forward\_spatial\_gui\_input](#class-editorplugin-method-forward-spatial-gui-input) **(** [Camera](class_camera#class-camera) camera, [InputEvent](class_inputevent#class-inputevent) event **)** virtual |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_breakpoints](#class-editorplugin-method-get-breakpoints) **(** **)** virtual |
| [EditorInterface](class_editorinterface#class-editorinterface) | [get\_editor\_interface](#class-editorplugin-method-get-editor-interface) **(** **)** |
| [Texture](class_texture#class-texture) | [get\_plugin\_icon](#class-editorplugin-method-get-plugin-icon) **(** **)** virtual |
| [String](class_string#class-string) | [get\_plugin\_name](#class-editorplugin-method-get-plugin-name) **(** **)** virtual |
| [ScriptCreateDialog](class_scriptcreatedialog#class-scriptcreatedialog) | [get\_script\_create\_dialog](#class-editorplugin-method-get-script-create-dialog) **(** **)** |
| [Dictionary](class_dictionary#class-dictionary) | [get\_state](#class-editorplugin-method-get-state) **(** **)** virtual |
| [UndoRedo](class_undoredo#class-undoredo) | [get\_undo\_redo](#class-editorplugin-method-get-undo-redo) **(** **)** |
| void | [get\_window\_layout](#class-editorplugin-method-get-window-layout) **(** [ConfigFile](class_configfile#class-configfile) layout **)** virtual |
| [bool](class_bool#class-bool) | [handles](#class-editorplugin-method-handles) **(** [Object](class_object#class-object) object **)** virtual |
| [bool](class_bool#class-bool) | [has\_main\_screen](#class-editorplugin-method-has-main-screen) **(** **)** virtual |
| void | [hide\_bottom\_panel](#class-editorplugin-method-hide-bottom-panel) **(** **)** |
| void | [make\_bottom\_panel\_item\_visible](#class-editorplugin-method-make-bottom-panel-item-visible) **(** [Control](class_control#class-control) item **)** |
| void | [make\_visible](#class-editorplugin-method-make-visible) **(** [bool](class_bool#class-bool) visible **)** virtual |
| void | [queue\_save\_layout](#class-editorplugin-method-queue-save-layout) **(** **)** const |
| void | [remove\_autoload\_singleton](#class-editorplugin-method-remove-autoload-singleton) **(** [String](class_string#class-string) name **)** |
| void | [remove\_control\_from\_bottom\_panel](#class-editorplugin-method-remove-control-from-bottom-panel) **(** [Control](class_control#class-control) control **)** |
| void | [remove\_control\_from\_container](#class-editorplugin-method-remove-control-from-container) **(** [CustomControlContainer](#enum-editorplugin-customcontrolcontainer) container, [Control](class_control#class-control) control **)** |
| void | [remove\_control\_from\_docks](#class-editorplugin-method-remove-control-from-docks) **(** [Control](class_control#class-control) control **)** |
| void | [remove\_custom\_type](#class-editorplugin-method-remove-custom-type) **(** [String](class_string#class-string) type **)** |
| void | [remove\_export\_plugin](#class-editorplugin-method-remove-export-plugin) **(** [EditorExportPlugin](class_editorexportplugin#class-editorexportplugin) plugin **)** |
| void | [remove\_import\_plugin](#class-editorplugin-method-remove-import-plugin) **(** [EditorImportPlugin](class_editorimportplugin#class-editorimportplugin) importer **)** |
| void | [remove\_inspector\_plugin](#class-editorplugin-method-remove-inspector-plugin) **(** [EditorInspectorPlugin](class_editorinspectorplugin#class-editorinspectorplugin) plugin **)** |
| void | [remove\_scene\_import\_plugin](#class-editorplugin-method-remove-scene-import-plugin) **(** [EditorSceneImporter](class_editorsceneimporter#class-editorsceneimporter) scene\_importer **)** |
| void | [remove\_spatial\_gizmo\_plugin](#class-editorplugin-method-remove-spatial-gizmo-plugin) **(** [EditorSpatialGizmoPlugin](class_editorspatialgizmoplugin#class-editorspatialgizmoplugin) plugin **)** |
| void | [remove\_tool\_menu\_item](#class-editorplugin-method-remove-tool-menu-item) **(** [String](class_string#class-string) name **)** |
| void | [save\_external\_data](#class-editorplugin-method-save-external-data) **(** **)** virtual |
| void | [set\_force\_draw\_over\_forwarding\_enabled](#class-editorplugin-method-set-force-draw-over-forwarding-enabled) **(** **)** |
| void | [set\_input\_event\_forwarding\_always\_enabled](#class-editorplugin-method-set-input-event-forwarding-always-enabled) **(** **)** |
| void | [set\_state](#class-editorplugin-method-set-state) **(** [Dictionary](class_dictionary#class-dictionary) state **)** virtual |
| void | [set\_window\_layout](#class-editorplugin-method-set-window-layout) **(** [ConfigFile](class_configfile#class-configfile) layout **)** virtual |
| [int](class_int#class-int) | [update\_overlays](#class-editorplugin-method-update-overlays) **(** **)** const |
Signals
-------
### main\_screen\_changed ( [String](class_string#class-string) screen\_name )
Emitted when user changes the workspace (**2D**, **3D**, **Script**, **AssetLib**). Also works with custom screens defined by plugins.
### resource\_saved ( [Resource](class_resource#class-resource) resource )
### scene\_changed ( [Node](class_node#class-node) scene\_root )
Emitted when the scene is changed in the editor. The argument will return the root node of the scene that has just become active. If this scene is new and empty, the argument will be `null`.
### scene\_closed ( [String](class_string#class-string) filepath )
Emitted when user closes a scene. The argument is file path to a closed scene.
Enumerations
------------
enum **CustomControlContainer**:
* **CONTAINER\_TOOLBAR** = **0**
* **CONTAINER\_SPATIAL\_EDITOR\_MENU** = **1**
* **CONTAINER\_SPATIAL\_EDITOR\_SIDE\_LEFT** = **2**
* **CONTAINER\_SPATIAL\_EDITOR\_SIDE\_RIGHT** = **3**
* **CONTAINER\_SPATIAL\_EDITOR\_BOTTOM** = **4**
* **CONTAINER\_CANVAS\_EDITOR\_MENU** = **5**
* **CONTAINER\_CANVAS\_EDITOR\_SIDE\_LEFT** = **6**
* **CONTAINER\_CANVAS\_EDITOR\_SIDE\_RIGHT** = **7**
* **CONTAINER\_CANVAS\_EDITOR\_BOTTOM** = **8**
* **CONTAINER\_PROPERTY\_EDITOR\_BOTTOM** = **9**
* **CONTAINER\_PROJECT\_SETTING\_TAB\_LEFT** = **10**
* **CONTAINER\_PROJECT\_SETTING\_TAB\_RIGHT** = **11**
enum **DockSlot**:
* **DOCK\_SLOT\_LEFT\_UL** = **0**
* **DOCK\_SLOT\_LEFT\_BL** = **1**
* **DOCK\_SLOT\_LEFT\_UR** = **2**
* **DOCK\_SLOT\_LEFT\_BR** = **3**
* **DOCK\_SLOT\_RIGHT\_UL** = **4**
* **DOCK\_SLOT\_RIGHT\_BL** = **5**
* **DOCK\_SLOT\_RIGHT\_UR** = **6**
* **DOCK\_SLOT\_RIGHT\_BR** = **7**
* **DOCK\_SLOT\_MAX** = **8** --- Represents the size of the [DockSlot](#enum-editorplugin-dockslot) enum.
Method Descriptions
-------------------
### void add\_autoload\_singleton ( [String](class_string#class-string) name, [String](class_string#class-string) path )
Adds a script at `path` to the Autoload list as `name`.
### [ToolButton](class_toolbutton#class-toolbutton) add\_control\_to\_bottom\_panel ( [Control](class_control#class-control) control, [String](class_string#class-string) title )
Adds a control to the bottom panel (together with Output, Debug, Animation, etc). Returns a reference to the button added. It's up to you to hide/show the button when needed. When your plugin is deactivated, make sure to remove your custom control with [remove\_control\_from\_bottom\_panel](#class-editorplugin-method-remove-control-from-bottom-panel) and free it with [Node.queue\_free](class_node#class-node-method-queue-free).
### void add\_control\_to\_container ( [CustomControlContainer](#enum-editorplugin-customcontrolcontainer) container, [Control](class_control#class-control) control )
Adds a custom control to a container (see [CustomControlContainer](#enum-editorplugin-customcontrolcontainer)). There are many locations where custom controls can be added in the editor UI.
Please remember that you have to manage the visibility of your custom controls yourself (and likely hide it after adding it).
When your plugin is deactivated, make sure to remove your custom control with [remove\_control\_from\_container](#class-editorplugin-method-remove-control-from-container) and free it with [Node.queue\_free](class_node#class-node-method-queue-free).
### void add\_control\_to\_dock ( [DockSlot](#enum-editorplugin-dockslot) slot, [Control](class_control#class-control) control )
Adds the control to a specific dock slot (see [DockSlot](#enum-editorplugin-dockslot) for options).
If the dock is repositioned and as long as the plugin is active, the editor will save the dock position on further sessions.
When your plugin is deactivated, make sure to remove your custom control with [remove\_control\_from\_docks](#class-editorplugin-method-remove-control-from-docks) and free it with [Node.queue\_free](class_node#class-node-method-queue-free).
### void add\_custom\_type ( [String](class_string#class-string) type, [String](class_string#class-string) base, [Script](class_script#class-script) script, [Texture](class_texture#class-texture) icon )
Adds a custom type, which will appear in the list of nodes or resources. An icon can be optionally passed.
When given node or resource is selected, the base type will be instanced (ie, "Spatial", "Control", "Resource"), then the script will be loaded and set to this object.
You can use the virtual method [handles](#class-editorplugin-method-handles) to check if your custom object is being edited by checking the script or using the `is` keyword.
During run-time, this will be a simple object with a script so this function does not need to be called then.
### void add\_export\_plugin ( [EditorExportPlugin](class_editorexportplugin#class-editorexportplugin) plugin )
Registers a new [EditorExportPlugin](class_editorexportplugin#class-editorexportplugin). Export plugins are used to perform tasks when the project is being exported.
See [add\_inspector\_plugin](#class-editorplugin-method-add-inspector-plugin) for an example of how to register a plugin.
### void add\_import\_plugin ( [EditorImportPlugin](class_editorimportplugin#class-editorimportplugin) importer )
Registers a new [EditorImportPlugin](class_editorimportplugin#class-editorimportplugin). Import plugins are used to import custom and unsupported assets as a custom [Resource](class_resource#class-resource) type.
**Note:** If you want to import custom 3D asset formats use [add\_scene\_import\_plugin](#class-editorplugin-method-add-scene-import-plugin) instead.
See [add\_inspector\_plugin](#class-editorplugin-method-add-inspector-plugin) for an example of how to register a plugin.
### void add\_inspector\_plugin ( [EditorInspectorPlugin](class_editorinspectorplugin#class-editorinspectorplugin) plugin )
Registers a new [EditorInspectorPlugin](class_editorinspectorplugin#class-editorinspectorplugin). Inspector plugins are used to extend [EditorInspector](class_editorinspector#class-editorinspector) and provide custom configuration tools for your object's properties.
**Note:** Always use [remove\_inspector\_plugin](#class-editorplugin-method-remove-inspector-plugin) to remove the registered [EditorInspectorPlugin](class_editorinspectorplugin#class-editorinspectorplugin) when your `EditorPlugin` is disabled to prevent leaks and an unexpected behavior.
```
const MyInspectorPlugin = preload("res://addons/your_addon/path/to/your/script.gd")
var inspector_plugin = MyInspectorPlugin.new()
func _enter_tree():
add_inspector_plugin(inspector_plugin)
func _exit_tree():
remove_inspector_plugin(inspector_plugin)
```
### void add\_scene\_import\_plugin ( [EditorSceneImporter](class_editorsceneimporter#class-editorsceneimporter) scene\_importer )
Registers a new [EditorSceneImporter](class_editorsceneimporter#class-editorsceneimporter). Scene importers are used to import custom 3D asset formats as scenes.
### void add\_spatial\_gizmo\_plugin ( [EditorSpatialGizmoPlugin](class_editorspatialgizmoplugin#class-editorspatialgizmoplugin) plugin )
Registers a new [EditorSpatialGizmoPlugin](class_editorspatialgizmoplugin#class-editorspatialgizmoplugin). Gizmo plugins are used to add custom gizmos to the 3D preview viewport for a [Spatial](class_spatial#class-spatial).
See [add\_inspector\_plugin](#class-editorplugin-method-add-inspector-plugin) for an example of how to register a plugin.
### void add\_tool\_menu\_item ( [String](class_string#class-string) name, [Object](class_object#class-object) handler, [String](class_string#class-string) callback, [Variant](class_variant#class-variant) ud=null )
Adds a custom menu item to **Project > Tools** as `name` that calls `callback` on an instance of `handler` with a parameter `ud` when user activates it.
### void add\_tool\_submenu\_item ( [String](class_string#class-string) name, [Object](class_object#class-object) submenu )
Adds a custom submenu under **Project > Tools >** `name`. `submenu` should be an object of class [PopupMenu](class_popupmenu#class-popupmenu). This submenu should be cleaned up using `remove_tool_menu_item(name)`.
### void apply\_changes ( ) virtual
This method is called when the editor is about to save the project, switch to another tab, etc. It asks the plugin to apply any pending state changes to ensure consistency.
This is used, for example, in shader editors to let the plugin know that it must apply the shader code being written by the user to the object.
### [bool](class_bool#class-bool) build ( ) virtual
This method is called when the editor is about to run the project. The plugin can then perform required operations before the project runs.
This method must return a boolean. If this method returns `false`, the project will not run. The run is aborted immediately, so this also prevents all other plugins' [build](#class-editorplugin-method-build) methods from running.
### void clear ( ) virtual
Clear all the state and reset the object being edited to zero. This ensures your plugin does not keep editing a currently existing node, or a node from the wrong scene.
### void disable\_plugin ( ) virtual
Called by the engine when the user disables the `EditorPlugin` in the Plugin tab of the project settings window.
### void edit ( [Object](class_object#class-object) object ) virtual
This function is used for plugins that edit specific object types (nodes or resources). It requests the editor to edit the given object.
### void enable\_plugin ( ) virtual
Called by the engine when the user enables the `EditorPlugin` in the Plugin tab of the project settings window.
### void forward\_canvas\_draw\_over\_viewport ( [Control](class_control#class-control) overlay ) virtual
Called by the engine when the 2D editor's viewport is updated. Use the `overlay` [Control](class_control#class-control) for drawing. You can update the viewport manually by calling [update\_overlays](#class-editorplugin-method-update-overlays).
```
func forward_canvas_draw_over_viewport(overlay):
# Draw a circle at cursor position.
overlay.draw_circle(overlay.get_local_mouse_position(), 64, Color.white)
func forward_canvas_gui_input(event):
if event is InputEventMouseMotion:
# Redraw viewport when cursor is moved.
update_overlays()
return true
return false
```
### void forward\_canvas\_force\_draw\_over\_viewport ( [Control](class_control#class-control) overlay ) virtual
This method is the same as [forward\_canvas\_draw\_over\_viewport](#class-editorplugin-method-forward-canvas-draw-over-viewport), except it draws on top of everything. Useful when you need an extra layer that shows over anything else.
You need to enable calling of this method by using [set\_force\_draw\_over\_forwarding\_enabled](#class-editorplugin-method-set-force-draw-over-forwarding-enabled).
### [bool](class_bool#class-bool) forward\_canvas\_gui\_input ( [InputEvent](class_inputevent#class-inputevent) event ) virtual
Called when there is a root node in the current edited scene, [handles](#class-editorplugin-method-handles) is implemented and an [InputEvent](class_inputevent#class-inputevent) happens in the 2D viewport. Intercepts the [InputEvent](class_inputevent#class-inputevent), if `return true` `EditorPlugin` consumes the `event`, otherwise forwards `event` to other Editor classes. Example:
```
# Prevents the InputEvent to reach other Editor classes
func forward_canvas_gui_input(event):
var forward = true
return forward
```
Must `return false` in order to forward the [InputEvent](class_inputevent#class-inputevent) to other Editor classes. Example:
```
# Consumes InputEventMouseMotion and forwards other InputEvent types
func forward_canvas_gui_input(event):
var forward = false
if event is InputEventMouseMotion:
forward = true
return forward
```
### void forward\_spatial\_draw\_over\_viewport ( [Control](class_control#class-control) overlay ) virtual
Called by the engine when the 3D editor's viewport is updated. Use the `overlay` [Control](class_control#class-control) for drawing. You can update the viewport manually by calling [update\_overlays](#class-editorplugin-method-update-overlays).
```
func forward_spatial_draw_over_viewport(overlay):
# Draw a circle at cursor position.
overlay.draw_circle(overlay.get_local_mouse_position(), 64)
func forward_spatial_gui_input(camera, event):
if event is InputEventMouseMotion:
# Redraw viewport when cursor is moved.
update_overlays()
return true
return false
```
### void forward\_spatial\_force\_draw\_over\_viewport ( [Control](class_control#class-control) overlay ) virtual
This method is the same as [forward\_spatial\_draw\_over\_viewport](#class-editorplugin-method-forward-spatial-draw-over-viewport), except it draws on top of everything. Useful when you need an extra layer that shows over anything else.
You need to enable calling of this method by using [set\_force\_draw\_over\_forwarding\_enabled](#class-editorplugin-method-set-force-draw-over-forwarding-enabled).
### [bool](class_bool#class-bool) forward\_spatial\_gui\_input ( [Camera](class_camera#class-camera) camera, [InputEvent](class_inputevent#class-inputevent) event ) virtual
Called when there is a root node in the current edited scene, [handles](#class-editorplugin-method-handles) is implemented and an [InputEvent](class_inputevent#class-inputevent) happens in the 3D viewport. Intercepts the [InputEvent](class_inputevent#class-inputevent), if `return true` `EditorPlugin` consumes the `event`, otherwise forwards `event` to other Editor classes. Example:
```
# Prevents the InputEvent to reach other Editor classes
func forward_spatial_gui_input(camera, event):
var forward = true
return forward
```
Must `return false` in order to forward the [InputEvent](class_inputevent#class-inputevent) to other Editor classes. Example:
```
# Consumes InputEventMouseMotion and forwards other InputEvent types
func forward_spatial_gui_input(camera, event):
var forward = false
if event is InputEventMouseMotion:
forward = true
return forward
```
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_breakpoints ( ) virtual
This is for editors that edit script-based objects. You can return a list of breakpoints in the format (`script:line`), for example: `res://path_to_script.gd:25`.
### [EditorInterface](class_editorinterface#class-editorinterface) get\_editor\_interface ( )
Returns the [EditorInterface](class_editorinterface#class-editorinterface) object that gives you control over Godot editor's window and its functionalities.
### [Texture](class_texture#class-texture) get\_plugin\_icon ( ) virtual
Override this method in your plugin to return a [Texture](class_texture#class-texture) in order to give it an icon.
For main screen plugins, this appears at the top of the screen, to the right of the "2D", "3D", "Script", and "AssetLib" buttons.
Ideally, the plugin icon should be white with a transparent background and 16x16 pixels in size.
```
func get_plugin_icon():
# You can use a custom icon:
return preload("res://addons/my_plugin/my_plugin_icon.svg")
# Or use a built-in icon:
return get_editor_interface().get_base_control().get_icon("Node", "EditorIcons")
```
### [String](class_string#class-string) get\_plugin\_name ( ) virtual
Override this method in your plugin to provide the name of the plugin when displayed in the Godot editor.
For main screen plugins, this appears at the top of the screen, to the right of the "2D", "3D", "Script", and "AssetLib" buttons.
### [ScriptCreateDialog](class_scriptcreatedialog#class-scriptcreatedialog) get\_script\_create\_dialog ( )
Gets the Editor's dialog used for making scripts.
**Note:** Users can configure it before use.
**Warning:** Removing and freeing this node will render a part of the editor useless and may cause a crash.
### [Dictionary](class_dictionary#class-dictionary) get\_state ( ) virtual
Override this method to provide a state data you want to be saved, like view position, grid settings, folding, etc. This is used when saving the scene (so state is kept when opening it again) and for switching tabs (so state can be restored when the tab returns). This data is automatically saved for each scene in an `editstate` file in the editor metadata folder. If you want to store global (scene-independent) editor data for your plugin, you can use [get\_window\_layout](#class-editorplugin-method-get-window-layout) instead.
Use [set\_state](#class-editorplugin-method-set-state) to restore your saved state.
**Note:** This method should not be used to save important settings that should persist with the project.
**Note:** You must implement [get\_plugin\_name](#class-editorplugin-method-get-plugin-name) for the state to be stored and restored correctly.
```
func get_state():
var state = {"zoom": zoom, "preferred_color": my_color}
return state
```
### [UndoRedo](class_undoredo#class-undoredo) get\_undo\_redo ( )
Gets the undo/redo object. Most actions in the editor can be undoable, so use this object to make sure this happens when it's worth it.
### void get\_window\_layout ( [ConfigFile](class_configfile#class-configfile) layout ) virtual
Override this method to provide the GUI layout of the plugin or any other data you want to be stored. This is used to save the project's editor layout when [queue\_save\_layout](#class-editorplugin-method-queue-save-layout) is called or the editor layout was changed (for example changing the position of a dock). The data is stored in the `editor_layout.cfg` file in the editor metadata directory.
Use [set\_window\_layout](#class-editorplugin-method-set-window-layout) to restore your saved layout.
```
func get_window_layout(configuration):
configuration.set_value("MyPlugin", "window_position", $Window.position)
configuration.set_value("MyPlugin", "icon_color", $Icon.modulate)
```
### [bool](class_bool#class-bool) handles ( [Object](class_object#class-object) object ) virtual
Implement this function if your plugin edits a specific type of object (Resource or Node). If you return `true`, then you will get the functions [edit](#class-editorplugin-method-edit) and [make\_visible](#class-editorplugin-method-make-visible) called when the editor requests them. If you have declared the methods [forward\_canvas\_gui\_input](#class-editorplugin-method-forward-canvas-gui-input) and [forward\_spatial\_gui\_input](#class-editorplugin-method-forward-spatial-gui-input) these will be called too.
### [bool](class_bool#class-bool) has\_main\_screen ( ) virtual
Returns `true` if this is a main screen editor plugin (it goes in the workspace selector together with **2D**, **3D**, **Script** and **AssetLib**).
### void hide\_bottom\_panel ( )
Minimizes the bottom panel.
### void make\_bottom\_panel\_item\_visible ( [Control](class_control#class-control) item )
Makes a specific item in the bottom panel visible.
### void make\_visible ( [bool](class_bool#class-bool) visible ) virtual
This function will be called when the editor is requested to become visible. It is used for plugins that edit a specific object type.
Remember that you have to manage the visibility of all your editor controls manually.
### void queue\_save\_layout ( ) const
Queue save the project's editor layout.
### void remove\_autoload\_singleton ( [String](class_string#class-string) name )
Removes an Autoload `name` from the list.
### void remove\_control\_from\_bottom\_panel ( [Control](class_control#class-control) control )
Removes the control from the bottom panel. You have to manually [Node.queue\_free](class_node#class-node-method-queue-free) the control.
### void remove\_control\_from\_container ( [CustomControlContainer](#enum-editorplugin-customcontrolcontainer) container, [Control](class_control#class-control) control )
Removes the control from the specified container. You have to manually [Node.queue\_free](class_node#class-node-method-queue-free) the control.
### void remove\_control\_from\_docks ( [Control](class_control#class-control) control )
Removes the control from the dock. You have to manually [Node.queue\_free](class_node#class-node-method-queue-free) the control.
### void remove\_custom\_type ( [String](class_string#class-string) type )
Removes a custom type added by [add\_custom\_type](#class-editorplugin-method-add-custom-type).
### void remove\_export\_plugin ( [EditorExportPlugin](class_editorexportplugin#class-editorexportplugin) plugin )
Removes an export plugin registered by [add\_export\_plugin](#class-editorplugin-method-add-export-plugin).
### void remove\_import\_plugin ( [EditorImportPlugin](class_editorimportplugin#class-editorimportplugin) importer )
Removes an import plugin registered by [add\_import\_plugin](#class-editorplugin-method-add-import-plugin).
### void remove\_inspector\_plugin ( [EditorInspectorPlugin](class_editorinspectorplugin#class-editorinspectorplugin) plugin )
Removes an inspector plugin registered by [add\_import\_plugin](#class-editorplugin-method-add-import-plugin)
### void remove\_scene\_import\_plugin ( [EditorSceneImporter](class_editorsceneimporter#class-editorsceneimporter) scene\_importer )
Removes a scene importer registered by [add\_scene\_import\_plugin](#class-editorplugin-method-add-scene-import-plugin).
### void remove\_spatial\_gizmo\_plugin ( [EditorSpatialGizmoPlugin](class_editorspatialgizmoplugin#class-editorspatialgizmoplugin) plugin )
Removes a gizmo plugin registered by [add\_spatial\_gizmo\_plugin](#class-editorplugin-method-add-spatial-gizmo-plugin).
### void remove\_tool\_menu\_item ( [String](class_string#class-string) name )
Removes a menu `name` from **Project > Tools**.
### void save\_external\_data ( ) virtual
This method is called after the editor saves the project or when it's closed. It asks the plugin to save edited external scenes/resources.
### void set\_force\_draw\_over\_forwarding\_enabled ( )
Enables calling of [forward\_canvas\_force\_draw\_over\_viewport](#class-editorplugin-method-forward-canvas-force-draw-over-viewport) for the 2D editor and [forward\_spatial\_force\_draw\_over\_viewport](#class-editorplugin-method-forward-spatial-force-draw-over-viewport) for the 3D editor when their viewports are updated. You need to call this method only once and it will work permanently for this plugin.
### void set\_input\_event\_forwarding\_always\_enabled ( )
Use this method if you always want to receive inputs from 3D view screen inside [forward\_spatial\_gui\_input](#class-editorplugin-method-forward-spatial-gui-input). It might be especially usable if your plugin will want to use raycast in the scene.
### void set\_state ( [Dictionary](class_dictionary#class-dictionary) state ) virtual
Restore the state saved by [get\_state](#class-editorplugin-method-get-state). This method is called when the current scene tab is changed in the editor.
**Note:** Your plugin must implement [get\_plugin\_name](#class-editorplugin-method-get-plugin-name), otherwise it will not be recognized and this method will not be called.
```
func set_state(data):
zoom = data.get("zoom", 1.0)
preferred_color = data.get("my_color", Color.white)
```
### void set\_window\_layout ( [ConfigFile](class_configfile#class-configfile) layout ) virtual
Restore the plugin GUI layout and data saved by [get\_window\_layout](#class-editorplugin-method-get-window-layout). This method is called for every plugin on editor startup. Use the provided `configuration` file to read your saved data.
```
func set_window_layout(configuration):
$Window.position = configuration.get_value("MyPlugin", "window_position", Vector2())
$Icon.modulate = configuration.get_value("MyPlugin", "icon_color", Color.white)
```
### [int](class_int#class-int) update\_overlays ( ) const
Updates the overlays of the 2D and 3D editor viewport. Causes methods [forward\_canvas\_draw\_over\_viewport](#class-editorplugin-method-forward-canvas-draw-over-viewport), [forward\_canvas\_force\_draw\_over\_viewport](#class-editorplugin-method-forward-canvas-force-draw-over-viewport), [forward\_spatial\_draw\_over\_viewport](#class-editorplugin-method-forward-spatial-draw-over-viewport) and [forward\_spatial\_force\_draw\_over\_viewport](#class-editorplugin-method-forward-spatial-force-draw-over-viewport) to be called.
| programming_docs |
godot VisibilityNotifier2D VisibilityNotifier2D
====================
**Inherits:** [Node2D](class_node2d#class-node2d) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
**Inherited By:** [VisibilityEnabler2D](class_visibilityenabler2d#class-visibilityenabler2d)
Detects approximately when the node is visible on screen.
Description
-----------
The VisibilityNotifier2D detects when it is visible on the screen. It also notifies when its bounding rectangle enters or exits the screen or a viewport.
If you want nodes to be disabled automatically when they exit the screen, use [VisibilityEnabler2D](class_visibilityenabler2d#class-visibilityenabler2d) instead.
**Note:** For performance reasons, VisibilityNotifier2D uses an approximate heuristic with precision determined by [ProjectSettings.world/2d/cell\_size](class_projectsettings#class-projectsettings-property-world-2d-cell-size). If you need precise visibility checking, use another method such as adding an [Area2D](class_area2d#class-area2d) node as a child of a [Camera2D](class_camera2d#class-camera2d) node.
Tutorials
---------
* [2D Dodge The Creeps Demo](https://godotengine.org/asset-library/asset/515)
Properties
----------
| | | |
| --- | --- | --- |
| [Rect2](class_rect2#class-rect2) | [rect](#class-visibilitynotifier2d-property-rect) | `Rect2( -10, -10, 20, 20 )` |
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [is\_on\_screen](#class-visibilitynotifier2d-method-is-on-screen) **(** **)** const |
Signals
-------
### screen\_entered ( )
Emitted when the VisibilityNotifier2D enters the screen.
### screen\_exited ( )
Emitted when the VisibilityNotifier2D exits the screen.
### viewport\_entered ( [Viewport](class_viewport#class-viewport) viewport )
Emitted when the VisibilityNotifier2D enters a [Viewport](class_viewport#class-viewport)'s view.
### viewport\_exited ( [Viewport](class_viewport#class-viewport) viewport )
Emitted when the VisibilityNotifier2D exits a [Viewport](class_viewport#class-viewport)'s view.
Property Descriptions
---------------------
### [Rect2](class_rect2#class-rect2) rect
| | |
| --- | --- |
| *Default* | `Rect2( -10, -10, 20, 20 )` |
| *Setter* | set\_rect(value) |
| *Getter* | get\_rect() |
The VisibilityNotifier2D's bounding rectangle.
Method Descriptions
-------------------
### [bool](class_bool#class-bool) is\_on\_screen ( ) const
If `true`, the bounding rectangle is on the screen.
**Note:** It takes one frame for the node's visibility to be assessed once added to the scene tree, so this method will return `false` right after it is instantiated, even if it will be on screen in the draw pass.
godot SoftBody SoftBody
========
**Inherits:** [MeshInstance](class_meshinstance#class-meshinstance) **<** [GeometryInstance](class_geometryinstance#class-geometryinstance) **<** [VisualInstance](class_visualinstance#class-visualinstance) **<** [CullInstance](class_cullinstance#class-cullinstance) **<** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
A soft mesh physics body.
Description
-----------
A deformable physics body. Used to create elastic or deformable objects such as cloth, rubber, or other flexible materials.
**Note:** There are many known bugs in `SoftBody`. Therefore, it's not recommended to use them for things that can affect gameplay (such as a player character made entirely out of soft bodies).
Tutorials
---------
* [Using SoftBody](https://docs.godotengine.org/en/3.5/tutorials/physics/soft_body.html)
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [areaAngular\_stiffness](#class-softbody-property-areaangular-stiffness) | `0.5` |
| [int](class_int#class-int) | [collision\_layer](#class-softbody-property-collision-layer) | `1` |
| [int](class_int#class-int) | [collision\_mask](#class-softbody-property-collision-mask) | `1` |
| [float](class_float#class-float) | [damping\_coefficient](#class-softbody-property-damping-coefficient) | `0.01` |
| [float](class_float#class-float) | [drag\_coefficient](#class-softbody-property-drag-coefficient) | `0.0` |
| [float](class_float#class-float) | [linear\_stiffness](#class-softbody-property-linear-stiffness) | `0.5` |
| [NodePath](class_nodepath#class-nodepath) | [parent\_collision\_ignore](#class-softbody-property-parent-collision-ignore) | `NodePath("")` |
| [bool](class_bool#class-bool) | [physics\_enabled](#class-softbody-property-physics-enabled) | `true` |
| [float](class_float#class-float) | [pose\_matching\_coefficient](#class-softbody-property-pose-matching-coefficient) | `0.0` |
| [float](class_float#class-float) | [pressure\_coefficient](#class-softbody-property-pressure-coefficient) | `0.0` |
| [bool](class_bool#class-bool) | [ray\_pickable](#class-softbody-property-ray-pickable) | `true` |
| [int](class_int#class-int) | [simulation\_precision](#class-softbody-property-simulation-precision) | `5` |
| [float](class_float#class-float) | [total\_mass](#class-softbody-property-total-mass) | `1.0` |
| [float](class_float#class-float) | [volume\_stiffness](#class-softbody-property-volume-stiffness) | `0.5` |
Methods
-------
| | |
| --- | --- |
| void | [add\_collision\_exception\_with](#class-softbody-method-add-collision-exception-with) **(** [Node](class_node#class-node) body **)** |
| [Array](class_array#class-array) | [get\_collision\_exceptions](#class-softbody-method-get-collision-exceptions) **(** **)** |
| [bool](class_bool#class-bool) | [get\_collision\_layer\_bit](#class-softbody-method-get-collision-layer-bit) **(** [int](class_int#class-int) bit **)** const |
| [bool](class_bool#class-bool) | [get\_collision\_mask\_bit](#class-softbody-method-get-collision-mask-bit) **(** [int](class_int#class-int) bit **)** const |
| [Vector3](class_vector3#class-vector3) | [get\_point\_transform](#class-softbody-method-get-point-transform) **(** [int](class_int#class-int) point\_index **)** |
| [bool](class_bool#class-bool) | [is\_point\_pinned](#class-softbody-method-is-point-pinned) **(** [int](class_int#class-int) point\_index **)** const |
| void | [remove\_collision\_exception\_with](#class-softbody-method-remove-collision-exception-with) **(** [Node](class_node#class-node) body **)** |
| void | [set\_collision\_layer\_bit](#class-softbody-method-set-collision-layer-bit) **(** [int](class_int#class-int) bit, [bool](class_bool#class-bool) value **)** |
| void | [set\_collision\_mask\_bit](#class-softbody-method-set-collision-mask-bit) **(** [int](class_int#class-int) bit, [bool](class_bool#class-bool) value **)** |
| void | [set\_point\_pinned](#class-softbody-method-set-point-pinned) **(** [int](class_int#class-int) point\_index, [bool](class_bool#class-bool) pinned, [NodePath](class_nodepath#class-nodepath) attachment\_path=NodePath("") **)** |
Property Descriptions
---------------------
### [float](class_float#class-float) areaAngular\_stiffness
| | |
| --- | --- |
| *Default* | `0.5` |
| *Setter* | set\_areaAngular\_stiffness(value) |
| *Getter* | get\_areaAngular\_stiffness() |
### [int](class_int#class-int) collision\_layer
| | |
| --- | --- |
| *Default* | `1` |
| *Setter* | set\_collision\_layer(value) |
| *Getter* | get\_collision\_layer() |
The physics layers this SoftBody is in.
Collidable objects can exist in any of 32 different layers. These layers work like a tagging system, and are not visual. A collidable can use these layers to select with which objects it can collide, using the collision\_mask property.
A contact is detected if object A is in any of the layers that object B scans, or object B is in any layer scanned by object A. See [Collision layers and masks](https://docs.godotengine.org/en/3.5/tutorials/physics/physics_introduction.html#collision-layers-and-masks) in the documentation for more information.
### [int](class_int#class-int) collision\_mask
| | |
| --- | --- |
| *Default* | `1` |
| *Setter* | set\_collision\_mask(value) |
| *Getter* | get\_collision\_mask() |
The physics layers this SoftBody scans for collisions. See [Collision layers and masks](https://docs.godotengine.org/en/3.5/tutorials/physics/physics_introduction.html#collision-layers-and-masks) in the documentation for more information.
### [float](class_float#class-float) damping\_coefficient
| | |
| --- | --- |
| *Default* | `0.01` |
| *Setter* | set\_damping\_coefficient(value) |
| *Getter* | get\_damping\_coefficient() |
### [float](class_float#class-float) drag\_coefficient
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_drag\_coefficient(value) |
| *Getter* | get\_drag\_coefficient() |
### [float](class_float#class-float) linear\_stiffness
| | |
| --- | --- |
| *Default* | `0.5` |
| *Setter* | set\_linear\_stiffness(value) |
| *Getter* | get\_linear\_stiffness() |
### [NodePath](class_nodepath#class-nodepath) parent\_collision\_ignore
| | |
| --- | --- |
| *Default* | `NodePath("")` |
| *Setter* | set\_parent\_collision\_ignore(value) |
| *Getter* | get\_parent\_collision\_ignore() |
[NodePath](class_nodepath#class-nodepath) to a [CollisionObject](class_collisionobject#class-collisionobject) this SoftBody should avoid clipping.
### [bool](class_bool#class-bool) physics\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_physics\_enabled(value) |
| *Getter* | is\_physics\_enabled() |
If `true`, the `SoftBody` is simulated in physics. Can be set to `false` to pause the physics simulation.
### [float](class_float#class-float) pose\_matching\_coefficient
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_pose\_matching\_coefficient(value) |
| *Getter* | get\_pose\_matching\_coefficient() |
### [float](class_float#class-float) pressure\_coefficient
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_pressure\_coefficient(value) |
| *Getter* | get\_pressure\_coefficient() |
### [bool](class_bool#class-bool) ray\_pickable
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_ray\_pickable(value) |
| *Getter* | is\_ray\_pickable() |
If `true`, the `SoftBody` will respond to [RayCast](class_raycast#class-raycast)s.
### [int](class_int#class-int) simulation\_precision
| | |
| --- | --- |
| *Default* | `5` |
| *Setter* | set\_simulation\_precision(value) |
| *Getter* | get\_simulation\_precision() |
Increasing this value will improve the resulting simulation, but can affect performance. Use with care.
### [float](class_float#class-float) total\_mass
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_total\_mass(value) |
| *Getter* | get\_total\_mass() |
The SoftBody's mass.
### [float](class_float#class-float) volume\_stiffness
| | |
| --- | --- |
| *Default* | `0.5` |
| *Setter* | set\_volume\_stiffness(value) |
| *Getter* | get\_volume\_stiffness() |
Method Descriptions
-------------------
### void add\_collision\_exception\_with ( [Node](class_node#class-node) body )
Adds a body to the list of bodies that this body can't collide with.
### [Array](class_array#class-array) get\_collision\_exceptions ( )
Returns an array of nodes that were added as collision exceptions for this body.
### [bool](class_bool#class-bool) get\_collision\_layer\_bit ( [int](class_int#class-int) bit ) const
Returns an individual bit on the collision mask.
### [bool](class_bool#class-bool) get\_collision\_mask\_bit ( [int](class_int#class-int) bit ) const
Returns an individual bit on the collision mask.
### [Vector3](class_vector3#class-vector3) get\_point\_transform ( [int](class_int#class-int) point\_index )
Returns local translation of a vertex in the surface array.
### [bool](class_bool#class-bool) is\_point\_pinned ( [int](class_int#class-int) point\_index ) const
Returns `true` if vertex is set to pinned.
### void remove\_collision\_exception\_with ( [Node](class_node#class-node) body )
Removes a body from the list of bodies that this body can't collide with.
### void set\_collision\_layer\_bit ( [int](class_int#class-int) bit, [bool](class_bool#class-bool) value )
Sets individual bits on the layer mask. Use this if you only need to change one layer's value.
### void set\_collision\_mask\_bit ( [int](class_int#class-int) bit, [bool](class_bool#class-bool) value )
Sets individual bits on the collision mask. Use this if you only need to change one layer's value.
### void set\_point\_pinned ( [int](class_int#class-int) point\_index, [bool](class_bool#class-bool) pinned, [NodePath](class_nodepath#class-nodepath) attachment\_path=NodePath("") )
Sets the pinned state of a surface vertex. When set to `true`, the optional `attachment_path` can define a [Spatial](class_spatial#class-spatial) the pinned vertex will be attached to.
godot AudioEffectInstance AudioEffectInstance
===================
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [AudioEffectSpectrumAnalyzerInstance](class_audioeffectspectrumanalyzerinstance#class-audioeffectspectrumanalyzerinstance)
godot VisualScriptPropertySet VisualScriptPropertySet
=======================
**Inherits:** [VisualScriptNode](class_visualscriptnode#class-visualscriptnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A Visual Script node that sets a property of an [Object](class_object#class-object).
Description
-----------
`VisualScriptPropertySet` can set the value of any property from the current object or other objects.
Properties
----------
| | | |
| --- | --- | --- |
| [AssignOp](#enum-visualscriptpropertyset-assignop) | [assign\_op](#class-visualscriptpropertyset-property-assign-op) | `0` |
| [String](class_string#class-string) | [base\_script](#class-visualscriptpropertyset-property-base-script) | |
| [String](class_string#class-string) | [base\_type](#class-visualscriptpropertyset-property-base-type) | `"Object"` |
| [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) | [basic\_type](#class-visualscriptpropertyset-property-basic-type) | |
| [String](class_string#class-string) | [index](#class-visualscriptpropertyset-property-index) | |
| [NodePath](class_nodepath#class-nodepath) | [node\_path](#class-visualscriptpropertyset-property-node-path) | |
| [String](class_string#class-string) | [property](#class-visualscriptpropertyset-property-property) | `""` |
| [CallMode](#enum-visualscriptpropertyset-callmode) | [set\_mode](#class-visualscriptpropertyset-property-set-mode) | `0` |
Enumerations
------------
enum **CallMode**:
* **CALL\_MODE\_SELF** = **0** --- The property will be set on this [Object](class_object#class-object).
* **CALL\_MODE\_NODE\_PATH** = **1** --- The property will be set on the given [Node](class_node#class-node) in the scene tree.
* **CALL\_MODE\_INSTANCE** = **2** --- The property will be set on an instanced node with the given type and script.
* **CALL\_MODE\_BASIC\_TYPE** = **3** --- The property will be set on a GDScript basic type (e.g. [Vector2](class_vector2#class-vector2)).
enum **AssignOp**:
* **ASSIGN\_OP\_NONE** = **0** --- The property will be assigned regularly.
* **ASSIGN\_OP\_ADD** = **1** --- The value will be added to the property. Equivalent of doing `+=`.
* **ASSIGN\_OP\_SUB** = **2** --- The value will be subtracted from the property. Equivalent of doing `-=`.
* **ASSIGN\_OP\_MUL** = **3** --- The property will be multiplied by the value. Equivalent of doing `*=`.
* **ASSIGN\_OP\_DIV** = **4** --- The property will be divided by the value. Equivalent of doing `/=`.
* **ASSIGN\_OP\_MOD** = **5** --- A modulo operation will be performed on the property and the value. Equivalent of doing `%=`.
* **ASSIGN\_OP\_SHIFT\_LEFT** = **6** --- The property will be binarly shifted to the left by the given value. Equivalent of doing `<<`.
* **ASSIGN\_OP\_SHIFT\_RIGHT** = **7** --- The property will be binarly shifted to the right by the given value. Equivalent of doing `>>`.
* **ASSIGN\_OP\_BIT\_AND** = **8** --- A binary `AND` operation will be performed on the property. Equivalent of doing `&=`.
* **ASSIGN\_OP\_BIT\_OR** = **9** --- A binary `OR` operation will be performed on the property. Equivalent of doing `|=`.
* **ASSIGN\_OP\_BIT\_XOR** = **10** --- A binary `XOR` operation will be performed on the property. Equivalent of doing `^=`.
Property Descriptions
---------------------
### [AssignOp](#enum-visualscriptpropertyset-assignop) assign\_op
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_assign\_op(value) |
| *Getter* | get\_assign\_op() |
The additional operation to perform when assigning. See [AssignOp](#enum-visualscriptpropertyset-assignop) for options.
### [String](class_string#class-string) base\_script
| | |
| --- | --- |
| *Setter* | set\_base\_script(value) |
| *Getter* | get\_base\_script() |
The script to be used when [set\_mode](#class-visualscriptpropertyset-property-set-mode) is set to [CALL\_MODE\_INSTANCE](#class-visualscriptpropertyset-constant-call-mode-instance).
### [String](class_string#class-string) base\_type
| | |
| --- | --- |
| *Default* | `"Object"` |
| *Setter* | set\_base\_type(value) |
| *Getter* | get\_base\_type() |
The base type to be used when [set\_mode](#class-visualscriptpropertyset-property-set-mode) is set to [CALL\_MODE\_INSTANCE](#class-visualscriptpropertyset-constant-call-mode-instance).
### [Variant.Type](class_%40globalscope#enum-globalscope-variant-type) basic\_type
| | |
| --- | --- |
| *Setter* | set\_basic\_type(value) |
| *Getter* | get\_basic\_type() |
The type to be used when [set\_mode](#class-visualscriptpropertyset-property-set-mode) is set to [CALL\_MODE\_BASIC\_TYPE](#class-visualscriptpropertyset-constant-call-mode-basic-type).
### [String](class_string#class-string) index
| | |
| --- | --- |
| *Setter* | set\_index(value) |
| *Getter* | get\_index() |
The indexed name of the property to set. See [Object.set\_indexed](class_object#class-object-method-set-indexed) for details.
### [NodePath](class_nodepath#class-nodepath) node\_path
| | |
| --- | --- |
| *Setter* | set\_base\_path(value) |
| *Getter* | get\_base\_path() |
The node path to use when [set\_mode](#class-visualscriptpropertyset-property-set-mode) is set to [CALL\_MODE\_NODE\_PATH](#class-visualscriptpropertyset-constant-call-mode-node-path).
### [String](class_string#class-string) property
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_property(value) |
| *Getter* | get\_property() |
The name of the property to set. Changing this will clear [index](#class-visualscriptpropertyset-property-index).
### [CallMode](#enum-visualscriptpropertyset-callmode) set\_mode
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_call\_mode(value) |
| *Getter* | get\_call\_mode() |
`set_mode` determines the target object on which the property will be set. See [CallMode](#enum-visualscriptpropertyset-callmode) for options.
godot SceneTreeTween SceneTreeTween
==============
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Lightweight object used for general-purpose animation via script, using [Tweener](class_tweener#class-tweener)s.
Description
-----------
`SceneTreeTween` is a tween managed by the scene tree. As opposed to [Tween](class_tween#class-tween), it does not require the instantiation of a node.
`SceneTreeTween`s are more light-weight than [AnimationPlayer](class_animationplayer#class-animationplayer), so they are very much suited for simple animations or general tasks that don't require visual tweaking provided by the editor. They can be used in a fire-and-forget manner for some logic that normally would be done by code. You can e.g. make something shoot periodically by using a looped [CallbackTweener](class_callbacktweener#class-callbacktweener) with a delay.
A `SceneTreeTween` can be created by using either [SceneTree.create\_tween](class_scenetree#class-scenetree-method-create-tween) or [Node.create\_tween](class_node#class-node-method-create-tween). `SceneTreeTween`s created manually (i.e. by using `Tween.new()`) are invalid. They can't be used for tweening values, but you can do manual interpolation with [interpolate\_value](#class-scenetreetween-method-interpolate-value).
A tween animation is created by adding [Tweener](class_tweener#class-tweener)s to the `SceneTreeTween` object, using [tween\_property](#class-scenetreetween-method-tween-property), [tween\_interval](#class-scenetreetween-method-tween-interval), [tween\_callback](#class-scenetreetween-method-tween-callback) or [tween\_method](#class-scenetreetween-method-tween-method):
```
var tween = get_tree().create_tween()
tween.tween_property($Sprite, "modulate", Color.red, 1)
tween.tween_property($Sprite, "scale", Vector2(), 1)
tween.tween_callback($Sprite, "queue_free")
```
This sequence will make the `$Sprite` node turn red, then shrink, before finally calling [Node.queue\_free](class_node#class-node-method-queue-free) to free the sprite. [Tweener](class_tweener#class-tweener)s are executed one after another by default. This behavior can be changed using [parallel](#class-scenetreetween-method-parallel) and [set\_parallel](#class-scenetreetween-method-set-parallel).
When a [Tweener](class_tweener#class-tweener) is created with one of the `tween_*` methods, a chained method call can be used to tweak the properties of this [Tweener](class_tweener#class-tweener). For example, if you want to set a different transition type in the above example, you can use [set\_trans](#class-scenetreetween-method-set-trans):
```
var tween = get_tree().create_tween()
tween.tween_property($Sprite, "modulate", Color.red, 1).set_trans(Tween.TRANS_SINE)
tween.tween_property($Sprite, "scale", Vector2(), 1).set_trans(Tween.TRANS_BOUNCE)
tween.tween_callback($Sprite, "queue_free")
```
Most of the `SceneTreeTween` methods can be chained this way too. In the following example the `SceneTreeTween` is bound to the running script's node and a default transition is set for its [Tweener](class_tweener#class-tweener)s:
```
var tween = get_tree().create_tween().bind_node(self).set_trans(Tween.TRANS_ELASTIC)
tween.tween_property($Sprite, "modulate", Color.red, 1)
tween.tween_property($Sprite, "scale", Vector2(), 1)
tween.tween_callback($Sprite, "queue_free")
```
Another interesting use for `SceneTreeTween`s is animating arbitrary sets of objects:
```
var tween = create_tween()
for sprite in get_children():
tween.tween_property(sprite, "position", Vector2(0, 0), 1)
```
In the example above, all children of a node are moved one after another to position (0, 0).
You should avoid using more than one `SceneTreeTween` per object's property. If two or more tweens animate one property at the same time, the last one created will take priority and assign the final value. If you want to interrupt and restart an animation, consider assigning the `SceneTreeTween` to a variable:
```
var tween
func animate():
if tween:
tween.kill() # Abort the previous animation.
tween = create_tween()
```
Some [Tweener](class_tweener#class-tweener)s use transitions and eases. The first accepts a [TransitionType](class_tween#enum-tween-transitiontype) constant, and refers to the way the timing of the animation is handled (see [easings.net](https://easings.net/) for some examples). The second accepts an [EaseType](class_tween#enum-tween-easetype) constant, and controls where the `trans_type` is applied to the interpolation (in the beginning, the end, or both). If you don't know which transition and easing to pick, you can try different [TransitionType](class_tween#enum-tween-transitiontype) constants with [Tween.EASE\_IN\_OUT](class_tween#class-tween-constant-ease-in-out), and use the one that looks best.
[Tween easing and transition types cheatsheet](https://raw.githubusercontent.com/godotengine/godot-docs/master/img/tween_cheatsheet.png)
**Note:** All `SceneTreeTween`s will automatically start by default. To prevent a `SceneTreeTween` from autostarting, you can call [stop](#class-scenetreetween-method-stop) immediately after it is created.
**Note:** `SceneTreeTween`s are processing after all of nodes in the current frame, i.e. after [Node.\_process](class_node#class-node-method-process) or [Node.\_physics\_process](class_node#class-node-method-physics-process) (depending on [TweenProcessMode](class_tween#enum-tween-tweenprocessmode)).
Methods
-------
| | |
| --- | --- |
| [SceneTreeTween](#class-scenetreetween) | [bind\_node](#class-scenetreetween-method-bind-node) **(** [Node](class_node#class-node) node **)** |
| [SceneTreeTween](#class-scenetreetween) | [chain](#class-scenetreetween-method-chain) **(** **)** |
| [bool](class_bool#class-bool) | [custom\_step](#class-scenetreetween-method-custom-step) **(** [float](class_float#class-float) delta **)** |
| [float](class_float#class-float) | [get\_total\_elapsed\_time](#class-scenetreetween-method-get-total-elapsed-time) **(** **)** const |
| [Variant](class_variant#class-variant) | [interpolate\_value](#class-scenetreetween-method-interpolate-value) **(** [Variant](class_variant#class-variant) initial\_value, [Variant](class_variant#class-variant) delta\_value, [float](class_float#class-float) elapsed\_time, [float](class_float#class-float) duration, [TransitionType](class_tween#enum-tween-transitiontype) trans\_type, [EaseType](class_tween#enum-tween-easetype) ease\_type **)** const |
| [bool](class_bool#class-bool) | [is\_running](#class-scenetreetween-method-is-running) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_valid](#class-scenetreetween-method-is-valid) **(** **)** const |
| void | [kill](#class-scenetreetween-method-kill) **(** **)** |
| [SceneTreeTween](#class-scenetreetween) | [parallel](#class-scenetreetween-method-parallel) **(** **)** |
| void | [pause](#class-scenetreetween-method-pause) **(** **)** |
| void | [play](#class-scenetreetween-method-play) **(** **)** |
| [SceneTreeTween](#class-scenetreetween) | [set\_ease](#class-scenetreetween-method-set-ease) **(** [EaseType](class_tween#enum-tween-easetype) ease **)** |
| [SceneTreeTween](#class-scenetreetween) | [set\_loops](#class-scenetreetween-method-set-loops) **(** [int](class_int#class-int) loops=0 **)** |
| [SceneTreeTween](#class-scenetreetween) | [set\_parallel](#class-scenetreetween-method-set-parallel) **(** [bool](class_bool#class-bool) parallel=true **)** |
| [SceneTreeTween](#class-scenetreetween) | [set\_pause\_mode](#class-scenetreetween-method-set-pause-mode) **(** [TweenPauseMode](#enum-scenetreetween-tweenpausemode) mode **)** |
| [SceneTreeTween](#class-scenetreetween) | [set\_process\_mode](#class-scenetreetween-method-set-process-mode) **(** [TweenProcessMode](class_tween#enum-tween-tweenprocessmode) mode **)** |
| [SceneTreeTween](#class-scenetreetween) | [set\_speed\_scale](#class-scenetreetween-method-set-speed-scale) **(** [float](class_float#class-float) speed **)** |
| [SceneTreeTween](#class-scenetreetween) | [set\_trans](#class-scenetreetween-method-set-trans) **(** [TransitionType](class_tween#enum-tween-transitiontype) trans **)** |
| void | [stop](#class-scenetreetween-method-stop) **(** **)** |
| [CallbackTweener](class_callbacktweener#class-callbacktweener) | [tween\_callback](#class-scenetreetween-method-tween-callback) **(** [Object](class_object#class-object) object, [String](class_string#class-string) method, [Array](class_array#class-array) binds=[ ] **)** |
| [IntervalTweener](class_intervaltweener#class-intervaltweener) | [tween\_interval](#class-scenetreetween-method-tween-interval) **(** [float](class_float#class-float) time **)** |
| [MethodTweener](class_methodtweener#class-methodtweener) | [tween\_method](#class-scenetreetween-method-tween-method) **(** [Object](class_object#class-object) object, [String](class_string#class-string) method, [Variant](class_variant#class-variant) from, [Variant](class_variant#class-variant) to, [float](class_float#class-float) duration, [Array](class_array#class-array) binds=[ ] **)** |
| [PropertyTweener](class_propertytweener#class-propertytweener) | [tween\_property](#class-scenetreetween-method-tween-property) **(** [Object](class_object#class-object) object, [NodePath](class_nodepath#class-nodepath) property, [Variant](class_variant#class-variant) final\_val, [float](class_float#class-float) duration **)** |
Signals
-------
### finished ( )
Emitted when the `SceneTreeTween` has finished all tweening. Never emitted when the `SceneTreeTween` is set to infinite looping (see [set\_loops](#class-scenetreetween-method-set-loops)).
**Note:** The `SceneTreeTween` is removed (invalidated) in the next processing frame after this signal is emitted. Calling [stop](#class-scenetreetween-method-stop) inside the signal callback will prevent the `SceneTreeTween` from being removed.
### loop\_finished ( [int](class_int#class-int) loop\_count )
Emitted when a full loop is complete (see [set\_loops](#class-scenetreetween-method-set-loops)), providing the loop index. This signal is not emitted after the final loop, use [finished](#class-scenetreetween-signal-finished) instead for this case.
### step\_finished ( [int](class_int#class-int) idx )
Emitted when one step of the `SceneTreeTween` is complete, providing the step index. One step is either a single [Tweener](class_tweener#class-tweener) or a group of [Tweener](class_tweener#class-tweener)s running in parallel.
Enumerations
------------
enum **TweenPauseMode**:
* **TWEEN\_PAUSE\_BOUND** = **0** --- If the `SceneTreeTween` has a bound node, it will process when that node can process (see [Node.pause\_mode](class_node#class-node-property-pause-mode)). Otherwise it's the same as [TWEEN\_PAUSE\_STOP](#class-scenetreetween-constant-tween-pause-stop).
* **TWEEN\_PAUSE\_STOP** = **1** --- If [SceneTree](class_scenetree#class-scenetree) is paused, the `SceneTreeTween` will also pause.
* **TWEEN\_PAUSE\_PROCESS** = **2** --- The `SceneTreeTween` will process regardless of whether [SceneTree](class_scenetree#class-scenetree) is paused.
Method Descriptions
-------------------
### [SceneTreeTween](#class-scenetreetween) bind\_node ( [Node](class_node#class-node) node )
Binds this `SceneTreeTween` with the given `node`. `SceneTreeTween`s are processed directly by the [SceneTree](class_scenetree#class-scenetree), so they run independently of the animated nodes. When you bind a [Node](class_node#class-node) with the `SceneTreeTween`, the `SceneTreeTween` will halt the animation when the object is not inside tree and the `SceneTreeTween` will be automatically killed when the bound object is freed. Also [TWEEN\_PAUSE\_BOUND](#class-scenetreetween-constant-tween-pause-bound) will make the pausing behavior dependent on the bound node.
For a shorter way to create and bind a `SceneTreeTween`, you can use [Node.create\_tween](class_node#class-node-method-create-tween).
### [SceneTreeTween](#class-scenetreetween) chain ( )
Used to chain two [Tweener](class_tweener#class-tweener)s after [set\_parallel](#class-scenetreetween-method-set-parallel) is called with `true`.
```
var tween = create_tween().set_parallel(true)
tween.tween_property(...)
tween.tween_property(...) # Will run parallelly with above.
tween.chain().tween_property(...) # Will run after two above are finished.
```
### [bool](class_bool#class-bool) custom\_step ( [float](class_float#class-float) delta )
Processes the `SceneTreeTween` by the given `delta` value, in seconds. This is mostly useful for manual control when the `SceneTreeTween` is paused. It can also be used to end the `SceneTreeTween` animation immediately, by setting `delta` longer than the whole duration of the `SceneTreeTween` animation.
Returns `true` if the `SceneTreeTween` still has [Tweener](class_tweener#class-tweener)s that haven't finished.
**Note:** The `SceneTreeTween` will become invalid in the next processing frame after its animation finishes. Calling [stop](#class-scenetreetween-method-stop) after performing [custom\_step](#class-scenetreetween-method-custom-step) instead keeps and resets the `SceneTreeTween`.
### [float](class_float#class-float) get\_total\_elapsed\_time ( ) const
Returns the total time in seconds the `SceneTreeTween` has been animating (i.e. the time since it started, not counting pauses etc.). The time is affected by [set\_speed\_scale](#class-scenetreetween-method-set-speed-scale), and [stop](#class-scenetreetween-method-stop) will reset it to `0`.
**Note:** As it results from accumulating frame deltas, the time returned after the `SceneTreeTween` has finished animating will be slightly greater than the actual `SceneTreeTween` duration.
### [Variant](class_variant#class-variant) interpolate\_value ( [Variant](class_variant#class-variant) initial\_value, [Variant](class_variant#class-variant) delta\_value, [float](class_float#class-float) elapsed\_time, [float](class_float#class-float) duration, [TransitionType](class_tween#enum-tween-transitiontype) trans\_type, [EaseType](class_tween#enum-tween-easetype) ease\_type ) const
This method can be used for manual interpolation of a value, when you don't want `SceneTreeTween` to do animating for you. It's similar to [@GDScript.lerp](class_%40gdscript#class-gdscript-method-lerp), but with support for custom transition and easing.
`initial_value` is the starting value of the interpolation.
`delta_value` is the change of the value in the interpolation, i.e. it's equal to `final_value - initial_value`.
`elapsed_time` is the time in seconds that passed after the interpolation started and it's used to control the position of the interpolation. E.g. when it's equal to half of the `duration`, the interpolated value will be halfway between initial and final values. This value can also be greater than `duration` or lower than 0, which will extrapolate the value.
`duration` is the total time of the interpolation.
**Note:** If `duration` is equal to `0`, the method will always return the final value, regardless of `elapsed_time` provided.
### [bool](class_bool#class-bool) is\_running ( ) const
Returns whether the `SceneTreeTween` is currently running, i.e. it wasn't paused and it's not finished.
### [bool](class_bool#class-bool) is\_valid ( ) const
Returns whether the `SceneTreeTween` is valid. A valid `SceneTreeTween` is a `SceneTreeTween` contained by the scene tree (i.e. the array from [SceneTree.get\_processed\_tweens](class_scenetree#class-scenetree-method-get-processed-tweens) will contain this `SceneTreeTween`). A `SceneTreeTween` might become invalid when it has finished tweening, is killed, or when created with `SceneTreeTween.new()`. Invalid `SceneTreeTween`s can't have [Tweener](class_tweener#class-tweener)s appended. You can however still use [interpolate\_value](#class-scenetreetween-method-interpolate-value).
### void kill ( )
Aborts all tweening operations and invalidates the `SceneTreeTween`.
### [SceneTreeTween](#class-scenetreetween) parallel ( )
Makes the next [Tweener](class_tweener#class-tweener) run parallelly to the previous one. Example:
```
var tween = create_tween()
tween.tween_property(...)
tween.parallel().tween_property(...)
tween.parallel().tween_property(...)
```
All [Tweener](class_tweener#class-tweener)s in the example will run at the same time.
You can make the `SceneTreeTween` parallel by default by using [set\_parallel](#class-scenetreetween-method-set-parallel).
### void pause ( )
Pauses the tweening. The animation can be resumed by using [play](#class-scenetreetween-method-play).
### void play ( )
Resumes a paused or stopped `SceneTreeTween`.
### [SceneTreeTween](#class-scenetreetween) set\_ease ( [EaseType](class_tween#enum-tween-easetype) ease )
Sets the default ease type for [PropertyTweener](class_propertytweener#class-propertytweener)s and [MethodTweener](class_methodtweener#class-methodtweener)s animated by this `SceneTreeTween`.
### [SceneTreeTween](#class-scenetreetween) set\_loops ( [int](class_int#class-int) loops=0 )
Sets the number of times the tweening sequence will be repeated, i.e. `set_loops(2)` will run the animation twice.
Calling this method without arguments will make the `SceneTreeTween` run infinitely, until either it is killed with [kill](#class-scenetreetween-method-kill), the `SceneTreeTween`'s bound node is freed, or all the animated objects have been freed (which makes further animation impossible).
**Warning:** Make sure to always add some duration/delay when using infinite loops. To prevent the game freezing, 0-duration looped animations (e.g. a single [CallbackTweener](class_callbacktweener#class-callbacktweener) with no delay) are stopped after a small number of loops, which may produce unexpected results. If a `SceneTreeTween`'s lifetime depends on some node, always use [bind\_node](#class-scenetreetween-method-bind-node).
### [SceneTreeTween](#class-scenetreetween) set\_parallel ( [bool](class_bool#class-bool) parallel=true )
If `parallel` is `true`, the [Tweener](class_tweener#class-tweener)s appended after this method will by default run simultaneously, as opposed to sequentially.
### [SceneTreeTween](#class-scenetreetween) set\_pause\_mode ( [TweenPauseMode](#enum-scenetreetween-tweenpausemode) mode )
Determines the behavior of the `SceneTreeTween` when the [SceneTree](class_scenetree#class-scenetree) is paused. Check [TweenPauseMode](#enum-scenetreetween-tweenpausemode) for options.
Default value is [TWEEN\_PAUSE\_BOUND](#class-scenetreetween-constant-tween-pause-bound).
### [SceneTreeTween](#class-scenetreetween) set\_process\_mode ( [TweenProcessMode](class_tween#enum-tween-tweenprocessmode) mode )
Determines whether the `SceneTreeTween` should run during idle frame (see [Node.\_process](class_node#class-node-method-process)) or physics frame (see [Node.\_physics\_process](class_node#class-node-method-physics-process).
Default value is [Tween.TWEEN\_PROCESS\_IDLE](class_tween#class-tween-constant-tween-process-idle).
### [SceneTreeTween](#class-scenetreetween) set\_speed\_scale ( [float](class_float#class-float) speed )
Scales the speed of tweening. This affects all [Tweener](class_tweener#class-tweener)s and their delays.
### [SceneTreeTween](#class-scenetreetween) set\_trans ( [TransitionType](class_tween#enum-tween-transitiontype) trans )
Sets the default transition type for [PropertyTweener](class_propertytweener#class-propertytweener)s and [MethodTweener](class_methodtweener#class-methodtweener)s animated by this `SceneTreeTween`.
### void stop ( )
Stops the tweening and resets the `SceneTreeTween` to its initial state. This will not remove any appended [Tweener](class_tweener#class-tweener)s.
### [CallbackTweener](class_callbacktweener#class-callbacktweener) tween\_callback ( [Object](class_object#class-object) object, [String](class_string#class-string) method, [Array](class_array#class-array) binds=[ ] )
Creates and appends a [CallbackTweener](class_callbacktweener#class-callbacktweener). This method can be used to call an arbitrary method in any object. Use `binds` to bind additional arguments for the call.
Example: object that keeps shooting every 1 second.
```
var tween = get_tree().create_tween().set_loops()
tween.tween_callback(self, "shoot").set_delay(1)
```
Example: turning a sprite red and then blue, with 2 second delay.
```
var tween = get_tree().create_tween()
tween.tween_callback($Sprite, "set_modulate", [Color.red]).set_delay(2)
tween.tween_callback($Sprite, "set_modulate", [Color.blue]).set_delay(2)
```
### [IntervalTweener](class_intervaltweener#class-intervaltweener) tween\_interval ( [float](class_float#class-float) time )
Creates and appends an [IntervalTweener](class_intervaltweener#class-intervaltweener). This method can be used to create delays in the tween animation, as an alternative to using the delay in other [Tweener](class_tweener#class-tweener)s, or when there's no animation (in which case the `SceneTreeTween` acts as a timer). `time` is the length of the interval, in seconds.
Example: creating an interval in code execution.
```
# ... some code
yield(create_tween().tween_interval(2), "finished")
# ... more code
```
Example: creating an object that moves back and forth and jumps every few seconds.
```
var tween = create_tween().set_loops()
tween.tween_property($Sprite, "position:x", 200.0, 1).as_relative()
tween.tween_callback(self, "jump")
tween.tween_interval(2)
tween.tween_property($Sprite, "position:x", -200.0, 1).as_relative()
tween.tween_callback(self, "jump")
tween.tween_interval(2)
```
### [MethodTweener](class_methodtweener#class-methodtweener) tween\_method ( [Object](class_object#class-object) object, [String](class_string#class-string) method, [Variant](class_variant#class-variant) from, [Variant](class_variant#class-variant) to, [float](class_float#class-float) duration, [Array](class_array#class-array) binds=[ ] )
Creates and appends a [MethodTweener](class_methodtweener#class-methodtweener). This method is similar to a combination of [tween\_callback](#class-scenetreetween-method-tween-callback) and [tween\_property](#class-scenetreetween-method-tween-property). It calls a method over time with a tweened value provided as an argument. The value is tweened between `from` and `to` over the time specified by `duration`, in seconds. Use `binds` to bind additional arguments for the call. You can use [MethodTweener.set\_ease](class_methodtweener#class-methodtweener-method-set-ease) and [MethodTweener.set\_trans](class_methodtweener#class-methodtweener-method-set-trans) to tweak the easing and transition of the value or [MethodTweener.set\_delay](class_methodtweener#class-methodtweener-method-set-delay) to delay the tweening.
Example: making a 3D object look from one point to another point.
```
var tween = create_tween()
tween.tween_method(self, "look_at", Vector3(-1, 0, -1), Vector3(1, 0, -1), 1, [Vector3.UP]) # The look_at() method takes up vector as second argument.
```
Example: setting a text of a [Label](class_label#class-label), using an intermediate method and after a delay.
```
func _ready():
var tween = create_tween()
tween.tween_method(self, "set_label_text", 0, 10, 1).set_delay(1)
func set_label_text(value: int):
$Label.text = "Counting " + str(value)
```
### [PropertyTweener](class_propertytweener#class-propertytweener) tween\_property ( [Object](class_object#class-object) object, [NodePath](class_nodepath#class-nodepath) property, [Variant](class_variant#class-variant) final\_val, [float](class_float#class-float) duration )
Creates and appends a [PropertyTweener](class_propertytweener#class-propertytweener). This method tweens a `property` of an `object` between an initial value and `final_val` in a span of time equal to `duration`, in seconds. The initial value by default is the property's value at the time the tweening of the [PropertyTweener](class_propertytweener#class-propertytweener) starts. For example:
```
var tween = create_tween()
tween.tween_property($Sprite, "position", Vector2(100, 200), 1)
tween.tween_property($Sprite, "position", Vector2(200, 300), 1)
```
will move the sprite to position (100, 200) and then to (200, 300). If you use [PropertyTweener.from](class_propertytweener#class-propertytweener-method-from) or [PropertyTweener.from\_current](class_propertytweener#class-propertytweener-method-from-current), the starting position will be overwritten by the given value instead. See other methods in [PropertyTweener](class_propertytweener#class-propertytweener) to see how the tweening can be tweaked further.
**Note:** You can find the correct property name by hovering over the property in the Inspector. You can also provide the components of a property directly by using `"property:component"` (eg. `position:x`), where it would only apply to that particular component.
Example: moving object twice from the same position, with different transition types.
```
var tween = create_tween()
tween.tween_property($Sprite, "position", Vector2.RIGHT * 300, 1).as_relative().set_trans(Tween.TRANS_SINE)
tween.tween_property($Sprite, "position", Vector2.RIGHT * 300, 1).as_relative().from_current().set_trans(Tween.TRANS_EXPO)
```
| programming_docs |
godot WorldEnvironment WorldEnvironment
================
**Inherits:** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Default environment properties for the entire scene (post-processing effects, lighting and background settings).
Description
-----------
The `WorldEnvironment` node is used to configure the default [Environment](class_environment#class-environment) for the scene.
The parameters defined in the `WorldEnvironment` can be overridden by an [Environment](class_environment#class-environment) node set on the current [Camera](class_camera#class-camera). Additionally, only one `WorldEnvironment` may be instanced in a given scene at a time.
The `WorldEnvironment` allows the user to specify default lighting parameters (e.g. ambient lighting), various post-processing effects (e.g. SSAO, DOF, Tonemapping), and how to draw the background (e.g. solid color, skybox). Usually, these are added in order to improve the realism/color balance of the scene.
Tutorials
---------
* [Environment and post-processing](https://docs.godotengine.org/en/3.5/tutorials/3d/environment_and_post_processing.html)
* [3D Material Testers Demo](https://godotengine.org/asset-library/asset/123)
* [2D HDR Demo](https://godotengine.org/asset-library/asset/110)
* [Third Person Shooter Demo](https://godotengine.org/asset-library/asset/678)
Properties
----------
| | |
| --- | --- |
| [Environment](class_environment#class-environment) | [environment](#class-worldenvironment-property-environment) |
Property Descriptions
---------------------
### [Environment](class_environment#class-environment) environment
| | |
| --- | --- |
| *Setter* | set\_environment(value) |
| *Getter* | get\_environment() |
The [Environment](class_environment#class-environment) resource used by this `WorldEnvironment`, defining the default properties.
godot PointMesh PointMesh
=========
**Inherits:** [PrimitiveMesh](class_primitivemesh#class-primitivemesh) **<** [Mesh](class_mesh#class-mesh) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Mesh with a single Point primitive.
Description
-----------
The PointMesh is made from a single point. Instead of relying on triangles, points are rendered as a single rectangle on the screen with a constant size. They are intended to be used with Particle systems, but can be used as a cheap way to render constant size billboarded sprites (for example in a point cloud).
PointMeshes, must be used with a material that has a point size. Point size can be accessed in a shader with `POINT_SIZE`, or in a [SpatialMaterial](class_spatialmaterial#class-spatialmaterial) by setting [SpatialMaterial.flags\_use\_point\_size](class_spatialmaterial#class-spatialmaterial-property-flags-use-point-size) and the variable [SpatialMaterial.params\_point\_size](class_spatialmaterial#class-spatialmaterial-property-params-point-size).
When using PointMeshes, properties that normally alter vertices will be ignored, including billboard mode, grow, and cull face.
godot Navigation Navigation
==========
**Inherits:** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Mesh-based navigation and pathfinding node.
Description
-----------
*Deprecated.* `Navigation` node and [get\_simple\_path](#class-navigation-method-get-simple-path) are deprecated and will be removed in a future version. Use [NavigationServer.map\_get\_path](class_navigationserver#class-navigationserver-method-map-get-path) instead.
Provides navigation and pathfinding within a collection of [NavigationMesh](class_navigationmesh#class-navigationmesh)es. By default, these will be automatically collected from child [NavigationMeshInstance](class_navigationmeshinstance#class-navigationmeshinstance) nodes. In addition to basic pathfinding, this class also assists with aligning navigation agents with the meshes they are navigating on.
Tutorials
---------
* [3D Navmesh Demo](https://godotengine.org/asset-library/asset/124)
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [cell\_height](#class-navigation-property-cell-height) | `0.25` |
| [float](class_float#class-float) | [cell\_size](#class-navigation-property-cell-size) | `0.25` |
| [float](class_float#class-float) | [edge\_connection\_margin](#class-navigation-property-edge-connection-margin) | `0.25` |
| [int](class_int#class-int) | [navigation\_layers](#class-navigation-property-navigation-layers) | `1` |
| [Vector3](class_vector3#class-vector3) | [up\_vector](#class-navigation-property-up-vector) | `Vector3( 0, 1, 0 )` |
Methods
-------
| | |
| --- | --- |
| [Vector3](class_vector3#class-vector3) | [get\_closest\_point](#class-navigation-method-get-closest-point) **(** [Vector3](class_vector3#class-vector3) to\_point **)** const |
| [Vector3](class_vector3#class-vector3) | [get\_closest\_point\_normal](#class-navigation-method-get-closest-point-normal) **(** [Vector3](class_vector3#class-vector3) to\_point **)** const |
| [RID](class_rid#class-rid) | [get\_closest\_point\_owner](#class-navigation-method-get-closest-point-owner) **(** [Vector3](class_vector3#class-vector3) to\_point **)** const |
| [Vector3](class_vector3#class-vector3) | [get\_closest\_point\_to\_segment](#class-navigation-method-get-closest-point-to-segment) **(** [Vector3](class_vector3#class-vector3) start, [Vector3](class_vector3#class-vector3) end, [bool](class_bool#class-bool) use\_collision=false **)** const |
| [RID](class_rid#class-rid) | [get\_rid](#class-navigation-method-get-rid) **(** **)** const |
| [PoolVector3Array](class_poolvector3array#class-poolvector3array) | [get\_simple\_path](#class-navigation-method-get-simple-path) **(** [Vector3](class_vector3#class-vector3) start, [Vector3](class_vector3#class-vector3) end, [bool](class_bool#class-bool) optimize=true **)** const |
Signals
-------
### map\_changed ( [RID](class_rid#class-rid) map )
Emitted when a navigation map is updated, when a region moves or is modified.
Property Descriptions
---------------------
### [float](class_float#class-float) cell\_height
| | |
| --- | --- |
| *Default* | `0.25` |
| *Setter* | set\_cell\_height(value) |
| *Getter* | get\_cell\_height() |
The cell height to use for fields.
### [float](class_float#class-float) cell\_size
| | |
| --- | --- |
| *Default* | `0.25` |
| *Setter* | set\_cell\_size(value) |
| *Getter* | get\_cell\_size() |
The XZ plane cell size to use for fields.
### [float](class_float#class-float) edge\_connection\_margin
| | |
| --- | --- |
| *Default* | `0.25` |
| *Setter* | set\_edge\_connection\_margin(value) |
| *Getter* | get\_edge\_connection\_margin() |
This value is used to detect the near edges to connect compatible regions.
### [int](class_int#class-int) navigation\_layers
| | |
| --- | --- |
| *Default* | `1` |
| *Setter* | set\_navigation\_layers(value) |
| *Getter* | get\_navigation\_layers() |
A bitfield determining all navigation map layers the navigation can use on a [get\_simple\_path](#class-navigation-method-get-simple-path) path query.
### [Vector3](class_vector3#class-vector3) up\_vector
| | |
| --- | --- |
| *Default* | `Vector3( 0, 1, 0 )` |
| *Setter* | set\_up\_vector(value) |
| *Getter* | get\_up\_vector() |
Defines which direction is up. By default, this is `(0, 1, 0)`, which is the world's "up" direction.
Method Descriptions
-------------------
### [Vector3](class_vector3#class-vector3) get\_closest\_point ( [Vector3](class_vector3#class-vector3) to\_point ) const
Returns the navigation point closest to the point given. Points are in local coordinate space.
### [Vector3](class_vector3#class-vector3) get\_closest\_point\_normal ( [Vector3](class_vector3#class-vector3) to\_point ) const
Returns the surface normal at the navigation point closest to the point given. Useful for rotating a navigation agent according to the navigation mesh it moves on.
### [RID](class_rid#class-rid) get\_closest\_point\_owner ( [Vector3](class_vector3#class-vector3) to\_point ) const
Returns the owner of the [NavigationMesh](class_navigationmesh#class-navigationmesh) which contains the navigation point closest to the point given. This is usually a [NavigationMeshInstance](class_navigationmeshinstance#class-navigationmeshinstance).
### [Vector3](class_vector3#class-vector3) get\_closest\_point\_to\_segment ( [Vector3](class_vector3#class-vector3) start, [Vector3](class_vector3#class-vector3) end, [bool](class_bool#class-bool) use\_collision=false ) const
Returns the navigation point closest to the given line segment. When enabling `use_collision`, only considers intersection points between segment and navigation meshes. If multiple intersection points are found, the one closest to the segment start point is returned.
### [RID](class_rid#class-rid) get\_rid ( ) const
Returns the [RID](class_rid#class-rid) of the navigation map on the [NavigationServer](class_navigationserver#class-navigationserver).
### [PoolVector3Array](class_poolvector3array#class-poolvector3array) get\_simple\_path ( [Vector3](class_vector3#class-vector3) start, [Vector3](class_vector3#class-vector3) end, [bool](class_bool#class-bool) optimize=true ) const
*Deprecated.* `Navigation` node and [get\_simple\_path](#class-navigation-method-get-simple-path) are deprecated and will be removed in a future version. Use [NavigationServer.map\_get\_path](class_navigationserver#class-navigationserver-method-map-get-path) instead.
Returns the path between two given points. Points are in local coordinate space. If `optimize` is `true` (the default), the agent properties associated with each [NavigationMesh](class_navigationmesh#class-navigationmesh) (radius, height, etc.) are considered in the path calculation, otherwise they are ignored.
godot DirectionalLight DirectionalLight
================
**Inherits:** [Light](class_light#class-light) **<** [VisualInstance](class_visualinstance#class-visualinstance) **<** [CullInstance](class_cullinstance#class-cullinstance) **<** [Spatial](class_spatial#class-spatial) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Directional light from a distance, as from the Sun.
Description
-----------
A directional light is a type of [Light](class_light#class-light) node that models an infinite number of parallel rays covering the entire scene. It is used for lights with strong intensity that are located far away from the scene to model sunlight or moonlight. The worldspace location of the DirectionalLight transform (origin) is ignored. Only the basis is used to determine light direction.
Tutorials
---------
* [3D lights and shadows](https://docs.godotengine.org/en/3.5/tutorials/3d/lights_and_shadows.html)
Properties
----------
| | | |
| --- | --- | --- |
| [float](class_float#class-float) | [directional\_shadow\_bias\_split\_scale](#class-directionallight-property-directional-shadow-bias-split-scale) | `0.25` |
| [bool](class_bool#class-bool) | [directional\_shadow\_blend\_splits](#class-directionallight-property-directional-shadow-blend-splits) | `false` |
| [ShadowDepthRange](#enum-directionallight-shadowdepthrange) | [directional\_shadow\_depth\_range](#class-directionallight-property-directional-shadow-depth-range) | `0` |
| [float](class_float#class-float) | [directional\_shadow\_max\_distance](#class-directionallight-property-directional-shadow-max-distance) | `100.0` |
| [ShadowMode](#enum-directionallight-shadowmode) | [directional\_shadow\_mode](#class-directionallight-property-directional-shadow-mode) | `2` |
| [float](class_float#class-float) | [directional\_shadow\_normal\_bias](#class-directionallight-property-directional-shadow-normal-bias) | `0.8` |
| [float](class_float#class-float) | [directional\_shadow\_split\_1](#class-directionallight-property-directional-shadow-split-1) | `0.1` |
| [float](class_float#class-float) | [directional\_shadow\_split\_2](#class-directionallight-property-directional-shadow-split-2) | `0.2` |
| [float](class_float#class-float) | [directional\_shadow\_split\_3](#class-directionallight-property-directional-shadow-split-3) | `0.5` |
| [float](class_float#class-float) | shadow\_bias | `0.1` (overrides [Light](class_light#class-light-property-shadow-bias)) |
Enumerations
------------
enum **ShadowMode**:
* **SHADOW\_ORTHOGONAL** = **0** --- Renders the entire scene's shadow map from an orthogonal point of view. This is the fastest directional shadow mode. May result in blurrier shadows on close objects.
* **SHADOW\_PARALLEL\_2\_SPLITS** = **1** --- Splits the view frustum in 2 areas, each with its own shadow map. This shadow mode is a compromise between [SHADOW\_ORTHOGONAL](#class-directionallight-constant-shadow-orthogonal) and [SHADOW\_PARALLEL\_4\_SPLITS](#class-directionallight-constant-shadow-parallel-4-splits) in terms of performance.
* **SHADOW\_PARALLEL\_4\_SPLITS** = **2** --- Splits the view frustum in 4 areas, each with its own shadow map. This is the slowest directional shadow mode.
enum **ShadowDepthRange**:
* **SHADOW\_DEPTH\_RANGE\_STABLE** = **0** --- Keeps the shadow stable when the camera moves, at the cost of lower effective shadow resolution.
* **SHADOW\_DEPTH\_RANGE\_OPTIMIZED** = **1** --- Tries to achieve maximum shadow resolution. May result in saw effect on shadow edges. This mode typically works best in games where the camera will often move at high speeds, such as most racing games.
Property Descriptions
---------------------
### [float](class_float#class-float) directional\_shadow\_bias\_split\_scale
| | |
| --- | --- |
| *Default* | `0.25` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
Amount of extra bias for shadow splits that are far away. If self-shadowing occurs only on the splits far away, increasing this value can fix them. This is ignored when [directional\_shadow\_mode](#class-directionallight-property-directional-shadow-mode) is [SHADOW\_ORTHOGONAL](#class-directionallight-constant-shadow-orthogonal).
### [bool](class_bool#class-bool) directional\_shadow\_blend\_splits
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_blend\_splits(value) |
| *Getter* | is\_blend\_splits\_enabled() |
If `true`, shadow detail is sacrificed in exchange for smoother transitions between splits. Enabling shadow blend splitting also has a moderate performance cost. This is ignored when [directional\_shadow\_mode](#class-directionallight-property-directional-shadow-mode) is [SHADOW\_ORTHOGONAL](#class-directionallight-constant-shadow-orthogonal).
### [ShadowDepthRange](#enum-directionallight-shadowdepthrange) directional\_shadow\_depth\_range
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_shadow\_depth\_range(value) |
| *Getter* | get\_shadow\_depth\_range() |
Optimizes shadow rendering for detail versus movement. See [ShadowDepthRange](#enum-directionallight-shadowdepthrange).
### [float](class_float#class-float) directional\_shadow\_max\_distance
| | |
| --- | --- |
| *Default* | `100.0` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
The maximum distance for shadow splits. Increasing this value will make directional shadows visible from further away, at the cost of lower overall shadow detail and performance (since more objects need to be included in the directional shadow rendering).
### [ShadowMode](#enum-directionallight-shadowmode) directional\_shadow\_mode
| | |
| --- | --- |
| *Default* | `2` |
| *Setter* | set\_shadow\_mode(value) |
| *Getter* | get\_shadow\_mode() |
The light's shadow rendering algorithm. See [ShadowMode](#enum-directionallight-shadowmode).
### [float](class_float#class-float) directional\_shadow\_normal\_bias
| | |
| --- | --- |
| *Default* | `0.8` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
Can be used to fix special cases of self shadowing when objects are perpendicular to the light.
### [float](class_float#class-float) directional\_shadow\_split\_1
| | |
| --- | --- |
| *Default* | `0.1` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
The distance from camera to shadow split 1. Relative to [directional\_shadow\_max\_distance](#class-directionallight-property-directional-shadow-max-distance). Only used when [directional\_shadow\_mode](#class-directionallight-property-directional-shadow-mode) is [SHADOW\_PARALLEL\_2\_SPLITS](#class-directionallight-constant-shadow-parallel-2-splits) or [SHADOW\_PARALLEL\_4\_SPLITS](#class-directionallight-constant-shadow-parallel-4-splits).
### [float](class_float#class-float) directional\_shadow\_split\_2
| | |
| --- | --- |
| *Default* | `0.2` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
The distance from shadow split 1 to split 2. Relative to [directional\_shadow\_max\_distance](#class-directionallight-property-directional-shadow-max-distance). Only used when [directional\_shadow\_mode](#class-directionallight-property-directional-shadow-mode) is [SHADOW\_PARALLEL\_2\_SPLITS](#class-directionallight-constant-shadow-parallel-2-splits) or [SHADOW\_PARALLEL\_4\_SPLITS](#class-directionallight-constant-shadow-parallel-4-splits).
### [float](class_float#class-float) directional\_shadow\_split\_3
| | |
| --- | --- |
| *Default* | `0.5` |
| *Setter* | set\_param(value) |
| *Getter* | get\_param() |
The distance from shadow split 2 to split 3. Relative to [directional\_shadow\_max\_distance](#class-directionallight-property-directional-shadow-max-distance). Only used when [directional\_shadow\_mode](#class-directionallight-property-directional-shadow-mode) is [SHADOW\_PARALLEL\_4\_SPLITS](#class-directionallight-constant-shadow-parallel-4-splits).
godot ResourceFormatSaver ResourceFormatSaver
===================
**Inherits:** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Saves a specific resource type to a file.
Description
-----------
The engine can save resources when you do it from the editor, or when you use the [ResourceSaver](class_resourcesaver#class-resourcesaver) singleton. This is accomplished thanks to multiple `ResourceFormatSaver`s, each handling its own format and called automatically by the engine.
By default, Godot saves resources as `.tres` (text-based), `.res` (binary) or another built-in format, but you can choose to create your own format by extending this class. Be sure to respect the documented return types and values. You should give it a global class name with `class_name` for it to be registered. Like built-in ResourceFormatSavers, it will be called automatically when saving resources of its recognized type(s). You may also implement a [ResourceFormatLoader](class_resourceformatloader#class-resourceformatloader).
Methods
-------
| | |
| --- | --- |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_recognized\_extensions](#class-resourceformatsaver-method-get-recognized-extensions) **(** [Resource](class_resource#class-resource) resource **)** virtual |
| [bool](class_bool#class-bool) | [recognize](#class-resourceformatsaver-method-recognize) **(** [Resource](class_resource#class-resource) resource **)** virtual |
| [int](class_int#class-int) | [save](#class-resourceformatsaver-method-save) **(** [String](class_string#class-string) path, [Resource](class_resource#class-resource) resource, [int](class_int#class-int) flags **)** virtual |
Method Descriptions
-------------------
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_recognized\_extensions ( [Resource](class_resource#class-resource) resource ) virtual
Returns the list of extensions available for saving the resource object, provided it is recognized (see [recognize](#class-resourceformatsaver-method-recognize)).
### [bool](class_bool#class-bool) recognize ( [Resource](class_resource#class-resource) resource ) virtual
Returns whether the given resource object can be saved by this saver.
### [int](class_int#class-int) save ( [String](class_string#class-string) path, [Resource](class_resource#class-resource) resource, [int](class_int#class-int) flags ) virtual
Saves the given resource object to a file at the target `path`. `flags` is a bitmask composed with [SaverFlags](class_resourcesaver#enum-resourcesaver-saverflags) constants.
Returns [@GlobalScope.OK](class_%40globalscope#class-globalscope-constant-ok) on success, or an [Error](class_%40globalscope#enum-globalscope-error) constant in case of failure.
| programming_docs |
godot LineEdit LineEdit
========
**Inherits:** [Control](class_control#class-control) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Control that provides single-line string editing.
Description
-----------
LineEdit provides a single-line string editor, used for text fields.
It features many built-in shortcuts which will always be available (`Ctrl` here maps to `Command` on macOS):
* Ctrl + C: Copy
* Ctrl + X: Cut
* Ctrl + V or Ctrl + Y: Paste/"yank"
* Ctrl + Z: Undo
* Ctrl + Shift + Z: Redo
* Ctrl + U: Delete text from the cursor position to the beginning of the line
* Ctrl + K: Delete text from the cursor position to the end of the line
* Ctrl + A: Select all text
* Up/Down arrow: Move the cursor to the beginning/end of the line
On macOS, some extra keyboard shortcuts are available:
* Ctrl + F: Like the right arrow key, move the cursor one character right
* Ctrl + B: Like the left arrow key, move the cursor one character left
* Ctrl + P: Like the up arrow key, move the cursor to the previous line
* Ctrl + N: Like the down arrow key, move the cursor to the next line
* Ctrl + D: Like the Delete key, delete the character on the right side of cursor
* Ctrl + H: Like the Backspace key, delete the character on the left side of the cursor
* Command + Left arrow: Like the Home key, move the cursor to the beginning of the line
* Command + Right arrow: Like the End key, move the cursor to the end of the line
Properties
----------
| | | |
| --- | --- | --- |
| [Align](#enum-lineedit-align) | [align](#class-lineedit-property-align) | `0` |
| [bool](class_bool#class-bool) | [caret\_blink](#class-lineedit-property-caret-blink) | `false` |
| [float](class_float#class-float) | [caret\_blink\_speed](#class-lineedit-property-caret-blink-speed) | `0.65` |
| [int](class_int#class-int) | [caret\_position](#class-lineedit-property-caret-position) | `0` |
| [bool](class_bool#class-bool) | [clear\_button\_enabled](#class-lineedit-property-clear-button-enabled) | `false` |
| [bool](class_bool#class-bool) | [context\_menu\_enabled](#class-lineedit-property-context-menu-enabled) | `true` |
| [bool](class_bool#class-bool) | [deselect\_on\_focus\_loss\_enabled](#class-lineedit-property-deselect-on-focus-loss-enabled) | `true` |
| [bool](class_bool#class-bool) | [editable](#class-lineedit-property-editable) | `true` |
| [bool](class_bool#class-bool) | [expand\_to\_text\_length](#class-lineedit-property-expand-to-text-length) | `false` |
| [FocusMode](class_control#enum-control-focusmode) | focus\_mode | `2` (overrides [Control](class_control#class-control-property-focus-mode)) |
| [int](class_int#class-int) | [max\_length](#class-lineedit-property-max-length) | `0` |
| [bool](class_bool#class-bool) | [middle\_mouse\_paste\_enabled](#class-lineedit-property-middle-mouse-paste-enabled) | `true` |
| [CursorShape](class_control#enum-control-cursorshape) | mouse\_default\_cursor\_shape | `1` (overrides [Control](class_control#class-control-property-mouse-default-cursor-shape)) |
| [float](class_float#class-float) | [placeholder\_alpha](#class-lineedit-property-placeholder-alpha) | `0.6` |
| [String](class_string#class-string) | [placeholder\_text](#class-lineedit-property-placeholder-text) | `""` |
| [Texture](class_texture#class-texture) | [right\_icon](#class-lineedit-property-right-icon) | |
| [bool](class_bool#class-bool) | [secret](#class-lineedit-property-secret) | `false` |
| [String](class_string#class-string) | [secret\_character](#class-lineedit-property-secret-character) | `"*"` |
| [bool](class_bool#class-bool) | [selecting\_enabled](#class-lineedit-property-selecting-enabled) | `true` |
| [bool](class_bool#class-bool) | [shortcut\_keys\_enabled](#class-lineedit-property-shortcut-keys-enabled) | `true` |
| [String](class_string#class-string) | [text](#class-lineedit-property-text) | `""` |
| [bool](class_bool#class-bool) | [virtual\_keyboard\_enabled](#class-lineedit-property-virtual-keyboard-enabled) | `true` |
Methods
-------
| | |
| --- | --- |
| void | [append\_at\_cursor](#class-lineedit-method-append-at-cursor) **(** [String](class_string#class-string) text **)** |
| void | [clear](#class-lineedit-method-clear) **(** **)** |
| void | [delete\_char\_at\_cursor](#class-lineedit-method-delete-char-at-cursor) **(** **)** |
| void | [delete\_text](#class-lineedit-method-delete-text) **(** [int](class_int#class-int) from\_column, [int](class_int#class-int) to\_column **)** |
| void | [deselect](#class-lineedit-method-deselect) **(** **)** |
| [PopupMenu](class_popupmenu#class-popupmenu) | [get\_menu](#class-lineedit-method-get-menu) **(** **)** const |
| [int](class_int#class-int) | [get\_scroll\_offset](#class-lineedit-method-get-scroll-offset) **(** **)** const |
| [int](class_int#class-int) | [get\_selection\_from\_column](#class-lineedit-method-get-selection-from-column) **(** **)** const |
| [int](class_int#class-int) | [get\_selection\_to\_column](#class-lineedit-method-get-selection-to-column) **(** **)** const |
| [bool](class_bool#class-bool) | [has\_selection](#class-lineedit-method-has-selection) **(** **)** const |
| void | [menu\_option](#class-lineedit-method-menu-option) **(** [int](class_int#class-int) option **)** |
| void | [select](#class-lineedit-method-select) **(** [int](class_int#class-int) from=0, [int](class_int#class-int) to=-1 **)** |
| void | [select\_all](#class-lineedit-method-select-all) **(** **)** |
Theme Properties
----------------
| | | |
| --- | --- | --- |
| [Color](class_color#class-color) | [clear\_button\_color](#class-lineedit-theme-color-clear-button-color) | `Color( 0.88, 0.88, 0.88, 1 )` |
| [Color](class_color#class-color) | [clear\_button\_color\_pressed](#class-lineedit-theme-color-clear-button-color-pressed) | `Color( 1, 1, 1, 1 )` |
| [Color](class_color#class-color) | [cursor\_color](#class-lineedit-theme-color-cursor-color) | `Color( 0.94, 0.94, 0.94, 1 )` |
| [Color](class_color#class-color) | [font\_color](#class-lineedit-theme-color-font-color) | `Color( 0.88, 0.88, 0.88, 1 )` |
| [Color](class_color#class-color) | [font\_color\_selected](#class-lineedit-theme-color-font-color-selected) | `Color( 0, 0, 0, 1 )` |
| [Color](class_color#class-color) | [font\_color\_uneditable](#class-lineedit-theme-color-font-color-uneditable) | `Color( 0.88, 0.88, 0.88, 0.5 )` |
| [Color](class_color#class-color) | [selection\_color](#class-lineedit-theme-color-selection-color) | `Color( 0.49, 0.49, 0.49, 1 )` |
| [int](class_int#class-int) | [minimum\_spaces](#class-lineedit-theme-constant-minimum-spaces) | `12` |
| [Font](class_font#class-font) | [font](#class-lineedit-theme-font-font) | |
| [Texture](class_texture#class-texture) | [clear](#class-lineedit-theme-icon-clear) | |
| [StyleBox](class_stylebox#class-stylebox) | [focus](#class-lineedit-theme-style-focus) | |
| [StyleBox](class_stylebox#class-stylebox) | [normal](#class-lineedit-theme-style-normal) | |
| [StyleBox](class_stylebox#class-stylebox) | [read\_only](#class-lineedit-theme-style-read-only) | |
Signals
-------
### text\_change\_rejected ( [String](class_string#class-string) rejected\_substring )
Emitted when appending text that overflows the [max\_length](#class-lineedit-property-max-length). The appended text is truncated to fit [max\_length](#class-lineedit-property-max-length), and the part that couldn't fit is passed as the `rejected_substring` argument.
### text\_changed ( [String](class_string#class-string) new\_text )
Emitted when the text changes.
### text\_entered ( [String](class_string#class-string) new\_text )
Emitted when the user presses [@GlobalScope.KEY\_ENTER](class_%40globalscope#class-globalscope-constant-key-enter) on the `LineEdit`.
Enumerations
------------
enum **Align**:
* **ALIGN\_LEFT** = **0** --- Aligns the text on the left-hand side of the `LineEdit`.
* **ALIGN\_CENTER** = **1** --- Centers the text in the middle of the `LineEdit`.
* **ALIGN\_RIGHT** = **2** --- Aligns the text on the right-hand side of the `LineEdit`.
* **ALIGN\_FILL** = **3** --- Stretches whitespaces to fit the `LineEdit`'s width.
enum **MenuItems**:
* **MENU\_CUT** = **0** --- Cuts (copies and clears) the selected text.
* **MENU\_COPY** = **1** --- Copies the selected text.
* **MENU\_PASTE** = **2** --- Pastes the clipboard text over the selected text (or at the cursor's position).
Non-printable escape characters are automatically stripped from the OS clipboard via [String.strip\_escapes](class_string#class-string-method-strip-escapes).
* **MENU\_CLEAR** = **3** --- Erases the whole `LineEdit` text.
* **MENU\_SELECT\_ALL** = **4** --- Selects the whole `LineEdit` text.
* **MENU\_UNDO** = **5** --- Undoes the previous action.
* **MENU\_REDO** = **6** --- Reverse the last undo action.
* **MENU\_MAX** = **7** --- Represents the size of the [MenuItems](#enum-lineedit-menuitems) enum.
Property Descriptions
---------------------
### [Align](#enum-lineedit-align) align
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_align(value) |
| *Getter* | get\_align() |
Text alignment as defined in the [Align](#enum-lineedit-align) enum.
### [bool](class_bool#class-bool) caret\_blink
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | cursor\_set\_blink\_enabled(value) |
| *Getter* | cursor\_get\_blink\_enabled() |
If `true`, the caret (visual cursor) blinks.
### [float](class_float#class-float) caret\_blink\_speed
| | |
| --- | --- |
| *Default* | `0.65` |
| *Setter* | cursor\_set\_blink\_speed(value) |
| *Getter* | cursor\_get\_blink\_speed() |
Duration (in seconds) of a caret's blinking cycle.
### [int](class_int#class-int) caret\_position
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_cursor\_position(value) |
| *Getter* | get\_cursor\_position() |
The cursor's position inside the `LineEdit`. When set, the text may scroll to accommodate it.
### [bool](class_bool#class-bool) clear\_button\_enabled
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_clear\_button\_enabled(value) |
| *Getter* | is\_clear\_button\_enabled() |
If `true`, the `LineEdit` will show a clear button if `text` is not empty, which can be used to clear the text quickly.
### [bool](class_bool#class-bool) context\_menu\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_context\_menu\_enabled(value) |
| *Getter* | is\_context\_menu\_enabled() |
If `true`, the context menu will appear when right-clicked.
### [bool](class_bool#class-bool) deselect\_on\_focus\_loss\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_deselect\_on\_focus\_loss\_enabled(value) |
| *Getter* | is\_deselect\_on\_focus\_loss\_enabled() |
If `true`, the selected text will be deselected when focus is lost.
### [bool](class_bool#class-bool) editable
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_editable(value) |
| *Getter* | is\_editable() |
If `false`, existing text cannot be modified and new text cannot be added.
### [bool](class_bool#class-bool) expand\_to\_text\_length
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_expand\_to\_text\_length(value) |
| *Getter* | get\_expand\_to\_text\_length() |
If `true`, the `LineEdit` width will increase to stay longer than the [text](#class-lineedit-property-text). It will **not** compress if the [text](#class-lineedit-property-text) is shortened.
### [int](class_int#class-int) max\_length
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_max\_length(value) |
| *Getter* | get\_max\_length() |
Maximum amount of characters that can be entered inside the `LineEdit`. If `0`, there is no limit.
When a limit is defined, characters that would exceed [max\_length](#class-lineedit-property-max-length) are truncated. This happens both for existing [text](#class-lineedit-property-text) contents when setting the max length, or for new text inserted in the `LineEdit`, including pasting. If any input text is truncated, the [text\_change\_rejected](#class-lineedit-signal-text-change-rejected) signal is emitted with the truncated substring as parameter.
**Example:**
```
text = "Hello world"
max_length = 5
# `text` becomes "Hello".
max_length = 10
text += " goodbye"
# `text` becomes "Hello good".
# `text_change_rejected` is emitted with "bye" as parameter.
```
### [bool](class_bool#class-bool) middle\_mouse\_paste\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_middle\_mouse\_paste\_enabled(value) |
| *Getter* | is\_middle\_mouse\_paste\_enabled() |
If `false`, using middle mouse button to paste clipboard will be disabled.
**Note:** This method is only implemented on Linux.
### [float](class_float#class-float) placeholder\_alpha
| | |
| --- | --- |
| *Default* | `0.6` |
| *Setter* | set\_placeholder\_alpha(value) |
| *Getter* | get\_placeholder\_alpha() |
Opacity of the [placeholder\_text](#class-lineedit-property-placeholder-text). From `0` to `1`.
### [String](class_string#class-string) placeholder\_text
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_placeholder(value) |
| *Getter* | get\_placeholder() |
Text shown when the `LineEdit` is empty. It is **not** the `LineEdit`'s default value (see [text](#class-lineedit-property-text)).
### [Texture](class_texture#class-texture) right\_icon
| | |
| --- | --- |
| *Setter* | set\_right\_icon(value) |
| *Getter* | get\_right\_icon() |
Sets the icon that will appear in the right end of the `LineEdit` if there's no [text](#class-lineedit-property-text), or always, if [clear\_button\_enabled](#class-lineedit-property-clear-button-enabled) is set to `false`.
### [bool](class_bool#class-bool) secret
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_secret(value) |
| *Getter* | is\_secret() |
If `true`, every character is replaced with the secret character (see [secret\_character](#class-lineedit-property-secret-character)).
### [String](class_string#class-string) secret\_character
| | |
| --- | --- |
| *Default* | `"*"` |
| *Setter* | set\_secret\_character(value) |
| *Getter* | get\_secret\_character() |
The character to use to mask secret input (defaults to "\*"). Only a single character can be used as the secret character.
### [bool](class_bool#class-bool) selecting\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_selecting\_enabled(value) |
| *Getter* | is\_selecting\_enabled() |
If `false`, it's impossible to select the text using mouse nor keyboard.
### [bool](class_bool#class-bool) shortcut\_keys\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_shortcut\_keys\_enabled(value) |
| *Getter* | is\_shortcut\_keys\_enabled() |
If `false`, using shortcuts will be disabled.
### [String](class_string#class-string) text
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_text(value) |
| *Getter* | get\_text() |
String value of the `LineEdit`.
**Note:** Changing text using this property won't emit the [text\_changed](#class-lineedit-signal-text-changed) signal.
### [bool](class_bool#class-bool) virtual\_keyboard\_enabled
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_virtual\_keyboard\_enabled(value) |
| *Getter* | is\_virtual\_keyboard\_enabled() |
If `true`, the native virtual keyboard is shown when focused on platforms that support it.
Method Descriptions
-------------------
### void append\_at\_cursor ( [String](class_string#class-string) text )
Adds `text` after the cursor. If the resulting value is longer than [max\_length](#class-lineedit-property-max-length), nothing happens.
### void clear ( )
Erases the `LineEdit`'s [text](#class-lineedit-property-text).
### void delete\_char\_at\_cursor ( )
Deletes one character at the cursor's current position (equivalent to pressing the `Delete` key).
### void delete\_text ( [int](class_int#class-int) from\_column, [int](class_int#class-int) to\_column )
Deletes a section of the [text](#class-lineedit-property-text) going from position `from_column` to `to_column`. Both parameters should be within the text's length.
### void deselect ( )
Clears the current selection.
### [PopupMenu](class_popupmenu#class-popupmenu) get\_menu ( ) const
Returns the [PopupMenu](class_popupmenu#class-popupmenu) of this `LineEdit`. By default, this menu is displayed when right-clicking on the `LineEdit`.
**Warning:** This is a required internal node, removing and freeing it may cause a crash. If you wish to hide it or any of its children, use their [CanvasItem.visible](class_canvasitem#class-canvasitem-property-visible) property.
### [int](class_int#class-int) get\_scroll\_offset ( ) const
Returns the scroll offset due to [caret\_position](#class-lineedit-property-caret-position), as a number of characters.
### [int](class_int#class-int) get\_selection\_from\_column ( ) const
Returns the selection begin column.
### [int](class_int#class-int) get\_selection\_to\_column ( ) const
Returns the selection end column.
### [bool](class_bool#class-bool) has\_selection ( ) const
Returns `true` if the user has selected text.
### void menu\_option ( [int](class_int#class-int) option )
Executes a given action as defined in the [MenuItems](#enum-lineedit-menuitems) enum.
### void select ( [int](class_int#class-int) from=0, [int](class_int#class-int) to=-1 )
Selects characters inside `LineEdit` between `from` and `to`. By default, `from` is at the beginning and `to` at the end.
```
text = "Welcome"
select() # Will select "Welcome".
select(4) # Will select "ome".
select(2, 5) # Will select "lco".
```
### void select\_all ( )
Selects the whole [String](class_string#class-string).
Theme Property Descriptions
---------------------------
### [Color](class_color#class-color) clear\_button\_color
| | |
| --- | --- |
| *Default* | `Color( 0.88, 0.88, 0.88, 1 )` |
Color used as default tint for the clear button.
### [Color](class_color#class-color) clear\_button\_color\_pressed
| | |
| --- | --- |
| *Default* | `Color( 1, 1, 1, 1 )` |
Color used for the clear button when it's pressed.
### [Color](class_color#class-color) cursor\_color
| | |
| --- | --- |
| *Default* | `Color( 0.94, 0.94, 0.94, 1 )` |
Color of the `LineEdit`'s visual cursor (caret).
### [Color](class_color#class-color) font\_color
| | |
| --- | --- |
| *Default* | `Color( 0.88, 0.88, 0.88, 1 )` |
Default font color.
### [Color](class_color#class-color) font\_color\_selected
| | |
| --- | --- |
| *Default* | `Color( 0, 0, 0, 1 )` |
Font color for selected text (inside the selection rectangle).
### [Color](class_color#class-color) font\_color\_uneditable
| | |
| --- | --- |
| *Default* | `Color( 0.88, 0.88, 0.88, 0.5 )` |
Font color when editing is disabled.
### [Color](class_color#class-color) selection\_color
| | |
| --- | --- |
| *Default* | `Color( 0.49, 0.49, 0.49, 1 )` |
Color of the selection rectangle.
### [int](class_int#class-int) minimum\_spaces
| | |
| --- | --- |
| *Default* | `12` |
Minimum horizontal space for the text (not counting the clear button and content margins). This value is measured in count of space characters (i.e. this amount of space characters can be displayed without scrolling).
### [Font](class_font#class-font) font
Font used for the text.
### [Texture](class_texture#class-texture) clear
Texture for the clear button. See [clear\_button\_enabled](#class-lineedit-property-clear-button-enabled).
### [StyleBox](class_stylebox#class-stylebox) focus
Background used when `LineEdit` has GUI focus.
### [StyleBox](class_stylebox#class-stylebox) normal
Default background for the `LineEdit`.
### [StyleBox](class_stylebox#class-stylebox) read\_only
Background used when `LineEdit` is in read-only mode ([editable](#class-lineedit-property-editable) is set to `false`).
| programming_docs |
godot Texture Texture
=======
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [AnimatedTexture](class_animatedtexture#class-animatedtexture), [AtlasTexture](class_atlastexture#class-atlastexture), [CameraTexture](class_cameratexture#class-cameratexture), [CurveTexture](class_curvetexture#class-curvetexture), [ExternalTexture](class_externaltexture#class-externaltexture), [GradientTexture](class_gradienttexture#class-gradienttexture), [GradientTexture2D](class_gradienttexture2d#class-gradienttexture2d), [ImageTexture](class_imagetexture#class-imagetexture), [LargeTexture](class_largetexture#class-largetexture), [MeshTexture](class_meshtexture#class-meshtexture), [NoiseTexture](class_noisetexture#class-noisetexture), [ProxyTexture](class_proxytexture#class-proxytexture), [StreamTexture](class_streamtexture#class-streamtexture), [ViewportTexture](class_viewporttexture#class-viewporttexture)
Texture for 2D and 3D.
Description
-----------
A texture works by registering an image in the video hardware, which then can be used in 3D models or 2D [Sprite](class_sprite#class-sprite) or GUI [Control](class_control#class-control).
Textures are often created by loading them from a file. See [@GDScript.load](class_%40gdscript#class-gdscript-method-load).
`Texture` is a base for other resources. It cannot be used directly.
**Note:** The maximum texture size is 16384×16384 pixels due to graphics hardware limitations. Larger textures may fail to import.
Properties
----------
| | | |
| --- | --- | --- |
| [int](class_int#class-int) | [flags](#class-texture-property-flags) | `4` |
Methods
-------
| | |
| --- | --- |
| void | [draw](#class-texture-method-draw) **(** [RID](class_rid#class-rid) canvas\_item, [Vector2](class_vector2#class-vector2) position, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [Texture](#class-texture) normal\_map=null **)** const |
| void | [draw\_rect](#class-texture-method-draw-rect) **(** [RID](class_rid#class-rid) canvas\_item, [Rect2](class_rect2#class-rect2) rect, [bool](class_bool#class-bool) tile, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [Texture](#class-texture) normal\_map=null **)** const |
| void | [draw\_rect\_region](#class-texture-method-draw-rect-region) **(** [RID](class_rid#class-rid) canvas\_item, [Rect2](class_rect2#class-rect2) rect, [Rect2](class_rect2#class-rect2) src\_rect, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [Texture](#class-texture) normal\_map=null, [bool](class_bool#class-bool) clip\_uv=true **)** const |
| [Image](class_image#class-image) | [get\_data](#class-texture-method-get-data) **(** **)** const |
| [int](class_int#class-int) | [get\_height](#class-texture-method-get-height) **(** **)** const |
| [Vector2](class_vector2#class-vector2) | [get\_size](#class-texture-method-get-size) **(** **)** const |
| [int](class_int#class-int) | [get\_width](#class-texture-method-get-width) **(** **)** const |
| [bool](class_bool#class-bool) | [has\_alpha](#class-texture-method-has-alpha) **(** **)** const |
Enumerations
------------
enum **Flags**:
* **FLAGS\_DEFAULT** = **7** --- Default flags. [FLAG\_MIPMAPS](#class-texture-constant-flag-mipmaps), [FLAG\_REPEAT](#class-texture-constant-flag-repeat) and [FLAG\_FILTER](#class-texture-constant-flag-filter) are enabled.
* **FLAG\_MIPMAPS** = **1** --- Generates mipmaps, which are smaller versions of the same texture to use when zoomed out, keeping the aspect ratio.
* **FLAG\_REPEAT** = **2** --- Repeats the texture (instead of clamp to edge).
**Note:** Ignored when using an [AtlasTexture](class_atlastexture#class-atlastexture) as these don't support repetition.
* **FLAG\_FILTER** = **4** --- Uses a magnifying filter, to enable smooth zooming in of the texture.
* **FLAG\_ANISOTROPIC\_FILTER** = **8** --- Uses anisotropic mipmap filtering. Generates smaller versions of the same texture with different aspect ratios.
This results in better-looking textures when viewed from oblique angles.
* **FLAG\_CONVERT\_TO\_LINEAR** = **16** --- Converts the texture to the sRGB color space.
* **FLAG\_MIRRORED\_REPEAT** = **32** --- Repeats the texture with alternate sections mirrored.
**Note:** Ignored when using an [AtlasTexture](class_atlastexture#class-atlastexture) as these don't support repetition.
* **FLAG\_VIDEO\_SURFACE** = **2048** --- Texture is a video surface.
Property Descriptions
---------------------
### [int](class_int#class-int) flags
| | |
| --- | --- |
| *Default* | `4` |
| *Setter* | set\_flags(value) |
| *Getter* | get\_flags() |
The texture's [Flags](#enum-texture-flags). [Flags](#enum-texture-flags) are used to set various properties of the `Texture`.
Method Descriptions
-------------------
### void draw ( [RID](class_rid#class-rid) canvas\_item, [Vector2](class_vector2#class-vector2) position, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [Texture](#class-texture) normal\_map=null ) const
Draws the texture using a [CanvasItem](class_canvasitem#class-canvasitem) with the [VisualServer](class_visualserver#class-visualserver) API at the specified `position`. Equivalent to [VisualServer.canvas\_item\_add\_texture\_rect](class_visualserver#class-visualserver-method-canvas-item-add-texture-rect) with a rect at `position` and the size of this `Texture`.
### void draw\_rect ( [RID](class_rid#class-rid) canvas\_item, [Rect2](class_rect2#class-rect2) rect, [bool](class_bool#class-bool) tile, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [Texture](#class-texture) normal\_map=null ) const
Draws the texture using a [CanvasItem](class_canvasitem#class-canvasitem) with the [VisualServer](class_visualserver#class-visualserver) API. Equivalent to [VisualServer.canvas\_item\_add\_texture\_rect](class_visualserver#class-visualserver-method-canvas-item-add-texture-rect).
### void draw\_rect\_region ( [RID](class_rid#class-rid) canvas\_item, [Rect2](class_rect2#class-rect2) rect, [Rect2](class_rect2#class-rect2) src\_rect, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [Texture](#class-texture) normal\_map=null, [bool](class_bool#class-bool) clip\_uv=true ) const
Draws a part of the texture using a [CanvasItem](class_canvasitem#class-canvasitem) with the [VisualServer](class_visualserver#class-visualserver) API. Equivalent to [VisualServer.canvas\_item\_add\_texture\_rect\_region](class_visualserver#class-visualserver-method-canvas-item-add-texture-rect-region).
### [Image](class_image#class-image) get\_data ( ) const
Returns an [Image](class_image#class-image) that is a copy of data from this `Texture`. [Image](class_image#class-image)s can be accessed and manipulated directly.
### [int](class_int#class-int) get\_height ( ) const
Returns the texture height.
### [Vector2](class_vector2#class-vector2) get\_size ( ) const
Returns the texture size.
### [int](class_int#class-int) get\_width ( ) const
Returns the texture width.
### [bool](class_bool#class-bool) has\_alpha ( ) const
Returns `true` if this `Texture` has an alpha channel.
godot RemoteTransform2D RemoteTransform2D
=================
**Inherits:** [Node2D](class_node2d#class-node2d) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
RemoteTransform2D pushes its own [Transform2D](class_transform2d#class-transform2d) to another [CanvasItem](class_canvasitem#class-canvasitem) derived Node in the scene.
Description
-----------
RemoteTransform2D pushes its own [Transform2D](class_transform2d#class-transform2d) to another [CanvasItem](class_canvasitem#class-canvasitem) derived Node (called the remote node) in the scene.
It can be set to update another Node's position, rotation and/or scale. It can use either global or local coordinates.
Properties
----------
| | | |
| --- | --- | --- |
| [NodePath](class_nodepath#class-nodepath) | [remote\_path](#class-remotetransform2d-property-remote-path) | `NodePath("")` |
| [bool](class_bool#class-bool) | [update\_position](#class-remotetransform2d-property-update-position) | `true` |
| [bool](class_bool#class-bool) | [update\_rotation](#class-remotetransform2d-property-update-rotation) | `true` |
| [bool](class_bool#class-bool) | [update\_scale](#class-remotetransform2d-property-update-scale) | `true` |
| [bool](class_bool#class-bool) | [use\_global\_coordinates](#class-remotetransform2d-property-use-global-coordinates) | `true` |
Methods
-------
| | |
| --- | --- |
| void | [force\_update\_cache](#class-remotetransform2d-method-force-update-cache) **(** **)** |
Property Descriptions
---------------------
### [NodePath](class_nodepath#class-nodepath) remote\_path
| | |
| --- | --- |
| *Default* | `NodePath("")` |
| *Setter* | set\_remote\_node(value) |
| *Getter* | get\_remote\_node() |
The [NodePath](class_nodepath#class-nodepath) to the remote node, relative to the RemoteTransform2D's position in the scene.
### [bool](class_bool#class-bool) update\_position
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_update\_position(value) |
| *Getter* | get\_update\_position() |
If `true`, the remote node's position is updated.
### [bool](class_bool#class-bool) update\_rotation
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_update\_rotation(value) |
| *Getter* | get\_update\_rotation() |
If `true`, the remote node's rotation is updated.
### [bool](class_bool#class-bool) update\_scale
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_update\_scale(value) |
| *Getter* | get\_update\_scale() |
If `true`, the remote node's scale is updated.
### [bool](class_bool#class-bool) use\_global\_coordinates
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_use\_global\_coordinates(value) |
| *Getter* | get\_use\_global\_coordinates() |
If `true`, global coordinates are used. If `false`, local coordinates are used.
Method Descriptions
-------------------
### void force\_update\_cache ( )
`RemoteTransform2D` caches the remote node. It may not notice if the remote node disappears; [force\_update\_cache](#class-remotetransform2d-method-force-update-cache) forces it to update the cache again.
godot CameraServer CameraServer
============
**Inherits:** [Object](class_object#class-object)
Server keeping track of different cameras accessible in Godot.
Description
-----------
The `CameraServer` keeps track of different cameras accessible in Godot. These are external cameras such as webcams or the cameras on your phone.
It is notably used to provide AR modules with a video feed from the camera.
**Note:** This class is currently only implemented on macOS and iOS. On other platforms, no [CameraFeed](class_camerafeed#class-camerafeed)s will be available.
Methods
-------
| | |
| --- | --- |
| void | [add\_feed](#class-cameraserver-method-add-feed) **(** [CameraFeed](class_camerafeed#class-camerafeed) feed **)** |
| [Array](class_array#class-array) | [feeds](#class-cameraserver-method-feeds) **(** **)** |
| [CameraFeed](class_camerafeed#class-camerafeed) | [get\_feed](#class-cameraserver-method-get-feed) **(** [int](class_int#class-int) index **)** |
| [int](class_int#class-int) | [get\_feed\_count](#class-cameraserver-method-get-feed-count) **(** **)** |
| void | [remove\_feed](#class-cameraserver-method-remove-feed) **(** [CameraFeed](class_camerafeed#class-camerafeed) feed **)** |
Signals
-------
### camera\_feed\_added ( [int](class_int#class-int) id )
Emitted when a [CameraFeed](class_camerafeed#class-camerafeed) is added (e.g. a webcam is plugged in).
### camera\_feed\_removed ( [int](class_int#class-int) id )
Emitted when a [CameraFeed](class_camerafeed#class-camerafeed) is removed (e.g. a webcam is unplugged).
Enumerations
------------
enum **FeedImage**:
* **FEED\_RGBA\_IMAGE** = **0** --- The RGBA camera image.
* **FEED\_YCBCR\_IMAGE** = **0** --- The [YCbCr](https://en.wikipedia.org/wiki/YCbCr) camera image.
* **FEED\_Y\_IMAGE** = **0** --- The Y component camera image.
* **FEED\_CBCR\_IMAGE** = **1** --- The CbCr component camera image.
Method Descriptions
-------------------
### void add\_feed ( [CameraFeed](class_camerafeed#class-camerafeed) feed )
Adds the camera `feed` to the camera server.
### [Array](class_array#class-array) feeds ( )
Returns an array of [CameraFeed](class_camerafeed#class-camerafeed)s.
### [CameraFeed](class_camerafeed#class-camerafeed) get\_feed ( [int](class_int#class-int) index )
Returns the [CameraFeed](class_camerafeed#class-camerafeed) corresponding to the camera with the given `index`.
### [int](class_int#class-int) get\_feed\_count ( )
Returns the number of [CameraFeed](class_camerafeed#class-camerafeed)s registered.
### void remove\_feed ( [CameraFeed](class_camerafeed#class-camerafeed) feed )
Removes the specified camera `feed`.
godot AnimationNodeBlendSpace2D AnimationNodeBlendSpace2D
=========================
**Inherits:** [AnimationRootNode](class_animationrootnode#class-animationrootnode) **<** [AnimationNode](class_animationnode#class-animationnode) **<** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Blends linearly between three [AnimationNode](class_animationnode#class-animationnode) of any type placed in a 2D space.
Description
-----------
A resource to add to an [AnimationNodeBlendTree](class_animationnodeblendtree#class-animationnodeblendtree).
This node allows you to blend linearly between three animations using a [Vector2](class_vector2#class-vector2) weight.
You can add vertices to the blend space with [add\_blend\_point](#class-animationnodeblendspace2d-method-add-blend-point) and automatically triangulate it by setting [auto\_triangles](#class-animationnodeblendspace2d-property-auto-triangles) to `true`. Otherwise, use [add\_triangle](#class-animationnodeblendspace2d-method-add-triangle) and [remove\_triangle](#class-animationnodeblendspace2d-method-remove-triangle) to create up the blend space by hand.
Tutorials
---------
* [AnimationTree](https://docs.godotengine.org/en/3.5/tutorials/animation/animation_tree.html)
* [Third Person Shooter Demo](https://godotengine.org/asset-library/asset/678)
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | [auto\_triangles](#class-animationnodeblendspace2d-property-auto-triangles) | `true` |
| [BlendMode](#enum-animationnodeblendspace2d-blendmode) | [blend\_mode](#class-animationnodeblendspace2d-property-blend-mode) | `0` |
| [Vector2](class_vector2#class-vector2) | [max\_space](#class-animationnodeblendspace2d-property-max-space) | `Vector2( 1, 1 )` |
| [Vector2](class_vector2#class-vector2) | [min\_space](#class-animationnodeblendspace2d-property-min-space) | `Vector2( -1, -1 )` |
| [Vector2](class_vector2#class-vector2) | [snap](#class-animationnodeblendspace2d-property-snap) | `Vector2( 0.1, 0.1 )` |
| [String](class_string#class-string) | [x\_label](#class-animationnodeblendspace2d-property-x-label) | `"x"` |
| [String](class_string#class-string) | [y\_label](#class-animationnodeblendspace2d-property-y-label) | `"y"` |
Methods
-------
| | |
| --- | --- |
| void | [add\_blend\_point](#class-animationnodeblendspace2d-method-add-blend-point) **(** [AnimationRootNode](class_animationrootnode#class-animationrootnode) node, [Vector2](class_vector2#class-vector2) pos, [int](class_int#class-int) at\_index=-1 **)** |
| void | [add\_triangle](#class-animationnodeblendspace2d-method-add-triangle) **(** [int](class_int#class-int) x, [int](class_int#class-int) y, [int](class_int#class-int) z, [int](class_int#class-int) at\_index=-1 **)** |
| [int](class_int#class-int) | [get\_blend\_point\_count](#class-animationnodeblendspace2d-method-get-blend-point-count) **(** **)** const |
| [AnimationRootNode](class_animationrootnode#class-animationrootnode) | [get\_blend\_point\_node](#class-animationnodeblendspace2d-method-get-blend-point-node) **(** [int](class_int#class-int) point **)** const |
| [Vector2](class_vector2#class-vector2) | [get\_blend\_point\_position](#class-animationnodeblendspace2d-method-get-blend-point-position) **(** [int](class_int#class-int) point **)** const |
| [int](class_int#class-int) | [get\_triangle\_count](#class-animationnodeblendspace2d-method-get-triangle-count) **(** **)** const |
| [int](class_int#class-int) | [get\_triangle\_point](#class-animationnodeblendspace2d-method-get-triangle-point) **(** [int](class_int#class-int) triangle, [int](class_int#class-int) point **)** |
| void | [remove\_blend\_point](#class-animationnodeblendspace2d-method-remove-blend-point) **(** [int](class_int#class-int) point **)** |
| void | [remove\_triangle](#class-animationnodeblendspace2d-method-remove-triangle) **(** [int](class_int#class-int) triangle **)** |
| void | [set\_blend\_point\_node](#class-animationnodeblendspace2d-method-set-blend-point-node) **(** [int](class_int#class-int) point, [AnimationRootNode](class_animationrootnode#class-animationrootnode) node **)** |
| void | [set\_blend\_point\_position](#class-animationnodeblendspace2d-method-set-blend-point-position) **(** [int](class_int#class-int) point, [Vector2](class_vector2#class-vector2) pos **)** |
Signals
-------
### triangles\_updated ( )
Emitted every time the blend space's triangles are created, removed, or when one of their vertices changes position.
Enumerations
------------
enum **BlendMode**:
* **BLEND\_MODE\_INTERPOLATED** = **0** --- The interpolation between animations is linear.
* **BLEND\_MODE\_DISCRETE** = **1** --- The blend space plays the animation of the node the blending position is closest to. Useful for frame-by-frame 2D animations.
* **BLEND\_MODE\_DISCRETE\_CARRY** = **2** --- Similar to [BLEND\_MODE\_DISCRETE](#class-animationnodeblendspace2d-constant-blend-mode-discrete), but starts the new animation at the last animation's playback position.
Property Descriptions
---------------------
### [bool](class_bool#class-bool) auto\_triangles
| | |
| --- | --- |
| *Default* | `true` |
| *Setter* | set\_auto\_triangles(value) |
| *Getter* | get\_auto\_triangles() |
If `true`, the blend space is triangulated automatically. The mesh updates every time you add or remove points with [add\_blend\_point](#class-animationnodeblendspace2d-method-add-blend-point) and [remove\_blend\_point](#class-animationnodeblendspace2d-method-remove-blend-point).
### [BlendMode](#enum-animationnodeblendspace2d-blendmode) blend\_mode
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_blend\_mode(value) |
| *Getter* | get\_blend\_mode() |
Controls the interpolation between animations. See [BlendMode](#enum-animationnodeblendspace2d-blendmode) constants.
### [Vector2](class_vector2#class-vector2) max\_space
| | |
| --- | --- |
| *Default* | `Vector2( 1, 1 )` |
| *Setter* | set\_max\_space(value) |
| *Getter* | get\_max\_space() |
The blend space's X and Y axes' upper limit for the points' position. See [add\_blend\_point](#class-animationnodeblendspace2d-method-add-blend-point).
### [Vector2](class_vector2#class-vector2) min\_space
| | |
| --- | --- |
| *Default* | `Vector2( -1, -1 )` |
| *Setter* | set\_min\_space(value) |
| *Getter* | get\_min\_space() |
The blend space's X and Y axes' lower limit for the points' position. See [add\_blend\_point](#class-animationnodeblendspace2d-method-add-blend-point).
### [Vector2](class_vector2#class-vector2) snap
| | |
| --- | --- |
| *Default* | `Vector2( 0.1, 0.1 )` |
| *Setter* | set\_snap(value) |
| *Getter* | get\_snap() |
Position increment to snap to when moving a point.
### [String](class_string#class-string) x\_label
| | |
| --- | --- |
| *Default* | `"x"` |
| *Setter* | set\_x\_label(value) |
| *Getter* | get\_x\_label() |
Name of the blend space's X axis.
### [String](class_string#class-string) y\_label
| | |
| --- | --- |
| *Default* | `"y"` |
| *Setter* | set\_y\_label(value) |
| *Getter* | get\_y\_label() |
Name of the blend space's Y axis.
Method Descriptions
-------------------
### void add\_blend\_point ( [AnimationRootNode](class_animationrootnode#class-animationrootnode) node, [Vector2](class_vector2#class-vector2) pos, [int](class_int#class-int) at\_index=-1 )
Adds a new point that represents a `node` at the position set by `pos`. You can insert it at a specific index using the `at_index` argument. If you use the default value for `at_index`, the point is inserted at the end of the blend points array.
### void add\_triangle ( [int](class_int#class-int) x, [int](class_int#class-int) y, [int](class_int#class-int) z, [int](class_int#class-int) at\_index=-1 )
Creates a new triangle using three points `x`, `y`, and `z`. Triangles can overlap. You can insert the triangle at a specific index using the `at_index` argument. If you use the default value for `at_index`, the point is inserted at the end of the blend points array.
### [int](class_int#class-int) get\_blend\_point\_count ( ) const
Returns the number of points in the blend space.
### [AnimationRootNode](class_animationrootnode#class-animationrootnode) get\_blend\_point\_node ( [int](class_int#class-int) point ) const
Returns the [AnimationRootNode](class_animationrootnode#class-animationrootnode) referenced by the point at index `point`.
### [Vector2](class_vector2#class-vector2) get\_blend\_point\_position ( [int](class_int#class-int) point ) const
Returns the position of the point at index `point`.
### [int](class_int#class-int) get\_triangle\_count ( ) const
Returns the number of triangles in the blend space.
### [int](class_int#class-int) get\_triangle\_point ( [int](class_int#class-int) triangle, [int](class_int#class-int) point )
Returns the position of the point at index `point` in the triangle of index `triangle`.
### void remove\_blend\_point ( [int](class_int#class-int) point )
Removes the point at index `point` from the blend space.
### void remove\_triangle ( [int](class_int#class-int) triangle )
Removes the triangle at index `triangle` from the blend space.
### void set\_blend\_point\_node ( [int](class_int#class-int) point, [AnimationRootNode](class_animationrootnode#class-animationrootnode) node )
Changes the [AnimationNode](class_animationnode#class-animationnode) referenced by the point at index `point`.
### void set\_blend\_point\_position ( [int](class_int#class-int) point, [Vector2](class_vector2#class-vector2) pos )
Updates the position of the point at index `point` on the blend axis.
| programming_docs |
godot Curve Curve
=====
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
A mathematic curve.
Description
-----------
A curve that can be saved and re-used for other objects. By default, it ranges between `0` and `1` on the Y axis and positions points relative to the `0.5` Y position.
See also [Gradient](class_gradient#class-gradient) which is designed for color interpolation. See also [Curve2D](class_curve2d#class-curve2d) and [Curve3D](class_curve3d#class-curve3d).
Properties
----------
| | | |
| --- | --- | --- |
| [int](class_int#class-int) | [bake\_resolution](#class-curve-property-bake-resolution) | `100` |
| [float](class_float#class-float) | [max\_value](#class-curve-property-max-value) | `1.0` |
| [float](class_float#class-float) | [min\_value](#class-curve-property-min-value) | `0.0` |
Methods
-------
| | |
| --- | --- |
| [int](class_int#class-int) | [add\_point](#class-curve-method-add-point) **(** [Vector2](class_vector2#class-vector2) position, [float](class_float#class-float) left\_tangent=0, [float](class_float#class-float) right\_tangent=0, [TangentMode](#enum-curve-tangentmode) left\_mode=0, [TangentMode](#enum-curve-tangentmode) right\_mode=0 **)** |
| void | [bake](#class-curve-method-bake) **(** **)** |
| void | [clean\_dupes](#class-curve-method-clean-dupes) **(** **)** |
| void | [clear\_points](#class-curve-method-clear-points) **(** **)** |
| [int](class_int#class-int) | [get\_point\_count](#class-curve-method-get-point-count) **(** **)** const |
| [TangentMode](#enum-curve-tangentmode) | [get\_point\_left\_mode](#class-curve-method-get-point-left-mode) **(** [int](class_int#class-int) index **)** const |
| [float](class_float#class-float) | [get\_point\_left\_tangent](#class-curve-method-get-point-left-tangent) **(** [int](class_int#class-int) index **)** const |
| [Vector2](class_vector2#class-vector2) | [get\_point\_position](#class-curve-method-get-point-position) **(** [int](class_int#class-int) index **)** const |
| [TangentMode](#enum-curve-tangentmode) | [get\_point\_right\_mode](#class-curve-method-get-point-right-mode) **(** [int](class_int#class-int) index **)** const |
| [float](class_float#class-float) | [get\_point\_right\_tangent](#class-curve-method-get-point-right-tangent) **(** [int](class_int#class-int) index **)** const |
| [float](class_float#class-float) | [interpolate](#class-curve-method-interpolate) **(** [float](class_float#class-float) offset **)** const |
| [float](class_float#class-float) | [interpolate\_baked](#class-curve-method-interpolate-baked) **(** [float](class_float#class-float) offset **)** |
| void | [remove\_point](#class-curve-method-remove-point) **(** [int](class_int#class-int) index **)** |
| void | [set\_point\_left\_mode](#class-curve-method-set-point-left-mode) **(** [int](class_int#class-int) index, [TangentMode](#enum-curve-tangentmode) mode **)** |
| void | [set\_point\_left\_tangent](#class-curve-method-set-point-left-tangent) **(** [int](class_int#class-int) index, [float](class_float#class-float) tangent **)** |
| [int](class_int#class-int) | [set\_point\_offset](#class-curve-method-set-point-offset) **(** [int](class_int#class-int) index, [float](class_float#class-float) offset **)** |
| void | [set\_point\_right\_mode](#class-curve-method-set-point-right-mode) **(** [int](class_int#class-int) index, [TangentMode](#enum-curve-tangentmode) mode **)** |
| void | [set\_point\_right\_tangent](#class-curve-method-set-point-right-tangent) **(** [int](class_int#class-int) index, [float](class_float#class-float) tangent **)** |
| void | [set\_point\_value](#class-curve-method-set-point-value) **(** [int](class_int#class-int) index, [float](class_float#class-float) y **)** |
Signals
-------
### range\_changed ( )
Emitted when [max\_value](#class-curve-property-max-value) or [min\_value](#class-curve-property-min-value) is changed.
Enumerations
------------
enum **TangentMode**:
* **TANGENT\_FREE** = **0** --- The tangent on this side of the point is user-defined.
* **TANGENT\_LINEAR** = **1** --- The curve calculates the tangent on this side of the point as the slope halfway towards the adjacent point.
* **TANGENT\_MODE\_COUNT** = **2** --- The total number of available tangent modes.
Property Descriptions
---------------------
### [int](class_int#class-int) bake\_resolution
| | |
| --- | --- |
| *Default* | `100` |
| *Setter* | set\_bake\_resolution(value) |
| *Getter* | get\_bake\_resolution() |
The number of points to include in the baked (i.e. cached) curve data.
### [float](class_float#class-float) max\_value
| | |
| --- | --- |
| *Default* | `1.0` |
| *Setter* | set\_max\_value(value) |
| *Getter* | get\_max\_value() |
The maximum value the curve can reach.
### [float](class_float#class-float) min\_value
| | |
| --- | --- |
| *Default* | `0.0` |
| *Setter* | set\_min\_value(value) |
| *Getter* | get\_min\_value() |
The minimum value the curve can reach.
Method Descriptions
-------------------
### [int](class_int#class-int) add\_point ( [Vector2](class_vector2#class-vector2) position, [float](class_float#class-float) left\_tangent=0, [float](class_float#class-float) right\_tangent=0, [TangentMode](#enum-curve-tangentmode) left\_mode=0, [TangentMode](#enum-curve-tangentmode) right\_mode=0 )
Adds a point to the curve. For each side, if the `*_mode` is [TANGENT\_LINEAR](#class-curve-constant-tangent-linear), the `*_tangent` angle (in degrees) uses the slope of the curve halfway to the adjacent point. Allows custom assignments to the `*_tangent` angle if `*_mode` is set to [TANGENT\_FREE](#class-curve-constant-tangent-free).
### void bake ( )
Recomputes the baked cache of points for the curve.
### void clean\_dupes ( )
Removes points that are closer than `CMP_EPSILON` (0.00001) units to their neighbor on the curve.
### void clear\_points ( )
Removes all points from the curve.
### [int](class_int#class-int) get\_point\_count ( ) const
Returns the number of points describing the curve.
### [TangentMode](#enum-curve-tangentmode) get\_point\_left\_mode ( [int](class_int#class-int) index ) const
Returns the left [TangentMode](#enum-curve-tangentmode) for the point at `index`.
### [float](class_float#class-float) get\_point\_left\_tangent ( [int](class_int#class-int) index ) const
Returns the left tangent angle (in degrees) for the point at `index`.
### [Vector2](class_vector2#class-vector2) get\_point\_position ( [int](class_int#class-int) index ) const
Returns the curve coordinates for the point at `index`.
### [TangentMode](#enum-curve-tangentmode) get\_point\_right\_mode ( [int](class_int#class-int) index ) const
Returns the right [TangentMode](#enum-curve-tangentmode) for the point at `index`.
### [float](class_float#class-float) get\_point\_right\_tangent ( [int](class_int#class-int) index ) const
Returns the right tangent angle (in degrees) for the point at `index`.
### [float](class_float#class-float) interpolate ( [float](class_float#class-float) offset ) const
Returns the Y value for the point that would exist at the X position `offset` along the curve.
### [float](class_float#class-float) interpolate\_baked ( [float](class_float#class-float) offset )
Returns the Y value for the point that would exist at the X position `offset` along the curve using the baked cache. Bakes the curve's points if not already baked.
### void remove\_point ( [int](class_int#class-int) index )
Removes the point at `index` from the curve.
### void set\_point\_left\_mode ( [int](class_int#class-int) index, [TangentMode](#enum-curve-tangentmode) mode )
Sets the left [TangentMode](#enum-curve-tangentmode) for the point at `index` to `mode`.
### void set\_point\_left\_tangent ( [int](class_int#class-int) index, [float](class_float#class-float) tangent )
Sets the left tangent angle for the point at `index` to `tangent`.
### [int](class_int#class-int) set\_point\_offset ( [int](class_int#class-int) index, [float](class_float#class-float) offset )
Sets the offset from `0.5`.
### void set\_point\_right\_mode ( [int](class_int#class-int) index, [TangentMode](#enum-curve-tangentmode) mode )
Sets the right [TangentMode](#enum-curve-tangentmode) for the point at `index` to `mode`.
### void set\_point\_right\_tangent ( [int](class_int#class-int) index, [float](class_float#class-float) tangent )
Sets the right tangent angle for the point at `index` to `tangent`.
### void set\_point\_value ( [int](class_int#class-int) index, [float](class_float#class-float) y )
Assigns the vertical position `y` to the point at `index`.
godot AnimationNodeStateMachinePlayback AnimationNodeStateMachinePlayback
=================================
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Playback control for [AnimationNodeStateMachine](class_animationnodestatemachine#class-animationnodestatemachine).
Description
-----------
Allows control of [AnimationTree](class_animationtree#class-animationtree) state machines created with [AnimationNodeStateMachine](class_animationnodestatemachine#class-animationnodestatemachine). Retrieve with `$AnimationTree.get("parameters/playback")`.
**Example:**
```
var state_machine = $AnimationTree.get("parameters/playback")
state_machine.travel("some_state")
```
Tutorials
---------
* [Using AnimationTree](https://docs.godotengine.org/en/3.5/tutorials/animation/animation_tree.html)
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | resource\_local\_to\_scene | `true` (overrides [Resource](class_resource#class-resource-property-resource-local-to-scene)) |
Methods
-------
| | |
| --- | --- |
| [float](class_float#class-float) | [get\_current\_length](#class-animationnodestatemachineplayback-method-get-current-length) **(** **)** const |
| [String](class_string#class-string) | [get\_current\_node](#class-animationnodestatemachineplayback-method-get-current-node) **(** **)** const |
| [float](class_float#class-float) | [get\_current\_play\_position](#class-animationnodestatemachineplayback-method-get-current-play-position) **(** **)** const |
| [PoolStringArray](class_poolstringarray#class-poolstringarray) | [get\_travel\_path](#class-animationnodestatemachineplayback-method-get-travel-path) **(** **)** const |
| [bool](class_bool#class-bool) | [is\_playing](#class-animationnodestatemachineplayback-method-is-playing) **(** **)** const |
| void | [start](#class-animationnodestatemachineplayback-method-start) **(** [String](class_string#class-string) node **)** |
| void | [stop](#class-animationnodestatemachineplayback-method-stop) **(** **)** |
| void | [travel](#class-animationnodestatemachineplayback-method-travel) **(** [String](class_string#class-string) to\_node **)** |
Method Descriptions
-------------------
### [float](class_float#class-float) get\_current\_length ( ) const
### [String](class_string#class-string) get\_current\_node ( ) const
Returns the currently playing animation state.
### [float](class_float#class-float) get\_current\_play\_position ( ) const
Returns the playback position within the current animation state.
### [PoolStringArray](class_poolstringarray#class-poolstringarray) get\_travel\_path ( ) const
Returns the current travel path as computed internally by the A\* algorithm.
### [bool](class_bool#class-bool) is\_playing ( ) const
Returns `true` if an animation is playing.
### void start ( [String](class_string#class-string) node )
Starts playing the given animation.
### void stop ( )
Stops the currently playing animation.
### void travel ( [String](class_string#class-string) to\_node )
Transitions from the current state to another one, following the shortest path.
godot AudioStreamGeneratorPlayback AudioStreamGeneratorPlayback
============================
**Inherits:** [AudioStreamPlaybackResampled](class_audiostreamplaybackresampled#class-audiostreamplaybackresampled) **<** [AudioStreamPlayback](class_audiostreamplayback#class-audiostreamplayback) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Plays back audio generated using [AudioStreamGenerator](class_audiostreamgenerator#class-audiostreamgenerator).
Description
-----------
This class is meant to be used with [AudioStreamGenerator](class_audiostreamgenerator#class-audiostreamgenerator) to play back the generated audio in real-time.
Tutorials
---------
* [Audio Generator Demo](https://godotengine.org/asset-library/asset/526)
* [Godot 3.2 will get new audio features](https://godotengine.org/article/godot-32-will-get-new-audio-features)
Methods
-------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [can\_push\_buffer](#class-audiostreamgeneratorplayback-method-can-push-buffer) **(** [int](class_int#class-int) amount **)** const |
| void | [clear\_buffer](#class-audiostreamgeneratorplayback-method-clear-buffer) **(** **)** |
| [int](class_int#class-int) | [get\_frames\_available](#class-audiostreamgeneratorplayback-method-get-frames-available) **(** **)** const |
| [int](class_int#class-int) | [get\_skips](#class-audiostreamgeneratorplayback-method-get-skips) **(** **)** const |
| [bool](class_bool#class-bool) | [push\_buffer](#class-audiostreamgeneratorplayback-method-push-buffer) **(** [PoolVector2Array](class_poolvector2array#class-poolvector2array) frames **)** |
| [bool](class_bool#class-bool) | [push\_frame](#class-audiostreamgeneratorplayback-method-push-frame) **(** [Vector2](class_vector2#class-vector2) frame **)** |
Method Descriptions
-------------------
### [bool](class_bool#class-bool) can\_push\_buffer ( [int](class_int#class-int) amount ) const
Returns `true` if a buffer of the size `amount` can be pushed to the audio sample data buffer without overflowing it, `false` otherwise.
### void clear\_buffer ( )
Clears the audio sample data buffer.
### [int](class_int#class-int) get\_frames\_available ( ) const
Returns the number of audio data frames left to play. If this returned number reaches `0`, the audio will stop playing until frames are added again. Therefore, make sure your script can always generate and push new audio frames fast enough to avoid audio cracking.
### [int](class_int#class-int) get\_skips ( ) const
### [bool](class_bool#class-bool) push\_buffer ( [PoolVector2Array](class_poolvector2array#class-poolvector2array) frames )
Pushes several audio data frames to the buffer. This is usually more efficient than [push\_frame](#class-audiostreamgeneratorplayback-method-push-frame) in C# and compiled languages via GDNative, but [push\_buffer](#class-audiostreamgeneratorplayback-method-push-buffer) may be *less* efficient in GDScript.
### [bool](class_bool#class-bool) push\_frame ( [Vector2](class_vector2#class-vector2) frame )
Pushes a single audio data frame to the buffer. This is usually less efficient than [push\_buffer](#class-audiostreamgeneratorplayback-method-push-buffer) in C# and compiled languages via GDNative, but [push\_frame](#class-audiostreamgeneratorplayback-method-push-frame) may be *more* efficient in GDScript.
godot GLTFSkeleton GLTFSkeleton
============
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
Description
-----------
**Note:** This class is only compiled in editor builds. Run-time glTF loading and saving is *not* available in exported projects. References to `GLTFSkeleton` within a script will cause an error in an exported project.
Properties
----------
| | | |
| --- | --- | --- |
| [PoolIntArray](class_poolintarray#class-poolintarray) | [joints](#class-gltfskeleton-property-joints) | `PoolIntArray( )` |
| [PoolIntArray](class_poolintarray#class-poolintarray) | [roots](#class-gltfskeleton-property-roots) | `PoolIntArray( )` |
Methods
-------
| | |
| --- | --- |
| [BoneAttachment](class_boneattachment#class-boneattachment) | [get\_bone\_attachment](#class-gltfskeleton-method-get-bone-attachment) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_bone\_attachment\_count](#class-gltfskeleton-method-get-bone-attachment-count) **(** **)** |
| [Dictionary](class_dictionary#class-dictionary) | [get\_godot\_bone\_node](#class-gltfskeleton-method-get-godot-bone-node) **(** **)** |
| [Skeleton](class_skeleton#class-skeleton) | [get\_godot\_skeleton](#class-gltfskeleton-method-get-godot-skeleton) **(** **)** |
| [Array](class_array#class-array) | [get\_unique\_names](#class-gltfskeleton-method-get-unique-names) **(** **)** |
| void | [set\_godot\_bone\_node](#class-gltfskeleton-method-set-godot-bone-node) **(** [Dictionary](class_dictionary#class-dictionary) godot\_bone\_node **)** |
| void | [set\_unique\_names](#class-gltfskeleton-method-set-unique-names) **(** [Array](class_array#class-array) unique\_names **)** |
Property Descriptions
---------------------
### [PoolIntArray](class_poolintarray#class-poolintarray) joints
| | |
| --- | --- |
| *Default* | `PoolIntArray( )` |
| *Setter* | set\_joints(value) |
| *Getter* | get\_joints() |
### [PoolIntArray](class_poolintarray#class-poolintarray) roots
| | |
| --- | --- |
| *Default* | `PoolIntArray( )` |
| *Setter* | set\_roots(value) |
| *Getter* | get\_roots() |
Method Descriptions
-------------------
### [BoneAttachment](class_boneattachment#class-boneattachment) get\_bone\_attachment ( [int](class_int#class-int) idx )
### [int](class_int#class-int) get\_bone\_attachment\_count ( )
### [Dictionary](class_dictionary#class-dictionary) get\_godot\_bone\_node ( )
### [Skeleton](class_skeleton#class-skeleton) get\_godot\_skeleton ( )
### [Array](class_array#class-array) get\_unique\_names ( )
### void set\_godot\_bone\_node ( [Dictionary](class_dictionary#class-dictionary) godot\_bone\_node )
### void set\_unique\_names ( [Array](class_array#class-array) unique\_names )
godot AudioEffect AudioEffect
===========
**Inherits:** [Resource](class_resource#class-resource) **<** [Reference](class_reference#class-reference) **<** [Object](class_object#class-object)
**Inherited By:** [AudioEffectAmplify](class_audioeffectamplify#class-audioeffectamplify), [AudioEffectCapture](class_audioeffectcapture#class-audioeffectcapture), [AudioEffectChorus](class_audioeffectchorus#class-audioeffectchorus), [AudioEffectCompressor](class_audioeffectcompressor#class-audioeffectcompressor), [AudioEffectDelay](class_audioeffectdelay#class-audioeffectdelay), [AudioEffectDistortion](class_audioeffectdistortion#class-audioeffectdistortion), [AudioEffectEQ](class_audioeffecteq#class-audioeffecteq), [AudioEffectFilter](class_audioeffectfilter#class-audioeffectfilter), [AudioEffectLimiter](class_audioeffectlimiter#class-audioeffectlimiter), [AudioEffectPanner](class_audioeffectpanner#class-audioeffectpanner), [AudioEffectPhaser](class_audioeffectphaser#class-audioeffectphaser), [AudioEffectPitchShift](class_audioeffectpitchshift#class-audioeffectpitchshift), [AudioEffectRecord](class_audioeffectrecord#class-audioeffectrecord), [AudioEffectReverb](class_audioeffectreverb#class-audioeffectreverb), [AudioEffectSpectrumAnalyzer](class_audioeffectspectrumanalyzer#class-audioeffectspectrumanalyzer), [AudioEffectStereoEnhance](class_audioeffectstereoenhance#class-audioeffectstereoenhance)
Audio effect for audio.
Description
-----------
Base resource for audio bus. Applies an audio effect on the bus that the resource is applied on.
Tutorials
---------
* [Audio Mic Record Demo](https://godotengine.org/asset-library/asset/527)
godot HSplitContainer HSplitContainer
===============
**Inherits:** [SplitContainer](class_splitcontainer#class-splitcontainer) **<** [Container](class_container#class-container) **<** [Control](class_control#class-control) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
Horizontal split container.
Description
-----------
Horizontal split container. See [SplitContainer](class_splitcontainer#class-splitcontainer). This goes from left to right.
Tutorials
---------
* [GUI containers](https://docs.godotengine.org/en/3.5/tutorials/ui/gui_containers.html)
Theme Properties
----------------
| | | |
| --- | --- | --- |
| [int](class_int#class-int) | [autohide](#class-hsplitcontainer-theme-constant-autohide) | `1` |
| [int](class_int#class-int) | [separation](#class-hsplitcontainer-theme-constant-separation) | `12` |
| [Texture](class_texture#class-texture) | [grabber](#class-hsplitcontainer-theme-icon-grabber) | |
| [StyleBox](class_stylebox#class-stylebox) | [bg](#class-hsplitcontainer-theme-style-bg) | |
Theme Property Descriptions
---------------------------
### [int](class_int#class-int) autohide
| | |
| --- | --- |
| *Default* | `1` |
Boolean value. If 1 (`true`), the grabber will hide automatically when it isn't under the cursor. If 0 (`false`), it's always visible.
### [int](class_int#class-int) separation
| | |
| --- | --- |
| *Default* | `12` |
The space between sides of the container.
### [Texture](class_texture#class-texture) grabber
The icon used for the grabber drawn in the middle area.
### [StyleBox](class_stylebox#class-stylebox) bg
| programming_docs |
godot GraphNode GraphNode
=========
**Inherits:** [Container](class_container#class-container) **<** [Control](class_control#class-control) **<** [CanvasItem](class_canvasitem#class-canvasitem) **<** [Node](class_node#class-node) **<** [Object](class_object#class-object)
A GraphNode is a container with potentially several input and output slots allowing connections between GraphNodes. Slots can have different, incompatible types.
Description
-----------
A GraphNode is a container. Each GraphNode can have several input and output slots, sometimes referred to as ports, allowing connections between GraphNodes. To add a slot to GraphNode, add any [Control](class_control#class-control)-derived child node to it.
After adding at least one child to GraphNode new sections will be automatically created in the Inspector called 'Slot'. When 'Slot' is expanded you will see list with index number for each slot. You can click on each of them to expand further.
In the Inspector you can enable (show) or disable (hide) slots. By default, all slots are disabled so you may not see any slots on your GraphNode initially. You can assign a type to each slot. Only slots of the same type will be able to connect to each other. You can also assign colors to slots. A tuple of input and output slots is defined for each GUI element included in the GraphNode. Input connections are on the left and output connections are on the right side of GraphNode. Only enabled slots are counted as connections.
Properties
----------
| | | |
| --- | --- | --- |
| [bool](class_bool#class-bool) | [comment](#class-graphnode-property-comment) | `false` |
| [Vector2](class_vector2#class-vector2) | [offset](#class-graphnode-property-offset) | `Vector2( 0, 0 )` |
| [Overlay](#enum-graphnode-overlay) | [overlay](#class-graphnode-property-overlay) | `0` |
| [bool](class_bool#class-bool) | [resizable](#class-graphnode-property-resizable) | `false` |
| [bool](class_bool#class-bool) | [selected](#class-graphnode-property-selected) | `false` |
| [bool](class_bool#class-bool) | [show\_close](#class-graphnode-property-show-close) | `false` |
| [String](class_string#class-string) | [title](#class-graphnode-property-title) | `""` |
Methods
-------
| | |
| --- | --- |
| void | [clear\_all\_slots](#class-graphnode-method-clear-all-slots) **(** **)** |
| void | [clear\_slot](#class-graphnode-method-clear-slot) **(** [int](class_int#class-int) idx **)** |
| [Color](class_color#class-color) | [get\_connection\_input\_color](#class-graphnode-method-get-connection-input-color) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_connection\_input\_count](#class-graphnode-method-get-connection-input-count) **(** **)** |
| [Vector2](class_vector2#class-vector2) | [get\_connection\_input\_position](#class-graphnode-method-get-connection-input-position) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_connection\_input\_type](#class-graphnode-method-get-connection-input-type) **(** [int](class_int#class-int) idx **)** |
| [Color](class_color#class-color) | [get\_connection\_output\_color](#class-graphnode-method-get-connection-output-color) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_connection\_output\_count](#class-graphnode-method-get-connection-output-count) **(** **)** |
| [Vector2](class_vector2#class-vector2) | [get\_connection\_output\_position](#class-graphnode-method-get-connection-output-position) **(** [int](class_int#class-int) idx **)** |
| [int](class_int#class-int) | [get\_connection\_output\_type](#class-graphnode-method-get-connection-output-type) **(** [int](class_int#class-int) idx **)** |
| [Color](class_color#class-color) | [get\_slot\_color\_left](#class-graphnode-method-get-slot-color-left) **(** [int](class_int#class-int) idx **)** const |
| [Color](class_color#class-color) | [get\_slot\_color\_right](#class-graphnode-method-get-slot-color-right) **(** [int](class_int#class-int) idx **)** const |
| [int](class_int#class-int) | [get\_slot\_type\_left](#class-graphnode-method-get-slot-type-left) **(** [int](class_int#class-int) idx **)** const |
| [int](class_int#class-int) | [get\_slot\_type\_right](#class-graphnode-method-get-slot-type-right) **(** [int](class_int#class-int) idx **)** const |
| [bool](class_bool#class-bool) | [is\_slot\_enabled\_left](#class-graphnode-method-is-slot-enabled-left) **(** [int](class_int#class-int) idx **)** const |
| [bool](class_bool#class-bool) | [is\_slot\_enabled\_right](#class-graphnode-method-is-slot-enabled-right) **(** [int](class_int#class-int) idx **)** const |
| void | [set\_slot](#class-graphnode-method-set-slot) **(** [int](class_int#class-int) idx, [bool](class_bool#class-bool) enable\_left, [int](class_int#class-int) type\_left, [Color](class_color#class-color) color\_left, [bool](class_bool#class-bool) enable\_right, [int](class_int#class-int) type\_right, [Color](class_color#class-color) color\_right, [Texture](class_texture#class-texture) custom\_left=null, [Texture](class_texture#class-texture) custom\_right=null **)** |
| void | [set\_slot\_color\_left](#class-graphnode-method-set-slot-color-left) **(** [int](class_int#class-int) idx, [Color](class_color#class-color) color\_left **)** |
| void | [set\_slot\_color\_right](#class-graphnode-method-set-slot-color-right) **(** [int](class_int#class-int) idx, [Color](class_color#class-color) color\_right **)** |
| void | [set\_slot\_enabled\_left](#class-graphnode-method-set-slot-enabled-left) **(** [int](class_int#class-int) idx, [bool](class_bool#class-bool) enable\_left **)** |
| void | [set\_slot\_enabled\_right](#class-graphnode-method-set-slot-enabled-right) **(** [int](class_int#class-int) idx, [bool](class_bool#class-bool) enable\_right **)** |
| void | [set\_slot\_type\_left](#class-graphnode-method-set-slot-type-left) **(** [int](class_int#class-int) idx, [int](class_int#class-int) type\_left **)** |
| void | [set\_slot\_type\_right](#class-graphnode-method-set-slot-type-right) **(** [int](class_int#class-int) idx, [int](class_int#class-int) type\_right **)** |
Theme Properties
----------------
| | | |
| --- | --- | --- |
| [Color](class_color#class-color) | [close\_color](#class-graphnode-theme-color-close-color) | `Color( 0, 0, 0, 1 )` |
| [Color](class_color#class-color) | [resizer\_color](#class-graphnode-theme-color-resizer-color) | `Color( 0, 0, 0, 1 )` |
| [Color](class_color#class-color) | [title\_color](#class-graphnode-theme-color-title-color) | `Color( 0, 0, 0, 1 )` |
| [int](class_int#class-int) | [close\_offset](#class-graphnode-theme-constant-close-offset) | `18` |
| [int](class_int#class-int) | [port\_offset](#class-graphnode-theme-constant-port-offset) | `3` |
| [int](class_int#class-int) | [separation](#class-graphnode-theme-constant-separation) | `1` |
| [int](class_int#class-int) | [title\_offset](#class-graphnode-theme-constant-title-offset) | `20` |
| [Font](class_font#class-font) | [title\_font](#class-graphnode-theme-font-title-font) | |
| [Texture](class_texture#class-texture) | [close](#class-graphnode-theme-icon-close) | |
| [Texture](class_texture#class-texture) | [port](#class-graphnode-theme-icon-port) | |
| [Texture](class_texture#class-texture) | [resizer](#class-graphnode-theme-icon-resizer) | |
| [StyleBox](class_stylebox#class-stylebox) | [breakpoint](#class-graphnode-theme-style-breakpoint) | |
| [StyleBox](class_stylebox#class-stylebox) | [comment](#class-graphnode-theme-style-comment) | |
| [StyleBox](class_stylebox#class-stylebox) | [commentfocus](#class-graphnode-theme-style-commentfocus) | |
| [StyleBox](class_stylebox#class-stylebox) | [defaultfocus](#class-graphnode-theme-style-defaultfocus) | |
| [StyleBox](class_stylebox#class-stylebox) | [defaultframe](#class-graphnode-theme-style-defaultframe) | |
| [StyleBox](class_stylebox#class-stylebox) | [frame](#class-graphnode-theme-style-frame) | |
| [StyleBox](class_stylebox#class-stylebox) | [position](#class-graphnode-theme-style-position) | |
| [StyleBox](class_stylebox#class-stylebox) | [selectedframe](#class-graphnode-theme-style-selectedframe) | |
Signals
-------
### close\_request ( )
Emitted when the GraphNode is requested to be closed. Happens on clicking the close button (see [show\_close](#class-graphnode-property-show-close)).
### dragged ( [Vector2](class_vector2#class-vector2) from, [Vector2](class_vector2#class-vector2) to )
Emitted when the GraphNode is dragged.
### offset\_changed ( )
Emitted when the GraphNode is moved.
### raise\_request ( )
Emitted when the GraphNode is requested to be displayed over other ones. Happens on focusing (clicking into) the GraphNode.
### resize\_request ( [Vector2](class_vector2#class-vector2) new\_minsize )
Emitted when the GraphNode is requested to be resized. Happens on dragging the resizer handle (see [resizable](#class-graphnode-property-resizable)).
### slot\_updated ( [int](class_int#class-int) idx )
Emitted when any GraphNode's slot is updated.
Enumerations
------------
enum **Overlay**:
* **OVERLAY\_DISABLED** = **0** --- No overlay is shown.
* **OVERLAY\_BREAKPOINT** = **1** --- Show overlay set in the `breakpoint` theme property.
* **OVERLAY\_POSITION** = **2** --- Show overlay set in the `position` theme property.
Property Descriptions
---------------------
### [bool](class_bool#class-bool) comment
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_comment(value) |
| *Getter* | is\_comment() |
If `true`, the GraphNode is a comment node.
### [Vector2](class_vector2#class-vector2) offset
| | |
| --- | --- |
| *Default* | `Vector2( 0, 0 )` |
| *Setter* | set\_offset(value) |
| *Getter* | get\_offset() |
The offset of the GraphNode, relative to the scroll offset of the [GraphEdit](class_graphedit#class-graphedit).
**Note:** You cannot use position directly, as [GraphEdit](class_graphedit#class-graphedit) is a [Container](class_container#class-container).
### [Overlay](#enum-graphnode-overlay) overlay
| | |
| --- | --- |
| *Default* | `0` |
| *Setter* | set\_overlay(value) |
| *Getter* | get\_overlay() |
Sets the overlay shown above the GraphNode. See [Overlay](#enum-graphnode-overlay).
### [bool](class_bool#class-bool) resizable
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_resizable(value) |
| *Getter* | is\_resizable() |
If `true`, the user can resize the GraphNode.
**Note:** Dragging the handle will only emit the [resize\_request](#class-graphnode-signal-resize-request) signal, the GraphNode needs to be resized manually.
### [bool](class_bool#class-bool) selected
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_selected(value) |
| *Getter* | is\_selected() |
If `true`, the GraphNode is selected.
### [bool](class_bool#class-bool) show\_close
| | |
| --- | --- |
| *Default* | `false` |
| *Setter* | set\_show\_close\_button(value) |
| *Getter* | is\_close\_button\_visible() |
If `true`, the close button will be visible.
**Note:** Pressing it will only emit the [close\_request](#class-graphnode-signal-close-request) signal, the GraphNode needs to be removed manually.
### [String](class_string#class-string) title
| | |
| --- | --- |
| *Default* | `""` |
| *Setter* | set\_title(value) |
| *Getter* | get\_title() |
The text displayed in the GraphNode's title bar.
Method Descriptions
-------------------
### void clear\_all\_slots ( )
Disables all input and output slots of the GraphNode.
### void clear\_slot ( [int](class_int#class-int) idx )
Disables input and output slot whose index is `idx`.
### [Color](class_color#class-color) get\_connection\_input\_color ( [int](class_int#class-int) idx )
Returns the [Color](class_color#class-color) of the input connection `idx`.
### [int](class_int#class-int) get\_connection\_input\_count ( )
Returns the number of enabled input slots (connections) to the GraphNode.
### [Vector2](class_vector2#class-vector2) get\_connection\_input\_position ( [int](class_int#class-int) idx )
Returns the position of the input connection `idx`.
### [int](class_int#class-int) get\_connection\_input\_type ( [int](class_int#class-int) idx )
Returns the type of the input connection `idx`.
### [Color](class_color#class-color) get\_connection\_output\_color ( [int](class_int#class-int) idx )
Returns the [Color](class_color#class-color) of the output connection `idx`.
### [int](class_int#class-int) get\_connection\_output\_count ( )
Returns the number of enabled output slots (connections) of the GraphNode.
### [Vector2](class_vector2#class-vector2) get\_connection\_output\_position ( [int](class_int#class-int) idx )
Returns the position of the output connection `idx`.
### [int](class_int#class-int) get\_connection\_output\_type ( [int](class_int#class-int) idx )
Returns the type of the output connection `idx`.
### [Color](class_color#class-color) get\_slot\_color\_left ( [int](class_int#class-int) idx ) const
Returns the left (input) [Color](class_color#class-color) of the slot `idx`.
### [Color](class_color#class-color) get\_slot\_color\_right ( [int](class_int#class-int) idx ) const
Returns the right (output) [Color](class_color#class-color) of the slot `idx`.
### [int](class_int#class-int) get\_slot\_type\_left ( [int](class_int#class-int) idx ) const
Returns the left (input) type of the slot `idx`.
### [int](class_int#class-int) get\_slot\_type\_right ( [int](class_int#class-int) idx ) const
Returns the right (output) type of the slot `idx`.
### [bool](class_bool#class-bool) is\_slot\_enabled\_left ( [int](class_int#class-int) idx ) const
Returns `true` if left (input) side of the slot `idx` is enabled.
### [bool](class_bool#class-bool) is\_slot\_enabled\_right ( [int](class_int#class-int) idx ) const
Returns `true` if right (output) side of the slot `idx` is enabled.
### void set\_slot ( [int](class_int#class-int) idx, [bool](class_bool#class-bool) enable\_left, [int](class_int#class-int) type\_left, [Color](class_color#class-color) color\_left, [bool](class_bool#class-bool) enable\_right, [int](class_int#class-int) type\_right, [Color](class_color#class-color) color\_right, [Texture](class_texture#class-texture) custom\_left=null, [Texture](class_texture#class-texture) custom\_right=null )
Sets properties of the slot with ID `idx`.
If `enable_left`/`right`, a port will appear and the slot will be able to be connected from this side.
`type_left`/`right` is an arbitrary type of the port. Only ports with the same type values can be connected.
`color_left`/`right` is the tint of the port's icon on this side.
`custom_left`/`right` is a custom texture for this side's port.
**Note:** This method only sets properties of the slot. To create the slot, add a [Control](class_control#class-control)-derived child to the GraphNode.
Individual properties can be set using one of the `set_slot_*` methods. You must enable at least one side of the slot to do so.
### void set\_slot\_color\_left ( [int](class_int#class-int) idx, [Color](class_color#class-color) color\_left )
Sets the [Color](class_color#class-color) of the left (input) side of the slot `idx` to `color_left`.
### void set\_slot\_color\_right ( [int](class_int#class-int) idx, [Color](class_color#class-color) color\_right )
Sets the [Color](class_color#class-color) of the right (output) side of the slot `idx` to `color_right`.
### void set\_slot\_enabled\_left ( [int](class_int#class-int) idx, [bool](class_bool#class-bool) enable\_left )
Toggles the left (input) side of the slot `idx`. If `enable_left` is `true`, a port will appear on the left side and the slot will be able to be connected from this side.
### void set\_slot\_enabled\_right ( [int](class_int#class-int) idx, [bool](class_bool#class-bool) enable\_right )
Toggles the right (output) side of the slot `idx`. If `enable_right` is `true`, a port will appear on the right side and the slot will be able to be connected from this side.
### void set\_slot\_type\_left ( [int](class_int#class-int) idx, [int](class_int#class-int) type\_left )
Sets the left (input) type of the slot `idx` to `type_left`.
### void set\_slot\_type\_right ( [int](class_int#class-int) idx, [int](class_int#class-int) type\_right )
Sets the right (output) type of the slot `idx` to `type_right`.
Theme Property Descriptions
---------------------------
### [Color](class_color#class-color) close\_color
| | |
| --- | --- |
| *Default* | `Color( 0, 0, 0, 1 )` |
The color modulation applied to the close button icon.
### [Color](class_color#class-color) resizer\_color
| | |
| --- | --- |
| *Default* | `Color( 0, 0, 0, 1 )` |
The color modulation applied to the resizer icon.
### [Color](class_color#class-color) title\_color
| | |
| --- | --- |
| *Default* | `Color( 0, 0, 0, 1 )` |
Color of the title text.
### [int](class_int#class-int) close\_offset
| | |
| --- | --- |
| *Default* | `18` |
The vertical offset of the close button.
### [int](class_int#class-int) port\_offset
| | |
| --- | --- |
| *Default* | `3` |
Horizontal offset for the ports.
### [int](class_int#class-int) separation
| | |
| --- | --- |
| *Default* | `1` |
The vertical distance between ports.
### [int](class_int#class-int) title\_offset
| | |
| --- | --- |
| *Default* | `20` |
Vertical offset of the title text.
### [Font](class_font#class-font) title\_font
Font used for the title text.
### [Texture](class_texture#class-texture) close
The icon for the close button, visible when [show\_close](#class-graphnode-property-show-close) is enabled.
### [Texture](class_texture#class-texture) port
The icon used for representing ports.
### [Texture](class_texture#class-texture) resizer
The icon used for resizer, visible when [resizable](#class-graphnode-property-resizable) is enabled.
### [StyleBox](class_stylebox#class-stylebox) breakpoint
The background used when [overlay](#class-graphnode-property-overlay) is set to [OVERLAY\_BREAKPOINT](#class-graphnode-constant-overlay-breakpoint).
### [StyleBox](class_stylebox#class-stylebox) comment
The [StyleBox](class_stylebox#class-stylebox) used when [comment](#class-graphnode-property-comment) is enabled.
### [StyleBox](class_stylebox#class-stylebox) commentfocus
The [StyleBox](class_stylebox#class-stylebox) used when [comment](#class-graphnode-property-comment) is enabled and the `GraphNode` is focused.
### [StyleBox](class_stylebox#class-stylebox) defaultfocus
### [StyleBox](class_stylebox#class-stylebox) defaultframe
### [StyleBox](class_stylebox#class-stylebox) frame
The default background for `GraphNode`.
### [StyleBox](class_stylebox#class-stylebox) position
The background used when [overlay](#class-graphnode-property-overlay) is set to [OVERLAY\_POSITION](#class-graphnode-constant-overlay-position).
### [StyleBox](class_stylebox#class-stylebox) selectedframe
The background used when the `GraphNode` is selected.
godot VisualServer VisualServer
============
**Inherits:** [Object](class_object#class-object)
Server for anything visible.
Description
-----------
Server for anything visible. The visual server is the API backend for everything visible. The whole scene system mounts on it to display.
The visual server is completely opaque, the internals are entirely implementation specific and cannot be accessed.
The visual server can be used to bypass the scene system entirely.
Resources are created using the `*_create` functions.
All objects are drawn to a viewport. You can use the [Viewport](class_viewport#class-viewport) attached to the [SceneTree](class_scenetree#class-scenetree) or you can create one yourself with [viewport\_create](#class-visualserver-method-viewport-create). When using a custom scenario or canvas, the scenario or canvas needs to be attached to the viewport using [viewport\_set\_scenario](#class-visualserver-method-viewport-set-scenario) or [viewport\_attach\_canvas](#class-visualserver-method-viewport-attach-canvas).
In 3D, all visual objects must be associated with a scenario. The scenario is a visual representation of the world. If accessing the visual server from a running game, the scenario can be accessed from the scene tree from any [Spatial](class_spatial#class-spatial) node with [Spatial.get\_world](class_spatial#class-spatial-method-get-world). Otherwise, a scenario can be created with [scenario\_create](#class-visualserver-method-scenario-create).
Similarly, in 2D, a canvas is needed to draw all canvas items.
In 3D, all visible objects are comprised of a resource and an instance. A resource can be a mesh, a particle system, a light, or any other 3D object. In order to be visible resources must be attached to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base). The instance must also be attached to the scenario using [instance\_set\_scenario](#class-visualserver-method-instance-set-scenario) in order to be visible.
In 2D, all visible objects are some form of canvas item. In order to be visible, a canvas item needs to be the child of a canvas attached to a viewport, or it needs to be the child of another canvas item that is eventually attached to the canvas.
Tutorials
---------
* [Optimization using Servers](https://docs.godotengine.org/en/3.5/tutorials/performance/using_servers.html)
Properties
----------
| | |
| --- | --- |
| [bool](class_bool#class-bool) | [render\_loop\_enabled](#class-visualserver-property-render-loop-enabled) |
Methods
-------
| | |
| --- | --- |
| void | [black\_bars\_set\_images](#class-visualserver-method-black-bars-set-images) **(** [RID](class_rid#class-rid) left, [RID](class_rid#class-rid) top, [RID](class_rid#class-rid) right, [RID](class_rid#class-rid) bottom **)** |
| void | [black\_bars\_set\_margins](#class-visualserver-method-black-bars-set-margins) **(** [int](class_int#class-int) left, [int](class_int#class-int) top, [int](class_int#class-int) right, [int](class_int#class-int) bottom **)** |
| [RID](class_rid#class-rid) | [camera\_create](#class-visualserver-method-camera-create) **(** **)** |
| void | [camera\_set\_cull\_mask](#class-visualserver-method-camera-set-cull-mask) **(** [RID](class_rid#class-rid) camera, [int](class_int#class-int) layers **)** |
| void | [camera\_set\_environment](#class-visualserver-method-camera-set-environment) **(** [RID](class_rid#class-rid) camera, [RID](class_rid#class-rid) env **)** |
| void | [camera\_set\_frustum](#class-visualserver-method-camera-set-frustum) **(** [RID](class_rid#class-rid) camera, [float](class_float#class-float) size, [Vector2](class_vector2#class-vector2) offset, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far **)** |
| void | [camera\_set\_orthogonal](#class-visualserver-method-camera-set-orthogonal) **(** [RID](class_rid#class-rid) camera, [float](class_float#class-float) size, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far **)** |
| void | [camera\_set\_perspective](#class-visualserver-method-camera-set-perspective) **(** [RID](class_rid#class-rid) camera, [float](class_float#class-float) fovy\_degrees, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far **)** |
| void | [camera\_set\_transform](#class-visualserver-method-camera-set-transform) **(** [RID](class_rid#class-rid) camera, [Transform](class_transform#class-transform) transform **)** |
| void | [camera\_set\_use\_vertical\_aspect](#class-visualserver-method-camera-set-use-vertical-aspect) **(** [RID](class_rid#class-rid) camera, [bool](class_bool#class-bool) enable **)** |
| [RID](class_rid#class-rid) | [canvas\_create](#class-visualserver-method-canvas-create) **(** **)** |
| void | [canvas\_item\_add\_circle](#class-visualserver-method-canvas-item-add-circle) **(** [RID](class_rid#class-rid) item, [Vector2](class_vector2#class-vector2) pos, [float](class_float#class-float) radius, [Color](class_color#class-color) color **)** |
| void | [canvas\_item\_add\_clip\_ignore](#class-visualserver-method-canvas-item-add-clip-ignore) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) ignore **)** |
| void | [canvas\_item\_add\_line](#class-visualserver-method-canvas-item-add-line) **(** [RID](class_rid#class-rid) item, [Vector2](class_vector2#class-vector2) from, [Vector2](class_vector2#class-vector2) to, [Color](class_color#class-color) color, [float](class_float#class-float) width=1.0, [bool](class_bool#class-bool) antialiased=false **)** |
| void | [canvas\_item\_add\_mesh](#class-visualserver-method-canvas-item-add-mesh) **(** [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) mesh, [Transform2D](class_transform2d#class-transform2d) transform=Transform2D( 1, 0, 0, 1, 0, 0 ), [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map **)** |
| void | [canvas\_item\_add\_multimesh](#class-visualserver-method-canvas-item-add-multimesh) **(** [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) mesh, [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map **)** |
| void | [canvas\_item\_add\_nine\_patch](#class-visualserver-method-canvas-item-add-nine-patch) **(** [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [Rect2](class_rect2#class-rect2) source, [RID](class_rid#class-rid) texture, [Vector2](class_vector2#class-vector2) topleft, [Vector2](class_vector2#class-vector2) bottomright, [NinePatchAxisMode](#enum-visualserver-ninepatchaxismode) x\_axis\_mode=0, [NinePatchAxisMode](#enum-visualserver-ninepatchaxismode) y\_axis\_mode=0, [bool](class_bool#class-bool) draw\_center=true, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [RID](class_rid#class-rid) normal\_map **)** |
| void | [canvas\_item\_add\_particles](#class-visualserver-method-canvas-item-add-particles) **(** [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) particles, [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map **)** |
| void | [canvas\_item\_add\_polygon](#class-visualserver-method-canvas-item-add-polygon) **(** [RID](class_rid#class-rid) item, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [PoolVector2Array](class_poolvector2array#class-poolvector2array) uvs=PoolVector2Array( ), [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map, [bool](class_bool#class-bool) antialiased=false **)** |
| void | [canvas\_item\_add\_polyline](#class-visualserver-method-canvas-item-add-polyline) **(** [RID](class_rid#class-rid) item, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [float](class_float#class-float) width=1.0, [bool](class_bool#class-bool) antialiased=false **)** |
| void | [canvas\_item\_add\_primitive](#class-visualserver-method-canvas-item-add-primitive) **(** [RID](class_rid#class-rid) item, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [PoolVector2Array](class_poolvector2array#class-poolvector2array) uvs, [RID](class_rid#class-rid) texture, [float](class_float#class-float) width=1.0, [RID](class_rid#class-rid) normal\_map **)** |
| void | [canvas\_item\_add\_rect](#class-visualserver-method-canvas-item-add-rect) **(** [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [Color](class_color#class-color) color **)** |
| void | [canvas\_item\_add\_set\_transform](#class-visualserver-method-canvas-item-add-set-transform) **(** [RID](class_rid#class-rid) item, [Transform2D](class_transform2d#class-transform2d) transform **)** |
| void | [canvas\_item\_add\_texture\_rect](#class-visualserver-method-canvas-item-add-texture-rect) **(** [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [RID](class_rid#class-rid) texture, [bool](class_bool#class-bool) tile=false, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [RID](class_rid#class-rid) normal\_map **)** |
| void | [canvas\_item\_add\_texture\_rect\_region](#class-visualserver-method-canvas-item-add-texture-rect-region) **(** [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [RID](class_rid#class-rid) texture, [Rect2](class_rect2#class-rect2) src\_rect, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [RID](class_rid#class-rid) normal\_map, [bool](class_bool#class-bool) clip\_uv=true **)** |
| void | [canvas\_item\_add\_triangle\_array](#class-visualserver-method-canvas-item-add-triangle-array) **(** [RID](class_rid#class-rid) item, [PoolIntArray](class_poolintarray#class-poolintarray) indices, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [PoolVector2Array](class_poolvector2array#class-poolvector2array) uvs=PoolVector2Array( ), [PoolIntArray](class_poolintarray#class-poolintarray) bones=PoolIntArray( ), [PoolRealArray](class_poolrealarray#class-poolrealarray) weights=PoolRealArray( ), [RID](class_rid#class-rid) texture, [int](class_int#class-int) count=-1, [RID](class_rid#class-rid) normal\_map, [bool](class_bool#class-bool) antialiased=false, [bool](class_bool#class-bool) antialiasing\_use\_indices=false **)** |
| void | [canvas\_item\_clear](#class-visualserver-method-canvas-item-clear) **(** [RID](class_rid#class-rid) item **)** |
| [RID](class_rid#class-rid) | [canvas\_item\_create](#class-visualserver-method-canvas-item-create) **(** **)** |
| void | [canvas\_item\_set\_clip](#class-visualserver-method-canvas-item-set-clip) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) clip **)** |
| void | [canvas\_item\_set\_copy\_to\_backbuffer](#class-visualserver-method-canvas-item-set-copy-to-backbuffer) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled, [Rect2](class_rect2#class-rect2) rect **)** |
| void | [canvas\_item\_set\_custom\_rect](#class-visualserver-method-canvas-item-set-custom-rect) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) use\_custom\_rect, [Rect2](class_rect2#class-rect2) rect=Rect2( 0, 0, 0, 0 ) **)** |
| void | [canvas\_item\_set\_distance\_field\_mode](#class-visualserver-method-canvas-item-set-distance-field-mode) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_item\_set\_draw\_behind\_parent](#class-visualserver-method-canvas-item-set-draw-behind-parent) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_item\_set\_draw\_index](#class-visualserver-method-canvas-item-set-draw-index) **(** [RID](class_rid#class-rid) item, [int](class_int#class-int) index **)** |
| void | [canvas\_item\_set\_light\_mask](#class-visualserver-method-canvas-item-set-light-mask) **(** [RID](class_rid#class-rid) item, [int](class_int#class-int) mask **)** |
| void | [canvas\_item\_set\_material](#class-visualserver-method-canvas-item-set-material) **(** [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) material **)** |
| void | [canvas\_item\_set\_modulate](#class-visualserver-method-canvas-item-set-modulate) **(** [RID](class_rid#class-rid) item, [Color](class_color#class-color) color **)** |
| void | [canvas\_item\_set\_parent](#class-visualserver-method-canvas-item-set-parent) **(** [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) parent **)** |
| void | [canvas\_item\_set\_self\_modulate](#class-visualserver-method-canvas-item-set-self-modulate) **(** [RID](class_rid#class-rid) item, [Color](class_color#class-color) color **)** |
| void | [canvas\_item\_set\_sort\_children\_by\_y](#class-visualserver-method-canvas-item-set-sort-children-by-y) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_item\_set\_transform](#class-visualserver-method-canvas-item-set-transform) **(** [RID](class_rid#class-rid) item, [Transform2D](class_transform2d#class-transform2d) transform **)** |
| void | [canvas\_item\_set\_use\_parent\_material](#class-visualserver-method-canvas-item-set-use-parent-material) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_item\_set\_visible](#class-visualserver-method-canvas-item-set-visible) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) visible **)** |
| void | [canvas\_item\_set\_z\_as\_relative\_to\_parent](#class-visualserver-method-canvas-item-set-z-as-relative-to-parent) **(** [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_item\_set\_z\_index](#class-visualserver-method-canvas-item-set-z-index) **(** [RID](class_rid#class-rid) item, [int](class_int#class-int) z\_index **)** |
| void | [canvas\_light\_attach\_to\_canvas](#class-visualserver-method-canvas-light-attach-to-canvas) **(** [RID](class_rid#class-rid) light, [RID](class_rid#class-rid) canvas **)** |
| [RID](class_rid#class-rid) | [canvas\_light\_create](#class-visualserver-method-canvas-light-create) **(** **)** |
| void | [canvas\_light\_occluder\_attach\_to\_canvas](#class-visualserver-method-canvas-light-occluder-attach-to-canvas) **(** [RID](class_rid#class-rid) occluder, [RID](class_rid#class-rid) canvas **)** |
| [RID](class_rid#class-rid) | [canvas\_light\_occluder\_create](#class-visualserver-method-canvas-light-occluder-create) **(** **)** |
| void | [canvas\_light\_occluder\_set\_enabled](#class-visualserver-method-canvas-light-occluder-set-enabled) **(** [RID](class_rid#class-rid) occluder, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_light\_occluder\_set\_light\_mask](#class-visualserver-method-canvas-light-occluder-set-light-mask) **(** [RID](class_rid#class-rid) occluder, [int](class_int#class-int) mask **)** |
| void | [canvas\_light\_occluder\_set\_polygon](#class-visualserver-method-canvas-light-occluder-set-polygon) **(** [RID](class_rid#class-rid) occluder, [RID](class_rid#class-rid) polygon **)** |
| void | [canvas\_light\_occluder\_set\_transform](#class-visualserver-method-canvas-light-occluder-set-transform) **(** [RID](class_rid#class-rid) occluder, [Transform2D](class_transform2d#class-transform2d) transform **)** |
| void | [canvas\_light\_set\_color](#class-visualserver-method-canvas-light-set-color) **(** [RID](class_rid#class-rid) light, [Color](class_color#class-color) color **)** |
| void | [canvas\_light\_set\_enabled](#class-visualserver-method-canvas-light-set-enabled) **(** [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_light\_set\_energy](#class-visualserver-method-canvas-light-set-energy) **(** [RID](class_rid#class-rid) light, [float](class_float#class-float) energy **)** |
| void | [canvas\_light\_set\_height](#class-visualserver-method-canvas-light-set-height) **(** [RID](class_rid#class-rid) light, [float](class_float#class-float) height **)** |
| void | [canvas\_light\_set\_item\_cull\_mask](#class-visualserver-method-canvas-light-set-item-cull-mask) **(** [RID](class_rid#class-rid) light, [int](class_int#class-int) mask **)** |
| void | [canvas\_light\_set\_item\_shadow\_cull\_mask](#class-visualserver-method-canvas-light-set-item-shadow-cull-mask) **(** [RID](class_rid#class-rid) light, [int](class_int#class-int) mask **)** |
| void | [canvas\_light\_set\_layer\_range](#class-visualserver-method-canvas-light-set-layer-range) **(** [RID](class_rid#class-rid) light, [int](class_int#class-int) min\_layer, [int](class_int#class-int) max\_layer **)** |
| void | [canvas\_light\_set\_mode](#class-visualserver-method-canvas-light-set-mode) **(** [RID](class_rid#class-rid) light, [CanvasLightMode](#enum-visualserver-canvaslightmode) mode **)** |
| void | [canvas\_light\_set\_scale](#class-visualserver-method-canvas-light-set-scale) **(** [RID](class_rid#class-rid) light, [float](class_float#class-float) scale **)** |
| void | [canvas\_light\_set\_shadow\_buffer\_size](#class-visualserver-method-canvas-light-set-shadow-buffer-size) **(** [RID](class_rid#class-rid) light, [int](class_int#class-int) size **)** |
| void | [canvas\_light\_set\_shadow\_color](#class-visualserver-method-canvas-light-set-shadow-color) **(** [RID](class_rid#class-rid) light, [Color](class_color#class-color) color **)** |
| void | [canvas\_light\_set\_shadow\_enabled](#class-visualserver-method-canvas-light-set-shadow-enabled) **(** [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled **)** |
| void | [canvas\_light\_set\_shadow\_filter](#class-visualserver-method-canvas-light-set-shadow-filter) **(** [RID](class_rid#class-rid) light, [CanvasLightShadowFilter](#enum-visualserver-canvaslightshadowfilter) filter **)** |
| void | [canvas\_light\_set\_shadow\_gradient\_length](#class-visualserver-method-canvas-light-set-shadow-gradient-length) **(** [RID](class_rid#class-rid) light, [float](class_float#class-float) length **)** |
| void | [canvas\_light\_set\_shadow\_smooth](#class-visualserver-method-canvas-light-set-shadow-smooth) **(** [RID](class_rid#class-rid) light, [float](class_float#class-float) smooth **)** |
| void | [canvas\_light\_set\_texture](#class-visualserver-method-canvas-light-set-texture) **(** [RID](class_rid#class-rid) light, [RID](class_rid#class-rid) texture **)** |
| void | [canvas\_light\_set\_texture\_offset](#class-visualserver-method-canvas-light-set-texture-offset) **(** [RID](class_rid#class-rid) light, [Vector2](class_vector2#class-vector2) offset **)** |
| void | [canvas\_light\_set\_transform](#class-visualserver-method-canvas-light-set-transform) **(** [RID](class_rid#class-rid) light, [Transform2D](class_transform2d#class-transform2d) transform **)** |
| void | [canvas\_light\_set\_z\_range](#class-visualserver-method-canvas-light-set-z-range) **(** [RID](class_rid#class-rid) light, [int](class_int#class-int) min\_z, [int](class_int#class-int) max\_z **)** |
| [RID](class_rid#class-rid) | [canvas\_occluder\_polygon\_create](#class-visualserver-method-canvas-occluder-polygon-create) **(** **)** |
| void | [canvas\_occluder\_polygon\_set\_cull\_mode](#class-visualserver-method-canvas-occluder-polygon-set-cull-mode) **(** [RID](class_rid#class-rid) occluder\_polygon, [CanvasOccluderPolygonCullMode](#enum-visualserver-canvasoccluderpolygoncullmode) mode **)** |
| void | [canvas\_occluder\_polygon\_set\_shape](#class-visualserver-method-canvas-occluder-polygon-set-shape) **(** [RID](class_rid#class-rid) occluder\_polygon, [PoolVector2Array](class_poolvector2array#class-poolvector2array) shape, [bool](class_bool#class-bool) closed **)** |
| void | [canvas\_occluder\_polygon\_set\_shape\_as\_lines](#class-visualserver-method-canvas-occluder-polygon-set-shape-as-lines) **(** [RID](class_rid#class-rid) occluder\_polygon, [PoolVector2Array](class_poolvector2array#class-poolvector2array) shape **)** |
| void | [canvas\_set\_item\_mirroring](#class-visualserver-method-canvas-set-item-mirroring) **(** [RID](class_rid#class-rid) canvas, [RID](class_rid#class-rid) item, [Vector2](class_vector2#class-vector2) mirroring **)** |
| void | [canvas\_set\_modulate](#class-visualserver-method-canvas-set-modulate) **(** [RID](class_rid#class-rid) canvas, [Color](class_color#class-color) color **)** |
| [RID](class_rid#class-rid) | [directional\_light\_create](#class-visualserver-method-directional-light-create) **(** **)** |
| void | [draw](#class-visualserver-method-draw) **(** [bool](class_bool#class-bool) swap\_buffers=true, [float](class_float#class-float) frame\_step=0.0 **)** |
| [RID](class_rid#class-rid) | [environment\_create](#class-visualserver-method-environment-create) **(** **)** |
| void | [environment\_set\_adjustment](#class-visualserver-method-environment-set-adjustment) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) brightness, [float](class_float#class-float) contrast, [float](class_float#class-float) saturation, [RID](class_rid#class-rid) ramp **)** |
| void | [environment\_set\_ambient\_light](#class-visualserver-method-environment-set-ambient-light) **(** [RID](class_rid#class-rid) env, [Color](class_color#class-color) color, [float](class_float#class-float) energy=1.0, [float](class_float#class-float) sky\_contibution=0.0 **)** |
| void | [environment\_set\_background](#class-visualserver-method-environment-set-background) **(** [RID](class_rid#class-rid) env, [EnvironmentBG](#enum-visualserver-environmentbg) bg **)** |
| void | [environment\_set\_bg\_color](#class-visualserver-method-environment-set-bg-color) **(** [RID](class_rid#class-rid) env, [Color](class_color#class-color) color **)** |
| void | [environment\_set\_bg\_energy](#class-visualserver-method-environment-set-bg-energy) **(** [RID](class_rid#class-rid) env, [float](class_float#class-float) energy **)** |
| void | [environment\_set\_canvas\_max\_layer](#class-visualserver-method-environment-set-canvas-max-layer) **(** [RID](class_rid#class-rid) env, [int](class_int#class-int) max\_layer **)** |
| void | [environment\_set\_dof\_blur\_far](#class-visualserver-method-environment-set-dof-blur-far) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) distance, [float](class_float#class-float) transition, [float](class_float#class-float) far\_amount, [EnvironmentDOFBlurQuality](#enum-visualserver-environmentdofblurquality) quality **)** |
| void | [environment\_set\_dof\_blur\_near](#class-visualserver-method-environment-set-dof-blur-near) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) distance, [float](class_float#class-float) transition, [float](class_float#class-float) far\_amount, [EnvironmentDOFBlurQuality](#enum-visualserver-environmentdofblurquality) quality **)** |
| void | [environment\_set\_fog](#class-visualserver-method-environment-set-fog) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [Color](class_color#class-color) color, [Color](class_color#class-color) sun\_color, [float](class_float#class-float) sun\_amount **)** |
| void | [environment\_set\_fog\_depth](#class-visualserver-method-environment-set-fog-depth) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) depth\_begin, [float](class_float#class-float) depth\_end, [float](class_float#class-float) depth\_curve, [bool](class_bool#class-bool) transmit, [float](class_float#class-float) transmit\_curve **)** |
| void | [environment\_set\_fog\_height](#class-visualserver-method-environment-set-fog-height) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) min\_height, [float](class_float#class-float) max\_height, [float](class_float#class-float) height\_curve **)** |
| void | [environment\_set\_glow](#class-visualserver-method-environment-set-glow) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [int](class_int#class-int) level\_flags, [float](class_float#class-float) intensity, [float](class_float#class-float) strength, [float](class_float#class-float) bloom\_threshold, [EnvironmentGlowBlendMode](#enum-visualserver-environmentglowblendmode) blend\_mode, [float](class_float#class-float) hdr\_bleed\_threshold, [float](class_float#class-float) hdr\_bleed\_scale, [float](class_float#class-float) hdr\_luminance\_cap, [bool](class_bool#class-bool) bicubic\_upscale, [bool](class_bool#class-bool) high\_quality **)** |
| void | [environment\_set\_sky](#class-visualserver-method-environment-set-sky) **(** [RID](class_rid#class-rid) env, [RID](class_rid#class-rid) sky **)** |
| void | [environment\_set\_sky\_custom\_fov](#class-visualserver-method-environment-set-sky-custom-fov) **(** [RID](class_rid#class-rid) env, [float](class_float#class-float) scale **)** |
| void | [environment\_set\_sky\_orientation](#class-visualserver-method-environment-set-sky-orientation) **(** [RID](class_rid#class-rid) env, [Basis](class_basis#class-basis) orientation **)** |
| void | [environment\_set\_ssao](#class-visualserver-method-environment-set-ssao) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) radius, [float](class_float#class-float) intensity, [float](class_float#class-float) radius2, [float](class_float#class-float) intensity2, [float](class_float#class-float) bias, [float](class_float#class-float) light\_affect, [float](class_float#class-float) ao\_channel\_affect, [Color](class_color#class-color) color, [EnvironmentSSAOQuality](#enum-visualserver-environmentssaoquality) quality, [EnvironmentSSAOBlur](#enum-visualserver-environmentssaoblur) blur, [float](class_float#class-float) bilateral\_sharpness **)** |
| void | [environment\_set\_ssr](#class-visualserver-method-environment-set-ssr) **(** [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [int](class_int#class-int) max\_steps, [float](class_float#class-float) fade\_in, [float](class_float#class-float) fade\_out, [float](class_float#class-float) depth\_tolerance, [bool](class_bool#class-bool) roughness **)** |
| void | [environment\_set\_tonemap](#class-visualserver-method-environment-set-tonemap) **(** [RID](class_rid#class-rid) env, [EnvironmentToneMapper](#enum-visualserver-environmenttonemapper) tone\_mapper, [float](class_float#class-float) exposure, [float](class_float#class-float) white, [bool](class_bool#class-bool) auto\_exposure, [float](class_float#class-float) min\_luminance, [float](class_float#class-float) max\_luminance, [float](class_float#class-float) auto\_exp\_speed, [float](class_float#class-float) auto\_exp\_grey **)** |
| void | [finish](#class-visualserver-method-finish) **(** **)** |
| void | [force\_draw](#class-visualserver-method-force-draw) **(** [bool](class_bool#class-bool) swap\_buffers=true, [float](class_float#class-float) frame\_step=0.0 **)** |
| void | [force\_sync](#class-visualserver-method-force-sync) **(** **)** |
| void | [free\_rid](#class-visualserver-method-free-rid) **(** [RID](class_rid#class-rid) rid **)** |
| [int](class_int#class-int) | [get\_render\_info](#class-visualserver-method-get-render-info) **(** [RenderInfo](#enum-visualserver-renderinfo) info **)** |
| [RID](class_rid#class-rid) | [get\_test\_cube](#class-visualserver-method-get-test-cube) **(** **)** |
| [RID](class_rid#class-rid) | [get\_test\_texture](#class-visualserver-method-get-test-texture) **(** **)** |
| [String](class_string#class-string) | [get\_video\_adapter\_name](#class-visualserver-method-get-video-adapter-name) **(** **)** const |
| [String](class_string#class-string) | [get\_video\_adapter\_vendor](#class-visualserver-method-get-video-adapter-vendor) **(** **)** const |
| [RID](class_rid#class-rid) | [get\_white\_texture](#class-visualserver-method-get-white-texture) **(** **)** |
| [RID](class_rid#class-rid) | [gi\_probe\_create](#class-visualserver-method-gi-probe-create) **(** **)** |
| [float](class_float#class-float) | [gi\_probe\_get\_bias](#class-visualserver-method-gi-probe-get-bias) **(** [RID](class_rid#class-rid) probe **)** const |
| [AABB](class_aabb#class-aabb) | [gi\_probe\_get\_bounds](#class-visualserver-method-gi-probe-get-bounds) **(** [RID](class_rid#class-rid) probe **)** const |
| [float](class_float#class-float) | [gi\_probe\_get\_cell\_size](#class-visualserver-method-gi-probe-get-cell-size) **(** [RID](class_rid#class-rid) probe **)** const |
| [PoolIntArray](class_poolintarray#class-poolintarray) | [gi\_probe\_get\_dynamic\_data](#class-visualserver-method-gi-probe-get-dynamic-data) **(** [RID](class_rid#class-rid) probe **)** const |
| [int](class_int#class-int) | [gi\_probe\_get\_dynamic\_range](#class-visualserver-method-gi-probe-get-dynamic-range) **(** [RID](class_rid#class-rid) probe **)** const |
| [float](class_float#class-float) | [gi\_probe\_get\_energy](#class-visualserver-method-gi-probe-get-energy) **(** [RID](class_rid#class-rid) probe **)** const |
| [float](class_float#class-float) | [gi\_probe\_get\_normal\_bias](#class-visualserver-method-gi-probe-get-normal-bias) **(** [RID](class_rid#class-rid) probe **)** const |
| [float](class_float#class-float) | [gi\_probe\_get\_propagation](#class-visualserver-method-gi-probe-get-propagation) **(** [RID](class_rid#class-rid) probe **)** const |
| [Transform](class_transform#class-transform) | [gi\_probe\_get\_to\_cell\_xform](#class-visualserver-method-gi-probe-get-to-cell-xform) **(** [RID](class_rid#class-rid) probe **)** const |
| [bool](class_bool#class-bool) | [gi\_probe\_is\_compressed](#class-visualserver-method-gi-probe-is-compressed) **(** [RID](class_rid#class-rid) probe **)** const |
| [bool](class_bool#class-bool) | [gi\_probe\_is\_interior](#class-visualserver-method-gi-probe-is-interior) **(** [RID](class_rid#class-rid) probe **)** const |
| void | [gi\_probe\_set\_bias](#class-visualserver-method-gi-probe-set-bias) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) bias **)** |
| void | [gi\_probe\_set\_bounds](#class-visualserver-method-gi-probe-set-bounds) **(** [RID](class_rid#class-rid) probe, [AABB](class_aabb#class-aabb) bounds **)** |
| void | [gi\_probe\_set\_cell\_size](#class-visualserver-method-gi-probe-set-cell-size) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) range **)** |
| void | [gi\_probe\_set\_compress](#class-visualserver-method-gi-probe-set-compress) **(** [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable **)** |
| void | [gi\_probe\_set\_dynamic\_data](#class-visualserver-method-gi-probe-set-dynamic-data) **(** [RID](class_rid#class-rid) probe, [PoolIntArray](class_poolintarray#class-poolintarray) data **)** |
| void | [gi\_probe\_set\_dynamic\_range](#class-visualserver-method-gi-probe-set-dynamic-range) **(** [RID](class_rid#class-rid) probe, [int](class_int#class-int) range **)** |
| void | [gi\_probe\_set\_energy](#class-visualserver-method-gi-probe-set-energy) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) energy **)** |
| void | [gi\_probe\_set\_interior](#class-visualserver-method-gi-probe-set-interior) **(** [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable **)** |
| void | [gi\_probe\_set\_normal\_bias](#class-visualserver-method-gi-probe-set-normal-bias) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) bias **)** |
| void | [gi\_probe\_set\_propagation](#class-visualserver-method-gi-probe-set-propagation) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) propagation **)** |
| void | [gi\_probe\_set\_to\_cell\_xform](#class-visualserver-method-gi-probe-set-to-cell-xform) **(** [RID](class_rid#class-rid) probe, [Transform](class_transform#class-transform) xform **)** |
| [bool](class_bool#class-bool) | [has\_changed](#class-visualserver-method-has-changed) **(** [ChangedPriority](#enum-visualserver-changedpriority) queried\_priority=0 **)** const |
| [bool](class_bool#class-bool) | [has\_feature](#class-visualserver-method-has-feature) **(** [Features](#enum-visualserver-features) feature **)** const |
| [bool](class_bool#class-bool) | [has\_os\_feature](#class-visualserver-method-has-os-feature) **(** [String](class_string#class-string) feature **)** const |
| void | [immediate\_begin](#class-visualserver-method-immediate-begin) **(** [RID](class_rid#class-rid) immediate, [PrimitiveType](#enum-visualserver-primitivetype) primitive, [RID](class_rid#class-rid) texture **)** |
| void | [immediate\_clear](#class-visualserver-method-immediate-clear) **(** [RID](class_rid#class-rid) immediate **)** |
| void | [immediate\_color](#class-visualserver-method-immediate-color) **(** [RID](class_rid#class-rid) immediate, [Color](class_color#class-color) color **)** |
| [RID](class_rid#class-rid) | [immediate\_create](#class-visualserver-method-immediate-create) **(** **)** |
| void | [immediate\_end](#class-visualserver-method-immediate-end) **(** [RID](class_rid#class-rid) immediate **)** |
| [RID](class_rid#class-rid) | [immediate\_get\_material](#class-visualserver-method-immediate-get-material) **(** [RID](class_rid#class-rid) immediate **)** const |
| void | [immediate\_normal](#class-visualserver-method-immediate-normal) **(** [RID](class_rid#class-rid) immediate, [Vector3](class_vector3#class-vector3) normal **)** |
| void | [immediate\_set\_material](#class-visualserver-method-immediate-set-material) **(** [RID](class_rid#class-rid) immediate, [RID](class_rid#class-rid) material **)** |
| void | [immediate\_tangent](#class-visualserver-method-immediate-tangent) **(** [RID](class_rid#class-rid) immediate, [Plane](class_plane#class-plane) tangent **)** |
| void | [immediate\_uv](#class-visualserver-method-immediate-uv) **(** [RID](class_rid#class-rid) immediate, [Vector2](class_vector2#class-vector2) tex\_uv **)** |
| void | [immediate\_uv2](#class-visualserver-method-immediate-uv2) **(** [RID](class_rid#class-rid) immediate, [Vector2](class_vector2#class-vector2) tex\_uv **)** |
| void | [immediate\_vertex](#class-visualserver-method-immediate-vertex) **(** [RID](class_rid#class-rid) immediate, [Vector3](class_vector3#class-vector3) vertex **)** |
| void | [immediate\_vertex\_2d](#class-visualserver-method-immediate-vertex-2d) **(** [RID](class_rid#class-rid) immediate, [Vector2](class_vector2#class-vector2) vertex **)** |
| void | [init](#class-visualserver-method-init) **(** **)** |
| void | [instance\_attach\_object\_instance\_id](#class-visualserver-method-instance-attach-object-instance-id) **(** [RID](class_rid#class-rid) instance, [int](class_int#class-int) id **)** |
| void | [instance\_attach\_skeleton](#class-visualserver-method-instance-attach-skeleton) **(** [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) skeleton **)** |
| [RID](class_rid#class-rid) | [instance\_create](#class-visualserver-method-instance-create) **(** **)** |
| [RID](class_rid#class-rid) | [instance\_create2](#class-visualserver-method-instance-create2) **(** [RID](class_rid#class-rid) base, [RID](class_rid#class-rid) scenario **)** |
| void | [instance\_geometry\_set\_as\_instance\_lod](#class-visualserver-method-instance-geometry-set-as-instance-lod) **(** [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) as\_lod\_of\_instance **)** |
| void | [instance\_geometry\_set\_cast\_shadows\_setting](#class-visualserver-method-instance-geometry-set-cast-shadows-setting) **(** [RID](class_rid#class-rid) instance, [ShadowCastingSetting](#enum-visualserver-shadowcastingsetting) shadow\_casting\_setting **)** |
| void | [instance\_geometry\_set\_draw\_range](#class-visualserver-method-instance-geometry-set-draw-range) **(** [RID](class_rid#class-rid) instance, [float](class_float#class-float) min, [float](class_float#class-float) max, [float](class_float#class-float) min\_margin, [float](class_float#class-float) max\_margin **)** |
| void | [instance\_geometry\_set\_flag](#class-visualserver-method-instance-geometry-set-flag) **(** [RID](class_rid#class-rid) instance, [InstanceFlags](#enum-visualserver-instanceflags) flag, [bool](class_bool#class-bool) enabled **)** |
| void | [instance\_geometry\_set\_material\_overlay](#class-visualserver-method-instance-geometry-set-material-overlay) **(** [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) material **)** |
| void | [instance\_geometry\_set\_material\_override](#class-visualserver-method-instance-geometry-set-material-override) **(** [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) material **)** |
| void | [instance\_set\_base](#class-visualserver-method-instance-set-base) **(** [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) base **)** |
| void | [instance\_set\_blend\_shape\_weight](#class-visualserver-method-instance-set-blend-shape-weight) **(** [RID](class_rid#class-rid) instance, [int](class_int#class-int) shape, [float](class_float#class-float) weight **)** |
| void | [instance\_set\_custom\_aabb](#class-visualserver-method-instance-set-custom-aabb) **(** [RID](class_rid#class-rid) instance, [AABB](class_aabb#class-aabb) aabb **)** |
| void | [instance\_set\_exterior](#class-visualserver-method-instance-set-exterior) **(** [RID](class_rid#class-rid) instance, [bool](class_bool#class-bool) enabled **)** |
| void | [instance\_set\_extra\_visibility\_margin](#class-visualserver-method-instance-set-extra-visibility-margin) **(** [RID](class_rid#class-rid) instance, [float](class_float#class-float) margin **)** |
| void | [instance\_set\_layer\_mask](#class-visualserver-method-instance-set-layer-mask) **(** [RID](class_rid#class-rid) instance, [int](class_int#class-int) mask **)** |
| void | [instance\_set\_scenario](#class-visualserver-method-instance-set-scenario) **(** [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) scenario **)** |
| void | [instance\_set\_surface\_material](#class-visualserver-method-instance-set-surface-material) **(** [RID](class_rid#class-rid) instance, [int](class_int#class-int) surface, [RID](class_rid#class-rid) material **)** |
| void | [instance\_set\_transform](#class-visualserver-method-instance-set-transform) **(** [RID](class_rid#class-rid) instance, [Transform](class_transform#class-transform) transform **)** |
| void | [instance\_set\_use\_lightmap](#class-visualserver-method-instance-set-use-lightmap) **(** [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) lightmap\_instance, [RID](class_rid#class-rid) lightmap, [int](class_int#class-int) lightmap\_slice=-1, [Rect2](class_rect2#class-rect2) lightmap\_uv\_rect=Rect2( 0, 0, 1, 1 ) **)** |
| void | [instance\_set\_visible](#class-visualserver-method-instance-set-visible) **(** [RID](class_rid#class-rid) instance, [bool](class_bool#class-bool) visible **)** |
| [Array](class_array#class-array) | [instances\_cull\_aabb](#class-visualserver-method-instances-cull-aabb) **(** [AABB](class_aabb#class-aabb) aabb, [RID](class_rid#class-rid) scenario **)** const |
| [Array](class_array#class-array) | [instances\_cull\_convex](#class-visualserver-method-instances-cull-convex) **(** [Array](class_array#class-array) convex, [RID](class_rid#class-rid) scenario **)** const |
| [Array](class_array#class-array) | [instances\_cull\_ray](#class-visualserver-method-instances-cull-ray) **(** [Vector3](class_vector3#class-vector3) from, [Vector3](class_vector3#class-vector3) to, [RID](class_rid#class-rid) scenario **)** const |
| void | [light\_directional\_set\_blend\_splits](#class-visualserver-method-light-directional-set-blend-splits) **(** [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enable **)** |
| void | [light\_directional\_set\_shadow\_depth\_range\_mode](#class-visualserver-method-light-directional-set-shadow-depth-range-mode) **(** [RID](class_rid#class-rid) light, [LightDirectionalShadowDepthRangeMode](#enum-visualserver-lightdirectionalshadowdepthrangemode) range\_mode **)** |
| void | [light\_directional\_set\_shadow\_mode](#class-visualserver-method-light-directional-set-shadow-mode) **(** [RID](class_rid#class-rid) light, [LightDirectionalShadowMode](#enum-visualserver-lightdirectionalshadowmode) mode **)** |
| void | [light\_omni\_set\_shadow\_detail](#class-visualserver-method-light-omni-set-shadow-detail) **(** [RID](class_rid#class-rid) light, [LightOmniShadowDetail](#enum-visualserver-lightomnishadowdetail) detail **)** |
| void | [light\_omni\_set\_shadow\_mode](#class-visualserver-method-light-omni-set-shadow-mode) **(** [RID](class_rid#class-rid) light, [LightOmniShadowMode](#enum-visualserver-lightomnishadowmode) mode **)** |
| void | [light\_set\_bake\_mode](#class-visualserver-method-light-set-bake-mode) **(** [RID](class_rid#class-rid) light, [LightBakeMode](#enum-visualserver-lightbakemode) bake\_mode **)** |
| void | [light\_set\_color](#class-visualserver-method-light-set-color) **(** [RID](class_rid#class-rid) light, [Color](class_color#class-color) color **)** |
| void | [light\_set\_cull\_mask](#class-visualserver-method-light-set-cull-mask) **(** [RID](class_rid#class-rid) light, [int](class_int#class-int) mask **)** |
| void | [light\_set\_negative](#class-visualserver-method-light-set-negative) **(** [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enable **)** |
| void | [light\_set\_param](#class-visualserver-method-light-set-param) **(** [RID](class_rid#class-rid) light, [LightParam](#enum-visualserver-lightparam) param, [float](class_float#class-float) value **)** |
| void | [light\_set\_projector](#class-visualserver-method-light-set-projector) **(** [RID](class_rid#class-rid) light, [RID](class_rid#class-rid) texture **)** |
| void | [light\_set\_reverse\_cull\_face\_mode](#class-visualserver-method-light-set-reverse-cull-face-mode) **(** [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled **)** |
| void | [light\_set\_shadow](#class-visualserver-method-light-set-shadow) **(** [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled **)** |
| void | [light\_set\_shadow\_color](#class-visualserver-method-light-set-shadow-color) **(** [RID](class_rid#class-rid) light, [Color](class_color#class-color) color **)** |
| void | [light\_set\_use\_gi](#class-visualserver-method-light-set-use-gi) **(** [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled **)** |
| [RID](class_rid#class-rid) | [lightmap\_capture\_create](#class-visualserver-method-lightmap-capture-create) **(** **)** |
| [AABB](class_aabb#class-aabb) | [lightmap\_capture\_get\_bounds](#class-visualserver-method-lightmap-capture-get-bounds) **(** [RID](class_rid#class-rid) capture **)** const |
| [float](class_float#class-float) | [lightmap\_capture\_get\_energy](#class-visualserver-method-lightmap-capture-get-energy) **(** [RID](class_rid#class-rid) capture **)** const |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [lightmap\_capture\_get\_octree](#class-visualserver-method-lightmap-capture-get-octree) **(** [RID](class_rid#class-rid) capture **)** const |
| [int](class_int#class-int) | [lightmap\_capture\_get\_octree\_cell\_subdiv](#class-visualserver-method-lightmap-capture-get-octree-cell-subdiv) **(** [RID](class_rid#class-rid) capture **)** const |
| [Transform](class_transform#class-transform) | [lightmap\_capture\_get\_octree\_cell\_transform](#class-visualserver-method-lightmap-capture-get-octree-cell-transform) **(** [RID](class_rid#class-rid) capture **)** const |
| [bool](class_bool#class-bool) | [lightmap\_capture\_is\_interior](#class-visualserver-method-lightmap-capture-is-interior) **(** [RID](class_rid#class-rid) capture **)** const |
| void | [lightmap\_capture\_set\_bounds](#class-visualserver-method-lightmap-capture-set-bounds) **(** [RID](class_rid#class-rid) capture, [AABB](class_aabb#class-aabb) bounds **)** |
| void | [lightmap\_capture\_set\_energy](#class-visualserver-method-lightmap-capture-set-energy) **(** [RID](class_rid#class-rid) capture, [float](class_float#class-float) energy **)** |
| void | [lightmap\_capture\_set\_interior](#class-visualserver-method-lightmap-capture-set-interior) **(** [RID](class_rid#class-rid) capture, [bool](class_bool#class-bool) interior **)** |
| void | [lightmap\_capture\_set\_octree](#class-visualserver-method-lightmap-capture-set-octree) **(** [RID](class_rid#class-rid) capture, [PoolByteArray](class_poolbytearray#class-poolbytearray) octree **)** |
| void | [lightmap\_capture\_set\_octree\_cell\_subdiv](#class-visualserver-method-lightmap-capture-set-octree-cell-subdiv) **(** [RID](class_rid#class-rid) capture, [int](class_int#class-int) subdiv **)** |
| void | [lightmap\_capture\_set\_octree\_cell\_transform](#class-visualserver-method-lightmap-capture-set-octree-cell-transform) **(** [RID](class_rid#class-rid) capture, [Transform](class_transform#class-transform) xform **)** |
| [RID](class_rid#class-rid) | [make\_sphere\_mesh](#class-visualserver-method-make-sphere-mesh) **(** [int](class_int#class-int) latitudes, [int](class_int#class-int) longitudes, [float](class_float#class-float) radius **)** |
| [RID](class_rid#class-rid) | [material\_create](#class-visualserver-method-material-create) **(** **)** |
| [Variant](class_variant#class-variant) | [material\_get\_param](#class-visualserver-method-material-get-param) **(** [RID](class_rid#class-rid) material, [String](class_string#class-string) parameter **)** const |
| [Variant](class_variant#class-variant) | [material\_get\_param\_default](#class-visualserver-method-material-get-param-default) **(** [RID](class_rid#class-rid) material, [String](class_string#class-string) parameter **)** const |
| [RID](class_rid#class-rid) | [material\_get\_shader](#class-visualserver-method-material-get-shader) **(** [RID](class_rid#class-rid) shader\_material **)** const |
| void | [material\_set\_line\_width](#class-visualserver-method-material-set-line-width) **(** [RID](class_rid#class-rid) material, [float](class_float#class-float) width **)** |
| void | [material\_set\_next\_pass](#class-visualserver-method-material-set-next-pass) **(** [RID](class_rid#class-rid) material, [RID](class_rid#class-rid) next\_material **)** |
| void | [material\_set\_param](#class-visualserver-method-material-set-param) **(** [RID](class_rid#class-rid) material, [String](class_string#class-string) parameter, [Variant](class_variant#class-variant) value **)** |
| void | [material\_set\_render\_priority](#class-visualserver-method-material-set-render-priority) **(** [RID](class_rid#class-rid) material, [int](class_int#class-int) priority **)** |
| void | [material\_set\_shader](#class-visualserver-method-material-set-shader) **(** [RID](class_rid#class-rid) shader\_material, [RID](class_rid#class-rid) shader **)** |
| void | [mesh\_add\_surface\_from\_arrays](#class-visualserver-method-mesh-add-surface-from-arrays) **(** [RID](class_rid#class-rid) mesh, [PrimitiveType](#enum-visualserver-primitivetype) primitive, [Array](class_array#class-array) arrays, [Array](class_array#class-array) blend\_shapes=[ ], [int](class_int#class-int) compress\_format=2194432 **)** |
| void | [mesh\_clear](#class-visualserver-method-mesh-clear) **(** [RID](class_rid#class-rid) mesh **)** |
| [RID](class_rid#class-rid) | [mesh\_create](#class-visualserver-method-mesh-create) **(** **)** |
| [int](class_int#class-int) | [mesh\_get\_blend\_shape\_count](#class-visualserver-method-mesh-get-blend-shape-count) **(** [RID](class_rid#class-rid) mesh **)** const |
| [BlendShapeMode](#enum-visualserver-blendshapemode) | [mesh\_get\_blend\_shape\_mode](#class-visualserver-method-mesh-get-blend-shape-mode) **(** [RID](class_rid#class-rid) mesh **)** const |
| [AABB](class_aabb#class-aabb) | [mesh\_get\_custom\_aabb](#class-visualserver-method-mesh-get-custom-aabb) **(** [RID](class_rid#class-rid) mesh **)** const |
| [int](class_int#class-int) | [mesh\_get\_surface\_count](#class-visualserver-method-mesh-get-surface-count) **(** [RID](class_rid#class-rid) mesh **)** const |
| void | [mesh\_remove\_surface](#class-visualserver-method-mesh-remove-surface) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) index **)** |
| void | [mesh\_set\_blend\_shape\_count](#class-visualserver-method-mesh-set-blend-shape-count) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) amount **)** |
| void | [mesh\_set\_blend\_shape\_mode](#class-visualserver-method-mesh-set-blend-shape-mode) **(** [RID](class_rid#class-rid) mesh, [BlendShapeMode](#enum-visualserver-blendshapemode) mode **)** |
| void | [mesh\_set\_custom\_aabb](#class-visualserver-method-mesh-set-custom-aabb) **(** [RID](class_rid#class-rid) mesh, [AABB](class_aabb#class-aabb) aabb **)** |
| [AABB](class_aabb#class-aabb) | [mesh\_surface\_get\_aabb](#class-visualserver-method-mesh-surface-get-aabb) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [mesh\_surface\_get\_array](#class-visualserver-method-mesh-surface-get-array) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [int](class_int#class-int) | [mesh\_surface\_get\_array\_index\_len](#class-visualserver-method-mesh-surface-get-array-index-len) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [int](class_int#class-int) | [mesh\_surface\_get\_array\_len](#class-visualserver-method-mesh-surface-get-array-len) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [Array](class_array#class-array) | [mesh\_surface\_get\_arrays](#class-visualserver-method-mesh-surface-get-arrays) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [Array](class_array#class-array) | [mesh\_surface\_get\_blend\_shape\_arrays](#class-visualserver-method-mesh-surface-get-blend-shape-arrays) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [int](class_int#class-int) | [mesh\_surface\_get\_format](#class-visualserver-method-mesh-surface-get-format) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [int](class_int#class-int) | [mesh\_surface\_get\_format\_offset](#class-visualserver-method-mesh-surface-get-format-offset) **(** [int](class_int#class-int) format, [int](class_int#class-int) vertex\_len, [int](class_int#class-int) index\_len, [int](class_int#class-int) array\_index **)** const |
| [int](class_int#class-int) | [mesh\_surface\_get\_format\_stride](#class-visualserver-method-mesh-surface-get-format-stride) **(** [int](class_int#class-int) format, [int](class_int#class-int) vertex\_len, [int](class_int#class-int) index\_len, [int](class_int#class-int) array\_index **)** const |
| [PoolByteArray](class_poolbytearray#class-poolbytearray) | [mesh\_surface\_get\_index\_array](#class-visualserver-method-mesh-surface-get-index-array) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [RID](class_rid#class-rid) | [mesh\_surface\_get\_material](#class-visualserver-method-mesh-surface-get-material) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [PrimitiveType](#enum-visualserver-primitivetype) | [mesh\_surface\_get\_primitive\_type](#class-visualserver-method-mesh-surface-get-primitive-type) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| [Array](class_array#class-array) | [mesh\_surface\_get\_skeleton\_aabb](#class-visualserver-method-mesh-surface-get-skeleton-aabb) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface **)** const |
| void | [mesh\_surface\_set\_material](#class-visualserver-method-mesh-surface-set-material) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface, [RID](class_rid#class-rid) material **)** |
| void | [mesh\_surface\_update\_region](#class-visualserver-method-mesh-surface-update-region) **(** [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface, [int](class_int#class-int) offset, [PoolByteArray](class_poolbytearray#class-poolbytearray) data **)** |
| void | [multimesh\_allocate](#class-visualserver-method-multimesh-allocate) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) instances, [MultimeshTransformFormat](#enum-visualserver-multimeshtransformformat) transform\_format, [MultimeshColorFormat](#enum-visualserver-multimeshcolorformat) color\_format, [MultimeshCustomDataFormat](#enum-visualserver-multimeshcustomdataformat) custom\_data\_format=0 **)** |
| [RID](class_rid#class-rid) | [multimesh\_create](#class-visualserver-method-multimesh-create) **(** **)** |
| [AABB](class_aabb#class-aabb) | [multimesh\_get\_aabb](#class-visualserver-method-multimesh-get-aabb) **(** [RID](class_rid#class-rid) multimesh **)** const |
| [int](class_int#class-int) | [multimesh\_get\_instance\_count](#class-visualserver-method-multimesh-get-instance-count) **(** [RID](class_rid#class-rid) multimesh **)** const |
| [RID](class_rid#class-rid) | [multimesh\_get\_mesh](#class-visualserver-method-multimesh-get-mesh) **(** [RID](class_rid#class-rid) multimesh **)** const |
| [int](class_int#class-int) | [multimesh\_get\_visible\_instances](#class-visualserver-method-multimesh-get-visible-instances) **(** [RID](class_rid#class-rid) multimesh **)** const |
| [Color](class_color#class-color) | [multimesh\_instance\_get\_color](#class-visualserver-method-multimesh-instance-get-color) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index **)** const |
| [Color](class_color#class-color) | [multimesh\_instance\_get\_custom\_data](#class-visualserver-method-multimesh-instance-get-custom-data) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index **)** const |
| [Transform](class_transform#class-transform) | [multimesh\_instance\_get\_transform](#class-visualserver-method-multimesh-instance-get-transform) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index **)** const |
| [Transform2D](class_transform2d#class-transform2d) | [multimesh\_instance\_get\_transform\_2d](#class-visualserver-method-multimesh-instance-get-transform-2d) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index **)** const |
| void | [multimesh\_instance\_set\_color](#class-visualserver-method-multimesh-instance-set-color) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Color](class_color#class-color) color **)** |
| void | [multimesh\_instance\_set\_custom\_data](#class-visualserver-method-multimesh-instance-set-custom-data) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Color](class_color#class-color) custom\_data **)** |
| void | [multimesh\_instance\_set\_transform](#class-visualserver-method-multimesh-instance-set-transform) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Transform](class_transform#class-transform) transform **)** |
| void | [multimesh\_instance\_set\_transform\_2d](#class-visualserver-method-multimesh-instance-set-transform-2d) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Transform2D](class_transform2d#class-transform2d) transform **)** |
| void | [multimesh\_set\_as\_bulk\_array](#class-visualserver-method-multimesh-set-as-bulk-array) **(** [RID](class_rid#class-rid) multimesh, [PoolRealArray](class_poolrealarray#class-poolrealarray) array **)** |
| void | [multimesh\_set\_mesh](#class-visualserver-method-multimesh-set-mesh) **(** [RID](class_rid#class-rid) multimesh, [RID](class_rid#class-rid) mesh **)** |
| void | [multimesh\_set\_visible\_instances](#class-visualserver-method-multimesh-set-visible-instances) **(** [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) visible **)** |
| [RID](class_rid#class-rid) | [omni\_light\_create](#class-visualserver-method-omni-light-create) **(** **)** |
| [RID](class_rid#class-rid) | [particles\_create](#class-visualserver-method-particles-create) **(** **)** |
| [AABB](class_aabb#class-aabb) | [particles\_get\_current\_aabb](#class-visualserver-method-particles-get-current-aabb) **(** [RID](class_rid#class-rid) particles **)** |
| [bool](class_bool#class-bool) | [particles\_get\_emitting](#class-visualserver-method-particles-get-emitting) **(** [RID](class_rid#class-rid) particles **)** |
| [bool](class_bool#class-bool) | [particles\_is\_inactive](#class-visualserver-method-particles-is-inactive) **(** [RID](class_rid#class-rid) particles **)** |
| void | [particles\_request\_process](#class-visualserver-method-particles-request-process) **(** [RID](class_rid#class-rid) particles **)** |
| void | [particles\_restart](#class-visualserver-method-particles-restart) **(** [RID](class_rid#class-rid) particles **)** |
| void | [particles\_set\_amount](#class-visualserver-method-particles-set-amount) **(** [RID](class_rid#class-rid) particles, [int](class_int#class-int) amount **)** |
| void | [particles\_set\_custom\_aabb](#class-visualserver-method-particles-set-custom-aabb) **(** [RID](class_rid#class-rid) particles, [AABB](class_aabb#class-aabb) aabb **)** |
| void | [particles\_set\_draw\_order](#class-visualserver-method-particles-set-draw-order) **(** [RID](class_rid#class-rid) particles, [ParticlesDrawOrder](#enum-visualserver-particlesdraworder) order **)** |
| void | [particles\_set\_draw\_pass\_mesh](#class-visualserver-method-particles-set-draw-pass-mesh) **(** [RID](class_rid#class-rid) particles, [int](class_int#class-int) pass, [RID](class_rid#class-rid) mesh **)** |
| void | [particles\_set\_draw\_passes](#class-visualserver-method-particles-set-draw-passes) **(** [RID](class_rid#class-rid) particles, [int](class_int#class-int) count **)** |
| void | [particles\_set\_emission\_transform](#class-visualserver-method-particles-set-emission-transform) **(** [RID](class_rid#class-rid) particles, [Transform](class_transform#class-transform) transform **)** |
| void | [particles\_set\_emitting](#class-visualserver-method-particles-set-emitting) **(** [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) emitting **)** |
| void | [particles\_set\_explosiveness\_ratio](#class-visualserver-method-particles-set-explosiveness-ratio) **(** [RID](class_rid#class-rid) particles, [float](class_float#class-float) ratio **)** |
| void | [particles\_set\_fixed\_fps](#class-visualserver-method-particles-set-fixed-fps) **(** [RID](class_rid#class-rid) particles, [int](class_int#class-int) fps **)** |
| void | [particles\_set\_fractional\_delta](#class-visualserver-method-particles-set-fractional-delta) **(** [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) enable **)** |
| void | [particles\_set\_lifetime](#class-visualserver-method-particles-set-lifetime) **(** [RID](class_rid#class-rid) particles, [float](class_float#class-float) lifetime **)** |
| void | [particles\_set\_one\_shot](#class-visualserver-method-particles-set-one-shot) **(** [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) one\_shot **)** |
| void | [particles\_set\_pre\_process\_time](#class-visualserver-method-particles-set-pre-process-time) **(** [RID](class_rid#class-rid) particles, [float](class_float#class-float) time **)** |
| void | [particles\_set\_process\_material](#class-visualserver-method-particles-set-process-material) **(** [RID](class_rid#class-rid) particles, [RID](class_rid#class-rid) material **)** |
| void | [particles\_set\_randomness\_ratio](#class-visualserver-method-particles-set-randomness-ratio) **(** [RID](class_rid#class-rid) particles, [float](class_float#class-float) ratio **)** |
| void | [particles\_set\_speed\_scale](#class-visualserver-method-particles-set-speed-scale) **(** [RID](class_rid#class-rid) particles, [float](class_float#class-float) scale **)** |
| void | [particles\_set\_use\_local\_coordinates](#class-visualserver-method-particles-set-use-local-coordinates) **(** [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) enable **)** |
| [RID](class_rid#class-rid) | [reflection\_probe\_create](#class-visualserver-method-reflection-probe-create) **(** **)** |
| void | [reflection\_probe\_set\_as\_interior](#class-visualserver-method-reflection-probe-set-as-interior) **(** [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable **)** |
| void | [reflection\_probe\_set\_cull\_mask](#class-visualserver-method-reflection-probe-set-cull-mask) **(** [RID](class_rid#class-rid) probe, [int](class_int#class-int) layers **)** |
| void | [reflection\_probe\_set\_enable\_box\_projection](#class-visualserver-method-reflection-probe-set-enable-box-projection) **(** [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable **)** |
| void | [reflection\_probe\_set\_enable\_shadows](#class-visualserver-method-reflection-probe-set-enable-shadows) **(** [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable **)** |
| void | [reflection\_probe\_set\_extents](#class-visualserver-method-reflection-probe-set-extents) **(** [RID](class_rid#class-rid) probe, [Vector3](class_vector3#class-vector3) extents **)** |
| void | [reflection\_probe\_set\_intensity](#class-visualserver-method-reflection-probe-set-intensity) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) intensity **)** |
| void | [reflection\_probe\_set\_interior\_ambient](#class-visualserver-method-reflection-probe-set-interior-ambient) **(** [RID](class_rid#class-rid) probe, [Color](class_color#class-color) color **)** |
| void | [reflection\_probe\_set\_interior\_ambient\_energy](#class-visualserver-method-reflection-probe-set-interior-ambient-energy) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) energy **)** |
| void | [reflection\_probe\_set\_interior\_ambient\_probe\_contribution](#class-visualserver-method-reflection-probe-set-interior-ambient-probe-contribution) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) contrib **)** |
| void | [reflection\_probe\_set\_max\_distance](#class-visualserver-method-reflection-probe-set-max-distance) **(** [RID](class_rid#class-rid) probe, [float](class_float#class-float) distance **)** |
| void | [reflection\_probe\_set\_origin\_offset](#class-visualserver-method-reflection-probe-set-origin-offset) **(** [RID](class_rid#class-rid) probe, [Vector3](class_vector3#class-vector3) offset **)** |
| void | [reflection\_probe\_set\_update\_mode](#class-visualserver-method-reflection-probe-set-update-mode) **(** [RID](class_rid#class-rid) probe, [ReflectionProbeUpdateMode](#enum-visualserver-reflectionprobeupdatemode) mode **)** |
| void | [request\_frame\_drawn\_callback](#class-visualserver-method-request-frame-drawn-callback) **(** [Object](class_object#class-object) where, [String](class_string#class-string) method, [Variant](class_variant#class-variant) userdata **)** |
| [RID](class_rid#class-rid) | [scenario\_create](#class-visualserver-method-scenario-create) **(** **)** |
| void | [scenario\_set\_debug](#class-visualserver-method-scenario-set-debug) **(** [RID](class_rid#class-rid) scenario, [ScenarioDebugMode](#enum-visualserver-scenariodebugmode) debug\_mode **)** |
| void | [scenario\_set\_environment](#class-visualserver-method-scenario-set-environment) **(** [RID](class_rid#class-rid) scenario, [RID](class_rid#class-rid) environment **)** |
| void | [scenario\_set\_fallback\_environment](#class-visualserver-method-scenario-set-fallback-environment) **(** [RID](class_rid#class-rid) scenario, [RID](class_rid#class-rid) environment **)** |
| void | [scenario\_set\_reflection\_atlas\_size](#class-visualserver-method-scenario-set-reflection-atlas-size) **(** [RID](class_rid#class-rid) scenario, [int](class_int#class-int) size, [int](class_int#class-int) subdiv **)** |
| void | [set\_boot\_image](#class-visualserver-method-set-boot-image) **(** [Image](class_image#class-image) image, [Color](class_color#class-color) color, [bool](class_bool#class-bool) scale, [bool](class_bool#class-bool) use\_filter=true **)** |
| void | [set\_debug\_generate\_wireframes](#class-visualserver-method-set-debug-generate-wireframes) **(** [bool](class_bool#class-bool) generate **)** |
| void | [set\_default\_clear\_color](#class-visualserver-method-set-default-clear-color) **(** [Color](class_color#class-color) color **)** |
| void | [set\_shader\_async\_hidden\_forbidden](#class-visualserver-method-set-shader-async-hidden-forbidden) **(** [bool](class_bool#class-bool) forbidden **)** |
| void | [set\_shader\_time\_scale](#class-visualserver-method-set-shader-time-scale) **(** [float](class_float#class-float) scale **)** |
| void | [set\_use\_occlusion\_culling](#class-visualserver-method-set-use-occlusion-culling) **(** [bool](class_bool#class-bool) enable **)** |
| [RID](class_rid#class-rid) | [shader\_create](#class-visualserver-method-shader-create) **(** **)** |
| [String](class_string#class-string) | [shader\_get\_code](#class-visualserver-method-shader-get-code) **(** [RID](class_rid#class-rid) shader **)** const |
| [RID](class_rid#class-rid) | [shader\_get\_default\_texture\_param](#class-visualserver-method-shader-get-default-texture-param) **(** [RID](class_rid#class-rid) shader, [String](class_string#class-string) name **)** const |
| [Array](class_array#class-array) | [shader\_get\_param\_list](#class-visualserver-method-shader-get-param-list) **(** [RID](class_rid#class-rid) shader **)** const |
| void | [shader\_set\_code](#class-visualserver-method-shader-set-code) **(** [RID](class_rid#class-rid) shader, [String](class_string#class-string) code **)** |
| void | [shader\_set\_default\_texture\_param](#class-visualserver-method-shader-set-default-texture-param) **(** [RID](class_rid#class-rid) shader, [String](class_string#class-string) name, [RID](class_rid#class-rid) texture **)** |
| void | [skeleton\_allocate](#class-visualserver-method-skeleton-allocate) **(** [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bones, [bool](class_bool#class-bool) is\_2d\_skeleton=false **)** |
| [Transform](class_transform#class-transform) | [skeleton\_bone\_get\_transform](#class-visualserver-method-skeleton-bone-get-transform) **(** [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone **)** const |
| [Transform2D](class_transform2d#class-transform2d) | [skeleton\_bone\_get\_transform\_2d](#class-visualserver-method-skeleton-bone-get-transform-2d) **(** [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone **)** const |
| void | [skeleton\_bone\_set\_transform](#class-visualserver-method-skeleton-bone-set-transform) **(** [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone, [Transform](class_transform#class-transform) transform **)** |
| void | [skeleton\_bone\_set\_transform\_2d](#class-visualserver-method-skeleton-bone-set-transform-2d) **(** [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone, [Transform2D](class_transform2d#class-transform2d) transform **)** |
| [RID](class_rid#class-rid) | [skeleton\_create](#class-visualserver-method-skeleton-create) **(** **)** |
| [int](class_int#class-int) | [skeleton\_get\_bone\_count](#class-visualserver-method-skeleton-get-bone-count) **(** [RID](class_rid#class-rid) skeleton **)** const |
| [RID](class_rid#class-rid) | [sky\_create](#class-visualserver-method-sky-create) **(** **)** |
| void | [sky\_set\_texture](#class-visualserver-method-sky-set-texture) **(** [RID](class_rid#class-rid) sky, [RID](class_rid#class-rid) cube\_map, [int](class_int#class-int) radiance\_size **)** |
| [RID](class_rid#class-rid) | [spot\_light\_create](#class-visualserver-method-spot-light-create) **(** **)** |
| void | [sync](#class-visualserver-method-sync) **(** **)** |
| void | [texture\_allocate](#class-visualserver-method-texture-allocate) **(** [RID](class_rid#class-rid) texture, [int](class_int#class-int) width, [int](class_int#class-int) height, [int](class_int#class-int) depth\_3d, [Format](class_image#enum-image-format) format, [TextureType](#enum-visualserver-texturetype) type, [int](class_int#class-int) flags=7 **)** |
| void | [texture\_bind](#class-visualserver-method-texture-bind) **(** [RID](class_rid#class-rid) texture, [int](class_int#class-int) number **)** |
| [RID](class_rid#class-rid) | [texture\_create](#class-visualserver-method-texture-create) **(** **)** |
| [RID](class_rid#class-rid) | [texture\_create\_from\_image](#class-visualserver-method-texture-create-from-image) **(** [Image](class_image#class-image) image, [int](class_int#class-int) flags=7 **)** |
| [Array](class_array#class-array) | [texture\_debug\_usage](#class-visualserver-method-texture-debug-usage) **(** **)** |
| [Image](class_image#class-image) | [texture\_get\_data](#class-visualserver-method-texture-get-data) **(** [RID](class_rid#class-rid) texture, [int](class_int#class-int) cube\_side=0 **)** const |
| [int](class_int#class-int) | [texture\_get\_depth](#class-visualserver-method-texture-get-depth) **(** [RID](class_rid#class-rid) texture **)** const |
| [int](class_int#class-int) | [texture\_get\_flags](#class-visualserver-method-texture-get-flags) **(** [RID](class_rid#class-rid) texture **)** const |
| [Format](class_image#enum-image-format) | [texture\_get\_format](#class-visualserver-method-texture-get-format) **(** [RID](class_rid#class-rid) texture **)** const |
| [int](class_int#class-int) | [texture\_get\_height](#class-visualserver-method-texture-get-height) **(** [RID](class_rid#class-rid) texture **)** const |
| [String](class_string#class-string) | [texture\_get\_path](#class-visualserver-method-texture-get-path) **(** [RID](class_rid#class-rid) texture **)** const |
| [int](class_int#class-int) | [texture\_get\_texid](#class-visualserver-method-texture-get-texid) **(** [RID](class_rid#class-rid) texture **)** const |
| [TextureType](#enum-visualserver-texturetype) | [texture\_get\_type](#class-visualserver-method-texture-get-type) **(** [RID](class_rid#class-rid) texture **)** const |
| [int](class_int#class-int) | [texture\_get\_width](#class-visualserver-method-texture-get-width) **(** [RID](class_rid#class-rid) texture **)** const |
| void | [texture\_set\_data](#class-visualserver-method-texture-set-data) **(** [RID](class_rid#class-rid) texture, [Image](class_image#class-image) image, [int](class_int#class-int) layer=0 **)** |
| void | [texture\_set\_data\_partial](#class-visualserver-method-texture-set-data-partial) **(** [RID](class_rid#class-rid) texture, [Image](class_image#class-image) image, [int](class_int#class-int) src\_x, [int](class_int#class-int) src\_y, [int](class_int#class-int) src\_w, [int](class_int#class-int) src\_h, [int](class_int#class-int) dst\_x, [int](class_int#class-int) dst\_y, [int](class_int#class-int) dst\_mip, [int](class_int#class-int) layer=0 **)** |
| void | [texture\_set\_flags](#class-visualserver-method-texture-set-flags) **(** [RID](class_rid#class-rid) texture, [int](class_int#class-int) flags **)** |
| void | [texture\_set\_path](#class-visualserver-method-texture-set-path) **(** [RID](class_rid#class-rid) texture, [String](class_string#class-string) path **)** |
| void | [texture\_set\_proxy](#class-visualserver-method-texture-set-proxy) **(** [RID](class_rid#class-rid) proxy, [RID](class_rid#class-rid) base **)** |
| void | [texture\_set\_shrink\_all\_x2\_on\_set\_data](#class-visualserver-method-texture-set-shrink-all-x2-on-set-data) **(** [bool](class_bool#class-bool) shrink **)** |
| void | [texture\_set\_size\_override](#class-visualserver-method-texture-set-size-override) **(** [RID](class_rid#class-rid) texture, [int](class_int#class-int) width, [int](class_int#class-int) height, [int](class_int#class-int) depth **)** |
| void | [textures\_keep\_original](#class-visualserver-method-textures-keep-original) **(** [bool](class_bool#class-bool) enable **)** |
| void | [viewport\_attach\_camera](#class-visualserver-method-viewport-attach-camera) **(** [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) camera **)** |
| void | [viewport\_attach\_canvas](#class-visualserver-method-viewport-attach-canvas) **(** [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas **)** |
| void | [viewport\_attach\_to\_screen](#class-visualserver-method-viewport-attach-to-screen) **(** [RID](class_rid#class-rid) viewport, [Rect2](class_rect2#class-rect2) rect=Rect2( 0, 0, 0, 0 ), [int](class_int#class-int) screen=0 **)** |
| [RID](class_rid#class-rid) | [viewport\_create](#class-visualserver-method-viewport-create) **(** **)** |
| void | [viewport\_detach](#class-visualserver-method-viewport-detach) **(** [RID](class_rid#class-rid) viewport **)** |
| [int](class_int#class-int) | [viewport\_get\_render\_info](#class-visualserver-method-viewport-get-render-info) **(** [RID](class_rid#class-rid) viewport, [ViewportRenderInfo](#enum-visualserver-viewportrenderinfo) info **)** |
| [RID](class_rid#class-rid) | [viewport\_get\_texture](#class-visualserver-method-viewport-get-texture) **(** [RID](class_rid#class-rid) viewport **)** const |
| void | [viewport\_remove\_canvas](#class-visualserver-method-viewport-remove-canvas) **(** [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas **)** |
| void | [viewport\_set\_active](#class-visualserver-method-viewport-set-active) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) active **)** |
| void | [viewport\_set\_canvas\_stacking](#class-visualserver-method-viewport-set-canvas-stacking) **(** [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas, [int](class_int#class-int) layer, [int](class_int#class-int) sublayer **)** |
| void | [viewport\_set\_canvas\_transform](#class-visualserver-method-viewport-set-canvas-transform) **(** [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas, [Transform2D](class_transform2d#class-transform2d) offset **)** |
| void | [viewport\_set\_clear\_mode](#class-visualserver-method-viewport-set-clear-mode) **(** [RID](class_rid#class-rid) viewport, [ViewportClearMode](#enum-visualserver-viewportclearmode) clear\_mode **)** |
| void | [viewport\_set\_debug\_draw](#class-visualserver-method-viewport-set-debug-draw) **(** [RID](class_rid#class-rid) viewport, [ViewportDebugDraw](#enum-visualserver-viewportdebugdraw) draw **)** |
| void | [viewport\_set\_disable\_3d](#class-visualserver-method-viewport-set-disable-3d) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) disabled **)** |
| void | [viewport\_set\_disable\_environment](#class-visualserver-method-viewport-set-disable-environment) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) disabled **)** |
| void | [viewport\_set\_global\_canvas\_transform](#class-visualserver-method-viewport-set-global-canvas-transform) **(** [RID](class_rid#class-rid) viewport, [Transform2D](class_transform2d#class-transform2d) transform **)** |
| void | [viewport\_set\_hdr](#class-visualserver-method-viewport-set-hdr) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled **)** |
| void | [viewport\_set\_hide\_canvas](#class-visualserver-method-viewport-set-hide-canvas) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) hidden **)** |
| void | [viewport\_set\_hide\_scenario](#class-visualserver-method-viewport-set-hide-scenario) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) hidden **)** |
| void | [viewport\_set\_msaa](#class-visualserver-method-viewport-set-msaa) **(** [RID](class_rid#class-rid) viewport, [ViewportMSAA](#enum-visualserver-viewportmsaa) msaa **)** |
| void | [viewport\_set\_parent\_viewport](#class-visualserver-method-viewport-set-parent-viewport) **(** [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) parent\_viewport **)** |
| void | [viewport\_set\_render\_direct\_to\_screen](#class-visualserver-method-viewport-set-render-direct-to-screen) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled **)** |
| void | [viewport\_set\_scenario](#class-visualserver-method-viewport-set-scenario) **(** [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) scenario **)** |
| void | [viewport\_set\_shadow\_atlas\_quadrant\_subdivision](#class-visualserver-method-viewport-set-shadow-atlas-quadrant-subdivision) **(** [RID](class_rid#class-rid) viewport, [int](class_int#class-int) quadrant, [int](class_int#class-int) subdivision **)** |
| void | [viewport\_set\_shadow\_atlas\_size](#class-visualserver-method-viewport-set-shadow-atlas-size) **(** [RID](class_rid#class-rid) viewport, [int](class_int#class-int) size **)** |
| void | [viewport\_set\_sharpen\_intensity](#class-visualserver-method-viewport-set-sharpen-intensity) **(** [RID](class_rid#class-rid) viewport, [float](class_float#class-float) intensity **)** |
| void | [viewport\_set\_size](#class-visualserver-method-viewport-set-size) **(** [RID](class_rid#class-rid) viewport, [int](class_int#class-int) width, [int](class_int#class-int) height **)** |
| void | [viewport\_set\_transparent\_background](#class-visualserver-method-viewport-set-transparent-background) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled **)** |
| void | [viewport\_set\_update\_mode](#class-visualserver-method-viewport-set-update-mode) **(** [RID](class_rid#class-rid) viewport, [ViewportUpdateMode](#enum-visualserver-viewportupdatemode) update\_mode **)** |
| void | [viewport\_set\_usage](#class-visualserver-method-viewport-set-usage) **(** [RID](class_rid#class-rid) viewport, [ViewportUsage](#enum-visualserver-viewportusage) usage **)** |
| void | [viewport\_set\_use\_32\_bpc\_depth](#class-visualserver-method-viewport-set-use-32-bpc-depth) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled **)** |
| void | [viewport\_set\_use\_arvr](#class-visualserver-method-viewport-set-use-arvr) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) use\_arvr **)** |
| void | [viewport\_set\_use\_debanding](#class-visualserver-method-viewport-set-use-debanding) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) debanding **)** |
| void | [viewport\_set\_use\_fxaa](#class-visualserver-method-viewport-set-use-fxaa) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) fxaa **)** |
| void | [viewport\_set\_vflip](#class-visualserver-method-viewport-set-vflip) **(** [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled **)** |
Signals
-------
### frame\_post\_draw ( )
Emitted at the end of the frame, after the VisualServer has finished updating all the Viewports.
### frame\_pre\_draw ( )
Emitted at the beginning of the frame, before the VisualServer updates all the Viewports.
Enumerations
------------
enum **CubeMapSide**:
* **CUBEMAP\_LEFT** = **0** --- Marks the left side of a cubemap.
* **CUBEMAP\_RIGHT** = **1** --- Marks the right side of a cubemap.
* **CUBEMAP\_BOTTOM** = **2** --- Marks the bottom side of a cubemap.
* **CUBEMAP\_TOP** = **3** --- Marks the top side of a cubemap.
* **CUBEMAP\_FRONT** = **4** --- Marks the front side of a cubemap.
* **CUBEMAP\_BACK** = **5** --- Marks the back side of a cubemap.
enum **TextureType**:
* **TEXTURE\_TYPE\_2D** = **0** --- Normal texture with 2 dimensions, width and height.
* **TEXTURE\_TYPE\_CUBEMAP** = **2** --- Texture made up of six faces, can be looked up with a `vec3` in shader.
* **TEXTURE\_TYPE\_2D\_ARRAY** = **3** --- An array of 2-dimensional textures.
* **TEXTURE\_TYPE\_3D** = **4** --- A 3-dimensional texture with width, height, and depth.
enum **TextureFlags**:
* **TEXTURE\_FLAG\_MIPMAPS** = **1** --- Generates mipmaps, which are smaller versions of the same texture to use when zoomed out, keeping the aspect ratio.
* **TEXTURE\_FLAG\_REPEAT** = **2** --- Repeats the texture (instead of clamp to edge).
* **TEXTURE\_FLAG\_FILTER** = **4** --- Uses a magnifying filter, to enable smooth zooming in of the texture.
* **TEXTURE\_FLAG\_ANISOTROPIC\_FILTER** = **8** --- Uses anisotropic mipmap filtering. Generates smaller versions of the same texture with different aspect ratios.
This results in better-looking textures when viewed from oblique angles.
* **TEXTURE\_FLAG\_CONVERT\_TO\_LINEAR** = **16** --- Converts the texture to the sRGB color space.
* **TEXTURE\_FLAG\_MIRRORED\_REPEAT** = **32** --- Repeats the texture with alternate sections mirrored.
* **TEXTURE\_FLAG\_USED\_FOR\_STREAMING** = **2048** --- Texture is a video surface.
* **TEXTURE\_FLAGS\_DEFAULT** = **7** --- Default flags. [TEXTURE\_FLAG\_MIPMAPS](#class-visualserver-constant-texture-flag-mipmaps), [TEXTURE\_FLAG\_REPEAT](#class-visualserver-constant-texture-flag-repeat) and [TEXTURE\_FLAG\_FILTER](#class-visualserver-constant-texture-flag-filter) are enabled.
enum **ShaderMode**:
* **SHADER\_SPATIAL** = **0** --- Shader is a 3D shader.
* **SHADER\_CANVAS\_ITEM** = **1** --- Shader is a 2D shader.
* **SHADER\_PARTICLES** = **2** --- Shader is a particle shader.
* **SHADER\_MAX** = **3** --- Represents the size of the [ShaderMode](#enum-visualserver-shadermode) enum.
enum **ArrayType**:
* **ARRAY\_VERTEX** = **0** --- Array is a vertex array.
* **ARRAY\_NORMAL** = **1** --- Array is a normal array.
* **ARRAY\_TANGENT** = **2** --- Array is a tangent array.
* **ARRAY\_COLOR** = **3** --- Array is a color array.
* **ARRAY\_TEX\_UV** = **4** --- Array is an UV coordinates array.
* **ARRAY\_TEX\_UV2** = **5** --- Array is an UV coordinates array for the second UV coordinates.
* **ARRAY\_BONES** = **6** --- Array contains bone information.
* **ARRAY\_WEIGHTS** = **7** --- Array is weight information.
* **ARRAY\_INDEX** = **8** --- Array is index array.
* **ARRAY\_MAX** = **9** --- Represents the size of the [ArrayType](#enum-visualserver-arraytype) enum.
enum **ArrayFormat**:
* **ARRAY\_FORMAT\_VERTEX** = **1** --- Flag used to mark a vertex array.
* **ARRAY\_FORMAT\_NORMAL** = **2** --- Flag used to mark a normal array.
* **ARRAY\_FORMAT\_TANGENT** = **4** --- Flag used to mark a tangent array.
* **ARRAY\_FORMAT\_COLOR** = **8** --- Flag used to mark a color array.
* **ARRAY\_FORMAT\_TEX\_UV** = **16** --- Flag used to mark an UV coordinates array.
* **ARRAY\_FORMAT\_TEX\_UV2** = **32** --- Flag used to mark an UV coordinates array for the second UV coordinates.
* **ARRAY\_FORMAT\_BONES** = **64** --- Flag used to mark a bone information array.
* **ARRAY\_FORMAT\_WEIGHTS** = **128** --- Flag used to mark a weights array.
* **ARRAY\_FORMAT\_INDEX** = **256** --- Flag used to mark an index array.
* **ARRAY\_COMPRESS\_VERTEX** = **512** --- Flag used to mark a compressed (half float) vertex array.
* **ARRAY\_COMPRESS\_NORMAL** = **1024** --- Flag used to mark a compressed (half float) normal array.
* **ARRAY\_COMPRESS\_TANGENT** = **2048** --- Flag used to mark a compressed (half float) tangent array.
* **ARRAY\_COMPRESS\_COLOR** = **4096** --- Flag used to mark a compressed (half float) color array.
* **ARRAY\_COMPRESS\_TEX\_UV** = **8192** --- Flag used to mark a compressed (half float) UV coordinates array.
* **ARRAY\_COMPRESS\_TEX\_UV2** = **16384** --- Flag used to mark a compressed (half float) UV coordinates array for the second UV coordinates.
* **ARRAY\_COMPRESS\_BONES** = **32768** --- Flag used to mark a compressed bone array.
* **ARRAY\_COMPRESS\_WEIGHTS** = **65536** --- Flag used to mark a compressed (half float) weight array.
* **ARRAY\_COMPRESS\_INDEX** = **131072** --- Flag used to mark a compressed index array.
* **ARRAY\_FLAG\_USE\_2D\_VERTICES** = **262144** --- Flag used to mark that the array contains 2D vertices.
* **ARRAY\_FLAG\_USE\_16\_BIT\_BONES** = **524288** --- Flag used to mark that the array uses 16-bit bones instead of 8-bit.
* **ARRAY\_FLAG\_USE\_OCTAHEDRAL\_COMPRESSION** = **2097152** --- Flag used to mark that the array uses an octahedral representation of normal and tangent vectors rather than cartesian.
* **ARRAY\_COMPRESS\_DEFAULT** = **2194432** --- Used to set flags [ARRAY\_COMPRESS\_NORMAL](#class-visualserver-constant-array-compress-normal), [ARRAY\_COMPRESS\_TANGENT](#class-visualserver-constant-array-compress-tangent), [ARRAY\_COMPRESS\_COLOR](#class-visualserver-constant-array-compress-color), [ARRAY\_COMPRESS\_TEX\_UV](#class-visualserver-constant-array-compress-tex-uv), [ARRAY\_COMPRESS\_TEX\_UV2](#class-visualserver-constant-array-compress-tex-uv2), [ARRAY\_COMPRESS\_WEIGHTS](#class-visualserver-constant-array-compress-weights), and [ARRAY\_FLAG\_USE\_OCTAHEDRAL\_COMPRESSION](#class-visualserver-constant-array-flag-use-octahedral-compression) quickly.
enum **PrimitiveType**:
* **PRIMITIVE\_POINTS** = **0** --- Primitive to draw consists of points.
* **PRIMITIVE\_LINES** = **1** --- Primitive to draw consists of lines.
* **PRIMITIVE\_LINE\_STRIP** = **2** --- Primitive to draw consists of a line strip from start to end.
* **PRIMITIVE\_LINE\_LOOP** = **3** --- Primitive to draw consists of a line loop (a line strip with a line between the last and the first vertex).
* **PRIMITIVE\_TRIANGLES** = **4** --- Primitive to draw consists of triangles.
* **PRIMITIVE\_TRIANGLE\_STRIP** = **5** --- Primitive to draw consists of a triangle strip (the last 3 vertices are always combined to make a triangle).
* **PRIMITIVE\_TRIANGLE\_FAN** = **6** --- Primitive to draw consists of a triangle strip (the last 2 vertices are always combined with the first to make a triangle).
* **PRIMITIVE\_MAX** = **7** --- Represents the size of the [PrimitiveType](#enum-visualserver-primitivetype) enum.
enum **BlendShapeMode**:
* **BLEND\_SHAPE\_MODE\_NORMALIZED** = **0** --- Blend shapes are normalized.
* **BLEND\_SHAPE\_MODE\_RELATIVE** = **1** --- Blend shapes are relative to base weight.
enum **LightType**:
* **LIGHT\_DIRECTIONAL** = **0** --- Is a directional (sun) light.
* **LIGHT\_OMNI** = **1** --- Is an omni light.
* **LIGHT\_SPOT** = **2** --- Is a spot light.
enum **LightParam**:
* **LIGHT\_PARAM\_ENERGY** = **0** --- The light's energy.
* **LIGHT\_PARAM\_INDIRECT\_ENERGY** = **1** --- Secondary multiplier used with indirect light (light bounces).
* **LIGHT\_PARAM\_SIZE** = **2** --- The light's size, currently only used for soft shadows in baked lightmaps.
* **LIGHT\_PARAM\_SPECULAR** = **3** --- The light's influence on specularity.
* **LIGHT\_PARAM\_RANGE** = **4** --- The light's range.
* **LIGHT\_PARAM\_ATTENUATION** = **5** --- The light's attenuation.
* **LIGHT\_PARAM\_SPOT\_ANGLE** = **6** --- The spotlight's angle.
* **LIGHT\_PARAM\_SPOT\_ATTENUATION** = **7** --- The spotlight's attenuation.
* **LIGHT\_PARAM\_CONTACT\_SHADOW\_SIZE** = **8** --- Scales the shadow color.
* **LIGHT\_PARAM\_SHADOW\_MAX\_DISTANCE** = **9** --- Max distance that shadows will be rendered.
* **LIGHT\_PARAM\_SHADOW\_SPLIT\_1\_OFFSET** = **10** --- Proportion of shadow atlas occupied by the first split.
* **LIGHT\_PARAM\_SHADOW\_SPLIT\_2\_OFFSET** = **11** --- Proportion of shadow atlas occupied by the second split.
* **LIGHT\_PARAM\_SHADOW\_SPLIT\_3\_OFFSET** = **12** --- Proportion of shadow atlas occupied by the third split. The fourth split occupies the rest.
* **LIGHT\_PARAM\_SHADOW\_NORMAL\_BIAS** = **13** --- Normal bias used to offset shadow lookup by object normal. Can be used to fix self-shadowing artifacts.
* **LIGHT\_PARAM\_SHADOW\_BIAS** = **14** --- Bias the shadow lookup to fix self-shadowing artifacts.
* **LIGHT\_PARAM\_SHADOW\_BIAS\_SPLIT\_SCALE** = **15** --- Increases bias on further splits to fix self-shadowing that only occurs far away from the camera.
* **LIGHT\_PARAM\_MAX** = **16** --- Represents the size of the [LightParam](#enum-visualserver-lightparam) enum.
enum **LightBakeMode**:
* **LIGHT\_BAKE\_DISABLED** = **0**
* **LIGHT\_BAKE\_INDIRECT** = **1**
* **LIGHT\_BAKE\_ALL** = **2**
enum **LightOmniShadowMode**:
* **LIGHT\_OMNI\_SHADOW\_DUAL\_PARABOLOID** = **0** --- Use a dual paraboloid shadow map for omni lights.
* **LIGHT\_OMNI\_SHADOW\_CUBE** = **1** --- Use a cubemap shadow map for omni lights. Slower but better quality than dual paraboloid.
enum **LightOmniShadowDetail**:
* **LIGHT\_OMNI\_SHADOW\_DETAIL\_VERTICAL** = **0** --- Use more detail vertically when computing shadow map.
* **LIGHT\_OMNI\_SHADOW\_DETAIL\_HORIZONTAL** = **1** --- Use more detail horizontally when computing shadow map.
enum **LightDirectionalShadowMode**:
* **LIGHT\_DIRECTIONAL\_SHADOW\_ORTHOGONAL** = **0** --- Use orthogonal shadow projection for directional light.
* **LIGHT\_DIRECTIONAL\_SHADOW\_PARALLEL\_2\_SPLITS** = **1** --- Use 2 splits for shadow projection when using directional light.
* **LIGHT\_DIRECTIONAL\_SHADOW\_PARALLEL\_4\_SPLITS** = **2** --- Use 4 splits for shadow projection when using directional light.
enum **LightDirectionalShadowDepthRangeMode**:
* **LIGHT\_DIRECTIONAL\_SHADOW\_DEPTH\_RANGE\_STABLE** = **0** --- Keeps shadows stable as camera moves but has lower effective resolution.
* **LIGHT\_DIRECTIONAL\_SHADOW\_DEPTH\_RANGE\_OPTIMIZED** = **1** --- Optimize use of shadow maps, increasing the effective resolution. But may result in shadows moving or flickering slightly.
enum **ViewportUpdateMode**:
* **VIEWPORT\_UPDATE\_DISABLED** = **0** --- Do not update the viewport.
* **VIEWPORT\_UPDATE\_ONCE** = **1** --- Update the viewport once then set to disabled.
* **VIEWPORT\_UPDATE\_WHEN\_VISIBLE** = **2** --- Update the viewport whenever it is visible.
* **VIEWPORT\_UPDATE\_ALWAYS** = **3** --- Always update the viewport.
enum **ViewportClearMode**:
* **VIEWPORT\_CLEAR\_ALWAYS** = **0** --- The viewport is always cleared before drawing.
* **VIEWPORT\_CLEAR\_NEVER** = **1** --- The viewport is never cleared before drawing.
* **VIEWPORT\_CLEAR\_ONLY\_NEXT\_FRAME** = **2** --- The viewport is cleared once, then the clear mode is set to [VIEWPORT\_CLEAR\_NEVER](#class-visualserver-constant-viewport-clear-never).
enum **ViewportMSAA**:
* **VIEWPORT\_MSAA\_DISABLED** = **0** --- Multisample antialiasing is disabled.
* **VIEWPORT\_MSAA\_2X** = **1** --- Multisample antialiasing is set to 2×.
* **VIEWPORT\_MSAA\_4X** = **2** --- Multisample antialiasing is set to 4×.
* **VIEWPORT\_MSAA\_8X** = **3** --- Multisample antialiasing is set to 8×.
* **VIEWPORT\_MSAA\_16X** = **4** --- Multisample antialiasing is set to 16×.
* **VIEWPORT\_MSAA\_EXT\_2X** = **5** --- Multisample antialiasing is set to 2× on external texture. Special mode for GLES2 Android VR (Oculus Quest and Go).
* **VIEWPORT\_MSAA\_EXT\_4X** = **6** --- Multisample antialiasing is set to 4× on external texture. Special mode for GLES2 Android VR (Oculus Quest and Go).
enum **ViewportUsage**:
* **VIEWPORT\_USAGE\_2D** = **0** --- The Viewport does not render 3D but samples.
* **VIEWPORT\_USAGE\_2D\_NO\_SAMPLING** = **1** --- The Viewport does not render 3D and does not sample.
* **VIEWPORT\_USAGE\_3D** = **2** --- The Viewport renders 3D with effects.
* **VIEWPORT\_USAGE\_3D\_NO\_EFFECTS** = **3** --- The Viewport renders 3D but without effects.
enum **ViewportRenderInfo**:
* **VIEWPORT\_RENDER\_INFO\_OBJECTS\_IN\_FRAME** = **0** --- Number of objects drawn in a single frame.
* **VIEWPORT\_RENDER\_INFO\_VERTICES\_IN\_FRAME** = **1** --- Number of vertices drawn in a single frame.
* **VIEWPORT\_RENDER\_INFO\_MATERIAL\_CHANGES\_IN\_FRAME** = **2** --- Number of material changes during this frame.
* **VIEWPORT\_RENDER\_INFO\_SHADER\_CHANGES\_IN\_FRAME** = **3** --- Number of shader changes during this frame.
* **VIEWPORT\_RENDER\_INFO\_SURFACE\_CHANGES\_IN\_FRAME** = **4** --- Number of surface changes during this frame.
* **VIEWPORT\_RENDER\_INFO\_DRAW\_CALLS\_IN\_FRAME** = **5** --- Number of draw calls during this frame.
* **VIEWPORT\_RENDER\_INFO\_2D\_ITEMS\_IN\_FRAME** = **6** --- Number of 2d items drawn this frame.
* **VIEWPORT\_RENDER\_INFO\_2D\_DRAW\_CALLS\_IN\_FRAME** = **7** --- Number of 2d draw calls during this frame.
* **VIEWPORT\_RENDER\_INFO\_MAX** = **8** --- Represents the size of the [ViewportRenderInfo](#enum-visualserver-viewportrenderinfo) enum.
enum **ViewportDebugDraw**:
* **VIEWPORT\_DEBUG\_DRAW\_DISABLED** = **0** --- Debug draw is disabled. Default setting.
* **VIEWPORT\_DEBUG\_DRAW\_UNSHADED** = **1** --- Debug draw sets objects to unshaded.
* **VIEWPORT\_DEBUG\_DRAW\_OVERDRAW** = **2** --- Overwrites clear color to `(0,0,0,0)`.
* **VIEWPORT\_DEBUG\_DRAW\_WIREFRAME** = **3** --- Debug draw draws objects in wireframe.
enum **ScenarioDebugMode**:
* **SCENARIO\_DEBUG\_DISABLED** = **0** --- Do not use a debug mode.
* **SCENARIO\_DEBUG\_WIREFRAME** = **1** --- Draw all objects as wireframe models.
* **SCENARIO\_DEBUG\_OVERDRAW** = **2** --- Draw all objects in a way that displays how much overdraw is occurring. Overdraw occurs when a section of pixels is drawn and shaded and then another object covers it up. To optimize a scene, you should reduce overdraw.
* **SCENARIO\_DEBUG\_SHADELESS** = **3** --- Draw all objects without shading. Equivalent to setting all objects shaders to `unshaded`.
enum **InstanceType**:
* **INSTANCE\_NONE** = **0** --- The instance does not have a type.
* **INSTANCE\_MESH** = **1** --- The instance is a mesh.
* **INSTANCE\_MULTIMESH** = **2** --- The instance is a multimesh.
* **INSTANCE\_IMMEDIATE** = **3** --- The instance is an immediate geometry.
* **INSTANCE\_PARTICLES** = **4** --- The instance is a particle emitter.
* **INSTANCE\_LIGHT** = **5** --- The instance is a light.
* **INSTANCE\_REFLECTION\_PROBE** = **6** --- The instance is a reflection probe.
* **INSTANCE\_GI\_PROBE** = **7** --- The instance is a GI probe.
* **INSTANCE\_LIGHTMAP\_CAPTURE** = **8** --- The instance is a lightmap capture.
* **INSTANCE\_MAX** = **9** --- Represents the size of the [InstanceType](#enum-visualserver-instancetype) enum.
* **INSTANCE\_GEOMETRY\_MASK** = **30** --- A combination of the flags of geometry instances (mesh, multimesh, immediate and particles).
enum **InstanceFlags**:
* **INSTANCE\_FLAG\_USE\_BAKED\_LIGHT** = **0** --- Allows the instance to be used in baked lighting.
* **INSTANCE\_FLAG\_DRAW\_NEXT\_FRAME\_IF\_VISIBLE** = **1** --- When set, manually requests to draw geometry on next frame.
* **INSTANCE\_FLAG\_MAX** = **2** --- Represents the size of the [InstanceFlags](#enum-visualserver-instanceflags) enum.
enum **ShadowCastingSetting**:
* **SHADOW\_CASTING\_SETTING\_OFF** = **0** --- Disable shadows from this instance.
* **SHADOW\_CASTING\_SETTING\_ON** = **1** --- Cast shadows from this instance.
* **SHADOW\_CASTING\_SETTING\_DOUBLE\_SIDED** = **2** --- Disable backface culling when rendering the shadow of the object. This is slightly slower but may result in more correct shadows.
* **SHADOW\_CASTING\_SETTING\_SHADOWS\_ONLY** = **3** --- Only render the shadows from the object. The object itself will not be drawn.
enum **NinePatchAxisMode**:
* **NINE\_PATCH\_STRETCH** = **0** --- The nine patch gets stretched where needed.
* **NINE\_PATCH\_TILE** = **1** --- The nine patch gets filled with tiles where needed.
* **NINE\_PATCH\_TILE\_FIT** = **2** --- The nine patch gets filled with tiles where needed and stretches them a bit if needed.
enum **CanvasLightMode**:
* **CANVAS\_LIGHT\_MODE\_ADD** = **0** --- Adds light color additive to the canvas.
* **CANVAS\_LIGHT\_MODE\_SUB** = **1** --- Adds light color subtractive to the canvas.
* **CANVAS\_LIGHT\_MODE\_MIX** = **2** --- The light adds color depending on transparency.
* **CANVAS\_LIGHT\_MODE\_MASK** = **3** --- The light adds color depending on mask.
enum **CanvasLightShadowFilter**:
* **CANVAS\_LIGHT\_FILTER\_NONE** = **0** --- Do not apply a filter to canvas light shadows.
* **CANVAS\_LIGHT\_FILTER\_PCF3** = **1** --- Use PCF3 filtering to filter canvas light shadows.
* **CANVAS\_LIGHT\_FILTER\_PCF5** = **2** --- Use PCF5 filtering to filter canvas light shadows.
* **CANVAS\_LIGHT\_FILTER\_PCF7** = **3** --- Use PCF7 filtering to filter canvas light shadows.
* **CANVAS\_LIGHT\_FILTER\_PCF9** = **4** --- Use PCF9 filtering to filter canvas light shadows.
* **CANVAS\_LIGHT\_FILTER\_PCF13** = **5** --- Use PCF13 filtering to filter canvas light shadows.
enum **CanvasOccluderPolygonCullMode**:
* **CANVAS\_OCCLUDER\_POLYGON\_CULL\_DISABLED** = **0** --- Culling of the canvas occluder is disabled.
* **CANVAS\_OCCLUDER\_POLYGON\_CULL\_CLOCKWISE** = **1** --- Culling of the canvas occluder is clockwise.
* **CANVAS\_OCCLUDER\_POLYGON\_CULL\_COUNTER\_CLOCKWISE** = **2** --- Culling of the canvas occluder is counterclockwise.
enum **RenderInfo**:
* **INFO\_OBJECTS\_IN\_FRAME** = **0** --- The amount of objects in the frame.
* **INFO\_VERTICES\_IN\_FRAME** = **1** --- The amount of vertices in the frame.
* **INFO\_MATERIAL\_CHANGES\_IN\_FRAME** = **2** --- The amount of modified materials in the frame.
* **INFO\_SHADER\_CHANGES\_IN\_FRAME** = **3** --- The amount of shader rebinds in the frame.
* **INFO\_SHADER\_COMPILES\_IN\_FRAME** = **4** --- The peak amount of shaders that have been under compilation in the frame.
This is useful to know when asynchronous shader compilation has finished for the current shaders on screen.
**Note:** For complete certainty, only assume there are no outstanding compilations when this value is zero for at least two frames in a row.
Unimplemented in the GLES2 rendering backend, always returns 0.
* **INFO\_SURFACE\_CHANGES\_IN\_FRAME** = **5** --- The amount of surface changes in the frame.
* **INFO\_DRAW\_CALLS\_IN\_FRAME** = **6** --- The amount of draw calls in frame.
* **INFO\_2D\_ITEMS\_IN\_FRAME** = **7** --- The amount of 2d items in the frame.
* **INFO\_2D\_DRAW\_CALLS\_IN\_FRAME** = **8** --- The amount of 2d draw calls in frame.
* **INFO\_USAGE\_VIDEO\_MEM\_TOTAL** = **9** --- Unimplemented in the GLES2 and GLES3 rendering backends, always returns 0.
* **INFO\_VIDEO\_MEM\_USED** = **10** --- The amount of video memory used, i.e. texture and vertex memory combined.
* **INFO\_TEXTURE\_MEM\_USED** = **11** --- The amount of texture memory used.
* **INFO\_VERTEX\_MEM\_USED** = **12** --- The amount of vertex memory used.
enum **Features**:
* **FEATURE\_SHADERS** = **0** --- Hardware supports shaders. This enum is currently unused in Godot 3.x.
* **FEATURE\_MULTITHREADED** = **1** --- Hardware supports multithreading. This enum is currently unused in Godot 3.x.
enum **MultimeshTransformFormat**:
* **MULTIMESH\_TRANSFORM\_2D** = **0** --- Use [Transform2D](class_transform2d#class-transform2d) to store MultiMesh transform.
* **MULTIMESH\_TRANSFORM\_3D** = **1** --- Use [Transform](class_transform#class-transform) to store MultiMesh transform.
enum **MultimeshColorFormat**:
* **MULTIMESH\_COLOR\_NONE** = **0** --- MultiMesh does not use per-instance color.
* **MULTIMESH\_COLOR\_8BIT** = **1** --- MultiMesh color uses 8 bits per component. This packs the color into a single float.
* **MULTIMESH\_COLOR\_FLOAT** = **2** --- MultiMesh color uses a float per channel.
enum **MultimeshCustomDataFormat**:
* **MULTIMESH\_CUSTOM\_DATA\_NONE** = **0** --- MultiMesh does not use custom data.
* **MULTIMESH\_CUSTOM\_DATA\_8BIT** = **1** --- MultiMesh custom data uses 8 bits per component. This packs the 4-component custom data into a single float.
* **MULTIMESH\_CUSTOM\_DATA\_FLOAT** = **2** --- MultiMesh custom data uses a float per component.
enum **ReflectionProbeUpdateMode**:
* **REFLECTION\_PROBE\_UPDATE\_ONCE** = **0** --- Reflection probe will update reflections once and then stop.
* **REFLECTION\_PROBE\_UPDATE\_ALWAYS** = **1** --- Reflection probe will update each frame. This mode is necessary to capture moving objects.
enum **ParticlesDrawOrder**:
* **PARTICLES\_DRAW\_ORDER\_INDEX** = **0** --- Draw particles in the order that they appear in the particles array.
* **PARTICLES\_DRAW\_ORDER\_LIFETIME** = **1** --- Sort particles based on their lifetime.
* **PARTICLES\_DRAW\_ORDER\_VIEW\_DEPTH** = **2** --- Sort particles based on their distance to the camera.
enum **EnvironmentBG**:
* **ENV\_BG\_CLEAR\_COLOR** = **0** --- Use the clear color as background.
* **ENV\_BG\_COLOR** = **1** --- Use a specified color as the background.
* **ENV\_BG\_SKY** = **2** --- Use a sky resource for the background.
* **ENV\_BG\_COLOR\_SKY** = **3** --- Use a custom color for background, but use a sky for shading and reflections.
* **ENV\_BG\_CANVAS** = **4** --- Use a specified canvas layer as the background. This can be useful for instantiating a 2D scene in a 3D world.
* **ENV\_BG\_KEEP** = **5** --- Do not clear the background, use whatever was rendered last frame as the background.
* **ENV\_BG\_MAX** = **7** --- Represents the size of the [EnvironmentBG](#enum-visualserver-environmentbg) enum.
enum **EnvironmentDOFBlurQuality**:
* **ENV\_DOF\_BLUR\_QUALITY\_LOW** = **0** --- Use lowest blur quality. Fastest, but may look bad.
* **ENV\_DOF\_BLUR\_QUALITY\_MEDIUM** = **1** --- Use medium blur quality.
* **ENV\_DOF\_BLUR\_QUALITY\_HIGH** = **2** --- Used highest blur quality. Looks the best, but is the slowest.
enum **EnvironmentGlowBlendMode**:
* **GLOW\_BLEND\_MODE\_ADDITIVE** = **0** --- Add the effect of the glow on top of the scene.
* **GLOW\_BLEND\_MODE\_SCREEN** = **1** --- Blends the glow effect with the screen. Does not get as bright as additive.
* **GLOW\_BLEND\_MODE\_SOFTLIGHT** = **2** --- Produces a subtle color disturbance around objects.
* **GLOW\_BLEND\_MODE\_REPLACE** = **3** --- Shows the glow effect by itself without the underlying scene.
enum **EnvironmentToneMapper**:
* **ENV\_TONE\_MAPPER\_LINEAR** = **0** --- Output color as they came in. This can cause bright lighting to look blown out, with noticeable clipping in the output colors.
* **ENV\_TONE\_MAPPER\_REINHARD** = **1** --- Use the Reinhard tonemapper. Performs a variation on rendered pixels' colors by this formula: `color = color / (1 + color)`. This avoids clipping bright highlights, but the resulting image can look a bit dull.
* **ENV\_TONE\_MAPPER\_FILMIC** = **2** --- Use the filmic tonemapper. This avoids clipping bright highlights, with a resulting image that usually looks more vivid than [ENV\_TONE\_MAPPER\_REINHARD](#class-visualserver-constant-env-tone-mapper-reinhard).
* **ENV\_TONE\_MAPPER\_ACES** = **3** --- Use the legacy Godot version of the Academy Color Encoding System tonemapper. Unlike [ENV\_TONE\_MAPPER\_ACES\_FITTED](#class-visualserver-constant-env-tone-mapper-aces-fitted), this version of ACES does not handle bright lighting in a physically accurate way. ACES typically has a more contrasted output compared to [ENV\_TONE\_MAPPER\_REINHARD](#class-visualserver-constant-env-tone-mapper-reinhard) and [ENV\_TONE\_MAPPER\_FILMIC](#class-visualserver-constant-env-tone-mapper-filmic).
**Note:** This tonemapping operator will be removed in Godot 4.0 in favor of the more accurate [ENV\_TONE\_MAPPER\_ACES\_FITTED](#class-visualserver-constant-env-tone-mapper-aces-fitted).
* **ENV\_TONE\_MAPPER\_ACES\_FITTED** = **4** --- Use the Academy Color Encoding System tonemapper. ACES is slightly more expensive than other options, but it handles bright lighting in a more realistic fashion by desaturating it as it becomes brighter. ACES typically has a more contrasted output compared to [ENV\_TONE\_MAPPER\_REINHARD](#class-visualserver-constant-env-tone-mapper-reinhard) and [ENV\_TONE\_MAPPER\_FILMIC](#class-visualserver-constant-env-tone-mapper-filmic).
enum **EnvironmentSSAOQuality**:
* **ENV\_SSAO\_QUALITY\_LOW** = **0** --- Lowest quality of screen space ambient occlusion.
* **ENV\_SSAO\_QUALITY\_MEDIUM** = **1** --- Medium quality screen space ambient occlusion.
* **ENV\_SSAO\_QUALITY\_HIGH** = **2** --- Highest quality screen space ambient occlusion.
enum **EnvironmentSSAOBlur**:
* **ENV\_SSAO\_BLUR\_DISABLED** = **0** --- Disables the blur set for SSAO. Will make SSAO look noisier.
* **ENV\_SSAO\_BLUR\_1x1** = **1** --- Perform a 1x1 blur on the SSAO output.
* **ENV\_SSAO\_BLUR\_2x2** = **2** --- Performs a 2x2 blur on the SSAO output.
* **ENV\_SSAO\_BLUR\_3x3** = **3** --- Performs a 3x3 blur on the SSAO output. Use this for smoothest SSAO.
enum **ChangedPriority**:
* **CHANGED\_PRIORITY\_ANY** = **0** --- Used to query for any changes that request a redraw, whatever the priority.
* **CHANGED\_PRIORITY\_LOW** = **1** --- Registered changes which have low priority can be optionally prevented from causing editor redraws. Examples might include dynamic shaders (typically using the `TIME` built-in).
* **CHANGED\_PRIORITY\_HIGH** = **2** --- Registered changes which can cause a redraw default to high priority.
Constants
---------
* **NO\_INDEX\_ARRAY** = **-1** --- Marks an error that shows that the index array is empty.
* **ARRAY\_WEIGHTS\_SIZE** = **4** --- Number of weights/bones per vertex.
* **CANVAS\_ITEM\_Z\_MIN** = **-4096** --- The minimum Z-layer for canvas items.
* **CANVAS\_ITEM\_Z\_MAX** = **4096** --- The maximum Z-layer for canvas items.
* **MAX\_GLOW\_LEVELS** = **7** --- Max number of glow levels that can be used with glow post-process effect.
* **MAX\_CURSORS** = **8** --- Unused enum in Godot 3.x.
* **MATERIAL\_RENDER\_PRIORITY\_MIN** = **-128** --- The minimum renderpriority of all materials.
* **MATERIAL\_RENDER\_PRIORITY\_MAX** = **127** --- The maximum renderpriority of all materials.
Property Descriptions
---------------------
### [bool](class_bool#class-bool) render\_loop\_enabled
| | |
| --- | --- |
| *Setter* | set\_render\_loop\_enabled(value) |
| *Getter* | is\_render\_loop\_enabled() |
If `false`, disables rendering completely, but the engine logic is still being processed. You can call [force\_draw](#class-visualserver-method-force-draw) to draw a frame even with rendering disabled.
Method Descriptions
-------------------
### void black\_bars\_set\_images ( [RID](class_rid#class-rid) left, [RID](class_rid#class-rid) top, [RID](class_rid#class-rid) right, [RID](class_rid#class-rid) bottom )
Sets images to be rendered in the window margin.
### void black\_bars\_set\_margins ( [int](class_int#class-int) left, [int](class_int#class-int) top, [int](class_int#class-int) right, [int](class_int#class-int) bottom )
Sets margin size, where black bars (or images, if [black\_bars\_set\_images](#class-visualserver-method-black-bars-set-images) was used) are rendered.
### [RID](class_rid#class-rid) camera\_create ( )
Creates a camera and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `camera_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void camera\_set\_cull\_mask ( [RID](class_rid#class-rid) camera, [int](class_int#class-int) layers )
Sets the cull mask associated with this camera. The cull mask describes which 3D layers are rendered by this camera. Equivalent to [Camera.cull\_mask](class_camera#class-camera-property-cull-mask).
### void camera\_set\_environment ( [RID](class_rid#class-rid) camera, [RID](class_rid#class-rid) env )
Sets the environment used by this camera. Equivalent to [Camera.environment](class_camera#class-camera-property-environment).
### void camera\_set\_frustum ( [RID](class_rid#class-rid) camera, [float](class_float#class-float) size, [Vector2](class_vector2#class-vector2) offset, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far )
Sets camera to use frustum projection. This mode allows adjusting the `offset` argument to create "tilted frustum" effects.
### void camera\_set\_orthogonal ( [RID](class_rid#class-rid) camera, [float](class_float#class-float) size, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far )
Sets camera to use orthogonal projection, also known as orthographic projection. Objects remain the same size on the screen no matter how far away they are.
### void camera\_set\_perspective ( [RID](class_rid#class-rid) camera, [float](class_float#class-float) fovy\_degrees, [float](class_float#class-float) z\_near, [float](class_float#class-float) z\_far )
Sets camera to use perspective projection. Objects on the screen becomes smaller when they are far away.
### void camera\_set\_transform ( [RID](class_rid#class-rid) camera, [Transform](class_transform#class-transform) transform )
Sets [Transform](class_transform#class-transform) of camera.
### void camera\_set\_use\_vertical\_aspect ( [RID](class_rid#class-rid) camera, [bool](class_bool#class-bool) enable )
If `true`, preserves the horizontal aspect ratio which is equivalent to [Camera.KEEP\_WIDTH](class_camera#class-camera-constant-keep-width). If `false`, preserves the vertical aspect ratio which is equivalent to [Camera.KEEP\_HEIGHT](class_camera#class-camera-constant-keep-height).
### [RID](class_rid#class-rid) canvas\_create ( )
Creates a canvas and returns the assigned [RID](class_rid#class-rid). It can be accessed with the RID that is returned. This RID will be used in all `canvas_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void canvas\_item\_add\_circle ( [RID](class_rid#class-rid) item, [Vector2](class_vector2#class-vector2) pos, [float](class_float#class-float) radius, [Color](class_color#class-color) color )
Adds a circle command to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_clip\_ignore ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) ignore )
If ignore is `true`, the VisualServer does not perform clipping.
### void canvas\_item\_add\_line ( [RID](class_rid#class-rid) item, [Vector2](class_vector2#class-vector2) from, [Vector2](class_vector2#class-vector2) to, [Color](class_color#class-color) color, [float](class_float#class-float) width=1.0, [bool](class_bool#class-bool) antialiased=false )
Adds a line command to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_mesh ( [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) mesh, [Transform2D](class_transform2d#class-transform2d) transform=Transform2D( 1, 0, 0, 1, 0, 0 ), [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map )
Adds a mesh command to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_multimesh ( [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) mesh, [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map )
Adds a [MultiMesh](class_multimesh#class-multimesh) to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands. Only affects its aabb at the moment.
### void canvas\_item\_add\_nine\_patch ( [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [Rect2](class_rect2#class-rect2) source, [RID](class_rid#class-rid) texture, [Vector2](class_vector2#class-vector2) topleft, [Vector2](class_vector2#class-vector2) bottomright, [NinePatchAxisMode](#enum-visualserver-ninepatchaxismode) x\_axis\_mode=0, [NinePatchAxisMode](#enum-visualserver-ninepatchaxismode) y\_axis\_mode=0, [bool](class_bool#class-bool) draw\_center=true, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [RID](class_rid#class-rid) normal\_map )
Adds a nine patch image to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
See [NinePatchRect](class_ninepatchrect#class-ninepatchrect) for more explanation.
### void canvas\_item\_add\_particles ( [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) particles, [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map )
Adds a particle system to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_polygon ( [RID](class_rid#class-rid) item, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [PoolVector2Array](class_poolvector2array#class-poolvector2array) uvs=PoolVector2Array( ), [RID](class_rid#class-rid) texture, [RID](class_rid#class-rid) normal\_map, [bool](class_bool#class-bool) antialiased=false )
Adds a polygon to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_polyline ( [RID](class_rid#class-rid) item, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [float](class_float#class-float) width=1.0, [bool](class_bool#class-bool) antialiased=false )
Adds a polyline, which is a line from multiple points with a width, to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_primitive ( [RID](class_rid#class-rid) item, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [PoolVector2Array](class_poolvector2array#class-poolvector2array) uvs, [RID](class_rid#class-rid) texture, [float](class_float#class-float) width=1.0, [RID](class_rid#class-rid) normal\_map )
Adds a primitive to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_rect ( [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [Color](class_color#class-color) color )
Adds a rectangle to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_set\_transform ( [RID](class_rid#class-rid) item, [Transform2D](class_transform2d#class-transform2d) transform )
Adds a [Transform2D](class_transform2d#class-transform2d) command to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
This sets the extra\_matrix uniform when executed. This affects the later commands of the canvas item.
### void canvas\_item\_add\_texture\_rect ( [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [RID](class_rid#class-rid) texture, [bool](class_bool#class-bool) tile=false, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [RID](class_rid#class-rid) normal\_map )
Adds a textured rect to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_texture\_rect\_region ( [RID](class_rid#class-rid) item, [Rect2](class_rect2#class-rect2) rect, [RID](class_rid#class-rid) texture, [Rect2](class_rect2#class-rect2) src\_rect, [Color](class_color#class-color) modulate=Color( 1, 1, 1, 1 ), [bool](class_bool#class-bool) transpose=false, [RID](class_rid#class-rid) normal\_map, [bool](class_bool#class-bool) clip\_uv=true )
Adds a texture rect with region setting to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_add\_triangle\_array ( [RID](class_rid#class-rid) item, [PoolIntArray](class_poolintarray#class-poolintarray) indices, [PoolVector2Array](class_poolvector2array#class-poolvector2array) points, [PoolColorArray](class_poolcolorarray#class-poolcolorarray) colors, [PoolVector2Array](class_poolvector2array#class-poolvector2array) uvs=PoolVector2Array( ), [PoolIntArray](class_poolintarray#class-poolintarray) bones=PoolIntArray( ), [PoolRealArray](class_poolrealarray#class-poolrealarray) weights=PoolRealArray( ), [RID](class_rid#class-rid) texture, [int](class_int#class-int) count=-1, [RID](class_rid#class-rid) normal\_map, [bool](class_bool#class-bool) antialiased=false, [bool](class_bool#class-bool) antialiasing\_use\_indices=false )
Adds a triangle array to the [CanvasItem](class_canvasitem#class-canvasitem)'s draw commands.
### void canvas\_item\_clear ( [RID](class_rid#class-rid) item )
Clears the [CanvasItem](class_canvasitem#class-canvasitem) and removes all commands in it.
### [RID](class_rid#class-rid) canvas\_item\_create ( )
Creates a new [CanvasItem](class_canvasitem#class-canvasitem) and returns its [RID](class_rid#class-rid). It can be accessed with the RID that is returned. This RID will be used in all `canvas_item_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void canvas\_item\_set\_clip ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) clip )
Sets clipping for the [CanvasItem](class_canvasitem#class-canvasitem).
### void canvas\_item\_set\_copy\_to\_backbuffer ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled, [Rect2](class_rect2#class-rect2) rect )
Sets the [CanvasItem](class_canvasitem#class-canvasitem) to copy a rect to the backbuffer.
### void canvas\_item\_set\_custom\_rect ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) use\_custom\_rect, [Rect2](class_rect2#class-rect2) rect=Rect2( 0, 0, 0, 0 ) )
Defines a custom drawing rectangle for the [CanvasItem](class_canvasitem#class-canvasitem).
### void canvas\_item\_set\_distance\_field\_mode ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled )
Enables the use of distance fields for GUI elements that are rendering distance field based fonts.
### void canvas\_item\_set\_draw\_behind\_parent ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled )
Sets [CanvasItem](class_canvasitem#class-canvasitem) to be drawn behind its parent.
### void canvas\_item\_set\_draw\_index ( [RID](class_rid#class-rid) item, [int](class_int#class-int) index )
Sets the index for the [CanvasItem](class_canvasitem#class-canvasitem).
### void canvas\_item\_set\_light\_mask ( [RID](class_rid#class-rid) item, [int](class_int#class-int) mask )
The light mask. See [LightOccluder2D](class_lightoccluder2d#class-lightoccluder2d) for more information on light masks.
### void canvas\_item\_set\_material ( [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) material )
Sets a new material to the [CanvasItem](class_canvasitem#class-canvasitem).
### void canvas\_item\_set\_modulate ( [RID](class_rid#class-rid) item, [Color](class_color#class-color) color )
Sets the color that modulates the [CanvasItem](class_canvasitem#class-canvasitem) and its children.
### void canvas\_item\_set\_parent ( [RID](class_rid#class-rid) item, [RID](class_rid#class-rid) parent )
Sets the parent for the [CanvasItem](class_canvasitem#class-canvasitem). The parent can be another canvas item, or it can be the root canvas that is attached to the viewport.
### void canvas\_item\_set\_self\_modulate ( [RID](class_rid#class-rid) item, [Color](class_color#class-color) color )
Sets the color that modulates the [CanvasItem](class_canvasitem#class-canvasitem) without children.
### void canvas\_item\_set\_sort\_children\_by\_y ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled )
Sets if [CanvasItem](class_canvasitem#class-canvasitem)'s children should be sorted by y-position.
### void canvas\_item\_set\_transform ( [RID](class_rid#class-rid) item, [Transform2D](class_transform2d#class-transform2d) transform )
Sets the [CanvasItem](class_canvasitem#class-canvasitem)'s [Transform2D](class_transform2d#class-transform2d).
### void canvas\_item\_set\_use\_parent\_material ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled )
Sets if the [CanvasItem](class_canvasitem#class-canvasitem) uses its parent's material.
### void canvas\_item\_set\_visible ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) visible )
Sets if the canvas item (including its children) is visible.
### void canvas\_item\_set\_z\_as\_relative\_to\_parent ( [RID](class_rid#class-rid) item, [bool](class_bool#class-bool) enabled )
If this is enabled, the Z index of the parent will be added to the children's Z index.
### void canvas\_item\_set\_z\_index ( [RID](class_rid#class-rid) item, [int](class_int#class-int) z\_index )
Sets the [CanvasItem](class_canvasitem#class-canvasitem)'s Z index, i.e. its draw order (lower indexes are drawn first).
### void canvas\_light\_attach\_to\_canvas ( [RID](class_rid#class-rid) light, [RID](class_rid#class-rid) canvas )
Attaches the canvas light to the canvas. Removes it from its previous canvas.
### [RID](class_rid#class-rid) canvas\_light\_create ( )
Creates a canvas light and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `canvas_light_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void canvas\_light\_occluder\_attach\_to\_canvas ( [RID](class_rid#class-rid) occluder, [RID](class_rid#class-rid) canvas )
Attaches a light occluder to the canvas. Removes it from its previous canvas.
### [RID](class_rid#class-rid) canvas\_light\_occluder\_create ( )
Creates a light occluder and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `canvas_light_ocluder_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void canvas\_light\_occluder\_set\_enabled ( [RID](class_rid#class-rid) occluder, [bool](class_bool#class-bool) enabled )
Enables or disables light occluder.
### void canvas\_light\_occluder\_set\_light\_mask ( [RID](class_rid#class-rid) occluder, [int](class_int#class-int) mask )
The light mask. See [LightOccluder2D](class_lightoccluder2d#class-lightoccluder2d) for more information on light masks.
### void canvas\_light\_occluder\_set\_polygon ( [RID](class_rid#class-rid) occluder, [RID](class_rid#class-rid) polygon )
Sets a light occluder's polygon.
### void canvas\_light\_occluder\_set\_transform ( [RID](class_rid#class-rid) occluder, [Transform2D](class_transform2d#class-transform2d) transform )
Sets a light occluder's [Transform2D](class_transform2d#class-transform2d).
### void canvas\_light\_set\_color ( [RID](class_rid#class-rid) light, [Color](class_color#class-color) color )
Sets the color for a light.
### void canvas\_light\_set\_enabled ( [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled )
Enables or disables a canvas light.
### void canvas\_light\_set\_energy ( [RID](class_rid#class-rid) light, [float](class_float#class-float) energy )
Sets a canvas light's energy.
### void canvas\_light\_set\_height ( [RID](class_rid#class-rid) light, [float](class_float#class-float) height )
Sets a canvas light's height.
### void canvas\_light\_set\_item\_cull\_mask ( [RID](class_rid#class-rid) light, [int](class_int#class-int) mask )
The light mask. See [LightOccluder2D](class_lightoccluder2d#class-lightoccluder2d) for more information on light masks.
### void canvas\_light\_set\_item\_shadow\_cull\_mask ( [RID](class_rid#class-rid) light, [int](class_int#class-int) mask )
The binary mask used to determine which layers this canvas light's shadows affects. See [LightOccluder2D](class_lightoccluder2d#class-lightoccluder2d) for more information on light masks.
### void canvas\_light\_set\_layer\_range ( [RID](class_rid#class-rid) light, [int](class_int#class-int) min\_layer, [int](class_int#class-int) max\_layer )
The layer range that gets rendered with this light.
### void canvas\_light\_set\_mode ( [RID](class_rid#class-rid) light, [CanvasLightMode](#enum-visualserver-canvaslightmode) mode )
The mode of the light, see [CanvasLightMode](#enum-visualserver-canvaslightmode) constants.
### void canvas\_light\_set\_scale ( [RID](class_rid#class-rid) light, [float](class_float#class-float) scale )
Sets the texture's scale factor of the light. Equivalent to [Light2D.texture\_scale](class_light2d#class-light2d-property-texture-scale).
### void canvas\_light\_set\_shadow\_buffer\_size ( [RID](class_rid#class-rid) light, [int](class_int#class-int) size )
Sets the width of the shadow buffer, size gets scaled to the next power of two for this.
### void canvas\_light\_set\_shadow\_color ( [RID](class_rid#class-rid) light, [Color](class_color#class-color) color )
Sets the color of the canvas light's shadow.
### void canvas\_light\_set\_shadow\_enabled ( [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled )
Enables or disables the canvas light's shadow.
### void canvas\_light\_set\_shadow\_filter ( [RID](class_rid#class-rid) light, [CanvasLightShadowFilter](#enum-visualserver-canvaslightshadowfilter) filter )
Sets the canvas light's shadow's filter, see [CanvasLightShadowFilter](#enum-visualserver-canvaslightshadowfilter) constants.
### void canvas\_light\_set\_shadow\_gradient\_length ( [RID](class_rid#class-rid) light, [float](class_float#class-float) length )
Sets the length of the shadow's gradient.
### void canvas\_light\_set\_shadow\_smooth ( [RID](class_rid#class-rid) light, [float](class_float#class-float) smooth )
Smoothens the shadow. The lower, the smoother.
### void canvas\_light\_set\_texture ( [RID](class_rid#class-rid) light, [RID](class_rid#class-rid) texture )
Sets texture to be used by light. Equivalent to [Light2D.texture](class_light2d#class-light2d-property-texture).
### void canvas\_light\_set\_texture\_offset ( [RID](class_rid#class-rid) light, [Vector2](class_vector2#class-vector2) offset )
Sets the offset of the light's texture. Equivalent to [Light2D.offset](class_light2d#class-light2d-property-offset).
### void canvas\_light\_set\_transform ( [RID](class_rid#class-rid) light, [Transform2D](class_transform2d#class-transform2d) transform )
Sets the canvas light's [Transform2D](class_transform2d#class-transform2d).
### void canvas\_light\_set\_z\_range ( [RID](class_rid#class-rid) light, [int](class_int#class-int) min\_z, [int](class_int#class-int) max\_z )
Sets the Z range of objects that will be affected by this light. Equivalent to [Light2D.range\_z\_min](class_light2d#class-light2d-property-range-z-min) and [Light2D.range\_z\_max](class_light2d#class-light2d-property-range-z-max).
### [RID](class_rid#class-rid) canvas\_occluder\_polygon\_create ( )
Creates a new light occluder polygon and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `canvas_occluder_polygon_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void canvas\_occluder\_polygon\_set\_cull\_mode ( [RID](class_rid#class-rid) occluder\_polygon, [CanvasOccluderPolygonCullMode](#enum-visualserver-canvasoccluderpolygoncullmode) mode )
Sets an occluder polygons cull mode. See [CanvasOccluderPolygonCullMode](#enum-visualserver-canvasoccluderpolygoncullmode) constants.
### void canvas\_occluder\_polygon\_set\_shape ( [RID](class_rid#class-rid) occluder\_polygon, [PoolVector2Array](class_poolvector2array#class-poolvector2array) shape, [bool](class_bool#class-bool) closed )
Sets the shape of the occluder polygon.
### void canvas\_occluder\_polygon\_set\_shape\_as\_lines ( [RID](class_rid#class-rid) occluder\_polygon, [PoolVector2Array](class_poolvector2array#class-poolvector2array) shape )
Sets the shape of the occluder polygon as lines.
### void canvas\_set\_item\_mirroring ( [RID](class_rid#class-rid) canvas, [RID](class_rid#class-rid) item, [Vector2](class_vector2#class-vector2) mirroring )
A copy of the canvas item will be drawn with a local offset of the mirroring [Vector2](class_vector2#class-vector2).
### void canvas\_set\_modulate ( [RID](class_rid#class-rid) canvas, [Color](class_color#class-color) color )
Modulates all colors in the given canvas.
### [RID](class_rid#class-rid) directional\_light\_create ( )
Creates a directional light and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID can be used in most `light_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this directional light to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### void draw ( [bool](class_bool#class-bool) swap\_buffers=true, [float](class_float#class-float) frame\_step=0.0 )
Draws a frame. *This method is deprecated*, please use [force\_draw](#class-visualserver-method-force-draw) instead.
### [RID](class_rid#class-rid) environment\_create ( )
Creates an environment and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `environment_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void environment\_set\_adjustment ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) brightness, [float](class_float#class-float) contrast, [float](class_float#class-float) saturation, [RID](class_rid#class-rid) ramp )
Sets the values to be used with the "Adjustment" post-process effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_ambient\_light ( [RID](class_rid#class-rid) env, [Color](class_color#class-color) color, [float](class_float#class-float) energy=1.0, [float](class_float#class-float) sky\_contibution=0.0 )
Sets the ambient light parameters. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_background ( [RID](class_rid#class-rid) env, [EnvironmentBG](#enum-visualserver-environmentbg) bg )
Sets the *BGMode* of the environment. Equivalent to [Environment.background\_mode](class_environment#class-environment-property-background-mode).
### void environment\_set\_bg\_color ( [RID](class_rid#class-rid) env, [Color](class_color#class-color) color )
Color displayed for clear areas of the scene (if using Custom color or Color+Sky background modes).
### void environment\_set\_bg\_energy ( [RID](class_rid#class-rid) env, [float](class_float#class-float) energy )
Sets the intensity of the background color.
### void environment\_set\_canvas\_max\_layer ( [RID](class_rid#class-rid) env, [int](class_int#class-int) max\_layer )
Sets the maximum layer to use if using Canvas background mode.
### void environment\_set\_dof\_blur\_far ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) distance, [float](class_float#class-float) transition, [float](class_float#class-float) far\_amount, [EnvironmentDOFBlurQuality](#enum-visualserver-environmentdofblurquality) quality )
Sets the values to be used with the "DoF Far Blur" post-process effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_dof\_blur\_near ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) distance, [float](class_float#class-float) transition, [float](class_float#class-float) far\_amount, [EnvironmentDOFBlurQuality](#enum-visualserver-environmentdofblurquality) quality )
Sets the values to be used with the "DoF Near Blur" post-process effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_fog ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [Color](class_color#class-color) color, [Color](class_color#class-color) sun\_color, [float](class_float#class-float) sun\_amount )
Sets the variables to be used with the scene fog. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_fog\_depth ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) depth\_begin, [float](class_float#class-float) depth\_end, [float](class_float#class-float) depth\_curve, [bool](class_bool#class-bool) transmit, [float](class_float#class-float) transmit\_curve )
Sets the variables to be used with the fog depth effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_fog\_height ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) min\_height, [float](class_float#class-float) max\_height, [float](class_float#class-float) height\_curve )
Sets the variables to be used with the fog height effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_glow ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [int](class_int#class-int) level\_flags, [float](class_float#class-float) intensity, [float](class_float#class-float) strength, [float](class_float#class-float) bloom\_threshold, [EnvironmentGlowBlendMode](#enum-visualserver-environmentglowblendmode) blend\_mode, [float](class_float#class-float) hdr\_bleed\_threshold, [float](class_float#class-float) hdr\_bleed\_scale, [float](class_float#class-float) hdr\_luminance\_cap, [bool](class_bool#class-bool) bicubic\_upscale, [bool](class_bool#class-bool) high\_quality )
Sets the variables to be used with the "glow" post-process effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_sky ( [RID](class_rid#class-rid) env, [RID](class_rid#class-rid) sky )
Sets the [Sky](class_sky#class-sky) to be used as the environment's background when using *BGMode* sky. Equivalent to [Environment.background\_sky](class_environment#class-environment-property-background-sky).
### void environment\_set\_sky\_custom\_fov ( [RID](class_rid#class-rid) env, [float](class_float#class-float) scale )
Sets a custom field of view for the background [Sky](class_sky#class-sky). Equivalent to [Environment.background\_sky\_custom\_fov](class_environment#class-environment-property-background-sky-custom-fov).
### void environment\_set\_sky\_orientation ( [RID](class_rid#class-rid) env, [Basis](class_basis#class-basis) orientation )
Sets the rotation of the background [Sky](class_sky#class-sky) expressed as a [Basis](class_basis#class-basis). Equivalent to [Environment.background\_sky\_orientation](class_environment#class-environment-property-background-sky-orientation).
### void environment\_set\_ssao ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [float](class_float#class-float) radius, [float](class_float#class-float) intensity, [float](class_float#class-float) radius2, [float](class_float#class-float) intensity2, [float](class_float#class-float) bias, [float](class_float#class-float) light\_affect, [float](class_float#class-float) ao\_channel\_affect, [Color](class_color#class-color) color, [EnvironmentSSAOQuality](#enum-visualserver-environmentssaoquality) quality, [EnvironmentSSAOBlur](#enum-visualserver-environmentssaoblur) blur, [float](class_float#class-float) bilateral\_sharpness )
Sets the variables to be used with the "Screen Space Ambient Occlusion (SSAO)" post-process effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_ssr ( [RID](class_rid#class-rid) env, [bool](class_bool#class-bool) enable, [int](class_int#class-int) max\_steps, [float](class_float#class-float) fade\_in, [float](class_float#class-float) fade\_out, [float](class_float#class-float) depth\_tolerance, [bool](class_bool#class-bool) roughness )
Sets the variables to be used with the "screen space reflections" post-process effect. See [Environment](class_environment#class-environment) for more details.
### void environment\_set\_tonemap ( [RID](class_rid#class-rid) env, [EnvironmentToneMapper](#enum-visualserver-environmenttonemapper) tone\_mapper, [float](class_float#class-float) exposure, [float](class_float#class-float) white, [bool](class_bool#class-bool) auto\_exposure, [float](class_float#class-float) min\_luminance, [float](class_float#class-float) max\_luminance, [float](class_float#class-float) auto\_exp\_speed, [float](class_float#class-float) auto\_exp\_grey )
Sets the variables to be used with the "tonemap" post-process effect. See [Environment](class_environment#class-environment) for more details.
### void finish ( )
Removes buffers and clears testcubes.
### void force\_draw ( [bool](class_bool#class-bool) swap\_buffers=true, [float](class_float#class-float) frame\_step=0.0 )
Forces a frame to be drawn when the function is called. Drawing a frame updates all [Viewport](class_viewport#class-viewport)s that are set to update. Use with extreme caution.
### void force\_sync ( )
Synchronizes threads.
### void free\_rid ( [RID](class_rid#class-rid) rid )
Tries to free an object in the VisualServer.
### [int](class_int#class-int) get\_render\_info ( [RenderInfo](#enum-visualserver-renderinfo) info )
Returns a certain information, see [RenderInfo](#enum-visualserver-renderinfo) for options.
### [RID](class_rid#class-rid) get\_test\_cube ( )
Returns the id of the test cube. Creates one if none exists.
### [RID](class_rid#class-rid) get\_test\_texture ( )
Returns the id of the test texture. Creates one if none exists.
### [String](class_string#class-string) get\_video\_adapter\_name ( ) const
Returns the name of the video adapter (e.g. "GeForce GTX 1080/PCIe/SSE2").
**Note:** When running a headless or server binary, this function returns an empty string.
### [String](class_string#class-string) get\_video\_adapter\_vendor ( ) const
Returns the vendor of the video adapter (e.g. "NVIDIA Corporation").
**Note:** When running a headless or server binary, this function returns an empty string.
### [RID](class_rid#class-rid) get\_white\_texture ( )
Returns the id of a white texture. Creates one if none exists.
### [RID](class_rid#class-rid) gi\_probe\_create ( )
Creates a GI probe and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `gi_probe_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this GI probe to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### [float](class_float#class-float) gi\_probe\_get\_bias ( [RID](class_rid#class-rid) probe ) const
Returns the bias value for the GI probe. Bias is used to avoid self occlusion. Equivalent to [GIProbeData.bias](class_giprobedata#class-giprobedata-property-bias).
### [AABB](class_aabb#class-aabb) gi\_probe\_get\_bounds ( [RID](class_rid#class-rid) probe ) const
Returns the axis-aligned bounding box that covers the full extent of the GI probe.
### [float](class_float#class-float) gi\_probe\_get\_cell\_size ( [RID](class_rid#class-rid) probe ) const
Returns the cell size set by [gi\_probe\_set\_cell\_size](#class-visualserver-method-gi-probe-set-cell-size).
### [PoolIntArray](class_poolintarray#class-poolintarray) gi\_probe\_get\_dynamic\_data ( [RID](class_rid#class-rid) probe ) const
Returns the data used by the GI probe.
### [int](class_int#class-int) gi\_probe\_get\_dynamic\_range ( [RID](class_rid#class-rid) probe ) const
Returns the dynamic range set for this GI probe. Equivalent to [GIProbe.dynamic\_range](class_giprobe#class-giprobe-property-dynamic-range).
### [float](class_float#class-float) gi\_probe\_get\_energy ( [RID](class_rid#class-rid) probe ) const
Returns the energy multiplier for this GI probe. Equivalent to [GIProbe.energy](class_giprobe#class-giprobe-property-energy).
### [float](class_float#class-float) gi\_probe\_get\_normal\_bias ( [RID](class_rid#class-rid) probe ) const
Returns the normal bias for this GI probe. Equivalent to [GIProbe.normal\_bias](class_giprobe#class-giprobe-property-normal-bias).
### [float](class_float#class-float) gi\_probe\_get\_propagation ( [RID](class_rid#class-rid) probe ) const
Returns the propagation value for this GI probe. Equivalent to [GIProbe.propagation](class_giprobe#class-giprobe-property-propagation).
### [Transform](class_transform#class-transform) gi\_probe\_get\_to\_cell\_xform ( [RID](class_rid#class-rid) probe ) const
Returns the Transform set by [gi\_probe\_set\_to\_cell\_xform](#class-visualserver-method-gi-probe-set-to-cell-xform).
### [bool](class_bool#class-bool) gi\_probe\_is\_compressed ( [RID](class_rid#class-rid) probe ) const
Returns `true` if the GI probe data associated with this GI probe is compressed. Equivalent to [GIProbe.compress](class_giprobe#class-giprobe-property-compress).
### [bool](class_bool#class-bool) gi\_probe\_is\_interior ( [RID](class_rid#class-rid) probe ) const
Returns `true` if the GI probe is set to interior, meaning it does not account for sky light. Equivalent to [GIProbe.interior](class_giprobe#class-giprobe-property-interior).
### void gi\_probe\_set\_bias ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) bias )
Sets the bias value to avoid self-occlusion. Equivalent to [GIProbe.bias](class_giprobe#class-giprobe-property-bias).
### void gi\_probe\_set\_bounds ( [RID](class_rid#class-rid) probe, [AABB](class_aabb#class-aabb) bounds )
Sets the axis-aligned bounding box that covers the extent of the GI probe.
### void gi\_probe\_set\_cell\_size ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) range )
Sets the size of individual cells within the GI probe.
### void gi\_probe\_set\_compress ( [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable )
Sets the compression setting for the GI probe data. Compressed data will take up less space but may look worse. Equivalent to [GIProbe.compress](class_giprobe#class-giprobe-property-compress).
### void gi\_probe\_set\_dynamic\_data ( [RID](class_rid#class-rid) probe, [PoolIntArray](class_poolintarray#class-poolintarray) data )
Sets the data to be used in the GI probe for lighting calculations. Normally this is created and called internally within the [GIProbe](class_giprobe#class-giprobe) node. You should not try to set this yourself.
### void gi\_probe\_set\_dynamic\_range ( [RID](class_rid#class-rid) probe, [int](class_int#class-int) range )
Sets the dynamic range of the GI probe. Dynamic range sets the limit for how bright lights can be. A smaller range captures greater detail but limits how bright lights can be. Equivalent to [GIProbe.dynamic\_range](class_giprobe#class-giprobe-property-dynamic-range).
### void gi\_probe\_set\_energy ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) energy )
Sets the energy multiplier for this GI probe. A higher energy makes the indirect light from the GI probe brighter. Equivalent to [GIProbe.energy](class_giprobe#class-giprobe-property-energy).
### void gi\_probe\_set\_interior ( [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable )
Sets the interior value of this GI probe. A GI probe set to interior does not include the sky when calculating lighting. Equivalent to [GIProbe.interior](class_giprobe#class-giprobe-property-interior).
### void gi\_probe\_set\_normal\_bias ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) bias )
Sets the normal bias for this GI probe. Normal bias behaves similar to the other form of bias and may help reduce self-occlusion. Equivalent to [GIProbe.normal\_bias](class_giprobe#class-giprobe-property-normal-bias).
### void gi\_probe\_set\_propagation ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) propagation )
Sets the propagation of light within this GI probe. Equivalent to [GIProbe.propagation](class_giprobe#class-giprobe-property-propagation).
### void gi\_probe\_set\_to\_cell\_xform ( [RID](class_rid#class-rid) probe, [Transform](class_transform#class-transform) xform )
Sets the to cell [Transform](class_transform#class-transform) for this GI probe.
### [bool](class_bool#class-bool) has\_changed ( [ChangedPriority](#enum-visualserver-changedpriority) queried\_priority=0 ) const
Returns `true` if changes have been made to the VisualServer's data. [draw](#class-visualserver-method-draw) is usually called if this happens.
As changes are registered as either high or low priority (e.g. dynamic shaders), this function takes an optional argument to query either low or high priority changes, or any changes.
### [bool](class_bool#class-bool) has\_feature ( [Features](#enum-visualserver-features) feature ) const
Not yet implemented. Always returns `false`.
### [bool](class_bool#class-bool) has\_os\_feature ( [String](class_string#class-string) feature ) const
Returns `true` if the OS supports a certain feature. Features might be `s3tc`, `etc`, `etc2`, `pvrtc` and `skinning_fallback`.
When rendering with GLES2, returns `true` with `skinning_fallback` in case the hardware doesn't support the default GPU skinning process.
### void immediate\_begin ( [RID](class_rid#class-rid) immediate, [PrimitiveType](#enum-visualserver-primitivetype) primitive, [RID](class_rid#class-rid) texture )
Sets up [ImmediateGeometry](class_immediategeometry#class-immediategeometry) internals to prepare for drawing. Equivalent to [ImmediateGeometry.begin](class_immediategeometry#class-immediategeometry-method-begin).
### void immediate\_clear ( [RID](class_rid#class-rid) immediate )
Clears everything that was set up between [immediate\_begin](#class-visualserver-method-immediate-begin) and [immediate\_end](#class-visualserver-method-immediate-end). Equivalent to [ImmediateGeometry.clear](class_immediategeometry#class-immediategeometry-method-clear).
### void immediate\_color ( [RID](class_rid#class-rid) immediate, [Color](class_color#class-color) color )
Sets the color to be used with next vertex. Equivalent to [ImmediateGeometry.set\_color](class_immediategeometry#class-immediategeometry-method-set-color).
### [RID](class_rid#class-rid) immediate\_create ( )
Creates an immediate geometry and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `immediate_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this immediate geometry to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### void immediate\_end ( [RID](class_rid#class-rid) immediate )
Ends drawing the [ImmediateGeometry](class_immediategeometry#class-immediategeometry) and displays it. Equivalent to [ImmediateGeometry.end](class_immediategeometry#class-immediategeometry-method-end).
### [RID](class_rid#class-rid) immediate\_get\_material ( [RID](class_rid#class-rid) immediate ) const
Returns the material assigned to the [ImmediateGeometry](class_immediategeometry#class-immediategeometry).
### void immediate\_normal ( [RID](class_rid#class-rid) immediate, [Vector3](class_vector3#class-vector3) normal )
Sets the normal to be used with next vertex. Equivalent to [ImmediateGeometry.set\_normal](class_immediategeometry#class-immediategeometry-method-set-normal).
### void immediate\_set\_material ( [RID](class_rid#class-rid) immediate, [RID](class_rid#class-rid) material )
Sets the material to be used to draw the [ImmediateGeometry](class_immediategeometry#class-immediategeometry).
### void immediate\_tangent ( [RID](class_rid#class-rid) immediate, [Plane](class_plane#class-plane) tangent )
Sets the tangent to be used with next vertex. Equivalent to [ImmediateGeometry.set\_tangent](class_immediategeometry#class-immediategeometry-method-set-tangent).
### void immediate\_uv ( [RID](class_rid#class-rid) immediate, [Vector2](class_vector2#class-vector2) tex\_uv )
Sets the UV to be used with next vertex. Equivalent to [ImmediateGeometry.set\_uv](class_immediategeometry#class-immediategeometry-method-set-uv).
### void immediate\_uv2 ( [RID](class_rid#class-rid) immediate, [Vector2](class_vector2#class-vector2) tex\_uv )
Sets the UV2 to be used with next vertex. Equivalent to [ImmediateGeometry.set\_uv2](class_immediategeometry#class-immediategeometry-method-set-uv2).
### void immediate\_vertex ( [RID](class_rid#class-rid) immediate, [Vector3](class_vector3#class-vector3) vertex )
Adds the next vertex using the information provided in advance. Equivalent to [ImmediateGeometry.add\_vertex](class_immediategeometry#class-immediategeometry-method-add-vertex).
### void immediate\_vertex\_2d ( [RID](class_rid#class-rid) immediate, [Vector2](class_vector2#class-vector2) vertex )
Adds the next vertex using the information provided in advance. This is a helper class that calls [immediate\_vertex](#class-visualserver-method-immediate-vertex) under the hood. Equivalent to [ImmediateGeometry.add\_vertex](class_immediategeometry#class-immediategeometry-method-add-vertex).
### void init ( )
Initializes the visual server. This function is called internally by platform-dependent code during engine initialization. If called from a running game, it will not do anything.
### void instance\_attach\_object\_instance\_id ( [RID](class_rid#class-rid) instance, [int](class_int#class-int) id )
Attaches a unique Object ID to instance. Object ID must be attached to instance for proper culling with [instances\_cull\_aabb](#class-visualserver-method-instances-cull-aabb), [instances\_cull\_convex](#class-visualserver-method-instances-cull-convex), and [instances\_cull\_ray](#class-visualserver-method-instances-cull-ray).
### void instance\_attach\_skeleton ( [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) skeleton )
Attaches a skeleton to an instance. Removes the previous skeleton from the instance.
### [RID](class_rid#class-rid) instance\_create ( )
Creates a visual instance and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `instance_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
An instance is a way of placing a 3D object in the scenario. Objects like particles, meshes, and reflection probes need to be associated with an instance to be visible in the scenario using [instance\_set\_base](#class-visualserver-method-instance-set-base).
### [RID](class_rid#class-rid) instance\_create2 ( [RID](class_rid#class-rid) base, [RID](class_rid#class-rid) scenario )
Creates a visual instance, adds it to the VisualServer, and sets both base and scenario. It can be accessed with the RID that is returned. This RID will be used in all `instance_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void instance\_geometry\_set\_as\_instance\_lod ( [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) as\_lod\_of\_instance )
Not implemented in Godot 3.x.
### void instance\_geometry\_set\_cast\_shadows\_setting ( [RID](class_rid#class-rid) instance, [ShadowCastingSetting](#enum-visualserver-shadowcastingsetting) shadow\_casting\_setting )
Sets the shadow casting setting to one of [ShadowCastingSetting](#enum-visualserver-shadowcastingsetting). Equivalent to [GeometryInstance.cast\_shadow](class_geometryinstance#class-geometryinstance-property-cast-shadow).
### void instance\_geometry\_set\_draw\_range ( [RID](class_rid#class-rid) instance, [float](class_float#class-float) min, [float](class_float#class-float) max, [float](class_float#class-float) min\_margin, [float](class_float#class-float) max\_margin )
Not implemented in Godot 3.x.
### void instance\_geometry\_set\_flag ( [RID](class_rid#class-rid) instance, [InstanceFlags](#enum-visualserver-instanceflags) flag, [bool](class_bool#class-bool) enabled )
Sets the flag for a given [InstanceFlags](#enum-visualserver-instanceflags). See [InstanceFlags](#enum-visualserver-instanceflags) for more details.
### void instance\_geometry\_set\_material\_overlay ( [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) material )
Sets a material that will be rendered for all surfaces on top of active materials for the mesh associated with this instance. Equivalent to [GeometryInstance.material\_overlay](class_geometryinstance#class-geometryinstance-property-material-overlay).
### void instance\_geometry\_set\_material\_override ( [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) material )
Sets a material that will override the material for all surfaces on the mesh associated with this instance. Equivalent to [GeometryInstance.material\_override](class_geometryinstance#class-geometryinstance-property-material-override).
### void instance\_set\_base ( [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) base )
Sets the base of the instance. A base can be any of the 3D objects that are created in the VisualServer that can be displayed. For example, any of the light types, mesh, multimesh, immediate geometry, particle system, reflection probe, lightmap capture, and the GI probe are all types that can be set as the base of an instance in order to be displayed in the scenario.
### void instance\_set\_blend\_shape\_weight ( [RID](class_rid#class-rid) instance, [int](class_int#class-int) shape, [float](class_float#class-float) weight )
Sets the weight for a given blend shape associated with this instance.
### void instance\_set\_custom\_aabb ( [RID](class_rid#class-rid) instance, [AABB](class_aabb#class-aabb) aabb )
Sets a custom AABB to use when culling objects from the view frustum. Equivalent to [GeometryInstance.set\_custom\_aabb](class_geometryinstance#class-geometryinstance-method-set-custom-aabb).
### void instance\_set\_exterior ( [RID](class_rid#class-rid) instance, [bool](class_bool#class-bool) enabled )
Function not implemented in Godot 3.x.
### void instance\_set\_extra\_visibility\_margin ( [RID](class_rid#class-rid) instance, [float](class_float#class-float) margin )
Sets a margin to increase the size of the AABB when culling objects from the view frustum. This allows you to avoid culling objects that fall outside the view frustum. Equivalent to [GeometryInstance.extra\_cull\_margin](class_geometryinstance#class-geometryinstance-property-extra-cull-margin).
### void instance\_set\_layer\_mask ( [RID](class_rid#class-rid) instance, [int](class_int#class-int) mask )
Sets the render layers that this instance will be drawn to. Equivalent to [VisualInstance.layers](class_visualinstance#class-visualinstance-property-layers).
### void instance\_set\_scenario ( [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) scenario )
Sets the scenario that the instance is in. The scenario is the 3D world that the objects will be displayed in.
### void instance\_set\_surface\_material ( [RID](class_rid#class-rid) instance, [int](class_int#class-int) surface, [RID](class_rid#class-rid) material )
Sets the material of a specific surface. Equivalent to [MeshInstance.set\_surface\_material](class_meshinstance#class-meshinstance-method-set-surface-material).
### void instance\_set\_transform ( [RID](class_rid#class-rid) instance, [Transform](class_transform#class-transform) transform )
Sets the world space transform of the instance. Equivalent to [Spatial.transform](class_spatial#class-spatial-property-transform).
### void instance\_set\_use\_lightmap ( [RID](class_rid#class-rid) instance, [RID](class_rid#class-rid) lightmap\_instance, [RID](class_rid#class-rid) lightmap, [int](class_int#class-int) lightmap\_slice=-1, [Rect2](class_rect2#class-rect2) lightmap\_uv\_rect=Rect2( 0, 0, 1, 1 ) )
Sets the lightmap to use with this instance.
### void instance\_set\_visible ( [RID](class_rid#class-rid) instance, [bool](class_bool#class-bool) visible )
Sets whether an instance is drawn or not. Equivalent to [Spatial.visible](class_spatial#class-spatial-property-visible).
### [Array](class_array#class-array) instances\_cull\_aabb ( [AABB](class_aabb#class-aabb) aabb, [RID](class_rid#class-rid) scenario ) const
Returns an array of object IDs intersecting with the provided AABB. Only visual 3D nodes are considered, such as [MeshInstance](class_meshinstance#class-meshinstance) or [DirectionalLight](class_directionallight#class-directionallight). Use [@GDScript.instance\_from\_id](class_%40gdscript#class-gdscript-method-instance-from-id) to obtain the actual nodes. A scenario RID must be provided, which is available in the [World](class_world#class-world) you want to query. This forces an update for all resources queued to update.
**Warning:** This function is primarily intended for editor usage. For in-game use cases, prefer physics collision.
### [Array](class_array#class-array) instances\_cull\_convex ( [Array](class_array#class-array) convex, [RID](class_rid#class-rid) scenario ) const
Returns an array of object IDs intersecting with the provided convex shape. Only visual 3D nodes are considered, such as [MeshInstance](class_meshinstance#class-meshinstance) or [DirectionalLight](class_directionallight#class-directionallight). Use [@GDScript.instance\_from\_id](class_%40gdscript#class-gdscript-method-instance-from-id) to obtain the actual nodes. A scenario RID must be provided, which is available in the [World](class_world#class-world) you want to query. This forces an update for all resources queued to update.
**Warning:** This function is primarily intended for editor usage. For in-game use cases, prefer physics collision.
### [Array](class_array#class-array) instances\_cull\_ray ( [Vector3](class_vector3#class-vector3) from, [Vector3](class_vector3#class-vector3) to, [RID](class_rid#class-rid) scenario ) const
Returns an array of object IDs intersecting with the provided 3D ray. Only visual 3D nodes are considered, such as [MeshInstance](class_meshinstance#class-meshinstance) or [DirectionalLight](class_directionallight#class-directionallight). Use [@GDScript.instance\_from\_id](class_%40gdscript#class-gdscript-method-instance-from-id) to obtain the actual nodes. A scenario RID must be provided, which is available in the [World](class_world#class-world) you want to query. This forces an update for all resources queued to update.
**Warning:** This function is primarily intended for editor usage. For in-game use cases, prefer physics collision.
### void light\_directional\_set\_blend\_splits ( [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enable )
If `true`, this directional light will blend between shadow map splits resulting in a smoother transition between them. Equivalent to [DirectionalLight.directional\_shadow\_blend\_splits](class_directionallight#class-directionallight-property-directional-shadow-blend-splits).
### void light\_directional\_set\_shadow\_depth\_range\_mode ( [RID](class_rid#class-rid) light, [LightDirectionalShadowDepthRangeMode](#enum-visualserver-lightdirectionalshadowdepthrangemode) range\_mode )
Sets the shadow depth range mode for this directional light. Equivalent to [DirectionalLight.directional\_shadow\_depth\_range](class_directionallight#class-directionallight-property-directional-shadow-depth-range). See [LightDirectionalShadowDepthRangeMode](#enum-visualserver-lightdirectionalshadowdepthrangemode) for options.
### void light\_directional\_set\_shadow\_mode ( [RID](class_rid#class-rid) light, [LightDirectionalShadowMode](#enum-visualserver-lightdirectionalshadowmode) mode )
Sets the shadow mode for this directional light. Equivalent to [DirectionalLight.directional\_shadow\_mode](class_directionallight#class-directionallight-property-directional-shadow-mode). See [LightDirectionalShadowMode](#enum-visualserver-lightdirectionalshadowmode) for options.
### void light\_omni\_set\_shadow\_detail ( [RID](class_rid#class-rid) light, [LightOmniShadowDetail](#enum-visualserver-lightomnishadowdetail) detail )
Sets whether to use vertical or horizontal detail for this omni light. This can be used to alleviate artifacts in the shadow map. Equivalent to [OmniLight.omni\_shadow\_detail](class_omnilight#class-omnilight-property-omni-shadow-detail).
### void light\_omni\_set\_shadow\_mode ( [RID](class_rid#class-rid) light, [LightOmniShadowMode](#enum-visualserver-lightomnishadowmode) mode )
Sets whether to use a dual paraboloid or a cubemap for the shadow map. Dual paraboloid is faster but may suffer from artifacts. Equivalent to [OmniLight.omni\_shadow\_mode](class_omnilight#class-omnilight-property-omni-shadow-mode).
### void light\_set\_bake\_mode ( [RID](class_rid#class-rid) light, [LightBakeMode](#enum-visualserver-lightbakemode) bake\_mode )
Sets the bake mode for this light, see [LightBakeMode](#enum-visualserver-lightbakemode) for options. The bake mode affects how the light will be baked in [BakedLightmap](class_bakedlightmap#class-bakedlightmap)s and [GIProbe](class_giprobe#class-giprobe)s.
### void light\_set\_color ( [RID](class_rid#class-rid) light, [Color](class_color#class-color) color )
Sets the color of the light. Equivalent to [Light.light\_color](class_light#class-light-property-light-color).
### void light\_set\_cull\_mask ( [RID](class_rid#class-rid) light, [int](class_int#class-int) mask )
Sets the cull mask for this Light. Lights only affect objects in the selected layers. Equivalent to [Light.light\_cull\_mask](class_light#class-light-property-light-cull-mask).
### void light\_set\_negative ( [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enable )
If `true`, light will subtract light instead of adding light. Equivalent to [Light.light\_negative](class_light#class-light-property-light-negative).
### void light\_set\_param ( [RID](class_rid#class-rid) light, [LightParam](#enum-visualserver-lightparam) param, [float](class_float#class-float) value )
Sets the specified light parameter. See [LightParam](#enum-visualserver-lightparam) for options. Equivalent to [Light.set\_param](class_light#class-light-method-set-param).
### void light\_set\_projector ( [RID](class_rid#class-rid) light, [RID](class_rid#class-rid) texture )
Not implemented in Godot 3.x.
### void light\_set\_reverse\_cull\_face\_mode ( [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled )
If `true`, reverses the backface culling of the mesh. This can be useful when you have a flat mesh that has a light behind it. If you need to cast a shadow on both sides of the mesh, set the mesh to use double sided shadows with [instance\_geometry\_set\_cast\_shadows\_setting](#class-visualserver-method-instance-geometry-set-cast-shadows-setting). Equivalent to [Light.shadow\_reverse\_cull\_face](class_light#class-light-property-shadow-reverse-cull-face).
### void light\_set\_shadow ( [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled )
If `true`, light will cast shadows. Equivalent to [Light.shadow\_enabled](class_light#class-light-property-shadow-enabled).
### void light\_set\_shadow\_color ( [RID](class_rid#class-rid) light, [Color](class_color#class-color) color )
Sets the color of the shadow cast by the light. Equivalent to [Light.shadow\_color](class_light#class-light-property-shadow-color).
### void light\_set\_use\_gi ( [RID](class_rid#class-rid) light, [bool](class_bool#class-bool) enabled )
Sets whether GI probes capture light information from this light. *Deprecated method.* Use [light\_set\_bake\_mode](#class-visualserver-method-light-set-bake-mode) instead. This method is only kept for compatibility reasons and calls [light\_set\_bake\_mode](#class-visualserver-method-light-set-bake-mode) internally, setting the bake mode to [LIGHT\_BAKE\_DISABLED](#class-visualserver-constant-light-bake-disabled) or [LIGHT\_BAKE\_INDIRECT](#class-visualserver-constant-light-bake-indirect) depending on the given parameter.
### [RID](class_rid#class-rid) lightmap\_capture\_create ( )
Creates a lightmap capture and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `lightmap_capture_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this lightmap capture to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### [AABB](class_aabb#class-aabb) lightmap\_capture\_get\_bounds ( [RID](class_rid#class-rid) capture ) const
Returns the size of the lightmap capture area.
### [float](class_float#class-float) lightmap\_capture\_get\_energy ( [RID](class_rid#class-rid) capture ) const
Returns the energy multiplier used by the lightmap capture.
### [PoolByteArray](class_poolbytearray#class-poolbytearray) lightmap\_capture\_get\_octree ( [RID](class_rid#class-rid) capture ) const
Returns the octree used by the lightmap capture.
### [int](class_int#class-int) lightmap\_capture\_get\_octree\_cell\_subdiv ( [RID](class_rid#class-rid) capture ) const
Returns the cell subdivision amount used by this lightmap capture's octree.
### [Transform](class_transform#class-transform) lightmap\_capture\_get\_octree\_cell\_transform ( [RID](class_rid#class-rid) capture ) const
Returns the cell transform for this lightmap capture's octree.
### [bool](class_bool#class-bool) lightmap\_capture\_is\_interior ( [RID](class_rid#class-rid) capture ) const
Returns `true` if capture is in "interior" mode.
### void lightmap\_capture\_set\_bounds ( [RID](class_rid#class-rid) capture, [AABB](class_aabb#class-aabb) bounds )
Sets the size of the area covered by the lightmap capture. Equivalent to [BakedLightmapData.bounds](class_bakedlightmapdata#class-bakedlightmapdata-property-bounds).
### void lightmap\_capture\_set\_energy ( [RID](class_rid#class-rid) capture, [float](class_float#class-float) energy )
Sets the energy multiplier for this lightmap capture. Equivalent to [BakedLightmapData.energy](class_bakedlightmapdata#class-bakedlightmapdata-property-energy).
### void lightmap\_capture\_set\_interior ( [RID](class_rid#class-rid) capture, [bool](class_bool#class-bool) interior )
Sets the "interior" mode for this lightmap capture. Equivalent to [BakedLightmapData.interior](class_bakedlightmapdata#class-bakedlightmapdata-property-interior).
### void lightmap\_capture\_set\_octree ( [RID](class_rid#class-rid) capture, [PoolByteArray](class_poolbytearray#class-poolbytearray) octree )
Sets the octree to be used by this lightmap capture. This function is normally used by the [BakedLightmap](class_bakedlightmap#class-bakedlightmap) node. Equivalent to [BakedLightmapData.octree](class_bakedlightmapdata#class-bakedlightmapdata-property-octree).
### void lightmap\_capture\_set\_octree\_cell\_subdiv ( [RID](class_rid#class-rid) capture, [int](class_int#class-int) subdiv )
Sets the subdivision level of this lightmap capture's octree. Equivalent to [BakedLightmapData.cell\_subdiv](class_bakedlightmapdata#class-bakedlightmapdata-property-cell-subdiv).
### void lightmap\_capture\_set\_octree\_cell\_transform ( [RID](class_rid#class-rid) capture, [Transform](class_transform#class-transform) xform )
Sets the octree cell transform for this lightmap capture's octree. Equivalent to [BakedLightmapData.cell\_space\_transform](class_bakedlightmapdata#class-bakedlightmapdata-property-cell-space-transform).
### [RID](class_rid#class-rid) make\_sphere\_mesh ( [int](class_int#class-int) latitudes, [int](class_int#class-int) longitudes, [float](class_float#class-float) radius )
Returns a mesh of a sphere with the given amount of horizontal and vertical subdivisions.
### [RID](class_rid#class-rid) material\_create ( )
Creates an empty material and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `material_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### [Variant](class_variant#class-variant) material\_get\_param ( [RID](class_rid#class-rid) material, [String](class_string#class-string) parameter ) const
Returns the value of a certain material's parameter.
### [Variant](class_variant#class-variant) material\_get\_param\_default ( [RID](class_rid#class-rid) material, [String](class_string#class-string) parameter ) const
Returns the default value for the param if available. Returns `null` otherwise.
### [RID](class_rid#class-rid) material\_get\_shader ( [RID](class_rid#class-rid) shader\_material ) const
Returns the shader of a certain material's shader. Returns an empty RID if the material doesn't have a shader.
### void material\_set\_line\_width ( [RID](class_rid#class-rid) material, [float](class_float#class-float) width )
Sets a material's line width.
### void material\_set\_next\_pass ( [RID](class_rid#class-rid) material, [RID](class_rid#class-rid) next\_material )
Sets an object's next material.
### void material\_set\_param ( [RID](class_rid#class-rid) material, [String](class_string#class-string) parameter, [Variant](class_variant#class-variant) value )
Sets a material's parameter.
### void material\_set\_render\_priority ( [RID](class_rid#class-rid) material, [int](class_int#class-int) priority )
Sets a material's render priority.
### void material\_set\_shader ( [RID](class_rid#class-rid) shader\_material, [RID](class_rid#class-rid) shader )
Sets a shader material's shader.
### void mesh\_add\_surface\_from\_arrays ( [RID](class_rid#class-rid) mesh, [PrimitiveType](#enum-visualserver-primitivetype) primitive, [Array](class_array#class-array) arrays, [Array](class_array#class-array) blend\_shapes=[ ], [int](class_int#class-int) compress\_format=2194432 )
Adds a surface generated from the Arrays to a mesh. See [PrimitiveType](#enum-visualserver-primitivetype) constants for types.
### void mesh\_clear ( [RID](class_rid#class-rid) mesh )
Removes all surfaces from a mesh.
### [RID](class_rid#class-rid) mesh\_create ( )
Creates a new mesh and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `mesh_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this mesh to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### [int](class_int#class-int) mesh\_get\_blend\_shape\_count ( [RID](class_rid#class-rid) mesh ) const
Returns a mesh's blend shape count.
### [BlendShapeMode](#enum-visualserver-blendshapemode) mesh\_get\_blend\_shape\_mode ( [RID](class_rid#class-rid) mesh ) const
Returns a mesh's blend shape mode.
### [AABB](class_aabb#class-aabb) mesh\_get\_custom\_aabb ( [RID](class_rid#class-rid) mesh ) const
Returns a mesh's custom aabb.
### [int](class_int#class-int) mesh\_get\_surface\_count ( [RID](class_rid#class-rid) mesh ) const
Returns a mesh's number of surfaces.
### void mesh\_remove\_surface ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) index )
Removes a mesh's surface.
### void mesh\_set\_blend\_shape\_count ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) amount )
Sets a mesh's blend shape count.
### void mesh\_set\_blend\_shape\_mode ( [RID](class_rid#class-rid) mesh, [BlendShapeMode](#enum-visualserver-blendshapemode) mode )
Sets a mesh's blend shape mode.
### void mesh\_set\_custom\_aabb ( [RID](class_rid#class-rid) mesh, [AABB](class_aabb#class-aabb) aabb )
Sets a mesh's custom aabb.
### [AABB](class_aabb#class-aabb) mesh\_surface\_get\_aabb ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's aabb.
### [PoolByteArray](class_poolbytearray#class-poolbytearray) mesh\_surface\_get\_array ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's vertex buffer.
### [int](class_int#class-int) mesh\_surface\_get\_array\_index\_len ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's amount of indices.
### [int](class_int#class-int) mesh\_surface\_get\_array\_len ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's amount of vertices.
### [Array](class_array#class-array) mesh\_surface\_get\_arrays ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's buffer arrays.
### [Array](class_array#class-array) mesh\_surface\_get\_blend\_shape\_arrays ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's arrays for blend shapes.
### [int](class_int#class-int) mesh\_surface\_get\_format ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns the format of a mesh's surface.
### [int](class_int#class-int) mesh\_surface\_get\_format\_offset ( [int](class_int#class-int) format, [int](class_int#class-int) vertex\_len, [int](class_int#class-int) index\_len, [int](class_int#class-int) array\_index ) const
Function is unused in Godot 3.x.
### [int](class_int#class-int) mesh\_surface\_get\_format\_stride ( [int](class_int#class-int) format, [int](class_int#class-int) vertex\_len, [int](class_int#class-int) index\_len, [int](class_int#class-int) array\_index ) const
### [PoolByteArray](class_poolbytearray#class-poolbytearray) mesh\_surface\_get\_index\_array ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's index buffer.
### [RID](class_rid#class-rid) mesh\_surface\_get\_material ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns a mesh's surface's material.
### [PrimitiveType](#enum-visualserver-primitivetype) mesh\_surface\_get\_primitive\_type ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns the primitive type of a mesh's surface.
### [Array](class_array#class-array) mesh\_surface\_get\_skeleton\_aabb ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface ) const
Returns the aabb of a mesh's surface's skeleton.
### void mesh\_surface\_set\_material ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface, [RID](class_rid#class-rid) material )
Sets a mesh's surface's material.
### void mesh\_surface\_update\_region ( [RID](class_rid#class-rid) mesh, [int](class_int#class-int) surface, [int](class_int#class-int) offset, [PoolByteArray](class_poolbytearray#class-poolbytearray) data )
Updates a specific region of a vertex buffer for the specified surface. Warning: this function alters the vertex buffer directly with no safety mechanisms, you can easily corrupt your mesh.
### void multimesh\_allocate ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) instances, [MultimeshTransformFormat](#enum-visualserver-multimeshtransformformat) transform\_format, [MultimeshColorFormat](#enum-visualserver-multimeshcolorformat) color\_format, [MultimeshCustomDataFormat](#enum-visualserver-multimeshcustomdataformat) custom\_data\_format=0 )
Allocates space for the multimesh data. Format parameters determine how the data will be stored by OpenGL. See [MultimeshTransformFormat](#enum-visualserver-multimeshtransformformat), [MultimeshColorFormat](#enum-visualserver-multimeshcolorformat), and [MultimeshCustomDataFormat](#enum-visualserver-multimeshcustomdataformat) for usage. Equivalent to [MultiMesh.instance\_count](class_multimesh#class-multimesh-property-instance-count).
### [RID](class_rid#class-rid) multimesh\_create ( )
Creates a new multimesh on the VisualServer and returns an [RID](class_rid#class-rid) handle. This RID will be used in all `multimesh_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this multimesh to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### [AABB](class_aabb#class-aabb) multimesh\_get\_aabb ( [RID](class_rid#class-rid) multimesh ) const
Calculates and returns the axis-aligned bounding box that encloses all instances within the multimesh.
### [int](class_int#class-int) multimesh\_get\_instance\_count ( [RID](class_rid#class-rid) multimesh ) const
Returns the number of instances allocated for this multimesh.
### [RID](class_rid#class-rid) multimesh\_get\_mesh ( [RID](class_rid#class-rid) multimesh ) const
Returns the RID of the mesh that will be used in drawing this multimesh.
### [int](class_int#class-int) multimesh\_get\_visible\_instances ( [RID](class_rid#class-rid) multimesh ) const
Returns the number of visible instances for this multimesh.
### [Color](class_color#class-color) multimesh\_instance\_get\_color ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index ) const
Returns the color by which the specified instance will be modulated.
### [Color](class_color#class-color) multimesh\_instance\_get\_custom\_data ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index ) const
Returns the custom data associated with the specified instance.
### [Transform](class_transform#class-transform) multimesh\_instance\_get\_transform ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index ) const
Returns the [Transform](class_transform#class-transform) of the specified instance.
### [Transform2D](class_transform2d#class-transform2d) multimesh\_instance\_get\_transform\_2d ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index ) const
Returns the [Transform2D](class_transform2d#class-transform2d) of the specified instance. For use when the multimesh is set to use 2D transforms.
### void multimesh\_instance\_set\_color ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Color](class_color#class-color) color )
Sets the color by which this instance will be modulated. Equivalent to [MultiMesh.set\_instance\_color](class_multimesh#class-multimesh-method-set-instance-color).
### void multimesh\_instance\_set\_custom\_data ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Color](class_color#class-color) custom\_data )
Sets the custom data for this instance. Custom data is passed as a [Color](class_color#class-color), but is interpreted as a `vec4` in the shader. Equivalent to [MultiMesh.set\_instance\_custom\_data](class_multimesh#class-multimesh-method-set-instance-custom-data).
### void multimesh\_instance\_set\_transform ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Transform](class_transform#class-transform) transform )
Sets the [Transform](class_transform#class-transform) for this instance. Equivalent to [MultiMesh.set\_instance\_transform](class_multimesh#class-multimesh-method-set-instance-transform).
### void multimesh\_instance\_set\_transform\_2d ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) index, [Transform2D](class_transform2d#class-transform2d) transform )
Sets the [Transform2D](class_transform2d#class-transform2d) for this instance. For use when multimesh is used in 2D. Equivalent to [MultiMesh.set\_instance\_transform\_2d](class_multimesh#class-multimesh-method-set-instance-transform-2d).
### void multimesh\_set\_as\_bulk\_array ( [RID](class_rid#class-rid) multimesh, [PoolRealArray](class_poolrealarray#class-poolrealarray) array )
Sets all data related to the instances in one go. This is especially useful when loading the data from disk or preparing the data from GDNative.
All data is packed in one large float array. An array may look like this: Transform for instance 1, color data for instance 1, custom data for instance 1, transform for instance 2, color data for instance 2, etc.
[Transform](class_transform#class-transform) is stored as 12 floats, [Transform2D](class_transform2d#class-transform2d) is stored as 8 floats, `COLOR_8BIT` / `CUSTOM_DATA_8BIT` is stored as 1 float (4 bytes as is) and `COLOR_FLOAT` / `CUSTOM_DATA_FLOAT` is stored as 4 floats.
### void multimesh\_set\_mesh ( [RID](class_rid#class-rid) multimesh, [RID](class_rid#class-rid) mesh )
Sets the mesh to be drawn by the multimesh. Equivalent to [MultiMesh.mesh](class_multimesh#class-multimesh-property-mesh).
### void multimesh\_set\_visible\_instances ( [RID](class_rid#class-rid) multimesh, [int](class_int#class-int) visible )
Sets the number of instances visible at a given time. If -1, all instances that have been allocated are drawn. Equivalent to [MultiMesh.visible\_instance\_count](class_multimesh#class-multimesh-property-visible-instance-count).
### [RID](class_rid#class-rid) omni\_light\_create ( )
Creates a new omni light and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID can be used in most `light_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this omni light to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### [RID](class_rid#class-rid) particles\_create ( )
Creates a particle system and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `particles_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach these particles to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### [AABB](class_aabb#class-aabb) particles\_get\_current\_aabb ( [RID](class_rid#class-rid) particles )
Calculates and returns the axis-aligned bounding box that contains all the particles. Equivalent to [Particles.capture\_aabb](class_particles#class-particles-method-capture-aabb).
### [bool](class_bool#class-bool) particles\_get\_emitting ( [RID](class_rid#class-rid) particles )
Returns `true` if particles are currently set to emitting.
### [bool](class_bool#class-bool) particles\_is\_inactive ( [RID](class_rid#class-rid) particles )
Returns `true` if particles are not emitting and particles are set to inactive.
### void particles\_request\_process ( [RID](class_rid#class-rid) particles )
Add particle system to list of particle systems that need to be updated. Update will take place on the next frame, or on the next call to [instances\_cull\_aabb](#class-visualserver-method-instances-cull-aabb), [instances\_cull\_convex](#class-visualserver-method-instances-cull-convex), or [instances\_cull\_ray](#class-visualserver-method-instances-cull-ray).
### void particles\_restart ( [RID](class_rid#class-rid) particles )
Reset the particles on the next update. Equivalent to [Particles.restart](class_particles#class-particles-method-restart).
### void particles\_set\_amount ( [RID](class_rid#class-rid) particles, [int](class_int#class-int) amount )
Sets the number of particles to be drawn and allocates the memory for them. Equivalent to [Particles.amount](class_particles#class-particles-property-amount).
### void particles\_set\_custom\_aabb ( [RID](class_rid#class-rid) particles, [AABB](class_aabb#class-aabb) aabb )
Sets a custom axis-aligned bounding box for the particle system. Equivalent to [Particles.visibility\_aabb](class_particles#class-particles-property-visibility-aabb).
### void particles\_set\_draw\_order ( [RID](class_rid#class-rid) particles, [ParticlesDrawOrder](#enum-visualserver-particlesdraworder) order )
Sets the draw order of the particles to one of the named enums from [ParticlesDrawOrder](#enum-visualserver-particlesdraworder). See [ParticlesDrawOrder](#enum-visualserver-particlesdraworder) for options. Equivalent to [Particles.draw\_order](class_particles#class-particles-property-draw-order).
### void particles\_set\_draw\_pass\_mesh ( [RID](class_rid#class-rid) particles, [int](class_int#class-int) pass, [RID](class_rid#class-rid) mesh )
Sets the mesh to be used for the specified draw pass. Equivalent to [Particles.draw\_pass\_1](class_particles#class-particles-property-draw-pass-1), [Particles.draw\_pass\_2](class_particles#class-particles-property-draw-pass-2), [Particles.draw\_pass\_3](class_particles#class-particles-property-draw-pass-3), and [Particles.draw\_pass\_4](class_particles#class-particles-property-draw-pass-4).
### void particles\_set\_draw\_passes ( [RID](class_rid#class-rid) particles, [int](class_int#class-int) count )
Sets the number of draw passes to use. Equivalent to [Particles.draw\_passes](class_particles#class-particles-property-draw-passes).
### void particles\_set\_emission\_transform ( [RID](class_rid#class-rid) particles, [Transform](class_transform#class-transform) transform )
Sets the [Transform](class_transform#class-transform) that will be used by the particles when they first emit.
### void particles\_set\_emitting ( [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) emitting )
If `true`, particles will emit over time. Setting to false does not reset the particles, but only stops their emission. Equivalent to [Particles.emitting](class_particles#class-particles-property-emitting).
### void particles\_set\_explosiveness\_ratio ( [RID](class_rid#class-rid) particles, [float](class_float#class-float) ratio )
Sets the explosiveness ratio. Equivalent to [Particles.explosiveness](class_particles#class-particles-property-explosiveness).
### void particles\_set\_fixed\_fps ( [RID](class_rid#class-rid) particles, [int](class_int#class-int) fps )
Sets the frame rate that the particle system rendering will be fixed to. Equivalent to [Particles.fixed\_fps](class_particles#class-particles-property-fixed-fps).
### void particles\_set\_fractional\_delta ( [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) enable )
If `true`, uses fractional delta which smooths the movement of the particles. Equivalent to [Particles.fract\_delta](class_particles#class-particles-property-fract-delta).
### void particles\_set\_lifetime ( [RID](class_rid#class-rid) particles, [float](class_float#class-float) lifetime )
Sets the lifetime of each particle in the system. Equivalent to [Particles.lifetime](class_particles#class-particles-property-lifetime).
### void particles\_set\_one\_shot ( [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) one\_shot )
If `true`, particles will emit once and then stop. Equivalent to [Particles.one\_shot](class_particles#class-particles-property-one-shot).
### void particles\_set\_pre\_process\_time ( [RID](class_rid#class-rid) particles, [float](class_float#class-float) time )
Sets the preprocess time for the particles' animation. This lets you delay starting an animation until after the particles have begun emitting. Equivalent to [Particles.preprocess](class_particles#class-particles-property-preprocess).
### void particles\_set\_process\_material ( [RID](class_rid#class-rid) particles, [RID](class_rid#class-rid) material )
Sets the material for processing the particles.
**Note:** This is not the material used to draw the materials. Equivalent to [Particles.process\_material](class_particles#class-particles-property-process-material).
### void particles\_set\_randomness\_ratio ( [RID](class_rid#class-rid) particles, [float](class_float#class-float) ratio )
Sets the emission randomness ratio. This randomizes the emission of particles within their phase. Equivalent to [Particles.randomness](class_particles#class-particles-property-randomness).
### void particles\_set\_speed\_scale ( [RID](class_rid#class-rid) particles, [float](class_float#class-float) scale )
Sets the speed scale of the particle system. Equivalent to [Particles.speed\_scale](class_particles#class-particles-property-speed-scale).
### void particles\_set\_use\_local\_coordinates ( [RID](class_rid#class-rid) particles, [bool](class_bool#class-bool) enable )
If `true`, particles use local coordinates. If `false` they use global coordinates. Equivalent to [Particles.local\_coords](class_particles#class-particles-property-local-coords).
### [RID](class_rid#class-rid) reflection\_probe\_create ( )
Creates a reflection probe and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `reflection_probe_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this reflection probe to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### void reflection\_probe\_set\_as\_interior ( [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable )
If `true`, reflections will ignore sky contribution. Equivalent to [ReflectionProbe.interior\_enable](class_reflectionprobe#class-reflectionprobe-property-interior-enable).
### void reflection\_probe\_set\_cull\_mask ( [RID](class_rid#class-rid) probe, [int](class_int#class-int) layers )
Sets the render cull mask for this reflection probe. Only instances with a matching cull mask will be rendered by this probe. Equivalent to [ReflectionProbe.cull\_mask](class_reflectionprobe#class-reflectionprobe-property-cull-mask).
### void reflection\_probe\_set\_enable\_box\_projection ( [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable )
If `true`, uses box projection. This can make reflections look more correct in certain situations. Equivalent to [ReflectionProbe.box\_projection](class_reflectionprobe#class-reflectionprobe-property-box-projection).
### void reflection\_probe\_set\_enable\_shadows ( [RID](class_rid#class-rid) probe, [bool](class_bool#class-bool) enable )
If `true`, computes shadows in the reflection probe. This makes the reflection much slower to compute. Equivalent to [ReflectionProbe.enable\_shadows](class_reflectionprobe#class-reflectionprobe-property-enable-shadows).
### void reflection\_probe\_set\_extents ( [RID](class_rid#class-rid) probe, [Vector3](class_vector3#class-vector3) extents )
Sets the size of the area that the reflection probe will capture. Equivalent to [ReflectionProbe.extents](class_reflectionprobe#class-reflectionprobe-property-extents).
### void reflection\_probe\_set\_intensity ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) intensity )
Sets the intensity of the reflection probe. Intensity modulates the strength of the reflection. Equivalent to [ReflectionProbe.intensity](class_reflectionprobe#class-reflectionprobe-property-intensity).
### void reflection\_probe\_set\_interior\_ambient ( [RID](class_rid#class-rid) probe, [Color](class_color#class-color) color )
Sets the ambient light color for this reflection probe when set to interior mode. Equivalent to [ReflectionProbe.interior\_ambient\_color](class_reflectionprobe#class-reflectionprobe-property-interior-ambient-color).
### void reflection\_probe\_set\_interior\_ambient\_energy ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) energy )
Sets the energy multiplier for this reflection probes ambient light contribution when set to interior mode. Equivalent to [ReflectionProbe.interior\_ambient\_energy](class_reflectionprobe#class-reflectionprobe-property-interior-ambient-energy).
### void reflection\_probe\_set\_interior\_ambient\_probe\_contribution ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) contrib )
Sets the contribution value for how much the reflection affects the ambient light for this reflection probe when set to interior mode. Useful so that ambient light matches the color of the room. Equivalent to [ReflectionProbe.interior\_ambient\_contrib](class_reflectionprobe#class-reflectionprobe-property-interior-ambient-contrib).
### void reflection\_probe\_set\_max\_distance ( [RID](class_rid#class-rid) probe, [float](class_float#class-float) distance )
Sets the max distance away from the probe an object can be before it is culled. Equivalent to [ReflectionProbe.max\_distance](class_reflectionprobe#class-reflectionprobe-property-max-distance).
### void reflection\_probe\_set\_origin\_offset ( [RID](class_rid#class-rid) probe, [Vector3](class_vector3#class-vector3) offset )
Sets the origin offset to be used when this reflection probe is in box project mode. Equivalent to [ReflectionProbe.origin\_offset](class_reflectionprobe#class-reflectionprobe-property-origin-offset).
### void reflection\_probe\_set\_update\_mode ( [RID](class_rid#class-rid) probe, [ReflectionProbeUpdateMode](#enum-visualserver-reflectionprobeupdatemode) mode )
Sets how often the reflection probe updates. Can either be once or every frame. See [ReflectionProbeUpdateMode](#enum-visualserver-reflectionprobeupdatemode) for options.
### void request\_frame\_drawn\_callback ( [Object](class_object#class-object) where, [String](class_string#class-string) method, [Variant](class_variant#class-variant) userdata )
Schedules a callback to the corresponding named `method` on `where` after a frame has been drawn.
The callback method must use only 1 argument which will be called with `userdata`.
### [RID](class_rid#class-rid) scenario\_create ( )
Creates a scenario and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `scenario_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
The scenario is the 3D world that all the visual instances exist in.
### void scenario\_set\_debug ( [RID](class_rid#class-rid) scenario, [ScenarioDebugMode](#enum-visualserver-scenariodebugmode) debug\_mode )
Sets the [ScenarioDebugMode](#enum-visualserver-scenariodebugmode) for this scenario. See [ScenarioDebugMode](#enum-visualserver-scenariodebugmode) for options.
### void scenario\_set\_environment ( [RID](class_rid#class-rid) scenario, [RID](class_rid#class-rid) environment )
Sets the environment that will be used with this scenario.
### void scenario\_set\_fallback\_environment ( [RID](class_rid#class-rid) scenario, [RID](class_rid#class-rid) environment )
Sets the fallback environment to be used by this scenario. The fallback environment is used if no environment is set. Internally, this is used by the editor to provide a default environment.
### void scenario\_set\_reflection\_atlas\_size ( [RID](class_rid#class-rid) scenario, [int](class_int#class-int) size, [int](class_int#class-int) subdiv )
Sets the size of the reflection atlas shared by all reflection probes in this scenario.
### void set\_boot\_image ( [Image](class_image#class-image) image, [Color](class_color#class-color) color, [bool](class_bool#class-bool) scale, [bool](class_bool#class-bool) use\_filter=true )
Sets a boot image. The color defines the background color. If `scale` is `true`, the image will be scaled to fit the screen size. If `use_filter` is `true`, the image will be scaled with linear interpolation. If `use_filter` is `false`, the image will be scaled with nearest-neighbor interpolation.
### void set\_debug\_generate\_wireframes ( [bool](class_bool#class-bool) generate )
If `true`, the engine will generate wireframes for use with the wireframe debug mode.
### void set\_default\_clear\_color ( [Color](class_color#class-color) color )
Sets the default clear color which is used when a specific clear color has not been selected.
### void set\_shader\_async\_hidden\_forbidden ( [bool](class_bool#class-bool) forbidden )
If asynchronous shader compilation is enabled, this controls whether [SpatialMaterial.ASYNC\_MODE\_HIDDEN](class_spatialmaterial#class-spatialmaterial-constant-async-mode-hidden) is obeyed.
For instance, you may want to enable this temporarily before taking a screenshot. This ensures everything is visible even if shaders with async mode *hidden* are not ready yet.
Reflection probes use this internally to ensure they capture everything regardless the shaders are ready or not.
### void set\_shader\_time\_scale ( [float](class_float#class-float) scale )
Sets the scale to apply to the passage of time for the shaders' `TIME` builtin.
The default value is `1.0`, which means `TIME` will count the real time as it goes by, without narrowing or stretching it.
### void set\_use\_occlusion\_culling ( [bool](class_bool#class-bool) enable )
Enables or disables occlusion culling.
### [RID](class_rid#class-rid) shader\_create ( )
Creates an empty shader and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `shader_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### [String](class_string#class-string) shader\_get\_code ( [RID](class_rid#class-rid) shader ) const
Returns a shader's code.
### [RID](class_rid#class-rid) shader\_get\_default\_texture\_param ( [RID](class_rid#class-rid) shader, [String](class_string#class-string) name ) const
Returns a default texture from a shader searched by name.
### [Array](class_array#class-array) shader\_get\_param\_list ( [RID](class_rid#class-rid) shader ) const
Returns the parameters of a shader.
### void shader\_set\_code ( [RID](class_rid#class-rid) shader, [String](class_string#class-string) code )
Sets a shader's code.
### void shader\_set\_default\_texture\_param ( [RID](class_rid#class-rid) shader, [String](class_string#class-string) name, [RID](class_rid#class-rid) texture )
Sets a shader's default texture. Overwrites the texture given by name.
### void skeleton\_allocate ( [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bones, [bool](class_bool#class-bool) is\_2d\_skeleton=false )
Allocates the GPU buffers for this skeleton.
### [Transform](class_transform#class-transform) skeleton\_bone\_get\_transform ( [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone ) const
Returns the [Transform](class_transform#class-transform) set for a specific bone of this skeleton.
### [Transform2D](class_transform2d#class-transform2d) skeleton\_bone\_get\_transform\_2d ( [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone ) const
Returns the [Transform2D](class_transform2d#class-transform2d) set for a specific bone of this skeleton.
### void skeleton\_bone\_set\_transform ( [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone, [Transform](class_transform#class-transform) transform )
Sets the [Transform](class_transform#class-transform) for a specific bone of this skeleton.
### void skeleton\_bone\_set\_transform\_2d ( [RID](class_rid#class-rid) skeleton, [int](class_int#class-int) bone, [Transform2D](class_transform2d#class-transform2d) transform )
Sets the [Transform2D](class_transform2d#class-transform2d) for a specific bone of this skeleton.
### [RID](class_rid#class-rid) skeleton\_create ( )
Creates a skeleton and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `skeleton_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### [int](class_int#class-int) skeleton\_get\_bone\_count ( [RID](class_rid#class-rid) skeleton ) const
Returns the number of bones allocated for this skeleton.
### [RID](class_rid#class-rid) sky\_create ( )
Creates an empty sky and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `sky_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void sky\_set\_texture ( [RID](class_rid#class-rid) sky, [RID](class_rid#class-rid) cube\_map, [int](class_int#class-int) radiance\_size )
Sets a sky's texture.
### [RID](class_rid#class-rid) spot\_light\_create ( )
Creates a spot light and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID can be used in most `light_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
To place in a scene, attach this spot light to an instance using [instance\_set\_base](#class-visualserver-method-instance-set-base) using the returned RID.
### void sync ( )
Not implemented in Godot 3.x.
### void texture\_allocate ( [RID](class_rid#class-rid) texture, [int](class_int#class-int) width, [int](class_int#class-int) height, [int](class_int#class-int) depth\_3d, [Format](class_image#enum-image-format) format, [TextureType](#enum-visualserver-texturetype) type, [int](class_int#class-int) flags=7 )
Allocates the GPU memory for the texture.
### void texture\_bind ( [RID](class_rid#class-rid) texture, [int](class_int#class-int) number )
Binds the texture to a texture slot.
### [RID](class_rid#class-rid) texture\_create ( )
Creates an empty texture and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `texture_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### [RID](class_rid#class-rid) texture\_create\_from\_image ( [Image](class_image#class-image) image, [int](class_int#class-int) flags=7 )
Creates a texture, allocates the space for an image, and fills in the image.
### [Array](class_array#class-array) texture\_debug\_usage ( )
Returns a list of all the textures and their information.
### [Image](class_image#class-image) texture\_get\_data ( [RID](class_rid#class-rid) texture, [int](class_int#class-int) cube\_side=0 ) const
Returns a copy of a texture's image unless it's a CubeMap, in which case it returns the [RID](class_rid#class-rid) of the image at one of the cubes sides.
### [int](class_int#class-int) texture\_get\_depth ( [RID](class_rid#class-rid) texture ) const
Returns the depth of the texture.
### [int](class_int#class-int) texture\_get\_flags ( [RID](class_rid#class-rid) texture ) const
Returns the flags of a texture.
### [Format](class_image#enum-image-format) texture\_get\_format ( [RID](class_rid#class-rid) texture ) const
Returns the format of the texture's image.
### [int](class_int#class-int) texture\_get\_height ( [RID](class_rid#class-rid) texture ) const
Returns the texture's height.
### [String](class_string#class-string) texture\_get\_path ( [RID](class_rid#class-rid) texture ) const
Returns the texture's path.
### [int](class_int#class-int) texture\_get\_texid ( [RID](class_rid#class-rid) texture ) const
Returns the opengl id of the texture's image.
### [TextureType](#enum-visualserver-texturetype) texture\_get\_type ( [RID](class_rid#class-rid) texture ) const
Returns the type of the texture, can be any of the [TextureType](#enum-visualserver-texturetype).
### [int](class_int#class-int) texture\_get\_width ( [RID](class_rid#class-rid) texture ) const
Returns the texture's width.
### void texture\_set\_data ( [RID](class_rid#class-rid) texture, [Image](class_image#class-image) image, [int](class_int#class-int) layer=0 )
Sets the texture's image data. If it's a CubeMap, it sets the image data at a cube side.
### void texture\_set\_data\_partial ( [RID](class_rid#class-rid) texture, [Image](class_image#class-image) image, [int](class_int#class-int) src\_x, [int](class_int#class-int) src\_y, [int](class_int#class-int) src\_w, [int](class_int#class-int) src\_h, [int](class_int#class-int) dst\_x, [int](class_int#class-int) dst\_y, [int](class_int#class-int) dst\_mip, [int](class_int#class-int) layer=0 )
Sets a part of the data for a texture. Warning: this function calls the underlying graphics API directly and may corrupt your texture if used improperly.
### void texture\_set\_flags ( [RID](class_rid#class-rid) texture, [int](class_int#class-int) flags )
Sets the texture's flags. See [TextureFlags](#enum-visualserver-textureflags) for options.
### void texture\_set\_path ( [RID](class_rid#class-rid) texture, [String](class_string#class-string) path )
Sets the texture's path.
### void texture\_set\_proxy ( [RID](class_rid#class-rid) proxy, [RID](class_rid#class-rid) base )
Creates an update link between two textures, similar to how [ViewportTexture](class_viewporttexture#class-viewporttexture)s operate. When the base texture is the texture of a [Viewport](class_viewport#class-viewport), every time the viewport renders a new frame, the proxy texture automatically receives an update.
For example, this code links a generic [ImageTexture](class_imagetexture#class-imagetexture) to the texture output of the [Viewport](class_viewport#class-viewport) using the VisualServer API:
```
func _ready():
var viewport_rid = get_viewport().get_viewport_rid()
var viewport_texture_rid = VisualServer.viewport_get_texture(viewport_rid)
var proxy_texture = ImageTexture.new()
var viewport_texture_image_data = VisualServer.texture_get_data(viewport_texture_rid)
proxy_texture.create_from_image(viewport_texture_image_data)
var proxy_texture_rid = proxy_texture.get_rid()
VisualServer.texture_set_proxy(proxy_texture_rid, viewport_texture_rid)
$TextureRect.texture = proxy_texture
```
### void texture\_set\_shrink\_all\_x2\_on\_set\_data ( [bool](class_bool#class-bool) shrink )
If `true`, sets internal processes to shrink all image data to half the size.
### void texture\_set\_size\_override ( [RID](class_rid#class-rid) texture, [int](class_int#class-int) width, [int](class_int#class-int) height, [int](class_int#class-int) depth )
Resizes the texture to the specified dimensions.
### void textures\_keep\_original ( [bool](class_bool#class-bool) enable )
If `true`, the image will be stored in the texture's images array if overwritten.
### void viewport\_attach\_camera ( [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) camera )
Sets a viewport's camera.
### void viewport\_attach\_canvas ( [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas )
Sets a viewport's canvas.
### void viewport\_attach\_to\_screen ( [RID](class_rid#class-rid) viewport, [Rect2](class_rect2#class-rect2) rect=Rect2( 0, 0, 0, 0 ), [int](class_int#class-int) screen=0 )
Copies viewport to a region of the screen specified by `rect`. If [Viewport.render\_direct\_to\_screen](class_viewport#class-viewport-property-render-direct-to-screen) is `true`, then viewport does not use a framebuffer and the contents of the viewport are rendered directly to screen. However, note that the root viewport is drawn last, therefore it will draw over the screen. Accordingly, you must set the root viewport to an area that does not cover the area that you have attached this viewport to.
For example, you can set the root viewport to not render at all with the following code:
```
func _ready():
get_viewport().set_attach_to_screen_rect(Rect2())
$Viewport.set_attach_to_screen_rect(Rect2(0, 0, 600, 600))
```
Using this can result in significant optimization, especially on lower-end devices. However, it comes at the cost of having to manage your viewports manually. For further optimization, see [viewport\_set\_render\_direct\_to\_screen](#class-visualserver-method-viewport-set-render-direct-to-screen).
### [RID](class_rid#class-rid) viewport\_create ( )
Creates an empty viewport and adds it to the VisualServer. It can be accessed with the RID that is returned. This RID will be used in all `viewport_*` VisualServer functions.
Once finished with your RID, you will want to free the RID using the VisualServer's [free\_rid](#class-visualserver-method-free-rid) static method.
### void viewport\_detach ( [RID](class_rid#class-rid) viewport )
Detaches the viewport from the screen.
### [int](class_int#class-int) viewport\_get\_render\_info ( [RID](class_rid#class-rid) viewport, [ViewportRenderInfo](#enum-visualserver-viewportrenderinfo) info )
Returns a viewport's render information. For options, see the [ViewportRenderInfo](#enum-visualserver-viewportrenderinfo) constants.
### [RID](class_rid#class-rid) viewport\_get\_texture ( [RID](class_rid#class-rid) viewport ) const
Returns the viewport's last rendered frame.
### void viewport\_remove\_canvas ( [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas )
Detaches a viewport from a canvas and vice versa.
### void viewport\_set\_active ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) active )
If `true`, sets the viewport active, else sets it inactive.
### void viewport\_set\_canvas\_stacking ( [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas, [int](class_int#class-int) layer, [int](class_int#class-int) sublayer )
Sets the stacking order for a viewport's canvas.
`layer` is the actual canvas layer, while `sublayer` specifies the stacking order of the canvas among those in the same layer.
### void viewport\_set\_canvas\_transform ( [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) canvas, [Transform2D](class_transform2d#class-transform2d) offset )
Sets the transformation of a viewport's canvas.
### void viewport\_set\_clear\_mode ( [RID](class_rid#class-rid) viewport, [ViewportClearMode](#enum-visualserver-viewportclearmode) clear\_mode )
Sets the clear mode of a viewport. See [ViewportClearMode](#enum-visualserver-viewportclearmode) for options.
### void viewport\_set\_debug\_draw ( [RID](class_rid#class-rid) viewport, [ViewportDebugDraw](#enum-visualserver-viewportdebugdraw) draw )
Sets the debug draw mode of a viewport. See [ViewportDebugDraw](#enum-visualserver-viewportdebugdraw) for options.
### void viewport\_set\_disable\_3d ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) disabled )
If `true`, a viewport's 3D rendering is disabled.
### void viewport\_set\_disable\_environment ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) disabled )
If `true`, rendering of a viewport's environment is disabled.
### void viewport\_set\_global\_canvas\_transform ( [RID](class_rid#class-rid) viewport, [Transform2D](class_transform2d#class-transform2d) transform )
Sets the viewport's global transformation matrix.
### void viewport\_set\_hdr ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled )
If `true`, the viewport renders to high dynamic range (HDR) instead of standard dynamic range (SDR). See also [viewport\_set\_use\_32\_bpc\_depth](#class-visualserver-method-viewport-set-use-32-bpc-depth).
**Note:** Only available on the GLES3 backend.
### void viewport\_set\_hide\_canvas ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) hidden )
If `true`, the viewport's canvas is not rendered.
### void viewport\_set\_hide\_scenario ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) hidden )
Currently unimplemented in Godot 3.x.
### void viewport\_set\_msaa ( [RID](class_rid#class-rid) viewport, [ViewportMSAA](#enum-visualserver-viewportmsaa) msaa )
Sets the anti-aliasing mode. See [ViewportMSAA](#enum-visualserver-viewportmsaa) for options.
### void viewport\_set\_parent\_viewport ( [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) parent\_viewport )
Sets the viewport's parent to another viewport.
### void viewport\_set\_render\_direct\_to\_screen ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled )
If `true`, render the contents of the viewport directly to screen. This allows a low-level optimization where you can skip drawing a viewport to the root viewport. While this optimization can result in a significant increase in speed (especially on older devices), it comes at a cost of usability. When this is enabled, you cannot read from the viewport or from the `SCREEN_TEXTURE`. You also lose the benefit of certain window settings, such as the various stretch modes. Another consequence to be aware of is that in 2D the rendering happens in window coordinates, so if you have a viewport that is double the size of the window, and you set this, then only the portion that fits within the window will be drawn, no automatic scaling is possible, even if your game scene is significantly larger than the window size.
### void viewport\_set\_scenario ( [RID](class_rid#class-rid) viewport, [RID](class_rid#class-rid) scenario )
Sets a viewport's scenario.
The scenario contains information about the [ScenarioDebugMode](#enum-visualserver-scenariodebugmode), environment information, reflection atlas etc.
### void viewport\_set\_shadow\_atlas\_quadrant\_subdivision ( [RID](class_rid#class-rid) viewport, [int](class_int#class-int) quadrant, [int](class_int#class-int) subdivision )
Sets the shadow atlas quadrant's subdivision.
### void viewport\_set\_shadow\_atlas\_size ( [RID](class_rid#class-rid) viewport, [int](class_int#class-int) size )
Sets the size of the shadow atlas's images (used for omni and spot lights). The value will be rounded up to the nearest power of 2.
### void viewport\_set\_sharpen\_intensity ( [RID](class_rid#class-rid) viewport, [float](class_float#class-float) intensity )
Sets the sharpening `intensity` for the `viewport`. If set to a value greater than `0.0`, contrast-adaptive sharpening will be applied to the 3D viewport. This has a low performance cost and can be used to recover some of the sharpness lost from using FXAA. Values around `0.5` generally give the best results. See also [viewport\_set\_use\_fxaa](#class-visualserver-method-viewport-set-use-fxaa).
### void viewport\_set\_size ( [RID](class_rid#class-rid) viewport, [int](class_int#class-int) width, [int](class_int#class-int) height )
Sets the viewport's width and height.
### void viewport\_set\_transparent\_background ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled )
If `true`, the viewport renders its background as transparent.
### void viewport\_set\_update\_mode ( [RID](class_rid#class-rid) viewport, [ViewportUpdateMode](#enum-visualserver-viewportupdatemode) update\_mode )
Sets when the viewport should be updated. See [ViewportUpdateMode](#enum-visualserver-viewportupdatemode) constants for options.
### void viewport\_set\_usage ( [RID](class_rid#class-rid) viewport, [ViewportUsage](#enum-visualserver-viewportusage) usage )
Sets the viewport's 2D/3D mode. See [ViewportUsage](#enum-visualserver-viewportusage) constants for options.
### void viewport\_set\_use\_32\_bpc\_depth ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled )
If `true`, allocates the viewport's framebuffer with full floating-point precision (32-bit) instead of half floating-point precision (16-bit). Only effective if [viewport\_set\_use\_32\_bpc\_depth](#class-visualserver-method-viewport-set-use-32-bpc-depth) is used on the same [Viewport](class_viewport#class-viewport) to set HDR to `true`.
**Note:** Only available on the GLES3 backend.
### void viewport\_set\_use\_arvr ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) use\_arvr )
If `true`, the viewport uses augmented or virtual reality technologies. See [ARVRInterface](class_arvrinterface#class-arvrinterface).
### void viewport\_set\_use\_debanding ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) debanding )
If `true`, uses a fast post-processing filter to make banding significantly less visible. In some cases, debanding may introduce a slightly noticeable dithering pattern. It's recommended to enable debanding only when actually needed since the dithering pattern will make lossless-compressed screenshots larger.
**Note:** Only available on the GLES3 backend. [Viewport.hdr](class_viewport#class-viewport-property-hdr) must also be `true` for debanding to be effective.
### void viewport\_set\_use\_fxaa ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) fxaa )
Enables fast approximate antialiasing for this viewport. FXAA is a popular screen-space antialiasing method, which is fast but will make the image look blurry, especially at lower resolutions. It can still work relatively well at large resolutions such as 1440p and 4K. Some of the lost sharpness can be recovered by enabling contrast-adaptive sharpening (see [viewport\_set\_sharpen\_intensity](#class-visualserver-method-viewport-set-sharpen-intensity)).
### void viewport\_set\_vflip ( [RID](class_rid#class-rid) viewport, [bool](class_bool#class-bool) enabled )
If `true`, the viewport's rendering is flipped vertically.
| programming_docs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.