Built-in scenario functions

Overview

Functions are used as arguments by script components. They allow you to calculate specific values and even perform operations on the system.

Functions are categorized into:

  • clean - the return value depends only on the parameters.

  • with site-effects - the return value may vary depending on the system state.

  • modifiers - makes changes to the system.

Components use arguments all the time, arguments can be represented as expressions, expressions can use functions.

Categories of functions

Category Description

Math

Pure mathematical functions.

String

Pure functions to handle strings.

Date/Time

Clean date and time functions and side-effect functions to access the current time.

Transformations

Pure value conversion, encoding, packaging, and representation functions.

Hash sums

Pure hash functions.

Files and paths

Clean functions to handle file paths and directory categories.

Service functions

Various functions for bidirectional access to context and state.

Access

Side-effect functions of special access to variables.

Configuration

Side-effect functions to retrieve data from the system configuration.

Constants

Pure constant substitution functions.

Symbols

Pure symbol substitution functions.

IVR

Side-effect call data access functions and queue state modifiers.

Function catalog

Table 1. Mathematical functions
Function Parameters Description

sin

num

Sine of a number

cos

num

Cosine of a number

tan

num

Tangent of a number

asin

num

The arcsine of a number

acos

num

Arccosine of a number

atan

num

The arctangent of a number

atan2

num, num

The arctangent of the quotient of two numbers

sinh

num

Hyperbolic sine of a number

cosh

num

Hyperbolic cosine of a number

tanh

num

The hyperbolic tangent of a number

exp

num

Exponent of the number

log

num

The natural logarithm of a number

log2

num

The binary logarithm of a number

log10

num

The decimal logarithm of a number

pow

num, num

The result of raising one number to the power of another

sqrt

num

The square root of a number

erf

num

Error Function:

2/sqrt(pi)*integral from 0 to X of exp(-t*t) dt

Not available on Windows

erfc

num

1.0 - erf(X)

Not available on Windows

max

num, num

The maximum of two numbers

min

num, num

The minimum of two numbers

trunc

num

The result of discarding the fractional part of a number

round

num

The result of rounding a number to an integer

abs

num

Absolute value of the number

floor

num

The integer nearest to the bottom

ceil

num

Nearest integer from above

lg

num

The decimal logarithm of a number

ln

num

The natural logarithm of a number

log

num, num

The logarithm of one number by the base of another number

sqr

num

Square the number

random

A random decimal number from 0 to 1

random

int

A random integer from 0 to the specified integer

random

int, int

Ca random integer in the range between two integers

Table 2. String functions
Function Parameters Description

newid

Returns the generated UUID identifier.

len

str

Returns the length of the string in characters.

concat

str,str

Returns the result of concatenating two strings.

equal

str,str

The result of comparing two strings: 0 or 1

str

str,str

Returns the position index of the first occurrence of the substring (n2) in the string (n1). Returns 0 if no occurrences are found.

rstr

str,str

Returns the position index of the last occurrence of the substring (n2) in the string (n1). Returns 0 if no occurrences are found.

substr

str,int

Returns the substring from the specified position (n2) to the end.

substr

str,int,int

Returns a substring from the specified position (p2) of no more than the specified length (p3).

replace

str,str,str

Returns the result of replacing occurrence (n1) in the string (n2) by the value (n3).

lower

str

Returns the string in lower case.

upper

str

Returns a string in uppercase.

remove

str,int

Returns the string after removing a substring from it from the specified position (n2) to the end.

remove

str,int,int

Returns a string after removing a substring from it from the specified position (n2) of the specified length (n3).

indexof

str,str

Returns the position index of the first occurrence of the substring (n2) in the string (n1). Returns 0 if no occurrences are found.

indexof

str,str,int

Returns the position index of the first occurrence of the substring (n2) in the string (n1), starting from the specified position (n3). Returns 0 if no occurrences are found.

trim

str

Returns a string spared of blank characters at the beginning and end (space, tab, etc).

ltrim

str

Returns a string spared from empty characters at the beginning (space, tab, etc.).

rtrim

str

Returns a string spared of empty characters at the end (space, tab, etc.).

trimstart

str

Returns a string spared from empty characters at the beginning (space, tab, etc.).

trimend

str

Returns a string spared of empty characters at the end (space, tab, etc.).

left

str,int

Returns the left side of a string of no more than the specified length.

right

str,int

Returns the right side of a string of no more than the specified length.

reverse

str

Returns the inverted string.

regexreplace

str,str,str

Returns the result of replacement using a regular expression. n1 - value, n2 - pattern, n3 - replacement.

regexreplaceg

str,str,str

Returns the result of replacement using a regular expression with the global option. n1 - value, n2 - pattern, n3 - replacement.

modify_json

str,json,json

Returns the modified json structure. Applies the search query (n1) to the value (n2), modifies the detected element according to the options (n3) and returns the total result.

Example:
modify_json(
  "chat/0/msgs",
  '{"chat":[{"msgs":[{"txt":"abc"}]}]}',
  '{"action":"append","value":{"txt":"zcv"}}'
)

Options are represented as a json object with the mandatory action key. Possible options:

  • append - for an array. Adds a new element to the end. In the options, the value of the element by key value.

  • prepend - for an array. Adds a new element to the beginning. In the options, the value of the element by key value

  • insert - for an array. Adds a new element at the specified position. The options are value key value of the element, position key position index.

  • replace - for an array. Replaces the element at the specified position with a new one. In options new element value by key value, position by key index.

  • replace_auto - for an array. Replaces all elements of the array with the specified value. In options value by key value.

  • delete - for an array. Removes an element from the specified position. In the options, the value of the key position index.

  • keystore - for an object. Saves the item by the specified key, adds or modifies the value depending on the presence of the key. In options, the value of the element by key value, the value of the key by key key.

  • keyreplace - for an object. Replaces the element by the specified key, and if the key is missing, leaves it unchanged. In options, the value of the element by key value, the value of the key by key key.

  • keyinsert - for the object. Saves the item by the specified key if it does not exist, and otherwise terminates with an error. In options, the value of the element by key value, the value of the key by key key.

  • keydelete - for an object. Deletes the item by the specified key. In the options, the value of the key by key key.

Table 3. Date/Time Functions
Function Parameters Description

nowtick

Returns a number representing the absolute value in milliseconds since 1970.

now

Returns the current date and time in the server’s local time zone in RFC3339 format. For example, 2019-10-06T16:43:30.46+03:00.

nowutc

Returns the current date and time in UTC in the format RFC3339.

nowgregsecond

Returns the number of seconds in the Gregorian calendar, from A.D. 0.

ticktolocal

int

Returns the date in the server’s local time zone by absolute value tick.

ticktoutc

int

Returns the date in UTC by absolute value tick.

tick

dt

Converts the date to unix timestamp

dateformat

str, dt

Returns a string from a date representation (n2) using the specified format (n1). For example: yyyy-MM-dd.

Possible placeholders for the formatting string: yyyy, yy, MM, d, dd, h, HH, MMM, mm, ss, ffff, fff, ff, f, zzz.

date

Returns the current date in the server’s local time zone without specifying a time zone. Format YYYY-MM-DD.

date

dt

Returns the date from the specified date/time.

time

Returns the current time in the local time zone of the server without specifying a time zone. The format is YYYYYY-MM-DD. Format HH:mm:ss.fff.

time

dt

Returns the time from the specified date/time.

datetime

str

Returns the date/time generated by the string. A string can contain various date/time representations, including RFC3339.

datetime

int,int,int

Returns the date/time based on the passed p1 - year, p2 - month, p3 - day.

datetime

int,int,int,int,int

Returns the date/time based on the passed p1 - year, p2 - month, p3 - day, p4 - hour, p5 - minute.

datetime

int,int,int,int,int,int

Returns the date/time based on the passed p1 - year, p2 - month, p3 - day, p4 - hour, p5 - minute, p6 - second.

datetime

int,int,int,int,int,int,int

Returns the date/time based on the passed p1 - year, p2 - month, p3 - day, p4 - hour, p5 - minute, p6 - second, and p7 - millisecond.

datediff

atom,dt,dt

Returns the number of specified time units between two dates.

The parameter is specified as an atom (not a string), e.g. datediff('dd',"2019-10-06","2019-10-05")

Possible types of units in descending order: yy, yyyy, q, qq, m, mm, ww, wk, d, dd, h, hh, mi, n, s, ss, ms

dateadd

atom,int,dt

Returns the date after adding the specified number (n2) of specified time units (n1) to the specified date/time (n3).

The parameter is specified as an atom (not a string), e.g. dateadd('mi',120,"2019-10-06T13:05:28")

Possible types of units in descending order: yy, yyyy, q, qq, m, mm, ww, wk, d, dd, h, hh, mi, n, s, ss, ms

year

dt

Returns the current year of the specified date/time.

month

dt

Returns the current month (1-12) of the specified date/time.

day

dt

Returns the current day (1-31) of the specified date/time.

hour

dt

Returns the current hour (0-23) of the specified date/time.

minute

dt

Returns the current minute (0-59) of the specified date/time.

second

dt

Returns the current second (0-59) of the specified date/time.

millisecond

dt

Returns the current millisecond (0-999) of the specified date/time.

dayofyear

dt

Returns the day number in the year for the specified date/time.

dayofweek

dt

Returns the day of the week number (1-7) for the specified date/time.

weekofyear

dt

Returns the week number in the year for the specified date/time.

isleapyear

int

Returns true if the specified date/time represents a leap year.

datetimelocal

dt

Returns the date/time converted to the local time zone of the server. Numerical values of date/time are not changed, but the absolute time point can be shifted after changing the time zone to local time zone.

datetimeutc

dt

Returns the date/time converted to UTC. Numerical date/time values are not changed, but the absolute time point may be shifted after changing the timezone to zero.

localtoutc

dt

Returns the UTC date/time for the specified date/time considered in the server’s local time zone.

utctolocal

dt

Returns the local date/time for the specified date/time, treated as a UTC.

valid_date

dt

Returns true if the specified string contains a valid date/time, otherwise false.

Table 4. Conversion functions
Function Parameters Description

char

str

Returns a string with a single character by its numeric code.

str

int

Converts a numeric value to a string.

num

str

Converts a string to a number. If it fails, it terminates with an error.

numval

str

Converts a string to a number by cutting off the end of unsuitable characters. In the limit, returns 0.

dechex

int

Returns a string with a HEX representation of the number.

hexdec

str

Returns a number based on its HEX representation.

base64encode

str

Returns the string resulting from packing into Base64 representation.

base64decode

str

Returns the string resulting from decompression from the Base-64 representation.

urlencode

str

Returns the string encoded with the UrlEncode.

urldecode

str

Returns the string decoded using the UrlEncode.

htmlencode

str

Returns the string encoded by c Unicode Hex Character Code.

htmldecode

str

Returns the string decoded by c Unicode Hex Character Code

escape

str

Returns the string resulting from the conversion to escape-sequence. Used for inserting into JSON.

unescape

str

Returns the string resulting from unpacking from an escape sequence. Used for cleanup after JSON.

translit

str

Returns the result of transliteration of the string.

ifelse

bool,any,any

If the value of the first parameter is true, it returns n2, otherwise it returns n3.

Table 5. Hash sums
Function Parameters Description

md5

str

Returns the hash of a string using the algorithm MD5.

crc32

any

Returns the hash of any value using the algorithm CRC32 (IEEE 802.3).

crc32

num,any

Returns the new hash value from the previous value combined with the new portion. n1 is the previous hash value, n2 is the new data portion. According to the algorithm CRC32 (IEEE 802.3).

adler32

any

Returns the hash of any value using the algorithm Adler-32.

adler32

num,any

Returns the new hash value from the previous value combined with the new portion. n1 is the previous hash value, n2 is the new data portion. According to the algorithm Adler-32.

phash2

any

Returns the hash sum from any value using an internal algorithm.

Table 6. Functions for working with file paths
Function Parameters Description

pathtype

str

Returns the path type (category prefix from the specified path).

relpath

str

Returns the relative path (the specified path without the category prefix).

filename

str

Returns the filename selected from the specified path.

fileext

str

Returns the file extension selected from the specified path.

filedir

str

Returns the name of the directory. For a file path it is the name of the directory, for a directory path it is the name of the parent directory.

makepath

str,str

Returns the path formed as a result of meshing two parts.

makepath

str,str,str

Returns the path generated by concatenating three parts: path, filename, and file extension.

temp

Returns :TEMP, the prefix of the script’s temporary local directory.

syn_media

Returns :SYNC_COMMON, the category prefix of the synchronizing general-purpose directory.

syn_dom_media

syn_domain

Returns :SYNC_DOMAIN_DATA the category prefix of the synchronizing domain data directory.

syn_script

Returns :SYNC_SCRIPT_DATA the category prefix of the current script’s synchronizing data directory (by code).

syn_script_media

Returns :SYNC_SCRIPT_STATIC the category prefix of the synchronizing directory of static script files (by code).

ss_public

Returns :SITESHARE_PUBLIC, the category prefix of the network intra-site general purpose directory.

ss_domain

Returns :SITESHARE_DOMAIN_DATA, the category prefix of the network intra-site directory of the current domain.

ss_script

Returns :SITESHARE_SCRIPT_DATA, the category prefix of the current script’s network intra-site directory (by code).

gs_public

Returns :GLOBALSHARE_PUBLIC, the category prefix of a network cross-site general-purpose directory.

gs_domain

Returns :GLOBALSHARE_DOMAIN_DATA, the network cross-site directory category prefix of the current domain.

gs_script

Returns :GLOBALSHARE_SCRIPT_DATA, the category prefix of the current script’s network cross-site directory (by code).

Table 7. Service functions
Function Parameters Description

startparam

int

Returns the value of the input parameter with the specified index. Scenarios can accept up to 20 input parameters.

getscriptref

Returns a string containing the identifier of the current script handler. This identifier can be used to send messages to the handler by other script handlers, e.g. using Script Interaction.

get_project_id

Returns a string containing the project ID of the currently running script.

cmd

str,str,str,str

cmd

str,str,str,str,str

component

int(atom,binary),binary(map,proplist)

Executes a component of the specified type from the group of service script components. The first parameter is the component type (numeric number or key from the module name, for example 103 or pause), the second parameter is the component properties from the documentation except for transition branches and variables for output values (can be erlang:map() or erlang:proplist() or binary() with JSON). Returns an object with the keys of output variable fields and additionally "transferKey", the format of the returned value is the same as the format of the second parameter.

component

int(atom,binary),binary(map,proplist),atom

Executes a component of the specified type from the service script component group. The first parameter is the component type (numeric number or key from the module name, e.g. 103 or pause). The second parameter is the component properties from the documentation except for the transition branches and variables for the output values (could be erlang:map() or erlang:proplist() or binary() with the JSON). The third parameter sets the format of the returned value (map, proplist, json). Another third parameter can order the output of a value by a specific key from the result (for example, to return a value usually stored in the output variable of a component). Also the third parameter can set the mode of returning a string glued from transferKey and varValue values (format "TransferKeyValue;OtherKeyValue"), for this purpose it is necessary to specify without quotes as the third parameter: "{transfer,Key}". Returns an object with the keys of the output variable fields and optionally "transferKey", or a value on a specific key from this object.

Examples: ---- component(notify, #{mode ⇒ 0, text ⇒ [a1], user ⇒ <<"admin">>}, map) component(111, #{<<"mode">> ⇒ 0, <<"text">> ⇒ <<"Something">>, <<"user">> ⇒ <<"admin">>}, json) component(111, <<"\"mode\": 0, \"text\": \"Something\", \"user\": \"admin\"">>, <<"transferKey">>) component(parser, #{algoritm ⇒ 0, functionJSON ⇒ 0, data ⇒ <<"{\\\"a\\\":\\\"value\\\"}">>, query ⇒ <<"a">>}, {transfer,<<"resultVariable">>}) ----

Component codes and fields are available in the documentation on the respective component pages. One possible way is to set up a new script with a component that has the settings of interest, and copy its contents from the JSON script.

lock

any,int

Expects and blocks a critical section (analog of the Mutex component). The first parameter is the unique name of the critical section. The second parameter is the waiting time in milliseconds before timeout. Returns "ok", "timeout", "error".

lock

any,int,any,int

Expects and blocks a critical section (analog of the Mutex component). The first parameter is the unique name of the critical section. The second parameter - waiting time in milliseconds before timeout. The third parameter - type of operation under lock (1 or read - read, 2 or write - write). The fourth parameter is the time in milliseconds after which the critical section will be automatically released. Returns "ok", "timeout", "error".

unlock

any

Releases a critical section (analog of the Mutex component). Returns "ok" or "error".

dc_read_types

str

dc_read_fields

str,str

dc_read

str,str

dc_read

str,str,str

dc_find

str,str

dc_find

str,str,str

dc_select

str,str

dc_select

str,str,str

Table 8. Accessibility functions
Function Parameters Description

check_variable

str

Returns true if the variable with the specified name exists and contains a value.

get_variable_value

str

Returns the value of a variable by its name.

get_variable_value

str, any

Returns the value of the variable by its name, or if no value is set, the default value from the second parameter.

get_variable_id

str

Returns a string containing the variable identifier of the variable by its name.

get_variable_orig

str

Returns the value of a variable by its name, and if the value is string, it is returned in its original encoding without conversion.

set_variable_value_if_undefined

str, any

Sets the value of a variable by its name if its value is not specified. Returns the value of the variable as a result of the operation.

var

str

Returns the value of a variable by its name.

storage_put

str, any

Extends or places a value (2 parameter) on a key (1 parameter) for 2 days in the data store on the site. Returns "ok". If the storage is unavailable, returns "error".

storage_put

str, any, int

Extends or places a value (2 parameter) on a key (1 parameter) for the specified number of seconds (3 parameter) in the data store on the site. Returns "ok". If the storage is unavailable, returns "error".

storage_get

str, any

Returns a key value from the data store on the site, or a default value if none is available. If the storage is unavailable, returns "error".

storage_del

str

Deletes the value by the specified key from the data storage on the site. If the storage is unavailable, returns "error".

Reading and modifying an existing value in the repository when working in parallel mode should be done in a critical section, such as that built by the "Mutex" component or expression functions lock/unlock.
Table 9. Configuration functions
Function Parameters Description

wsurl

Returns the URL of the nearest available server with the logical role ws.

site

Returns the site where the script is executed.

domain

Returns the domain in which the script is executing.

parentdomain

Returns the parent domain relative to the one in which the script is executed.

isworktime

Returns true if the current time is working, false otherwise. The schedule is taken from domain settings and applied to the local time zone of the site (server with role mdc/sdc).

isworktime

int

Returns true if the current time is working, false otherwise. The schedule is taken from domain settings and applied to the time zone specified in minutes, e.g. 0 is UTC, 180 is GMT+3.

In the format of proto://ip-address:port.

Table 10. Constants
Function Parameters Description

e

Returns a number e (2.718281828459045).

pi

Returns a number pi (3.141592653589793).

phi

Returns a number phi (1.618033988749895).

Table 11. Symbols
Function Parameters Description

tab

Returns a string containing a tab character.

endline

Returns a string with an end-of-line character.

quot

Returns a string containing a quote character.

dblquot

Returns a string containing a double-quote character.

Table 12. Scenario Functions IVR (issue RP-1468)
Function Parameters Description

ivrparam

str

Returns the value of the specified parameter from the X-Era-Ivr header that is generated by the role b2b. For example, from, to, by.

Available only for calls received in the IVR.

callednum

Returns a string with the number dialed by the subscriber from the INVITE that got routed. ATTENTION: For calls coming from outside (from connections to providers), this number is generally not the same as the one that received the external call. For the latter, use the function calledid().

Available only for calls received in the IVR.

To get the subscriber’s number when making outgoing calls with ivr (component 'Outgoing Call', API 'invite_byivr'), it is necessary to use IVR script parameters (startparam(N)) and pass the necessary information through them.

calledext

Returns a string with the extension CAF, which the call was received at IVR. Contains the entire postfix after the ficacode number has been removed.

Available only for calls received in the IVR.

To get the subscriber’s number when making outgoing calls with ivr (component 'Outgoing Call', API 'invite_byivr'), it is necessary to use IVR script parameters (startparam(N)) and pass the necessary information through them.

remotenum

Returns a string containing the subscriber number generated by applying presentation rules, either the internal subscriber number of the current domain or username from the From header of the request received for routing INVITE. NOTE: For calls coming in from outside (from ISP connections), this number is generally not the same as the one from which the outside call came, as it may be converted normalization rules. For the latter, use the function callerid().

Available only for calls received in the IVR.

To get the subscriber’s number when making outgoing calls with ivr (component 'Outgoing Call', API 'invite_byivr'), it is necessary to use IVR script parameters (startparam(N)) and pass the necessary information through them.

calledid

Returns a string with the number dialed by the subscriber. For calls received externally from the provider, contains the username header To of the original received INVITE request before normalization and routing rules are applied.

Available only for calls received in the IVR.

callerid

Returns a string with the number dialed by the subscriber. For calls received externally from the provider, contains username header From the original received INVITE request before normalization, routing, and presentation rules are applied.

Available only for calls received in the IVR.

callid

Returns a string with the value of the CallId header value of the b2b - ivr arm of the SIP dialog with the subscriber.

seancenativeid

Returns a string containing the current session native identifier (NID), retrieving it from the current call’s labels. If executed at the very beginning of the first call, can delay execution for up to 500 ms while waiting for a session to be assigned.

seanceid

Returns a string containing the current session identifier (SI), identifying it in the session store by native session label. If executed at the beginning of the first call, this function can delay execution for up to 500 ms while waiting for a session to be assigned.

sipheader

Returns a string with the value of the specified b2b - ivr SIP conversation shoulder header with the subscriber. In order for an arbitrary header from the original request from the subscriber to be propagated to the c IVR arm, you must configure in the role configuration parameters 'esg' and 'b2b' a list of propagated headers (parameter 'fwd_headers'). If there is more than one specified header, their values will be separated by a line feed ('\r\n' or 0x0D,0x0A).

Available only for calls received in the IVR.

huntid

Returns a string containing the identifier of the hunt-group entity the call is directed to.

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript and preivrscript scripts. In all other cases it returns invalid_mode.

huntobjid

Returns a string containing the runtime-object identifier of the hunt-group queue.

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript and preivrscript scripts. In all other cases it returns invalid_mode.

queuepriority

Returns the current numeric value of the priority in the queue.

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript scripts. In all other cases it returns invalid_mode.

queuepriority

int

Sets a new numeric priority value in the queue, and the queue is automatically moved.

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript scripts. In all other cases it returns invalid_mode

queueposition

Returns the current position in the queue.

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript scripts. In all other cases it returns invalid_mode

queueestimatedsec

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript scripts. In all other cases it returns invalid_mode

queuerescount

Returns the number of operators in the hunt group.

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript scripts. In all other cases it returns invalid_mode

queuerescount

str

Returns the number of operators in the hunt group that are in state (online or free, specified by parameter).

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript scripts. In all other cases it returns invalid_mode

queuestate

Returns a string with the name of the queue pending state.

Available only for calls received in the IVR via a featurecode with type hunt, in qivrscript scripts. In all other cases it returns invalid_mode

q_displayname

Returns the displayname from the URI of the From header of an INVITE SIP request waiting in a hunt group queue with type sipuser.

Available only for preivrscript scripts. In all other cases returns invalid_mode.

q_username

Returns username from the URI of the From header of an INVITE SIP request waiting in a hunt group queue with type sipuser.

Available only for preivrscript scripts. In all other cases returns invalid_mode.

q_domain

Returns the domain from the URI of the From header of an INVITE SIP request waiting in a hunt group queue with type sipuser.

Available only for preivrscript scripts. In all other cases returns invalid_mode.

r_number

Returns a string containing the operator call number (username from the URI of the To header of the INVITE SIP request sent for the operator call).

Available only for preivrscript scripts. In all other cases returns invalid_mode.