Asterisk dial plan variables --------------------------- There are two levels of parameter evaluation done in the Asterisk dial plan in extensions.conf. * The first, and most frequently used, is the substitution of variable references with their values. * Then there are the evaluations of expressions done in $[ .. ]. This will be discussed below. Asterisk has user-defined variables and standard variables set by various modules in Asterisk. These standard variables are listed at the end of this document. ___________________________ PARAMETER QUOTING: --------------------------- exten => s,5,BackGround,blabla The parameter (blabla) can be quoted ("blabla"). In this case, a comma does not terminate the field. However, the double quotes will be passed down to the Background command, in this example. Also, characters special to variable substitution, expression evaluation, etc (see below), can be quoted. For example, to literally use a $ on the string "$1231", quote it with a preceding \. Special characters that must be quoted to be used, are [ ] $ " \. (to write \ itself, use \\). These Double quotes and escapes are evaluated at the level of the asterisk config file parser. Double quotes can also be used inside expressions, as discussed below. ___________________________ VARIABLES: --------------------------- Parameter strings can include variables. Variable names are arbitrary strings. They are stored in the respective channel structure. To set a variable to a particular value, do : exten => 1,2,SetVar(varname=value) You can substitute the value of a variable everywhere using ${variablename}. For example, to stringwise append $lala to $blabla and store result in $koko, do: exten => 1,2,SetVar(koko=${blabla}${lala}) There are two reference modes - reference by value and reference by name. To refer to a variable with its name (as an argument to a function that requires a variable), just write the name. To refer to the variable's value, enclose it inside ${}. For example, SetVar takes as the first argument (before the =) a variable name, so: exten => 1,2,SetVar(koko=lala) exten => 1,3,SetVar(${koko}=blabla) stores to the variable "koko" the value "lala" and to variable "lala" the value "blabla". In fact, everything contained ${here} is just replaced with the value of the variable "here". _______________________________ REMOVING CHARACTERS FROM STRING ------------------------------- The format for removing characters from a variable can be expressed as: ${variable_name[:offset[:length]]} If you want to remove the first N characters from the string assigned to a variable, simply append a colon and the number of characters to remove from the beginning of the string to the variable name. ;Remove the first character of extension, save in "number" variable exten => _9X.,1,SetVar(number=${EXTEN:1}) Assuming we've dialed 918005551234, the value saved to the 'number' variable would be 18005551234. This is useful in situations when we require users to dial a number to access an outside line, but do not wish to pass the first digit. If you use a negative offset number, Asterisk starts counting from the end of the string and then removes everything before the new position. The following example will save the numbers 1234 to the 'number' variable, still assuming we've dialed 918005551234. ;Remove everything before the last four digits of the dialed string exten => _9X.,1,SetVar(number=${EXTEN:-4}) We can also limit the number of characters from our offset position that we wish to use. This is done by appending a second colon and length value to the variable name. The following example will save the numbers 555 to the 'number' variable. ;Only save the middle numbers 555 from the string 918005551234 exten => _9X.,1,SetVar(number=${EXTEN:5:3}) The length value can also be used in conjunction with a negative offset. This may be useful if the length of the string is unknown, but the trailing digits are. The following example will save the numbers 555 to the 'number' variable, even if the string starts with more characters than expected (unlike the previous example). ;Save the numbers 555 to the 'number' variable exten => _9X.,1,SetVar(number=${EXTEN:-7:3}) If a negative length value is entered, it is ignored and Asterisk will match to the end of the string. ___________________________ EXPRESSIONS: --------------------------- Everything contained inside a bracket pair prefixed by a $ (like $[this]) is considered as an expression and it is evaluated. Evaluation works similar to (but is done on a later stage than) variable substitution: the expression (including the square brackets) is replaced by the result of the expression evaluation. Note: The arguments and operands of the expression MUST BE separated by at least one space. For example, after the sequence: exten => 1,1,SetVar(lala=$[1 + 2]) exten => 1,2,SetVar(koko=$[2 * ${lala}]) the value of variable koko is "6". And, further: exten => 1,1,SetVar(lala=$[1+2]); will not work as you might have expected. Since all the chars in the single token "1+2" are not numbers, it will be evaluated as the string "1+2". Again, please do not forget, that this is a very simple parsing engine, and it uses a space (at least one), to separate "tokens". and, further: exten => 1,1,SetVar,"lala=$[ 1 + 2 ]"; will parse as intended. Extra spaces are ignored. ___________________________ SPACES INSIDE VARIABLE --------------------------- If the variable being evaluated contains spaces, there can be problems. For these cases, double quotes around text that may contain spaces will force the surrounded text to be evaluated as a single token. The double quotes will be counted as part of that lexical token. As an example: exten => s,6,GotoIf($[ "${CALLERIDNAME}" : "Privacy Manager" ]?callerid-liar|s|1:s|7) The variable CALLERIDNAME could evaluate to "DELOREAN MOTORS" (with a space) but the above will evaluate to: "DELOREAN MOTORS" : "Privacy Manager" and will evaluate to 0. The above without double quotes would have evaluated to: DELOREAN MOTORS : Privacy Manager and will result in syntax errors, because token DELOREAN is immediately followed by token MOTORS and the expression parser will not know how to evaluate this expression. _____________________ OPERATORS --------------------- Operators are listed below in order of increasing precedence. Operators with equal precedence are grouped within { } symbols. expr1 | expr2 Return the evaluation of expr1 if it is neither an empty string nor zero; otherwise, returns the evaluation of expr2. expr1 & expr2 Return the evaluation of expr1 if neither expression evaluates to an empty string or zero; otherwise, returns zero. expr1 {=, >, >=, <, <=, !=} expr2 Return the results of integer comparison if both arguments are integers; otherwise, returns the results of string comparison using the locale-specific collation sequence. The result of each comparison is 1 if the specified relation is true, or 0 if the relation is false. expr1 {+, -} expr2 Return the results of addition or subtraction of integer-valued arguments. expr1 {*, /, %} expr2 Return the results of multiplication, integer division, or remainder of integer-valued arguments. expr1 : expr2 The `:' operator matches expr1 against expr2, which must be a regular expression. The regular expression is anchored to the beginning of the string with an implicit `^'. If the match succeeds and the pattern contains at least one regu- lar expression subexpression `\(...\)', the string correspond- ing to `\1' is returned; otherwise the matching operator returns the number of characters matched. If the match fails and the pattern contains a regular expression subexpression the null string is returned; otherwise 0. Parentheses are used for grouping in the usual manner. The parser must be parsed with bison (bison is REQUIRED - yacc cannot produce pure parsers, which are reentrant) ___________________________ CONDITIONALS --------------------------- There is one conditional operator - the conditional goto : exten => 1,2,gotoif(condition?label1:label2) If condition is true go to label1, else go to label2. Labels are interpreted exactly as in the normal goto command. "condition" is just a string. If the string is empty or "0", the condition is considered to be false, if it's anything else, the condition is true. This is designed to be used together with the expression syntax described above, eg : exten => 1,2,gotoif($[${CALLERID} = 123456]?2|1:3|1) Example of use : exten => s,2,SetVar(vara=1) exten => s,3,SetVar(varb=$[${vara} + 2]) exten => s,4,SetVar(varc=$[${varb} * 2]) exten => s,5,GotoIf($[${varc} = 6]?99|1:s|6) ___________________________ PARSE ERRORS --------------------------- Syntax errors are now output with 3 lines. If the extensions.conf file contains a line like: exten => s,6,GotoIf($[ "${CALLERIDNUM}" = "3071234567" & & "${CALLERIDNAME}" : "Privacy Manager" ]?callerid-liar|s|1:s|7) You may see an error in /var/log/asterisk/messages like this: May 3 15:58:53 WARNING[1234455344]: ast_yyerror(): syntax error: parse error; Input: "3072312154" : "3071234567" & & "Steves Extension" : "Privacy Manager" ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^ The first line shows the string passed to the expression parser. This string is the result of the variable replacements, etc. This way, you can see the actual string that went into the parser. The second line usually shows a string of '^' chars, that show what's been legally parsed so far. And the third line shows where the parser was (lookahead token lexing, etc), when the parse hit the rocks. A single '^' here. The error is going to be somewhere between the last '^' on the second line, and the '^' on the third line. That's right, in the example above, there are two '&' chars, separated by a space, and this is a definite no-no! ___________________________ NULL STRINGS --------------------------- Testing to see if a string is null can be done in one of two different ways: exten => _XX.,1,GotoIf($["${calledid}" != ""]?3) exten => _XX.,1,GotoIf($[foo${calledid} != foo]?3) The second example above is the way suggested by the WIKI. It will work as long as there are no spaces in the evaluated value. The first way should work in all cases, and indeed, might now be the safest way to handle this situation. ___________________________ WARNING --------------------------- If you need to do complicated things with strings, asterisk expressions is most likely NOT the best way to go about it. AGI scripts are an excellent option to this need, and make available the full power of whatever language you desire, be it Perl, C, C++, Cobol, RPG, Java, Snobol, PL/I, Scheme, Common Lisp, Shell scripts, Tcl, Forth, Modula, Pascal, APL, assembler, etc. --------------------------------------------------------- Asterisk standard channel variables --------------------------------------------------------- There are a number of variables that are defined or read by Asterisk. Here is a list of them. More information is available in each application's help text. All these variables are in UPPER CASE only. Variables marked with a * are builtin functions and can't be set, only read in the dialplan. Writes to such variables are silently ignored. ${ACCOUNTCODE} * Account code (if specified) ${BLINDTRANSFER} The name of the channel on the other side of a blind transfer ${BRIDGEPEER} Bridged peer ${CALLERANI} * Caller ANI (PRI channels) ${CALLERID} * Caller ID ${CALLERIDNAME} * Caller ID Name only ${CALLERIDNUM} * Caller ID Number only ${CALLINGANI2} * Caller ANI2 (PRI channels) ${CALLINGPRES} * Caller ID presentation for incoming calls (PRI channels) ${CALLINGTNS} * Transit Network Selector (PRI channels) ${CALLINGTON} * Caller Type of Number (PRI channels) ${CHANNEL} * Current channel name ${CONTEXT} * Current context ${DATETIME} * Current date time in the format: DDMMYYYY-HH:MM:SS ${DNID} * Dialed Number Identifier ${EPOCH} * Current unix style epoch ${EXTEN} * Current extension ${ENV(VAR)} * Environmental variable VAR ${GOTO_ON_BLINDXFR} Transfer to the specified context/extension/priority after a blind transfer (use ^ characters in place of | to separate context/extension/priority when setting this variable from the dialplan) ${HANGUPCAUSE} * Asterisk cause of hangup (inbound/outbound) ${HINT} * Channel hints for this extension ${HINTNAME} * Suggested Caller*ID name for this extension ${INVALID_EXTEN} The invalid called extension (used in the "i" extension) ${LANGUAGE} * Current language ${LEN(VAR)} * String length of VAR (integer) ${PRIORITY} * Current priority in the dialplan ${PRIREDIRECTREASON} Reason for redirect on PRI, if a call was directed ${RDNIS} * Redirected Dial Number ID Service ${TIMESTAMP} * Current date time in the format: YYYYMMDD-HHMMSS ${TRANSFER_CONTEXT} Context for transferred calls ${UNIQUEID} * Current call unique identifier Various application variables ----------------------------- ${CURL} * Resulting page content for curl() ${ENUM} * Result of application EnumLookup ${EXITCONTEXT} Context to exit to in IVR menu (app background()) or in the RetryDial() application ${MONITOR} * Set to "TRUE" if the channel is/has been monitored (app monitor()) ${MONITOR_EXEC} Application to execute after monitoring a call ${MONITOR_EXEC_ARGS} Arguments to application ${MONITOR_FILENAME} File for monitoring (recording) calls in queue ${QUEUE_PRIO} Queue priority ${QUEUESTATUS} Status of the call, one of: (TIMEOUT | FULL | JOINEMPTY | LEAVEEMPTY | JOINUNAVAIL | LEAVEUNAVAIL) ${RECORDED_FILE} * Recorded file in record() ${TALK_DETECTED} * Result from talkdetect() ${TOUCH_MONITOR} The filename base to use with Touch Monitor (auto record) ${TXTCIDNAME} * Result of application TXTCIDName ${VPB_GETDTMF} chan_vpb The MeetMe Conference Bridge uses the following variables: ---------------------------------------------------------- ${MEETME_RECORDINGFILE} Name of file for recording a conference with the "r" option ${MEETME_RECORDINGFORMAT} Format of file to be recorded ${MEETME_EXIT_CONTEXT} Context for exit out of meetme meeting ${MEETME_AGI_BACKGROUND} AGI script for Meetme (zap only) ${MEETMESECS} * Number of seconds a user participated in a MeetMe conference The VoiceMail() application uses the following variables: --------------------------------------------------------- ${VM_CATEGORY} Sets voicemail category ${VM_NAME} * Full name in voicemail ${VM_DUR} * Voicemail duration ${VM_MSGNUM} * Number of voicemail message in mailbox ${VM_CALLERID} * Voicemail Caller ID (Person leaving vm) ${VM_CIDNAME} * Voicemail Caller ID Name ${VM_CIDNUM} * Voicemail Caller ID Number ${VM_DATE} * Voicemail Date ${VM_MESSAGEFILE} * Path to message left by caller The VMAuthenticate() application uses the following variables: --------------------------------------------------------- ${AUTH_MAILBOX} * Authenticated mailbox ${AUTH_CONTEXT} * Authenticated mailbox context DUNDiLookup() uses the following variables --------------------------------------------------------- ${DUNDTECH} * The Technology of the result from a call to DUNDiLookup() ${DUNDDEST} * The Destination of the result from a call to DUNDiLookup() The Zaptel channel sets the following variables: --------------------------------------------------------- ${ANI2} * The ANI2 Code provided by the network on the incoming call. (ie, Code 29 identifies call as a Prison/Inmate Call) ${CALLTYPE} * Type of call (Speech, Digital, etc) ${CALLEDTON} * Type of number for incoming PRI extension i.e. 0=unknown, 1=international, 2=domestic, 3=net_specific, 4=subscriber, 6=abbreviated, 7=reserved ${CALLINGSUBADDR} * Called PRI Subaddress ${FAXEXTEN} * The extension called before being redirected to "fax" ${PRIREDIRECTREASON} * Reason for redirect, if a call was directed The SIP channel sets the following variables: --------------------------------------------------------- ${SIPCALLID} * SIP Call-ID: header verbatim (for logging or CDR matching) ${SIPDOMAIN} * SIP destination domain of an inbound call (if appropriate) ${SIPUSERAGENT} * SIP user agent ${SIPURI} * SIP uri ${SIP_CODEC} Set the SIP codec for a call The Agent channel uses the following variables: --------------------------------------------------------- ${AGENTMAXLOGINTRIES} Set the maximum number of failed logins ${AGENTUPDATECDR} Whether to update the CDR record with Agent channel data ${AGENTGOODBYE} Sound file to use for "Good Bye" when agent logs out ${AGENTACKCALL} Whether the agent should acknowledge the incoming call ${AGENTAUTOLOGOFF} Auto logging off for an agent ${AGENTWRAPUPTIME} Setting the time for wrapup between incoming calls ${AGENTNUMBER} * Agent number (username) set at login ${AGENTSTATUS} * Status of login ( fail | on | off ) ${AGENTEXTEN} * Extension for logged in agent The Dial() application uses the following variables: --------------------------------------------------------- ${DIALEDPEERNAME} * Dialed peer name ${DIALEDPEERNUMBER} * Dialed peer number ${DIALEDTIME} * Time for the call (seconds) ${ANSWEREDTIME} * Time from dial to answer (seconds) ${DIALSTATUS} * Status of the call, one of: (CHANUNAVAIL | CONGESTION | BUSY | NOANSWER | ANSWER | CANCEL) ${LIMIT_PLAYAUDIO_CALLER} Soundfile for call limits ${LIMIT_PLAYAUDIO_CALLEE} Soundfile for call limits ${LIMIT_WARNING_FILE} Soundfile for call limits ${LIMIT_TIMEOUT_FILE} Soundfile for call limits ${LIMIT_CONNECT_FILE} Soundfile for call limits ${OUTBOUND_GROUP} Default groups for peer channels (as in SetGroup) * See "show application dial" for more information The chanisavail() application sets the following variables: ----------------------------------------------------------- ${AVAILCHAN} * the name of the available channel if one was found ${AVAILORIGCHAN} * the canonical channel name that was used to create the channel ${AVAILSTATUS} * Status of requested channel When using macros in the dialplan, these variables are available --------------------------------------------------------- ${MACRO_EXTEN} * The calling extensions ${MACRO_CONTEXT} * The calling context ${MACRO_PRIORITY} * The calling priority ${MACRO_OFFSET} Offset to add to priority at return from macro If you compile with OSP support in the SIP channel, these variables are used: --------------------------------------------------------- ${OSPHANDLE} Handle from the OSP Library ${OSPTECH} OSP Technology from Library ${OSPDEST} OSP Destination from Library ${OSPTOKEN} OSP Token to use for call from Library ${OSPRESULTS} Number of OSP results ____________________________________ CDR Variables ------------------------------------ If the channel has a cdr, that cdr record has it's own set of variables which can be accessed just like channel variables. The following builtin variables are available. ${CDR(clid)} Caller ID ${CDR(src)} Source ${CDR(dst)} Destination ${CDR(dcontext)} Destination context ${CDR(channel)} Channel name ${CDR(dstchannel)} Destination channel ${CDR(lastapp)} Last app executed ${CDR(lastdata)} Last app's arguments ${CDR(start)} Time the call started. ${CDR(answer)} Time the call was answered. ${CDR(end)} Time the call ended. ${CDR(duration)} Duration of the call. ${CDR(billsec)} Duration of the call once it was answered. ${CDR(disposition)} ANSWERED, NO ANSWER, BUSY ${CDR(amaflags)} DOCUMENTATION, BILL, IGNORE etc ${CDR(accountcode)} The channel's account code. ${CDR(uniqueid)} The channel's unique id. ${CDR(userfield)} The channels uses specified field. In addition, you can set your own extra variables with a traditional SetVAR(CDR(var)=val) to anything you want. Certain functional variables may be accessed with $(foo ). A list of these functional variables may be found by typing "show functions" at the Asterisk CLI.