Merged revisions 226377 via svnmerge from
[asterisk/asterisk.git] / doc / tex / channelvariables.tex
1 \section{Introduction}
2
3 There are two levels of parameter evaluation done in the Asterisk
4 dial plan in extensions.conf.
5 \begin{enumerate}
6 \item The first, and most frequently used, is the substitution of variable
7   references with their values.
8 \item Then there are the evaluations of expressions done in \$[ .. ].
9   This will be discussed below.
10 \end{enumerate}
11 Asterisk has user-defined variables and standard variables set
12 by various modules in Asterisk. These standard variables are
13 listed at the end of this document.
14
15 \section{Parameter Quoting}
16 \begin{astlisting}
17 \begin{verbatim}
18 exten => s,5,BackGround,blabla
19 \end{verbatim}
20 \end{astlisting}
21 The parameter (blabla) can be quoted ("blabla"). In this case, a
22 comma does not terminate the field. However, the double quotes
23 will be passed down to the Background command, in this example.
24
25 Also, characters special to variable substitution, expression evaluation, etc
26 (see below), can be quoted. For example, to literally use a \$ on the
27 string "\$1231", quote it with a preceding \textbackslash. Special characters that must
28 be quoted to be used, are [ ] \$ " \textbackslash. (to write \textbackslash itself, use \textbackslash).
29
30 These Double quotes and escapes are evaluated at the level of the
31 asterisk config file parser.
32
33 Double quotes can also be used inside expressions, as discussed below.
34
35 \section{Variables}
36
37 Parameter strings can include variables. Variable names are arbitrary strings.
38 They are stored in the respective channel structure.
39
40 To set a variable to a particular value, do:
41 \begin{astlisting}
42 \begin{verbatim}
43     exten => 1,2,Set(varname=value)
44 \end{verbatim}
45 \end{astlisting}
46 You can substitute the value of a variable everywhere using \$\{variablename\}.
47 For example, to stringwise append \$lala to \$blabla and store result in \$koko,
48 do:
49 \begin{astlisting}
50 \begin{verbatim}
51    exten => 1,2,Set(koko=${blabla}${lala})
52 \end{verbatim}
53 \end{astlisting}
54
55 There are two reference modes - reference by value and reference by name.
56 To refer to a variable with its name (as an argument to a function that
57 requires a variable), just write the name. To refer to the variable's value,
58 enclose it inside \$\{\}. For example, Set takes as the first argument
59 (before the =) a variable name, so:
60 \begin{astlisting}
61 \begin{verbatim}
62   exten => 1,2,Set(koko=lala)
63   exten => 1,3,Set(${koko}=blabla)
64 \end{verbatim}
65 \end{astlisting}
66 stores to the variable "koko" the value "lala" and to variable "lala" the
67 value "blabla".
68
69 In fact, everything contained \$\{here\} is just replaced with the value of
70 the variable "here".
71
72 \section{Variable Inheritance}
73
74 Variable names which are prefixed by "\_" will be inherited to channels
75 that are created in the process of servicing the original channel in
76 which the variable was set.  When the inheritance takes place, the
77 prefix will be removed in the channel inheriting the variable.  If the
78 name is prefixed by "\_\_" in the channel, then the variable is
79 inherited and the "\_\_" will remain intact in the new channel.
80
81 In the dialplan, all references to these variables refer to the same
82 variable, regardless of having a prefix or not.  Note that setting any
83 version of the variable removes any other version of the variable,
84 regardless of prefix.
85
86 \subsection{Example}
87 \begin{astlisting}
88 \begin{verbatim}
89 Set(__FOO=bar) ; Sets an inherited version of "FOO" variable
90 Set(FOO=bar)   ; Removes the inherited version and sets a local
91                ; variable.
92 \end{verbatim}
93 \end{astlisting}
94
95 However, NoOp(\$\{\_\_FOO\}) is identical to NoOp(\$\{FOO\})
96
97 \section{Selecting Characters from Variables}
98
99 The format for selecting characters from a variable can be expressed as:
100 \begin{astlisting}
101 \begin{verbatim}
102   ${variable_name[:offset[:length]]}
103 \end{verbatim}
104 \end{astlisting}
105 If you want to select the first N characters from the string assigned
106 to a variable, simply append a colon and the number of characters to
107 skip from the beginning of the string to the variable name.
108 \begin{astlisting}
109 \begin{verbatim}
110   ; Remove the first character of extension, save in "number" variable
111   exten => _9X.,1,Set(number=${EXTEN:1})
112 \end{verbatim}
113 \end{astlisting}
114 Assuming we've dialed 918005551234, the value saved to the 'number' variable
115 would be 18005551234. This is useful in situations when we require users to
116 dial a number to access an outside line, but do not wish to pass the first
117 digit.
118
119 If you use a negative offset number, Asterisk starts counting from the end
120 of the string and then selects everything after the new position. The following
121 example will save the numbers 1234 to the 'number' variable, still assuming
122 we've dialed 918005551234.
123 \begin{astlisting}
124 \begin{verbatim}
125   ; Remove everything before the last four digits of the dialed string
126   exten => _9X.,1,Set(number=${EXTEN:-4})
127 \end{verbatim}
128 \end{astlisting}
129 We can also limit the number of characters from our offset position that we
130 wish to use. This is done by appending a second colon and length value to the
131 variable name. The following example will save the numbers 555 to the 'number'
132 variable.
133 \begin{astlisting}
134 \begin{verbatim}
135   ; Only save the middle numbers 555 from the string 918005551234
136   exten => _9X.,1,Set(number=${EXTEN:5:3})
137 \end{verbatim}
138 \end{astlisting}
139 The length value can also be used in conjunction with a negative offset. This
140 may be useful if the length of the string is unknown, but the trailing digits
141 are. The following example will save the numbers 555 to the 'number' variable,
142 even if the string starts with more characters than expected (unlike the
143 previous example).
144 \begin{astlisting}
145 \begin{verbatim}
146   ; Save the numbers 555 to the 'number' variable
147   exten => _9X.,1,Set(number=${EXTEN:-7:3})
148 \end{verbatim}
149 \end{astlisting}
150 If a negative length value is entered, Asterisk will remove that many characters
151 from the end of the string.
152 \begin{astlisting}
153 \begin{verbatim}
154   ; Set pin to everything but the trailing #.
155   exten => _XXXX#,1,Set(pin=${EXTEN:0:-1})
156 \end{verbatim}
157 \end{astlisting}
158
159 \section{Expressions}
160
161 Everything contained inside a bracket pair prefixed by a \$ (like \$[this]) is
162 considered as an expression and it is evaluated. Evaluation works similar to
163 (but is done on a later stage than) variable substitution: the expression
164 (including the square brackets) is replaced by the result of the expression
165 evaluation.
166
167 For example, after the sequence:
168 \begin{astlisting}
169 \begin{verbatim}
170 exten => 1,1,Set(lala=$[1 + 2])
171 exten => 1,2,Set(koko=$[2 * ${lala}])
172 \end{verbatim}
173 \end{astlisting}
174 the value of variable koko is "6".
175
176 and, further:
177 \begin{astlisting}
178 \begin{verbatim}
179 exten => 1,1,Set,(lala=$[  1 +    2   ]);
180 \end{verbatim}
181 \end{astlisting}
182 will parse as intended. Extra spaces are ignored.
183
184
185 \subsection{Spaces Inside Variables Values}
186
187 If the variable being evaluated contains spaces, there can be problems.
188
189 For these cases, double quotes around text that may contain spaces
190 will force the surrounded text to be evaluated as a single token.
191 The double quotes will be counted as part of that lexical token.
192
193 As an example:
194
195 \begin{astlisting}
196 \begin{verbatim}
197 exten => s,6,GotoIf($[ "${CALLERID(name)}" : "Privacy Manager" ]?callerid-liar,s,1:s,7)
198 \end{verbatim}
199 \end{astlisting}
200
201 The variable CALLERID(name) could evaluate to "DELOREAN MOTORS" (with a space)
202 but the above will evaluate to:
203
204 \begin{verbatim}
205 "DELOREAN MOTORS" : "Privacy Manager"
206 \end{verbatim}
207
208 and will evaluate to 0.
209
210 The above without double quotes would have evaluated to:
211
212 \begin{verbatim}
213 DELOREAN MOTORS : Privacy Manager
214 \end{verbatim}
215
216 and will result in syntax errors, because token DELOREAN is immediately
217 followed by token MOTORS and the expression parser will not know how to
218 evaluate this expression, because it does not match its grammar.
219
220 \subsection{Operators}
221
222 Operators are listed below in order of increasing precedence.  Operators
223 with equal precedence are grouped within \{ \} symbols.
224
225 \begin{itemize}
226   \item \verb!expr1 | expr2!
227
228        Return the evaluation of expr1 if it is neither an empty string
229        nor zero; otherwise, returns the evaluation of expr2.
230
231   \item \verb!expr1 & expr2!
232
233        Return the evaluation of expr1 if neither expression evaluates to
234        an empty string or zero; otherwise, returns zero.
235
236   \item \verb+expr1 {=, >, >=, <, <=, !=} expr2+
237
238        Return the results of floating point comparison if both arguments are
239        numbers; otherwise, returns the results of string comparison
240        using the locale-specific collation sequence.  The result of each
241        comparison is 1 if the specified relation is true, or 0 if the
242        relation is false.
243
244   \item \verb!expr1 {+, -} expr2!
245
246        Return the results of addition or subtraction of floating point-valued
247        arguments.
248
249   \item \verb!expr1 {*, /, %} expr2!
250
251        Return the results of multiplication, floating point division, or
252        remainder of arguments.
253
254   \item \verb!- expr1!
255
256        Return the result of subtracting expr1 from 0.
257        This, the unary minus operator, is right associative, and
258        has the same precedence as the ! operator.
259
260   \item \verb+! expr1+
261
262        Return the result of a logical complement of expr1.
263        In other words, if expr1 is null, 0, an empty string,
264        or the string "0", return a 1. Otherwise, return a 0.
265        It has the same precedence as the unary minus operator, and
266        is also right associative.
267
268   \item \verb!expr1 : expr2!
269
270        The `:' operator matches expr1 against expr2, which must be a
271        regular expression.  The regular expression is anchored to the
272        beginning of  the string with an implicit `\^'.
273
274        If the match succeeds and the pattern contains at least one regular
275        expression subexpression `\(...\)', the string corresponing
276        to `\textbackslash1' is returned; otherwise the matching operator
277        returns the number of characters matched.  If the match fails and
278        the pattern contains a regular expression subexpression the null
279        string is returned; otherwise 0.
280
281        Normally, the double quotes wrapping a string are left as part
282        of the string. This is disastrous to the : operator. Therefore,
283        before the regex match is made, beginning and ending double quote
284        characters are stripped from both the pattern and the string.
285
286    \item \verb!expr1 =~ expr2!
287
288        Exactly the same as the ':' operator, except that the match is
289        not anchored to the beginning of the string. Pardon any similarity
290        to seemingly similar operators in other programming languages!
291        The ":" and "=\~" operators share the same precedence.
292
293    \item \verb!expr1 ? expr2 :: expr3!
294
295        Traditional Conditional operator. If expr1 is a number
296        that evaluates to 0 (false), expr3 is result of the this
297        expression evaluation.  Otherwise, expr2 is the result.
298        If expr1 is a string, and evaluates to an empty string,
299        or the two characters (""), then expr3 is the
300        result. Otherwise, expr2 is the result.  In Asterisk, all
301        3 exprs will be "evaluated"; if expr1 is "true", expr2
302        will be the result of the "evaluation" of this
303        expression.  expr3 will be the result otherwise. This
304        operator has the lowest precedence.
305
306    \item \verb!expr1 ~~ expr2!
307
308         Concatenation operator. The two exprs are evaluated and
309         turned into strings, stripped of surrounding double quotes,
310         and are turned into a single string with no invtervening spaces. 
311         This operator is new to trunk after 1.6.0; it is not needed 
312         in existing extensions.conf code. Because of the way asterisk
313         evaluates ${ } and $[ ] constructs (recursively, bottom-
314         up), no $[] or ${} is ever present when the contents
315         of a ${} or $[] is evaluated. Thus, tokens are usually
316         already merged at evaluation time. But, in AEL, various
317         exprs are evaluated raw, and ${} and $[] are gathered
318         and treated as tokens. And in AEL, no two tokens can
319         sit side by side without an intervening operator.
320         So, in AEL, concatenation must be explicitly specified
321         in expressions. This new operator will play well into
322         future plans, where expressions ($[] constructs, and
323         variable references (${} constructs) are merged into a 
324         single grammar. 
325
326 \end{itemize}
327
328 Parentheses are used for grouping in the usual manner.
329
330 Operator precedence is applied as one would expect in any of the C
331 or C derived languages.
332
333 \subsection{Floating Point Numbers}
334
335 In 1.6 and above, we shifted the \$[...] expressions to be calculated
336 via floating point numbers instead of integers. We use 'long double' numbers
337 when possible, which provide around 16 digits of precision with 12 byte numbers.
338
339 To specify a floating point constant, the number has to have this format: D.D, where D is
340 a string of base 10 digits. So, you can say 0.10, but you can't say .10 or 20.-- we hope
341 this is not an excessive restriction!
342
343 Floating point numbers are turned into strings via the '\%g'/'\%Lg' format of the printf
344 function set. This allows numbers to still 'look' like integers to those counting
345 on integer behavior. If you were counting on 1/4 evaluating to 0, you need to now say
346 TRUNC(1/4). For a list of all the truncation/rounding capabilities, see the next section.
347
348
349 \subsection{Functions}
350
351 In 1.6 and above, we upgraded the \$[] expressions to handle floating point numbers.
352 Because of this, folks counting on integer behavior would be disrupted. To make
353 the same results possible, some rounding and integer truncation functions have been
354 added to the core of the Expr2 parser. Indeed, dialplan functions can be called from
355 \$[..] expressions without the \$\{...\} operators. The only trouble might be in the fact that
356 the arguments to these functions must be specified with a comma. If you try to call
357 the MATH function, for example, and try to say 3 + MATH(7*8), the expression parser will
358 evaluate 7*8 for you into 56, and the MATH function will most likely complain that its
359 input doesn't make any sense.
360
361 We also provide access to most of the floating point functions in the C library. (but not all of them).
362
363 While we don't expect someone to want to do Fourier analysis in the dialplan, we
364 don't want to preclude it, either.
365
366 Here is a list of the 'builtin' functions in Expr2. All other dialplan functions
367 are available by simply calling them (read-only). In other words, you don't need to
368 surround function calls in \$[...] expressions with \$\{...\}. Don't jump to conclusions,
369 though! -- you still need to wrap variable names in curly braces!
370
371 \begin{enumerate}
372 \item COS(x) x is in radians. Results vary from -1 to 1.
373 \item SIN(x) x is in radians. Results vary from -1 to 1.
374 \item TAN(x) x is in radians.
375 \item ACOS(x) x should be a value between -1 and 1.
376 \item ASIN(x) x should be a value between -1 and 1.
377 \item ATAN(x) returns the arc tangent in radians; between -PI/2 and PI/2.
378 \item ATAN2(x,y) returns a result resembling y/x, except that the signs of both args are used to determine the quadrant of the result. Its result is in radians, between -PI and PI.
379 \item POW(x,y) returns the value of x raised to the power of y.
380 \item SQRT(x) returns the square root of x.
381 \item FLOOR(x) rounds x down to the nearest integer.
382 \item CEIL(x) rounds x up to the nearest integer.
383 \item ROUND(x) rounds x to the nearest integer, but round halfway cases away from zero.
384 \item RINT(x) rounds x to the nearest integer, rounding halfway cases to the nearest even integer.
385 \item TRUNC(x) rounds x to the nearest integer not larger in absolute value.
386 \item REMAINDER(x,y) computes the remainder of dividing x by y. The return value is x - n*y, where n is the value x/y, rounded to the nearest integer. If this quotient is 1/2, it is rounded to the nearest even number.
387 \item EXP(x) returns e to the x power.
388 \item EXP2(x) returns 2 to the x power.
389 \item LOG(x) returns the natural logarithm of x.
390 \item LOG2(x) returns the base 2 log of x.
391 \item LOG10(x) returns the base 10 log of x.
392 \end{enumerate}
393
394 \subsection{Examples}
395
396 \begin{astlisting}
397 \begin{verbatim}
398  "One Thousand Five Hundred" =~ "(T[^ ]+)"
399    returns: Thousand
400
401  "One Thousand Five Hundred" =~ "T[^ ]+"
402    returns: 8
403
404  "One Thousand Five Hundred" : "T[^ ]+"
405    returns: 0
406
407  "8015551212" : "(...)"
408    returns: 801
409
410  "3075551212":"...(...)"
411    returns: 555
412
413  ! "One Thousand Five Hundred" =~ "T[^ ]+"
414    returns: 0 (because it applies to the string, which is non-null,
415                     which it turns to "0", and then looks for the pattern
416                     in the "0", and doesn't find it)
417
418  !( "One Thousand Five Hundred" : "T[^ ]+" )
419    returns: 1  (because the string doesn't start with a word starting
420                      with T, so the match evals to 0, and the ! operator
421                      inverts it to 1 ).
422
423  2 + 8 / 2
424    returns 6. (because of operator precedence; the division is done first, then the addition).
425
426  2+8/2
427    returns 6. Spaces aren't necessary.
428
429 (2+8)/2
430    returns 5, of course.
431
432 (3+8)/2
433    returns 5.5 now.
434
435 TRUNC((3+8)/2)
436    returns 5.
437
438 FLOOR(2.5)
439    returns 2
440
441 FLOOR(-2.5)
442    returns -3
443
444 CEIL(2.5)
445    returns 3.
446
447 CEIL(-2.5)
448    returns -2.
449
450 ROUND(2.5)
451    returns 3.
452
453 ROUND(3.5)
454    returns 4.
455
456 ROUND(-2.5)
457    returns -3
458
459 RINT(2.5)
460    returns 2.
461
462 RINT(3.5)
463    returns 4.
464
465 RINT(-2.5)
466    returns -2.
467
468 RINT(-3.5)
469    returns -4.
470
471 TRUNC(2.5)
472    returns 2.
473
474 TRUNC(3.5)
475    returns 3.
476
477 TRUNC(-3.5)
478    returns -3.
479 \end{verbatim}
480 \end{astlisting}
481
482 Of course, all of the above examples use constants, but would work the
483 same if any of the numeric or string constants were replaced with a
484 variable reference \$\{CALLERID(num)\}, for instance.
485
486
487 \subsection{Numbers Vs. Strings}
488
489 Tokens consisting only of numbers are converted to 'long double' if possible, which
490 are from 80 bits to 128 bits depending on the OS, compiler, and hardware.
491 This means that overflows can occur when the
492 numbers get above 18 digits (depending on the number of bits involved).  Warnings will appear in the logs in this
493 case.
494
495 \subsection{Conditionals}
496
497 There is one conditional application - the conditional goto :
498 \begin{astlisting}
499 \begin{verbatim}
500   exten => 1,2,GotoIf(condition?label1:label2)
501 \end{verbatim}
502 \end{astlisting}
503
504 If condition is true go to label1, else go to label2. Labels are interpreted
505 exactly as in the normal goto command.
506
507 "condition" is just a string. If the string is empty or "0", the condition
508 is considered to be false, if it's anything else, the condition is true.
509 This is designed to be used together with the expression syntax described
510 above, eg :
511
512 \begin{astlisting}
513 \begin{verbatim}
514   exten => 1,2,GotoIf($[${CALLERID(all)} = 123456]?2,1:3,1)
515 \end{verbatim}
516 \end{astlisting}
517
518 Example of use :
519 \begin{astlisting}
520 \begin{verbatim}
521 exten => s,2,Set(vara=1)
522 exten => s,3,Set(varb=$[${vara} + 2])
523 exten => s,4,Set(varc=$[${varb} * 2])
524 exten => s,5,GotoIf($[${varc} = 6]?99,1:s,6)
525 \end{verbatim}
526 \end{astlisting}
527
528 \subsection{Parse Errors}
529
530 Syntax errors are now output with 3 lines.
531
532 If the extensions.conf file contains a line like:
533
534 \begin{astlisting}
535 \begin{verbatim}
536 exten => s,6,GotoIf($[ "${CALLERID(num)}"  = "3071234567" & &  "${CALLERID(name)}" : "Privacy Manager" ]?callerid-liar,s,1:s,7)
537 \end{verbatim}
538 \end{astlisting}
539
540 You may see an error in \path{/var/log/asterisk/messages} like this:
541 \begin{astlisting}
542 \begin{verbatim}
543 Jul 15 21:27:49 WARNING[1251240752]: ast_yyerror(): syntax error: parse error, unexpected TOK_AND, expecting TOK_MINUS or TOK_LP or TOKEN; Input:
544 "3072312154"  = "3071234567" & & "Steves Extension" : "Privacy Manager"
545                ^
546 \end{verbatim}
547 \end{astlisting}
548
549 The log line tells you that a syntax error was encountered. It now
550 also tells you (in grand standard bison format) that it hit an "AND"
551 (\&) token unexpectedly, and that was hoping for for a MINUS (-), LP
552 (left parenthesis), or a plain token (a string or number).
553
554 The next line shows the evaluated expression, and the line after
555 that, the position of the parser in the expression when it became confused,
556 marked with the "\^" character.
557
558 \subsection{NULL Strings}
559 Testing to see if a string is null can be done in one of two different ways:
560 \begin{astlisting}
561 \begin{verbatim}
562   exten => _XX.,1,GotoIf($["${calledid}" != ""]?3)
563     or
564   exten => _XX.,1,GotoIf($[foo${calledid} != foo]?3)
565 \end{verbatim}
566 \end{astlisting}
567
568 The second example above is the way suggested by the WIKI. It will
569 work as long as there are no spaces in the evaluated value.
570
571 The first way should work in all cases, and indeed, might now
572 be the safest way to handle this situation.
573
574 \subsection{Warning}
575
576 If you need to do complicated things with strings, asterisk expressions
577 is most likely NOT the best way to go about it. AGI scripts are an
578 excellent option to this need, and make available the full power of
579 whatever language you desire, be it Perl, C, C++, Cobol, RPG, Java,
580 Snobol, PL/I, Scheme, Common Lisp, Shell scripts, Tcl, Forth, Modula,
581 Pascal, APL, assembler, etc.
582
583 \subsection{Incompatabilities}
584
585 The asterisk expression parser has undergone some evolution. It is hoped
586 that the changes will be viewed as positive.
587
588 The "original" expression parser had a simple, hand-written scanner,
589 and a simple bison grammar. This was upgraded to a more involved bison
590 grammar, and a hand-written scanner upgraded to allow extra spaces,
591 and to generate better error diagnostics. This upgrade required bison
592 1.85, and part of the user community felt the pain of having to
593 upgrade their bison version.
594
595 The next upgrade included new bison and flex input files, and the makefile
596 was upgraded to detect current version of both flex and bison, conditionally
597 compiling and linking the new files if the versions of flex and bison would
598 allow it.
599
600 If you have not touched your extensions.conf files in a year or so, the
601 above upgrades may cause you some heartburn in certain circumstances, as
602 several changes have been made, and these will affect asterisk's behavior on
603 legacy extension.conf constructs.  The changes have been engineered
604 to minimize these conflicts, but there are bound to be problems.
605
606 The following list gives some (and most likely, not all) of areas
607 of possible concern with "legacy" extension.conf files:
608
609 \begin{enumerate}
610 \item Tokens separated by space(s).
611    Previously, tokens were separated by spaces. Thus, ' 1 + 1 ' would evaluate
612    to the value '2', but '1+1' would evaluate to the string '1+1'. If this
613    behavior was depended on, then the expression evaluation will break. '1+1'
614    will now evaluate to '2', and something is not going to work right.
615    To keep such strings from being evaluated, simply wrap them in double
616    quotes: '  "1+1" '
617
618 \item The colon operator. In versions previous to double quoting, the
619    colon operator takes the right hand string, and using it as a
620    regex pattern, looks for it in the left hand string. It is given
621    an implicit \^ operator at the beginning, meaning the pattern
622    will match only at the beginning of the left hand string.
623    If the pattern or the matching string had double quotes around
624    them, these could get in the way of the pattern match. Now,
625    the wrapping double quotes are stripped from both the pattern
626    and the left hand string before applying the pattern. This
627    was done because it recognized that the new way of
628    scanning the expression doesn't use spaces to separate tokens,
629    and the average regex expression is full of operators that
630    the scanner will recognize as expression operators. Thus, unless
631    the pattern is wrapped in double quotes, there will be trouble.
632    For instance,      \$\{VAR1\} : (Who$|$What*)+
633    may have have worked before, but unless you wrap the pattern
634    in double quotes now, look out for trouble! This is better:
635          "\$\{VAR1\}" : "(Who$|$What*)+"
636    and should work as previous.
637
638 \item Variables and Double Quotes
639    Before these changes, if a variable's value contained one or more double
640    quotes, it was no reason for concern. It is now!
641
642 \item LE, GE, NE operators removed. The code supported these operators,
643    but they were not documented. The symbolic operators, $<$=, $>$=, and !=
644    should be used instead.
645
646 \item  Added the unary '-' operator. So you can 3+ -4 and get -1.
647
648 \item  Added the unary '!' operator, which is a logical complement.
649     Basically, if the string or number is null, empty, or '0',
650     a '1' is returned. Otherwise a '0' is returned.
651
652 \item  Added the '=~' operator, just in case someone is just looking for
653     match anywhere in the string. The only diff with the ':' is that
654     match doesn't have to be anchored to the beginning of the string.
655
656 \item  Added the conditional operator  'expr1 ? true\_expr : false\_expr'
657     First, all 3 exprs are evaluated, and if expr1 is false, the 'false\_expr'
658     is returned as the result. See above for details.
659
660 \item  Unary operators '-' and '!' were made right associative.
661 \end{enumerate}
662
663 \subsection{Debugging Hints}
664
665 There are two utilities you can build to help debug the \$[ ] in
666 your extensions.conf file.
667
668 The first, and most simplistic, is to issue the command:
669 \begin{astlisting}
670 \begin{verbatim}
671 make testexpr2
672 \end{verbatim}
673 \end{astlisting}
674 in the top level asterisk source directory. This will build a small
675 executable, that is able to take the first command line argument, and
676 run it thru the expression parser. No variable substitutions will be
677 performed. It might be safest to wrap the expression in single
678 quotes...
679 \begin{astlisting}
680 \begin{verbatim}
681 testexpr2 '2*2+2/2'
682 \end{verbatim}
683 \end{astlisting}
684 is an example.
685
686 And, in the utils directory, you can say:
687 \begin{astlisting}
688 \begin{verbatim}
689 make check_expr
690 \end{verbatim}
691 \end{astlisting}
692 and a small program will be built, that will check the file mentioned
693 in the first command line argument, for any expressions that might be
694 have problems when you move to flex-2.5.31.  It was originally
695 designed to help spot possible incompatibilities when moving from the
696 pre-2.5.31 world to the upgraded version of the lexer.
697
698 But one more capability has been added to check\_expr, that might make
699 it more generally useful. It now does a simple minded evaluation of
700 all variables, and then passes the \$[] exprs to the parser. If there
701 are any parse errors, they will be reported in the log file. You can
702 use check\_expr to do a quick sanity check of the expressions in your
703 extensions.conf file, to see if they pass a crude syntax check.
704
705 The "simple-minded" variable substitution replaces \$\{varname\} variable
706 references with '555'. You can override the 555 for variable values,
707 by entering in var=val arguments after the filename on the command
708 line.  So...
709 \begin{astlisting}
710 \begin{verbatim}
711  check_expr /etc/asterisk/extensions.conf CALLERID(num)=3075551212 DIALSTATUS=TORTURE EXTEN=121
712 \end{verbatim}
713 \end{astlisting}
714 will substitute any \$\{CALLERID(num)\} variable references with
715 3075551212, any \$\{DIALSTATUS\} variable references with 'TORTURE', and
716 any \$\{EXTEN\} references with '121'.  If there is any fancy stuff
717 going on in the reference, like \$\{EXTEN:2\}, then the override will
718 not work. Everything in the \$\{...\} has to match. So, to substitute
719 \$\{EXTEN:2\} references, you'd best say:
720 \begin{astlisting}
721 \begin{verbatim}
722  check_expr /etc/asterisk/extensions.conf CALLERID(num)=3075551212 DIALSTATUS=TORTURE EXTEN:2=121
723 \end{verbatim}
724 \end{astlisting}
725 on stdout, you will see something like:
726
727 \begin{astlisting}
728 \begin{verbatim}
729  OK -- $[ "${DIALSTATUS}"  = "TORTURE" | "${DIALSTATUS}" = "DONTCALL" ] at line 416
730 \end{verbatim}
731 \end{astlisting}
732
733 In the expr2\_log file that is generated, you will see:
734
735 \begin{astlisting}
736 \begin{verbatim}
737  line 416, evaluation of $[  "TORTURE"  = "TORTURE" | "TORTURE" = "DONTCALL"  ] result: 1
738 \end{verbatim}
739 \end{astlisting}
740
741 check\_expr is a very simplistic algorithm, and it is far from being
742 guaranteed to work in all cases, but it is hoped that it will be
743 useful.
744
745 \section{Asterisk standard channel variables}
746
747 There are a number of variables that are defined or read
748 by Asterisk. Here is a list of them. More information is
749 available in each application's help text. All these variables
750 are in UPPER CASE only.
751
752 Variables marked with a * are builtin functions and can't be set,
753 only read in the dialplan.  Writes to such variables are silently
754 ignored.
755
756 \begin{verbatim}
757 ${CDR(accountcode)}    * Account code (if specified)
758 ${BLINDTRANSFER}         The name of the channel on the other side of a blind transfer
759 ${BRIDGEPEER}            Bridged peer
760 ${BRIDGEPVTCALLID}       Bridged peer PVT call ID (SIP Call ID if a SIP call)
761 ${CALLERID(ani)}       * Caller ANI (PRI channels)
762 ${CALLERID(ani2)}      * ANI2 (Info digits) also called Originating line information or OLI
763 ${CALLERID(all)}       * Caller ID
764 ${CALLERID(dnid)}      * Dialed Number Identifier
765 ${CALLERID(name)}      * Caller ID Name only
766 ${CALLERID(num)}       * Caller ID Number only
767 ${CALLERID(rdnis)}     * Redirected Dial Number ID Service
768 ${CALLINGANI2}         * Caller ANI2 (PRI channels)
769 ${CALLINGPRES}         * Caller ID presentation for incoming calls (PRI channels)
770 ${CALLINGTNS}          * Transit Network Selector (PRI channels)
771 ${CALLINGTON}          * Caller Type of Number (PRI channels)
772 ${CHANNEL}             * Current channel name
773 ${CONTEXT}             * Current context
774 ${DATETIME}            * Current date time in the format: DDMMYYYY-HH:MM:SS
775                          (Deprecated; use ${STRFTIME(${EPOCH},,%d%m%Y-%H:%M:%S)})
776 ${DB_RESULT}             Result value of DB_EXISTS() dial plan function
777 ${EPOCH}               * Current unix style epoch
778 ${EXTEN}               * Current extension
779 ${ENV(VAR)}              Environmental variable VAR
780 ${GOTO_ON_BLINDXFR}      Transfer to the specified context/extension/priority
781                          after a blind transfer (use ^ characters in place of
782                          | to separate context/extension/priority when setting
783                          this variable from the dialplan)
784 ${HANGUPCAUSE}         * Asterisk cause of hangup (inbound/outbound)
785 ${HINT}                * Channel hints for this extension
786 ${HINTNAME}            * Suggested Caller*ID name for this extension
787 ${INVALID_EXTEN}         The invalid called extension (used in the "i" extension)
788 ${LANGUAGE}            * Current language (Deprecated; use ${LANGUAGE()})
789 ${LEN(VAR)}            * String length of VAR (integer)
790 ${PRIORITY}            * Current priority in the dialplan
791 ${PRIREDIRECTREASON}     Reason for redirect on PRI, if a call was directed
792 ${TIMESTAMP}           * Current date time in the format: YYYYMMDD-HHMMSS
793                          (Deprecated; use ${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)})
794 ${TRANSFER_CONTEXT}      Context for transferred calls
795 ${FORWARD_CONTEXT}       Context for forwarded calls
796 ${DYNAMIC_PEERNAME}      The name of the channel on the other side when a dynamic
797                          feature is used.
798 ${DYNAMIC_FEATURENAME}   The name of the last triggered dynamic feature.
799 ${UNIQUEID}            * Current call unique identifier
800 ${SYSTEMNAME}          * value of the systemname option of asterisk.conf
801 ${ENTITYID}            * Global Entity ID set automatically, or from asterisk.conf
802 \end{verbatim}
803
804 \subsection{Application return values}
805
806 Many applications return the result in a variable that you read to
807 get the result of the application. These status fields are unique
808 for each application.
809 For the various status values, see each application's help text.
810 \begin{verbatim}
811 ${AGISTATUS}         * agi()
812 ${AQMSTATUS}         * addqueuemember()
813 ${AVAILSTATUS}       * chanisavail()
814 ${CHECKGROUPSTATUS}  * checkgroup()
815 ${CHECKMD5STATUS}    * checkmd5()
816 ${CPLAYBACKSTATUS}   * controlplayback()
817 ${DIALSTATUS}        * dial()
818 ${DBGETSTATUS}       * dbget()
819 ${ENUMSTATUS}        * enumlookup()
820 ${HASVMSTATUS}       * hasnewvoicemail()
821 ${LOOKUPBLSTATUS}    * lookupblacklist()
822 ${OSPAUTHSTATUS}     * ospauth()
823 ${OSPLOOKUPSTATUS}   * osplookup()
824 ${OSPNEXTSTATUS}     * ospnext()
825 ${OSPFINISHSTATUS}   * ospfinish()
826 ${PARKEDAT}          * parkandannounce()
827 ${PLAYBACKSTATUS}    * playback()
828 ${PQMSTATUS}         * pausequeuemember()
829 ${PRIVACYMGRSTATUS}  * privacymanager()
830 ${QUEUESTATUS}       * queue()
831 ${RQMSTATUS}         * removequeuemember()
832 ${SENDIMAGESTATUS}   * sendimage()
833 ${SENDTEXTSTATUS}    * sendtext()
834 ${SENDURLSTATUS}     * sendurl()
835 ${SYSTEMSTATUS}      * system()
836 ${TRANSFERSTATUS}    * transfer()
837 ${TXTCIDNAMESTATUS}  * txtcidname()
838 ${UPQMSTATUS}        * unpausequeuemember()
839 ${VMSTATUS}          * voicmail()
840 ${VMBOXEXISTSSTATUS} * vmboxexists()
841 ${WAITSTATUS}        * waitforsilence()
842 \end{verbatim}
843
844 \subsection{Various application variables}
845 \begin{verbatim}
846 ${CURL}                 * Resulting page content for curl()
847 ${ENUM}                 * Result of application EnumLookup
848 ${EXITCONTEXT}            Context to exit to in IVR menu (app background())
849                           or in the RetryDial() application
850 ${MONITOR}              * Set to "TRUE" if the channel is/has been monitored (app monitor())
851 ${MONITOR_EXEC}           Application to execute after monitoring a call
852 ${MONITOR_EXEC_ARGS}      Arguments to application
853 ${MONITOR_FILENAME}       File for monitoring (recording) calls in queue
854 ${QUEUE_PRIO}             Queue priority
855 ${QUEUE_MAX_PENALTY}      Maximum member penalty allowed to answer caller
856 ${QUEUE_MIN_PENALTY}      Minimum member penalty allowed to answer caller
857 ${QUEUESTATUS}            Status of the call, one of:
858                           (TIMEOUT | FULL | JOINEMPTY | LEAVEEMPTY | JOINUNAVAIL | LEAVEUNAVAIL)
859 ${QUEUEPOSITION}        * When a caller is removed from a queue, his current position is logged
860                           in this variable. If the value is 0, then this means that the caller was
861                                                   serviced by a queue member. If non-zero, then this was the position in the
862                                                   queue the caller was in when he left.
863 ${RECORDED_FILE}        * Recorded file in record()
864 ${TALK_DETECTED}        * Result from talkdetect()
865 ${TOUCH_MONITOR}          The filename base to use with Touch Monitor (auto record)
866 ${TOUCH_MONITOR_PREF}   * The prefix for automonitor recording filenames.
867 ${TOUCH_MONITOR_FORMAT}   The audio format to use with Touch Monitor (auto record)
868 ${TOUCH_MONITOR_OUTPUT} * Recorded file from Touch Monitor (auto record)
869 ${TOUCH_MONITOR_MESSAGE_START} Recorded file to play for both channels at start of monitoring session
870 ${TOUCH_MONITOR_MESSAGE_STOP} Recorded file to play for both channels at end of monitoring session
871 ${TXTCIDNAME}           * Result of application TXTCIDName
872 ${VPB_GETDTMF}            chan_vpb
873 \end{verbatim}
874
875 \subsection{The MeetMe Conference Bridge}
876 \begin{verbatim}
877 ${MEETME_RECORDINGFILE}      Name of file for recording a conference with
878                              the "r" option
879 ${MEETME_RECORDINGFORMAT}    Format of file to be recorded
880 ${MEETME_EXIT_CONTEXT}       Context for exit out of meetme meeting
881 ${MEETME_AGI_BACKGROUND}     AGI script for Meetme (DAHDI only)
882 ${MEETMESECS}              * Number of seconds a user participated in a MeetMe conference
883 ${CONF_LIMIT_TIMEOUT_FILE}   File to play when time is up.  Used with the L() option.
884 ${CONF_LIMIT_WARNING_FILE}   File to play as warning if 'y' is defined.
885                              The default is to say the time remaining.  Used with the L() option.
886 \end{verbatim}
887
888 \subsection{The VoiceMail() application}
889 \begin{verbatim}
890 ${VM_CATEGORY}      Sets voicemail category
891 ${VM_NAME}        * Full name in voicemail
892 ${VM_DUR}         * Voicemail duration
893 ${VM_MSGNUM}      * Number of voicemail message in mailbox
894 ${VM_CALLERID}    * Voicemail Caller ID (Person leaving vm)
895 ${VM_CIDNAME}     * Voicemail Caller ID Name
896 ${VM_CIDNUM}      * Voicemail Caller ID Number
897 ${VM_DATE}        * Voicemail Date
898 ${VM_MESSAGEFILE} * Path to message left by caller
899 \end{verbatim}
900
901 \subsection{The VMAuthenticate() application}
902 \begin{verbatim}
903 ${AUTH_MAILBOX}   * Authenticated mailbox
904 ${AUTH_CONTEXT}   * Authenticated mailbox context
905 \end{verbatim}
906
907 \subsection{DUNDiLookup()}
908 \begin{verbatim}
909 ${DUNDTECH}       * The Technology of the result from a call to DUNDiLookup()
910 ${DUNDDEST}       * The Destination of the result from a call to DUNDiLookup()
911 \end{verbatim}
912
913 \subsection{chan\_dahdi}
914 \begin{verbatim}
915 ${ANI2}               * The ANI2 Code provided by the network on the incoming call.
916                         (ie, Code 29 identifies call as a Prison/Inmate Call)
917 ${CALLTYPE}           * Type of call (Speech, Digital, etc)
918 ${CALLEDTON}          * Type of number for incoming PRI extension
919                         i.e. 0=unknown, 1=international, 2=domestic, 3=net_specific,
920                         4=subscriber, 6=abbreviated, 7=reserved
921 ${CALLINGSUBADDR}     * Caller's PRI Subaddress
922 ${FAXEXTEN}           * The extension called before being redirected to "fax"
923 ${PRIREDIRECTREASON}  * Reason for redirect, if a call was directed
924 ${SMDI_VM_TYPE}       * When an call is received with an SMDI message, the 'type'
925                         of message 'b' or 'u'
926 \end{verbatim}
927
928 \subsection{chan\_sip}
929 \begin{verbatim}
930 ${SIPCALLID}         * SIP Call-ID: header verbatim (for logging or CDR matching)
931 ${SIPDOMAIN}         * SIP destination domain of an inbound call (if appropriate)
932 ${SIPFROMDOMAIN}       Set SIP domain on outbound calls
933 ${SIPUSERAGENT}      * SIP user agent (deprecated)
934 ${SIPURI}            * SIP uri
935 ${SIP_CODEC}           Set the SIP codec for an inbound call
936 ${SIP_CODEC_INBOUND}   Set the SIP codec for an inbound call
937 ${SIP_CODEC_OUTBOUND}  Set the SIP codec for an outbound call
938 ${SIP_URI_OPTIONS}   * additional options to add to the URI for an outgoing call
939 ${RTPAUDIOQOS}         RTCP QoS report for the audio of this call
940 ${RTPVIDEOQOS}         RTCP QoS report for the video of this call
941 \end{verbatim}
942
943 \subsection{chan\_agent}
944 \begin{verbatim}
945 ${AGENTMAXLOGINTRIES}  Set the maximum number of failed logins
946 ${AGENTUPDATECDR}      Whether to update the CDR record with Agent channel data
947 ${AGENTGOODBYE}        Sound file to use for "Good Bye" when agent logs out
948 ${AGENTACKCALL}        Whether the agent should acknowledge the incoming call
949 ${AGENTAUTOLOGOFF}     Auto logging off for an agent
950 ${AGENTWRAPUPTIME}     Setting the time for wrapup between incoming calls
951 ${AGENTNUMBER}       * Agent number (username) set at login
952 ${AGENTSTATUS}       * Status of login ( fail | on | off )
953 ${AGENTEXTEN}        * Extension for logged in agent
954 \end{verbatim}
955
956
957 \subsection{The Dial() application}
958 \begin{verbatim}
959 ${DIALEDPEERNAME}     * Dialed peer name
960 ${DIALEDPEERNUMBER}   * Dialed peer number
961 ${DIALEDTIME}         * Time for the call (seconds). Is only set if call was answered.
962 ${ANSWEREDTIME}       * Time from answer to hangup (seconds)
963 ${DIALSTATUS}         * Status of the call, one of:
964                         (CHANUNAVAIL | CONGESTION | BUSY | NOANSWER
965                         | ANSWER | CANCEL | DONTCALL | TORTURE)
966 ${DYNAMIC_FEATURES}   * The list of features (from the [applicationmap] section of
967                         features.conf) to activate during the call, with feature
968                         names separated by '#' characters
969 ${LIMIT_PLAYAUDIO_CALLER}  Soundfile for call limits
970 ${LIMIT_PLAYAUDIO_CALLEE}  Soundfile for call limits
971 ${LIMIT_WARNING_FILE}      Soundfile for call limits
972 ${LIMIT_TIMEOUT_FILE}      Soundfile for call limits
973 ${LIMIT_CONNECT_FILE}      Soundfile for call limits
974 ${OUTBOUND_GROUP}          Default groups for peer channels (as in SetGroup)
975                            * See "show application dial" for more information
976 \end{verbatim}
977
978 \subsection{The chanisavail() application}
979 \begin{verbatim}
980 ${AVAILCHAN}          * the name of the available channel if one was found
981 ${AVAILORIGCHAN}      * the canonical channel name that was used to create the channel
982 ${AVAILSTATUS}        * Status of requested channel
983 \end{verbatim}
984
985 \subsection{Dialplan Macros}
986 \begin{verbatim}
987 ${MACRO_EXTEN}        * The calling extensions
988 ${MACRO_CONTEXT}      * The calling context
989 ${MACRO_PRIORITY}     * The calling priority
990 ${MACRO_OFFSET}         Offset to add to priority at return from macro
991 \end{verbatim}
992
993 \subsection{The ChanSpy() application}
994 \begin{verbatim}
995 ${SPYGROUP}           * A ':' (colon) separated list of group names.
996                         (To be set on spied on channel and matched against the g(grp) option)
997 \end{verbatim}
998
999 \subsection{OSP}
1000 \begin{verbatim}
1001 ${OSPINHANDLE}          OSP handle of in_bound call
1002 ${OSPINTIMELIMIT}       Duration limit for in_bound call
1003 ${OSPOUTHANDLE}         OSP handle of out_bound call
1004 ${OSPTECH}              OSP technology
1005 ${OSPDEST}              OSP destination
1006 ${OSPCALLING}           OSP calling number
1007 ${OSPOUTTOKEN}          OSP token to use for out_bound call
1008 ${OSPOUTTIMELIMIT}      Duration limit for out_bound call
1009 ${OSPRESULTS}           Number of remained destinations
1010 \end{verbatim}
1011
1012 \subsection{Connected line digit manipulation}
1013 \begin{verbatim}
1014 ${CONNECTED_LINE_SEND_CALLEE_MACRO}        Macro to call before sending a connected line update to the callee
1015 ${CONNECTED_LINE_SEND_CALLEE_MACRO_ARGS}   Arguments to pass to ${CONNECTED_LINE_SEND_CALLEE_MACRO}
1016 ${CONNECTED_LINE_SEND_CALLER_MACRO}        Macro to call before sending a connected line update to the caller
1017 ${CONNECTED_LINE_SEND_CALLER_MACRO_ARGS}   Arguments to pass to ${CONNECTED_LINE_SEND_CALLER_MACRO}
1018 \end{verbatim}