appending one list to another should leave the first list empty, and not require...
[asterisk-bristuff.git] / funcs / func_strings.c
blob3c8ead803127288a144e701d087b645f7f9b97a0
1 /*
2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 2005-2006, Digium, Inc.
5 * Portions Copyright (C) 2005, Tilghman Lesher. All rights reserved.
6 * Portions Copyright (C) 2005, Anthony Minessale II
8 * See http://www.asterisk.org for more information about
9 * the Asterisk project. Please do not directly contact
10 * any of the maintainers of this project for assistance;
11 * the project provides a web site, mailing lists and IRC
12 * channels for your use.
14 * This program is free software, distributed under the terms of
15 * the GNU General Public License Version 2. See the LICENSE file
16 * at the top of the source tree.
19 /*! \file
21 * \brief String manipulation dialplan functions
23 * \author Tilghman Lesher
24 * \author Anothony Minessale II
27 #include "asterisk.h"
29 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31 #include <stdlib.h>
32 #include <stdio.h>
33 #include <string.h>
34 #include <sys/types.h>
35 #include <regex.h>
37 #include "asterisk/module.h"
38 #include "asterisk/options.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/logger.h"
42 #include "asterisk/utils.h"
43 #include "asterisk/app.h"
44 #include "asterisk/localtime.h"
46 static int function_fieldqty(struct ast_channel *chan, char *cmd,
47 char *parse, char *buf, size_t len)
49 char *varsubst, varval[8192] = "", *varval2 = varval;
50 int fieldcount = 0;
51 AST_DECLARE_APP_ARGS(args,
52 AST_APP_ARG(varname);
53 AST_APP_ARG(delim);
56 AST_STANDARD_APP_ARGS(args, parse);
57 if (args.delim) {
58 varsubst = alloca(strlen(args.varname) + 4);
60 sprintf(varsubst, "${%s}", args.varname);
61 pbx_substitute_variables_helper(chan, varsubst, varval, sizeof(varval) - 1);
62 if (ast_strlen_zero(varval2))
63 fieldcount = 0;
64 else {
65 while (strsep(&varval2, args.delim))
66 fieldcount++;
68 } else {
69 fieldcount = 1;
71 snprintf(buf, len, "%d", fieldcount);
73 return 0;
76 static struct ast_custom_function fieldqty_function = {
77 .name = "FIELDQTY",
78 .synopsis = "Count the fields, with an arbitrary delimiter",
79 .syntax = "FIELDQTY(<varname>|<delim>)",
80 .read = function_fieldqty,
83 static int filter(struct ast_channel *chan, char *cmd, char *parse, char *buf,
84 size_t len)
86 AST_DECLARE_APP_ARGS(args,
87 AST_APP_ARG(allowed);
88 AST_APP_ARG(string);
90 char *outbuf = buf;
92 AST_STANDARD_APP_ARGS(args, parse);
94 if (!args.string) {
95 ast_log(LOG_ERROR, "Usage: FILTER(<allowed-chars>|<string>)\n");
96 return -1;
99 for (; *(args.string) && (buf + len - 1 > outbuf); (args.string)++) {
100 if (strchr(args.allowed, *(args.string)))
101 *outbuf++ = *(args.string);
103 *outbuf = '\0';
105 return 0;
108 static struct ast_custom_function filter_function = {
109 .name = "FILTER",
110 .synopsis = "Filter the string to include only the allowed characters",
111 .syntax = "FILTER(<allowed-chars>|<string>)",
112 .read = filter,
115 static int regex(struct ast_channel *chan, char *cmd, char *parse, char *buf,
116 size_t len)
118 AST_DECLARE_APP_ARGS(args,
119 AST_APP_ARG(null);
120 AST_APP_ARG(reg);
121 AST_APP_ARG(str);
123 int errcode;
124 regex_t regexbuf;
126 buf[0] = '\0';
128 AST_NONSTANDARD_APP_ARGS(args, parse, '"');
130 if (args.argc != 3) {
131 ast_log(LOG_ERROR, "Unexpected arguments: should have been in the form '\"<regex>\" <string>'\n");
132 return -1;
134 if ((*args.str == ' ') || (*args.str == '\t'))
135 args.str++;
137 if (option_debug)
138 ast_log(LOG_DEBUG, "FUNCTION REGEX (%s)(%s)\n", args.reg, args.str);
140 if ((errcode = regcomp(&regexbuf, args.reg, REG_EXTENDED | REG_NOSUB))) {
141 regerror(errcode, &regexbuf, buf, len);
142 ast_log(LOG_WARNING, "Malformed input %s(%s): %s\n", cmd, parse, buf);
143 return -1;
146 strcpy(buf, regexec(&regexbuf, args.str, 0, NULL, 0) ? "0" : "1");
148 regfree(&regexbuf);
150 return 0;
153 static struct ast_custom_function regex_function = {
154 .name = "REGEX",
155 .synopsis = "Regular Expression",
156 .desc =
157 "Returns 1 if data matches regular expression, or 0 otherwise.\n"
158 "Please note that the space following the double quotes separating the regex from the data\n"
159 "is optional and if present, is skipped. If a space is desired at the beginning of the data,\n"
160 "then put two spaces there; the second will not be skipped.\n",
161 .syntax = "REGEX(\"<regular expression>\" <data>)",
162 .read = regex,
165 static int array(struct ast_channel *chan, char *cmd, char *var,
166 const char *value)
168 AST_DECLARE_APP_ARGS(arg1,
169 AST_APP_ARG(var)[100];
171 AST_DECLARE_APP_ARGS(arg2,
172 AST_APP_ARG(val)[100];
174 char *value2;
175 int i;
177 value2 = ast_strdupa(value);
178 if (!var || !value2)
179 return -1;
181 /* The functions this will generally be used with are SORT and ODBC_*, which
182 * both return comma-delimited lists. However, if somebody uses literal lists,
183 * their commas will be translated to vertical bars by the load, and I don't
184 * want them to be surprised by the result. Hence, we prefer commas as the
185 * delimiter, but we'll fall back to vertical bars if commas aren't found.
187 if (option_debug)
188 ast_log(LOG_DEBUG, "array (%s=%s)\n", var, value2);
189 if (strchr(var, ','))
190 AST_NONSTANDARD_APP_ARGS(arg1, var, ',');
191 else
192 AST_STANDARD_APP_ARGS(arg1, var);
194 if (strchr(value2, ','))
195 AST_NONSTANDARD_APP_ARGS(arg2, value2, ',');
196 else
197 AST_STANDARD_APP_ARGS(arg2, value2);
199 for (i = 0; i < arg1.argc; i++) {
200 if (option_debug)
201 ast_log(LOG_DEBUG, "array set value (%s=%s)\n", arg1.var[i],
202 arg2.val[i]);
203 if (i < arg2.argc) {
204 pbx_builtin_setvar_helper(chan, arg1.var[i], arg2.val[i]);
205 } else {
206 /* We could unset the variable, by passing a NULL, but due to
207 * pushvar semantics, that could create some undesired behavior. */
208 pbx_builtin_setvar_helper(chan, arg1.var[i], "");
212 return 0;
215 static struct ast_custom_function array_function = {
216 .name = "ARRAY",
217 .synopsis = "Allows setting multiple variables at once",
218 .syntax = "ARRAY(var1[|var2[...][|varN]])",
219 .write = array,
220 .desc =
221 "The comma-separated list passed as a value to which the function is set will\n"
222 "be interpreted as a set of values to which the comma-separated list of\n"
223 "variable names in the argument should be set.\n"
224 "Hence, Set(ARRAY(var1|var2)=1\\,2) will set var1 to 1 and var2 to 2\n"
225 "Note: remember to either backslash your commas in extensions.conf or quote the\n"
226 "entire argument, since Set can take multiple arguments itself.\n",
229 static int acf_sprintf(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
231 #define SPRINTF_FLAG 0
232 #define SPRINTF_WIDTH 1
233 #define SPRINTF_PRECISION 2
234 #define SPRINTF_LENGTH 3
235 #define SPRINTF_CONVERSION 4
236 int i, state = -1, argcount = 0;
237 char *formatstart = NULL, *bufptr = buf;
238 char formatbuf[256] = "";
239 int tmpi;
240 double tmpd;
241 AST_DECLARE_APP_ARGS(arg,
242 AST_APP_ARG(format);
243 AST_APP_ARG(var)[100];
246 AST_STANDARD_APP_ARGS(arg, data);
248 /* Scan the format, converting each argument into the requisite format type. */
249 for (i = 0; arg.format[i]; i++) {
250 switch (state) {
251 case SPRINTF_FLAG:
252 if (strchr("#0- +'I", arg.format[i]))
253 break;
254 state = SPRINTF_WIDTH;
255 case SPRINTF_WIDTH:
256 if (arg.format[i] >= '0' && arg.format[i] <= '9')
257 break;
259 /* Next character must be a period to go into a precision */
260 if (arg.format[i] == '.') {
261 state = SPRINTF_PRECISION;
262 } else {
263 state = SPRINTF_LENGTH;
264 i--;
266 break;
267 case SPRINTF_PRECISION:
268 if (arg.format[i] >= '0' && arg.format[i] <= '9')
269 break;
270 state = SPRINTF_LENGTH;
271 case SPRINTF_LENGTH:
272 if (strchr("hl", arg.format[i])) {
273 if (arg.format[i + 1] == arg.format[i])
274 i++;
275 state = SPRINTF_CONVERSION;
276 break;
277 } else if (strchr("Lqjzt", arg.format[i]))
278 state = SPRINTF_CONVERSION;
279 break;
280 state = SPRINTF_CONVERSION;
281 case SPRINTF_CONVERSION:
282 if (strchr("diouxXc", arg.format[i])) {
283 /* Integer */
285 /* Isolate this format alone */
286 ast_copy_string(formatbuf, formatstart, sizeof(formatbuf));
287 formatbuf[&arg.format[i] - formatstart + 1] = '\0';
289 /* Convert the argument into the required type */
290 if (sscanf(arg.var[argcount++], "%d", &tmpi) != 1) {
291 ast_log(LOG_ERROR, "Argument '%s' is not an integer number for format '%s'\n", arg.var[argcount - 1], formatbuf);
292 goto sprintf_fail;
295 /* Format the argument */
296 snprintf(bufptr, buf + len - bufptr, formatbuf, tmpi);
298 /* Update the position of the next parameter to print */
299 bufptr = strchr(buf, '\0');
300 } else if (strchr("eEfFgGaA", arg.format[i])) {
301 /* Double */
303 /* Isolate this format alone */
304 ast_copy_string(formatbuf, formatstart, sizeof(formatbuf));
305 formatbuf[&arg.format[i] - formatstart + 1] = '\0';
307 /* Convert the argument into the required type */
308 if (sscanf(arg.var[argcount++], "%lf", &tmpd) != 1) {
309 ast_log(LOG_ERROR, "Argument '%s' is not a floating point number for format '%s'\n", arg.var[argcount - 1], formatbuf);
310 goto sprintf_fail;
313 /* Format the argument */
314 snprintf(bufptr, buf + len - bufptr, formatbuf, tmpd);
316 /* Update the position of the next parameter to print */
317 bufptr = strchr(buf, '\0');
318 } else if (arg.format[i] == 's') {
319 /* String */
321 /* Isolate this format alone */
322 ast_copy_string(formatbuf, formatstart, sizeof(formatbuf));
323 formatbuf[&arg.format[i] - formatstart + 1] = '\0';
325 /* Format the argument */
326 snprintf(bufptr, buf + len - bufptr, formatbuf, arg.var[argcount++]);
328 /* Update the position of the next parameter to print */
329 bufptr = strchr(buf, '\0');
330 } else if (arg.format[i] == '%') {
331 /* Literal data to copy */
332 *bufptr++ = arg.format[i];
333 } else {
334 /* Not supported */
336 /* Isolate this format alone */
337 ast_copy_string(formatbuf, formatstart, sizeof(formatbuf));
338 formatbuf[&arg.format[i] - formatstart + 1] = '\0';
340 ast_log(LOG_ERROR, "Format type not supported: '%s' with argument '%s'\n", formatbuf, arg.var[argcount++]);
341 goto sprintf_fail;
343 state = -1;
344 break;
345 default:
346 if (arg.format[i] == '%') {
347 state = SPRINTF_FLAG;
348 formatstart = &arg.format[i];
349 break;
350 } else {
351 /* Literal data to copy */
352 *bufptr++ = arg.format[i];
356 return 0;
357 sprintf_fail:
358 return -1;
361 static struct ast_custom_function sprintf_function = {
362 .name = "SPRINTF",
363 .synopsis = "Format a variable according to a format string",
364 .syntax = "SPRINTF(<format>|<arg1>[|...<argN>])",
365 .read = acf_sprintf,
366 .desc =
367 "Parses the format string specified and returns a string matching that format.\n"
368 "Supports most options supported by sprintf(3). Returns a shortened string if\n"
369 "a format specifier is not recognized.\n",
372 static int quote(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
374 char *bufptr = buf, *dataptr = data;
375 *bufptr++ = '"';
376 for (; bufptr < buf + len - 1; dataptr++) {
377 if (*dataptr == '\\') {
378 *bufptr++ = '\\';
379 *bufptr++ = '\\';
380 } else if (*dataptr == '"') {
381 *bufptr++ = '\\';
382 *bufptr++ = '"';
383 } else if (*dataptr == '\0') {
384 break;
385 } else {
386 *bufptr++ = *dataptr;
389 *bufptr++ = '"';
390 *bufptr = '\0';
391 return 0;
394 static struct ast_custom_function quote_function = {
395 .name = "QUOTE",
396 .synopsis = "Quotes a given string, escaping embedded quotes as necessary",
397 .syntax = "QUOTE(<string>)",
398 .read = quote,
402 static int len(struct ast_channel *chan, char *cmd, char *data, char *buf,
403 size_t len)
405 int length = 0;
407 if (data)
408 length = strlen(data);
410 snprintf(buf, len, "%d", length);
412 return 0;
415 static struct ast_custom_function len_function = {
416 .name = "LEN",
417 .synopsis = "Returns the length of the argument given",
418 .syntax = "LEN(<string>)",
419 .read = len,
422 static int acf_strftime(struct ast_channel *chan, char *cmd, char *parse,
423 char *buf, size_t len)
425 AST_DECLARE_APP_ARGS(args,
426 AST_APP_ARG(epoch);
427 AST_APP_ARG(timezone);
428 AST_APP_ARG(format);
430 time_t epochi;
431 struct tm tm;
433 buf[0] = '\0';
435 AST_STANDARD_APP_ARGS(args, parse);
437 ast_get_time_t(args.epoch, &epochi, time(NULL), NULL);
438 ast_localtime(&epochi, &tm, args.timezone);
440 if (!args.format)
441 args.format = "%c";
443 if (!strftime(buf, len, args.format, &tm))
444 ast_log(LOG_WARNING, "C function strftime() output nothing?!!\n");
446 buf[len - 1] = '\0';
448 return 0;
451 static struct ast_custom_function strftime_function = {
452 .name = "STRFTIME",
453 .synopsis = "Returns the current date/time in a specified format.",
454 .syntax = "STRFTIME([<epoch>][|[timezone][|format]])",
455 .read = acf_strftime,
458 static int acf_strptime(struct ast_channel *chan, char *cmd, char *data,
459 char *buf, size_t len)
461 AST_DECLARE_APP_ARGS(args,
462 AST_APP_ARG(timestring);
463 AST_APP_ARG(timezone);
464 AST_APP_ARG(format);
466 struct tm time;
468 memset(&time, 0, sizeof(struct tm));
470 buf[0] = '\0';
472 if (!data) {
473 ast_log(LOG_ERROR,
474 "Asterisk function STRPTIME() requires an argument.\n");
475 return -1;
478 AST_STANDARD_APP_ARGS(args, data);
480 if (ast_strlen_zero(args.format)) {
481 ast_log(LOG_ERROR,
482 "No format supplied to STRPTIME(<timestring>|<timezone>|<format>)");
483 return -1;
486 if (!strptime(args.timestring, args.format, &time)) {
487 ast_log(LOG_WARNING, "C function strptime() output nothing?!!\n");
488 } else {
489 snprintf(buf, len, "%d", (int) ast_mktime(&time, args.timezone));
492 return 0;
495 static struct ast_custom_function strptime_function = {
496 .name = "STRPTIME",
497 .synopsis =
498 "Returns the epoch of the arbitrary date/time string structured as described in the format.",
499 .syntax = "STRPTIME(<datetime>|<timezone>|<format>)",
500 .desc =
501 "This is useful for converting a date into an EPOCH time, possibly to pass to\n"
502 "an application like SayUnixTime or to calculate the difference between two\n"
503 "date strings.\n"
504 "\n"
505 "Example:\n"
506 " ${STRPTIME(2006-03-01 07:30:35|America/Chicago|%Y-%m-%d %H:%M:%S)} returns 1141219835\n",
507 .read = acf_strptime,
510 static int function_eval(struct ast_channel *chan, char *cmd, char *data,
511 char *buf, size_t len)
513 memset(buf, 0, len);
515 if (ast_strlen_zero(data)) {
516 ast_log(LOG_WARNING, "EVAL requires an argument: EVAL(<string>)\n");
517 return -1;
520 pbx_substitute_variables_helper(chan, data, buf, len - 1);
522 return 0;
525 static struct ast_custom_function eval_function = {
526 .name = "EVAL",
527 .synopsis = "Evaluate stored variables.",
528 .syntax = "EVAL(<variable>)",
529 .desc = "Using EVAL basically causes a string to be evaluated twice.\n"
530 "When a variable or expression is in the dialplan, it will be\n"
531 "evaluated at runtime. However, if the result of the evaluation\n"
532 "is in fact a variable or expression, using EVAL will have it\n"
533 "evaluated a second time. For example, if the variable ${MYVAR}\n"
534 "contains \"${OTHERVAR}\", then the result of putting ${EVAL(${MYVAR})}\n"
535 "in the dialplan will be the contents of the variable, OTHERVAR.\n"
536 "Normally, by just putting ${MYVAR} in the dialplan, you would be\n"
537 "left with \"${OTHERVAR}\".\n",
538 .read = function_eval,
541 static int keypadhash(struct ast_channel *chan, char *cmd, char *data, char *buf, size_t len)
543 char *bufptr, *dataptr;
545 for (bufptr = buf, dataptr = data; bufptr < buf + len - 1; dataptr++) {
546 if (*dataptr == '1') {
547 *bufptr++ = '1';
548 } else if (strchr("AaBbCc2", *dataptr)) {
549 *bufptr++ = '2';
550 } else if (strchr("DdEeFf3", *dataptr)) {
551 *bufptr++ = '3';
552 } else if (strchr("GgHhIi4", *dataptr)) {
553 *bufptr++ = '4';
554 } else if (strchr("JjKkLl5", *dataptr)) {
555 *bufptr++ = '5';
556 } else if (strchr("MmNnOo6", *dataptr)) {
557 *bufptr++ = '6';
558 } else if (strchr("PpQqRrSs7", *dataptr)) {
559 *bufptr++ = '7';
560 } else if (strchr("TtUuVv8", *dataptr)) {
561 *bufptr++ = '8';
562 } else if (strchr("WwXxYyZz9", *dataptr)) {
563 *bufptr++ = '9';
564 } else if (*dataptr == '0') {
565 *bufptr++ = '0';
566 } else if (*dataptr == '\0') {
567 *bufptr++ = '\0';
568 break;
571 buf[len - 1] = '\0';
573 return 0;
576 static struct ast_custom_function keypadhash_function = {
577 .name = "KEYPADHASH",
578 .synopsis = "Hash the letters in the string into the equivalent keypad numbers.",
579 .syntax = "KEYPADHASH(<string>)",
580 .read = keypadhash,
581 .desc = "Example: ${KEYPADHASH(Les)} returns \"537\"\n",
584 static int unload_module(void)
586 int res = 0;
588 res |= ast_custom_function_unregister(&fieldqty_function);
589 res |= ast_custom_function_unregister(&filter_function);
590 res |= ast_custom_function_unregister(&regex_function);
591 res |= ast_custom_function_unregister(&array_function);
592 res |= ast_custom_function_unregister(&quote_function);
593 res |= ast_custom_function_unregister(&len_function);
594 res |= ast_custom_function_unregister(&strftime_function);
595 res |= ast_custom_function_unregister(&strptime_function);
596 res |= ast_custom_function_unregister(&eval_function);
597 res |= ast_custom_function_unregister(&keypadhash_function);
598 res |= ast_custom_function_unregister(&sprintf_function);
600 return res;
603 static int load_module(void)
605 int res = 0;
607 res |= ast_custom_function_register(&fieldqty_function);
608 res |= ast_custom_function_register(&filter_function);
609 res |= ast_custom_function_register(&regex_function);
610 res |= ast_custom_function_register(&array_function);
611 res |= ast_custom_function_register(&quote_function);
612 res |= ast_custom_function_register(&len_function);
613 res |= ast_custom_function_register(&strftime_function);
614 res |= ast_custom_function_register(&strptime_function);
615 res |= ast_custom_function_register(&eval_function);
616 res |= ast_custom_function_register(&keypadhash_function);
617 res |= ast_custom_function_register(&sprintf_function);
619 return res;
622 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "String handling dialplan functions");