6. Standard library

Functions which are documented in this chapter are considered core functions hence are available in all contexts. Functions in the standard library may be recognized by the fact that they are all in lowercase.

6.1. Array

array_combine(keys, values[, default_value])

Create a new array with the keys and values combines into a new array. Duplicate keys are updated.

Parameters
  • keys (array) – the array of keys

  • values (array) – the array of values

  • default_value (any) – the default value if not enough values for all keys

Returns

an array

Return type

array

array_combine(["a", "b", "c"], [1, 2], 0); // ["a"=>1,"b"=>2,"c"=>0]
array_combine(["a", "b", "a", "c"], [1, 2, 3, 4]); // ["a"=>3,"b"=>2,"c"=>4]
array_every(callback, array)

Returns true if all items in the array are true based on the result of the callback function.

Parameters
  • callback (function) – the callback

  • array (array) – the array

Returns

true if all callbacks return true

Return type

boolean

The callback function should take one argument (value) and return a boolean value.

array_every(function ($x) { return $x % 2 == 0; }, [0, 2, 4, 6]); // true
array_every(function ($x) { return $x % 2 == 0; }, [0, 2, 5, 6]); // false
array_filter(callback, array)

Returns the filtered items from the array using a callback.

Parameters
  • callback (function) – the callback

  • array (array) – the array

Returns

array of filtered values, keys are preserved

Return type

array

The callback function should take one argument (value) and return a boolean value.

array_filter(function ($x) { return $x % 2 == 0; }, [0, 1, 2, 3]); // even values
array_filter(is_number, [0, "Hello World", 2]);
array_find(callback, array)

Return the first element that matches in the array. If no element is found none is returned.

Parameters
  • callback (function) – the callback

  • array (array) – the array

Returns

the value if found

Return type

any

The callback function should take one argument (value) and return a boolean value.

array_find(function ($x) { return $x["id"] === 2; }, [["id" => 1, "name" => "a"], ["id" => 2, "name" => "b"]]); // ["id"=>2,"name"=>"b"]
array_includes(needle, array)

Returns true if needle is found in the array.

Parameters
  • needle (any) – the value to match or a callback function

  • array (array) – the array

Returns

true if needle is found

Return type

boolean

The callback function should take one argument (value) and return a boolean value. If the needle is not a function, it will be matched using the strict comparison operator (===).

array_includes(function ($x) { return $x === 2; }, [0, 1, 2, 3]); // true
array_includes(false, [0, none, ""]); // false
array_join(array[, separator])

Join the elements in the array with a separator returning a string

Parameters
  • array (array) – the array

  • separator (string) – the separator

Returns

a string from an array

Return type

string

See also

To split a string to an array, see str_split().

array_keys(array)

Returns the keys in the array.

Parameters

array (array) – the array

Returns

array’s keys

Return type

array

array_map(callback, array)

Returns values from the array with the callback applied.

Parameters
  • callback (function) – the callback

  • array (array) – the array

Returns

array of values, keys are preserved

Return type

array

The function should take one argument (value) and return a value.

array_map(function ($x) { return $x * 2; }, [0, 1, 2, 3]); // double values
array_random(array)

Returns a random key and value from the array. If the array is empty none is returned.

Parameters

array (array) – the array

Returns

array with key and value

Return type

array

The function should take one argument (value) and return a value.

array_random(["hello" => "foo", "world" => "bar"]); // ["world", "bar"] // [key, value]
array_range(start, stop[, step = 1])

Returns an array from a numeric range (half-open) with the given steps.

Parameters
  • start (number) – the first number

  • stop (number) – the last number (not included)

  • step (number) – the step between numbers

Returns

an array with numbers

Return type

array

foreach (array_range(0, 9) as $i) // 0,1,2,..,8
        echo $i;
array_reduce(callback, array[, initial])

Reduces the values in the array using the callback from left-to-right, optionally starting with a initial value.

Parameters
  • callback (function) – the callback

  • array (array) – the array

  • initial (any) – the initial value

Returns

a single value

Return type

any

The function should take two arguments (carry and value) and return a value.

If no initial value is provided and;

  • the array is empty, an error will be raised.

  • the array contains one value, that value will be returned.

array_reduce(function ($carry, $x) { return $carry + $x; }, [0, 1, 2, 3]); // sum values
array_reverse(array)

Return array in reverse order. Numeric keys are reindexed.

Parameters

array (array) – the array

Returns

array in reverse order

Return type

array

array_sort(callback, array[, options])

Returns the array sorted (with index association maintained) using the callback function to determine the order. The sort is not guaranteed to be stable.

Parameters
  • callback (function) – the callback

  • array (array) – the array

  • options (array) – options array

Returns

a sorted array

Return type

array

The following options are available in the options array.

  • keys (boolean) Sort the array based on their keys. The default is false.

The callback function should take two arguments (a and b) and return true if a is less-than b.

array_sort(function ($a, $b) { return $a < $b; }, [2, 3, 1]); // sort
array_sort(function ($a, $b) { return $a > $b; }, [2, 3, 1]); // reverse-sort

Note

Some other languages (eg. javascript and PHP) use a trivalue function (-1, 0, 1) in a similar way in order to determine the order. HSL does not since if needed, a trivalue function may be simulated internally using the provided less-than function. Further some sorting implementation may only need the less-than result hence the greater-than and equality result may be superfluous to establish.

function trivalue($a, $b, $lessthan)
{
      if ($lessthan($a, $b)) return -1;
      if ($lessthan($b, $a)) return 1;
      return 0;
}
array_shuffle(array)

Return array in shuffled order. Numeric keys are reindexed.

Parameters

array (array) – the array

Returns

array in shuffled order

Return type

array

array_unique(array)

Return an array with unique values (the first key is preserved).

Parameters

array (array) – the array

Returns

array with unique values

Return type

array

6.2. Cryptographic

aes_decrypt(message, key, mode[, options])

Decrypt a message using AES. On error none is returned.

Parameters
  • message (string) – the message to decrypt

  • key (string) – the key as raw bytes (no padding is done)

  • mode (string) – the block cipher mode of operation (ecb or cbc)

  • options (array) – options array

Returns

the message decrypted

Return type

string or none

The following options are available in the options array.

  • iv (string) The initialization vector as bytes (16 bytes for cbc).

  • padding (boolean) Use PKCS7 padding. The default is true.

Note

The key length must be either 16 bytes for AES-128, 24 bytes for AES-192 or 32 bytes for AES-256. No NUL bytes padding nor truncation is done on either the key or iv. The example below shows how to do manual padding.

$message = aes_decrypt(
                        $encrypted,
                        pack("a32", "short aes-256 key"),
                        "cbc",
                        ["iv" => pack("x16")]
                );
aes_encrypt(message, key, mode[, options])

Encrypt a message using AES. On error none is returned.

Parameters
  • message (string) – the message to encrypt

  • key (string) – the key as raw bytes (no padding is done)

  • mode (string) – the block cipher mode of operation (ecb or cbc)

  • options (array) – options array

Returns

the message encrypted

Return type

string or none

The following options are available in the options array.

  • iv (string) The initialization vector as bytes (16 bytes for cbc).

  • padding (boolean) Use PKCS7 padding. The default is true.

Note

The key length must be either 16 bytes for AES-128, 24 bytes for AES-192 or 32 bytes for AES-256. No NUL bytes padding nor truncation is done on either the key or iv. The example below shows how to do manual padding.

$encrypted = aes_encrypt(
                        $message,
                        pack("a32", "short aes-256 key"),
                        "cbc",
                        ["iv" => pack("x16")]
                );
hmac_md5(key, message[, options])

Return the HMAC MD5 hash of message with the key.

Parameters
  • key (string) – the HMAC key

  • message (string) – the value to hash

  • options (array) – options array

Returns

the hash value hex encoded

Return type

string

The following options are available in the options array.

  • binary (boolean) Return binary instead of hex format. The default is false.

hmac_sha1(key, message[, options])

Return the HMAC SHA1 hash of message with the key.

Parameters
  • key (string) – the HMAC key

  • message (string) – the value to hash

  • options (array) – options array

Returns

the hash value hex encoded

Return type

string

The following options are available in the options array.

  • binary (boolean) Return binary instead of hex format. The default is false.

hmac_sha2(key, message, hashsize[, options])

Return the HMAC SHA2 hash of message with the key.

Parameters
  • key (string) – the HMAC key

  • message (string) – the value to hash

  • hashsize (number) – the hash size (must be 256 or 512)

  • options (array) – options array

Returns

the hash value hex encoded

Return type

string

The following options are available in the options array.

  • binary (boolean) Return binary instead of hex format. The default is false.

md5(message[, options])

Return the MD5 hash of message.

Parameters
  • message (string) – the value to hash

  • options (array) – options array

Returns

the hash value hex encoded

Return type

string

The following options are available in the options array.

  • binary (boolean) Return binary instead of hex format. The default is false.

sha1(message[, options])

Return the SHA1 hash of message.

Parameters
  • message (string) – the value to hash

  • options (array) – options array

Returns

the hash value hex encoded

Return type

string

The following options are available in the options array.

  • binary (boolean) Return binary instead of hex format. The default is false.

sha2(message, hashsize[, options])

Return the SHA2 hash of message.

Parameters
  • message (string) – the value to hash

  • hashsize (number) – the hash size (must be 256 or 512)

  • options (array) – options array

Returns

the hash value hex encoded

Return type

string

The following options are available in the options array.

  • binary (boolean) Return binary instead of hex format. The default is false.

hash(message)

Return the numeric hash value of the message. The hash value is same for equal messages.

Parameters

message (string) – the value to hash

Returns

the hash value

Return type

number

rsa_privatekey(privatekey)

Return a RSA privatekey resource from a PEM certificate (--- BEGIN PRIVATE KEY ---). On error none is returned.

Parameters

privatekey (string) – the private key in PEM format

Returns

the privatekey

Return type

RSAPrivateKey resource or none

is_rsa_privatekey(privatekey)

Return a true if privatekey is a RSA privatekey resource.

Parameters

privatekey (any) – the privatekey

Returns

if the argument is a privatekey

Return type

boolean

rsa_sign(message, privatekey[, options])

RSA sign a message digest using a hash function. On error none is returned.

Parameters
  • message (string) – the message to sign

  • privatekey (RSAPrivateKey or string) – the private key resource or string

  • options (array) – options array

Returns

the message signature

Return type

string or none

The following options are available in the options array.

  • hash (string) The hash method to use (md5, sha1, sha256 or sha512). The default is sha256.

  • format (string) The private key format to use PrivateKeyInfo (PKCS#8) or RSAPrivateKey. The default is RSAPrivateKey.

  • pem (boolean) If the private key is in PEM format or raw bytes. The default is false.

  • id (boolean) If the private key is given as an id of an RSA key in the configuration. The default is false.

rsa_verify(message, signature, publickey[, options])

RSA verify a message digest using a hash function. On error none is returned.

Parameters
  • message (string) – the message to verify

  • signature (string) – the signature for the message as raw bytes

  • publickey (string) – the public key

  • options (array) – options array

Returns

if the signature verifies

Return type

boolean or none

The following options are available in the options array.

  • hash (string) The hash method to use (md5, sha1, sha256 or sha512). The default is sha256.

  • format (string) The public key format to use SubjectPublicKeyInfo or RSAPublicKey. The default is RSAPublicKey.

  • pem (boolean) If the public key is in PEM format or raw bytes. The default is false.

  • id (boolean) If the public key is given as an id of an RSA key in the configuration. The default is false.

ed25519_privatekey(privatekey)

Return a ED25519 privatekey resource from a PEM certificate (--- BEGIN PRIVATE KEY ---). On error none is returned.

Parameters

privatekey (string) – the private key in PEM format

Returns

the privatekey

Return type

ED25519PrivateKey resource or none

is_ed25519_privatekey(privatekey)

Return a true if privatekey is a ED25519 privatekey resource.

Parameters

privatekey (any) – the privatekey

Returns

if the argument is a privatekey

Return type

boolean

ed25519_sign(message, privatekey)

ED25519 sign a message. On error none is returned.

Parameters
  • message (string) – the message to sign

  • privatekey (ED25519PrivateKey or string) – the private key resource or string (as raw bytes)

Returns

the message signature

Return type

string or none

ed25519_verify(message, signature, publickey)

ED25519 verify a message. On error none is returned.

Parameters
  • message (string) – the message to sign

  • signature (string) – the signature as raw bytes

  • publickey (string) – the private key as raw bytes

Returns

if the signature verifies

Return type

boolean or none

pkcs7_sign(message, certificate[, options])

PKCS7 sign (S/MIME) a message. If certificate is given as an associative array it should include a x509 (X509Resource), privatekey (*PrivateKeyResource) and optionally a chain (array) of X509Resources. If certificate is given as a string it should either be an id or a PEM encoded string with a x509 certificate, a chain and a privatekey. On error none is returned.

Parameters
  • message (string) – the message to sign

  • certificate (array or string) – the certificate and privatekey to use

  • options (array) – options array

Returns

the message signature

Return type

string or none

The following options are available in the options array.

  • id (boolean) If a certificate argument is given as an string, use this to indicate a id of a certificate in the configuration. The default is false.

  • detached (boolean) If the signature should be detached (not include the message itself). The default is true.

If the certificate argument contains multiple certificates (intermediates) they will be included in the signature as well.

random_bytes(bytes)

Return a string of random bytes (at most 1MiB).

Parameters

bytes (number) – number of bytes to return

Returns

random bytes

Return type

string

random_number([first, last])

Return a random integer between first and last (inclusive) or a random double (decimal) between 0 and 1 (inclusive).

Parameters
  • first (number) – first possible number

  • last (number) – last possible number

Returns

the random number

Return type

number

crypt(key, salt)

Uses the underlying operating system’s crypt() function.

Parameters
  • key (string) – the user’s typed password

  • salt (string) – the salt

Returns

the encrypted string

Return type

string

if (crypt($password, $encryptedpassword) === $encryptedpassword)
  echo "match";

6.3. Data types

length(value)

Return the length of an array (items) or a string (characters). For all other datatypes none is returned.

Parameters

value (any) – the value

Returns

the length

Return type

number or none

array([...args])

This function creates an array.

Parameters

...args (any) – the input

Returns

an array

Return type

array

Note

array is not a function, it’s a language construct to create an array type. It’s an alias for the short array syntax [].

boolean(value)

This function converts the input of value to the boolean type (according to the truthiness) table.

Parameters

value (any) – the input

Returns

a boolean

Return type

boolean

number(value)

This function converts the input of value to the number type. Decimal and hexadecimal (Ox) numbers are supported. If the input contains an invalid number as string or type 0 is returned.

Parameters

value (any) – the input

Returns

a number

Return type

number

string(value)

This function converts the input of value to the string type, hence converting it to its string representation.

Parameters

value (any) – the input

Returns

a string

Return type

string

is_array(value)

Returns true if the type of value is an array.

Parameters

value (any) – the input

Returns

the result

Return type

boolean

is_boolean(value)

Returns true if the type of value is a boolean.

Parameters

value (any) – the input

Returns

the result

Return type

boolean

is_function(value)

Returns true if the type of value is a function.

Parameters

value (any) – the input

Returns

the result

Return type

boolean

is_number(value)

Returns true if the type of value is a number.

Parameters

value (any) – the input

Returns

the result

Return type

boolean

is_object(value)

Returns true if the type of value is an object.

Parameters

value (any) – the input

Returns

the result

Return type

boolean

is_string(value)

Returns true if the type of value is a string.

Parameters

value (any) – the input

Returns

the result

Return type

boolean

isset(x)

Returns true if the variable is defined.

Note

This is not a regular function. It’s a language construct and will only accept variables as input.

Parameters

x (variable) – a variable

Returns

the result

Return type

boolean

unset(x)

Unsets the variable or array index or slice of x, it return true if the variable or array index was defined.

Note

This is not a regular function. It’s a language construct and will only accept variables as input.

Parameters

x (variable) – a variable

Returns

if x was unset

Return type

boolean

class Map

The Map class maps keys to values. Keys are unique and may only point to a single value. This map is strongly-typed, meaning you have to define which data types you intend to store in it. There is a limited number of key types, but they are optimized for performance. As for value you may choose to use the any type to support all data types and also mixed in the map, but it is more memory efficent to use a specific type.

constructor(keytype, valuetype)

Create a Map with the following data types.

Parameters
  • keytype (string) – the key type

  • valuetype (string) – the value type

The following key types are available.

  • string

  • uint32, sint32

The following value types are available.

  • string

  • uint32, sint32

  • double

  • boolean

  • any (holds any value)

$map = Map("string", "uint32");
$map->set("foo", 123);

Warning

If the Map is shared between concurrent script executions (eg. using import or cache) do not modify (set, delete et.c.) the object as those operations are not thread-safe.

set(key, value)

Add or update the key with the value.

Parameters
  • key (string) – the key

  • value (string) – the value

Returns

if the element was created (true) or overwritten (false)

Return type

boolean

has(key)

Check if the key exists.

Parameters

key (string) – the key

Returns

if the key exists

Return type

boolean

get(key)

Get the value of key or none if it doesn’t exists.

Parameters

key (string) – the key

Returns

the value of key or none

Return type

any

delete(key)

Delete the key from the map.

Parameters

key (string) – the key

Returns

if the key existed before the remove

Return type

boolean

merge(key, value)

Merge key values in-place using the (+ operator). This can be used to add items to arrays or increment numbers.

Parameters
  • key (string) – the key

  • value (string) – the value

Returns

if the key existed before the merge

Return type

boolean

size()

Get number of keys in the map.

Returns

keys in map

Return type

number

clear()

Delete all keys in the map.

Return type

none

entries()

Iterator to all keys and values in the map in no specific order. The iterators value will be an array containg the [0=>key, 1=>value]. If iterating the map with foreach, the key and value will be mapped accordingly.

Return type

Iterator

$map = Map("string", "uint32");
$map->set("foo", 123);
$map->set("bar", 456);

$it = $map->entries();
echo $it->next(); // ["done"=>false,"value"=>[0=>"bar",1=>456]]
echo $it->next(); // ["done"=>false,"value"=>[0=>"foo",1=>123]]
echo $it->next(); // ["done"=>true,"value"=>]

foreach ($map->entries() as $k => $v)
  echo "$k = $v";
// bar = 456
// foo = 123
class Set

The Set class holds keys in a unique collection. This set is strongly-typed, meaning you have to define which data types you intend to store in it. There is a limited number of key types, but they are optimized for performance.

constructor(keytype)

Create a Set with the following data type.

Parameters

keytype (string) – the key type

The following key types are available.

  • string

  • uint32, sint32

$set = Set("string");
$set->add("foo");

Warning

If the Set is shared between concurrent script executions (eg. using import or cache) do not modify (add, delete et.c.) that object as those operations are not thread-safe.

add(key)

Add the key to the set.

Parameters

key (string) – the key

Returns

if the key was added (true) or not (false)

Return type

boolean

has(key)

Check if the key exists.

Parameters

key (string) – the key

Returns

if the key exists

Return type

boolean

delete(key)

Delete the key from the set.

Parameters

key (string) – the key

Returns

if the key existed before the remove

Return type

boolean

size()

Get number of keys in the set.

Returns

keys in set

Return type

number

clear()

Delete all keys in the set.

Return type

none

values()

Iterator to all keys in the set in no specific order. If iterating the set with foreach, the key (in the set) will be mapped to the value in the foreach statement.

Return type

Iterator

$set = Set("string");
$set->add("foo");
$set->add("bar");

$it = $set->values();
echo $it->next(); // ["done"=>false,"value"=>"bar"]
echo $it->next(); // ["done"=>false,"value"=>"foo"]
echo $it->next(); // ["done"=>true,"value"=>]

foreach ($set->values() as $v)
  echo "$v";
// bar
// foo

6.4. Date and time

executiontime()

Return the elapsed time since the beginning of the code execution.

Returns

the time in seconds (with decimals)

Return type

number

sleep(seconds)

Pause the code execution for x seconds.

Parameters

seconds (number) – the number of seconds to sleep

Returns

the time slept in seconds (with decimals)

Return type

number

Note

This function will suspend the current script execution while sleeping allowing for cooperative multitasking.

strftime(format[, time][, options])

Format according to the strftime manual.

Parameters
  • format (string) – the format string

  • time (number) – the default is current time without timezone

  • options (array) – options array

Returns

the time formatted (max length 100)

Return type

string

The following options are available in the options array.

  • local (boolean) Expect the time to be in the current local timezone. The default is true.

echo strftime("%H:%M:%S"); // prints current time eg "13:58:38"
strptime(datestring, format[, options])

Parse a date string according to the strptime manual with the time without timezone.

Parameters
  • datestring (string) – the date string

  • format (string) – the format string

  • options (array) – options array

Returns

the time in seconds

Return type

number

The following options are available in the options array.

  • local (boolean) Expect the time to be in the current local timezone. The default is true.

echo strptime("13:58:38", "%H:%M:%S"); // prints time of today at "13:58:38"
strpduration(during)

Parse a string formated as a duration. Supported time periods are d (days) h (hours), m (minutes) and s (seconds). On error none is returned.

Parameters

during (string) – the during string

Returns

the time in seconds

Return type

number

echo strpduration("1h3s"); // 3603
echo strpduration("1d"); // 86400
echo strpduration("3600"); // 3600
time()

Return elapsed seconds (unix time) since 1970-01-01T00:00:00Z without timezone.

Returns

the time in seconds (with decimals)

Return type

number

timelocal()

Return elapsed seconds (unix time) since 1970-01-01T00:00:00Z with timezone.

Returns

the time in seconds (with decimals)

Return type

number

uptime()

Return the monotonic time since system boot. Monotonic time is by definition suitable for relative time keeping, in contrast to time(). If you want to obtain the script execution time use executiontime().

Returns

the time in seconds (with decimals)

Return type

number

6.5. DNS

dns_query(host[, options])

Query for DNS records of a hostname.

Parameters
  • host (string) – the host

  • options (array) – options array

Returns

the result

Return type

array

The following options are available in the options array.

  • type (string or number) Query type (one of a, aaaa, mx, txt, cname, ns, ptr, srv or a RR type as number). The default is to query for a records.

  • extended_result (boolean) Get an extended result with more RR information. Must be used with numeric RR types. The default is false.

An array with either result or error in set in an associative array. dnssec is always included. result is the list of results (addresses, hostnames or strings) and error is the string representation of rcode or h_errno.

If extended_result is true, more information will be available in the result array for each record.

Type

Fields

a

type, ttl, address

aaaa

type, ttl, address

mx

type, ttl, preference, exchange

txt

type, ttl, string

cname

type, ttl, target

ns

type, ttl, target

ptr

type, ttl, target

srv

type, ttl, priority, weight, port, target

number

type, ttl, data

echo dns_query("nxdomain.halon.se");
// ["error"=>"NXDOMAIN","dnssec"=>false]

echo dns_query("halon.se");
// ["result"=>[0=>"54.152.237.238"],"dnssec"=>false]

echo dns_query(inet_reverse("8.8.8.8"), ["type" => "ptr", "extended_result" => true]);
// ["result"=>[0=>["type"=>"ptr","ttl"=>5,"target"=>"dns.google"]],"dnssec"=>false]

// DNSBL example
echo dns_query(inet_reverse("12.34.56.78", "dnsbl.example.com"));
// ["result"=>[0=>"127.0.0.1"],"dnssec"=>false]

// TLSA example
echo unpack("cccH*", dns_query("_25._tcp.mx.halon.io", ["type" => 52, "extended_result" => true])["result"][0]["data"]);
// [0=>3,1=>1,2=>1,3=>"42568063726264388f17d494cd3d01079ba1df4e60b1448e5670544cd7739218"]

Note

This function will suspend the current script execution while waiting for DNS responses allowing for cooperative multitasking.

domain_includes(subdomain, domain[, options])

Test if subdomain is a subdomain of domain. If the domain starts with a dot . it must be a subdomain of domain, hence it will not even if subdomain == domain.

Parameters
  • subdomain (string) – the subdomain

  • domain (string) – the domain

  • options (array) – options array

Returns

if subdomain is a subdomain of domain

Return type

boolean

The following options are available in the options array.

  • depth (number) The maximum allowed depth of the subdomains. The default is no limit.

domain_includes("www.halon.io", "halon.io"); // true
domain_includes("halon.io", "halon.io"); // true
domain_includes("www.halon.io", ".halon.io"); // true
domain_includes("halon.io", ".halon.io"); // false
domain_includes("test.www.halon.io", ".halon.io", ["depth" => 1]); // false
domain_publicsuffix(domain)

Return the public suffix (https://publicsuffix.org/) of a domain name. If not a valid TLD (none is returned).

Parameters

domain (string) – the domain

Returns

the public suffix

Return type

string or none

domain_publicsuffix("www.halon.io"); // "io"
domain_publicsuffix("www.google.co.uk"); // "co.uk"
domain_publicsuffix("example.badtld"); // none
idna_encode(domain)

IDNA encode a domain (to punycode). On error none is returned.

Parameters

domain (string) – a unicode domain

Returns

the punycode (ASCII) domain

Return type

string or none

echo idna_encode("fußball.example"); // xn--fuball-cta.example
idna_decode(domain)

IDNA decode a domain (to unicode). On error none is returned.

Parameters

domain (string) – a punycode (ASCII) domain

Returns

the unicode domain

Return type

string or none

echo idna_decode("xn--fuball-cta.example"); // fußball.example

6.6. Encodings and JSON

base32_encode(string[, options])

Base32 encode the string (RFC 4648).

Parameters

string (string) – the input string

Returns

the base32 representation

Return type

string

The following options are available in the options array.

  • padding (boolean) Use padding. The default is true.

base32_decode(string)

Base32 decode the string (RFC 4648).

Parameters

string (string) – the input string

Returns

the string representation

Return type

string

base64_encode(string)

Base64 encode the string.

Parameters

string (string) – the input string

Returns

the base64 representation

Return type

string

base64_decode(string)

Base64 decode the string.

Parameters

string (string) – the input string

Returns

the string representation

Return type

string

zlib_compress(string[, compression[, windowbits]])

Compress the string unsing zlib compression.

Parameters
  • string (string) – the input string

  • compression (number) – the compression level (default 9)

  • windowbits (number) – the window bits (default 15)

Returns

the compressed string

Return type

string

zlib_uncompress(string[, windowbits])

Compress the string unsing zlib compression.

Parameters
  • string (string) – the input string

  • windowbits (number) – the window bits (default 15)

Returns

the uncompressed string

Return type

string

csv_encode(values[, options])

Encode an array of strings as CSV encoded data. Multiline CSV data is supported.

Parameters
  • values (array) – strings to encode

  • options (array) – options array

Returns

an array of data

Return type

array

The following options are available in the options array.

  • delimiter (string) The format separator. The default is ,.

  • escape (string) Additional escape character (causing double quotes). The default is "\r\n and the delimiter.

echo csv_encode(["Hello", "World", "Hello World"], ["escape" => " "]);
// Hello,World,"Hello World"
csv_decode(string[, options])

Parse CSV data as string. Multiline CSV data is supported. On error none is returned.

Parameters
  • string (string) – CSV formated string

  • options (array) – options array

Returns

an array of data

Return type

array or none

The following options are available in the options array.

  • delimiter (string) The format separator. The default is ,.

  • comment (string) The comment character (first character only, eg # or ;). The default is not to allow comments.

  • header (boolean) If the CSV data includes a header. The default is true.

  • schema (array) Use a schema to convert columns to types.

The schema should be of the format of being an array keyed on the column name.

[
  "columnname" => [
      "type" => "string", "boolean" or "number",
      "format" => "json" or "regex",
      "nullable" => true or false or [ "", "NULL", ... ],
      "true" => [ "True", ... ],
      "false" => [ "False", ... ],
      "min_length" => ...
      ...other validation methods....
  ],
  ...
]

If the column is nullable either set nullable to true (to treat empty strings as none) or set nullable to an array of values to treat as none (eg. ["NULL"]). Likewise the boolean type has a true and false property for truthy and falsy values. The default is ["true"] and ["false"] (all lowercase).

Various types have different types of validations available.

Type

Validate

string

min_length (number)

string

max_length (number)

string

pattern (string)

string

format (string) json or regex

number

minimum (number)

number

maximum (number)

number

exclusive_minimum (number)

number

exclusive_maximum (number)

number

multiple_of (number)

any

enum (array)

echo csv_decode("enabled\nyes\nno", ["schema" => [
                "enabled" => ["type" => "boolean", "true" => ["yes"], "false" => ["no"]]
            ]]);
// [0=>["enabled"=>true],1=>["enabled"=>false]]

Note

It’s possible to import CSV data at compile time to a variable using the import statement.

json_encode(value[, options])

JSON encode a HSL data type. On error none is returned.

Parameters
  • value (any) – HSL data type

  • options (array) – options array

Returns

a JSON representation of value

Return type

string or none

The following options are available in the options array.

  • ensure_ascii (boolean) Convert all non-ASCII characters (UTF-8) to unicode (\uXXXX). The default is true.

  • pretty_print (boolean) Pretty print the JSON output. The default is false.

  • type_error (boolean) If conversion should fail on non-convertable types (or convert to none). The default is true.

Encode an array, number or string into a JSON representation (string). The encoding distinguishes arrays from objects if they are sequentially numbered from zero. On encoding errors an object with the data type of undefined is returned. All non-ASCII characters will be escaped as Unicode code points (\uXXXX).

Note

Since object keys are converted to strings (even numeric once) a json_encode() followed by a json_decode() does not always yield the same result.

json_decode(string[, options])

Decodes a JSON string into a HSL data type. On error none is returned.

Parameters
  • string (string) – JSON serialized data

  • options (array) – options array

Returns

the decoded string as the correct type

Return type

any or none

The following options are available in the options array.

  • allow_comments (boolean) Allow and ignore comments. The default is false.

The following translations are done (JSON to HSL).

  • object to associative array (is_array)

  • array to array (is_array)

  • string to string (is_string)

  • number to number (is_number)

  • true to true (is_boolean)

  • false to false (is_boolean)

  • null to none

Note

It’s possible to import JSON data at compile time to a variable using the import statement.

url_encode(string)

URL encode the string (RFC 3986).

Parameters

string (string) – the input string

Returns

the URL encoded representation

Return type

string

url_decode(string)

URL decode the string (RFC 3986).

Parameters

string (string) – the input string

Returns

the string representation

Return type

string

mimeword_encode(string)

MIME word encode the string (=?utf-8?Q?string?=).

Parameters

string (string) – the input string

Returns

the MIME word encoded representation

Return type

string

mimeword_decode(string)

MIME word decode the string (=?charset?encoding?encoded-text?=).

Parameters

string (string) – the input string

Returns

the string representation

Return type

string

yaml_decode(string[, options])

Decodes a YAML string into a HSL data type. On error none is returned.

Parameters
  • string (string) – YAML serialized data

  • options (array) – options array

Returns

the decoded string as the correct type

Return type

any or none

The following options are available in the options array.

  • tags (array) An array of callback functions to parse tagged values. See example below.

Types are automatically detected based on the following rules:

  • Quoted strings are always converted to strings.

  • Unquoted values are first tested as numbers, then booleans, before falling back to strings.

echo yaml_decode(''my-set: !Set
  - item1
  - item2
  - item3
my-map: !Map
  item1: !Regex /pattern1/
  item2: !Regex /pattern2/'', [
    "tags" => [
      "!Map" => function ($data) {
        $map = Map("string", "any");
        foreach ($data as $k => $v)
          $map->set($k, $v);
        return $map;
      },
      "!Set" => function ($data) {
        $map = Set("string");
        foreach ($data as $k => $v)
          $map->add($v);
        return $map;
      },
      "!Regex" => function ($data) {
        return pcre_compile($data);
      },
      "!PrivateKey" => function ($data) {
        $k = rsa_privatekey($data);
        if ($k == none)
                $k = ed25519_privatekey($data);
        return $k;
      },
      "!X509" => function ($data) {
        return X509::String($data);
      },
      "!MailMessage" => function ($data) {
        return MailMessage::String($data);
      },
  ]
]); // ["my-set"=>__OBJECT#Set#1__,"my-map"=>__OBJECT#Map#1__]

Note

It’s possible to import YAML data at compile time to a variable using the import statement.

pack(format[, ...args])

Pack arguments into a binary string. On error none is returned.

Parameters
  • format (string) – the pack format

  • ...args (any) – the arguments for the pack format

Returns

the packed data

Return type

string or none

The format may contain the following types. Some types may be followed by a * (an end-of-argument(s) repeater or a numeric repeater, eg. “Z*C3”).

Code

Repeaters

Type

HSL type

Bytes

a

n, *

String

String

1

C

n, *

Char

Number

1

e

n, *

Double (LE)

Number

8

E

n, *

Double (BE)

Number

8

H

n, *

Hex

String

1

n

n, *

Unsigned short (16 bit, BE)

Number

2

N

n, *

Unsigned long (32 bit, BE)

Number

4

v

n, *

Unsigned short (16 bit, LE)

Number

2

V

n, *

Unsigned long (32 bit, LE)

Number

4

x

n

NULL

1

Z

n, *

String (NULL terminated)

String

1

unpack(format, data[, offset = 0])

Unpack data from a binary string. On error none is returned.

Parameters
  • format (string) – the unpack format

  • data (string) – the packed data

  • offset (number) – the offset to begin unpack from

Returns

the unpacked data

Return type

array or none

The format may contain the following types. Some types may be followed by a * (an end-of-argument(s) repeater or a numeric repeater, eg. “Z*C3”).

Code

Repeaters

Type

HSL type

Bytes

a

n, *

String

String

1

c

n, *

Signed char

Number

1

C

n, *

Char

Number

1

e

n, *

Double (LE)

Number

8

E

n, *

Double (BE)

Number

8

H

n, *

Hex

String

1

n

n, *

Unsigned short (16 bit, BE)

Number

2

N

n, *

Unsigned long (32 bit, BE)

Number

4

v

n, *

Unsigned short (16 bit, LE)

Number

2

V

n, *

Unsigned long (32 bit, LE)

Number

4

x

n

Skip bytes

1

Z

n, *

String (excluding NULL)

String

1

class Iconv

This class allows characters set conversions using the Iconv library. Be aware that different versions of Iconv may have subtile differences.

constructor(fromcharset, tocharset)

Create a class for conversions between two character sets.

Parameters
  • fromcharset (string) – the input character set

  • tocharset (string) – the output character set

$text = Iconv("UTF-8", "ASCII//TRANSLIT//IGNORE");
echo $text->convert("Hello wörld"); // Hello wrld
close()

Close the Iconv resource and destroy the internal resource.

Note

Iconv classes are automatically garbage collected (closed). However you may want to explicitly call close.

convert(text)

Convert the text between the two different character sets. On error none is returned and you may call Iconv.errno() to get the error code.

Parameters

text (string) – text to convert

Returns

text

Return type

string or none

errno()

Get the latest errno returned from the underlying Iconv API.

Returns

errno

Return type

number

6.7. File and HTTP

class File

This class allows low level file access. A file resource is created for each File instance, this resource is automatically garbage collected (closed) once the object is destroyed.

constructor(filename[, options])

Open a virtual file from the configuration based on id, or a file on disk (using the file:// syntax). On error none is returned.

Parameters
  • filename (string) – the file name

  • options (array) – options array

The following options are available in the options array.

  • buffered (boolean) Buffer a file:// into memory or read from file descriptor. The default is true.

$file = File("myfile.txt");
while ($data = $file->read(8192))
        echo $data;

Note

In hsh a special file URI is available for stdin hsh://stdin.

constructor(fileresource)

Open a virtual file from a FileResource. On error none is returned.

Parameters

fileresource (FileResource) – a FileResource

close()

Close the file and destroy the internal file resource.

Returns

none

Return type

None

Note

Files are automatically garbage collected (closed). However you may want to explicitly call close.

read([length])

Read data from file. On EOF an empty string is returned. On error none is returned.

Parameters

length (number) – bytes to read (max 65536)

Returns

data

Return type

string or none

Note

If no length is given, all the remaning data until EOF will be read in one operation.

readline()

Read a line from file (without the CRLF or LF). If there are no more lines false is returned, and on error none is returned.

Returns

data

Return type

string, boolean or none

seek(offset[, whence = "SEEK_SET"])

Seek to the offset in the file. On error none is returned.

Parameters
  • offset (number) – the offset

  • whence (string) – the position specified by whence

Returns

position

Return type

number or none

Whence may be any of

Name

Position

SEEK_CUR

relative offset to the current position

SEEK_SET

absolute offset from the beginning

SEEK_END

negative offset from the end of the file

tell()

Get the current file position. On error none is returned.

Returns

position

Return type

number or none

getPath()

Get the path of a file. If no path information is available none is returned.

Returns

path

Return type

string or none

toFFIValue()

Return a shared pointer to a C FILE* representing the current File content and position. On error none is returned.

Returns

An FFIValue of pointer type

Return type

FFIValue or none

Note

The pointer is shared with the File instance, any operation on the File instance will also affect FILE pointer. However read operations on the FILE pointer will not affect the File position (File.tell()). The FILE pointer must not be closed or deleted.

#include <cstdio>

extern "C" void processfile(FILE* fp) {
  fseek(fp, 0, SEEK_SET);
}
static String(data)

Return a File resource containing the data.

Parameters

data (string) – the content

Returns

A file resource

Return type

File

$file = File::String("Hello\nWorld");
echo $file->readline(); // "Hello"
static read(filename)

Read all data from file. On error none is returned.

Parameters

filename (string) – the file name

Returns

data

Return type

string or none

$data = File::read("file.txt");
if ($data != none)
  echo length($data);
http(url[, options[, get[, post]]])

Make HTTP/HTTPS request to a URL and return the content.

Parameters
  • url (string) – URL to request

  • options (array) – options array

  • get (array) – GET variables, replaced and encoded in URL as $1, $2…

  • post (array, string or function) – POST data

Returns

if the request was successful (2XX) the content is returned, otherwise none is returned

Return type

string, array or none

The following options are available in the options array.

  • extended_result (boolean) Get an extended result with response code. The default is false.

  • connect_timeout (number) Connection timeout (in seconds). The default is 10 seconds.

  • timeout (number) Timeout (in seconds) for the request. The default is to wait indefinitely.

  • http_version (string) Send the request using a specific HTTP version (1.0, 1.1 or 2). The default is to use latest possible available.

  • post_size (number) Explicitly set the POST data size. The default is automatically calculated (but needs to be set when the POST data send using HTTP/1.0 and a POST data function callback).

  • max_file_size (number) Maximum file size (in bytes). The default is no limit.

  • sourceip (string) Explicitly bind an IP address. The default is to be chosen by the system.

  • sourceipid (string) Explicitly bind an IP address ID. The default is to be chosen by the system.

  • unix_socket_path (string) Unix socket path to connect to (instead of IP).

  • method (string) Request method. The default is GET unless POST data is sent.

  • headers (array) An array of additional HTTP headers as strings.

  • response_headers (boolean) Return the full request, including response headers (regardless of HTTP status). The default is false.

  • redirects (number) Specify the number of 304 redirects to follow (use -1 for unlimited). The default is 0 (not to follow redirects).

  • tls_verify_peer (boolean) Verify peer certificate. The default is true.

  • tls_verify_host (boolean) Verify certificate hostname (CN). The default is false.

  • tls_client_cert (array or string) If given as an associative array it should include a x509 (X509Resource), privatekey (*PrivateKeyResource) and optionally a chain (array) of X509Resources. If given as a string use the following id of a certificate in the configuration as client certificate. The default is to not send a client certificate.

  • proxy (string) Use a HTTP proxy. See CURL_PROXY manual. The default is to inherit proxy settings from the system. Setting it to an empty string will disable the proxy.

  • username (string) The authenticate username (default is Basic authentication)

  • password (string) The authenticate password

  • aws_sigv4 (string) aws_sigv4 option (see CURLOPT_AWS_SIGV4), for example aws:amz:us-east-1:s3. Use this option together with username and password.

If the option extended_result is true, the function returns an array containing the status code, content, and optionally an headers array if response_headers is enabled. If no valid HTTP response is receivied, none is returned.

The POST data may be sent in three different ways, depending on the different types, different encodings will be applied. The default Content-Type is always application/x-www-form-urlencoded if not changed using the headers options.

  • Associative array: The data will be properly encoded as a=b&c=d (x-www-form-urlencoded).

  • String: The data will be POSTed as is.

  • Function callback: The function callback is repeatedly called with one argument, the max length to return as a string. If the function return an empty string, the POST is done. If the function return none an error is triggered and the http() function will fail. This is useful for chunked POST data.

$response = http("http://halon.io/", [
    "extended_result" => true,
    "headers" => ["Host: example.com", "Accept: application/json"]
  ]);
if ($response) {
  echo $response;
}

$f = File::String(json_encode("POST this data as JSON"));
$response = http("http://halon.io/", [
    "extended_result" => true,
    "headers" => ["Content-Type: application/json", "Accept: application/json"]
  ], [], function ($max) closure ($f) {
    return $f->read($max);
  });
if ($response) {
  echo $response;
}

$file = File::String("POST this data as form-data");
$name = "test.txt";
$boundary = uuid();
$preamble = array_join([
    "--".$boundary,
    "Content-Disposition: form-data; name=\"file\"; filename=\"".$name."\"",
    "Content-Type: application/octet-stream",
  ], "\r\n")."\r\n\r\n";
$postamble = "\r\n--".$boundary."--\r\n";
$data = [$preamble, $file, $postamble];
$response = http("http://10.0.0.1/upload", [
    "extended_result" => true,
    "headers" => ["Content-type: multipart/form-data; boundary=".$boundary]
  ], [],
  function ($size) closure ($data) {
    while (length($data)) {
      if (is_string($data[0])) {
        $x = $data[0][0:$size];
        $data[0] = $data[0][$size:];
      } else {
        $x = $data[0]->read($size);
      }
      if ($x !== "")
        return $x;
      $data = $data[1:];
    }
    return "";
  });
if ($response) {
  echo $response;
}
url_parse(url[, options])

Parse an URL into its components (schema, username, password, hostname, port, path, query and fragment). Missing components are not included.

Parameters
  • url (string) – URL to parse

  • options (array) – options array

Returns

if the parse was successful each components part is return as an associative array, otherwise none is returned

Return type

array or none

The following options are available in the options array.

  • extended_result (boolean) If true on error, an associative array with error, errno is returned. The default is false.

echo url_parse("https://halon.io"); // ["scheme"=>"https","hostname"=>"halon.io","path"=>"/"]

6.8. Mail

envelope_address_parse(address)

Parse an email address into localpart and domain. On error none is returned.

Parameters

address (string) – email addresses

Returns

email address parts

Return type

array or none

echo envelope_address_parse("[email protected]"); // ["localpart"=>"user","domain"=>"example.com"]
envelope_localpart_escape(localpart)

Apply escaping to the an email envelope localpart.

Parameters

localpart (string) – localpart

Returns

escaped localpart

Return type

string

echo envelope_localpart_escape("email address") . "@example.org"; // "email address"@example.org
header_addresslist_compile(addresses)

Create a properly formated string of list of addresses often used with From, To and CC headers. The addresses array should include a list of associative arrays containg name and address.

Parameters

addresses (array) – an array of address objects

Returns

list of addresses

Return type

string

echo header_addresslist_compile([
  ["name" => "John Doe", "address" => "[email protected]"],
  ["name" => "Jane Doe", "address" => "[email protected]"],
]); // "John Doe" <[email protected]>, "Jane Doe" <[email protected]>
header_addresslist_extract(value[, options])

Extract addresses from a header value or field, often used with From, To and CC headers. The name option will make this function return an associative array with the display name and address. On error none is returned.

Parameters
  • value (string) – value to extract email addresses from

  • options (array) – an options array

Returns

email addresses

Return type

array or none

The following options are available in the options array.

  • name (boolean) Return an array of name and address. The default is false.

  • field (boolean) If the value is a header field (Header: Value) format. The default is false.

  • decode (boolean) Decode MIME words (=?charset?encoding?data?=`). The default is true.

echo header_addresslist_extract("Charlie <[email protected]>; James <[email protected]>", ["name" => true]);
// [0=>["name"=>"Charlie","address"=>"[email protected]"],1=>["name"=>"James","address"=>"[email protected]"]]

$fromAddresses = header_addresslist_extract("Charlie <[email protected]>; James <[email protected]>");
if ($fromAddresses and length($fromAddresses) > 1)
  echo "Too many From addresses";
header_dkim_decode(value[, options])

Decode a Tag=Value list from a DKIM header value or field, often used with DKIM-Signature or ARC- headers. On error none is returned.

Parameters
  • value (string) – value to extract tags from

  • options (array) – an options array

Returns

tags

Return type

array or none

The following options are available in the options array.

  • field (boolean) If the value is a header field (Header: Value) format. The default is false.

$tags = header_dkim_decode("v=1; d=domain; s=selector; h=to:from:date:subject");
if ($tags and isset($tags["s"]) and isset($tags["d"]))
  echo $tags["s"]."._domainkey.".$tags["d"];
xtext_encode(text)

Encode xtext according to the rfc1891.

Parameters

text (string) – value to encode

Returns

the encoded value

Return type

string

xtext_decode(text)

Decode xtext according to the rfc1891.

Parameters

text (string) – value to decode

Returns

the decoded value

Return type

string

spf_query(ip, helo, domain)

Check the SPF status of the senderdomain.

Parameters
  • ip (string) – IP or IPv6 address to check

  • helo (string) – HELO/EHLO host name

  • domain (string) – domain to lookup

Returns

the result

Return type

array

An array with a result (string), reason (string) and in case of errors error (string) and errno (number) fields as an associative array. The result is returned as the string result as defined by libspf2 (eg. pass).

libspf error

result

SPF_RESULT_INVALID

invalid

SPF_RESULT_NEUTRAL

neutral

SPF_RESULT_PASS

pass

SPF_RESULT_FAIL

fail

SPF_RESULT_SOFTFAIL

softfail

SPF_RESULT_NONE

none

SPF_RESULT_TEMPERROR

temperror

SPF_RESULT_PERMERROR

permerror

Note

This function will suspend the current script execution while waiting for DNS responses allowing for cooperative multitasking.

6.9. Mathematical

abs(number)

Return the absolute value of a number.

Parameters

number (number) – the numeric value to process

Returns

the absolute value

Return type

number

ceil(number)

Return the integer value of a number by rounding up if necessary.

Parameters

number (number) – the numeric value to process

Returns

the integer value

Return type

number

floor(number)

Return the integer value of a number by rounding down if necessary.

Parameters

number (number) – the numeric value to process

Returns

the integer value

Return type

number

log(number[, base = e])

Return the logarithm of number to base.

Parameters
  • number (number) – the numeric value to process

  • base (number) – the base

Returns

the logarithm value

Return type

number

pow(base, exponent)

Return base raised to the power of the exponent.

Parameters
  • base (number) – the base

  • exponent (number) – the exponent

Returns

the power of

Return type

number

See also

It’s significantly faster to use the ** operator since it’s an operator and not a function.

round(number[, decimals = 0])

Return number rounded to precision of decimals.

Parameters
  • number (number) – the numeric value to process

  • decimals (number) – the number of decimals

Returns

the rounded value

Return type

number

sqrt(number)

Return the square root of number.

Parameters

number (number) – the numeric value to process

Returns

the square root

Return type

number

See also

It’s significantly faster to use the number ** 0.5 operator to get the square root since it’s an operator and not a function.

6.10. MIME

class MIME

This is a MIME “string builder” used to construct MIME parts.

constructor()

The MIME object “constructor” takes no function arguments.

$part = MIME();
$part->setType("multipart/alternative");
$part->appendPart(MIME()->setType("text/plain")->setBody("*Hello World*"));
$part->appendPart(MIME()->setType("text/html")->setBody("<strong>Hello World</strong>"));
echo $part->toString();

Note

Many of the MIME object’s member functions return this, allowing them to be called with method chaining.

echo MIME()->addHeader("Subject", "Hello")->setBody("Hello World")->toString();
addHeader(name, value[, options])

Add a header. The value may be encoded (if needed) and reformatted.

Parameters
  • name (string) – name of the header

  • value (string) – value of the header

  • options (array) – an options array

Returns

this

Return type

MIME

The following options are available in the options array.

  • encode (boolean) Fold and encode the header. The default is true.

  • encoding (string) Encoding to use (base64 or quoted-printable). The default is quoted-printable.

Note

If a Content-Type header is added, the value of MIME.setType() is ignored. If a Content-Transfer-Encoding header is added it will be used as the default encoding for the MIME.setBody().

appendPart(part)

Add a MIME part (child) object, this is useful when building a multipart MIME.

Parameters

part (MIME) – a MIME part object

Returns

this

Return type

MIME

Note

If not explicit set the Content-Type is set to multipart/mixed. The MIME boundary is also automatically created.

setBody(body)

Set the MIME part body content. In case the MIME part has children (multipart) this will be the MIME parts preamble. The body will be encoded as either quoted-printable or base64 depending on the type of data if no Content-Transfer-Encoding header is explicitly added.

Parameters

body (string) – the body

Returns

this

Return type

MIME

setType(type)

Set the type field of the Content-Type header. The default type is text/plain, and for text/… the charset is always utf-8.

Parameters

type (string) – the content type

Returns

this

Return type

MIME

setBoundary(boundary)

Set the MIME boundary for multipart/* messages. The default is to use an UUID.

Parameters

boundary (string) – the boundary

Returns

this

Return type

MIME

setDate([timestamp])

Add a Date header field. The default date is the current time.

Parameters

timestamp (number) – the unix timestamp

Returns

this

Return type

MIME

setFileName(filename)

Set the file name in the Content-Disposition header. The default disposition is attachment, but can be changed with MIME.setDisposition().

Parameters

filename (string) – the filename

Returns

this

Return type

MIME

setDisposition(type)

Set the disposition type in the Content-Disposition header.

Parameters

type (string) – the disposition type

Returns

this

Return type

MIME

signDKIM(selector, domain, key[, options])

Sign the MIME structure (message) using DKIM.

Parameters
  • selector (string) – selector to use when signing

  • domain (string) – domain to use when signing

  • key (resource or string) – private key to use, either a *PrivateKey resource, pki:X (or a private RSA key in PEM format or a ed25519 key binary/base64 encoded, but not recommended).

  • options (array) – options array

Returns

this

Return type

MIME

The following options are available in the options array.

  • canonicalization_header (string) header canonicalization (simple or relaxed). The default is relaxed.

  • canonicalization_body (string) body canonicalization (simple or relaxed). The default is relaxed.

  • algorithm (string) algorithm to hash the message with (rsa-sha1, rsa-sha256 or ed25519-sha256). The default is rsa-sha256.

  • additional_headers (array) additional headers to sign in addition to those recommended by the RFC.

  • exclude_headers (array) exclude headers to sign from those recommended by the RFC.

  • oversign_headers (array) headers to oversign. The default is from.

  • timestamp (boolean or number) add the t tag to the signature (may be an absolute unix timestamp). The default is false.

  • expiration (number) add the x tag to the signature (an absolute unix timestamp). The default is no expiration.

  • expiration_relative (number) add the x tag to the signature (seconds relative to timestamp or current time). The default is no expiration.

  • identity (string) add the i tag to the signature. The default is no identity tag.

  • headers (array) headers to sign. The default is to sign all headers recommended by the RFC.

  • body_length (number) length of the body to sign. The default is to sign the entire message.

  • id (boolean) If the key is given as an id of an private key in the configuration. The default is auto detect.

  • additional_signatures (array) An array of associative arrays for additional dual signing for the same canonicalization and settings.

    • selector (string) selector to use when signing (required)

    • domain (string) domain to use when signing (required)

    • key (resource or string) private key to use, either a *PrivateKey resource, pki:X (or a private RSA key in PEM format or a ed25519 key binary/base64 encoded, but not recommended). (required)

    • identity (string or none) add the i tag to the signature. The default is to inherit the primary identity tag. Use none to not add a identity tag.

    • id (boolean) If the key is given as an string, you may set id to true and not prefix the value with pki:. The default is auto detect.

    • algorithm (string) Only if the key is given as PEM or base64 data, you should the algorithm (rsa or ed25519).

Note

In the message the primary DKIM-Signature will be added first, and any additional will be prepended before the primary signature. The reason is that mail headers are added and reasoned about bottom up, similar to the top-most Received header is the latest one.

DKIM-Signature: second-additional-signature
DKIM-Signature: first-additional-signature
DKIM-Signature: primary-signature
Subject: Hello World

Message Content
toString()

Return the created MIME as a string. This function useful for debugging.

Returns

the MIME as string

Return type

string

toFile()

Return a File class for the current MIME object.

Returns

A File class for the current MIME object.

Return type

File

queue(sender, recipient, transportid[, options])

Queue the message.

Parameters
  • sender (string or array) – the sender email address, either as a string or an associative array with a localpart and domain. The domain support internationalized domain names (U-labels).

  • recipient (string or array) – the recipient email address, either as a string or an associative array with a localpart and domain. The domain support internationalized domain names (U-labels).

  • transportid (string) – the transport profile ID

  • options (array) – an options array

Returns

an id object (with transaction and queue)

Return type

array

The following options are available in the options array.

  • metadata (array) Add metadata to the queued message, as a key-value pair array of strings.

  • hold (boolean) Put the message in the hold (inactive) queue. The default is false.

  • tenantid (string) Assign a tenantid to the message.

  • jobid (string) Assign a jobid to the message.

  • priority (number) The queue priority (0 - normal, 1 - high). The default is 0.

  • quotas (array) An array of quotas to be associated with the message, for use with queue_quota().

  • delay (number) Delay the first delivery attempt, in seconds. The default is 0.

  • dsn (array) Associative array of envid (string), ret (string), notify (string) and orcpt (string).

MIME()
        ->addHeader("Subject", "Hello")
        ->setBody("Hi, how are you?")
        ->queue("", ["localpart" => "info", "domain" => "example.com"], "outbound");
send(sender, recipients, server)

Try to send the message to the server. See MailMessage.send().

class MailMessage : MIMEPart

This class extends the MIMEPart class, all instances of this class automatically holds a reference to the top level MIMEPart object.

MailMessage.reset()

Undo all changes on the message.

Returns

number of changes discarded

Return type

number

$mail->reset();
MailMessage.snapshot()

Take a snapshot of the current state of the MIME object (to be used with MailMessage.restore()).

Returns

the snapshot id

Return type

number

$id = $mail->snapshot();
MailMessage.restore(id)

Restore to a snapshot (to be used with MailMessage.snapshot()).

Parameters

id (number) – snapshot id

Returns

if restore was successful

Return type

boolean

$mail->restore($id);
MailMessage.modifyContent(start, count, data)

An advanced method of adding custom modification that will be applied to the message (it works the same way as other modification function, eg. MIMEPart.addHeader()). This function should not be used when there are MIMEPart operations available doing the supposed modification.

Parameters
  • start (number) – start offset of modification

  • count (number) – bytes to remove at position

  • data (string) – data to add at position

Returns

this

Return type

MailMessage

$mail = MailMessage::String("Subject: Hello\r\n\r\nHello");
$mail->modifyContent(18, 5, "World");
echo $mail->toString();
MailMessage.toFile()

Return a File class for the current MIME object (with all changes applied).

Returns

A File class for the current MIME object.

Return type

File

MailMessage.toString()

Return the MailMessage as a string (with all changes applied).

Returns

the MailMessage as string

Return type

string

MailMessage.signDKIM(selector, domain, key[, options])

Sign the message using DKIM. On error none is returned.

Parameters
  • selector (string) – selector to use when signing

  • domain (string) – domain to use when signing

  • key (resource or string) – private key to use, either a *PrivateKey resource, pki:X (or a private RSA key in PEM format or a ed25519 key binary/base64 encoded, but not recommended).

  • options (array) – options array

Returns

this

Return type

MailMessage or none

The following options are available in the options array.

  • canonicalization_header (string) header canonicalization (simple or relaxed). The default is relaxed.

  • canonicalization_body (string) body canonicalization (simple or relaxed). The default is relaxed.

  • algorithm (string) algorithm to hash the message with (rsa-sha1, rsa-sha256 or ed25519-sha256). The default is rsa-sha256.

  • additional_headers (array) additional headers to sign in addition to those recommended by the RFC.

  • exclude_headers (array) exclude headers to sign from those recommended by the RFC.

  • oversign_headers (array) headers to oversign. The default is from.

  • timestamp (boolean or number) add the t tag to the signature (may be an absolute unix timestamp). The default is false.

  • expiration (number) add the x tag to the signature (an absolute unix timestamp). The default is no expiration.

  • expiration_relative (number) add the x tag to the signature (seconds relative to timestamp or current time). The default is no expiration.

  • identity (string) add the i tag to the signature. The default is no identity tag.

  • headers (array) headers to sign. The default is to sign all headers recommended by the RFC.

  • body_length (number) length of the body to sign. The default is to sign the entire message.

  • id (boolean) If the key is given as an id of an private key in the configuration. The default is auto detect.

  • return_header (boolean) Return the DKIM signature as a string, instead of adding it to the message. The default is false.

  • arc (number) Create an ARC-Message-Signature header by setting the ARC “i” field.

  • additional_signatures (array) An array of associative arrays for additional dual signing for the same canonicalization and settings.

    • selector (string) selector to use when signing (required)

    • domain (string) domain to use when signing (required)

    • key (resource or string) private key to use, either a *PrivateKey resource, pki:X (or a private RSA key in PEM format or a ed25519 key binary/base64 encoded, but not recommended). (required)

    • identity (string or none) add the i tag to the signature. The default is to inherit the primary identity tag. Use none to not add a identity tag.

    • id (boolean) If the key is given as an string, you may set id to true and not prefix the value with pki:. The default is auto detect.

    • algorithm (string) Only if the key is given as PEM or base64 data, you should the algorithm (rsa or ed25519).

Note

In the message the primary DKIM-Signature will be added first, and any additional will be prepended before the primary signature. The reason is that mail headers are added and reasoned about bottom up, similar to the top-most Received header is the latest one.

DKIM-Signature: second-additional-signature
DKIM-Signature: first-additional-signature
DKIM-Signature: primary-signature
Subject: Hello World

Message Content

Note

If return_header is used, you need to add the header yourself without encoding.

$dkimsig = $message->signDKIM("selector", "example.com", $key, ["return_header" => true]);
$message->addHeader("DKIM-Signature", $dkimsig, ["encode" => false]);

Note

Example commands to generate an ed25519 public/private key pair with OpenSSL.

# openssl genpkey -algorithm ed25519 -out dkim_ed25519.private
# openssl pkey -outform PEM -pubout -in dkim_ed25519.private
-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAt+BaReQe/Xs/jNbhGJre2Y1O4EUsHauy2Ygi5s3gc/0=
-----END PUBLIC KEY-----
# openssl pkey -outform DER -in dkim_ed25519.private | tail -c +17 | openssl base64
NvGwmGmY/vdZH75jDZs9HXe6RZUEx07BeOg3q1ffNRA=
MailMessage.verifyDKIM(headerfield, [options]])

DKIM verify a DKIM-Signature or ARC-Message-Signature header. The header should include both the header name and value (unmodified).

Parameters
  • headerfield (string) – the header to verify

  • options (array) – options array

Returns

associative array containing the result.

Return type

array

The following options are available in the options array.

  • dns_function (function) a custom DNS function. The default is to use the built in.

The DNS function will be called with the hostname (eg. 2018._domainkeys.example.com) for which a DKIM record should be returned. The result must be an array containing either an error field (permerror or temperror) or a result field with a DKIM TXT record as string.

The resulting array always contains a result field of either pass, permerror or temperror. In case of an error the reason is included in an error field. If the header was successfully parsed (regardless of the result) a tags field will be included.

Note

This function will suspend the current script execution while waiting for DNS responses allowing for cooperative multitasking.

MailMessage.send(sender, recipients, server)

Try to send the message to the server.

Parameters
  • sender (string or array) – the sender (MAIL FROM), an address object

  • recipients (array of (string or array)) – the recipient (RCPT TO), an array of address objects

  • server (string or array) – array with server settings or transport profile ID

Returns

associative array containing the result or an error

Return type

array

The address parameters should be either a string or an associative array with a localpart and domain and optionally a params field as an key-values array (to be sent in the MAIL FROM or RCPT TO command). The domain support internationalized domain names (U-labels). Transport profiles configured to use destination lookup by MX are not supported, see the note below.

$response = $message->send(
    ["localpart" => "nick", "domain" => "example.org"],
    [
        ["localpart" => "chris", "domain" => "example.com", "params" => ["NOTIFY" => "DELAY"]],
        ["localpart" => "charlie", "domain" => "example.com"],
    ],
    ["server" => "10.2.0.1", "tls" => "require"]);

if (isset($response["result"]))
{
    $result = $response["result"];
    $codes = [];
    if ($result["state"] == "EOD")
        $codes = ["reply_codes" => ["code" => $result["code"], "enhanced" => $result["enhanced"]]];
    if ($result["code"] >= 200 and $result["code"] <= 299)
        Accept($result["reason"], $codes);
    if ($result["code"] >= 500 and $result["code"] <= 599)
        Reject($result["reason"], $codes);
    Defer($result["reason"], $codes);
}
else
{
    $error = $response["error"];
    if (!$error["temporary"])
        Reject($error["message"]);
    Defer($error["message"]);
}

The following server settings are available in the server array.

  • server (string or array) The destination IP-address or hostname as a string, or an associative array with host (string) and mx (boolean). There is no default destination server.

  • port (number) TCP port. The default is 25.

  • helo (string) The default is to use the system hostname.

  • sourceip (string) Explicitly bind an IP address. The default is to be chosen by the system.

  • sourceipid (string) Explicitly bind an IP address ID. The default is to be chosen by the system.

  • nonlocal_source (boolean) Allow binding of non-local addresses (BINDANY). The default is false.

  • saslusername (string) If specified issue a AUTH LOGIN before MAIL FROM.

  • saslpassword (string) If specified issue a AUTH LOGIN before MAIL FROM.

  • saslmechanism (string) If specified issue the SASL mechanism and the saslpassword (used for eg. XOAUTH2).

  • tls (string) Use any of the following TLS modes; disabled, optional, optional_verify, dane, dane_fallback_require, dane_fallback_require_verify, dane_require, require or require_verify. The default is disabled.

  • tls_implicit (boolean) Use implicit TLS (do not use STARTTLS). The default is false.

  • tls_sni (string or boolean) Request a certificate using the SNI extension. If true the connected hostname will be used. The default is not to use SNI (false).

  • tls_protocols (string) Use one or many of the following TLS protocols; SSLv2, SSLv3, TLSv1, TLSv1.1, TLSv1.2 or TLSv1.3. Protocols may be separated by , and excluded by !. The default is !SSLv2,!SSLv3.

  • tls_ciphers (string) List of ciphers to support. The default is decided by OpenSSL for each tls_protocol.

  • tls_ciphersuites (string) List of TLS ciphersuites to support (TLSv1.3). The default is decided by OpenSSL for each tls_protocol.

  • tls_verify_host (boolean) Verify certificate hostname (CN). The default is false.

  • tls_verify_name (array) Hostnames to verify against the certificate’s CN and SAN (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • tls_client_cert (array or string) If given as an associative array it should include a x509 (X509Resource), privatekey (*PrivateKeyResource) and optionally a chain (array) of X509Resources. If given as a string use the following id of a certificate in the configuration as client certificate. The default is to not send a client certificate.

  • xclient (array) Associative array of XCLIENT attributes to send.

  • chunking (boolean) Enable CHUNKING support. The default is true.

  • pipelining (boolean) Enable PIPELINING support. The default is true.

  • protocol (string) The protocol to use; smtp or lmtp. The default is smtp.

  • mx_include (array) Filter the MX lookup result, only including ones matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • mx_exclude (array) Filter the MX lookup result, removing ones matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • mx_exclude_bypass (array) Before applying mx_exclude, allow the once matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • ip_exclude (array) Filter the IP addresses or networks, removing addresses listed.

  • ip_exclude_temporary (boolean) Specify if empty results due to filtered IP or MX addresses should result in a temporary or permanent error. The default is false (permanent error).

  • timeout (array) Associative array of state and the timeout in seconds. The default is set according to RFC2821.

  • connect_timeout (number) The connect timeout in seconds. The default is 30 seconds.

  • proxyprotocol (array) Associative array of server (IP), port as well as local sourceip to use when using an outbound PROXY PROTOCOL server.

If the send function resulted in a SMTP response you will get the SMTP response in a result field. This result field contains a state field (string) which indicates at what SMTP stage the error happened, a reason field (array of strings) containing the SMTP reponse (from the server) and a code field (number) containg the SMTP status code, optionally a enhanced (array of three numbers) field containg the SMTP enhanced status code. If a generic error happens the function will return a error field. This error field contains a temporary (boolean) field to indicate if the error may be transient, a reason field (string) containing a the error which happened and a type field (string) containing the type of error which happened (one of config, dns, network, dane, protocol, smtp, tls or plugin), for dns errors a subcategories is presented with a dns properites with one of the following value of other, nxdomain, nullmx, ipfamily, nodata or excluded.

If a SMTP connection could be established a connection field will be included. This field contains the localip field (string), the localipid field (string), the remoteip field (string) and the remotemx field (string).

A tls field will always be included, to indicate if the connection had TLS enabled.

The following state values are available.

BANNER

The initial SMTP greeting

HELO

EHLO

LHLO

STARTTLS

AUTH-CRAM-MD5

In reply to sending AUTH CRAM-MD5 command

AUTH-PLAIN

In reply to sending AUTH PLAIN command

AUTH-LOGIN

In reply to sending AUTH LOGIN command

AUTH-LOGIN-USER

In reply to sending AUTH LOGIN username

AUTH

In reply to last command of AUTH login attempt

XCLIENT

In reply to sending a XCLIENT command

MAIL

RCPT

DATA

In reply to sending the DATA command

BDAT

In reply to sending the BDAT command

EOD

In reply sending the End-of-DATA

RSET

NOOP

QUIT

Note

It’s not possible to use transport profiles configured to use destination lookup by MX, for the simple reason that this function supports sending to multiple recipients, on multiple domains/MX. You have to explicitly configure which host to deliver to. To use lookup MX for a specific domain use this server syntax.

$mail->send($sender, $recipients, ["server" => ["host" => "example.com", "mx" => true]]);
MailMessage.queue(sender, recipient, transportid[, options])

Queue the message.

Parameters
  • sender (string or array) – the sender email address, either as a string or an associative array with a localpart and domain

  • recipient (string or array) – the recipient email address, either as a string or an associative array with a localpart and domain

  • transportid (string) – the transport profile ID

  • options (array) – an options array

Returns

an id object (with transaction and queue)

Return type

array

The following options are available in the options array.

  • metadata (array) Add metadata to the queued message, as a key-value pair array of strings.

  • hold (boolean) Put the message in the hold (inactive) queue. The default is false.

  • tenantid (string) Assign a tenantid to the message.

  • jobid (string) Assign a jobid to the message.

  • priority (number) The queue priority (0 - normal, 1 - high). The default is 0.

  • quotas (array) An array of quotas to be associated with the message, for use with queue_quota().

  • delay (number) Delay the first delivery attempt, in seconds. The default is 0.

  • dsn (array) Associative array of envid (string), ret (string), notify (string) and orcpt (string).

static MailMessage.String(data)

Return a MailMessage resource containing the data.

Parameters

data (string) – the content

Returns

A MailMessage resource

Return type

MailMessage or none

static MailMessage.File(file)

Return a MailMessage resource containing the file’s content.

Parameters

file (File) – the content

Returns

A MailMessage resource

Return type

MailMessage or none

class MIMEPart

This class represent a MIME part in the MIME tree.

Note

This class can only be accessed through the extended MailMessage class or from functions returning this object type eg. MIMEPart.getParts().

Note

Changes done to any MIME object will not be reflected on consecutive calls to “get” functions, however they will be applied to the message upon delivery. Also multiple calls to the same “set” function may yield undefined behaviour (like calling setBody twice).

MIMEPart.getID()

Return the MIME part’s ID.

Returns

part id

Return type

string

MIMEPart.getSize()

Return the MIME part’s size in bytes.

Returns

size in bytes

Return type

number

MIMEPart.getFileName()

Return the MIME part’s file name (if it has one).

Returns

file name

Return type

string or none

MIMEPart.getType()

Return the MIME part’s Content-Type’s type field (eg. text/plain).

Returns

content type

Return type

string or none

MIMEPart.getHeader(name[, options])

Return the value of a header (if multiple headers with the same name exists, the first will be returned). If no header is found, the value none is returned. The name is not case sensitive.

Parameters
  • name (string) – name of the header

  • options (array) – an options array

Returns

header value

Return type

string or none

The following options are available in the options array.

  • index (number) The index of the header, from the top, starting at zero (per header name). The default is 0.

  • field (boolean) Get the header field as is (including the name, CRLF and whitespace preserved). The default is false.

  • decode (boolean) Unfold and decode the header’s MIME words (=?utf-8?q?…?=). The default is true.

if (is_string($contentid = $part->getHeader("Content-ID")))
        echo "Content-ID is $contentid";
// DKIM verify example
$dkimHeader = $part->getHeader("DKIM-Signature", ["field" => true]); // field needed for DKIM
if ($dkimHeader)
        echo $part->verifyDKIM($dkimHeader);

Note

The MIMEPart.getHeader() function family will return headers as a UTF-8 string with all MIME encoded-words decoded (=?charset?encoding?data?=). However even if headers must be in 7-bit ASCII, some senders do not conform to this and do send headers with different charset encodings. In those cases we (1) Use the MIME-parts “Content-Type” headers charset when converting to UTF-8. (2) If there is no charset information available we use a statistical charset detection function. (3) We just pretend it to be US-ASCII and covert it to UTF-8 anyway (guaranteeing the result will be valid UTF-8).

MIMEPart.getHeaders(name[, options])

Return a list of header values. If no header is found, an empty list is returned. The name is not case sensitive.

Parameters
  • name (string) – name of the header

  • options (array) – an options array

Returns

header values

Return type

array of string

The following options are available in the options array.

  • field (boolean) Get the header field as is (including the name). The default is false.

  • decode (boolean) Unfold and decode the header’s MIME words (=?utf-8?q?…?=). The default is true.

echo "Received headers: ".length(DATA()->getHeaders("Received"));
MIMEPart.getHeaderNames()

Return a list of all header names, from the top. The names are in lower case.

Returns

header names

Return type

array of string

MIMEPart.setHeader(name, value[, options])

Overwrite existing header(s) or create a new header. The name is not case sensitive.

Parameters
  • name (string) – name of the header

  • value (string) – value of the header

  • options (array) – an options array

Returns

number of headers changed

Return type

number

The following options are available in the options array.

  • index (number) The index of the header, from the top, starting at zero (per header name).

  • encode (boolean) Fold and encode the header. The default is true.

  • encoding (string) Encoding to use (base64 or quoted-printable). The default is quoted-printable.

MIMEPart.addHeader(name, value[, options])

Add a new header (at the top of the message).

Parameters
  • name (string) – name of the header

  • value (string) – value of the header

  • options (array) – an options array

Return type

none

The following options are available in the options array.

  • encode (boolean) Fold and encode the header. The default is true.

  • encoding (string) Encoding to use (base64 or quoted-printable). The default is quoted-printable.

MIMEPart.delHeader(name[, options])

Delete all headers by the name. The name is not case sensitive.

Parameters
  • name (string) – name of the header

  • options (array) – an options array

Returns

number of headers deleted

Return type

number

The following options are available in the options array.

  • index (number) The index of the header, from the top, starting at zero (per header name).

MIMEPart.setDateLater()

Add or set the Date header field upon message delivery/generation. The default date is the current time.

Returns

number of headers changed

Return type

number

Warning

If you also DKIM sign your messages when using this function it’s very important that you exclude the Date header from the DKIM signature using for example the exclude_headers option to MIME.signDKIM().

MIMEPart.remove()

Remove this MIME part.

Return type

none

MIMEPart.getBody([options])

Get the body (content) of a MIME part. The content will be decoded according to the Content-Transfer-Encoding header.

Parameters

options (array) – an options array

Returns

the body content

Return type

string or none

The following options are available in the options array.

  • decode (boolean) Decode the body accoding to the “Content-Transfer-Encoding” header. The default is true.

Note

This function will decode using the “Content-Transfer-Encoding” header. It will not do any character set conversion, hence the data can be in any character set encoding.

MIMEPart.setBody(data[, options])

Set the body (content) of a MIME part. The MIME parts encoding (Content-Transfer-Encoding) will be changed to the best readable match, that can be either 7bit, quoted-printable or base64 and the data will encoded as such.

Parameters
  • data (string) – the body content

  • options (array) – an options array

Returns

this

Return type

MIMEPart or none

The following options are available in the options array.

  • encoding (string) Force encoding of 7bit, 8bit, binary, base64 or quoted-printable. The default is to use the best readable match.

Note

Changes done to any MIME object will not be reflected on consecutive calls to “get” functions, however they will be applied to the message upon delivery. Also multiple calls to the same “set” function may yield undefined behaviour (like calling setBody twice).

MIMEPart.getPreamble()

Get the multipart MIME parts epilogue text. If the MIMEPart isn’t a multipart MIME, none is returned.

Return type

string or none

MIMEPart.setPreamble(data)

Set the multipart MIME parts preamble text. If the MIMEPart isn’t a multipart MIME, none is returned.

Parameters

data (string) – the preamble text

Returns

this

Return type

MIMEPart or none

MIMEPart.getEpilogue()

Get the multipart MIME parts epilogue text. If the MIMEPart isn’t a multipart MIME, none is returned.

Return type

string or none

MIMEPart.setEpilogue(data)

Set the multipart MIME parts epilogue text. If the MIMEPart isn’t a multipart MIME, none is returned.

Parameters

data (string) – the epilogue text

Returns

this

Return type

MIMEPart or none

MIMEPart.prependPart(part[, options])

Add a MIME part before this part. If the MIMEPart isn’t a multipart MIME, none is returned.

Parameters
  • part (MIME) – a MIME or MIMEPart object

  • options (array) – an options array

Returns

this

Return type

MIMEPart or none

The following options are available in the options array.

  • type (string) The multipart content type to use. The default is multipart/mixed.

MIMEPart.appendPart(part[, options])

Add a MIME part after this part. If the MIMEPart isn’t a multipart MIME, none is returned.

Parameters
  • part (MIME) – a MIME or MIMEPart object

  • options (array) – an options array

Returns

this

Return type

MIMEPart or none

The following options are available in the options array.

  • type (string) The multipart content type to use. The default is multipart/mixed.

MIMEPart.replacePart(part)

Replace the current MIME part.

Parameters

part (MIME) – a MIME or MIMEPart object

Return type

none

MIMEPart.findByType(type)

Find descendant parts (on any depth) based on their Content-Type. If type is given as a string, it’s compiled as a regex with /type/i (partial, case-insensitive).

Parameters

type (Regex or string) – type as regex

Returns

MIME parts

Return type

array of MIMEPart objects

MIMEPart.findByFileName(filename)

Find descendant parts (on any depth) based on their file name. If filename is given as a string, it’s compiled as a regex with /filename/i (partial, case-insensitive).

Parameters

filename (Regex or string) – filename as regex

Returns

MIME parts

Return type

array of MIMEPart objects

MIMEPart.getByID(id)

Get a MIME part by ID (on any depth, including the current part). If the part is not found none is returned.

Parameters

id (string) – the MIME part id

Returns

MIME part

Return type

MIMEPart object or none

MIMEPart.getParts()

Return child parts.

Returns

MIME parts

Return type

array of MIMEPart objects

MIMEPart.getErrors()

Return a list of all errors affecting this MIME part. The following errors are available; bad_header and unclosed_boundary.

Returns

list of errors

Return type

array of string

6.11. Misc

gethostname()

The hostname of the installation, this can be used to identify a software instance.

Returns

the hostname

Return type

string

uuid()

Return a unique ID.

Returns

a unique ID

Return type

string

echo()

Print a message to the log.

echo "Log message";

Note

echo is not a function, therefore do not call it with parentheses. The text messages is logged with syslog() level debug or stdout, with $messageid prefixed (when applicable).

syslog(priority, message)

The syslog function complements the echo statement by allowing messages with custom priorities to be logged.

Parameters
  • priority (string or number) – message priority

  • message (string) – message

Return type

none

Priority may be any of

Name

emerg

0

alert

1

crit

2

err

3

warning

4

notice

5

info

6

debug

7

It’s possible to change the facility of a log message by adding a facility value (see rfc5424).

syslog(3 + (4<<3), "This is sent as LOG_ERR to LOG_AUTH");

Note

If you want your log message to appear when the message log is viewed (as it does with echo(), you should prefix the message parameter with "[$messageid] ".

inet_includes(ip, network)

Returns true if ip is in the subnet or range of network. Both IPv4 and IPv6 are supported (comparison between different protocols always yields false). On error none is returned.

Parameters
  • ip (string) – ip address

  • network (string) – address, subnet or range.

Returns

true if ip is in network

Return type

boolean or none

inet_includes("127.0.0.1", "127.0.0.1/8");
inet_includes("127.0.0.1", "127.0.0.0-127.255.255.255");
inet_includes("127.0.0.1", "127.0.0.1");
inet_includes("2001:4860:4860::8888", "2001:4860:4860::/48");
inet_ntop(ip)

Converts an IP from a binary string format (4 char for IPv4 and 16 char for IPv6) to a printable string format (eg 10.0.0.1). On error none is returned.

Parameters

ip (string) – the ip in binary string format

Returns

an ip in printable string format

Return type

string or none

inet_pton(ip)

Converts an IP from printable string format (eg 10.0.0.1) to a binary string format (4 char for IPv4 and 16 char for IPv6). On error none is returned.

Parameters

ip (string) – the ip in printable format

Returns

an ip in binary string format

Return type

string or none

$x = unpack("N*", inet_pton($ip));
if (length($x) == 1)
        $x[0] = $x[0] & 0xffffff00; // mask ipv4 to /24
if (length($x) == 4)
        $x[3] = 0; // mask ipv6 to /96
echo inet_ntop(pack("N*", ...$x));
inet_reverse(ip[, zone])

Converts an IPv4 or IPv6 to a reverse DNS compatible format (to be used with PTR lookups or DNSxL lookups). By default the zone correspons to the ARPA address for each IP family. On error none is returned.

Parameters
  • ip (string) – the ip in printable format

  • zone (string) – the zone to append

Returns

an reverse DNS hostname

Return type

string or none

echo inet_reverse("8.8.8.8"); // 8.8.8.8.in-addr.arpa
echo inet_reverse("12.34.56.78", "example.com"); // 78.56.34.12.example.com

6.12. Protocols

smtp_lookup_rcpt(server, sender, recipient[, options])

Check if sender is allowed to send mail to recipient.

Parameters
  • server (string or array) – array with server settings or transport profile ID

  • sender (string or array) – the sender (MAIL FROM), either as a string or an associative array with a localpart and domain

  • recipient (string or array) – the recipient (RCPT TO), either as a string or an associative array with a localpart and domain

  • options (array) – options array

Returns

1 if the command succeeded, 0 if the command failed and -1 if an error occurred. The extended_result option may change this behaviour.

Return type

number or array

The following server settings are available in the server array.

  • server (string or array) The destination IP-address or hostname as a string, or an associative array with host (string) and mx (boolean). The default is to use MX lookup for the recipient domain.

  • port (number) TCP port. The default is 25.

  • helo (string) The default is to use the system hostname.

  • sourceip (string) Explicitly bind an IP address. The default is to be chosen by the system.

  • sourceipid (string) Explicitly bind an IP address ID. The default is to be chosen by the system.

  • nonlocal_source (boolean) Allow binding of non-local addresses (BINDANY). The default is false.

  • saslusername (string) If specified issue a AUTH LOGIN before MAIL FROM.

  • saslpassword (string) If specified issue a AUTH LOGIN before MAIL FROM.

  • saslmechanism (string) If specified issue the SASL mechanism and the saslpassword (used for eg. XOAUTH2).

  • tls (string) Use any of the following TLS modes; disabled, optional, optional_verify, dane, dane_fallback_require, dane_fallback_require_verify, dane_require, require or require_verify. The default is disabled.

  • tls_implicit (boolean) Use implicit TLS (do not use STARTTLS). The default is false.

  • tls_sni (string or boolean) Request a certificate using the SNI extension. If true the connected hostname will be used. The default is not to use SNI (false).

  • tls_protocols (string) Use one or many of the following TLS protocols; SSLv2, SSLv3, TLSv1, TLSv1.1, TLSv1.2 or TLSv1.3. Protocols may be separated by , and excluded by !. The default is !SSLv2,!SSLv3.

  • tls_ciphers (string) List of ciphers to support. The default is decided by OpenSSL for each tls_protocol.

  • tls_ciphersuites (string) List of TLS ciphersuites to support (TLSv1.3). The default is decided by OpenSSL for each tls_protocol.

  • tls_verify_host (boolean) Verify certificate hostname (CN). The default is false.

  • tls_verify_name (array) Hostnames to verify against the certificate’s CN and SAN (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • tls_client_cert (array or string) If given as an associative array it should include a x509 (X509Resource), privatekey (*PrivateKeyResource) and optionally a chain (array) of X509Resources. If given as a string use the following id of a certificate in the configuration as client certificate. The default is to not send a client certificate.

  • tls_capture_peer_cert (boolean) If set to true, the peer certificate will be available in the extended results. The default is true.

  • xclient (array) Associative array of XCLIENT attributes to send.

  • protocol (string) The protocol to use; smtp or lmtp. The default is smtp.

  • mx_include (array) Filter the MX lookup result, only including ones matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • mx_exclude (array) Filter the MX lookup result, removing ones matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • mx_exclude_bypass (array) Before applying mx_exclude, allow the once matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • ip_exclude (array) Filter the IP addresses or networks, removing addresses listed.

  • ip_exclude_temporary (boolean) Specify if empty results due to filtered IP or MX addresses should result in a temporary or permanent error. The default is false (permanent error).

  • timeout (array) Associative array of state and the timeout in seconds. The default is set according to RFC2821.

  • connect_timeout (number) The connect timeout in seconds. The default is 30 seconds.

  • proxyprotocol (array) Associative array of server (IP) and port as well as local sourceip to use when using an outbound PROXY PROTOCOL server.

The following options are available in the options array.

  • extended_result (boolean) If true an associative array with error_code, error_message, on_rcptto and tls is returned. The default is false.

smtp_lookup_auth(server, username, password)

Try to authenticate the username against a SMTP server.

Parameters
  • server (string or array) – array with server settings or transport profile ID

  • username (string) – username

  • password (string) – password

Returns

1 if the authentication succeeded, 0 if the authentication failed and -1 if an error occurred.

Return type

number

The following server settings are available in the server array.

  • server (string or array) The destination IP-address or hostname as a string, or an associative array with host (string) and mx (boolean). There is no default destination server.

  • port (number) TCP port. The default is 25.

  • helo (string) The default is to use the system hostname.

  • sourceip (string) Explicitly bind an IP address. The default is to be chosen by the system.

  • sourceipid (string) Explicitly bind an IP address ID. The default is to be chosen by the system.

  • nonlocal_source (boolean) Allow binding of non-local addresses (BINDANY). The default is false.

  • saslusername (string) If specified issue a AUTH LOGIN before MAIL FROM.

  • saslpassword (string) If specified issue a AUTH LOGIN before MAIL FROM.

  • saslmechanism (string) If specified issue the SASL mechanism and the saslpassword (used for eg. XOAUTH2).

  • tls (string) Use any of the following TLS modes; disabled, optional, optional_verify, dane, dane_fallback_require, dane_fallback_require_verify, dane_require, require or require_verify. The default is disabled.

  • tls_implicit (boolean) Use implicit TLS (do not use STARTTLS). The default is false.

  • tls_sni (string or boolean) Request a certificate using the SNI extension. If true the connected hostname will be used. The default is not to use SNI (false).

  • tls_protocols (string) Use one or many of the following TLS protocols; SSLv2, SSLv3, TLSv1, TLSv1.1, TLSv1.2 or TLSv1.3. Protocols may be separated by , and excluded by !. The default is !SSLv2,!SSLv3.

  • tls_ciphers (string) List of ciphers to support. The default is decided by OpenSSL for each tls_protocol.

  • tls_ciphersuites (string) List of TLS ciphersuites to support (TLSv1.3). The default is decided by OpenSSL for each tls_protocol.

  • tls_verify_host (boolean) Verify certificate hostname (CN). The default is false.

  • tls_verify_name (array) Hostnames to verify against the certificate’s CN and SAN (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • tls_client_cert (array or string) If given as an associative array it should include a x509 (X509Resource), privatekey (*PrivateKeyResource) and optionally a chain (array) of X509Resources. If given as a string use the following id of a certificate in the configuration as client certificate. The default is to not send a client certificate.

  • xclient (array) Associative array of XCLIENT attributes to send.

  • protocol (string) The protocol to use; smtp or lmtp. The default is smtp.

  • mx_include (array) Filter the MX lookup result, only including ones matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • mx_exclude (array) Filter the MX lookup result, removing ones matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • mx_exclude_bypass (array) Before applying mx_exclude, allow the once matching the hostnames/wildcards (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • ip_exclude (array) Filter the IP addresses or networks, removing addresses listed.

  • ip_exclude_temporary (boolean) Specify if empty results due to filtered IP or MX addresses should result in a temporary or permanent error. The default is false (permanent error).

  • timeout (array) Associative array of state and the timeout in seconds. The default is set according to RFC2821.

  • connect_timeout (number) The connect timeout in seconds. The default is 30 seconds.

  • proxyprotocol (array) Associative array of server (IP) and port as well as local sourceip to use when using an outbound PROXY PROTOCOL server.

6.13. String

chr(number)

Returns ASCII character from a number. This function complements ord().

Parameters

number (number) – the ASCII number

Returns

ASCII character

Return type

string

ord(character)

Return ASCII value of a character. This function complements chr().

Parameters

character (string) – the ASCII character

Returns

the ASCII value

Return type

number

str_repeat(string, multiplier)

Returns the string repeated multiplier times.

Parameters
  • string (string) – the input string

  • multiplier (number) – the string multiplier

Returns

the repeated string

Return type

string

See also

It’s significantly faster to use the string repeat * operator since it’s an operator and not a function.

str_replace(search, replace, subject)

Returns the string subject with the string search replace with replace.

Parameters
  • search (string) – the search string

  • replace (string) – the replace string

  • subject (string) – the string acted upon

Returns

subject with searched replaced with replace

Return type

string

str_replace("Hello", "Hej", "Hello World") // "Hej World"
str_split(string, delimiter[, limit = 0])

Splits the string into an array on the delimiter.

Parameters
  • string (string) – the string

  • delimiter (string) – the delimiter

  • limit (number) – the maximum number of parts returned

Returns

an array of strings

Return type

array

str_split("how are you", " ",  2) // ["how","are you"]
str_split("how are you", " ", -2) // ["how are","you"]

See also

To join an array to a string, see array_join().

str_find(string, substring[, offset = 0])

Return the position (starting from zero) of the first occurrence of substring in the string (starting from the offset). If the substring is not found -1 is returned.

Parameters
  • string (string) – the input string

  • substring (string) – the string to look for

  • offset (number) – the offset from the start

Returns

the position where substring is found

Return type

number

str_rfind(string, substring[, offset = 0])

Return the position (starting from zero) of the last occurrence of substring in the string searching backward (starting from the offset relative to the end). If the substring is not found -1 is returned.

Parameters
  • string (string) – the input string

  • substring (string) – the string to look for

  • offset (number) – the offset from the end

Returns

the position where substring is found

Return type

number

str_lower(string)

Returns string with all US-ASCII characters lowercased.

Parameters

string (string) – the input string

Returns

the string lowercased

Return type

string

str_upper(string)

Returns string with all US-ASCII characters uppercased.

Parameters

string (string) – the input string

Returns

the string uppercased

Return type

string

str_slice(string, offset[, length])

Return the substring of string.

Parameters
  • string (string) – the input string

  • offset (number) – the start position

  • length (number) – the length limit if given

Returns

the substring

Return type

string

See also

It’s significantly faster to use the slice [:] operator since it’s an operator and not a function.

str_strip(string[, characters])

Returns string with whitespace strip characters (\s\t\r\n) removed from the start and end of the string.

Parameters
  • string (string) – the input string

  • characters (string) – the strip characters

Returns

the trimmed string

Return type

string

str_lstrip(string[, characters])

Returns string with whitespace strip characters (\s\t\r\n) removed from the start of the string.

Parameters
  • string (string) – the input string

  • characters (string) – the strip characters

Returns

the trimmed string

Return type

string

str_rstrip(string[, characters])

Returns string with whitespace strip characters (\s\t\r\n) removed from the end of the string.

Parameters
  • string (string) – the input string

  • characters (string) – the strip characters

Returns

the trimmed string

Return type

string

str_chunk(string, lenght[, firstlenght])

Return the string chunks into an array of strings.

Parameters
  • string (string) – the input string

  • lenght (string) – the lenght of chunks

  • firstlenght (string) – the lenght of the first chunks

Returns

the chunked string

Return type

array of string

str_chunk("xxxxxxxxx", 3) // ["xxx","xxx","xxx"]
str_chunk("xxxxxxxxx", 3, 1) // ["x","xxx","xxx", "xx"]

6.14. Regular expression

pcre_match(pattern, subject)

PCRE matching in subject.

Parameters
  • pattern (Regex or string) – the regular expression

  • subject (string) – the string to match against

Returns

returns matches, if no result is found an empty array is returned.

Return type

array

Perl compatible regular expression data matching and extraction, requires capture groups. All modifiers supported by =~ operator are available.

Note

Use raw strings so you don’t have to escape the pattern.

See also

For matching only the regular expression operator can be used.

pcre_match_all(pattern, subject)

The implementation is identical to pcre_match() except the return type.

Parameters
  • pattern (Regex or string) – the regular expression

  • subject (string) – the string to match against

Returns

returns multiple results group by capture groups, and matched result.

Return type

array

pcre_quote(string)

Quote all metacharacters which has special meaning in a regular expression.

Parameters

string (string) – the string

Returns

a quoted string

Return type

string

pcre_compile(string)

Pre-compile a regex to a regular expression object.

Parameters

string (string) – the regular expression

Returns

a regex object

Return type

Regex

pcre_replace(pattern, replace, subject[, limit = 0])

Perl compatible regular expression data matching and replacing.

Parameters
  • pattern (Regex or string) – the regular expression to match

  • replace (function or string) – the pattern to replace as string or a callback function

  • subject (string) – the string acted upon

  • limit (number) – max occurrences to replace (0 equals unlimited)

Returns

return subject with the replacements done

Return type

string

In replace matches are available using $0 to $n. $0 will be the entire match, and $1 (and forward) each match group.

The replace function should take one argument (array of values [$0, $n...]) and return a string value.

echo pcre_replace("\\[link](.*?)\\[/link]",
        "<a href=\"$1\">$1</a>",
                        "[link]http://halon.se[/link]");
// <a href="http://halon.se">http://halon.se</a>

echo pcre_replace("\\d", "($0)", "foo1bar2baz");
// foo(1)bar(2)baz

// "ucfirst()"
echo pcre_replace(''\b[a-z]'', function ($i) { return str_upper($i[0]); }, "hello world");
// Hello World

6.15. Socket

class Socket

This class allows POSIX like socket(2) code. A socket resource is created for each Socket instance, this resource is automatically garbage collected (closed) once the object is destroyed.

constructor(family, type)
Parameters
  • family (string) – address family either AF_INET, AF_INET6 or AF_UNIX

  • type (string) – socket type either SOCK_STREAM (TCP) or SOCK_DGRAM (UDP)

$socket = Socket("AF_INET", "SOCK_STREAM");
$socket->close();

$socket2 = Socket(Socket::AF($address), "SOCK_STREAM");
$socket2->close();
bind(address[, port[, options]])

Bind the socket to address and port. The address must match the Sockets address family. On error none is returned.

Parameters
  • address (string) – address to bind

  • port (number) – port to bind

  • options (array) – options array

Returns

this

Return type

Socket or none

The following options are available in the options array.

  • nonlocal (boolean) Allow binding of a nonlocal source address (BINDANY). The default is false.

close()

Close the socket and destroy the internal socket resource. On error none is returned.

Returns

this

Return type

Socket or none

Note

Sockets are automatically garbage collected (closed). However you may want to explicitly call close.

connect(address[, port])

Connect the socket to address and port. The address must match the Sockets address family. On error none is returned.

Parameters
  • address (string) – address to connect to

  • port (number) – port to connect to

Returns

this

Return type

Socket or none

errno()

Get the latest errno returned from the underlying POSIX socket API.

Returns

errno

Return type

number

recv(length[, flags])

Receive data on socket. On error none is returned.

Parameters
  • length (number) – up to length bytes to receive (max 65536)

  • flags (array) – flags to control the behaviour

Returns

data

Return type

string or none

Flags may be any of, the default is no POSIX recv(3) flag. If multiple flags are given in the array, they are bitwise OR-ed.

Name

Behaviour

MSG_PEEK

peek at incoming message

MSG_WAITALL

wait for full request or error

MSG_DONTWAIT

do not block

send(data)

Send data on socket. On error none is returned.

Parameters

data (string) – data to send

Returns

bytes sent

Return type

number or none

settimeout(timeout)

Set the timeout for socket operations.

Parameters

timeout (number) – timeout in seconds. The default is no timeout.

Returns

this

Return type

Socket

shutdown(how)

Shutdown the socket for receiving, sending or both. On error none is returned.

Parameters

how (string) – how to shutdown either SHUT_RD, SHUT_WR or SHUT_RDWR.

Returns

this

Return type

Socket or none

Note

Sockets are automatically closed.

toFFIValue()

Return the file descriptor representing the current socket. On error none is returned.

Returns

An FFIValue of sint32 type

Return type

FFIValue or none

Note

The returned file descriptor must not be closed.

static AF(address)

Return the AF family of an address (either AF_INET or AF_INET6). A utility function helpful when constructing a Socket class. On error none is returned.

Parameters

address (string) – address

Returns

AF family

Return type

string or none

static Resource(socket)

Return a Socket object from a SocketResource.

Parameters

socket (SocketResource) – a SocketResource

Returns

A Socket resource

Return type

Socket or none

class TLSSocket

This class allows OpenSSL like SSL(3) code. The TLSSocket class takes a connected Socket instance (SOCK_STREAM) and encapsulates any read and writes in TLS/SSL.

constructor(socket, options)
Parameters
  • socket (Socket) – a socket

  • options (array) – options array

The following options are available in the options array.

  • tls_protocols (string) Use one or many of the following TLS protocols; SSLv2, SSLv3, TLSv1, TLSv1.1, TLSv1.2 or TLSv1.3. Protocols may be separated by , and excluded by !. The default is !SSLv2,!SSLv3.

  • tls_ciphers (string) List of ciphers to support. The default is decided by OpenSSL for each tls_protocol.

  • tls_ciphersuites (string) List of TLS ciphersuites to support (TLSv1.3). The default is decided by OpenSSL for each tls_protocol.

  • tls_verify_name (array) Hostnames to verify against the certificate’s CN and SAN (NO_PARTIAL_WILDCARDS | SINGLE_LABEL_SUBDOMAINS).

  • tls_verify_ca (boolean) Verify certificate against known CAs. The default is false.

  • tls_sni (string) Request a certificate using the SNI extension. The default is not to use SNI.

  • tls_client_cert (array or string) If given as an associative array it should include a x509 (X509Resource), privatekey (*PrivateKeyResource) and optionally a chain (array) of X509Resources. If given as a string use the following id of a certificate in the configuration as client certificate. The default is to not send a client certificate.

Note

By default, no certificate nor hostname validation is done.

handshake()

Perform the TLS/SSL handshake. If the handshake fails or the validation fails none is returned.

Returns

this

Return type

TLSSocket or none

recv(length)

Receive data on TLS/SSL socket. This function may perform an implicit handshake. On error none is returned.

Parameters

length (number) – up to length bytes to receive (max 65536)

Returns

data

Return type

string or none

send(data)

Send data on TLS/SSL socket. This function may perform an implicit handshake. On error none is returned.

Parameters

data (string) – data to send

Returns

bytes sent

Return type

number or none

shutdown()

Shut down the TLS/SSL connection. This function may need to be called multiple times. See SSL_shutdown(3) for details. On error none is returned.

Returns

shutdown status

Return type

number or none

errno()

Get the latest errno returned from the underlying OpenSSL SSL(3) socket API.

Returns

errno

Return type

number

getpeerx509()

Get the peer certificate (X.509) as a X509 instance. On error none is returned.

Returns

The peer certificate

Return type

X509 or none

toSocket()

Return a Socket class for the current TLSSocket object (upcast).

Returns

A Socket class for the current TLSSocket object.

Return type

Socket

class X509

This class allows you to parse an X509 resource. The X509 class takes a X509Resource.

constructor(x509resource)
Parameters

x509resource (X509Resource) – a X509Resource

subject()

The subject of the certificate. The first field in the tuple is the name (eg. CN, OU) and the second is the value.

Returns

The subject

Return type

array of [string, string]

issuer()

The issuer of the certificate. The first field in the tuple is the name (eg. CN, OU) and the second is the value.

Returns

The issuer

Return type

array of [string, string]

subject_alt_name()

The subject alt names (DNS) items

Returns

The SAN

Return type

array

version()

The version of the X.509 certificate

Returns

The version

Return type

number

serial_number()

The serial number in HEX

Returns

The serial

Return type

string

not_valid_before()

The start date of the certificate (in unix time)

Returns

The certificate start date

Return type

number

not_valid_after()

The end date of the certificate (in unix time)

Returns

The certificate end date

Return type

number

public_key([options])

Export the public key in binary DER format (default) or in PEM format.

Parameters

options (array) – options array

Returns

The public key

Return type

string

The following options are available in the options array.

  • pem (boolean) Export the public key in PEM format. The default is false.

verify(calist[, intermediates])

Verify the certificate against a list of CA’s (with optional intermediate certificates).

Parameters
  • calist (array) – array of X509

  • intermediates (array) – array of X509

Returns

The verification result

Return type

array

The return value is an associative arrays with result (boolean) or error (string), errno (number) and depth (number). For details see OpenSSL’s X509_verify_cert and X509_STORE_CTX_get_error.

if ($c->verify($calist)["result"])
 echo "ok";
export([options])

Export the certificate in binary DER format (default) or in PEM format.

Parameters

options (array) – options array

Returns

The certificate

Return type

string

The following options are available in the options array.

  • pem (boolean) Export the X.509 in PEM format. The default is false.

// SHA256 fingerprint
echo sha2($c->export(), 256);
extensions([options])

Return all extensions in the certificate.

Parameters

options (array) – options array

Returns

List of extensions

Return type

array

The following options are available in the options array.

  • text (boolean) Decode known extensions to friendly text. The default is false.

The return value is an array of associative arrays with oid, name, critical, value and optionally text.

echo $c->extensions(["text" => true]); // [0=>["oid"=>"2.5.29.19","name"=>"basicConstraints","critical"=>false,"value"=>"...","text"=>"CA:FALSE"]]
toResource()

Return the objects X509 resource.

Returns

The internal X509 resource

Return type

X509Resource

toFFIValue()

Return a pointer to a OpenSSL X509 object representing the current X509 resource.

Returns

An FFIValue of pointer type

Return type

FFIValue

Note

The X509 pointer must not be deleted.

#include <openssl/x509.h>

void processx509(X509* x509) {
}
static String(data[, options])

Return a X509 resource containing the data.

Parameters
  • data (string) – the content

  • options (array) – options array

Returns

A X509 resource

Return type

X509

The following options are available in the options array.

  • pem (boolean) The X.509 in PEM format. The default is false (DER).

  • multiple (boolean) Import multiple X509 certificates as an array. This option changes the return value to an array of X509 resources. The default is false.

6.16. FFI

The foreign function interface (FFI) enables loading of shared libraries following C interface calling conventions. The FFI interface has its own types (C types) and memory. It’s very easy to crash the Halon script engine if not used properly. The FFI feature is not enabled by default and needs to be enabled in the .yaml configuration for each program.

class FFI

This class allows you to load a shared object/library.

constructor(path)
Parameters

path (string) – a library (eg. libc.so.7)

$libc = FFI("libc.so.7");
func(name, arguments, returntype)

The name of the function to load, use FFI.type() to define the correct function signature. If the function is not found, none is returned.

Parameters
  • name (string) – the function name

  • arguments (FFIType) – the list of argument types

  • returntype (FFIType) – the return type

Returns

A function object

Return type

FFIFunction or none

$malloc = $libc->func("malloc", [ FFI::type("uint64") ], FFI::type("pointer"));
$free = $libc->func("free", [ FFI::type("pointer") ], FFI::type("void"));
$printf = $libc->func("printf", [ FFI::type("pointer"), FFI::type("...") ], FFI::type("sint32")); // variadic

The ... type prepresents functions having a variadic arguments list. All values in the variadic arguments list must have an explicit type since they are unknown in the function definition.

symbol(name)

Return a pointer to a global symbol in the library (eg. a variable). This function is the equivalent of dlsym(2). If the symbol is not found, none is returned.

Parameters

name (string) – a symbol name

Returns

An FFIValue of pointer type

Return type

FFIValue or none

static type(name)

A factory function for FFI types. This function is usually used to declare the function signature of an FFIFunction.

Parameters

name (string) – a type name

Returns

An FFI type

Return type

FFIType

The following types are available.

  • void (can only be used as return value)

  • uint8, sint8, uint16, sint16, uint32, sint32, uint64, sint64

  • float, double

  • pointer

  • ... (can only be used as function argument)

static cnumber(type, number)

Create an FFIValue containing a C number. It’s a basic type, which exists for the lifetime of the returned value and passed by value.

Parameters
  • type (FFIType) – an FFI C number type

  • number (number) – a number

Returns

An FFI value

Return type

FFIValue

The following FFI number types are available:

  • uint8, sint8, uint16, sint16, uint32, sint32, uint64, sint64, float, double

$malloc = $libc->func("malloc", [ FFI::type("uint64") ], FFI::type("pointer"));
$ptr = $malloc(FFI::cnumber(FFI::type("uint64"), 32));
static cstring(value)

Allocate a null-terminated C string (char *) in memory from a HSL string and return an FFIValue of pointer type pointing to that memory. This memory is owned by the FFIValue resource (use the FFI.detach() function to disclaim ownership). This function is intentionally not binary safe.

Parameters

value (string) – a string

Returns

An FFIValue of pointer type

Return type

FFIValue

$fopen = $libc->func("fopen", [ FFI::type("pointer"), FFI::type("pointer") ], FFI::type("pointer"));
$fp = $fopen(FFI::cstring("/dev/zero"), FFI::cstring("r"));
static callback(arguments, returntype, callback)

Allocate a FFI callback function and return a FFIValue of pointer type pointing to that function. This pointer can be passed a pointer to a FFI function taking a C function pointer. This memory is owned by the FFIValue resource (use the FFI.detach() function to disclaim ownership). The callback function argument will be FFI types and the return type needs to be of FFI type as well.

Parameters
  • arguments (FFIType) – the list of argument types

  • returntype (FFIType) – the return type

  • callback (function) – a callback function

Returns

An FFIValue of pointer type pointing to a C function callback

Return type

FFIValue

$math = $lib->func("math", [ FFI::type("pointer"), FFI::type("sint32"), FFI::type("sint32") ], FFI::type("sint32"));
$cb = FFI::callback([ FFI::type("sint32"), FFI::type("sint32") ], FFI::type("sint32"), function ($a, $b) {
            return FFI::cnumber(FFI::type("sint32"), FFI::number($a) * FFI::number($b));
      });
echo FFI::number($math($cb, 10, 5));

For the corresponding C library function

typedef int (*mathcb)(int, int);
extern "C" int math(mathcb cb, int a, int b) {
      return cb(a, b);
}
static nullptr()

Create an FFIValue containing a NULL pointer.

Returns

An FFIValue of pointer type

Return type

FFIValue

Note

The C equivalent of this function is NULL.

static allocate(size)

Allocate memory of size in bytes and return an FFIValue of pointer type pointing to that memory. This memory is owned by the FFIValue resource (use the FFI.detach() function to disclaim ownership). The memory is initially filled with zeros.

Parameters

size (any) – the memory size in bytes

Returns

An FFIValue of pointer type

Return type

FFIValue

Note

The C equivalent of this function is malloc(size) with a memset(pointer, size, 0).

static memcpy(pointer, data)

Copy the binary content of (string) data into memory location pointed to by an FFIValue of pointer type. The caller must make sure the pointer location is of sufficient length.

Parameters
  • pointer (FFIValue) – an FFIValue of pointer type

  • data (string) – the data to copied

Returns

An FFIValue

Return type

FFIValue

Note

The C equivalent of this function is memcpy(pointer, data, datalen).

static byref(value)

Return an FFIValue of pointer type pointing to the FFIValue value.

Parameters

value (FFIValue) – an FFI value

Returns

An FFIValue of pointer type

Return type

FFIValue

Note

The C equivalent of this function is &value.

static deref(value[, type])

Return an FFIValue with FFIType of type with the value at the address pointed at by the FFIValue value. The default type is pointer. If the type is a pointer and dereferenced pointer points to NULL then none is returned.

Parameters
  • value (FFIValue) – an FFI value

  • type (FFIType) – an FFI type

Returns

An FFIValue of pointer type

Return type

FFIValue or none

Note

The C equivalent of this function is *value.

static offset(pointer, offset)

Return a new FFIValue of pointer type pointing the same memory with an offset.

Parameters
  • pointer (FFIValue) – an FFI value of pointer type

  • offset (number) – the offset in bytes

Returns

An FFIValue of pointer type

Return type

FFIValue

Note

The C equivalent of this function is pointer + 32.

static string(pointer[, size])

Copy the binary content of a memory location pointed to by an FFIValue of pointer type to a HSL string. If the size is omitted the memory will be copied up to the first NULL character as a null-terminated C string (char *).

Parameters
  • pointer (FFIValue) – an FFI value of pointer type

  • size (number) – bytes to copy

Returns

A binary safe string

Return type

string

static number(value)

Convert an FFI value to a HSL number. The number type can safely represent all integers between +/-9007199254740991 (the equivalent of (2 ** 53) - 1). If you expect to work with greater numbers use FFI.number64().

Parameters

value (FFIValue) – an FFI value

Returns

A number

Return type

number

static number64(value)

Convert an FFI value (uint64, sint64 or pointer) to a pair of two 32 bit integers ([high, low]). For signed negative numbers a two complement representation is used.

Parameters

value (FFIValue) – an FFI value

Returns

A number pair

Return type

array of number

static attach(pointer[, destructor])

Assign the ownership of the data pointed to by the pointer argument (FFIValue of pointer type). The default destructor is free. An optional destructor FFIFunction (should have one pointer argument) may be given.

Parameters
  • pointer (FFIValue) – an FFIValue of pointer type

  • destructor (FFIFunction) – a destructor function

Returns

The pointer argument

Return type

FFIValue

$fopen = $libc->func("fopen", [ FFI::type("pointer"), FFI::type("pointer") ], FFI::type("pointer"));
$fclose = $libc->func("fclose", [ FFI::type("pointer") ], FFI::type("void"));
$fp = FFI::attach($fopen->call("/dev/zero", "r"), $fclose);
static detach(pointer)

Remove the ownership of the data pointed to by the pointer argument (FFIValue of pointer type).

Parameters

pointer (FFIValue) – an FFI value of pointer type

Returns

The pointer argument

Return type

FFIValue

FFIFunction(...args)

A callable Function object of type FFIFunction.

Parameters

args (FFIValue) – FFIValues or a HSL value

Returns

Return value of function call

Return type

FFIValue or none (for void or a pointer returning NULL)

Implicit conversion can be made if the function signature has once of the following types and the argument HSL type match. Note that the lifetime of converted values are for the duration of the function call.

Declaration type

HSL type

Conversion

pointer

String

FFI.cstring()

pointer

None

FFI.nullptr()

any number

Number

Be causes of value truncations

...

FFIValue

Argument must be of explicit type

$fopen = $libc->func("fopen", [ FFI::type("pointer"), FFI::type("pointer") ], FFI::type("pointer"));
$fp1 = $fopen(FFI::cstring("/dev/zero"), FFI::cstring("r"));
$fp2 = $fopen("/dev/zero", "r"); // implicit conversion
$printf("%s %zu\n", FFI::cstring("hello"), FFI::cnumber(FFI::type("uint64"), 123));
FFIType

An FFIType resource holds information about a function signature.

The following types are available.

  • void (can only be used as return value)

  • uint8, sint8, uint16, sint16, uint32, sint32, uint64, sint64

  • float, double

  • pointer

  • ... (can only be used as function argument)

FFIValue

An FFIValue resource is a container for an FFI value (it also contains the FFIType) so that the correct conversions can be made. If the value is of a pointer type you may control the lifetime of the object using the FFI.attach() and FFI.detach() functions.

6.17. Shared memory

The memory function API provides shared, atomic and synchronized memory access between parallel script executions within the same program. The memory resides in runtime memory (heap) hence it is automatically cleared upon program restart. Access to this memory is also available through the protobuf control socket API. The memory functions share the same memory and lock as the barrier structure.

memory_add(key, value)

Adds the value to the store, but only if the key doesn’t already exist.

Parameters
  • key (string) – the key name

  • value (any) – the value

Returns

if the value was added

Return type

boolean

memory_dec(key[, offset=1, remove_if_zero=false])

Decrements a number value in the store. If the key doesn’t exist, it’s created and the value is initialized to 0 before the decrement. If the value is not a number, this function fail and will return none.

Parameters
  • key (string) – the key name

  • offset (number) – the offset to decrement

  • remove_if_zero (boolean) – remove key if number reaches zero

Returns

the decremeted value

Return type

number or none

memory_delete(key[, callback])

Deletes a key from the store. If the key existed, the callback (if provided) will be called with the key and value as arguments.

Parameters
  • key (string) – the key name

  • callback (function) – a callback function

Returns

if the key was removed

Return type

boolean

memory_exists(key[, callback])

Checks if a key in the store exists. If the key exists the callback (if provided) will be called with the key and value as arguments.

Parameters
  • key (string) – the key name

  • callback (function) – a callback function

Returns

if the key exists

Return type

boolean

memory_fetch(key[, callback])

Returns the value of a key in the store. If the entry doesn’t exist and no callback is provided, none will be returned. If the entry doesn’t exist and a callback is provided, it will be called with the key as argument, and the return value of the callback will be used as return value for this function.

Parameters
  • key (string) – the key name

  • callback (function) – a callback function

Returns

the value of key

Return type

any

// fetch or create+fetch
echo memory_fetch("x", function ($k) {
        $v = 123;
        memory_store("x", $v);
        return $v;
    });

Note

Since this function may return none if the key doesn’t exist, it’s not possible to differentiate between keys with the value none and a non-existing key. If it’s important to differentiate between those, use memory_exists() with a callback.

memory_inc(key[, offset=1])

Increments a number value in the store. If the key doesn’t exist, it’s created and the value is initialized to 0 before the increment. If the value is not a number, this function fail and will return none.

Parameters
  • key (string) – the key name

  • offset (number) – the offset to increment

Returns

the incremeted value

Return type

number or none

memory_store(key, value[, callback])

Update or create the value of key in the store. If the key exists, the callback (if provided) will be called with the key and the current value as arguments in order to know what value was overwritten.

Parameters
  • key (string) – the key name

  • value (any) – the value

  • callback (function) – a callback function

Returns

if the key exists

Return type

boolean

memory_update(key, value, callback[, initial])

Update the value of key in the store, if it exists. The return value of the callback function (called with the key, current value and value as argument) will be used as the stored value.

If the key doesn’t exist, and…

  • …no initial value is provided, no action will take place.

  • …an initial value is provided, the callback will be called with the initial value as the current value.

Parameters
  • key (string) – the key name

  • value (any) – the value

  • callback (function) – a callback function

  • initial (any) – an initial value

Returns

if the key exists

Return type

boolean

// append items to an array (create the array if it doesn't exist)
memory_update("list", "item", function ($k, $c, $v) {
    $c[] = $v;
    return $c;
}, []);

// compare-and-swap (CAS) example between 3 and 5
$swapped = false;
if (memory_update("x", 5, function ($k, $c, $v) closure ($swapped) {
        if ($c != 3) return $c;
        $swapped = true;
        return $v;
    }) and $swapped)
{
    echo "swapped";
}

6.18. Queue

queue_suspend(fields, ttl[, options])

Add a dynamic queue pickup suspend for the following fields, this will cause no more messages matching this condition to be picked up for delivery during the ttl of the suspend. If a matching suspend already exists only the TTL is updated. On error none is returned.

Parameters
  • fields (array) – fields array

  • ttl (number) – ttl in seconds

  • options (array) – options array

Return type

array

The following fields are available in the fields array.

  • transportid (string) Transport ID

  • localip (string) Local IP

  • remoteip (string) Remote IP

  • remotemx (string) Remote MX

  • recipientdomain (string) Recipient domain

  • tenantid (string) Tenant ID

  • jobid (string) Job ID

  • grouping (string) Grouping

The following options are available in the options array.

  • tag (string) Apply tag to suspend.

  • properties (array) List of properties to be added (associative string-string array)

  • update (boolean) If we should update the suspend. The default is true.

The return value is always an associative array with id.

// Suspend matching traffic for one minute
queue_suspend(
       ["remotemx" => "*.protection.example.com"],
       60
    );
queue_policy(fields, condition, policy, ttl[, options])

Add a dynamic queue pickup policy for the specific fields, matching a specific condition. If a matching policy (fields and condition) already exists the condition and TTL is updated. On error none is returned.

Parameters
  • fields (array) – fields array

  • condition (array) – condition array

  • policy (array) – policy array

  • ttl (number) – ttl in seconds

  • options (array) – options array

Return type

array

The following field values are available in the fields array. The counter for those fields needs to exists in the policy configuration before it can have dynamic condition added to it.

  • transportid

  • localip

  • remoteip

  • remotemx

  • recipientdomain

  • tenantid

  • jobid

  • grouping

The following condition are available in the condition array.

  • transportid (string) Transport ID

  • localip (string) Local IP

  • remoteip (string) Remote IP

  • remotemx (string) Remote MX

  • recipientdomain (string) Recipient domain

  • tenantid (string) Tenant ID

  • jobid (string) Job ID

  • grouping (string) Grouping

The following policies are available in the policy array.

  • concurrency (number) The concurrency limit.

  • rate (array) The rate given as [messages, interval]. The interval is given in seconds.

  • properties (array) An associative array of properties

  • tag (string) Tag if concurrency or rate applies.

  • stop (boolean) If stop-on-match should be enabled. The default is false.

The following options are available in the options array.

  • update (boolean) If we should update the policy. The default is true.

The return value is always an associative array with id.

// Enforce a 10 messages per minute limit for an hour
queue_policy(
      ["localip", "recipientdomain"],
      ["recipientdomain" => "example.com"],
      ["rate" => [10, 60]],
      3600
    );

Note

If you have groupings and you add a condition matching a grouping, then the condition will be applied on the grouping and not the individual item. For example if you have a grouping named #exampleRollup (*.example.com) and you add a condition for mx1.example.com the condition will be applied on the #exampleRollup grouping instead.

queue_policy_delete(id)

Remove the queue policy reference by the id. Return a boolean value if the policy was removed. On error none is returned.

Parameters

id (string) – a queue policy id

Return type

boolean or none

queue_quota(name)

Get the usage for a specific quota. Messages may be assigned to one or more quotas when calling eg. eod.EODMailMessage.queue() which is then incremented accordingly. When the messages is removed from the queue (delivered or not) the quota is decremented.

Parameters

name (string) – the quota name

Returns

the quota information

Return type

array

The return value is always an associative array with count and bytes.

// Enforce a limit of 1 GiB of message data in queue for a specific senderdomain
// In this example we have a made-up namespace called "senderdomain:"
// but that is not necessary
//
// Do not forget to specificying the same quota name when accepting messages
//
if (queue_quota("senderdomain:$senderdomain")["bytes"] > 1024 * 1024 * 1024)
    Defer("Too many mail in queue from $senderdomain");
class Exception

This builtin class is used to create Exception objects. Similar to the built in exceptions thrown.

Exception.constructor(message)

Create an instance of the Exception class.

Parameters

message (string) – the exception message

try {
   throw Exception("Error");
} catch ($e) {
  echo $e->toString();
}
Exception.toString()

Return a user-friendly represention of the exception message including file, line or column if available.

Returns

exception message

Return type

string

Exception.message()

Return the error message without any additional information regarding file, line or column.

Returns

exception message

Return type

string

Exception.file()

Return the file which caused the exception. This function will only return the file for builin exceptions.

Returns

file

Return type

string or none

Exception.line()

Return the line which caused the exception. This function will only return the line for builin exceptions.

Returns

line number

Return type

number or none

Exception.column()

Return the column which caused the exception. This function will only return the column for builin exceptions.

Returns

column number

Return type

number or none