bd88fc2e9b33c1265b720c2406ab628b6bce9514
[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 "asterisk/file.h"
32 #include "asterisk/channel.h"
33 #include "asterisk/pbx.h"
34 #include "asterisk/module.h"
35 #include "asterisk/app.h"
36
37 /*** DOCUMENTATION
38         <function name="SORT" language="en_US">
39                 <synopsis>
40                         Sorts a list of key/vals into a list of keys, based upon the vals.      
41                 </synopsis>
42                 <syntax>
43                         <parameter name="keyval" required="true" argsep=":">
44                                 <argument name="key1" required="true" />
45                                 <argument name="val1" required="true" />
46                         </parameter>
47                         <parameter name="keyvaln" multiple="true" argsep=":">
48                                 <argument name="key2" required="true" />
49                                 <argument name="val2" required="true" />
50                         </parameter>
51                 </syntax>
52                 <description>
53                         <para>Takes a comma-separated list of keys and values, each separated by a colon, and returns a
54                         comma-separated list of the keys, sorted by their values.  Values will be evaluated as
55                         floating-point numbers.</para>
56                 </description>
57         </function>
58         <function name="CUT" language="en_US">
59                 <synopsis>
60                         Slices and dices strings, based upon a named delimiter.         
61                 </synopsis>
62                 <syntax>
63                         <parameter name="varname" required="true">
64                                 <para>Variable you want cut</para>
65                         </parameter>
66                         <parameter name="char-delim" required="true">
67                                 <para>Delimiter, defaults to <literal>-</literal></para>
68                         </parameter>
69                         <parameter name="range-spec" required="true">
70                                 <para>Number of the field you want (1-based offset), may also be specified as a range (with <literal>-</literal>)
71                                 or group of ranges and fields (with <literal>&amp;</literal>)</para>
72                         </parameter>
73                 </syntax>
74                 <description>
75                         <para>Cut out information from a string (<replaceable>varname</replaceable>), based upon a named delimiter.</para>
76                 </description>  
77         </function>
78  ***/
79
80 struct sortable_keys {
81         char *key;
82         float value;
83 };
84
85 static int sort_subroutine(const void *arg1, const void *arg2)
86 {
87         const struct sortable_keys *one=arg1, *two=arg2;
88         if (one->value < two->value)
89                 return -1;
90         else if (one->value == two->value)
91                 return 0;
92         else
93                 return 1;
94 }
95
96 #define ERROR_NOARG     (-1)
97 #define ERROR_NOMEM     (-2)
98 #define ERROR_USAGE     (-3)
99
100 static int sort_internal(struct ast_channel *chan, char *data, char *buffer, size_t buflen)
101 {
102         char *strings, *ptrkey, *ptrvalue;
103         int count=1, count2, element_count=0;
104         struct sortable_keys *sortable_keys;
105
106         *buffer = '\0';
107
108         if (!data)
109                 return ERROR_NOARG;
110
111         strings = ast_strdupa(data);
112
113         for (ptrkey = strings; *ptrkey; ptrkey++) {
114                 if (*ptrkey == ',')
115                         count++;
116         }
117
118         sortable_keys = alloca(count * sizeof(struct sortable_keys));
119
120         memset(sortable_keys, 0, count * sizeof(struct sortable_keys));
121
122         /* Parse each into a struct */
123         count2 = 0;
124         while ((ptrkey = strsep(&strings, ","))) {
125                 ptrvalue = strchr(ptrkey, ':');
126                 if (!ptrvalue) {
127                         count--;
128                         continue;
129                 }
130                 *ptrvalue++ = '\0';
131                 sortable_keys[count2].key = ptrkey;
132                 sscanf(ptrvalue, "%f", &sortable_keys[count2].value);
133                 count2++;
134         }
135
136         /* Sort the structs */
137         qsort(sortable_keys, count, sizeof(struct sortable_keys), sort_subroutine);
138
139         for (count2 = 0; count2 < count; count2++) {
140                 int blen = strlen(buffer);
141                 if (element_count++) {
142                         strncat(buffer + blen, ",", buflen - blen - 1);
143                         blen++;
144                 }
145                 strncat(buffer + blen, sortable_keys[count2].key, buflen - blen - 1);
146         }
147
148         return 0;
149 }
150
151 static int cut_internal(struct ast_channel *chan, char *data, struct ast_str **buf, ssize_t buflen)
152 {
153         char *parse;
154         size_t delim_consumed;
155         AST_DECLARE_APP_ARGS(args,
156                 AST_APP_ARG(varname);
157                 AST_APP_ARG(delimiter);
158                 AST_APP_ARG(field);
159         );
160         struct ast_str *str = ast_str_create(16);
161
162         parse = ast_strdupa(data);
163
164         AST_STANDARD_APP_ARGS(args, parse);
165
166         /* Check and parse arguments */
167         if (args.argc < 3) {
168                 ast_free(str);
169                 return ERROR_NOARG;
170         } else {
171                 char ds[2] = "";
172                 char *tmp = alloca(strlen(args.varname) + 4);
173
174                 if (tmp) {
175                         snprintf(tmp, strlen(args.varname) + 4, "${%s}", args.varname);
176                 } else {
177                         ast_free(str);
178                         return ERROR_NOMEM;
179                 }
180
181                 if (ast_get_encoded_char(args.delimiter, ds, &delim_consumed))
182                         ast_copy_string(ds, "-", sizeof(ds));
183
184                 ast_str_substitute_variables(&str, 0, chan, tmp);
185
186                 if (ast_str_strlen(str)) {
187                         int curfieldnum = 1;
188                         char *tmp2 = ast_str_buffer(str);
189                         int firstfield = 1;
190                         while (tmp2 != NULL && args.field != NULL) {
191                                 char *nextgroup = strsep(&(args.field), "&");
192                                 int num1 = 0, num2 = INT_MAX;
193                                 char trashchar;
194
195                                 if (sscanf(nextgroup, "%d-%d", &num1, &num2) == 2) {
196                                         /* range with both start and end */
197                                 } else if (sscanf(nextgroup, "-%d", &num2) == 1) {
198                                         /* range with end */
199                                         num1 = 0;
200                                 } else if ((sscanf(nextgroup, "%d%c", &num1, &trashchar) == 2) && (trashchar == '-')) {
201                                         /* range with start */
202                                         num2 = INT_MAX;
203                                 } else if (sscanf(nextgroup, "%d", &num1) == 1) {
204                                         /* single number */
205                                         num2 = num1;
206                                 } else {
207                                         ast_free(str);
208                                         return ERROR_USAGE;
209                                 }
210
211                                 /* Get to start, if any */
212                                 if (num1 > 0) {
213                                         while (tmp2 != NULL && curfieldnum < num1) {
214                                                 tmp2 = strchr(tmp2 + 1, ds[0]);
215                                                 curfieldnum++;
216                                         }
217                                 }
218
219                                 /* Most frequent problem is the expectation of reordering fields */
220                                 if ((num1 > 0) && (curfieldnum > num1))
221                                         ast_log(LOG_WARNING, "We're already past the field you wanted?\n");
222
223                                 /* Output fields until we either run out of fields or num2 is reached */
224                                 while (tmp2 != NULL && curfieldnum <= num2) {
225                                         char *tmp3 = strsep(&tmp2, ds);
226                                         ast_str_append(buf, buflen, "%s%s", firstfield ? "" : ds, tmp3);
227                                         firstfield = 0;
228                                         curfieldnum++;
229                                 }
230                         }
231                 }
232         }
233         ast_free(str);
234         return 0;
235 }
236
237 static int acf_sort_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
238 {
239         int ret = -1;
240
241         switch (sort_internal(chan, data, buf, len)) {
242         case ERROR_NOARG:
243                 ast_log(LOG_ERROR, "SORT() requires an argument\n");
244                 break;
245         case ERROR_NOMEM:
246                 ast_log(LOG_ERROR, "Out of memory\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 static int acf_cut_exec(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
259 {
260         int ret = -1;
261         struct ast_str *str = ast_str_create(16);
262
263         switch (cut_internal(chan, data, &str, len)) {
264         case ERROR_NOARG:
265                 ast_log(LOG_ERROR, "Syntax: CUT(<varname>,<char-delim>,<range-spec>) - missing argument!\n");
266                 break;
267         case ERROR_NOMEM:
268                 ast_log(LOG_ERROR, "Out of memory\n");
269                 break;
270         case ERROR_USAGE:
271                 ast_log(LOG_ERROR, "Usage: CUT(<varname>,<char-delim>,<range-spec>)\n");
272                 break;
273         case 0:
274                 ret = 0;
275                 ast_copy_string(buf, ast_str_buffer(str), len);
276                 break;
277         default:
278                 ast_log(LOG_ERROR, "Unknown internal error\n");
279         }
280         ast_free(str);
281         return ret;
282 }
283
284 static int acf_cut_exec2(struct ast_channel *chan, const char *cmd, char *data, struct ast_str **buf, ssize_t len)
285 {
286         int ret = -1;
287
288         switch (cut_internal(chan, data, buf, len)) {
289         case ERROR_NOARG:
290                 ast_log(LOG_ERROR, "Syntax: CUT(<varname>,<char-delim>,<range-spec>) - missing argument!\n");
291                 break;
292         case ERROR_NOMEM:
293                 ast_log(LOG_ERROR, "Out of memory\n");
294                 break;
295         case ERROR_USAGE:
296                 ast_log(LOG_ERROR, "Usage: CUT(<varname>,<char-delim>,<range-spec>)\n");
297                 break;
298         case 0:
299                 ret = 0;
300                 break;
301         default:
302                 ast_log(LOG_ERROR, "Unknown internal error\n");
303         }
304
305         return ret;
306 }
307
308 static struct ast_custom_function acf_sort = {
309         .name = "SORT",
310         .read = acf_sort_exec,
311 };
312
313 static struct ast_custom_function acf_cut = {
314         .name = "CUT",
315         .read = acf_cut_exec,
316         .read2 = acf_cut_exec2,
317 };
318
319 static int unload_module(void)
320 {
321         int res = 0;
322
323         res |= ast_custom_function_unregister(&acf_cut);
324         res |= ast_custom_function_unregister(&acf_sort);
325
326         return res;
327 }
328
329 static int load_module(void)
330 {
331         int res = 0;
332
333         res |= ast_custom_function_register(&acf_cut);
334         res |= ast_custom_function_register(&acf_sort);
335
336         return res;
337 }
338
339 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Cut out information from a string");