9f1104c5208c930a1d06a8d5df7c4514d17a2181
[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 \end{itemize}
306
307 Parentheses are used for grouping in the usual manner.
308
309 Operator precedence is applied as one would expect in any of the C
310 or C derived languages.
311
312 \subsection{Floating Point Numbers}
313
314 In 1.6 and above, we shifted the \$[...] expressions to be calculated
315 via floating point numbers instead of integers. We use 'long double' numbers
316 when possible, which provide around 16 digits of precision with 12 byte numbers.
317
318 To specify a floating point constant, the number has to have this format: D.D, where D is
319 a string of base 10 digits. So, you can say 0.10, but you can't say .10 or 20.-- we hope
320 this is not an excessive restriction!
321
322 Floating point numbers are turned into strings via the '\%g'/'\%Lg' format of the printf
323 function set. This allows numbers to still 'look' like integers to those counting
324 on integer behavior. If you were counting on 1/4 evaluating to 0, you need to now say
325 TRUNC(1/4). For a list of all the truncation/rounding capabilities, see the next section.
326
327
328 \subsection{Functions}
329
330 In 1.6 and above, we upgraded the \$[] expressions to handle floating point numbers.
331 Because of this, folks counting on integer behavior would be disrupted. To make
332 the same results possible, some rounding and integer truncation functions have been
333 added to the core of the Expr2 parser. Indeed, dialplan functions can be called from
334 \$[..] expressions without the \$\{...\} operators. The only trouble might be in the fact that
335 the arguments to these functions must be specified with a comma. If you try to call
336 the MATH function, for example, and try to say 3 + MATH(7*8), the expression parser will
337 evaluate 7*8 for you into 56, and the MATH function will most likely complain that its
338 input doesn't make any sense.
339
340 We also provide access to most of the floating point functions in the C library. (but not all of them).
341
342 While we don't expect someone to want to do Fourier analysis in the dialplan, we
343 don't want to preclude it, either.
344
345 Here is a list of the 'builtin' functions in Expr2. All other dialplan functions
346 are available by simply calling them (read-only). In other words, you don't need to
347 surround function calls in \$[...] expressions with \$\{...\}. Don't jump to conclusions,
348 though! -- you still need to wrap variable names in curly braces!
349
350 \begin{enumerate}
351 \item COS(x) x is in radians. Results vary from -1 to 1.
352 \item SIN(x) x is in radians. Results vary from -1 to 1.
353 \item TAN(x) x is in radians.
354 \item ACOS(x) x should be a value between -1 and 1.
355 \item ASIN(x) x should be a value between -1 and 1.
356 \item ATAN(x) returns the arc tangent in radians; between -PI/2 and PI/2.
357 \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.
358 \item POW(x,y) returns the value of x raised to the power of y.
359 \item SQRT(x) returns the square root of x.
360 \item FLOOR(x) rounds x down to the nearest integer.
361 \item CEIL(x) rounds x up to the nearest integer.
362 \item ROUND(x) rounds x to the nearest integer, but round halfway cases away from zero.
363 \item RINT(x) rounds x to the nearest integer, rounding halfway cases to the nearest even integer.
364 \item TRUNC(x) rounds x to the nearest integer not larger in absolute value.
365 \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.
366 \item EXP(x) returns e to the x power.
367 \item EXP2(x) returns 2 to the x power.
368 \item LOG(x) returns the natural logarithm of x.
369 \item LOG2(x) returns the base 2 log of x.
370 \item LOG10(x) returns the base 10 log of x.
371 \end{enumerate}
372
373 \subsection{Examples}
374
375 \begin{astlisting}
376 \begin{verbatim}
377  "One Thousand Five Hundred" =~ "(T[^ ]+)"
378    returns: Thousand
379
380  "One Thousand Five Hundred" =~ "T[^ ]+"
381    returns: 8
382
383  "One Thousand Five Hundred" : "T[^ ]+"
384    returns: 0
385
386  "8015551212" : "(...)"
387    returns: 801
388
389  "3075551212":"...(...)"
390    returns: 555
391
392  ! "One Thousand Five Hundred" =~ "T[^ ]+"
393    returns: 0 (because it applies to the string, which is non-null,
394                     which it turns to "0", and then looks for the pattern
395                     in the "0", and doesn't find it)
396
397  !( "One Thousand Five Hundred" : "T[^ ]+" )
398    returns: 1  (because the string doesn't start with a word starting
399                      with T, so the match evals to 0, and the ! operator
400                      inverts it to 1 ).
401
402  2 + 8 / 2
403    returns 6. (because of operator precedence; the division is done first, then the addition).
404
405  2+8/2
406    returns 6. Spaces aren't necessary.
407
408 (2+8)/2
409    returns 5, of course.
410
411 (3+8)/2
412    returns 5.5 now.
413
414 TRUNC((3+8)/2)
415    returns 5.
416
417 FLOOR(2.5)
418    returns 2
419
420 FLOOR(-2.5)
421    returns -3
422
423 CEIL(2.5)
424    returns 3.
425
426 CEIL(-2.5)
427    returns -2.
428
429 ROUND(2.5)
430    returns 3.
431
432 ROUND(3.5)
433    returns 4.
434
435 ROUND(-2.5)
436    returns -3
437
438 RINT(2.5)
439    returns 2.
440
441 RINT(3.5)
442    returns 4.
443
444 RINT(-2.5)
445    returns -2.
446
447 RINT(-3.5)
448    returns -4.
449
450 TRUNC(2.5)
451    returns 2.
452
453 TRUNC(3.5)
454    returns 3.
455
456 TRUNC(-3.5)
457    returns -3.
458 \end{verbatim}
459 \end{astlisting}
460
461 Of course, all of the above examples use constants, but would work the
462 same if any of the numeric or string constants were replaced with a
463 variable reference \$\{CALLERID(num)\}, for instance.
464
465
466 \subsection{Numbers Vs. Strings}
467
468 Tokens consisting only of numbers are converted to 'long double' if possible, which
469 are from 80 bits to 128 bits depending on the OS, compiler, and hardware.
470 This means that overflows can occur when the
471 numbers get above 18 digits (depending on the number of bits involved).  Warnings will appear in the logs in this
472 case.
473
474 \subsection{Conditionals}
475
476 There is one conditional application - the conditional goto :
477 \begin{astlisting}
478 \begin{verbatim}
479   exten => 1,2,GotoIf(condition?label1:label2)
480 \end{verbatim}
481 \end{astlisting}
482
483 If condition is true go to label1, else go to label2. Labels are interpreted
484 exactly as in the normal goto command.
485
486 "condition" is just a string. If the string is empty or "0", the condition
487 is considered to be false, if it's anything else, the condition is true.
488 This is designed to be used together with the expression syntax described
489 above, eg :
490
491 \begin{astlisting}
492 \begin{verbatim}
493   exten => 1,2,GotoIf($[${CALLERID(all)} = 123456]?2,1:3,1)
494 \end{verbatim}
495 \end{astlisting}
496
497 Example of use :
498 \begin{astlisting}
499 \begin{verbatim}
500 exten => s,2,Set(vara=1)
501 exten => s,3,Set(varb=$[${vara} + 2])
502 exten => s,4,Set(varc=$[${varb} * 2])
503 exten => s,5,GotoIf($[${varc} = 6]?99,1:s,6)
504 \end{verbatim}
505 \end{astlisting}
506
507 \subsection{Parse Errors}
508
509 Syntax errors are now output with 3 lines.
510
511 If the extensions.conf file contains a line like:
512
513 \begin{astlisting}
514 \begin{verbatim}
515 exten => s,6,GotoIf($[ "${CALLERID(num)}"  = "3071234567" & &  "${CALLERID(name)}" : "Privacy Manager" ]?callerid-liar,s,1:s,7)
516 \end{verbatim}
517 \end{astlisting}
518
519 You may see an error in \path{/var/log/asterisk/messages} like this:
520 \begin{astlisting}
521 \begin{verbatim}
522 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:
523 "3072312154"  = "3071234567" & & "Steves Extension" : "Privacy Manager"
524                ^
525 \end{verbatim}
526 \end{astlisting}
527
528 The log line tells you that a syntax error was encountered. It now
529 also tells you (in grand standard bison format) that it hit an "AND"
530 (\&) token unexpectedly, and that was hoping for for a MINUS (-), LP
531 (left parenthesis), or a plain token (a string or number).
532
533 The next line shows the evaluated expression, and the line after
534 that, the position of the parser in the expression when it became confused,
535 marked with the "\^" character.
536
537 \subsection{NULL Strings}
538 Testing to see if a string is null can be done in one of two different ways:
539 \begin{astlisting}
540 \begin{verbatim}
541   exten => _XX.,1,GotoIf($["${calledid}" != ""]?3)
542     or
543   exten => _XX.,1,GotoIf($[foo${calledid} != foo]?3)
544 \end{verbatim}
545 \end{astlisting}
546
547 The second example above is the way suggested by the WIKI. It will
548 work as long as there are no spaces in the evaluated value.
549
550 The first way should work in all cases, and indeed, might now
551 be the safest way to handle this situation.
552
553 \subsection{Warning}
554
555 If you need to do complicated things with strings, asterisk expressions
556 is most likely NOT the best way to go about it. AGI scripts are an
557 excellent option to this need, and make available the full power of
558 whatever language you desire, be it Perl, C, C++, Cobol, RPG, Java,
559 Snobol, PL/I, Scheme, Common Lisp, Shell scripts, Tcl, Forth, Modula,
560 Pascal, APL, assembler, etc.
561
562 \subsection{Incompatabilities}
563
564 The asterisk expression parser has undergone some evolution. It is hoped
565 that the changes will be viewed as positive.
566
567 The "original" expression parser had a simple, hand-written scanner,
568 and a simple bison grammar. This was upgraded to a more involved bison
569 grammar, and a hand-written scanner upgraded to allow extra spaces,
570 and to generate better error diagnostics. This upgrade required bison
571 1.85, and part of the user community felt the pain of having to
572 upgrade their bison version.
573
574 The next upgrade included new bison and flex input files, and the makefile
575 was upgraded to detect current version of both flex and bison, conditionally
576 compiling and linking the new files if the versions of flex and bison would
577 allow it.
578
579 If you have not touched your extensions.conf files in a year or so, the
580 above upgrades may cause you some heartburn in certain circumstances, as
581 several changes have been made, and these will affect asterisk's behavior on
582 legacy extension.conf constructs.  The changes have been engineered
583 to minimize these conflicts, but there are bound to be problems.
584
585 The following list gives some (and most likely, not all) of areas
586 of possible concern with "legacy" extension.conf files:
587
588 \begin{enumerate}
589 \item Tokens separated by space(s).
590    Previously, tokens were separated by spaces. Thus, ' 1 + 1 ' would evaluate
591    to the value '2', but '1+1' would evaluate to the string '1+1'. If this
592    behavior was depended on, then the expression evaluation will break. '1+1'
593    will now evaluate to '2', and something is not going to work right.
594    To keep such strings from being evaluated, simply wrap them in double
595    quotes: '  "1+1" '
596
597 \item The colon operator. In versions previous to double quoting, the
598    colon operator takes the right hand string, and using it as a
599    regex pattern, looks for it in the left hand string. It is given
600    an implicit \^ operator at the beginning, meaning the pattern
601    will match only at the beginning of the left hand string.
602    If the pattern or the matching string had double quotes around
603    them, these could get in the way of the pattern match. Now,
604    the wrapping double quotes are stripped from both the pattern
605    and the left hand string before applying the pattern. This
606    was done because it recognized that the new way of
607    scanning the expression doesn't use spaces to separate tokens,
608    and the average regex expression is full of operators that
609    the scanner will recognize as expression operators. Thus, unless
610    the pattern is wrapped in double quotes, there will be trouble.
611    For instance,      \$\{VAR1\} : (Who$|$What*)+
612    may have have worked before, but unless you wrap the pattern
613    in double quotes now, look out for trouble! This is better:
614          "\$\{VAR1\}" : "(Who$|$What*)+"
615    and should work as previous.
616
617 \item Variables and Double Quotes
618    Before these changes, if a variable's value contained one or more double
619    quotes, it was no reason for concern. It is now!
620
621 \item LE, GE, NE operators removed. The code supported these operators,
622    but they were not documented. The symbolic operators, $<$=, $>$=, and !=
623    should be used instead.
624
625 \item  Added the unary '-' operator. So you can 3+ -4 and get -1.
626
627 \item  Added the unary '!' operator, which is a logical complement.
628     Basically, if the string or number is null, empty, or '0',
629     a '1' is returned. Otherwise a '0' is returned.
630
631 \item  Added the '=~' operator, just in case someone is just looking for
632     match anywhere in the string. The only diff with the ':' is that
633     match doesn't have to be anchored to the beginning of the string.
634
635 \item  Added the conditional operator  'expr1 ? true\_expr : false\_expr'
636     First, all 3 exprs are evaluated, and if expr1 is false, the 'false\_expr'
637     is returned as the result. See above for details.
638
639 \item  Unary operators '-' and '!' were made right associative.
640 \end{enumerate}
641
642 \subsection{Debugging Hints}
643
644 There are two utilities you can build to help debug the \$[ ] in
645 your extensions.conf file.
646
647 The first, and most simplistic, is to issue the command:
648 \begin{astlisting}
649 \begin{verbatim}
650 make testexpr2
651 \end{verbatim}
652 \end{astlisting}
653 in the top level asterisk source directory. This will build a small
654 executable, that is able to take the first command line argument, and
655 run it thru the expression parser. No variable substitutions will be
656 performed. It might be safest to wrap the expression in single
657 quotes...
658 \begin{astlisting}
659 \begin{verbatim}
660 testexpr2 '2*2+2/2'
661 \end{verbatim}
662 \end{astlisting}
663 is an example.
664
665 And, in the utils directory, you can say:
666 \begin{astlisting}
667 \begin{verbatim}
668 make check_expr
669 \end{verbatim}
670 \end{astlisting}
671 and a small program will be built, that will check the file mentioned
672 in the first command line argument, for any expressions that might be
673 have problems when you move to flex-2.5.31.  It was originally
674 designed to help spot possible incompatibilities when moving from the
675 pre-2.5.31 world to the upgraded version of the lexer.
676
677 But one more capability has been added to check\_expr, that might make
678 it more generally useful. It now does a simple minded evaluation of
679 all variables, and then passes the \$[] exprs to the parser. If there
680 are any parse errors, they will be reported in the log file. You can
681 use check\_expr to do a quick sanity check of the expressions in your
682 extensions.conf file, to see if they pass a crude syntax check.
683
684 The "simple-minded" variable substitution replaces \$\{varname\} variable
685 references with '555'. You can override the 555 for variable values,
686 by entering in var=val arguments after the filename on the command
687 line.  So...
688 \begin{astlisting}
689 \begin{verbatim}
690  check_expr /etc/asterisk/extensions.conf CALLERID(num)=3075551212 DIALSTATUS=TORTURE EXTEN=121
691 \end{verbatim}
692 \end{astlisting}
693 will substitute any \$\{CALLERID(num)\} variable references with
694 3075551212, any \$\{DIALSTATUS\} variable references with 'TORTURE', and
695 any \$\{EXTEN\} references with '121'.  If there is any fancy stuff
696 going on in the reference, like \$\{EXTEN:2\}, then the override will
697 not work. Everything in the \$\{...\} has to match. So, to substitute
698 \$\{EXTEN:2\} references, you'd best say:
699 \begin{astlisting}
700 \begin{verbatim}
701  check_expr /etc/asterisk/extensions.conf CALLERID(num)=3075551212 DIALSTATUS=TORTURE EXTEN:2=121
702 \end{verbatim}
703 \end{astlisting}
704 on stdout, you will see something like:
705
706 \begin{astlisting}
707 \begin{verbatim}
708  OK -- $[ "${DIALSTATUS}"  = "TORTURE" | "${DIALSTATUS}" = "DONTCALL" ] at line 416
709 \end{verbatim}
710 \end{astlisting}
711
712 In the expr2\_log file that is generated, you will see:
713
714 \begin{astlisting}
715 \begin{verbatim}
716  line 416, evaluation of $[  "TORTURE"  = "TORTURE" | "TORTURE" = "DONTCALL"  ] result: 1
717 \end{verbatim}
718 \end{astlisting}
719
720 check\_expr is a very simplistic algorithm, and it is far from being
721 guaranteed to work in all cases, but it is hoped that it will be
722 useful.
723
724 \section{Asterisk standard channel variables}
725
726 There are a number of variables that are defined or read
727 by Asterisk. Here is a list of them. More information is
728 available in each application's help text. All these variables
729 are in UPPER CASE only.
730
731 Variables marked with a * are builtin functions and can't be set,
732 only read in the dialplan.  Writes to such variables are silently
733 ignored.
734
735 \begin{verbatim}
736 ${CDR(accountcode)}    * Account code (if specified)
737 ${BLINDTRANSFER}         The name of the channel on the other side of a blind transfer
738 ${BRIDGEPEER}            Bridged peer
739 ${BRIDGEPVTCALLID}       Bridged peer PVT call ID (SIP Call ID if a SIP call)
740 ${CALLERID(ani)}       * Caller ANI (PRI channels)
741 ${CALLERID(ani2)}      * ANI2 (Info digits) also called Originating line information or OLI
742 ${CALLERID(all)}       * Caller ID
743 ${CALLERID(dnid)}      * Dialed Number Identifier
744 ${CALLERID(name)}      * Caller ID Name only
745 ${CALLERID(num)}       * Caller ID Number only
746 ${CALLERID(rdnis)}     * Redirected Dial Number ID Service
747 ${CALLINGANI2}         * Caller ANI2 (PRI channels)
748 ${CALLINGPRES}         * Caller ID presentation for incoming calls (PRI channels)
749 ${CALLINGTNS}          * Transit Network Selector (PRI channels)
750 ${CALLINGTON}          * Caller Type of Number (PRI channels)
751 ${CHANNEL}             * Current channel name
752 ${CONTEXT}             * Current context
753 ${DATETIME}            * Current date time in the format: DDMMYYYY-HH:MM:SS
754                          (Deprecated; use ${STRFTIME(${EPOCH},,%d%m%Y-%H:%M:%S)})
755 ${DB_RESULT}             Result value of DB_EXISTS() dial plan function
756 ${EPOCH}               * Current unix style epoch
757 ${EXTEN}               * Current extension
758 ${ENV(VAR)}              Environmental variable VAR
759 ${GOTO_ON_BLINDXFR}      Transfer to the specified context/extension/priority
760                          after a blind transfer (use ^ characters in place of
761                          | to separate context/extension/priority when setting
762                          this variable from the dialplan)
763 ${HANGUPCAUSE}         * Asterisk cause of hangup (inbound/outbound)
764 ${HINT}                * Channel hints for this extension
765 ${HINTNAME}            * Suggested Caller*ID name for this extension
766 ${INVALID_EXTEN}         The invalid called extension (used in the "i" extension)
767 ${LANGUAGE}            * Current language (Deprecated; use ${LANGUAGE()})
768 ${LEN(VAR)}            * String length of VAR (integer)
769 ${PRIORITY}            * Current priority in the dialplan
770 ${PRIREDIRECTREASON}     Reason for redirect on PRI, if a call was directed
771 ${TIMESTAMP}           * Current date time in the format: YYYYMMDD-HHMMSS
772                          (Deprecated; use ${STRFTIME(${EPOCH},,%Y%m%d-%H%M%S)})
773 ${TRANSFER_CONTEXT}      Context for transferred calls
774 ${FORWARD_CONTEXT}       Context for forwarded calls
775 ${UNIQUEID}            * Current call unique identifier
776 ${SYSTEMNAME}          * value of the systemname option of asterisk.conf
777 \end{verbatim}
778
779 \subsection{Application return values}
780
781 Many applications return the result in a variable that you read to
782 get the result of the application. These status fields are unique
783 for each application.
784 For the various status values, see each application's help text.
785 \begin{verbatim}
786 ${AGISTATUS}         * agi()
787 ${AQMSTATUS}         * addqueuemember()
788 ${AVAILSTATUS}       * chanisavail()
789 ${CHECKGROUPSTATUS}  * checkgroup()
790 ${CHECKMD5STATUS}    * checkmd5()
791 ${CPLAYBACKSTATUS}   * controlplayback()
792 ${DIALSTATUS}        * dial()
793 ${DBGETSTATUS}       * dbget()
794 ${ENUMSTATUS}        * enumlookup()
795 ${HASVMSTATUS}       * hasnewvoicemail()
796 ${LOOKUPBLSTATUS}    * lookupblacklist()
797 ${OSPAUTHSTATUS}     * ospauth()
798 ${OSPLOOKUPSTATUS}   * osplookup()
799 ${OSPNEXTSTATUS}     * ospnext()
800 ${OSPFINISHSTATUS}   * ospfinish()
801 ${PARKEDAT}          * parkandannounce()
802 ${PLAYBACKSTATUS}    * playback()
803 ${PQMSTATUS}         * pausequeuemember()
804 ${PRIVACYMGRSTATUS}  * privacymanager()
805 ${QUEUESTATUS}       * queue()
806 ${RQMSTATUS}         * removequeuemember()
807 ${SENDIMAGESTATUS}   * sendimage()
808 ${SENDTEXTSTATUS}    * sendtext()
809 ${SENDURLSTATUS}     * sendurl()
810 ${SYSTEMSTATUS}      * system()
811 ${TRANSFERSTATUS}    * transfer()
812 ${TXTCIDNAMESTATUS}  * txtcidname()
813 ${UPQMSTATUS}        * unpausequeuemember()
814 ${VMSTATUS}          * voicmail()
815 ${VMBOXEXISTSSTATUS} * vmboxexists()
816 ${WAITSTATUS}        * waitforsilence()
817 \end{verbatim}
818
819 \subsection{Various application variables}
820 \begin{verbatim}
821 ${CURL}                 * Resulting page content for curl()
822 ${ENUM}                 * Result of application EnumLookup
823 ${EXITCONTEXT}            Context to exit to in IVR menu (app background())
824                           or in the RetryDial() application
825 ${MONITOR}              * Set to "TRUE" if the channel is/has been monitored (app monitor())
826 ${MONITOR_EXEC}           Application to execute after monitoring a call
827 ${MONITOR_EXEC_ARGS}      Arguments to application
828 ${MONITOR_FILENAME}       File for monitoring (recording) calls in queue
829 ${QUEUE_PRIO}             Queue priority
830 ${QUEUE_MAX_PENALTY}      Maximum member penalty allowed to answer caller
831 ${QUEUE_MIN_PENALTY}      Minimum member penalty allowed to answer caller
832 ${QUEUESTATUS}            Status of the call, one of:
833                           (TIMEOUT | FULL | JOINEMPTY | LEAVEEMPTY | JOINUNAVAIL | LEAVEUNAVAIL)
834 ${RECORDED_FILE}        * Recorded file in record()
835 ${TALK_DETECTED}        * Result from talkdetect()
836 ${TOUCH_MONITOR}          The filename base to use with Touch Monitor (auto record)
837 ${TOUCH_MONITOR_PREF}   * The prefix for automonitor recording filenames.
838 ${TOUCH_MONITOR_FORMAT}   The audio format to use with Touch Monitor (auto record)
839 ${TOUCH_MONITOR_OUTPUT} * Recorded file from Touch Monitor (auto record)
840 ${TXTCIDNAME}           * Result of application TXTCIDName
841 ${VPB_GETDTMF}            chan_vpb
842 \end{verbatim}
843
844 \subsection{The MeetMe Conference Bridge}
845 \begin{verbatim}
846 ${MEETME_RECORDINGFILE}      Name of file for recording a conference with
847                              the "r" option
848 ${MEETME_RECORDINGFORMAT}    Format of file to be recorded
849 ${MEETME_EXIT_CONTEXT}       Context for exit out of meetme meeting
850 ${MEETME_AGI_BACKGROUND}     AGI script for Meetme (zap only)
851 ${MEETMESECS}              * Number of seconds a user participated in a MeetMe conference
852 ${CONF_LIMIT_TIMEOUT_FILE}   File to play when time is up.  Used with the L() option.
853 ${CONF_LIMIT_WARNING_FILE}   File to play as warning if 'y' is defined.
854                              The default is to say the time remaining.  Used with the L() option.
855 \end{verbatim}
856
857 \subsection{The VoiceMail() application}
858 \begin{verbatim}
859 ${VM_CATEGORY}      Sets voicemail category
860 ${VM_NAME}        * Full name in voicemail
861 ${VM_DUR}         * Voicemail duration
862 ${VM_MSGNUM}      * Number of voicemail message in mailbox
863 ${VM_CALLERID}    * Voicemail Caller ID (Person leaving vm)
864 ${VM_CIDNAME}     * Voicemail Caller ID Name
865 ${VM_CIDNUM}      * Voicemail Caller ID Number
866 ${VM_DATE}        * Voicemail Date
867 ${VM_MESSAGEFILE} * Path to message left by caller
868 \end{verbatim}
869
870 \subsection{The VMAuthenticate() application}
871 \begin{verbatim}
872 ${AUTH_MAILBOX}   * Authenticated mailbox
873 ${AUTH_CONTEXT}   * Authenticated mailbox context
874 \end{verbatim}
875
876 \subsection{DUNDiLookup()}
877 \begin{verbatim}
878 ${DUNDTECH}       * The Technology of the result from a call to DUNDiLookup()
879 ${DUNDDEST}       * The Destination of the result from a call to DUNDiLookup()
880 \end{verbatim}
881
882 \subsection{chan\_zap}
883 \begin{verbatim}
884 ${ANI2}               * The ANI2 Code provided by the network on the incoming call.
885                         (ie, Code 29 identifies call as a Prison/Inmate Call)
886 ${CALLTYPE}           * Type of call (Speech, Digital, etc)
887 ${CALLEDTON}          * Type of number for incoming PRI extension
888                         i.e. 0=unknown, 1=international, 2=domestic, 3=net_specific,
889                         4=subscriber, 6=abbreviated, 7=reserved
890 ${CALLINGSUBADDR}     * Called PRI Subaddress
891 ${FAXEXTEN}           * The extension called before being redirected to "fax"
892 ${PRIREDIRECTREASON}  * Reason for redirect, if a call was directed
893 ${SMDI_VM_TYPE}       * When an call is received with an SMDI message, the 'type'
894                         of message 'b' or 'u'
895 \end{verbatim}
896
897 \subsection{chan\_sip}
898 \begin{verbatim}
899 ${SIPCALLID}         * SIP Call-ID: header verbatim (for logging or CDR matching)
900 ${SIPDOMAIN}         * SIP destination domain of an inbound call (if appropriate)
901 ${SIPUSERAGENT}      * SIP user agent (deprecated)
902 ${SIPURI}            * SIP uri
903 ${SIP_CODEC}           Set the SIP codec for a call
904 ${SIP_URI_OPTIONS}   * additional options to add to the URI for an outgoing call
905 ${RTPAUDIOQOS}         RTCP QoS report for the audio of this call
906 ${RTPVIDEOQOS}         RTCP QoS report for the video of this call
907 \end{verbatim}
908
909 \subsection{chan\_agent}
910 \begin{verbatim}
911 ${AGENTMAXLOGINTRIES}  Set the maximum number of failed logins
912 ${AGENTUPDATECDR}      Whether to update the CDR record with Agent channel data
913 ${AGENTGOODBYE}        Sound file to use for "Good Bye" when agent logs out
914 ${AGENTACKCALL}        Whether the agent should acknowledge the incoming call
915 ${AGENTAUTOLOGOFF}     Auto logging off for an agent
916 ${AGENTWRAPUPTIME}     Setting the time for wrapup between incoming calls
917 ${AGENTNUMBER}       * Agent number (username) set at login
918 ${AGENTSTATUS}       * Status of login ( fail | on | off )
919 ${AGENTEXTEN}        * Extension for logged in agent
920 \end{verbatim}
921
922
923 \subsection{The Dial() application}
924 \begin{verbatim}
925 ${DIALEDPEERNAME}     * Dialed peer name
926 ${DIALEDPEERNUMBER}   * Dialed peer number
927 ${DIALEDTIME}         * Time for the call (seconds)
928 ${ANSWEREDTIME}       * Time from dial to answer (seconds)
929 ${DIALSTATUS}         * Status of the call, one of:
930                         (CHANUNAVAIL | CONGESTION | BUSY | NOANSWER
931                         | ANSWER | CANCEL | DONTCALL | TORTURE)
932 ${DYNAMIC_FEATURES}   * The list of features (from the [applicationmap] section of
933                         features.conf) to activate during the call, with feature
934                         names separated by '#' characters
935 ${LIMIT_PLAYAUDIO_CALLER}  Soundfile for call limits
936 ${LIMIT_PLAYAUDIO_CALLEE}  Soundfile for call limits
937 ${LIMIT_WARNING_FILE}      Soundfile for call limits
938 ${LIMIT_TIMEOUT_FILE}      Soundfile for call limits
939 ${LIMIT_CONNECT_FILE}      Soundfile for call limits
940 ${OUTBOUND_GROUP}          Default groups for peer channels (as in SetGroup)
941                            * See "show application dial" for more information
942 \end{verbatim}
943
944 \subsection{The chanisavail() application}
945 \begin{verbatim}
946 ${AVAILCHAN}          * the name of the available channel if one was found
947 ${AVAILORIGCHAN}      * the canonical channel name that was used to create the channel
948 ${AVAILSTATUS}        * Status of requested channel
949 \end{verbatim}
950
951 \subsection{Dialplan Macros}
952 \begin{verbatim}
953 ${MACRO_EXTEN}        * The calling extensions
954 ${MACRO_CONTEXT}      * The calling context
955 ${MACRO_PRIORITY}     * The calling priority
956 ${MACRO_OFFSET}         Offset to add to priority at return from macro
957 \end{verbatim}
958
959 \subsection{The ChanSpy() application}
960 \begin{verbatim}
961 ${SPYGROUP}           * A ':' (colon) separated list of group names.
962                         (To be set on spied on channel and matched against the g(grp) option)
963 \end{verbatim}
964
965 \subsection{OSP}
966 \begin{verbatim}
967 ${OSPINHANDLE}          OSP handle of in_bound call
968 ${OSPINTIMELIMIT}       Duration limit for in_bound call
969 ${OSPOUTHANDLE}         OSP handle of out_bound call
970 ${OSPTECH}              OSP technology
971 ${OSPDEST}              OSP destination
972 ${OSPCALLING}           OSP calling number
973 ${OSPOUTTOKEN}          OSP token to use for out_bound call
974 ${OSPOUTTIMELIMIT}      Duration limit for out_bound call
975 ${OSPRESULTS}           Number of remained destinations
976 \end{verbatim}