Added multiple name listing. (Closes issue #10413)
[asterisk/asterisk.git] / apps / app_directory.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2005, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
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.
13  *
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.
17  */
18
19 /*! \file
20  *
21  * \brief Provide a directory of extensions
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * \ingroup applications
26  */
27  
28 #include "asterisk.h"
29
30 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
31
32 #include <ctype.h>
33
34 #include "asterisk/paths.h"     /* use ast_config_AST_SPOOL_DIR */
35 #include "asterisk/file.h"
36 #include "asterisk/pbx.h"
37 #include "asterisk/module.h"
38 #include "asterisk/say.h"
39 #include "asterisk/app.h"
40
41 #ifdef ODBC_STORAGE
42 #include <sys/mman.h>
43 #include "asterisk/res_odbc.h"
44
45 static char odbc_database[80] = "asterisk";
46 static char odbc_table[80] = "voicemessages";
47 static char vmfmts[80] = "wav";
48 #endif
49
50 static char *app = "Directory";
51
52 static char *synopsis = "Provide directory of voicemail extensions";
53 static char *descrip =
54 "  Directory(vm-context[,dial-context[,options]]): This application will present\n"
55 "the calling channel with a directory of extensions from which they can search\n"
56 "by name. The list of names and corresponding extensions is retrieved from the\n"
57 "voicemail configuration file, voicemail.conf.\n"
58 "  This application will immediately exit if one of the following DTMF digits are\n"
59 "received and the extension to jump to exists:\n"
60 "    0 - Jump to the 'o' extension, if it exists.\n"
61 "    * - Jump to the 'a' extension, if it exists.\n\n"
62 "  Parameters:\n"
63 "    vm-context   - This is the context within voicemail.conf to use for the\n"
64 "                   Directory.\n"
65 "    dial-context - This is the dialplan context to use when looking for an\n"
66 "                   extension that the user has selected, or when jumping to the\n"
67 "                   'o' or 'a' extension.\n\n"
68 "  Options:\n"
69 "    e - In addition to the name, also read the extension number to the\n"
70 "        caller before presenting dialing options.\n"
71 "    f - Allow the caller to enter the first name of a user in the directory\n"
72 "        instead of using the last name.\n"
73 "    m - Instead of reading each name sequentially and asking for confirmation,\n"
74 "        create a menu of up to 8 names.\n";
75
76 /* For simplicity, I'm keeping the format compatible with the voicemail config,
77    but i'm open to suggestions for isolating it */
78
79 #define VOICEMAIL_CONFIG "voicemail.conf"
80
81 /* How many digits to read in */
82 #define NUMDIGITS 3
83
84 enum {
85         OPT_LISTBYFIRSTNAME = (1 << 0),
86         OPT_SAYEXTENSION =    (1 << 1),
87         OPT_FROMVOICEMAIL =   (1 << 2),
88         OPT_SELECTFROMMENU =  (1 << 3),
89 } directory_option_flags;
90
91 struct items {
92         char exten[AST_MAX_EXTENSION + 1];
93         char name[AST_MAX_EXTENSION + 1];
94 };
95
96 AST_APP_OPTIONS(directory_app_options, {
97         AST_APP_OPTION('f', OPT_LISTBYFIRSTNAME),
98         AST_APP_OPTION('e', OPT_SAYEXTENSION),
99         AST_APP_OPTION('v', OPT_FROMVOICEMAIL),
100         AST_APP_OPTION('m', OPT_SELECTFROMMENU),
101 });
102
103 #ifdef ODBC_STORAGE
104 struct generic_prepare_struct {
105         const char *sql;
106         const char *param;
107 };
108
109 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
110 {
111         struct generic_prepare_struct *gps = data;
112         SQLHSTMT stmt;
113         int res;
114
115         res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
116         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
117                 ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
118                 return NULL;
119         }
120
121         res = SQLPrepare(stmt, (unsigned char *)gps->sql, SQL_NTS);
122         if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
123                 ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", (char *)gps->sql);
124                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
125                 return NULL;
126         }
127
128         if (!ast_strlen_zero(gps->param))
129                 SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->param), 0, (void *)gps->param, 0, NULL);
130
131         return stmt;
132 }
133
134 static void retrieve_file(char *dir)
135 {
136         int x = 0;
137         int res;
138         int fd=-1;
139         size_t fdlen = 0;
140         void *fdm = MAP_FAILED;
141         SQLHSTMT stmt;
142         char sql[256];
143         char fmt[80]="", empty[10] = "";
144         char *c;
145         SQLLEN colsize;
146         char full_fn[256];
147         struct odbc_obj *obj;
148         struct generic_prepare_struct gps = { .sql = sql, .param = dir };
149
150         obj = ast_odbc_request_obj(odbc_database, 1);
151         if (obj) {
152                 do {
153                         ast_copy_string(fmt, vmfmts, sizeof(fmt));
154                         c = strchr(fmt, '|');
155                         if (c)
156                                 *c = '\0';
157                         if (!strcasecmp(fmt, "wav49"))
158                                 strcpy(fmt, "WAV");
159                         snprintf(full_fn, sizeof(full_fn), "%s.%s", dir, fmt);
160                         snprintf(sql, sizeof(sql), "SELECT recording FROM %s WHERE dir=? AND msgnum=-1", odbc_table);
161                         stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
162
163                         if (!stmt) {
164                                 ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
165                                 break;
166                         }
167                         res = SQLFetch(stmt);
168                         if (res == SQL_NO_DATA) {
169                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
170                                 break;
171                         } else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
172                                 ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
173                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
174                                 break;
175                         }
176                         fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, AST_FILE_MODE);
177                         if (fd < 0) {
178                                 ast_log(LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
179                                 SQLFreeHandle(SQL_HANDLE_STMT, stmt);
180                                 break;
181                         }
182
183                         res = SQLGetData(stmt, 1, SQL_BINARY, empty, 0, &colsize);
184                         fdlen = colsize;
185                         if (fd > -1) {
186                                 char tmp[1]="";
187                                 lseek(fd, fdlen - 1, SEEK_SET);
188                                 if (write(fd, tmp, 1) != 1) {
189                                         close(fd);
190                                         fd = -1;
191                                         break;
192                                 }
193                                 if (fd > -1)
194                                         fdm = mmap(NULL, fdlen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
195                         }
196                         if (fdm != MAP_FAILED) {
197                                 memset(fdm, 0, fdlen);
198                                 res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, fdlen, &colsize);
199                                 if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
200                                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
201                                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
202                                         break;
203                                 }
204                         }
205                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
206                 } while (0);
207                 ast_odbc_release_obj(obj);
208         } else
209                 ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
210         if (fdm != MAP_FAILED)
211                 munmap(fdm, fdlen);
212         if (fd > -1)
213                 close(fd);
214         return;
215 }
216 #endif
217
218 static char *convert(const char *lastname)
219 {
220         char *tmp;
221         int lcount = 0;
222         tmp = ast_malloc(NUMDIGITS + 1);
223         if (tmp) {
224                 while((*lastname > 32) && lcount < NUMDIGITS) {
225                         switch(toupper(*lastname)) {
226                         case '1':
227                                 tmp[lcount++] = '1';
228                                 break;
229                         case '2':
230                         case 'A':
231                         case 'B':
232                         case 'C':
233                                 tmp[lcount++] = '2';
234                                 break;
235                         case '3':
236                         case 'D':
237                         case 'E':
238                         case 'F':
239                                 tmp[lcount++] = '3';
240                                 break;
241                         case '4':
242                         case 'G':
243                         case 'H':
244                         case 'I':
245                                 tmp[lcount++] = '4';
246                                 break;
247                         case '5':
248                         case 'J':
249                         case 'K':
250                         case 'L':
251                                 tmp[lcount++] = '5';
252                                 break;
253                         case '6':
254                         case 'M':
255                         case 'N':
256                         case 'O':
257                                 tmp[lcount++] = '6';
258                                 break;
259                         case '7':
260                         case 'P':
261                         case 'Q':
262                         case 'R':
263                         case 'S':
264                                 tmp[lcount++] = '7';
265                                 break;
266                         case '8':
267                         case 'T':
268                         case 'U':
269                         case 'V':
270                                 tmp[lcount++] = '8';
271                                 break;
272                         case '9':
273                         case 'W':
274                         case 'X':
275                         case 'Y':
276                         case 'Z':
277                                 tmp[lcount++] = '9';
278                                 break;
279                         }
280                         lastname++;
281                 }
282                 tmp[lcount] = '\0';
283         }
284         return tmp;
285 }
286
287 /* play name of mailbox owner.
288  * returns:  -1 for bad or missing extension
289  *           '1' for selected entry from directory
290  *           '*' for skipped entry from directory
291  */
292 static int play_mailbox_owner(struct ast_channel *chan, const char *context,
293                 const char *ext, const char *name, struct ast_flags *flags)
294 {
295         int res = 0;
296         char fn[256];
297
298         /* Check for the VoiceMail2 greeting first */
299         snprintf(fn, sizeof(fn), "%s/voicemail/%s/%s/greet",
300                 ast_config_AST_SPOOL_DIR, context, ext);
301 #ifdef ODBC_STORAGE
302         retrieve_file(fn);
303 #endif
304
305         if (ast_fileexists(fn, NULL, chan->language) <= 0) {
306                 /* no file, check for an old-style Voicemail greeting */
307                 snprintf(fn, sizeof(fn), "%s/vm/%s/greet",
308                         ast_config_AST_SPOOL_DIR, ext);
309         }
310 #ifdef ODBC_STORAGE
311         retrieve_file(fn);
312 #endif
313
314         if (ast_fileexists(fn, NULL, chan->language) > 0) {
315                 res = ast_stream_and_wait(chan, fn, AST_DIGIT_ANY);
316                 ast_stopstream(chan);
317                 /* If Option 'e' was specified, also read the extension number with the name */
318                 if (ast_test_flag(flags, OPT_SAYEXTENSION)) {
319                         ast_stream_and_wait(chan, "vm-extension", AST_DIGIT_ANY);
320                         res = ast_say_character_str(chan, ext, AST_DIGIT_ANY, chan->language);
321                 }
322         } else {
323                 res = ast_say_character_str(chan, S_OR(name, ext), AST_DIGIT_ANY, chan->language);
324                 if (!ast_strlen_zero(name) && ast_test_flag(flags, OPT_SAYEXTENSION)) {
325                         ast_stream_and_wait(chan, "vm-extension", AST_DIGIT_ANY);
326                         res = ast_say_character_str(chan, ext, AST_DIGIT_ANY, chan->language);
327                 }
328         }
329 #ifdef ODBC_STORAGE
330         ast_filedelete(fn, NULL);       
331 #endif
332
333         return res;
334 }
335
336 static int get_mailbox_response(struct ast_channel *chan, const char *context, const char *dialcontext, const char *ext, const char *name, struct ast_flags *flags)
337 {
338         int res = 0;
339         int loop = 3;
340
341         res = play_mailbox_owner(chan, context, ext, name, flags);
342         for (loop = 3 ; loop > 0; loop--) {
343                 if (!res)
344                         res = ast_stream_and_wait(chan, "dir-instr", AST_DIGIT_ANY);
345                 if (!res)
346                         res = ast_waitfordigit(chan, 3000);
347                 ast_stopstream(chan);
348         
349                 if (res < 0) /* User hungup, so jump out now */
350                         break;
351                 if (res == '1') {       /* Name selected */
352                         if (ast_test_flag(flags, OPT_FROMVOICEMAIL)) {
353                                 /* We still want to set the exten though */
354                                 ast_copy_string(chan->exten, ext, sizeof(chan->exten));
355                         } else {
356                                 if (ast_goto_if_exists(chan, dialcontext, ext, 1)) {
357                                         ast_log(LOG_WARNING,
358                                                 "Can't find extension '%s' in context '%s'.  "
359                                                 "Did you pass the wrong context to Directory?\n",
360                                                 ext, dialcontext);
361                                         res = -1;
362                                 }
363                         }
364                         break;
365                 }
366                 if (res == '*') /* Skip to next match in list */
367                         break;
368
369                 /* Not '1', or '*', so decrement number of tries */
370                 res = 0;
371         }
372
373         return(res);
374 }
375
376 static int select_item(struct ast_channel *chan, const struct items *items, int itemcount, const char *context, const char *dialcontext, struct ast_flags *flags)
377 {
378         int i, res = 0;
379         char buf[9];
380         for (i = 0; i < itemcount; i++) {
381                 snprintf(buf, sizeof(buf), "digits/%d", i + 1);
382                 /* Press <num> for <name>, [ extension <ext> ] */
383                 res = ast_streamfile(chan, "dir-multi1", chan->language) ||
384                         ast_waitstream(chan, AST_DIGIT_ANY) ||
385                         ast_streamfile(chan, buf, chan->language) ||
386                         ast_waitstream(chan, AST_DIGIT_ANY) ||
387                         ast_streamfile(chan, "dir-multi2", chan->language) ||
388                         ast_waitstream(chan, AST_DIGIT_ANY) ||
389                         play_mailbox_owner(chan, context, items[i].exten, items[i].name, flags) ||
390                         ast_waitstream(chan, AST_DIGIT_ANY) ||
391                         ast_waitfordigit(chan, 800);
392                 if (res)
393                         break;
394         }
395         /* Press "9" for more names. */
396         if (!res)
397                 res = ast_waitstream(chan, AST_DIGIT_ANY) ||
398                         (itemcount == 8 && ast_streamfile(chan, "dir-multi9", chan->language)) ||
399                         ast_waitstream(chan, AST_DIGIT_ANY) ||
400                         ast_waitfordigit(chan, 3000);
401
402         if (res && res > '0' && res < '9') {
403                 if (ast_test_flag(flags, OPT_FROMVOICEMAIL)) {
404                         /* We still want to set the exten */
405                         ast_copy_string(chan->exten, items[res - '0'].exten, sizeof(chan->exten));
406                 } else if (ast_goto_if_exists(chan, dialcontext, items[res - '1'].exten, 1)) {
407                         ast_log(LOG_WARNING,
408                                 "Can't find extension '%s' in context '%s'.  "
409                                 "Did you pass the wrong context to Directory?\n",
410                                 items[res - '0'].exten, dialcontext);
411                         res = -1;
412                 }
413         }
414         return res;
415 }
416
417 static struct ast_config *realtime_directory(char *context)
418 {
419         struct ast_config *cfg;
420         struct ast_config *rtdata;
421         struct ast_category *cat;
422         struct ast_variable *var;
423         char *mailbox;
424         const char *fullname;
425         const char *hidefromdir;
426         char tmp[100];
427         struct ast_flags config_flags = { 0 };
428
429         /* Load flat file config. */
430         cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags);
431
432         if (!cfg) {
433                 /* Loading config failed. */
434                 ast_log(LOG_WARNING, "Loading config failed.\n");
435                 return NULL;
436         }
437
438         /* Get realtime entries, categorized by their mailbox number
439            and present in the requested context */
440         rtdata = ast_load_realtime_multientry("voicemail", "mailbox LIKE", "%", "context", context, NULL);
441
442         /* if there are no results, just return the entries from the config file */
443         if (!rtdata)
444                 return cfg;
445
446         /* Does the context exist within the config file? If not, make one */
447         cat = ast_category_get(cfg, context);
448         if (!cat) {
449                 cat = ast_category_new(context, "", 99999);
450                 if (!cat) {
451                         ast_log(LOG_WARNING, "Out of memory\n");
452                         ast_config_destroy(cfg);
453                         return NULL;
454                 }
455                 ast_category_append(cfg, cat);
456         }
457
458         mailbox = NULL;
459         while ( (mailbox = ast_category_browse(rtdata, mailbox)) ) {
460                 fullname = ast_variable_retrieve(rtdata, mailbox, "fullname");
461                 hidefromdir = ast_variable_retrieve(rtdata, mailbox, "hidefromdir");
462                 snprintf(tmp, sizeof(tmp), "no-password,%s,hidefromdir=%s",
463                          fullname ? fullname : "",
464                          hidefromdir ? hidefromdir : "no");
465                 var = ast_variable_new(mailbox, tmp, "");
466                 if (var)
467                         ast_variable_append(cat, var);
468                 else
469                         ast_log(LOG_WARNING, "Out of memory adding mailbox '%s'\n", mailbox);
470         }
471         ast_config_destroy(rtdata);
472
473         return cfg;
474 }
475
476 static int do_directory(struct ast_channel *chan, struct ast_config *vmcfg, struct ast_config *ucfg, char *context, char *dialcontext, char digit, struct ast_flags *flags)
477 {
478         /* Read in the first three digits..  "digit" is the first digit, already read */
479         char ext[NUMDIGITS + 1], *cat;
480         char name[80] = "";
481         struct ast_variable *v;
482         int res;
483         int found=0;
484         int lastuserchoice = 0;
485         char *start, *conv, *stringp = NULL;
486         char *pos;
487         int breakout = 0;
488
489         if (ast_strlen_zero(context)) {
490                 ast_log(LOG_WARNING,
491                         "Directory must be called with an argument "
492                         "(context in which to interpret extensions)\n");
493                 return -1;
494         }
495         if (digit == '0') {
496                 if (!ast_goto_if_exists(chan, dialcontext, "o", 1) ||
497                     (!ast_strlen_zero(chan->macrocontext) &&
498                      !ast_goto_if_exists(chan, chan->macrocontext, "o", 1))) {
499                         return 0;
500                 } else {
501                         ast_log(LOG_WARNING, "Can't find extension 'o' in current context.  "
502                                 "Not Exiting the Directory!\n");
503                         res = 0;
504                 }
505         }       
506         if (digit == '*') {
507                 if (!ast_goto_if_exists(chan, dialcontext, "a", 1) ||
508                     (!ast_strlen_zero(chan->macrocontext) &&
509                      !ast_goto_if_exists(chan, chan->macrocontext, "a", 1))) {
510                         return 0;
511                 } else {
512                         ast_log(LOG_WARNING, "Can't find extension 'a' in current context.  "
513                                 "Not Exiting the Directory!\n");
514                         res = 0;
515                 }
516         }       
517         memset(ext, 0, sizeof(ext));
518         ext[0] = digit;
519         res = 0;
520         if (ast_readstring(chan, ext + 1, NUMDIGITS - 1, 3000, 3000, "#") < 0) res = -1;
521         if (!res) {
522                 if (ast_test_flag(flags, OPT_SELECTFROMMENU)) {
523                         char buf[AST_MAX_EXTENSION + 1], *bufptr, *fullname;
524                         struct items menuitems[8];
525                         int menucount = 0;
526                         for (v = ast_variable_browse(vmcfg, context); v; v = v->next) {
527                                 if (strcasestr(v->value, "hidefromdir=yes") == NULL) {
528                                         ast_copy_string(buf, v->value, sizeof(buf));
529                                         bufptr = buf;
530                                         /* password,Full Name,email,pager,options */
531                                         strsep(&bufptr, ",");
532                                         pos = strsep(&bufptr, ",");
533                                         fullname = pos;
534
535                                         if (ast_test_flag(flags, OPT_LISTBYFIRSTNAME) && strrchr(pos, ' '))
536                                                 pos = strrchr(pos, ' ') + 1;
537                                         conv = convert(pos);
538
539                                         if (conv && strcmp(conv, ext) == 0) {
540                                                 /* Match */
541                                                 found = 1;
542                                                 ast_copy_string(menuitems[menucount].name, fullname, sizeof(menuitems[0].name));
543                                                 ast_copy_string(menuitems[menucount].exten, v->name, sizeof(menuitems[0].exten));
544                                                 menucount++;
545                                         }
546
547                                         if (menucount == 8) {
548                                                 /* We have a full menu */
549                                                 res = select_item(chan, menuitems, menucount, context, dialcontext, flags);
550                                                 menucount = 0;
551                                                 if (res != '9' && res != 0) {
552                                                         if (res != -1)
553                                                                 lastuserchoice = res;
554                                                         break;
555                                                 }
556                                         }
557                                 }
558                         }
559
560                         if (menucount > 0) {
561                                 /* We have a partial menu left over */
562                                 res = select_item(chan, menuitems, menucount, context, dialcontext, flags);
563                                 if (res != '9') {
564                                         if (res != -1)
565                                                 lastuserchoice = res;
566                                 }
567                         }
568
569                         /* Make this flag conform to the old expected result */
570                         if (lastuserchoice > '1' && lastuserchoice < '9')
571                                 lastuserchoice = '1';
572                 } else {
573                         /* Search for all names which start with those digits */
574                         v = ast_variable_browse(vmcfg, context);
575                         while(v && !res) {
576                                 /* Find all candidate extensions */
577                                 while(v) {
578                                         /* Find a candidate extension */
579                                         start = ast_strdup(v->value);
580                                         if (start && !strcasestr(start, "hidefromdir=yes")) {
581                                                 stringp=start;
582                                                 strsep(&stringp, ",");
583                                                 pos = strsep(&stringp, ",");
584                                                 if (pos) {
585                                                         ast_copy_string(name, pos, sizeof(name));
586                                                         /* Grab the last name */
587                                                         if (!ast_test_flag(flags, OPT_LISTBYFIRSTNAME) && strrchr(pos,' '))
588                                                                 pos = strrchr(pos, ' ') + 1;
589                                                         conv = convert(pos);
590                                                         if (conv) {
591                                                                 if (!strncmp(conv, ext, strlen(ext))) {
592                                                                         /* Match! */
593                                                                         found++;
594                                                                         ast_free(conv);
595                                                                         ast_free(start);
596                                                                         break;
597                                                                 }
598                                                                 ast_free(conv);
599                                                         }
600                                                 }
601                                                 ast_free(start);
602                                         }
603                                         v = v->next;
604                                 }
605
606                                 if (v) {
607                                         /* We have a match -- play a greeting if they have it */
608                                         res = get_mailbox_response(chan, context, dialcontext, v->name, name, flags);
609                                         switch (res) {
610                                         case -1:
611                                                 /* user pressed '1' but extension does not exist, or
612                                                  * user hungup
613                                                  */
614                                                 lastuserchoice = 0;
615                                                 break;
616                                         case '1':
617                                                 /* user pressed '1' and extensions exists;
618                                                    get_mailbox_response will already have done
619                                                    a goto() on the channel
620                                                  */
621                                                 lastuserchoice = res;
622                                                 break;
623                                         case '*':
624                                                 /* user pressed '*' to skip something found */
625                                                 lastuserchoice = res;
626                                                 res = 0;
627                                                 break;
628                                         default:
629                                                 break;
630                                         }
631                                         v = v->next;
632                                 }
633                         }
634                 }
635
636                 if (!res && ucfg) {
637                         /* Search users.conf for all names which start with those digits */
638                         if (ast_test_flag(flags, OPT_SELECTFROMMENU)) {
639                                 char *fullname;
640                                 struct items menuitems[8];
641                                 int menucount = 0;
642                                 for (cat = ast_category_browse(ucfg, NULL); cat && !res ; cat = ast_category_browse(ucfg, cat)) {
643                                         const char *pos;
644                                         if (!strcasecmp(cat, "general"))
645                                                 continue;
646                                         if (!ast_true(ast_config_option(ucfg, cat, "hasdirectory")))
647                                                 continue;
648                                 
649                                         /* Find all candidate extensions */
650                                         if ((pos = ast_variable_retrieve(ucfg, cat, "fullname"))) {
651                                                 ast_copy_string(name, pos, sizeof(name));
652                                                 /* Grab the last name */
653                                                 if (!ast_test_flag(flags, OPT_LISTBYFIRSTNAME) && strrchr(pos,' '))
654                                                         pos = strrchr(pos, ' ') + 1;
655                                                 conv = convert(pos);
656                                                 if (conv && strcmp(conv, ext) == 0) {
657                                                         /* Match */
658                                                         found = 1;
659                                                         ast_copy_string(menuitems[menucount].name, fullname, sizeof(menuitems[0].name));
660                                                         ast_copy_string(menuitems[menucount].exten, v->name, sizeof(menuitems[0].exten));
661                                                         menucount++;
662
663                                                         if (menucount == 8) {
664                                                                 /* We have a full menu */
665                                                                 res = select_item(chan, menuitems, menucount, context, dialcontext, flags);
666                                                                 menucount = 0;
667                                                                 if (res != '9' && res != 0) {
668                                                                         if (res != -1)
669                                                                                 lastuserchoice = res;
670                                                                         break;
671                                                                 }
672                                                         }
673                                                 }
674                                         }
675                                 }
676                                 if (menucount > 0) {
677                                         /* We have a partial menu left over */
678                                         res = select_item(chan, menuitems, menucount, context, dialcontext, flags);
679                                         if (res != '9') {
680                                                 if (res != -1)
681                                                         lastuserchoice = res;
682                                         }
683                                 }
684
685                                 /* Make this flag conform to the old expected result */
686                                 if (lastuserchoice > '1' && lastuserchoice < '9')
687                                         lastuserchoice = '1';
688                         } else { /* !menu */
689                                 for (cat = ast_category_browse(ucfg, NULL); cat && !res ; cat = ast_category_browse(ucfg, cat)) {
690                                         const char *pos;
691                                         if (!strcasecmp(cat, "general"))
692                                                 continue;
693                                         if (!ast_true(ast_config_option(ucfg, cat, "hasdirectory")))
694                                                 continue;
695                                 
696                                         /* Find all candidate extensions */
697                                         if ((pos = ast_variable_retrieve(ucfg, cat, "fullname"))) {
698                                                 ast_copy_string(name, pos, sizeof(name));
699                                                 /* Grab the last name */
700                                                 if (ast_test_flag(flags, OPT_LISTBYFIRSTNAME) && strrchr(pos,' '))
701                                                         pos = strrchr(pos, ' ') + 1;
702                                                 conv = convert(pos);
703                                                 if (conv && strcmp(conv, ext) == 0) {
704                                                         /* Match! */
705                                                         found++;
706                                                         /* We have a match -- play a greeting if they have it */
707                                                         res = get_mailbox_response(chan, context, dialcontext, cat, name, flags);
708                                                 }
709                                                 switch (res) {
710                                                 case -1:
711                                                         /* user pressed '1' but extension does not exist, or
712                                                          * user hungup
713                                                          */
714                                                         lastuserchoice = 0;
715                                                         breakout = 1;
716                                                         break;
717                                                 case '1':
718                                                         /* user pressed '1' and extensions exists;
719                                                            play_mailbox_owner will already have done
720                                                            a goto() on the channel
721                                                          */
722                                                         lastuserchoice = res;
723                                                         breakout = 1;
724                                                         break;
725                                                 case '*':
726                                                         /* user pressed '*' to skip something found */
727                                                         lastuserchoice = res;
728                                                         breakout = 0;
729                                                         res = 0;
730                                                         break;
731                                                 default:
732                                                         breakout = 1;
733                                                         break;
734                                                 }
735                                                 ast_free(conv);
736                                                 if (breakout)
737                                                         break;
738                                         } else
739                                                 ast_free(conv);
740                                 }
741                         }
742                 }
743
744                 if (lastuserchoice != '1') {
745                         res = ast_streamfile(chan, found ? "dir-nomore" : "dir-nomatch", chan->language);
746                         if (!res)
747                                 res = 1;
748                         return res;
749                 }
750                 return 0;
751         }
752         return res;
753 }
754
755 static int directory_exec(struct ast_channel *chan, void *data)
756 {
757         int res = 0;
758         struct ast_config *cfg, *ucfg;
759         const char *dirintro;
760         char *parse, *opts[0];
761         struct ast_flags flags = { 0 };
762         struct ast_flags config_flags = { 0 };
763         AST_DECLARE_APP_ARGS(args,
764                 AST_APP_ARG(vmcontext);
765                 AST_APP_ARG(dialcontext);
766                 AST_APP_ARG(options);
767         );
768
769         if (ast_strlen_zero(data)) {
770                 ast_log(LOG_WARNING, "Directory requires an argument (context[,dialcontext])\n");
771                 return -1;
772         }
773
774         parse = ast_strdupa(data);
775
776         AST_STANDARD_APP_ARGS(args, parse);
777
778         if (args.options && ast_app_parse_options(directory_app_options, &flags, opts, args.options))
779                 return -1;
780
781         if (ast_strlen_zero(args.dialcontext))  
782                 args.dialcontext = args.vmcontext;
783
784         cfg = realtime_directory(args.vmcontext);
785         if (!cfg) {
786                 ast_log(LOG_ERROR, "Unable to read the configuration data!\n");
787                 return -1;
788         }
789         
790         ucfg = ast_config_load("users.conf", config_flags);
791
792         dirintro = ast_variable_retrieve(cfg, args.vmcontext, "directoryintro");
793         if (ast_strlen_zero(dirintro))
794                 dirintro = ast_variable_retrieve(cfg, "general", "directoryintro");
795         if (ast_strlen_zero(dirintro))
796                 dirintro = ast_test_flag(&flags, OPT_LISTBYFIRSTNAME) ? "dir-intro-fn" : "dir-intro";
797
798         if (chan->_state != AST_STATE_UP) 
799                 res = ast_answer(chan);
800
801         for (;;) {
802                 if (!res)
803                         res = ast_stream_and_wait(chan, dirintro, AST_DIGIT_ANY);
804                 ast_stopstream(chan);
805                 if (!res)
806                         res = ast_waitfordigit(chan, 5000);
807                 if (res > 0) {
808                         res = do_directory(chan, cfg, ucfg, args.vmcontext, args.dialcontext, res, &flags);
809                         if (res > 0) {
810                                 res = ast_waitstream(chan, AST_DIGIT_ANY);
811                                 ast_stopstream(chan);
812                                 if (res >= 0)
813                                         continue;
814                         }
815                 }
816                 break;
817         }
818         if (ucfg)
819                 ast_config_destroy(ucfg);
820         ast_config_destroy(cfg);
821         return res;
822 }
823
824 static int unload_module(void)
825 {
826         int res;
827         res = ast_unregister_application(app);
828         return res;
829 }
830
831 static int load_module(void)
832 {
833 #ifdef ODBC_STORAGE
834         struct ast_flags config_flags = { 0 };
835         struct ast_config *cfg = ast_config_load(VOICEMAIL_CONFIG, config_flags);
836         const char *tmp;
837
838         if (cfg) {
839                 if ((tmp = ast_variable_retrieve(cfg, "general", "odbcstorage"))) {
840                         ast_copy_string(odbc_database, tmp, sizeof(odbc_database));
841                 }
842                 if ((tmp = ast_variable_retrieve(cfg, "general", "odbctable"))) {
843                         ast_copy_string(odbc_table, tmp, sizeof(odbc_table));
844                 }
845                 if ((tmp = ast_variable_retrieve(cfg, "general", "format"))) {
846                         ast_copy_string(vmfmts, tmp, sizeof(vmfmts));
847                 }
848                 ast_config_destroy(cfg);
849         } else
850                 ast_log(LOG_WARNING, "Unable to load " VOICEMAIL_CONFIG " - ODBC defaults will be used\n");
851 #endif
852
853         return ast_register_application(app, directory_exec, synopsis, descrip);
854 }
855
856 AST_MODULE_INFO_STANDARD(ASTERISK_GPL_KEY, "Extension Directory");