Use the same delimited character as the FILTER function in FIELDQTY and CUT.
[asterisk/asterisk.git] / funcs / func_cut.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (c) 2003-2006 Tilghman Lesher.  All rights reserved.
5  *
6  * Tilghman Lesher <app_cut__v003@the-tilghman.com>
7  *
8  * This code is released by the author with no restrictions on usage.
9  *
10  * See http://www.asterisk.org for more information about
11  * the Asterisk project. Please do not directly contact
12  * any of the maintainers of this project for assistance;
13  * the project provides a web site, mailing lists and IRC
14  * channels for your use.
15  *
16  */
17
18 /*! \file
19  * 
20  * \brief CUT function
21  *
22  * \author Tilghman Lesher <app_cut__v003@the-tilghman.com>
23  *
24  * \ingroup functions
25  */
26
27 #include "asterisk.h"
28
29 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
30
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <unistd.h>
34 #include <string.h>
35
36 #include "asterisk/file.h"
37 #include "asterisk/logger.h"
38 #include "asterisk/options.h"
39 #include "asterisk/channel.h"
40 #include "asterisk/pbx.h"
41 #include "asterisk/module.h"
42 #include "asterisk/app.h"
43
44 /* Maximum length of any variable */
45 #define MAXRESULT       1024
46
47 struct sortable_keys {
48         char *key;
49         float value;
50 };
51
52 static int sort_subroutine(const void *arg1, const void *arg2)
53 {
54         const struct sortable_keys *one=arg1, *two=arg2;
55         if (one->value < two->value)
56                 return -1;
57         else if (one->value == two->value)
58                 return 0;
59         else
60                 return 1;
61 }
62
63 #define ERROR_NOARG     (-1)
64 #define ERROR_NOMEM     (-2)
65 #define ERROR_USAGE     (-3)
66
67 static int sort_internal(struct ast_channel *chan, char *data, char *buffer, size_t buflen)
68 {
69         char *strings, *ptrkey, *ptrvalue;
70         int count=1, count2, element_count=0;
71         struct sortable_keys *sortable_keys;
72
73         memset(buffer, 0, buflen);
74
75         if (!data)
76                 return ERROR_NOARG;
77
78         strings = ast_strdupa(data);
79
80         for (ptrkey = strings; *ptrkey; ptrkey++) {
81                 if (*ptrkey == ',')
82                         count++;
83         }
84
85         sortable_keys = alloca(count * sizeof(struct sortable_keys));
86
87         memset(sortable_keys, 0, count * sizeof(struct sortable_keys));
88
89         /* Parse each into a struct */
90         count2 = 0;
91         while ((ptrkey = strsep(&strings, ","))) {
92                 ptrvalue = index(ptrkey, ':');
93                 if (!ptrvalue) {
94                         count--;
95                         continue;
96                 }
97                 *ptrvalue++ = '\0';
98                 sortable_keys[count2].key = ptrkey;
99                 sscanf(ptrvalue, "%f", &sortable_keys[count2].value);
100                 count2++;
101         }
102
103         /* Sort the structs */
104         qsort(sortable_keys, count, sizeof(struct sortable_keys), sort_subroutine);
105
106         for (count2 = 0; count2 < count; count2++) {
107                 int blen = strlen(buffer);
108                 if (element_count++) {
109                         strncat(buffer + blen, ",", buflen - blen - 1);
110                         blen++;
111                 }
112                 strncat(buffer + blen, sortable_keys[count2].key, buflen - blen - 1);
113         }
114
115         return 0;
116 }
117
118 static int cut_internal(struct ast_channel *chan, char *data, char *buffer, size_t buflen)
119 {
120         char *parse;
121         size_t delim_consumed;
122         AST_DECLARE_APP_ARGS(args,
123                 AST_APP_ARG(varname);
124                 AST_APP_ARG(delimiter);
125                 AST_APP_ARG(field);
126         );
127
128         memset(buffer, 0, buflen); 
129         
130         parse = ast_strdupa(data);
131
132         AST_STANDARD_APP_ARGS(args, parse);
133
134         /* Check and parse arguments */
135         if (args.argc < 3) {
136                 return ERROR_NOARG;
137         } else {
138                 char d, ds[2] = "";
139                 char *tmp = alloca(strlen(args.varname) + 4);
140                 char varvalue[MAXRESULT], *tmp2=varvalue;
141
142                 if (tmp) {
143                         snprintf(tmp, strlen(args.varname) + 4, "${%s}", args.varname);
144                         memset(varvalue, 0, sizeof(varvalue));
145                 } else {
146                         return ERROR_NOMEM;
147                 }
148
149                 if (ast_get_encoded_char(args.delimiter, ds, &delim_consumed))
150                         return ERROR_NOARG;
151
152                 /* String form of the delimiter, for use with strsep(3) */
153                 d = *ds;
154
155                 pbx_substitute_variables_helper(chan, tmp, tmp2, MAXRESULT - 1);
156
157                 if (tmp2) {
158                         int curfieldnum = 1;
159                         while (tmp2 != NULL && args.field != NULL) {
160                                 char *nextgroup = strsep(&(args.field), "&");
161                                 int num1 = 0, num2 = MAXRESULT;
162                                 char trashchar;
163
164                                 if (sscanf(nextgroup, "%d-%d", &num1, &num2) == 2) {
165                                         /* range with both start and end */
166                                 } else if (sscanf(nextgroup, "-%d", &num2) == 1) {
167                                         /* range with end */
168                                         num1 = 0;
169                                 } else if ((sscanf(nextgroup, "%d%c", &num1, &trashchar) == 2) && (trashchar == '-')) {
170                                         /* range with start */
171                                         num2 = MAXRESULT;
172                                 } else if (sscanf(nextgroup, "%d", &num1) == 1) {
173                                         /* single number */
174                                         num2 = num1;
175                                 } else {
176                                         return ERROR_USAGE;
177                                 }
178
179                                 /* Get to start, if any */
180                                 if (num1 > 0) {
181                                         while (tmp2 != (char *)NULL + 1 && curfieldnum < num1) {
182                                                 tmp2 = index(tmp2, d) + 1;
183                                                 curfieldnum++;
184                                         }
185                                 }
186
187                                 /* Most frequent problem is the expectation of reordering fields */
188                                 if ((num1 > 0) && (curfieldnum > num1))
189                                         ast_log(LOG_WARNING, "We're already past the field you wanted?\n");
190
191                                 /* Re-null tmp2 if we added 1 to NULL */
192                                 if (tmp2 == (char *)NULL + 1)
193                                         tmp2 = NULL;
194
195                                 /* Output fields until we either run out of fields or num2 is reached */
196                                 while (tmp2 != NULL && curfieldnum <= num2) {
197                                         char *tmp3 = strsep(&tmp2, ds);
198                                         int curlen = strlen(buffer);
199
200                                         if (curlen)
201                                                 snprintf(buffer + curlen, buflen - curlen, "%c%s", d, tmp3);
202                                         else
203                                                 snprintf(buffer, buflen, "%s", tmp3);
204
205                                         curfieldnum++;
206                                 }
207                         }
208                 }
209         }
210         return 0;
211 }
212
213 static int acf_sort_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
214 {
215         int ret = -1;
216
217         switch (sort_internal(chan, data, buf, len)) {
218         case ERROR_NOARG:
219                 ast_log(LOG_ERROR, "SORT() requires an argument\n");
220                 break;
221         case ERROR_NOMEM:
222                 ast_log(LOG_ERROR, "Out of memory\n");
223                 break;
224         case 0:
225                 ret = 0;
226                 break;
227         default:
228                 ast_log(LOG_ERROR, "Unknown internal error\n");
229         }
230
231         return ret;
232 }
233
234 static int acf_cut_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
235 {
236         int ret = -1;
237
238         switch (cut_internal(chan, data, buf, len)) {
239         case ERROR_NOARG:
240                 ast_log(LOG_ERROR, "Syntax: CUT(<varname>,<char-delim>,<range-spec>) - missing argument!\n");
241                 break;
242         case ERROR_NOMEM:
243                 ast_log(LOG_ERROR, "Out of memory\n");
244                 break;
245         case ERROR_USAGE:
246                 ast_log(LOG_ERROR, "Usage: CUT(<varname>,<char-delim>,<range-spec>)\n");
247                 break;
248         case 0:
249                 ret = 0;
250                 break;
251         default:
252                 ast_log(LOG_ERROR, "Unknown internal error\n");
253         }
254
255         return ret;
256 }
257
258 struct ast_custom_function acf_sort = {
259         .name = "SORT",
260         .synopsis = "Sorts a list of key/vals into a list of keys, based upon the vals",
261         .syntax = "SORT(key1:val1[...][,keyN:valN])",
262         .desc =
263 "Takes a comma-separated list of keys and values, each separated by a colon, and returns a\n"
264 "comma-separated list of the keys, sorted by their values.  Values will be evaluated as\n"
265 "floating-point numbers.\n",
266         .read = acf_sort_exec,
267 };
268
269 struct ast_custom_function acf_cut = {
270         .name = "CUT",
271         .synopsis = "Slices and dices strings, based upon a named delimiter.",
272         .syntax = "CUT(<varname>,<char-delim>,<range-spec>)",
273         .desc =
274 "  varname    - variable you want cut\n"
275 "  char-delim - defaults to '-'\n"
276 "  range-spec - number of the field you want (1-based offset)\n"
277 "             may also be specified as a range (with -)\n"
278 "             or group of ranges and fields (with &)\n",
279         .read = acf_cut_exec,
280 };
281
282 static int unload_module(void)
283 {
284         int res = 0;
285
286         res |= ast_custom_function_unregister(&acf_cut);
287         res |= ast_custom_function_unregister(&acf_sort);
288
289         return res;
290 }
291
292 static int load_module(void)
293 {
294         int res = 0;
295
296         res |= ast_custom_function_register(&acf_cut);
297         res |= ast_custom_function_register(&acf_sort);
298
299         return res;
300 }
301
302 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Cut out information from a string");