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

core.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]);
core.array_find(callback, array)

Return the first element that matches in the array.

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"]
core.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
core.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().

core.array_keys(array)

Returns the keys in the array.

Parameters:array (array) – the array
Returns:array’s keys
Return type:array
core.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
core.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 (range(0, 9) as $i) // 0,1,2,..,8
        echo $i;
core.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
core.array_reverse(array)

Return array in reverse order

Parameters:array (array) – the array
Returns:array in reverse order
Return type:array
core.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;
}

6.2. Cryptographic

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

Decrypt a message using AES.

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 (on error)

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")]
                );
core.aes_encrypt(message, key, mode[, options])

Encrypt a message using AES.

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 (on error)

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")]
                );
core.hmac_md5(key, message)

Return the HMAC MD5 hash of message with the key.

Parameters:
  • key (string) – the HMAC key
  • message (string) – the value to hash
Returns:

the hash value hex encoded

Return type:

string

core.hmac_sha1(key, message)

Return the HMAC SHA1 hash of message with the key.

Parameters:
  • key (string) – the HMAC key
  • message (string) – the value to hash
Returns:

the hash value hex encoded

Return type:

string

core.hmac_sha2(key, message, hashsize)

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)
Returns:

the hash value hex encoded

Return type:

string

core.md5(message)

Return the MD5 hash of message.

Parameters:message (string) – the value to hash
Returns:the hash value hex encoded
Return type:string
core.sha1(message)

Return the SHA1 hash of message.

Parameters:message (string) – the value to hash
Returns:the hash value hex encoded
Return type:string
core.sha2(message, hashsize)

Return the SHA2 hash of message.

Parameters:
  • message (string) – the value to hash
  • hashsize (number) – the hash size (must be 256 or 512)
Returns:

the hash value hex encoded

Return type:

string

core.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
core.rsa_sign(message, privatekey[, options])

RSA sign a message digest using a hash function.

Parameters:
  • message (string) – the message to sign
  • privatekey (string) – the private key
  • options (array) – options array
Returns:

the message signature

Return type:

string or none (on error)

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 in configuration “pki:X” format. The default is false.
core.rsa_verify(message, signature, publickey[, options])

RSA verify a message digest using a hash function. On error the function return none.

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 (on error)

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 in configuration “pki:X” format. The default is false.
core.ed25519_sign(message, privatekey)

ED25519 sign a message.

Parameters:
  • message (string) – the message to sign
  • privatekey (string) – the private key as raw bytes
Returns:

the message signature

Return type:

string or none (on error)

core.ed25519_verify(message, signature, publickey)

ED25519 verify a message.

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 (on error)

core.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
core.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

core.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

core.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
core.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 [].

core.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
core.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
core.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
core.is_array(value)

Returns true if the type of value is an array.

Parameters:value (any) – the input
Returns:the result
Return type:boolean
core.is_boolean(value)

Returns true if the type of value is a boolean.

Parameters:value (any) – the input
Returns:the result
Return type:boolean
core.is_function(value)

Returns true if the type of value is a function.

Parameters:value (any) – the input
Returns:the result
Return type:boolean
core.is_number(value)

Returns true if the type of value is a number.

Parameters:value (any) – the input
Returns:the result
Return type:boolean
core.is_object(value)

Returns true if the type of value is an object.

Parameters:value (any) – the input
Returns:the result
Return type:boolean
core.is_string(value)

Returns true if the type of value is a string.

Parameters:value (any) – the input
Returns:the result
Return type:boolean
core.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
core.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

6.4. Date and time

core.executiontime()

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

Returns:the time in seconds (with decimals)
Return type:number
core.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
core.strftime(format[, time])

Format according to the strftime manual.

echo strftime("%H:%M:%S"); // prints current time eg "13:58:38"
Parameters:
  • format (string) – the format string
  • time (number) – the default is current time without timezone
Returns:

the time formatted (max length 100)

Return type:

string

core.strptime(datestring, format)

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

echo strptime("13:58:38", "%H:%M:%S"); // prints time of today at "13:58:38"
Parameters:
  • datestring (string) – the date string
  • format (string) – the format string
Returns:

the time in seconds

Return type:

number

core.time()

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

Returns:the time in seconds (with decimals)
Return type:number
core.timelocal()

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

Returns:the time in seconds (with decimals)
Return type:number
core.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

core.dns(host[, options])

Query for DNS records of a hostname.

Parameters:
  • host (string) – the host
  • options (array) – options array
Returns:

list of items or an extended result

Return type:

array

The following options are available in the options array.

  • type (string) Query type (one of a, aaaa, mx, txt, cname, ns or ptr). The default is to query for both a and aaaa.
  • timeout (number) Query timeout in seconds. The default is 5.
  • extended_result (boolean) Get a more extended result. The default is false.
  • servers (array) List of resolvers. The default is the system wide.

In the extended_result mode, either result or error in set in an associative array. dnssec is always included. result is the list of results and error is the string representation of rcode or h_errno.

echo dns("nxdomain.halon.se");
// []
echo dns("nxdomain.halon.se", ["extended_result" => true]);
// ["error"=>"NXDOMAIN","dnssec"=>0]

echo dns("halon.se");
// [0=>"54.152.237.238"]
echo dns("halon.se", ["extended_result" => true, "type" => "a"]);
// ["result"=>[0=>"54.152.237.238"],"dnssec"=>0]

echo dns(inet_reverse("8.8.8.8"), ["type" => "ptr"]);
// [0=>"google-public-dns-a.google.com"]

echo dns(inet_reverse("12.34.56.78", "dnsbl.example.com"), ["type" => "ptr"]);
// [0=>"127.0.0.1"]
core.domain_includes(subdomain, domain)

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.

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
Parameters:
  • subdomain (string) – the subdomain
  • domain (string) – the domain
Returns:

if subdomain is a subdomain of domain

Return type:

boolean

core.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
echo idna_encode("fußball.example"); // xn--fuball-cta.example
core.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
echo idna_decode("xn--fuball-cta.example"); // fußball.example

6.6. Encodings and JSON

core.base64_encode(string)

Base64 encode the string.

Parameters:string (string) – the input string
Returns:the base64 representation
Return type:string
core.base64_decode(string)

Base64 decode the string.

Parameters:string (string) – the input string
Returns:the string representation
Return type:string
core.csv_decode(string[, options])

Parse CSV data as string.

Parameters:
  • string (string) – CSV formated string
  • 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 ,.
  • 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" or "boolean" or "number",
      "nullable" => true or false or [ "", "NULL", ... ],
      "true" => [ "True", ... ],
      "false" => [ "False", ... ],
  ],
  ...
]

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).

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.

core.json_encode(value[, options])

JSON encode a HSL data type.

Parameters:
  • value (any) – HSL data type
  • options (array) – options array
Returns:

a JSON representation of value

Return type:

string

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.

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.

core.json_decode(string[, options])

Decodes a JSON string into a HSL data type.

Parameters:
  • string (string) – JSON serialized data
  • options (array) – options array
Returns:

the decoded string as the correct type, and on errors None is returned

Return type:

any

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.

core.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

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
core.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

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

6.7. File and HTTP

class core.File(filename)

The File 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.

Parameters:filename (string) – the file name
$file = File("myfile.txt");
while ($data = $file->read(8192))
        echo $data;

$file = GetMailFile();
while ($data = $file->read(8192))
        echo $data;
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.

param number length:
 bytes to read
return:data
rtype:string or None

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). On EOF or error None is returned.

Returns:data
Return type:string 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
static String(data)

Return a File resource containing the data.

Parameters:data (string) – the content
Returns:A file resource
Return type:File or None
$file = File::String("Hello\nWorld");
echo $file->readline(); // "Hello"
core.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 or string) – POST data as an array or a string for raw POST data
Returns:

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

Return type:

string or array

The following options are available in the options array.

  • extended_result (boolean) Get a more extended result. The default is false.
  • connect_timeout (number) Connection timeout (in seconds). The default is 10 seconds.
  • timeout (number) Timeout (in seconds) waiting for data once the connection is established. The default is to wait indefinitely.
  • 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.
  • 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.
  • tls_verify_peer (boolean) Verify peer certificate. The default is true.
  • tls_verify_host (boolean) Verify certificate hostname (CN). The default is false.
  • tls_default_ca (boolean) Load additional TLS certificates (ca_root_nss). The default is false.
  • background (boolean) Perform request in the background. In which case this function returns true if the queueing was successful, otherwise None on errors. The default is false.
  • background_hash (number) Assign this request to a specific queue. If this value is higher than the number of queues, it’s chosen by modulus. The default is queue 0.
  • background_retry_count (number) Number of retry attempts made after the initial failure. The default is 0.
  • background_retry_delay (number) The delay, in seconds, before each retry attempt. The default is 0 seconds.
  • proxy (string) Use a HTTP proxy. See CURL_PROXY manual. The default is to inherit proxy settings from the system.

If the option extended_result result is true. This function will return an array containing the status code and content. If no valid HTTP response is receivied None is return.

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

6.8. Mail

core.dnsbl(ip, hostname[, resolvers[, timeout = 5]])

Query the resolvers for the DNSBL status of an address. If no resolvers are given, the system default is used.

Parameters:
  • ip (string) – IP or IPv6 address to check
  • hostname (string) – in DNSBL list
  • resolvers (array) – list of resolvers
  • timeout (number) – timeout in seconds
Returns:

list of IP addresses

Return type:

array

This function works by reversing the IP addresses octets and appending to the hostname parameter.

core.spf(ip, helo, domain[, options])

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 too lookup
  • options (array) – options array
Returns:

0 if the addresses passed, 20 for softfail, 50 if the status is unknown and 100 if the spf failed.

Return type:

number

The following options are available in the options array.

  • extended_result (boolean) If true an associative array with result is returned with the string result as defined by libspf2 (eg. pass). The default is false.
core.globalview(ip)

Query the embedded Cyren IP reputation, ctipd. This function is only available in the full system distribution (virtual machine) package. All connectors are available in the script library.

Parameters:ip (string) – IP or IPv6 address to check
Returns:the recommended action to take for the ip accept, tempfail or permfail.
Return type:string

6.9. Mathematical

core.abs(number)

Return the absolute value of a number.

Parameters:number (number) – the numeric value to process
Returns:the absolute value
Return type:number
core.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
core.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
core.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

core.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.

core.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

core.sqrt(number)

Return the square root of number.

Parameters:number (number) – the numeric value to process
Returns:the square root
Return type:number

6.10. MIME

class core.MIME

The MIME object “constructor” takes no function arguments, and returns a new MIME object.

The standard library’s MIME object is a “string builder” to construct MIME parts. In the end-of-DATA context there is an similar MIME object as well (however it has other member functions available), which is used to work with a message’s MIME parts. To create a “string building” MIME object, call the MIME function without any arguments.

Note

If you call the MIME function with an argument in the end-of-DATA context then the EOD context’s MIME object will be created instead.

$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)

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
Returns:

this

Return type:

MIME

Note

If a Content-Type header is added, the value of MIME.setType() is ignored. If a Content-Transfer-Encoding header is added no encoding will be done on data added by 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

The Content-Type is not automatically set to multipart/*, this has to be done using MIME.setType(). The MIME boundary is however 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 Base64 encoded if no Content-Transfer-Encoding header is 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 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
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 (string) – private key to use, either pki:X or a private RSA key in PEM format.
  • options (array) – options array
Returns:

this

Return type:

MIME

The following options are available in the options array.

  • canonicalization_header (string) body 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.
  • oversign_headers (array) headers to oversign. The default is from.
  • headers (array) headers to sign. The default is to sign all headers recommended by the RFC.
toString()

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

Returns:the MIME as string
Return type:string
send(sender, recipient, transportid[, options])

Put the MIME message (email) into the queue.

Parameters:
  • sender (string or array) – the sender email address, either as a string or a tuple with localpart and domain
  • recipient (string or array) – the recipient email address, either as a string or a tuple with localpart and domain
  • transportid (string) – the transportid
  • options (array) – options array
Returns:

the message id

Return type:

string

The following options are available in the options array.

  • metadata (array) Add additional metadata to the message (KVP).
MIME()
        ->addHeader("Subject", "Hello")
        ->setBody("Hi, how are you?")
        ->send("", "[email protected]", "mailtransport:1");

6.11. Misc

core.serial()

The serial number of the installation. It can be used to identify a software instance. This function is only available in the full system distribution (virtual machine) package.

Returns:the serial number
Return type:string
core.gethostname()

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

Returns:the hostname
Return type:string
core.uuid()

Return a unique ID.

Returns:a unique ID
Return type:string
core.echo()

Print a message to the log.

echo "Log message";

Note

echo is not a function, therefore do not call it with parentheses, all messages are logged as syslog() level debug, with $messageid prefixed.

core.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] ".

core.stat(name, legends)

Collect statistics based on one or more legend (value). This function is only available in the full system distribution (virtual machine) package. Connectors for external time-series databases such as Graphite or InfluxDB are available in the script library.

The name is the name of the graph (the collection of legends). A legend is a value for which the system should collect statistics.

Parameters:
  • name (string) – name of the graph
  • legends (array) – key value pair of legends
Return type:

none

Values stat’ed are available

  • as a line graph (on the graphs and report page)
  • as a pie chart (on the graphs and report page)
  • using the statList and graphFile SOAP API call.
  • using SNMP

In order for the line graph to work properly, all values should be defined to the stat function on every stat call (even if they are not increased).

$fam4 = 0; $fam6 = 0;
if (inet_includes($senderip, "0.0.0.0/0")) { $fam4 = 1; } else { $fam6 = 1; }
stat("ip-family", ["ipv4" => $fam4, "ipv6" => $fam6]);

Note

You can only use “a-z0-9.-” in the name and “a-zA-Z0-9-_” in the legends (legends longer than 19 characters will be truncated on the graph page) when using the stat function.

core.inet_includes(ip, network)

Returns true if ip is in the subnet or range of network. Both IPv4 and IPv6 are supported.

Parameters:
  • ip (string) – ip address
  • network (string) – address, subnet or range.
Returns:

true if ip is in network

Return type:

boolean

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");
core.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
core.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
$x = unpack("N*", inet_pton($ip));
if (count($x) == 1)
        $x[0] = $x[0] & 0xffffff00; // mask ipv4 to /24
if (count($x) == 4)
        $x[3] = 0; // mask ipv6 to /96
echo inet_ntop(pack("N*", ...$x));
core.inet_reverse(ip[, zone])
Converts an IP 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

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
core.rate(namespace, entry, count, interval[, options])

Check or account for the rate of entry in namespace during the last interval.

Parameters:
  • namespace (string) – the namespace
  • entry (string) – an entry
  • count (number) – the count
  • interval (number) – the interval in seconds
  • options (array) – options array
Returns:

if count is greater than zero, it will increase the rate and return true, or return false if the limit is exceeded. If count is zero 0, it will return the number of items during the last interval.

Return type:

number

The following options are available in the options array.

  • sync (boolean) Synchronize the rate in between nodes in the cluster. The default is true.
if (rate("outbound", $saslusername, 3, 60) == false) {
      Reject("User is only allowed to send 3 messages per minute");
}

Note

Rates are shared between all contexts, and may also be synchronized in clusters.

core.mail(sender, recipient, subject, body, transportid[, options])

Put an email message into the queue.

Parameters:
  • sender (string or array) – the sender email address, either as a string or a tuple with localpart and domain
  • recipient (string or array) – the recipient email address, either as a string or a tuple with localpart and domain
  • subject (string) – the subject
  • body (string) – the body
  • transportid (string) – the transport ID
  • options (array) – options array
Returns:

the queued message ID

Return type:

string

The following options are available in the options array.

  • sender_name (string) Friendly name of the sender.
  • recipient_name (string) Friendly name of the recipient.
  • headers (array) Add additional message headers (KVP).
  • metadata (array) Add additional metadata to the message (KVP).
mail(
              "[email protected]",
              "[email protected]",
              "Lunch",
              "How about lunch on Friday?",
              "mailtransport:1"
      );

Note

If you want to build more complex emails use the MIME class.

6.12. Protocols

core.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 a tuple with localpart and domain
  • recipient (string or array) – the recipient (RCPT TO), either as a string or a tuple with 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 behavior.

Return type:

number or array

The following server settings are available in the server array.

  • host (string) IP-address or hostname. required
  • 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.
  • tls (string) Use any of the following TLS modes; disabled, optional, optional_verify, dane, dane_require, require or require_verify. The default is disabled.
  • 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_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_default_ca (boolean) Load additional TLS certificates (ca_root_nss). The default is false.
  • tls_client_cert (string) Use the following pki:X 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 false.
  • xclient (array) Associative array of XCLIENT attributes to send.

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.
core.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.

  • host (string) IP-address or hostname. required
  • 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.
  • tls (string) Use any of the following TLS modes; disabled, optional, optional_verify, dane, dane_require, require or require_verify. The default is disabled.
  • 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_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_default_ca (boolean) Load additional TLS certificates (ca_root_nss). The default is false.

Query an LDAP server for lookup and return all LDAP entries found.

Parameters:
  • profile (string) – ldap profile
  • lookup (any) – if lookup is a string value it will be inserted into the ldap query replacing %s (ldapescaped) or %x (raw, dangerous). If lookup is an array it will replace items (ldapsecaped) as $1, $2...
  • override (array) – override array
Returns:

an array with LDAP entries or -1 if an error occurred.

Return type:

array or number

The following overrides are available in the override array.

  • host (string) LDAP URI (ldap:// or ldaps://).
  • username (string) LDAP username.
  • password (string) LDAP password.
  • base (string) LDAP base.
  • query (string) LDAP query (unescaped).
  • tls_default_ca (boolean) Load additional TLS certificates (ca_root_nss). The default is true.
  • tls_verify_peer (boolean) Verify peer certificate. The default is true.
core.ldap_bind(profile, username, password[, override])

Try to bind (authenticate) against an LDAP server.

Parameters:
  • profile (string) – ldap profile
  • username (string) – LDAP username
  • password (string) – LDAP password
  • override (array) – override array
Returns:

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

Return type:

number

The following overrides are available in the override array.

  • host (string) LDAP URI (ldap:// or ldaps://).
  • tls_default_ca (boolean) Load additional TLS certificates (ca_root_nss). The default is true.
  • tls_verify_peer (boolean) Verify peer certificate. The default is true.
class core.LDAP(uri)

The LDAP class is a OpenLDAP wrapper class. The URI should be in the format of ldap:// or ldaps://. Multiple hosts may be given separated by space.

Parameters:uri (string) – The LDAP
$ldap = LDAP("ldap://ldap.forumsys.com");
$ldap->bind("uid=tesla,dc=example,dc=com", "password");
$x = $ldap->search("dc=example,dc=com");
while ($x and $entry = $x->entry())
    echo $entry;
setoption(name, value)

Set LDAP connection options.

Parameters:
  • name (string) – the option name
  • value (number) – the option value
Returns:

this

Return type:

LDAP or None

if (!$ldap->setoption("network_timeout", 5))
    echo LDAP::err2string($ldap->errno());

The following options is available

Name Type Default Description
protocol_version number 3  
referrals boolean false  
network_timeout number 0 No timeout
timeout number 0 No timeout (in seconds)
timelimit number 0 No timelimit (in seconds)
tls_verify_peer boolean true Verify peer certificate
tls_default_ca boolean false Load additional TLS certificates (ca_root_nss)
starttls()

Issue STARTTLS on LDAP connection.

Returns:this
Return type:LDAP or None
bind([dn[, cred]])

Bind the LDAP connection. For anonymous bind, do not specify the credentials.

Parameters:
  • dn (string) – The username DN
  • cred (string) – The password credentials
Returns:

this

Return type:

LDAP or None

search(basedn[, options])

Search LDAP connection in the current base and subtree.

Parameters:
  • basedn (string) – Base DN
  • options (array) – an options array
Returns:

A LDAP result class

Return type:

LDAPResult or None

The following options are available in the options array.

  • scope (string) The search scope, available scopes are sub (subtree), one (onelevel) and base. The default is sub.
  • filter (string) The search filter. The default is (objectclass=*).
  • attributes (array) Array of attributes to fetch. The default is to fetch all.
unbind()

Unbind the LDAP connection.

Returns:this
Return type:LDAP or None
errno()

Get the latest errno returned from the underlying OpenLDAP API.

Returns:errno
Return type:number
static err2string(errno)

Get a descriptive error message, uses OpenLDAP’s ldap_err2string().

Parameters:errno (number) – A errno (obtained from LDAP’s errno())
Returns:An error string
Return type:String
if (!$ldap->bind())
    echo LDAP::err2string($ldap->errno());
static filter_escape(value)

LDAP escape values to be used in LDAP filters.

Parameters:value (string) – An unescaped string
Returns:An escaped string
Return type:String
$result = $ldap->search("dc=example,dc=com", ["filter" => "(cn=" . LDAP::filter_escape("firstname.lastname"] . ")"));
static str2dn(str)

Parses the string representation of a distinguished name str into its components, returning an array of tupels.

Parameters:value (string) – String representation of a DN
Returns:Array of tupels
Return type:Array
echo LDAP::str2dn("cn=admin,dc=example,dc=org");
// [0=>[0=>"cn",1=>"admin"],1=>[0=>"dc",1=>"example"],2=>[0=>"dc",1=>"org"]]
static dn2str(dn)

Performs the inverse operation of LDAP.str2dn(), returning a string representation of dn with the necessary escaping.

Parameters:value (array) – Array of tupels
Returns:String representation of the DN
Return type:String
class core.LDAPResult

A LDAP result iterable object which holds the result from an LDAP search.

next()

Return the next result.

Returns:entry data
Return type:array or None
$result = $ldap->search("dc=example,dc=com");
if ($result)
  while ($entry = $result->next())
    echo $entry;

6.13. String

core.chr(number)

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

Parameters:number (number) – the ASCII number
Returns:ASCII character
Return type:string
core.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
core.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.

core.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

core.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().

core.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

core.str_rfind(string, find[, 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

core.str_lower(string)

Returns string with all US-ASCII character to lowercased.

Parameters:string (string) – the input string
Returns:the string lowercased
Return type:string
core.str_upper(string)

Returns string with all US-ASCII character uppercased.

Parameters:string (string) – the input string
Returns:the string uppercased
Return type:string
core.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.

core.str_strip(string)

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

Parameters:string (string) – the input string
Returns:the trimmed string
Return type:string

6.14. Regular expression

core.pcre_match(pattern, subject)

PCRE matching in subject.

Parameters:
  • pattern (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.

core.pcre_match_all(pattern, subject)

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

Parameters:
  • pattern (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

core.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
core.pcre_replace(pattern, replace, subject[, limit = 0])

Perl compatible regular expression data matching and replacing

Parameters:
  • pattern (string) – the regular expression to match
  • replace (any) – 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 strtoupper($i[0]); }, "hello world");
// Hello World

6.15. Socket

class core.Socket(family, type)

The Socket 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.

Parameters:
  • family (string) – address family either AF_INET or AF_INET6
  • 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.

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.

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.

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.

Parameters:
  • length (number) – up to length bytes to receive
  • flags (string) – 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.

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.

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.

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.

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.

Parameters:address (string) – address
Returns:AF family
Return type:String or None
class core.TLSSocket(socket, options)

The TLSSocket 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.

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_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_default_ca (boolean) Load additional TLS certificates (ca_root_nss). The default is false.
  • tls_sni (string) Request a certificate using the SNI extension. The default is not to use SNI.
  • tls_client_cert (string) Use the following pki:X 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.

Parameters:length (number) – up to length bytes to recv
Returns:data
Return type:string or None
send(data)

Send data on TLS/SSL socket. This function may perform an implicit handshake.

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.

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
getpeercert([options])

Get the peer certificate (X.509) given during the handshake as an associative array.

Parameters:options (array) – options array
Returns:X.509 certificate data
Return type:array

The following options are available in the options array.

  • fingerprint (string) Generate the fingerprint of the certificate using one of the following hash function (md5, sha1, sha256 or sha512). The default no hashing.

The following items are available in the result.

  • subject (array) The subject, if there are duplicate attribute types (eg. C or CN) the attribute value will be an array instead
  • issuer (array) The issuer, if there are duplicate attribute types (eg. C or CN) the attribute value will be an array instead
  • subject_alt_name (array) The subject alt names DNS items
  • version (number) The version of the X.509 certificate
  • serial_number (string) The serial number in HEX
  • not_valid_before (number) The start date of the certificate (in unix time)
  • not_valid_after (number) The end date of the certificate (in unix time)
  • fingerprint (string) The certificate fingerprint (if requested)

Note

Example output (using json_encode() with pretty print):

{
        "subject": {
                "C": "US",
                "ST": "California",
                "L": "Mountain View",
                "O": "Google Inc",
                "CN": "mail.google.com"
        },
        "issuer": {
                "C": "US",
                "O": "Google Trust Services",
                "CN": "Google Internet Authority G3"
        },
        "subject_alt_name": {
                "DNS": [
                        "mail.google.com",
                        "inbox.google.com"
                ]
        },
        "version": 2,
        "serial_number": "5d8bca2821d49564",
        "not_valid_before": 1511950612,
        "not_valid_after": 1519205880
}