Fri Jul 3 20:35:33 2009

Asterisk developer's documentation


app_voicemail.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2006, Digium, Inc.
00005  *
00006  * Mark Spencer <markster@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \brief Comedian Mail - Voicemail System
00022  *
00023  * \author Mark Spencer <markster@digium.com>
00024  * 
00025  * \par See also
00026  * \arg \ref Config_vm
00027  * \ingroup applications
00028  * \note This module requires res_adsi to load.
00029  */
00030 
00031 /*** MODULEINFO
00032    <depend>res_adsi</depend>
00033    <depend>res_smdi</depend>
00034  ***/
00035 
00036 /*** MAKEOPTS
00037 <category name="MENUSELECT_OPTS_app_voicemail" displayname="Voicemail Build Options" positive_output="yes" remove_on_change="apps/app_voicemail.o apps/app_directory.o">
00038    <member name="ODBC_STORAGE" displayname="Storage of Voicemail using ODBC">
00039       <depend>unixodbc</depend>
00040       <depend>ltdl</depend>
00041       <conflict>IMAP_STORAGE</conflict>
00042       <defaultenabled>no</defaultenabled>
00043    </member>
00044    <member name="IMAP_STORAGE" displayname="Storage of Voicemail using IMAP4">
00045       <depend>imap_tk</depend>
00046       <conflict>ODBC_STORAGE</conflict>
00047       <use>ssl</use>
00048       <defaultenabled>no</defaultenabled>
00049    </member>
00050 </category>
00051  ***/
00052 
00053 #include "asterisk.h"
00054 
00055 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00056 
00057 #include <stdlib.h>
00058 #include <errno.h>
00059 #include <unistd.h>
00060 #include <string.h>
00061 #include <stdlib.h>
00062 #include <stdio.h>
00063 #include <sys/time.h>
00064 #include <sys/stat.h>
00065 #include <sys/types.h>
00066 #include <sys/mman.h>
00067 #include <time.h>
00068 #include <dirent.h>
00069 #ifdef IMAP_STORAGE
00070 #include <ctype.h>
00071 #include <signal.h>
00072 #include <pwd.h>
00073 #ifdef USE_SYSTEM_IMAP
00074 #include <imap/c-client.h>
00075 #include <imap/imap4r1.h>
00076 #include <imap/linkage.h>
00077 #elif defined (USE_SYSTEM_CCLIENT)
00078 #include <c-client/c-client.h>
00079 #include <c-client/imap4r1.h>
00080 #include <c-client/linkage.h>
00081 #else
00082 #include "c-client.h"
00083 #include "imap4r1.h"
00084 #include "linkage.h"
00085 #endif
00086 #endif
00087 #include "asterisk/lock.h"
00088 #include "asterisk/file.h"
00089 #include "asterisk/logger.h"
00090 #include "asterisk/channel.h"
00091 #include "asterisk/pbx.h"
00092 #include "asterisk/options.h"
00093 #include "asterisk/config.h"
00094 #include "asterisk/say.h"
00095 #include "asterisk/module.h"
00096 #include "asterisk/adsi.h"
00097 #include "asterisk/app.h"
00098 #include "asterisk/manager.h"
00099 #include "asterisk/dsp.h"
00100 #include "asterisk/localtime.h"
00101 #include "asterisk/cli.h"
00102 #include "asterisk/utils.h"
00103 #include "asterisk/stringfields.h"
00104 #include "asterisk/smdi.h"
00105 #ifdef ODBC_STORAGE
00106 #include "asterisk/res_odbc.h"
00107 #endif
00108 
00109 #ifdef IMAP_STORAGE
00110 AST_MUTEX_DEFINE_STATIC(imaptemp_lock);
00111 static char imaptemp[1024];
00112 static char imapserver[48];
00113 static char imapport[8];
00114 static char imapflags[128];
00115 static char imapfolder[64];
00116 static char authuser[32];
00117 static char authpassword[42];
00118 
00119 static int expungeonhangup = 1;
00120 static char delimiter = '\0';
00121 static const long DEFAULT_IMAP_TCP_TIMEOUT = 60L;
00122 
00123 struct vm_state;
00124 struct ast_vm_user;
00125 
00126 static int init_mailstream (struct vm_state *vms, int box);
00127 static void write_file (char *filename, char *buffer, unsigned long len);
00128 /*static void status (MAILSTREAM *stream); */ /* No need for this. */
00129 static char *get_header_by_tag(char *header, char *tag);
00130 static void vm_imap_delete(int msgnum, struct ast_vm_user *vmu);
00131 static char *get_user_by_mailbox(char *mailbox);
00132 static struct vm_state *get_vm_state_by_imapuser(char *user, int interactive);
00133 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive);
00134 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu);
00135 static void vmstate_insert(struct vm_state *vms);
00136 static void vmstate_delete(struct vm_state *vms);
00137 static void set_update(MAILSTREAM * stream);
00138 static void init_vm_state(struct vm_state *vms);
00139 static void copy_msgArray(struct vm_state *dst, struct vm_state *src);
00140 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format);
00141 static void get_mailbox_delimiter(MAILSTREAM *stream);
00142 static void mm_parsequota (MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota);
00143 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int target);
00144 static int imap_store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms);
00145 static void check_quota(struct vm_state *vms, char *mailbox);
00146 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu,int box);
00147 struct vmstate {
00148    struct vm_state *vms;
00149    struct vmstate *next;
00150 };
00151 AST_MUTEX_DEFINE_STATIC(vmstate_lock);
00152 static struct vmstate *vmstates = NULL;
00153 #endif
00154 
00155 #define SMDI_MWI_WAIT_TIMEOUT 1000 /* 1 second */
00156 
00157 #define COMMAND_TIMEOUT 5000
00158 /* Don't modify these here; set your umask at runtime instead */
00159 #define  VOICEMAIL_DIR_MODE   0777
00160 #define  VOICEMAIL_FILE_MODE  0666
00161 #define  CHUNKSIZE   65536
00162 
00163 #define VOICEMAIL_CONFIG "voicemail.conf"
00164 #define ASTERISK_USERNAME "asterisk"
00165 
00166 /* Default mail command to mail voicemail. Change it with the
00167     mailcmd= command in voicemail.conf */
00168 #define SENDMAIL "/usr/sbin/sendmail -t"
00169 
00170 #define INTRO "vm-intro"
00171 
00172 #define MAXMSG 100
00173 #ifndef IMAP_STORAGE
00174 #define MAXMSGLIMIT 9999
00175 #else
00176 #define MAXMSGLIMIT 255
00177 #endif
00178 
00179 #define BASEMAXINLINE 256
00180 #define BASELINELEN 72
00181 #define BASEMAXINLINE 256
00182 #define eol "\r\n"
00183 
00184 #define MAX_DATETIME_FORMAT   512
00185 #define MAX_NUM_CID_CONTEXTS 10
00186 
00187 #define VM_REVIEW        (1 << 0)
00188 #define VM_OPERATOR      (1 << 1)
00189 #define VM_SAYCID        (1 << 2)
00190 #define VM_SVMAIL        (1 << 3)
00191 #define VM_ENVELOPE      (1 << 4)
00192 #define VM_SAYDURATION   (1 << 5)
00193 #define VM_SKIPAFTERCMD  (1 << 6)
00194 #define VM_FORCENAME     (1 << 7)   /*!< Have new users record their name */
00195 #define VM_FORCEGREET    (1 << 8)   /*!< Have new users record their greetings */
00196 #define VM_PBXSKIP       (1 << 9)
00197 #define VM_DIRECFORWARD  (1 << 10)  /*!< directory_forward */
00198 #define VM_ATTACH        (1 << 11)
00199 #define VM_DELETE        (1 << 12)
00200 #define VM_ALLOCED       (1 << 13)
00201 #define VM_SEARCH        (1 << 14)
00202 #define VM_TEMPGREETWARN (1 << 15)  /*!< Remind user tempgreeting is set */
00203 #define ERROR_LOCK_PATH  -100
00204 #define ERROR_MAILBOX_FULL -200
00205 
00206 
00207 enum {
00208    OPT_SILENT =           (1 << 0),
00209    OPT_BUSY_GREETING =    (1 << 1),
00210    OPT_UNAVAIL_GREETING = (1 << 2),
00211    OPT_RECORDGAIN =       (1 << 3),
00212    OPT_PREPEND_MAILBOX =  (1 << 4),
00213    OPT_PRIORITY_JUMP =    (1 << 5),
00214    OPT_AUTOPLAY =         (1 << 6),
00215 } vm_option_flags;
00216 
00217 enum {
00218    OPT_ARG_RECORDGAIN = 0,
00219    OPT_ARG_PLAYFOLDER = 1,
00220    /* This *must* be the last value in this enum! */
00221    OPT_ARG_ARRAY_SIZE = 2,
00222 } vm_option_args;
00223 
00224 AST_APP_OPTIONS(vm_app_options, {
00225    AST_APP_OPTION('s', OPT_SILENT),
00226    AST_APP_OPTION('b', OPT_BUSY_GREETING),
00227    AST_APP_OPTION('u', OPT_UNAVAIL_GREETING),
00228    AST_APP_OPTION_ARG('g', OPT_RECORDGAIN, OPT_ARG_RECORDGAIN),
00229    AST_APP_OPTION('p', OPT_PREPEND_MAILBOX),
00230    AST_APP_OPTION('j', OPT_PRIORITY_JUMP),
00231    AST_APP_OPTION_ARG('a', OPT_AUTOPLAY, OPT_ARG_PLAYFOLDER),
00232 });
00233 
00234 static int load_config(void);
00235 
00236 /*! \page vmlang Voicemail Language Syntaxes Supported
00237 
00238    \par Syntaxes supported, not really language codes.
00239    \arg \b en - English
00240    \arg \b de - German
00241    \arg \b es - Spanish
00242    \arg \b fr - French
00243    \arg \b it = Italian
00244    \arg \b nl - Dutch
00245    \arg \b pt - Polish
00246    \arg \b pt - Portuguese
00247    \arg \b pt_BR - Portuguese (Brazil)
00248    \arg \b gr - Greek
00249    \arg \b no - Norwegian
00250    \arg \b se - Swedish
00251    \arg \b ua - Ukrainian
00252    \arg \b he - Hebrew
00253 
00254 German requires the following additional soundfile:
00255 \arg \b 1F  einE (feminine)
00256 
00257 Spanish requires the following additional soundfile:
00258 \arg \b 1M      un (masculine)
00259 
00260 Dutch, Portuguese & Spanish require the following additional soundfiles:
00261 \arg \b vm-INBOXs singular of 'new'
00262 \arg \b vm-Olds      singular of 'old/heard/read'
00263 
00264 NB these are plural:
00265 \arg \b vm-INBOX  nieuwe (nl)
00266 \arg \b vm-Old    oude (nl)
00267 
00268 Polish uses:
00269 \arg \b vm-new-a  'new', feminine singular accusative
00270 \arg \b vm-new-e  'new', feminine plural accusative
00271 \arg \b vm-new-ych   'new', feminine plural genitive
00272 \arg \b vm-old-a  'old', feminine singular accusative
00273 \arg \b vm-old-e  'old', feminine plural accusative
00274 \arg \b vm-old-ych   'old', feminine plural genitive
00275 \arg \b digits/1-a   'one', not always same as 'digits/1'
00276 \arg \b digits/2-ie  'two', not always same as 'digits/2'
00277 
00278 Swedish uses:
00279 \arg \b vm-nytt      singular of 'new'
00280 \arg \b vm-nya    plural of 'new'
00281 \arg \b vm-gammalt   singular of 'old'
00282 \arg \b vm-gamla  plural of 'old'
00283 \arg \b digits/ett   'one', not always same as 'digits/1'
00284 
00285 Norwegian uses:
00286 \arg \b vm-ny     singular of 'new'
00287 \arg \b vm-nye    plural of 'new'
00288 \arg \b vm-gammel singular of 'old'
00289 \arg \b vm-gamle  plural of 'old'
00290 
00291 Dutch also uses:
00292 \arg \b nl-om     'at'?
00293 
00294 Spanish also uses:
00295 \arg \b vm-youhaveno
00296 
00297 Ukrainian requires the following additional soundfile:
00298 \arg \b vm-nove      'nove'
00299 \arg \b vm-stare  'stare'
00300 \arg \b digits/ua/1e 'odne'
00301 
00302 Italian requires the following additional soundfile:
00303 
00304 For vm_intro_it:
00305 \arg \b vm-nuovo  new
00306 \arg \b vm-nuovi  new plural
00307 \arg \b vm-vecchio   old
00308 \arg \b vm-vecchi old plural
00309 
00310 Hebrew also uses:
00311 \arg \b vm-INBOX1 '1 new message'
00312 \arg \b vm-OLD1   '1 old message'
00313 \arg \b vm-shtei  'shtei'
00314 \arg \b vm-nomessages 'you have no new messages'
00315 
00316 \note Don't use vm-INBOX or vm-Old, because they are the name of the INBOX and Old folders,
00317 spelled among others when you have to change folder. For the above reasons, vm-INBOX
00318 and vm-Old are spelled plural, to make them sound more as folder name than an adjective.
00319 
00320 */
00321 
00322 struct baseio {
00323    int iocp;
00324    int iolen;
00325    int linelength;
00326    int ateof;
00327    unsigned char iobuf[BASEMAXINLINE];
00328 };
00329 
00330 /*! Structure for linked list of users */
00331 struct ast_vm_user {
00332    char context[AST_MAX_CONTEXT];   /*!< Voicemail context */
00333    char mailbox[AST_MAX_EXTENSION]; /*!< Mailbox id, unique within vm context */
00334    char password[80];               /*!< Secret pin code, numbers only */
00335    char fullname[80];               /*!< Full name, for directory app */
00336    char email[80];                  /*!< E-mail address */
00337    char pager[80];                  /*!< E-mail address to pager (no attachment) */
00338    char serveremail[80];            /*!< From: Mail address */
00339    char mailcmd[160];               /*!< Configurable mail command */
00340    char language[MAX_LANGUAGE];     /*!< Config: Language setting */
00341    char zonetag[80];                /*!< Time zone */
00342    char callback[80];
00343    char dialout[80];
00344    char uniqueid[80];               /*!< Unique integer identifier */
00345    char exit[80];
00346    char attachfmt[20];              /*!< Attachment format */
00347    unsigned int flags;              /*!< VM_ flags */ 
00348    int saydurationm;
00349    int maxmsg;                      /*!< Maximum number of msgs per folder for this mailbox */
00350 #ifdef IMAP_STORAGE
00351    char imapuser[80];   /* IMAP server login */
00352    char imappassword[80];  /* IMAP server password if authpassword not defined */
00353 #endif
00354    double volgain;      /*!< Volume gain for voicemails sent via email */
00355    AST_LIST_ENTRY(ast_vm_user) list;
00356 };
00357 
00358 struct vm_zone {
00359    AST_LIST_ENTRY(vm_zone) list;
00360    char name[80];
00361    char timezone[80];
00362    char msg_format[512];
00363 };
00364 
00365 struct vm_state {
00366    char curbox[80];
00367    char username[80];
00368    char context[80];
00369    char curdir[PATH_MAX];
00370    char vmbox[PATH_MAX];
00371    char fn[PATH_MAX];
00372    char fn2[PATH_MAX];
00373    int *deleted;
00374    int *heard;
00375    int curmsg;
00376    int lastmsg;
00377    int newmessages;
00378    int oldmessages;
00379    int starting;
00380    int repeats;
00381 #ifdef IMAP_STORAGE
00382    ast_mutex_t lock;
00383    int updated; /* decremented on each mail check until 1 -allows delay */
00384    long msgArray[256];
00385    MAILSTREAM *mailstream;
00386    int vmArrayIndex;
00387    char imapuser[80]; /* IMAP server login */
00388    int interactive;
00389    unsigned int quota_limit;
00390    unsigned int quota_usage;
00391    struct vm_state *persist_vms;
00392 #endif
00393 };
00394 static int advanced_options(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int msg, int option, signed char record_gain);
00395 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context);
00396 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime,
00397          char *fmt, int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
00398          signed char record_gain, struct vm_state *vms);
00399 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain);
00400 static int vm_play_folder_name(struct ast_channel *chan, char *mbox);
00401 static int notify_new_message(struct ast_channel *chan, struct ast_vm_user *vmu, int msgnum, long duration, char *fmt, char *cidnum, char *cidname);
00402 static void make_email_file(FILE *p, char *srcemail, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, char *attach, char *format, int duration, int attach_user_voicemail, struct ast_channel *chan, const char *category, int imap);
00403 #if !(defined(ODBC_STORAGE) || defined(IMAP_STORAGE))
00404 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit);
00405 #endif
00406 static void apply_options(struct ast_vm_user *vmu, const char *options);
00407 
00408 #ifdef ODBC_STORAGE
00409 static char odbc_database[80];
00410 static char odbc_table[80];
00411 #define RETRIEVE(a,b,c) retrieve_file(a,b)
00412 #define DISPOSE(a,b) remove_file(a,b)
00413 #define STORE(a,b,c,d,e,f,g,h,i) store_file(a,b,c,d)
00414 #define EXISTS(a,b,c,d) (message_exists(a,b))
00415 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(a,b,c,d,e,f))
00416 #define COPY(a,b,c,d,e,f,g,h) (copy_file(a,b,c,d,e,f))
00417 #define DELETE(a,b,c,d) (delete_file(a,b))
00418 #else
00419 #ifdef IMAP_STORAGE
00420 #define RETRIEVE(a,b,c) imap_retrieve_file(a,b,c)
00421 #define DISPOSE(a,b) remove_file(a,b)
00422 #define STORE(a,b,c,d,e,f,g,h,i) (imap_store_file(a,b,c,d,e,f,g,h,i))
00423 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
00424 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
00425 #define COPY(a,b,c,d,e,f,g,h) (copy_file(g,h));
00426 #define DELETE(a,b,c,d) (vm_imap_delete(b,d))
00427 #else
00428 #define RETRIEVE(a,b,c)
00429 #define DISPOSE(a,b)
00430 #define STORE(a,b,c,d,e,f,g,h,i)
00431 #define EXISTS(a,b,c,d) (ast_fileexists(c,NULL,d) > 0)
00432 #define RENAME(a,b,c,d,e,f,g,h) (rename_file(g,h));
00433 #define COPY(a,b,c,d,e,f,g,h) (copy_plain_file(g,h));
00434 #define DELETE(a,b,c,d) (vm_delete(c))
00435 #endif
00436 #endif
00437 
00438 static char VM_SPOOL_DIR[PATH_MAX];
00439 
00440 static char ext_pass_cmd[128];
00441 
00442 int my_umask;
00443 
00444 #if ODBC_STORAGE
00445 #define tdesc "Comedian Mail (Voicemail System) with ODBC Storage"
00446 #elif IMAP_STORAGE
00447 #define tdesc "Comedian Mail (Voicemail System) with IMAP Storage"
00448 #else
00449 #define tdesc "Comedian Mail (Voicemail System)"
00450 #endif
00451 
00452 static char userscontext[AST_MAX_EXTENSION] = "default";
00453 
00454 static char *addesc = "Comedian Mail";
00455 
00456 static char *synopsis_vm =
00457 "Leave a Voicemail message";
00458 
00459 static char *descrip_vm =
00460 "  VoiceMail(mailbox[@context][&mailbox[@context]][...][|options]): This\n"
00461 "application allows the calling party to leave a message for the specified\n"
00462 "list of mailboxes. When multiple mailboxes are specified, the greeting will\n"
00463 "be taken from the first mailbox specified. Dialplan execution will stop if the\n"
00464 "specified mailbox does not exist.\n"
00465 "  The Voicemail application will exit if any of the following DTMF digits are\n"
00466 "received:\n"
00467 "    0 - Jump to the 'o' extension in the current dialplan context.\n"
00468 "    * - Jump to the 'a' extension in the current dialplan context.\n"
00469 "  This application will set the following channel variable upon completion:\n"
00470 "    VMSTATUS - This indicates the status of the execution of the VoiceMail\n"
00471 "               application. The possible values are:\n"
00472 "               SUCCESS | USEREXIT | FAILED\n\n"
00473 "  Options:\n"
00474 "    b    - Play the 'busy' greeting to the calling party.\n"
00475 "    g(#) - Use the specified amount of gain when recording the voicemail\n"
00476 "           message. The units are whole-number decibels (dB).\n"
00477 "           Only works on supported technologies, which is Zap only.\n"
00478 "    s    - Skip the playback of instructions for leaving a message to the\n"
00479 "           calling party.\n"
00480 "    u    - Play the 'unavailable' greeting.\n"
00481 "    j    - Jump to priority n+101 if the mailbox is not found or some other\n"
00482 "           error occurs.\n";
00483 
00484 static char *synopsis_vmain =
00485 "Check Voicemail messages";
00486 
00487 static char *descrip_vmain =
00488 "  VoiceMailMain([mailbox][@context][|options]): This application allows the\n"
00489 "calling party to check voicemail messages. A specific mailbox, and optional\n"
00490 "corresponding context, may be specified. If a mailbox is not provided, the\n"
00491 "calling party will be prompted to enter one. If a context is not specified,\n"
00492 "the 'default' context will be used.\n\n"
00493 "  Options:\n"
00494 "    p    - Consider the mailbox parameter as a prefix to the mailbox that\n"
00495 "           is entered by the caller.\n"
00496 "    g(#) - Use the specified amount of gain when recording a voicemail\n"
00497 "           message. The units are whole-number decibels (dB).\n"
00498 "    s    - Skip checking the passcode for the mailbox.\n"
00499 "    a(#) - Skip folder prompt and go directly to folder specified.\n"
00500 "           Defaults to INBOX\n";
00501 
00502 static char *synopsis_vm_box_exists =
00503 "Check to see if Voicemail mailbox exists";
00504 
00505 static char *descrip_vm_box_exists =
00506 "  MailboxExists(mailbox[@context][|options]): Check to see if the specified\n"
00507 "mailbox exists. If no voicemail context is specified, the 'default' context\n"
00508 "will be used.\n"
00509 "  This application will set the following channel variable upon completion:\n"
00510 "    VMBOXEXISTSSTATUS - This will contain the status of the execution of the\n"
00511 "                        MailboxExists application. Possible values include:\n"
00512 "                        SUCCESS | FAILED\n\n"
00513 "  Options:\n"
00514 "    j - Jump to priority n+101 if the mailbox is found.\n";
00515 
00516 static char *synopsis_vmauthenticate =
00517 "Authenticate with Voicemail passwords";
00518 
00519 static char *descrip_vmauthenticate =
00520 "  VMAuthenticate([mailbox][@context][|options]): This application behaves the\n"
00521 "same way as the Authenticate application, but the passwords are taken from\n"
00522 "voicemail.conf.\n"
00523 "  If the mailbox is specified, only that mailbox's password will be considered\n"
00524 "valid. If the mailbox is not specified, the channel variable AUTH_MAILBOX will\n"
00525 "be set with the authenticated mailbox.\n\n"
00526 "  Options:\n"
00527 "    s - Skip playing the initial prompts.\n";
00528 
00529 /* Leave a message */
00530 static char *app = "VoiceMail";
00531 
00532 /* Check mail, control, etc */
00533 static char *app2 = "VoiceMailMain";
00534 
00535 static char *app3 = "MailboxExists";
00536 static char *app4 = "VMAuthenticate";
00537 
00538 static AST_LIST_HEAD_STATIC(users, ast_vm_user);
00539 static AST_LIST_HEAD_STATIC(zones, vm_zone);
00540 static char zonetag[80];
00541 static int maxsilence;
00542 static int maxmsg;
00543 static int silencethreshold = 128;
00544 static char serveremail[80];
00545 static char mailcmd[160];  /* Configurable mail cmd */
00546 static char externnotify[160]; 
00547 static struct ast_smdi_interface *smdi_iface = NULL;
00548 static char vmfmts[80];
00549 static double volgain;
00550 static int vmminmessage;
00551 static int vmmaxmessage;
00552 static int maxgreet;
00553 static int skipms;
00554 static int maxlogins;
00555 
00556 static struct ast_flags globalflags = {0};
00557 
00558 static int saydurationminfo;
00559 
00560 static char dialcontext[AST_MAX_CONTEXT];
00561 static char callcontext[AST_MAX_CONTEXT];
00562 static char exitcontext[AST_MAX_CONTEXT];
00563 
00564 static char cidinternalcontexts[MAX_NUM_CID_CONTEXTS][64];
00565 
00566 
00567 static char *emailbody = NULL;
00568 static char *emailsubject = NULL;
00569 static char *pagerbody = NULL;
00570 static char *pagersubject = NULL;
00571 static char fromstring[100];
00572 static char pagerfromstring[100];
00573 static char emailtitle[100];
00574 static char charset[32] = "ISO-8859-1";
00575 
00576 static unsigned char adsifdn[4] = "\x00\x00\x00\x0F";
00577 static unsigned char adsisec[4] = "\x9B\xDB\xF7\xAC";
00578 static int adsiver = 1;
00579 static char emaildateformat[32] = "%A, %B %d, %Y at %r";
00580 
00581 
00582 static char *strip_control(const char *input, char *buf, size_t buflen)
00583 {
00584    char *bufptr = buf;
00585    for (; *input; input++) {
00586       if (*input < 32) {
00587          continue;
00588       }
00589       *bufptr++ = *input;
00590       if (bufptr == buf + buflen - 1) {
00591          break;
00592       }
00593    }
00594    *bufptr = '\0';
00595    return buf;
00596 }
00597 
00598 static void populate_defaults(struct ast_vm_user *vmu)
00599 {
00600    ast_copy_flags(vmu, (&globalflags), AST_FLAGS_ALL);   
00601    if (saydurationminfo)
00602       vmu->saydurationm = saydurationminfo;
00603    ast_copy_string(vmu->callback, callcontext, sizeof(vmu->callback));
00604    ast_copy_string(vmu->dialout, dialcontext, sizeof(vmu->dialout));
00605    ast_copy_string(vmu->exit, exitcontext, sizeof(vmu->exit));
00606    ast_copy_string(vmu->zonetag, zonetag, sizeof(vmu->zonetag));
00607    if (maxmsg)
00608       vmu->maxmsg = maxmsg;
00609    vmu->volgain = volgain;
00610 }
00611 
00612 static void apply_option(struct ast_vm_user *vmu, const char *var, const char *value)
00613 {
00614    int x;
00615    if (!strcasecmp(var, "attach")) {
00616       ast_set2_flag(vmu, ast_true(value), VM_ATTACH);
00617    } else if (!strcasecmp(var, "attachfmt")) {
00618       ast_copy_string(vmu->attachfmt, value, sizeof(vmu->attachfmt));
00619    } else if (!strcasecmp(var, "serveremail")) {
00620       ast_copy_string(vmu->serveremail, value, sizeof(vmu->serveremail));
00621    } else if (!strcasecmp(var, "language")) {
00622       ast_copy_string(vmu->language, value, sizeof(vmu->language));
00623    } else if (!strcasecmp(var, "tz")) {
00624       ast_copy_string(vmu->zonetag, value, sizeof(vmu->zonetag));
00625 #ifdef IMAP_STORAGE
00626    } else if (!strcasecmp(var, "imapuser")) {
00627       ast_copy_string(vmu->imapuser, value, sizeof(vmu->imapuser));
00628    } else if (!strcasecmp(var, "imappassword") || !strcasecmp(var, "imapsecret")) {
00629       ast_copy_string(vmu->imappassword, value, sizeof(vmu->imappassword));
00630 #endif
00631    } else if (!strcasecmp(var, "delete") || !strcasecmp(var, "deletevoicemail")) {
00632       ast_set2_flag(vmu, ast_true(value), VM_DELETE); 
00633    } else if (!strcasecmp(var, "saycid")){
00634       ast_set2_flag(vmu, ast_true(value), VM_SAYCID); 
00635    } else if (!strcasecmp(var,"sendvoicemail")){
00636       ast_set2_flag(vmu, ast_true(value), VM_SVMAIL); 
00637    } else if (!strcasecmp(var, "review")){
00638       ast_set2_flag(vmu, ast_true(value), VM_REVIEW);
00639    } else if (!strcasecmp(var, "tempgreetwarn")){
00640       ast_set2_flag(vmu, ast_true(value), VM_TEMPGREETWARN);   
00641    } else if (!strcasecmp(var, "operator")){
00642       ast_set2_flag(vmu, ast_true(value), VM_OPERATOR);  
00643    } else if (!strcasecmp(var, "envelope")){
00644       ast_set2_flag(vmu, ast_true(value), VM_ENVELOPE);  
00645    } else if (!strcasecmp(var, "sayduration")){
00646       ast_set2_flag(vmu, ast_true(value), VM_SAYDURATION);  
00647    } else if (!strcasecmp(var, "saydurationm")){
00648       if (sscanf(value, "%d", &x) == 1) {
00649          vmu->saydurationm = x;
00650       } else {
00651          ast_log(LOG_WARNING, "Invalid min duration for say duration\n");
00652       }
00653    } else if (!strcasecmp(var, "forcename")){
00654       ast_set2_flag(vmu, ast_true(value), VM_FORCENAME); 
00655    } else if (!strcasecmp(var, "forcegreetings")){
00656       ast_set2_flag(vmu, ast_true(value), VM_FORCEGREET);   
00657    } else if (!strcasecmp(var, "callback")) {
00658       ast_copy_string(vmu->callback, value, sizeof(vmu->callback));
00659    } else if (!strcasecmp(var, "dialout")) {
00660       ast_copy_string(vmu->dialout, value, sizeof(vmu->dialout));
00661    } else if (!strcasecmp(var, "exitcontext")) {
00662       ast_copy_string(vmu->exit, value, sizeof(vmu->exit));
00663    } else if (!strcasecmp(var, "maxmsg")) {
00664       vmu->maxmsg = atoi(value);
00665       if (vmu->maxmsg <= 0) {
00666          ast_log(LOG_WARNING, "Invalid number of messages per folder maxmsg=%s. Using default value %i\n", value, MAXMSG);
00667          vmu->maxmsg = MAXMSG;
00668       } else if (vmu->maxmsg > MAXMSGLIMIT) {
00669          ast_log(LOG_WARNING, "Maximum number of messages per folder is %i. Cannot accept value maxmsg=%s\n", MAXMSGLIMIT, value);
00670          vmu->maxmsg = MAXMSGLIMIT;
00671       }
00672    } else if (!strcasecmp(var, "volgain")) {
00673       sscanf(value, "%lf", &vmu->volgain);
00674    } else if (!strcasecmp(var, "options")) {
00675       apply_options(vmu, value);
00676    }
00677 }
00678 
00679 static int change_password_realtime(struct ast_vm_user *vmu, const char *password)
00680 {
00681    int res;
00682    if (!ast_strlen_zero(vmu->uniqueid)) {
00683       res = ast_update_realtime("voicemail", "uniqueid", vmu->uniqueid, "password", password, NULL);
00684       if (res > 0) {
00685          ast_copy_string(vmu->password, password, sizeof(vmu->password));
00686          res = 0;
00687       } else if (!res) {
00688          res = -1;
00689       }
00690       return res;
00691    }
00692    return -1;
00693 }
00694 
00695 static void apply_options(struct ast_vm_user *vmu, const char *options)
00696 {  /* Destructively Parse options and apply */
00697    char *stringp;
00698    char *s;
00699    char *var, *value;
00700    stringp = ast_strdupa(options);
00701    while ((s = strsep(&stringp, "|"))) {
00702       value = s;
00703       if ((var = strsep(&value, "=")) && value) {
00704          apply_option(vmu, var, value);
00705       }
00706    }  
00707 }
00708 
00709 static void apply_options_full(struct ast_vm_user *retval, struct ast_variable *var)
00710 {
00711    struct ast_variable *tmp;
00712    tmp = var;
00713    while (tmp) {
00714       if (!strcasecmp(tmp->name, "vmsecret")) {
00715          ast_copy_string(retval->password, tmp->value, sizeof(retval->password));
00716       } else if (!strcasecmp(tmp->name, "secret") || !strcasecmp(tmp->name, "password")) { /* don't overwrite vmsecret if it exists */
00717          if (ast_strlen_zero(retval->password))
00718             ast_copy_string(retval->password, tmp->value, sizeof(retval->password));
00719       } else if (!strcasecmp(tmp->name, "uniqueid")) {
00720          ast_copy_string(retval->uniqueid, tmp->value, sizeof(retval->uniqueid));
00721       } else if (!strcasecmp(tmp->name, "pager")) {
00722          ast_copy_string(retval->pager, tmp->value, sizeof(retval->pager));
00723       } else if (!strcasecmp(tmp->name, "email")) {
00724          ast_copy_string(retval->email, tmp->value, sizeof(retval->email));
00725       } else if (!strcasecmp(tmp->name, "fullname")) {
00726          ast_copy_string(retval->fullname, tmp->value, sizeof(retval->fullname));
00727       } else if (!strcasecmp(tmp->name, "context")) {
00728          ast_copy_string(retval->context, tmp->value, sizeof(retval->context));
00729 #ifdef IMAP_STORAGE
00730       } else if (!strcasecmp(tmp->name, "imapuser")) {
00731          ast_copy_string(retval->imapuser, tmp->value, sizeof(retval->imapuser));
00732       } else if (!strcasecmp(tmp->name, "imappassword") || !strcasecmp(tmp->name, "imapsecret")) {
00733          ast_copy_string(retval->imappassword, tmp->value, sizeof(retval->imappassword));
00734 #endif
00735       } else
00736          apply_option(retval, tmp->name, tmp->value);
00737       tmp = tmp->next;
00738    } 
00739 }
00740 
00741 static struct ast_vm_user *find_user_realtime(struct ast_vm_user *ivm, const char *context, const char *mailbox)
00742 {
00743    struct ast_variable *var;
00744    struct ast_vm_user *retval;
00745 
00746    if ((retval = (ivm ? ivm : ast_calloc(1, sizeof(*retval))))) {
00747       if (!ivm)
00748          ast_set_flag(retval, VM_ALLOCED);   
00749       else
00750          memset(retval, 0, sizeof(*retval));
00751       if (mailbox) 
00752          ast_copy_string(retval->mailbox, mailbox, sizeof(retval->mailbox));
00753       populate_defaults(retval);
00754       if (!context && ast_test_flag((&globalflags), VM_SEARCH))
00755          var = ast_load_realtime("voicemail", "mailbox", mailbox, NULL);
00756       else
00757          var = ast_load_realtime("voicemail", "mailbox", mailbox, "context", context, NULL);
00758       if (var) {
00759          apply_options_full(retval, var);
00760          ast_variables_destroy(var);
00761       } else { 
00762          if (!ivm) 
00763             free(retval);
00764          retval = NULL;
00765       }  
00766    } 
00767    return retval;
00768 }
00769 
00770 static struct ast_vm_user *find_user(struct ast_vm_user *ivm, const char *context, const char *mailbox)
00771 {
00772    /* This function could be made to generate one from a database, too */
00773    struct ast_vm_user *vmu=NULL, *cur;
00774    AST_LIST_LOCK(&users);
00775 
00776    if (!context && !ast_test_flag((&globalflags), VM_SEARCH))
00777       context = "default";
00778 
00779    AST_LIST_TRAVERSE(&users, cur, list) {
00780       if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mailbox, cur->mailbox))
00781          break;
00782       if (context && (!strcasecmp(context, cur->context)) && (!strcasecmp(mailbox, cur->mailbox)))
00783          break;
00784    }
00785    if (cur) {
00786       /* Make a copy, so that on a reload, we have no race */
00787       if ((vmu = (ivm ? ivm : ast_malloc(sizeof(*vmu))))) {
00788          memcpy(vmu, cur, sizeof(*vmu));
00789          ast_set2_flag(vmu, !ivm, VM_ALLOCED);
00790          AST_LIST_NEXT(vmu, list) = NULL;
00791       }
00792    } else
00793       vmu = find_user_realtime(ivm, context, mailbox);
00794    AST_LIST_UNLOCK(&users);
00795    return vmu;
00796 }
00797 
00798 static int reset_user_pw(const char *context, const char *mailbox, const char *newpass)
00799 {
00800    /* This function could be made to generate one from a database, too */
00801    struct ast_vm_user *cur;
00802    int res = -1;
00803    AST_LIST_LOCK(&users);
00804    AST_LIST_TRAVERSE(&users, cur, list) {
00805       if ((!context || !strcasecmp(context, cur->context)) &&
00806          (!strcasecmp(mailbox, cur->mailbox)))
00807             break;
00808    }
00809    if (cur) {
00810       ast_copy_string(cur->password, newpass, sizeof(cur->password));
00811       res = 0;
00812    }
00813    AST_LIST_UNLOCK(&users);
00814    return res;
00815 }
00816 
00817 static void vm_change_password(struct ast_vm_user *vmu, const char *newpassword)
00818 {
00819    struct ast_config   *cfg=NULL;
00820    struct ast_variable *var=NULL;
00821    struct ast_category *cat=NULL;
00822    char *category=NULL, *value=NULL, *new=NULL;
00823    const char *tmp=NULL;
00824                
00825    if (!change_password_realtime(vmu, newpassword))
00826       return;
00827 
00828    /* check voicemail.conf */
00829    if ((cfg = ast_config_load_with_comments(VOICEMAIL_CONFIG))) {
00830       while ((category = ast_category_browse(cfg, category))) {
00831          if (!strcasecmp(category, vmu->context)) {
00832             tmp = ast_variable_retrieve(cfg, category, vmu->mailbox);
00833             if (!tmp) {
00834                ast_log(LOG_WARNING, "We could not find the mailbox.\n");
00835                break;
00836             }
00837             value = strstr(tmp,",");
00838             if (!value) {
00839                ast_log(LOG_WARNING, "variable has bad format.\n");
00840                break;
00841             }
00842             new = alloca((strlen(value)+strlen(newpassword)+1));
00843             sprintf(new,"%s%s", newpassword, value);
00844             if (!(cat = ast_category_get(cfg, category))) {
00845                ast_log(LOG_WARNING, "Failed to get category structure.\n");
00846                break;
00847             }
00848             ast_variable_update(cat, vmu->mailbox, new, NULL, 0);
00849          }
00850       }
00851       /* save the results */
00852       reset_user_pw(vmu->context, vmu->mailbox, newpassword);
00853       ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
00854       config_text_file_save(VOICEMAIL_CONFIG, cfg, "AppVoicemail");
00855    }
00856    category = NULL;
00857    var = NULL;
00858    /* check users.conf and update the password stored for the mailbox*/
00859    /* if no vmsecret entry exists create one. */
00860    if ((cfg = ast_config_load_with_comments("users.conf"))) {
00861       if (option_debug > 3)
00862          ast_log(LOG_DEBUG, "we are looking for %s\n", vmu->mailbox);
00863       while ((category = ast_category_browse(cfg, category))) {
00864          if (option_debug > 3)
00865             ast_log(LOG_DEBUG, "users.conf: %s\n", category);
00866          if (!strcasecmp(category, vmu->mailbox)) {
00867             if (!(tmp = ast_variable_retrieve(cfg, category, "vmsecret"))) {
00868                if (option_debug > 3)
00869                   ast_log(LOG_DEBUG, "looks like we need to make vmsecret!\n");
00870                var = ast_variable_new("vmsecret", newpassword);
00871             } 
00872             new = alloca(strlen(newpassword)+1);
00873             sprintf(new, "%s", newpassword);
00874             if (!(cat = ast_category_get(cfg, category))) {
00875                if (option_debug > 3)
00876                   ast_log(LOG_DEBUG, "failed to get category!\n");
00877                break;
00878             }
00879             if (!var)      
00880                ast_variable_update(cat, "vmsecret", new, NULL, 0);
00881             else
00882                ast_variable_append(cat, var);
00883          }
00884       }
00885       /* save the results and clean things up */
00886       reset_user_pw(vmu->context, vmu->mailbox, newpassword);  
00887       ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
00888       config_text_file_save("users.conf", cfg, "AppVoicemail");
00889    }
00890 }
00891 
00892 static void vm_change_password_shell(struct ast_vm_user *vmu, char *newpassword)
00893 {
00894    char buf[255];
00895    snprintf(buf,255,"%s %s %s %s",ext_pass_cmd,vmu->context,vmu->mailbox,newpassword);
00896    if (!ast_safe_system(buf)) {
00897       ast_copy_string(vmu->password, newpassword, sizeof(vmu->password));
00898       /* Reset the password in memory, too */
00899       reset_user_pw(vmu->context, vmu->mailbox, newpassword);
00900    }
00901 }
00902 
00903 static int make_dir(char *dest, int len, const char *context, const char *ext, const char *folder)
00904 {
00905    return snprintf(dest, len, "%s%s/%s/%s", VM_SPOOL_DIR, context, ext, folder);
00906 }
00907 
00908 static int make_file(char *dest, const int len, const char *dir, const int num)
00909 {
00910    return snprintf(dest, len, "%s/msg%04d", dir, num);
00911 }
00912 
00913 /* same as mkstemp, but return a FILE * */
00914 static FILE *vm_mkftemp(char *template)
00915 {
00916    FILE *p = NULL;
00917    int pfd = mkstemp(template);
00918    chmod(template, VOICEMAIL_FILE_MODE & ~my_umask);
00919    if (pfd > -1) {
00920       p = fdopen(pfd, "w+");
00921       if (!p) {
00922          close(pfd);
00923          pfd = -1;
00924       }
00925    }
00926    return p;
00927 }
00928 
00929 /*! \brief basically mkdir -p $dest/$context/$ext/$folder
00930  * \param dest    String. base directory.
00931  * \param len     Length of dest.
00932  * \param context String. Ignored if is null or empty string.
00933  * \param ext     String. Ignored if is null or empty string.
00934  * \param folder  String. Ignored if is null or empty string. 
00935  * \return -1 on failure, 0 on success.
00936  */
00937 static int create_dirpath(char *dest, int len, const char *context, const char *ext, const char *folder)
00938 {
00939    mode_t   mode = VOICEMAIL_DIR_MODE;
00940 
00941    if (!ast_strlen_zero(context)) {
00942       make_dir(dest, len, context, "", "");
00943       if (mkdir(dest, mode) && errno != EEXIST) {
00944          ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", dest, strerror(errno));
00945          return -1;
00946       }
00947    }
00948    if (!ast_strlen_zero(ext)) {
00949       make_dir(dest, len, context, ext, "");
00950       if (mkdir(dest, mode) && errno != EEXIST) {
00951          ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", dest, strerror(errno));
00952          return -1;
00953       }
00954    }
00955    if (!ast_strlen_zero(folder)) {
00956       make_dir(dest, len, context, ext, folder);
00957       if (mkdir(dest, mode) && errno != EEXIST) {
00958          ast_log(LOG_WARNING, "mkdir '%s' failed: %s\n", dest, strerror(errno));
00959          return -1;
00960       }
00961    }
00962    return 0;
00963 }
00964 
00965 static char *mbox(int id)
00966 {
00967    static char *msgs[] = {
00968       "INBOX",
00969       "Old",
00970       "Work",
00971       "Family",
00972       "Friends",
00973       "Cust1",
00974       "Cust2",
00975       "Cust3",
00976       "Cust4",
00977       "Cust5",
00978    };
00979    return (id >= 0 && id < (sizeof(msgs)/sizeof(msgs[0]))) ? msgs[id] : "tmp";
00980 }
00981 
00982 static void free_user(struct ast_vm_user *vmu)
00983 {
00984    if (ast_test_flag(vmu, VM_ALLOCED))
00985       free(vmu);
00986 }
00987 
00988 /* All IMAP-specific functions should go in this block. This
00989  * keeps them from being spread out all over the code */
00990 #ifdef IMAP_STORAGE
00991 static void vm_imap_delete(int msgnum, struct ast_vm_user *vmu)
00992 {
00993    char arg[10];
00994    struct vm_state *vms;
00995    unsigned long messageNum;
00996 
00997    /* Greetings aren't stored in IMAP, so we can't delete them there */
00998    if (msgnum < 0) {
00999       return;
01000    }
01001 
01002    if (!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
01003       ast_log(LOG_WARNING, "Couldn't find a vm_state for mailbox %s. Unable to set \\DELETED flag for message %d\n", vmu->mailbox, msgnum);
01004       return;
01005    }
01006 
01007    /* find real message number based on msgnum */
01008    /* this may be an index into vms->msgArray based on the msgnum. */
01009    messageNum = vms->msgArray[msgnum];
01010    if (messageNum == 0) {
01011       ast_log(LOG_WARNING, "msgnum %d, mailbox message %lu is zero.\n",msgnum,messageNum);
01012       return;
01013    }
01014    if (option_debug > 2)
01015       ast_log(LOG_DEBUG, "deleting msgnum %d, which is mailbox message %lu\n",msgnum,messageNum);
01016    /* delete message */
01017    snprintf (arg, sizeof(arg), "%lu",messageNum);
01018    mail_setflag (vms->mailstream,arg,"\\DELETED");
01019 }
01020 
01021 static int imap_retrieve_file(const char *dir, const int msgnum, const struct ast_vm_user *vmu)
01022 {
01023    BODY *body;
01024    char *header_content;
01025    char *attachedfilefmt;
01026    const char *cid_num;
01027    const char *cid_name;
01028    const char *duration;
01029    const char *context;
01030    const char *category;
01031    const char *origtime;
01032    struct vm_state *vms;
01033    char text_file[PATH_MAX];
01034    FILE *text_file_ptr;
01035 
01036    /* Greetings are not stored on the IMAP server, so we should not
01037     * attempt to retrieve them.
01038     */
01039    if (msgnum < 0) {
01040       return 0;
01041    }
01042    
01043    /* Before anything can happen, we need a vm_state so that we can
01044     * actually access the imap server through the vms->mailstream
01045     */
01046    if(!(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 1)) && !(vms = get_vm_state_by_mailbox(vmu->mailbox, vmu->context, 0))) {
01047       /* This should not happen. If it does, then I guess we'd
01048        * need to create the vm_state, extract which mailbox to
01049        * open, and then set up the msgArray so that the correct
01050        * IMAP message could be accessed. If I have seen correctly
01051        * though, the vms should be obtainable from the vmstates list
01052        * and should have its msgArray properly set up.
01053        */
01054       ast_log(LOG_ERROR, "Couldn't find a vm_state for mailbox %s!!! Oh no!\n", vmu->mailbox);
01055    }
01056    
01057    make_file(vms->fn, sizeof(vms->fn), dir, msgnum);
01058 
01059    /* Don't try to retrieve a message from IMAP if it already is on the file system */
01060    if (ast_fileexists(vms->fn, NULL, NULL) > 0) {
01061       return 0;
01062    }
01063 
01064    if (option_debug > 2)
01065       ast_log (LOG_DEBUG,"Before mail_fetchheaders, curmsg is: %d, imap messages is %lu\n", msgnum, vms->msgArray[msgnum]);
01066    if (vms->msgArray[msgnum] == 0) {
01067       ast_log (LOG_WARNING,"Trying to access unknown message\n");
01068       return -1;
01069    }
01070 
01071    /* This will only work for new messages... */
01072    header_content = mail_fetchheader (vms->mailstream, vms->msgArray[msgnum]);
01073    /* empty string means no valid header */
01074    if (ast_strlen_zero(header_content)) {
01075       ast_log (LOG_ERROR,"Could not fetch header for message number %ld\n",vms->msgArray[msgnum]);
01076       return -1;
01077    }
01078 
01079    mail_fetchstructure (vms->mailstream,vms->msgArray[msgnum],&body);
01080    
01081    /* We have the body, now we extract the file name of the first attachment. */
01082    if (body->nested.part && body->nested.part->next && body->nested.part->next->body.parameter->value) {
01083       attachedfilefmt = ast_strdupa(body->nested.part->next->body.parameter->value);
01084    } else {
01085       ast_log(LOG_ERROR, "There is no file attached to this IMAP message.\n");
01086       return -1;
01087    }
01088    
01089    /* Find the format of the attached file */
01090 
01091    strsep(&attachedfilefmt, ".");
01092    if (!attachedfilefmt) {
01093       ast_log(LOG_ERROR, "File format could not be obtained from IMAP message attachment\n");
01094       return -1;
01095    }
01096    
01097    save_body(body, vms, "2", attachedfilefmt);
01098 
01099    /* Get info from headers!! */
01100    snprintf(text_file, sizeof(text_file), "%s.%s", vms->fn, "txt");
01101 
01102    if (!(text_file_ptr = fopen(text_file, "w"))) {
01103       ast_log(LOG_WARNING, "Unable to open/create file %s: %s\n", text_file, strerror(errno));
01104    }
01105 
01106    fprintf(text_file_ptr, "%s\n", "[message]");
01107 
01108    cid_num = get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Num:");
01109    cid_name = get_header_by_tag(header_content, "X-Asterisk-VM-Caller-ID-Name:");
01110    fprintf(text_file_ptr, "callerid=\"%s\" <%s>\n", S_OR(cid_name, ""), S_OR(cid_num, ""));
01111    context = get_header_by_tag(header_content, "X-Asterisk-VM-Context:");
01112    fprintf(text_file_ptr, "context=%s\n", S_OR(context, ""));
01113    origtime = get_header_by_tag(header_content, "X-Asterisk-VM-Orig-time:");
01114    fprintf(text_file_ptr, "origtime=%s\n", S_OR(origtime, ""));
01115    duration = get_header_by_tag(header_content, "X-Asterisk-VM-Duration:");
01116    fprintf(text_file_ptr, "duration=%s\n", S_OR(origtime, ""));
01117    category = get_header_by_tag(header_content, "X-Asterisk-VM-Category:");
01118    fprintf(text_file_ptr, "category=%s\n", S_OR(category, ""));
01119    
01120    fclose(text_file_ptr);
01121    return 0;
01122 }
01123 
01124 static int folder_int(const char *folder)
01125 {
01126    /*assume a NULL folder means INBOX*/
01127    if (!folder)
01128       return 0;
01129    if (!strcasecmp(folder, "INBOX"))
01130       return 0;
01131    else if (!strcasecmp(folder, "Old"))
01132       return 1;
01133    else if (!strcasecmp(folder, "Work"))
01134       return 2;
01135    else if (!strcasecmp(folder, "Family"))
01136       return 3;
01137    else if (!strcasecmp(folder, "Friends"))
01138       return 4;
01139    else if (!strcasecmp(folder, "Cust1"))
01140       return 5;
01141    else if (!strcasecmp(folder, "Cust2"))
01142       return 6;
01143    else if (!strcasecmp(folder, "Cust3"))
01144       return 7;
01145    else if (!strcasecmp(folder, "Cust4"))
01146       return 8;
01147    else if (!strcasecmp(folder, "Cust5"))
01148       return 9;
01149    else /*assume they meant INBOX if folder is not found otherwise*/
01150       return 0;
01151 }
01152 
01153 static int messagecount(const char *context, const char *mailbox, const char *folder)
01154 {
01155    SEARCHPGM *pgm;
01156    SEARCHHEADER *hdr;
01157 
01158    struct ast_vm_user *vmu, vmus;
01159    struct vm_state *vms_p;
01160    int ret = 0;
01161    int fold = folder_int(folder);
01162    
01163    if (ast_strlen_zero(mailbox))
01164       return 0;
01165 
01166    /* We have to get the user before we can open the stream! */
01167    /* ast_log (LOG_DEBUG,"Before find_user, context is %s and mailbox is %s\n",context,mailbox); */
01168    vmu = find_user(&vmus, context, mailbox);
01169    if (!vmu) {
01170       ast_log (LOG_ERROR,"Couldn't find mailbox %s in context %s\n",mailbox,context);
01171       return -1;
01172    } else {
01173       /* No IMAP account available */
01174       if (vmu->imapuser[0] == '\0') {
01175          ast_log (LOG_WARNING,"IMAP user not set for mailbox %s\n",vmu->mailbox);
01176          return -1;
01177       }
01178    }
01179 
01180    /* check if someone is accessing this box right now... */
01181    vms_p = get_vm_state_by_imapuser(vmu->imapuser,1);
01182    if (!vms_p) {
01183       vms_p = get_vm_state_by_mailbox(mailbox, context, 1);
01184    }
01185    if (vms_p) {
01186       if (option_debug > 2)
01187          ast_log (LOG_DEBUG,"Returning before search - user is logged in\n");
01188       if (fold == 0) {/*INBOX*/
01189          return vms_p->newmessages;
01190       }
01191       if (fold == 1) {/*Old messages*/
01192          return vms_p->oldmessages;
01193       }
01194    }
01195 
01196    /* add one if not there... */
01197    vms_p = get_vm_state_by_imapuser(vmu->imapuser,0);
01198    if (!vms_p) {
01199       vms_p = get_vm_state_by_mailbox(mailbox, context, 0);
01200    }
01201 
01202    if (!vms_p) {
01203       if (!(vms_p = create_vm_state_from_user(vmu))) {
01204          ast_log(LOG_WARNING, "Unable to allocate space for new vm_state!\n");
01205          return -1;
01206       }
01207    }
01208    ret = init_mailstream(vms_p, fold);
01209    if (!vms_p->mailstream) {
01210       ast_log (LOG_ERROR,"IMAP mailstream is NULL\n");
01211       return -1;
01212    }
01213    if (ret == 0) {
01214       pgm = mail_newsearchpgm ();
01215       hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", (char *)mailbox);
01216       pgm->header = hdr;
01217       if (fold != 1) {
01218          pgm->unseen = 1;
01219          pgm->seen = 0;
01220       }
01221       /* In the special case where fold is 1 (old messages) we have to do things a bit
01222        * differently. Old messages are stored in the INBOX but are marked as "seen"
01223        */
01224       else {
01225          pgm->unseen = 0;
01226          pgm->seen = 1;
01227       }
01228       pgm->undeleted = 1;
01229       pgm->deleted = 0;
01230 
01231       vms_p->vmArrayIndex = 0;
01232       mail_search_full (vms_p->mailstream, NULL, pgm, NIL);
01233       if (fold == 0)
01234          vms_p->newmessages = vms_p->vmArrayIndex;
01235       if (fold == 1)
01236          vms_p->oldmessages = vms_p->vmArrayIndex;
01237       /*Freeing the searchpgm also frees the searchhdr*/
01238       mail_free_searchpgm(&pgm);
01239       vms_p->updated = 0;
01240       return vms_p->vmArrayIndex;
01241    } else {  
01242       mail_ping(vms_p->mailstream);
01243    }
01244    return 0;
01245 }
01246 
01247 static int imap_store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum, struct ast_channel *chan, struct ast_vm_user *vmu, char *fmt, int duration, struct vm_state *vms)
01248 {
01249    char *myserveremail = serveremail;
01250    char fn[PATH_MAX];
01251    char mailbox[256];
01252    char *stringp;
01253    FILE *p=NULL;
01254    char tmp[80] = "/tmp/astmail-XXXXXX";
01255    long len;
01256    void *buf;
01257    int tempcopy = 0;
01258    STRING str;
01259 
01260    /*Greetings are not retrieved from IMAP, so there is no reason to attempt storing them there either*/
01261    if (msgnum < 0)
01262       return 0;
01263 
01264    /* Attach only the first format */
01265    fmt = ast_strdupa(fmt);
01266    stringp = fmt;
01267    strsep(&stringp, "|");
01268 
01269    if (!ast_strlen_zero(vmu->serveremail))
01270       myserveremail = vmu->serveremail;
01271 
01272    make_file(fn, sizeof(fn), dir, msgnum);
01273 
01274    if (ast_strlen_zero(vmu->email)) {
01275       /*we need the vmu->email to be set when we call make_email_file, but if we keep it set,
01276        * a duplicate e-mail will be created. So at the end of this function, we will revert back to an empty
01277        * string if tempcopy is 1
01278        */
01279       ast_copy_string(vmu->email, vmu->imapuser, sizeof(vmu->email));
01280       tempcopy = 1;
01281    }
01282 
01283    if (!strcmp(fmt, "wav49"))
01284       fmt = "WAV";
01285    if (option_debug > 2)
01286       ast_log(LOG_DEBUG, "Storing file '%s', format '%s'\n", fn, fmt);
01287    /* Make a temporary file instead of piping directly to sendmail, in case the mail
01288       command hangs */
01289    if ((p = vm_mkftemp(tmp)) == NULL) {
01290       ast_log(LOG_WARNING, "Unable to store '%s' (can't create temporary file)\n", fn);
01291       if (tempcopy)
01292          *(vmu->email) = '\0';
01293       return -1;
01294    } else {
01295       make_email_file(p, myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, S_OR(chan->cid.cid_num, NULL), S_OR(chan->cid.cid_name, NULL), fn, fmt, duration, 1, chan, NULL, 1);
01296       /* read mail file to memory */
01297       len = ftell(p);
01298       rewind(p);
01299       if ((buf = ast_malloc(len+1)) == NIL) {
01300          ast_log(LOG_ERROR, "Can't allocate %ld bytes to read message\n", len+1);
01301          fclose(p);
01302          return -1;
01303       }
01304       fread(buf, len, 1, p);
01305       ((char *)buf)[len] = '\0';
01306       INIT(&str, mail_string, buf, len);
01307       init_mailstream(vms, 0);
01308       imap_mailbox_name(mailbox, sizeof(mailbox), vms, 0, 1);
01309       if (!mail_append(vms->mailstream, mailbox, &str))
01310          ast_log(LOG_ERROR, "Error while sending the message to %s\n", mailbox);
01311       fclose(p);
01312       unlink(tmp);
01313       ast_free(buf);
01314       if (option_debug > 2)
01315          ast_log(LOG_DEBUG, "%s stored\n", fn);
01316       /* Using messagecount to populate the last place in the msgArray
01317        * is less than optimal, but it's the only way given the current setup
01318        */
01319       messagecount(vmu->context, vmu->mailbox, "INBOX");
01320    }
01321    if (tempcopy)
01322       *(vmu->email) = '\0';
01323    return 0;
01324 
01325 }
01326 
01327 static int inboxcount(const char *mailbox_context, int *newmsgs, int *oldmsgs)
01328 {
01329    char tmp[PATH_MAX] = "";
01330    char *mailboxnc;  
01331    char *context;
01332    char *mb;
01333    char *cur;
01334    if (newmsgs)
01335       *newmsgs = 0;
01336    if (oldmsgs)
01337       *oldmsgs = 0;
01338 
01339    if (option_debug > 2)
01340       ast_log (LOG_DEBUG,"Mailbox is set to %s\n",mailbox_context);
01341    /* If no mailbox, return immediately */
01342    if (ast_strlen_zero(mailbox_context))
01343       return 0;
01344    
01345    ast_copy_string(tmp, mailbox_context, sizeof(tmp));
01346    context = strchr(tmp, '@');
01347    if (strchr(mailbox_context, ',')) {
01348       int tmpnew, tmpold;
01349       ast_copy_string(tmp, mailbox_context, sizeof(tmp));
01350       mb = tmp;
01351       while ((cur = strsep(&mb, ", "))) {
01352          if (!ast_strlen_zero(cur)) {
01353             if (inboxcount(cur, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
01354                return -1;
01355             else {
01356                if (newmsgs)
01357                   *newmsgs += tmpnew; 
01358                if (oldmsgs)
01359                   *oldmsgs += tmpold;
01360             }
01361          }
01362       }
01363       return 0;
01364    }
01365    if (context) {
01366       *context = '\0';
01367       mailboxnc = tmp;
01368       context++;
01369    } else {
01370       context = "default";
01371       mailboxnc = (char *)mailbox_context;
01372    }
01373    if (newmsgs) {
01374       if ((*newmsgs = messagecount(context, mailboxnc, "INBOX")) < 0)
01375          return -1;
01376    }
01377    if (oldmsgs) {
01378       if ((*oldmsgs = messagecount(context, mailboxnc, "Old")) < 0)
01379          return -1;
01380    }
01381    return 0;
01382 }
01383    
01384 
01385 static int has_voicemail(const char *mailbox, const char *folder)
01386 {
01387    char tmp[256], *tmp2, *mbox, *context;
01388    ast_copy_string(tmp, mailbox, sizeof(tmp));
01389    tmp2 = tmp;
01390    if (strchr(tmp2, ',')) {
01391       while ((mbox = strsep(&tmp2, ","))) {
01392          if (!ast_strlen_zero(mbox)) {
01393             if (has_voicemail(mbox, folder))
01394                return 1;
01395          }
01396       }
01397    }
01398    if ((context= strchr(tmp, '@')))
01399       *context++ = '\0';
01400    else
01401       context = "default";
01402    return messagecount(context, tmp, folder) ? 1 : 0;
01403 }
01404 
01405 static int copy_message(struct ast_channel *chan, struct ast_vm_user *vmu, int imbox, int msgnum, long duration, struct ast_vm_user *recip, char *fmt, char *dir)
01406 {
01407    struct vm_state *sendvms = NULL, *destvms = NULL;
01408    char messagestring[10]; /*I guess this could be a problem if someone has more than 999999999 messages...*/
01409    if (msgnum >= recip->maxmsg) {
01410       ast_log(LOG_WARNING, "Unable to copy mail, mailbox %s is full\n", recip->mailbox);
01411       return -1;
01412    }
01413    if (!(sendvms = get_vm_state_by_imapuser(vmu->imapuser, 0))) {
01414       ast_log(LOG_ERROR, "Couldn't get vm_state for originator's mailbox!!\n");
01415       return -1;
01416    }
01417    if (!(destvms = get_vm_state_by_imapuser(recip->imapuser, 0))) {
01418       ast_log(LOG_ERROR, "Couldn't get vm_state for destination mailbox!\n");
01419       return -1;
01420    }
01421    snprintf(messagestring, sizeof(messagestring), "%ld", sendvms->msgArray[msgnum]);
01422    if ((mail_copy(sendvms->mailstream, messagestring, (char *) mbox(imbox)) == T))
01423       return 0;
01424    ast_log(LOG_WARNING, "Unable to copy message from mailbox %s to mailbox %s\n", vmu->mailbox, recip->mailbox);
01425    return -1;
01426 }
01427 
01428 static void imap_mailbox_name(char *spec, size_t len, struct vm_state *vms, int box, int use_folder)
01429 {
01430    char tmp[256], *t = tmp;
01431    size_t left = sizeof(tmp);
01432 
01433    if (box == 1) {
01434       ast_copy_string(vms->curbox, mbox(0), sizeof(vms->curbox));
01435       snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", mbox(1));
01436    } else {
01437       ast_copy_string(vms->curbox, mbox(box), sizeof(vms->curbox));
01438       snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", vms->curbox);
01439    }
01440 
01441    /* Build up server information */
01442    ast_build_string(&t, &left, "{%s:%s/imap", imapserver, imapport);
01443 
01444    /* Add authentication user if present */
01445    if (!ast_strlen_zero(authuser))
01446       ast_build_string(&t, &left, "/authuser=%s", authuser);
01447 
01448    /* Add flags if present */
01449    if (!ast_strlen_zero(imapflags))
01450       ast_build_string(&t, &left, "/%s", imapflags);
01451 
01452    /* End with username */
01453    ast_build_string(&t, &left, "/user=%s}", vms->imapuser);
01454 
01455    if (box == 0 || box == 1)
01456       snprintf(spec, len, "%s%s", tmp, use_folder? imapfolder: "INBOX");
01457    else
01458       snprintf(spec, len, "%s%s%c%s", tmp, imapfolder, delimiter, mbox(box));
01459 }
01460 
01461 static int init_mailstream(struct vm_state *vms, int box)
01462 {
01463    MAILSTREAM *stream = NIL;
01464    long debug;
01465    char tmp[256];
01466    
01467    if (!vms) {
01468       ast_log (LOG_ERROR,"vm_state is NULL!\n");
01469       return -1;
01470    }
01471    if (option_debug > 2)
01472       ast_log (LOG_DEBUG,"vm_state user is:%s\n",vms->imapuser);
01473    if (vms->mailstream == NIL || !vms->mailstream) {
01474       if (option_debug)
01475          ast_log (LOG_DEBUG,"mailstream not set.\n");
01476    } else {
01477       stream = vms->mailstream;
01478    }
01479    /* debug = T;  user wants protocol telemetry? */
01480    debug = NIL;  /* NO protocol telemetry? */
01481 
01482    if (delimiter == '\0') {      /* did not probe the server yet */
01483       char *cp;
01484 #ifdef USE_SYSTEM_IMAP
01485 #include <imap/linkage.c>
01486 #elif defined(USE_SYSTEM_CCLIENT)
01487 #include <c-client/linkage.c>
01488 #else
01489 #include "linkage.c"
01490 #endif
01491       /* Connect to INBOX first to get folders delimiter */
01492       imap_mailbox_name(tmp, sizeof(tmp), vms, 0, 1);
01493       ast_mutex_lock(&vms->lock);
01494       stream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
01495       ast_mutex_unlock(&vms->lock);
01496       if (stream == NIL) {
01497          ast_log (LOG_ERROR, "Can't connect to imap server %s\n", tmp);
01498          return -1;
01499       }
01500       get_mailbox_delimiter(stream);
01501       /* update delimiter in imapfolder */
01502       for (cp = imapfolder; *cp; cp++)
01503          if (*cp == '/')
01504             *cp = delimiter;
01505    }
01506    /* Now connect to the target folder */
01507    imap_mailbox_name(tmp, sizeof(tmp), vms, box, 1);
01508    if (option_debug > 2)
01509       ast_log (LOG_DEBUG,"Before mail_open, server: %s, box:%d\n", tmp, box);
01510    ast_mutex_lock(&vms->lock);
01511    vms->mailstream = mail_open (stream, tmp, debug ? OP_DEBUG : NIL);
01512    ast_mutex_unlock(&vms->lock);
01513    if (vms->mailstream == NIL) {
01514       return -1;
01515    } else {
01516       return 0;
01517    }
01518 }
01519 
01520 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu, int box)
01521 {
01522    SEARCHPGM *pgm;
01523    SEARCHHEADER *hdr;
01524    int ret;
01525 
01526    ast_copy_string(vms->imapuser,vmu->imapuser, sizeof(vms->imapuser));
01527    if (option_debug > 2)
01528       ast_log(LOG_DEBUG,"Before init_mailstream, user is %s\n",vmu->imapuser);
01529    ret = init_mailstream(vms, box);
01530    if (ret != 0 || !vms->mailstream) {
01531       ast_log (LOG_ERROR,"Could not initialize mailstream\n");
01532       return -1;
01533    }
01534    
01535    create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
01536 
01537    /* Check Quota */
01538    if  (box == 0)  {
01539       if (option_debug > 2)
01540          ast_log(LOG_DEBUG, "Mailbox name set to: %s, about to check quotas\n", mbox(box));
01541       check_quota(vms,(char *)mbox(box));
01542    }
01543 
01544    pgm = mail_newsearchpgm();
01545 
01546    /* Check IMAP folder for Asterisk messages only... */
01547    hdr = mail_newsearchheader ("X-Asterisk-VM-Extension", vmu->mailbox);
01548    pgm->header = hdr;
01549    pgm->deleted = 0;
01550    pgm->undeleted = 1;
01551 
01552    /* if box = 0, check for new, if box = 1, check for read */
01553    if (box == 0) {
01554       pgm->unseen = 1;
01555       pgm->seen = 0;
01556    } else if (box == 1) {
01557       pgm->seen = 1;
01558       pgm->unseen = 0;
01559    }
01560 
01561    vms->vmArrayIndex = 0;
01562    if (option_debug > 2)
01563       ast_log(LOG_DEBUG,"Before mail_search_full, user is %s\n",vmu->imapuser);
01564    mail_search_full (vms->mailstream, NULL, pgm, NIL);
01565 
01566    vms->lastmsg = vms->vmArrayIndex - 1;
01567 
01568    mail_free_searchpgm(&pgm);
01569    return 0;
01570 }
01571 
01572 static void write_file(char *filename, char *buffer, unsigned long len)
01573 {
01574    FILE *output;
01575 
01576    output = fopen (filename, "w");
01577    fwrite (buffer, len, 1, output);
01578    fclose (output);
01579 }
01580 
01581 void mm_searched(MAILSTREAM *stream, unsigned long number)
01582 {
01583    struct vm_state *vms;
01584    char *mailbox;
01585    char *user;
01586    mailbox = stream->mailbox;
01587    user = get_user_by_mailbox(mailbox);
01588    vms = get_vm_state_by_imapuser(user,2);
01589    if (vms) {
01590       if (option_debug > 2)
01591          ast_log (LOG_DEBUG, "saving mailbox message number %lu as message %d. Interactive set to %d\n",number,vms->vmArrayIndex,vms->interactive);
01592       vms->msgArray[vms->vmArrayIndex++] = number;
01593    } else {
01594       ast_log (LOG_ERROR, "No state found.\n");
01595    }
01596 }
01597 
01598 static struct ast_vm_user *find_user_realtime_imapuser(const char *imapuser)
01599 {
01600    struct ast_variable *var;
01601    struct ast_vm_user *vmu;
01602 
01603    vmu = ast_calloc(1, sizeof *vmu);
01604    if (!vmu)
01605       return NULL;
01606    ast_set_flag(vmu, VM_ALLOCED);
01607    populate_defaults(vmu);
01608 
01609    var = ast_load_realtime("voicemail", "imapuser", imapuser, NULL);
01610    if (var) {
01611       apply_options_full(vmu, var);
01612       ast_variables_destroy(var);
01613       return vmu;
01614    } else {
01615       free(vmu);
01616       return NULL;
01617    }
01618 }
01619 
01620 /* Interfaces to C-client */
01621 
01622 void mm_exists(MAILSTREAM * stream, unsigned long number)
01623 {
01624    /* mail_ping will callback here if new mail! */
01625    if (option_debug > 3)
01626       ast_log (LOG_DEBUG, "Entering EXISTS callback for message %ld\n", number);
01627    if (number == 0) return;
01628    set_update(stream);
01629 }
01630 
01631 
01632 void mm_expunged(MAILSTREAM * stream, unsigned long number)
01633 {
01634    /* mail_ping will callback here if expunged mail! */
01635    if (option_debug > 3)
01636       ast_log (LOG_DEBUG, "Entering EXPUNGE callback for message %ld\n", number);
01637    if (number == 0) return;
01638    set_update(stream);
01639 }
01640 
01641 
01642 void mm_flags(MAILSTREAM * stream, unsigned long number)
01643 {
01644    /* mail_ping will callback here if read mail! */
01645    if (option_debug > 3)
01646       ast_log (LOG_DEBUG, "Entering FLAGS callback for message %ld\n", number);
01647    if (number == 0) return;
01648    set_update(stream);
01649 }
01650 
01651 
01652 void mm_notify(MAILSTREAM * stream, char *string, long errflg)
01653 {
01654    mm_log (string, errflg);
01655 }
01656 
01657 
01658 void mm_list(MAILSTREAM * stream, int delim, char *mailbox, long attributes)
01659 {
01660    if (delimiter == '\0') {
01661       delimiter = delim;
01662    }
01663    if (option_debug > 4) {
01664       ast_log(LOG_DEBUG, "Delimiter set to %c and mailbox %s\n",delim, mailbox);
01665       if (attributes & LATT_NOINFERIORS)
01666          ast_log(LOG_DEBUG, "no inferiors\n");
01667       if (attributes & LATT_NOSELECT)
01668          ast_log(LOG_DEBUG, "no select\n");
01669       if (attributes & LATT_MARKED)
01670          ast_log(LOG_DEBUG, "marked\n");
01671       if (attributes & LATT_UNMARKED)
01672          ast_log(LOG_DEBUG, "unmarked\n");
01673    }
01674 }
01675 
01676 
01677 void mm_lsub(MAILSTREAM * stream, int delimiter, char *mailbox, long attributes)
01678 {
01679    if (option_debug > 4) {
01680       ast_log(LOG_DEBUG, "Delimiter set to %c and mailbox %s\n",delimiter, mailbox);
01681       if (attributes & LATT_NOINFERIORS)
01682          ast_log(LOG_DEBUG, "no inferiors\n");
01683       if (attributes & LATT_NOSELECT)
01684          ast_log(LOG_DEBUG, "no select\n");
01685       if (attributes & LATT_MARKED)
01686          ast_log(LOG_DEBUG, "marked\n");
01687       if (attributes & LATT_UNMARKED)
01688          ast_log(LOG_DEBUG, "unmarked\n");
01689    }
01690 }
01691 
01692 
01693 void mm_status(MAILSTREAM * stream, char *mailbox, MAILSTATUS * status)
01694 {
01695    ast_log (LOG_NOTICE," Mailbox %s", mailbox);
01696    if (status->flags & SA_MESSAGES)
01697       ast_log (LOG_NOTICE,", %lu messages", status->messages);
01698    if (status->flags & SA_RECENT)
01699       ast_log (LOG_NOTICE,", %lu recent", status->recent);
01700    if (status->flags & SA_UNSEEN)
01701       ast_log (LOG_NOTICE,", %lu unseen", status->unseen);
01702    if (status->flags & SA_UIDVALIDITY)
01703       ast_log (LOG_NOTICE,", %lu UID validity", status->uidvalidity);
01704    if (status->flags & SA_UIDNEXT)
01705       ast_log (LOG_NOTICE,", %lu next UID", status->uidnext);
01706    ast_log (LOG_NOTICE,"\n");
01707 }
01708 
01709 
01710 void mm_log(char *string, long errflg)
01711 {
01712    switch ((short) errflg) {
01713       case NIL:
01714          if (option_debug)
01715             ast_log(LOG_DEBUG,"IMAP Info: %s\n", string);
01716          break;
01717       case PARSE:
01718       case WARN:
01719          ast_log (LOG_WARNING,"IMAP Warning: %s\n", string);
01720          break;
01721       case ERROR:
01722          ast_log (LOG_ERROR,"IMAP Error: %s\n", string);
01723          break;
01724    }
01725 }
01726 
01727 
01728 void mm_dlog(char *string)
01729 {
01730    ast_log (LOG_NOTICE, "%s\n", string);
01731 }
01732 
01733 
01734 void mm_login(NETMBX * mb, char *user, char *pwd, long trial)
01735 {
01736    struct ast_vm_user *vmu;
01737 
01738    if (option_debug > 3)
01739       ast_log(LOG_DEBUG, "Entering callback mm_login\n");
01740 
01741    ast_copy_string(user, mb->user, MAILTMPLEN);
01742 
01743    /* We should only do this when necessary */
01744    if (!ast_strlen_zero(authpassword)) {
01745       ast_copy_string(pwd, authpassword, MAILTMPLEN);
01746    } else {
01747       AST_LIST_TRAVERSE(&users, vmu, list) {
01748          if (!strcasecmp(mb->user, vmu->imapuser)) {
01749             ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
01750             break;
01751          }
01752       }
01753       if (!vmu) {
01754          if ((vmu = find_user_realtime_imapuser(mb->user))) {
01755             ast_copy_string(pwd, vmu->imappassword, MAILTMPLEN);
01756             free_user(vmu);
01757          }
01758       }
01759    }
01760 }
01761 
01762 
01763 void mm_critical(MAILSTREAM * stream)
01764 {
01765 }
01766 
01767 
01768 void mm_nocritical(MAILSTREAM * stream)
01769 {
01770 }
01771 
01772 
01773 long mm_diskerror(MAILSTREAM * stream, long errcode, long serious)
01774 {
01775    kill (getpid (), SIGSTOP);
01776    return NIL;
01777 }
01778 
01779 
01780 void mm_fatal(char *string)
01781 {
01782    ast_log(LOG_ERROR,"IMAP access FATAL error: %s\n", string);
01783 }
01784 
01785 /* C-client callback to handle quota */
01786 static void mm_parsequota(MAILSTREAM *stream, unsigned char *msg, QUOTALIST *pquota)
01787 {
01788    struct vm_state *vms;
01789    char *mailbox;
01790    char *user;
01791    unsigned long usage = 0;
01792    unsigned long limit = 0;
01793    
01794    while (pquota) {
01795       usage = pquota->usage;
01796       limit = pquota->limit;
01797       pquota = pquota->next;
01798    }
01799    
01800    mailbox = stream->mailbox;
01801    user = get_user_by_mailbox(mailbox);
01802    vms = get_vm_state_by_imapuser(user,2);
01803    if (vms) {
01804       if (option_debug > 2)
01805          ast_log (LOG_DEBUG, "User %s usage is %lu, limit is %lu\n",user,usage,limit);
01806       vms->quota_usage = usage;
01807       vms->quota_limit = limit;
01808    } else {
01809       ast_log (LOG_ERROR, "No state found.\n");
01810    }
01811 }
01812 
01813 static char *get_header_by_tag(char *header, char *tag)
01814 {
01815    char *start;
01816    int taglen;
01817    char *eol_pnt;
01818 
01819    if (!header || !tag)
01820       return NULL;
01821 
01822    taglen = strlen(tag) + 1;
01823    if (taglen < 1)
01824       return NULL;
01825 
01826    start = strstr(header, tag);
01827    if (!start)
01828       return NULL;
01829 
01830    ast_mutex_lock(&imaptemp_lock);
01831    ast_copy_string(imaptemp, start+taglen, sizeof(imaptemp));
01832    ast_mutex_unlock(&imaptemp_lock);
01833    if ((eol_pnt = strchr(imaptemp,'\r')) || (eol_pnt = strchr(imaptemp,'\n')))
01834       *eol_pnt = '\0';
01835    return imaptemp;
01836 }
01837 
01838 static char *get_user_by_mailbox(char *mailbox)
01839 {
01840    char *start, *quote;
01841    char *eol_pnt;
01842 
01843    if (!mailbox)
01844       return NULL;
01845 
01846    start = strstr(mailbox,"/user=");
01847    if (!start)
01848       return NULL;
01849 
01850    ast_mutex_lock(&imaptemp_lock);
01851    ast_copy_string(imaptemp, start+6, sizeof(imaptemp));
01852    ast_mutex_unlock(&imaptemp_lock);
01853 
01854    quote = strchr(imaptemp,'\"');
01855    if (!quote) {  /* if username is not in quotes */
01856       eol_pnt = strchr(imaptemp,'/');
01857       if (!eol_pnt) {
01858          eol_pnt = strchr(imaptemp,'}');
01859       }
01860       *eol_pnt = '\0';
01861       return imaptemp;
01862    } else {
01863       eol_pnt = strchr(imaptemp+1,'\"');
01864       *eol_pnt = '\0';
01865       return imaptemp+1;
01866    }
01867 }
01868 
01869 static struct vm_state *create_vm_state_from_user(struct ast_vm_user *vmu)
01870 {
01871    struct vm_state *vms_p;
01872 
01873    if (option_debug > 4)
01874       ast_log(LOG_DEBUG,"Adding new vmstate for %s\n",vmu->imapuser);
01875    if (!(vms_p = ast_calloc(1, sizeof(*vms_p))))
01876       return NULL;
01877    ast_copy_string(vms_p->imapuser,vmu->imapuser, sizeof(vms_p->imapuser));
01878    ast_copy_string(vms_p->username, vmu->mailbox, sizeof(vms_p->username)); /* save for access from interactive entry point */
01879    ast_copy_string(vms_p->context, vmu->context, sizeof(vms_p->context));
01880    vms_p->mailstream = NIL; /* save for access from interactive entry point */
01881    if (option_debug > 4)
01882       ast_log(LOG_DEBUG,"Copied %s to %s\n",vmu->imapuser,vms_p->imapuser);
01883    vms_p->updated = 1;
01884    /* set mailbox to INBOX! */
01885    ast_copy_string(vms_p->curbox, mbox(0), sizeof(vms_p->curbox));
01886    init_vm_state(vms_p);
01887    vmstate_insert(vms_p);
01888    return vms_p;
01889 }
01890 
01891 static struct vm_state *get_vm_state_by_imapuser(char *user, int interactive)
01892 {
01893    struct vmstate *vlist = NULL;
01894 
01895    ast_mutex_lock(&vmstate_lock);
01896    vlist = vmstates;
01897    while (vlist) {
01898       if (vlist->vms) {
01899          if (vlist->vms->imapuser) {
01900             if (!strcmp(vlist->vms->imapuser,user)) {
01901                if (interactive == 2) {
01902                   ast_mutex_unlock(&vmstate_lock);
01903                   return vlist->vms;
01904                } else if (vlist->vms->interactive == interactive) {
01905                   ast_mutex_unlock(&vmstate_lock);
01906                   return vlist->vms;
01907                }
01908             }
01909          } else {
01910             if (option_debug > 2)
01911                ast_log(LOG_DEBUG, " error: imapuser is NULL for %s\n",user);
01912          }
01913       } else {
01914          if (option_debug > 2)
01915             ast_log(LOG_DEBUG, " error: vms is NULL for %s\n",user);
01916       }
01917       vlist = vlist->next;
01918    }
01919    ast_mutex_unlock(&vmstate_lock);
01920    if (option_debug > 2)
01921       ast_log(LOG_DEBUG, "%s not found in vmstates\n",user);
01922    return NULL;
01923 }
01924 
01925 static struct vm_state *get_vm_state_by_mailbox(const char *mailbox, const char *context, int interactive)
01926 { 
01927    struct vmstate *vlist = NULL;
01928    const char *local_context = S_OR(context, "default");
01929 
01930    ast_mutex_lock(&vmstate_lock);
01931    vlist = vmstates;
01932    if (option_debug > 2) 
01933       ast_log(LOG_DEBUG, "Mailbox set to %s\n",mailbox);
01934    while (vlist) {
01935       if (vlist->vms) {
01936          if (vlist->vms->username && vlist->vms->context) {
01937             if (option_debug > 2)
01938                ast_log(LOG_DEBUG, " comparing mailbox %s (i=%d) to vmstate mailbox %s (i=%d)\n",mailbox,interactive,vlist->vms->username,vlist->vms->interactive);
01939             if (!strcmp(vlist->vms->username,mailbox) && !(strcmp(vlist->vms->context, local_context)) && vlist->vms->interactive == interactive) {
01940                if (option_debug > 2)
01941                   ast_log(LOG_DEBUG, " Found it!\n");
01942                ast_mutex_unlock(&vmstate_lock);
01943                return vlist->vms;
01944             }
01945          } else {
01946             if (option_debug > 2)
01947                ast_log(LOG_DEBUG, " error: username or context is NULL for %s\n",mailbox);
01948          }
01949       } else {
01950          if (option_debug > 2)
01951             ast_log(LOG_DEBUG, " error: vms is NULL for %s\n",mailbox);
01952       }
01953       vlist = vlist->next;
01954    }
01955    ast_mutex_unlock(&vmstate_lock);
01956    if (option_debug > 2)
01957       ast_log(LOG_DEBUG, "%s not found in vmstates\n",mailbox);
01958    return NULL;
01959 }
01960 
01961 static void vmstate_insert(struct vm_state *vms) 
01962 {
01963    struct vmstate *v;
01964    struct vm_state *altvms;
01965 
01966    /* If interactive, it probably already exists, and we should
01967       use the one we already have since it is more up to date.
01968       We can compare the username to find the duplicate */
01969    if (vms->interactive == 1) {
01970       altvms = get_vm_state_by_mailbox(vms->username, vms->context, 0);
01971       if (altvms) {
01972          if (option_debug > 2)
01973             ast_log(LOG_DEBUG, "Duplicate mailbox %s, copying message info...\n",vms->username);
01974          vms->newmessages = altvms->newmessages;
01975          vms->oldmessages = altvms->oldmessages;
01976          /* memcpy(vms->msgArray, altvms->msgArray, sizeof(long)*256); */
01977          copy_msgArray(vms, altvms);
01978          vms->vmArrayIndex = altvms->vmArrayIndex;
01979          vms->lastmsg = altvms->lastmsg;
01980          vms->curmsg = altvms->curmsg;
01981          /* get a pointer to the persistent store */
01982          vms->persist_vms = altvms;
01983          /* Reuse the mailstream? */
01984          vms->mailstream = altvms->mailstream;
01985          /* vms->mailstream = NIL; */
01986       }
01987    }
01988 
01989    v = (struct vmstate *)malloc(sizeof(struct vmstate));
01990    if (!v) {
01991       ast_log(LOG_ERROR, "Out of memory\n");
01992    }
01993    if (option_debug > 2)
01994       ast_log(LOG_DEBUG, "Inserting vm_state for user:%s, mailbox %s\n",vms->imapuser,vms->username);
01995    ast_mutex_lock(&vmstate_lock);
01996    v->vms = vms;
01997    v->next = vmstates;
01998    vmstates = v;
01999    ast_mutex_unlock(&vmstate_lock);
02000 }
02001 
02002 static void vmstate_delete(struct vm_state *vms) 
02003 {
02004    struct vmstate *vc, *vf = NULL, *vl = NULL;
02005    struct vm_state *altvms;
02006 
02007    /* If interactive, we should copy pertainent info
02008       back to the persistent state (to make update immediate) */
02009    if (vms->interactive == 1) {
02010       altvms = vms->persist_vms;
02011       if (altvms) {
02012          if (option_debug > 2)
02013             ast_log(LOG_DEBUG, "Duplicate mailbox %s, copying message info...\n",vms->username);
02014          altvms->newmessages = vms->newmessages;
02015          altvms->oldmessages = vms->oldmessages;
02016          altvms->updated = 1;
02017       }
02018    }
02019 
02020    ast_mutex_lock(&vmstate_lock);
02021    vc = vmstates;
02022    if (option_debug > 2)
02023       ast_log(LOG_DEBUG, "Removing vm_state for user:%s, mailbox %s\n",vms->imapuser,vms->username);
02024    while (vc) {
02025       if (vc->vms == vms) {
02026          vf = vc;
02027          if (vl)
02028             vl->next = vc->next;
02029          else
02030             vmstates = vc->next;
02031          break;
02032       }
02033       vl = vc;
02034       vc = vc->next;
02035    }
02036    if (!vf) {
02037       ast_log(LOG_ERROR, "No vmstate found for user:%s, mailbox %s\n",vms->imapuser,vms->username);
02038    } else {
02039       ast_mutex_destroy(&vf->vms->lock);
02040       free(vf);
02041    }
02042    ast_mutex_unlock(&vmstate_lock);
02043 }
02044 
02045 static void set_update(MAILSTREAM * stream) 
02046 {
02047    struct vm_state *vms;
02048    char *mailbox;
02049    char *user;
02050 
02051    mailbox = stream->mailbox;
02052    user = get_user_by_mailbox(mailbox);
02053    vms = get_vm_state_by_imapuser(user, 0);
02054    if (vms) {
02055       if (option_debug > 2)
02056          ast_log (LOG_DEBUG, "User %s mailbox set for update.\n",user);
02057       vms->updated = 1; /* set updated flag since mailbox changed */
02058    } else {
02059       if (option_debug > 2)
02060          ast_log (LOG_WARNING, "User %s mailbox not found for update.\n",user);
02061    }
02062 }
02063 
02064 static void init_vm_state(struct vm_state *vms) 
02065 {
02066    int x;
02067    vms->vmArrayIndex = 0;
02068    for (x = 0; x < 256; x++) {
02069       vms->msgArray[x] = 0;
02070    }
02071    ast_mutex_init(&vms->lock);
02072 }
02073 
02074 static void copy_msgArray(struct vm_state *dst, struct vm_state *src)
02075 {
02076    int x;
02077    for (x = 0; x<256; x++) {
02078       dst->msgArray[x] = src->msgArray[x];
02079    }
02080 }
02081 
02082 static int save_body(BODY *body, struct vm_state *vms, char *section, char *format) 
02083 {
02084    char *body_content;
02085    char *body_decoded;
02086    unsigned long len;
02087    unsigned long newlen;
02088    char filename[256];
02089    
02090    if (!body || body == NIL)
02091       return -1;
02092    body_content = mail_fetchbody (vms->mailstream, vms->msgArray[vms->curmsg], section, &len);
02093    if (body_content != NIL) {
02094       snprintf(filename, sizeof(filename), "%s.%s", vms->fn, format);
02095       /* ast_log (LOG_DEBUG,body_content); */
02096       body_decoded = rfc822_base64 ((unsigned char *)body_content, len, &newlen);
02097       write_file (filename, (char *) body_decoded, newlen);
02098    }
02099    return 0;
02100 }
02101 
02102 /* get delimiter via mm_list callback */
02103 static void get_mailbox_delimiter(MAILSTREAM *stream) {
02104    char tmp[50];
02105    snprintf(tmp, sizeof(tmp), "{%s}", imapserver);
02106    mail_list(stream, tmp, "*");
02107 }
02108 
02109 /* Check Quota for user */
02110 static void check_quota(struct vm_state *vms, char *mailbox) {
02111    mail_parameters(NULL, SET_QUOTA, (void *) mm_parsequota);
02112    if (option_debug > 2)
02113       ast_log(LOG_DEBUG, "Mailbox name set to: %s, about to check quotas\n", mailbox);
02114    if (vms && vms->mailstream != NULL) {
02115       imap_getquotaroot(vms->mailstream, mailbox);
02116    } else {
02117       ast_log(LOG_WARNING,"Mailstream not available for mailbox: %s\n",mailbox);
02118    }
02119 }
02120 #endif
02121 
02122 /* only return failure if ast_lock_path returns 'timeout',
02123    not if the path does not exist or any other reason
02124 */
02125 static int vm_lock_path(const char *path)
02126 {
02127    switch (ast_lock_path(path)) {
02128    case AST_LOCK_TIMEOUT:
02129       return -1;
02130    default:
02131       return 0;
02132    }
02133 }
02134 
02135 
02136 #ifdef ODBC_STORAGE
02137 struct generic_prepare_struct {
02138    char *sql;
02139    int argc;
02140    char **argv;
02141 };
02142 
02143 static SQLHSTMT generic_prepare(struct odbc_obj *obj, void *data)
02144 {
02145    struct generic_prepare_struct *gps = data;
02146    int res, i;
02147    SQLHSTMT stmt;
02148 
02149    res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
02150    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02151       ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
02152       return NULL;
02153    }
02154    res = SQLPrepare(stmt, (unsigned char *)gps->sql, SQL_NTS);
02155    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02156       ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", gps->sql);
02157       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
02158       return NULL;
02159    }
02160    for (i = 0; i < gps->argc; i++)
02161       SQLBindParameter(stmt, i + 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(gps->argv[i]), 0, gps->argv[i], 0, NULL);
02162 
02163    return stmt;
02164 }
02165 
02166 static int retrieve_file(char *dir, int msgnum)
02167 {
02168    int x = 0;
02169    int res;
02170    int fd=-1;
02171    size_t fdlen = 0;
02172    void *fdm = MAP_FAILED;
02173    SQLSMALLINT colcount=0;
02174    SQLHSTMT stmt;
02175    char sql[PATH_MAX];
02176    char fmt[80]="";
02177    char *c;
02178    char coltitle[256];
02179    SQLSMALLINT collen;
02180    SQLSMALLINT datatype;
02181    SQLSMALLINT decimaldigits;
02182    SQLSMALLINT nullable;
02183    SQLULEN colsize;
02184    SQLLEN colsize2;
02185    FILE *f=NULL;
02186    char rowdata[80];
02187    char fn[PATH_MAX];
02188    char full_fn[PATH_MAX];
02189    char msgnums[80];
02190    char *argv[] = { dir, msgnums };
02191    struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
02192 
02193    struct odbc_obj *obj;
02194    obj = ast_odbc_request_obj(odbc_database, 0);
02195    if (obj) {
02196       ast_copy_string(fmt, vmfmts, sizeof(fmt));
02197       c = strchr(fmt, '|');
02198       if (c)
02199          *c = '\0';
02200       if (!strcasecmp(fmt, "wav49"))
02201          strcpy(fmt, "WAV");
02202       snprintf(msgnums, sizeof(msgnums),"%d", msgnum);
02203       if (msgnum > -1)
02204          make_file(fn, sizeof(fn), dir, msgnum);
02205       else
02206          ast_copy_string(fn, dir, sizeof(fn));
02207       snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
02208       
02209       if (!(f = fopen(full_fn, "w+"))) {
02210               ast_log(LOG_WARNING, "Failed to open/create '%s'\n", full_fn);
02211               goto yuck;
02212       }
02213       
02214       snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
02215       snprintf(sql, sizeof(sql), "SELECT * FROM %s WHERE dir=? AND msgnum=?",odbc_table);
02216       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
02217       if (!stmt) {
02218          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
02219          ast_odbc_release_obj(obj);
02220          goto yuck;
02221       }
02222       res = SQLFetch(stmt);
02223       if (res == SQL_NO_DATA) {
02224          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02225          ast_odbc_release_obj(obj);
02226          goto yuck;
02227       }
02228       else if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02229          ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
02230          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02231          ast_odbc_release_obj(obj);
02232          goto yuck;
02233       }
02234       fd = open(full_fn, O_RDWR | O_CREAT | O_TRUNC, 0770);
02235       if (fd < 0) {
02236          ast_log(LOG_WARNING, "Failed to write '%s': %s\n", full_fn, strerror(errno));
02237          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02238          ast_odbc_release_obj(obj);
02239          goto yuck;
02240       }
02241       res = SQLNumResultCols(stmt, &colcount);
02242       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {  
02243          ast_log(LOG_WARNING, "SQL Column Count error!\n[%s]\n\n", sql);
02244          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02245          ast_odbc_release_obj(obj);
02246          goto yuck;
02247       }
02248       if (f) 
02249          fprintf(f, "[message]\n");
02250       for (x=0;x<colcount;x++) {
02251          rowdata[0] = '\0';
02252          collen = sizeof(coltitle);
02253          res = SQLDescribeCol(stmt, x + 1, (unsigned char *)coltitle, sizeof(coltitle), &collen, 
02254                   &datatype, &colsize, &decimaldigits, &nullable);
02255          if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02256             ast_log(LOG_WARNING, "SQL Describe Column error!\n[%s]\n\n", sql);
02257             SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02258             ast_odbc_release_obj(obj);
02259             goto yuck;
02260          }
02261          if (!strcasecmp(coltitle, "recording")) {
02262             off_t offset;
02263             res = SQLGetData(stmt, x + 1, SQL_BINARY, rowdata, 0, &colsize2);
02264             fdlen = colsize2;
02265             if (fd > -1) {
02266                char tmp[1]="";
02267                lseek(fd, fdlen - 1, SEEK_SET);
02268                if (write(fd, tmp, 1) != 1) {
02269                   close(fd);
02270                   fd = -1;
02271                   continue;
02272                }
02273                /* Read out in small chunks */
02274                for (offset = 0; offset < colsize2; offset += CHUNKSIZE) {
02275                   if ((fdm = mmap(NULL, CHUNKSIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset)) == MAP_FAILED) {
02276                      ast_log(LOG_WARNING, "Could not mmap the output file: %s (%d)\n", strerror(errno), errno);
02277                      SQLFreeHandle(SQL_HANDLE_STMT, stmt);
02278                      ast_odbc_release_obj(obj);
02279                      goto yuck;
02280                   } else {
02281                      res = SQLGetData(stmt, x + 1, SQL_BINARY, fdm, CHUNKSIZE, NULL);
02282                      munmap(fdm, CHUNKSIZE);
02283                      if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02284                         ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
02285                         unlink(full_fn);
02286                         SQLFreeHandle(SQL_HANDLE_STMT, stmt);
02287                         ast_odbc_release_obj(obj);
02288                         goto yuck;
02289                      }
02290                   }
02291                }
02292                if (truncate(full_fn, fdlen) < 0) {
02293                   ast_log(LOG_WARNING, "Unable to truncate '%s': %s\n", full_fn, strerror(errno));
02294                }
02295             }
02296          } else {
02297             SQLLEN ind;
02298             res = SQLGetData(stmt, x + 1, SQL_CHAR, rowdata, sizeof(rowdata), &ind);
02299             if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02300                SQLINTEGER nativeerror = 0;
02301                SQLSMALLINT diagbytes = 0;
02302                unsigned char state[10], diagnostic[256];
02303                SQLGetDiagRec(SQL_HANDLE_STMT, stmt, 1, state, &nativeerror, diagnostic, sizeof(diagnostic), &diagbytes);
02304                ast_log(LOG_WARNING, "SQL Get Data error: %s: %s!\n[%s]\n\n", state, diagnostic, sql);
02305                SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02306                ast_odbc_release_obj(obj);
02307                goto yuck;
02308             }
02309             if (strcasecmp(coltitle, "msgnum") && strcasecmp(coltitle, "dir") && f)
02310                fprintf(f, "%s=%s\n", coltitle, rowdata);
02311          }
02312       }
02313       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02314       ast_odbc_release_obj(obj);
02315    } else
02316       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
02317 yuck: 
02318    if (f)
02319       fclose(f);
02320    if (fd > -1)
02321       close(fd);
02322    return x - 1;
02323 }
02324 
02325 static int last_message_index(struct ast_vm_user *vmu, char *dir)
02326 {
02327    int x = 0;
02328    int res;
02329    SQLHSTMT stmt;
02330    char sql[PATH_MAX];
02331    char rowdata[20];
02332    char *argv[] = { dir };
02333    struct generic_prepare_struct gps = { .sql = sql, .argc = 1, .argv = argv };
02334 
02335    struct odbc_obj *obj;
02336    obj = ast_odbc_request_obj(odbc_database, 0);
02337    if (obj) {
02338       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=?",odbc_table);
02339       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
02340       if (!stmt) {
02341          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
02342          ast_odbc_release_obj(obj);
02343          goto yuck;
02344       }
02345       res = SQLFetch(stmt);
02346       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02347          ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
02348          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02349          ast_odbc_release_obj(obj);
02350          goto yuck;
02351       }
02352       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
02353       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02354          ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
02355          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02356          ast_odbc_release_obj(obj);
02357          goto yuck;
02358       }
02359       if (sscanf(rowdata, "%d", &x) != 1)
02360          ast_log(LOG_WARNING, "Failed to read message count!\n");
02361       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02362       ast_odbc_release_obj(obj);
02363    } else
02364       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
02365 yuck: 
02366    return x - 1;
02367 }
02368 
02369 static int message_exists(char *dir, int msgnum)
02370 {
02371    int x = 0;
02372    int res;
02373    SQLHSTMT stmt;
02374    char sql[PATH_MAX];
02375    char rowdata[20];
02376    char msgnums[20];
02377    char *argv[] = { dir, msgnums };
02378    struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
02379 
02380    struct odbc_obj *obj;
02381    obj = ast_odbc_request_obj(odbc_database, 0);
02382    if (obj) {
02383       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
02384       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir=? AND msgnum=?",odbc_table);
02385       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
02386       if (!stmt) {
02387          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
02388          ast_odbc_release_obj(obj);
02389          goto yuck;
02390       }
02391       res = SQLFetch(stmt);
02392       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02393          ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
02394          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02395          ast_odbc_release_obj(obj);
02396          goto yuck;
02397       }
02398       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
02399       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02400          ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
02401          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02402          ast_odbc_release_obj(obj);
02403          goto yuck;
02404       }
02405       if (sscanf(rowdata, "%d", &x) != 1)
02406          ast_log(LOG_WARNING, "Failed to read message count!\n");
02407       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02408       ast_odbc_release_obj(obj);
02409    } else
02410       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
02411 yuck: 
02412    return x;
02413 }
02414 
02415 static int count_messages(struct ast_vm_user *vmu, char *dir)
02416 {
02417    return last_message_index(vmu, dir) + 1;
02418 }
02419 
02420 static void delete_file(char *sdir, int smsg)
02421 {
02422    SQLHSTMT stmt;
02423    char sql[PATH_MAX];
02424    char msgnums[20];
02425    char *argv[] = { sdir, msgnums };
02426    struct generic_prepare_struct gps = { .sql = sql, .argc = 2, .argv = argv };
02427 
02428    struct odbc_obj *obj;
02429    obj = ast_odbc_request_obj(odbc_database, 0);
02430    if (obj) {
02431       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
02432       snprintf(sql, sizeof(sql), "DELETE FROM %s WHERE dir=? AND msgnum=?",odbc_table);
02433       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
02434       if (!stmt)
02435          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
02436       else
02437          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
02438       ast_odbc_release_obj(obj);
02439    } else
02440       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
02441    return;  
02442 }
02443 
02444 static void copy_file(char *sdir, int smsg, char *ddir, int dmsg, char *dmailboxuser, char *dmailboxcontext)
02445 {
02446    SQLHSTMT stmt;
02447    char sql[512];
02448    char msgnums[20];
02449    char msgnumd[20];
02450    struct odbc_obj *obj;
02451    char *argv[] = { ddir, msgnumd, dmailboxuser, dmailboxcontext, sdir, msgnums };
02452    struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
02453 
02454    delete_file(ddir, dmsg);
02455    obj = ast_odbc_request_obj(odbc_database, 0);
02456    if (obj) {
02457       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
02458       snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
02459       snprintf(sql, sizeof(sql), "INSERT INTO %s (dir, msgnum, context, macrocontext, callerid, origtime, duration, recording, mailboxuser, mailboxcontext) SELECT ?,?,context,macrocontext,callerid,origtime,duration,recording,?,? FROM %s WHERE dir=? AND msgnum=?",odbc_table,odbc_table);
02460       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
02461       if (!stmt)
02462          ast_log(LOG_WARNING, "SQL Execute error!\n[%s] (You probably don't have MySQL 4.1 or later installed)\n\n", sql);
02463       else
02464          SQLFreeHandle(SQL_HANDLE_STMT, stmt);
02465       ast_odbc_release_obj(obj);
02466    } else
02467       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
02468    return;  
02469 }
02470 
02471 struct insert_cb_struct {
02472    char *dir;
02473    char *msgnum;
02474    void *recording;
02475    size_t recordinglen;
02476    SQLLEN indlen;
02477    const char *context;
02478    const char *macrocontext;
02479    const char *callerid;
02480    const char *origtime;
02481    const char *duration;
02482    char *mailboxuser;
02483    char *mailboxcontext;
02484    const char *category;
02485    char *sql;
02486 };
02487 
02488 static SQLHSTMT insert_cb(struct odbc_obj *obj, void *vd)
02489 {
02490    struct insert_cb_struct *d = vd;
02491    int res;
02492    SQLHSTMT stmt;
02493 
02494    res = SQLAllocHandle(SQL_HANDLE_STMT, obj->con, &stmt);
02495    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02496       ast_log(LOG_WARNING, "SQL Alloc Handle failed!\n");
02497       return NULL;
02498    }
02499 
02500    res = SQLPrepare(stmt, (unsigned char *)d->sql, SQL_NTS);
02501    if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
02502       ast_log(LOG_WARNING, "SQL Prepare failed![%s]\n", d->sql);
02503       SQLFreeHandle(SQL_HANDLE_STMT, stmt);
02504       return NULL;
02505    }
02506 
02507    SQLBindParameter(stmt, 1, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->dir), 0, (void *)d->dir, 0, NULL);
02508    SQLBindParameter(stmt, 2, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->msgnum), 0, (void *)d->msgnum, 0, NULL);
02509    SQLBindParameter(stmt, 3, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_LONGVARBINARY, d->recordinglen, 0, (void *)d->recording, 0, &d->indlen);
02510    SQLBindParameter(stmt, 4, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->context), 0, (void *)d->context, 0, NULL);
02511    SQLBindParameter(stmt, 5, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->macrocontext), 0, (void *)d->macrocontext, 0, NULL);
02512    SQLBindParameter(stmt, 6, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->callerid), 0, (void *)d->callerid, 0, NULL);
02513    SQLBindParameter(stmt, 7, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->origtime), 0, (void *)d->origtime, 0, NULL);
02514    SQLBindParameter(stmt, 8, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->duration), 0, (void *)d->duration, 0, NULL);
02515    SQLBindParameter(stmt, 9, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->mailboxuser), 0, (void *)d->mailboxuser, 0, NULL);
02516    SQLBindParameter(stmt, 10, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->mailboxcontext), 0, (void *)d->mailboxcontext, 0, NULL);
02517    if (!ast_strlen_zero(d->category)) {
02518       SQLBindParameter(stmt, 11, SQL_PARAM_INPUT, SQL_C_CHAR, SQL_CHAR, strlen(d->category), 0, (void *)d->category, 0, NULL);
02519    }
02520 
02521    return stmt;
02522 }
02523 
02524 static int store_file(char *dir, char *mailboxuser, char *mailboxcontext, int msgnum)
02525 {
02526    int x = 0;
02527    int fd = -1;
02528    void *fdm = MAP_FAILED;
02529    size_t fdlen = -1;
02530    SQLHSTMT stmt;
02531    char sql[PATH_MAX];
02532    char msgnums[20];
02533    char fn[PATH_MAX];
02534    char full_fn[PATH_MAX];
02535    char fmt[80]="";
02536    char *c;
02537    struct insert_cb_struct d = {
02538       .dir = dir,
02539       .msgnum = msgnums,
02540       .context = "",
02541       .macrocontext = "",
02542       .callerid = "",
02543       .origtime = "",
02544       .duration = "",
02545       .mailboxuser = mailboxuser,
02546       .mailboxcontext = mailboxcontext,
02547       .category = "",
02548       .sql = sql
02549    };
02550    struct ast_config *cfg=NULL;
02551    struct odbc_obj *obj;
02552 
02553    delete_file(dir, msgnum);
02554    obj = ast_odbc_request_obj(odbc_database, 0);
02555    if (obj) {
02556       ast_copy_string(fmt, vmfmts, sizeof(fmt));
02557       c = strchr(fmt, '|');
02558       if (c)
02559          *c = '\0';
02560       if (!strcasecmp(fmt, "wav49"))
02561          strcpy(fmt, "WAV");
02562       snprintf(msgnums, sizeof(msgnums),"%d", msgnum);
02563       if (msgnum > -1)
02564          make_file(fn, sizeof(fn), dir, msgnum);
02565       else
02566          ast_copy_string(fn, dir, sizeof(fn));
02567       snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
02568       cfg = ast_config_load(full_fn);
02569       snprintf(full_fn, sizeof(full_fn), "%s.%s", fn, fmt);
02570       fd = open(full_fn, O_RDWR);
02571       if (fd < 0) {
02572          ast_log(LOG_WARNING, "Open of sound file '%s' failed: %s\n", full_fn, strerror(errno));
02573          ast_odbc_release_obj(obj);
02574          goto yuck;
02575       }
02576       if (cfg) {
02577          d.context = ast_variable_retrieve(cfg, "message", "context");
02578          if (!d.context) d.context = "";
02579          d.macrocontext = ast_variable_retrieve(cfg, "message", "macrocontext");
02580          if (!d.macrocontext) d.macrocontext = "";
02581          d.callerid = ast_variable_retrieve(cfg, "message", "callerid");
02582          if (!d.callerid) d.callerid = "";
02583          d.origtime = ast_variable_retrieve(cfg, "message", "origtime");
02584          if (!d.origtime) d.origtime = "";
02585          d.duration = ast_variable_retrieve(cfg, "message", "duration");
02586          if (!d.duration) d.duration = "";
02587          d.category = ast_variable_retrieve(cfg, "message", "category");
02588          if (!d.category) d.category = "";
02589       }
02590       fdlen = lseek(fd, 0, SEEK_END);
02591       lseek(fd, 0, SEEK_SET);
02592       printf("Length is %zd\n", fdlen);
02593       fdm = mmap(NULL, fdlen, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
02594       if (fdm == MAP_FAILED) {
02595          ast_log(LOG_WARNING, "Memory map failed!\n");
02596          ast_odbc_release_obj(obj);
02597          goto yuck;
02598       }
02599       d.recording = fdm;
02600       d.recordinglen = d.indlen = fdlen; /* SQL_LEN_DATA_AT_EXEC(fdlen); */
02601       if (!ast_strlen_zero(d.category)) 
02602          snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext,category) VALUES (?,?,?,?,?,?,?,?,?,?,?)",odbc_table); 
02603       else
02604          snprintf(sql, sizeof(sql), "INSERT INTO %s (dir,msgnum,recording,context,macrocontext,callerid,origtime,duration,mailboxuser,mailboxcontext) VALUES (?,?, ? , ?,?,?,?,?,?,?)",odbc_table);
02605       stmt = ast_odbc_prepare_and_execute(obj, insert_cb, &d);
02606       if (stmt) {
02607          SQLFreeHandle(SQL_HANDLE_STMT, stmt);
02608       }
02609       ast_odbc_release_obj(obj);
02610    } else
02611       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
02612 yuck: 
02613    if (cfg)
02614       ast_config_destroy(cfg);
02615    if (fdm != MAP_FAILED)
02616       munmap(fdm, fdlen);
02617    if (fd > -1)
02618       close(fd);
02619    return x;
02620 }
02621 
02622 static void rename_file(char *sdir, int smsg, char *mailboxuser, char *mailboxcontext, char *ddir, int dmsg)
02623 {
02624    SQLHSTMT stmt;
02625    char sql[PATH_MAX];
02626    char msgnums[20];
02627    char msgnumd[20];
02628    struct odbc_obj *obj;
02629    char *argv[] = { ddir, msgnumd, mailboxuser, mailboxcontext, sdir, msgnums };
02630    struct generic_prepare_struct gps = { .sql = sql, .argc = 6, .argv = argv };
02631 
02632    delete_file(ddir, dmsg);
02633    obj = ast_odbc_request_obj(odbc_database, 0);
02634    if (obj) {
02635       snprintf(msgnums, sizeof(msgnums), "%d", smsg);
02636       snprintf(msgnumd, sizeof(msgnumd), "%d", dmsg);
02637       snprintf(sql, sizeof(sql), "UPDATE %s SET dir=?, msgnum=?, mailboxuser=?, mailboxcontext=? WHERE dir=? AND msgnum=?",odbc_table);
02638       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
02639       if (!stmt)
02640          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
02641       else
02642          SQLFreeHandle(SQL_HANDLE_STMT, stmt);
02643       ast_odbc_release_obj(obj);
02644    } else
02645       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
02646    return;  
02647 }
02648 
02649 #else
02650 #ifndef IMAP_STORAGE
02651 static int count_messages(struct ast_vm_user *vmu, char *dir)
02652 {
02653    /* Find all .txt files - even if they are not in sequence from 0000 */
02654 
02655    int vmcount = 0;
02656    DIR *vmdir = NULL;
02657    struct dirent *vment = NULL;
02658 
02659    if (vm_lock_path(dir))
02660       return ERROR_LOCK_PATH;
02661 
02662    if ((vmdir = opendir(dir))) {
02663       while ((vment = readdir(vmdir))) {
02664          if (strlen(vment->d_name) > 7 && !strncmp(vment->d_name + 7, ".txt", 4)) 
02665             vmcount++;
02666       }
02667       closedir(vmdir);
02668    }
02669    ast_unlock_path(dir);
02670    
02671    return vmcount;
02672 }
02673 
02674 static void rename_file(char *sfn, char *dfn)
02675 {
02676    char stxt[PATH_MAX];
02677    char dtxt[PATH_MAX];
02678    ast_filerename(sfn,dfn,NULL);
02679    snprintf(stxt, sizeof(stxt), "%s.txt", sfn);
02680    snprintf(dtxt, sizeof(dtxt), "%s.txt", dfn);
02681    rename(stxt, dtxt);
02682 }
02683 #endif
02684 
02685 /*
02686  * A negative return value indicates an error.
02687  */
02688 #if (!defined(IMAP_STORAGE) && !defined(ODBC_STORAGE))
02689 static int last_message_index(struct ast_vm_user *vmu, char *dir)
02690 {
02691    int x;
02692    char fn[PATH_MAX];
02693 
02694    if (vm_lock_path(dir))
02695       return ERROR_LOCK_PATH;
02696 
02697    for (x = 0; x < vmu->maxmsg; x++) {
02698       make_file(fn, sizeof(fn), dir, x);
02699       if (ast_fileexists(fn, NULL, NULL) < 1)
02700          break;
02701    }
02702    ast_unlock_path(dir);
02703 
02704    return x - 1;
02705 }
02706 #endif
02707 #endif
02708 #if (defined(IMAP_STORAGE) || defined(ODBC_STORAGE))
02709 static int remove_file(char *dir, int msgnum)
02710 {
02711    char fn[PATH_MAX];
02712    char full_fn[PATH_MAX];
02713    char msgnums[80];
02714    
02715    if (msgnum > -1) {
02716       snprintf(msgnums, sizeof(msgnums), "%d", msgnum);
02717       make_file(fn, sizeof(fn), dir, msgnum);
02718    } else {
02719 #ifndef IMAP_STORAGE
02720       ast_copy_string(fn, dir, sizeof(fn));
02721 #else
02722       /*IMAP stores greetings locally so it should not
02723        * try to dispose of them
02724        */
02725       return 0;
02726 #endif
02727    }
02728    ast_filedelete(fn, NULL);  
02729    snprintf(full_fn, sizeof(full_fn), "%s.txt", fn);
02730    unlink(full_fn);
02731    return 0;
02732 }
02733 #endif
02734 
02735 static int copy(char *infile, char *outfile)
02736 {
02737    int ifd;
02738    int ofd;
02739    int res;
02740    int len;
02741    char buf[4096];
02742 
02743 #ifdef HARDLINK_WHEN_POSSIBLE
02744    /* Hard link if possible; saves disk space & is faster */
02745    if (link(infile, outfile)) {
02746 #endif
02747       if ((ifd = open(infile, O_RDONLY)) < 0) {
02748          ast_log(LOG_WARNING, "Unable to open %s in read-only mode: %s\n", infile, strerror(errno));
02749          return -1;
02750       }
02751       if ((ofd = open(outfile, O_WRONLY | O_TRUNC | O_CREAT, VOICEMAIL_FILE_MODE)) < 0) {
02752          ast_log(LOG_WARNING, "Unable to open %s in write-only mode: %s\n", outfile, strerror(errno));
02753          close(ifd);
02754          return -1;
02755       }
02756       do {
02757          len = read(ifd, buf, sizeof(buf));
02758          if (len < 0) {
02759             ast_log(LOG_WARNING, "Read failed on %s: %s\n", infile, strerror(errno));
02760             close(ifd);
02761             close(ofd);
02762             unlink(outfile);
02763          }
02764          if (len) {
02765             res = write(ofd, buf, len);
02766             if (errno == ENOMEM || errno == ENOSPC || res != len) {
02767                ast_log(LOG_WARNING, "Write failed on %s (%d of %d): %s\n", outfile, res, len, strerror(errno));
02768                close(ifd);
02769                close(ofd);
02770                unlink(outfile);
02771             }
02772          }
02773       } while (len);
02774       close(ifd);
02775       close(ofd);
02776       return 0;
02777 #ifdef HARDLINK_WHEN_POSSIBLE
02778    } else {
02779       /* Hard link succeeded */
02780       return 0;
02781    }
02782 #endif
02783 }
02784 
02785 static void copy_plain_file(char *frompath, char *topath)
02786 {
02787    char frompath2[PATH_MAX], topath2[PATH_MAX];
02788    ast_filecopy(frompath, topath, NULL);
02789    snprintf(frompath2, sizeof(frompath2), "%s.txt", frompath);
02790    snprintf(topath2, sizeof(topath2), "%s.txt", topath);
02791    copy(frompath2, topath2);
02792 }
02793 
02794 static int vm_delete(char *file)
02795 {
02796    char *txt;
02797    int txtsize = 0;
02798 
02799    txtsize = (strlen(file) + 5)*sizeof(char);
02800    txt = alloca(txtsize);
02801    /* Sprintf here would safe because we alloca'd exactly the right length,
02802     * but trying to eliminate all sprintf's anyhow
02803     */
02804    snprintf(txt, txtsize, "%s.txt", file);
02805    unlink(txt);
02806    return ast_filedelete(file, NULL);
02807 }
02808 
02809 static int inbuf(struct baseio *bio, FILE *fi)
02810 {
02811    int l;
02812 
02813    if (bio->ateof)
02814       return 0;
02815 
02816    if ((l = fread(bio->iobuf,1,BASEMAXINLINE,fi)) <= 0) {
02817       if (ferror(fi))
02818          return -1;
02819 
02820       bio->ateof = 1;
02821       return 0;
02822    }
02823 
02824    bio->iolen= l;
02825    bio->iocp= 0;
02826 
02827    return 1;
02828 }
02829 
02830 static int inchar(struct baseio *bio, FILE *fi)
02831 {
02832    if (bio->iocp>=bio->iolen) {
02833       if (!inbuf(bio, fi))
02834          return EOF;
02835    }
02836 
02837    return bio->iobuf[bio->iocp++];
02838 }
02839 
02840 static int ochar(struct baseio *bio, int c, FILE *so)
02841 {
02842    if (bio->linelength>=BASELINELEN) {
02843       if (fputs(eol,so)==EOF)
02844          return -1;
02845 
02846       bio->linelength= 0;
02847    }
02848 
02849    if (putc(((unsigned char)c),so)==EOF)
02850       return -1;
02851 
02852    bio->linelength++;
02853 
02854    return 1;
02855 }
02856 
02857 static int base_encode(char *filename, FILE *so)
02858 {
02859    unsigned char dtable[BASEMAXINLINE];
02860    int i,hiteof= 0;
02861    FILE *fi;
02862    struct baseio bio;
02863 
02864    memset(&bio, 0, sizeof(bio));
02865    bio.iocp = BASEMAXINLINE;
02866 
02867    if (!(fi = fopen(filename, "rb"))) {
02868       ast_log(LOG_WARNING, "Failed to open file: %s: %s\n", filename, strerror(errno));
02869       return -1;
02870    }
02871 
02872    for (i= 0;i<9;i++) {
02873       dtable[i]= 'A'+i;
02874       dtable[i+9]= 'J'+i;
02875       dtable[26+i]= 'a'+i;
02876       dtable[26+i+9]= 'j'+i;
02877    }
02878    for (i= 0;i<8;i++) {
02879       dtable[i+18]= 'S'+i;
02880       dtable[26+i+18]= 's'+i;
02881    }
02882    for (i= 0;i<10;i++) {
02883       dtable[52+i]= '0'+i;
02884    }
02885    dtable[62]= '+';
02886    dtable[63]= '/';
02887 
02888    while (!hiteof){
02889       unsigned char igroup[3],ogroup[4];
02890       int c,n;
02891 
02892       igroup[0]= igroup[1]= igroup[2]= 0;
02893 
02894       for (n= 0;n<3;n++) {
02895          if ((c = inchar(&bio, fi)) == EOF) {
02896             hiteof= 1;
02897             break;
02898          }
02899 
02900          igroup[n]= (unsigned char)c;
02901       }
02902 
02903       if (n> 0) {
02904          ogroup[0]= dtable[igroup[0]>>2];
02905          ogroup[1]= dtable[((igroup[0]&3)<<4)|(igroup[1]>>4)];
02906          ogroup[2]= dtable[((igroup[1]&0xF)<<2)|(igroup[2]>>6)];
02907          ogroup[3]= dtable[igroup[2]&0x3F];
02908 
02909          if (n<3) {
02910             ogroup[3]= '=';
02911 
02912             if (n<2)
02913                ogroup[2]= '=';
02914          }
02915 
02916          for (i= 0;i<4;i++)
02917             ochar(&bio, ogroup[i], so);
02918       }
02919    }
02920 
02921    fclose(fi);
02922    
02923    if (fputs(eol,so)==EOF)
02924       return 0;
02925 
02926    return 1;
02927 }
02928 
02929 static void prep_email_sub_vars(struct ast_channel *ast, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, char *dur, char *date, char *passdata, size_t passdatasize, const char *category)
02930 {
02931    char callerid[256];
02932    /* Prepare variables for substition in email body and subject */
02933    pbx_builtin_setvar_helper(ast, "VM_NAME", vmu->fullname);
02934    pbx_builtin_setvar_helper(ast, "VM_DUR", dur);
02935    snprintf(passdata, passdatasize, "%d", msgnum);
02936    pbx_builtin_setvar_helper(ast, "VM_MSGNUM", passdata);
02937    pbx_builtin_setvar_helper(ast, "VM_CONTEXT", context);
02938    pbx_builtin_setvar_helper(ast, "VM_MAILBOX", mailbox);
02939    pbx_builtin_setvar_helper(ast, "VM_CALLERID", (!ast_strlen_zero(cidname) || !ast_strlen_zero(cidnum)) ?
02940       ast_callerid_merge(callerid, sizeof(callerid), cidname, cidnum, NULL) : "an unknown caller");
02941    pbx_builtin_setvar_helper(ast, "VM_CIDNAME", (!ast_strlen_zero(cidname) ? cidname : "an unknown caller"));
02942    pbx_builtin_setvar_helper(ast, "VM_CIDNUM", (!ast_strlen_zero(cidnum) ? cidnum : "an unknown caller"));
02943    pbx_builtin_setvar_helper(ast, "VM_DATE", date);
02944    pbx_builtin_setvar_helper(ast, "VM_CATEGORY", category ? ast_strdupa(category) : "no category");
02945 }
02946 
02947 static char *quote(const char *from, char *to, size_t len)
02948 {
02949    char *ptr = to;
02950    *ptr++ = '"';
02951    for (; ptr < to + len - 1; from++) {
02952       if (*from == '"')
02953          *ptr++ = '\\';
02954       else if (*from == '\0')
02955          break;
02956       *ptr++ = *from;
02957    }
02958    if (ptr < to + len - 1)
02959       *ptr++ = '"';
02960    *ptr = '\0';
02961    return to;
02962 }
02963 /*
02964  * fill in *tm for current time according to the proper timezone, if any.
02965  * Return tm so it can be used as a function argument.
02966  */
02967 static const struct tm *vmu_tm(const struct ast_vm_user *vmu, struct tm *tm)
02968 {
02969    const struct vm_zone *z = NULL;
02970    time_t t = time(NULL);
02971 
02972    /* Does this user have a timezone specified? */
02973    if (!ast_strlen_zero(vmu->zonetag)) {
02974       /* Find the zone in the list */
02975       AST_LIST_LOCK(&zones);
02976       AST_LIST_TRAVERSE(&zones, z, list) {
02977          if (!strcmp(z->name, vmu->zonetag))
02978             break;
02979       }
02980       AST_LIST_UNLOCK(&zones);
02981    }
02982    ast_localtime(&t, tm, z ? z->timezone : NULL);
02983    return tm;
02984 }
02985 
02986 /*!\brief Check if the string would need encoding within the MIME standard, to
02987  * avoid confusing certain mail software that expects messages to be 7-bit
02988  * clean.
02989  */
02990 static int check_mime(const char *str)
02991 {
02992    for (; *str; str++) {
02993       if (*str > 126 || *str < 32 || strchr("()<>@,:;/\"[]?.=", *str)) {
02994          return 1;
02995       }
02996    }
02997    return 0;
02998 }
02999 
03000 /*!\brief Encode a string according to the MIME rules for encoding strings
03001  * that are not 7-bit clean or contain control characters.
03002  *
03003  * Additionally, if the encoded string would exceed the MIME limit of 76
03004  * characters per line, then the encoding will be broken up into multiple
03005  * sections, separated by a space character, in order to facilitate
03006  * breaking up the associated header across multiple lines.
03007  *
03008  * \param start A string to be encoded
03009  * \param end An expandable buffer for holding the result
03010  * \param preamble The length of the first line already used for this string,
03011  * to ensure that each line maintains a maximum length of 76 chars.
03012  * \param postamble the length of any additional characters appended to the
03013  * line, used to ensure proper field wrapping.
03014  * \retval The encoded string.
03015  */
03016 static char *encode_mime_str(const char *start, char *end, size_t endsize, size_t preamble, size_t postamble)
03017 {
03018    char tmp[80];
03019    int first_section = 1;
03020    size_t endlen = 0, tmplen = 0;
03021    *end = '\0';
03022 
03023    tmplen = snprintf(tmp, sizeof(tmp), "=?%s?Q?", charset);
03024    for (; *start; start++) {
03025       int need_encoding = 0;
03026       if (*start < 33 || *start > 126 || strchr("()<>@,:;/\"[]?.=_", *start)) {
03027          need_encoding = 1;
03028       }
03029       if ((first_section && need_encoding && preamble + tmplen > 70) ||
03030          (first_section && !need_encoding && preamble + tmplen > 72) ||
03031          (!first_section && need_encoding && tmplen > 70) ||
03032          (!first_section && !need_encoding && tmplen > 72)) {
03033          /* Start new line */
03034          endlen += snprintf(end + endlen, endsize - endlen, "%s%s?=", first_section ? "" : " ", tmp);
03035          tmplen = snprintf(tmp, sizeof(tmp), "=?%s?Q?", charset);
03036          first_section = 0;
03037       }
03038       if (need_encoding && *start == ' ') {
03039          tmplen += snprintf(tmp + tmplen, sizeof(tmp) - tmplen, "_");
03040       } else if (need_encoding) {
03041          tmplen += snprintf(tmp + tmplen, sizeof(tmp) - tmplen, "=%hhX", *start);
03042       } else {
03043          tmplen += snprintf(tmp + tmplen, sizeof(tmp) - tmplen, "%c", *start);
03044       }
03045    }
03046    snprintf(end + endlen, endsize - endlen, "%s%s?=%s", first_section ? "" : " ", tmp, endlen + postamble > 74 ? " " : "");
03047    return end;
03048 }
03049 
03050 static void make_email_file(FILE *p, char *srcemail, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, char *attach, char *format, int duration, int attach_user_voicemail, struct ast_channel *chan, const char *category, int imap)
03051 {
03052    char date[256];
03053    char host[MAXHOSTNAMELEN] = "";
03054    char who[256];
03055    char bound[256];
03056    char fname[256];
03057    char dur[256];
03058    char tmpcmd[256];
03059    char enc_cidnum[256] = "", enc_cidname[256] = "";
03060    struct tm tm;
03061    char *passdata = NULL, *passdata2;
03062    size_t len_passdata = 0, len_passdata2, tmplen;
03063 #ifdef IMAP_STORAGE
03064 #define ENDL "\r\n"
03065 #else
03066 #define ENDL "\n"
03067 #endif
03068 
03069    /* One alloca for multiple fields */
03070    len_passdata2 = strlen(vmu->fullname);
03071    if (emailsubject && (tmplen = strlen(emailsubject)) > len_passdata2) {
03072       len_passdata2 = tmplen;
03073    }
03074    if ((tmplen = strlen(emailtitle)) > len_passdata2) {
03075       len_passdata2 = tmplen;
03076    }
03077    if ((tmplen = strlen(fromstring)) > len_passdata2) {
03078       len_passdata2 = tmplen;
03079    }
03080    len_passdata2 = len_passdata2 * 3 + 200;
03081    passdata2 = alloca(len_passdata2);
03082 
03083    if (cidnum) {
03084       strip_control(cidnum, enc_cidnum, sizeof(enc_cidnum));
03085    }
03086    if (cidname) {
03087       strip_control(cidname, enc_cidname, sizeof(enc_cidname));
03088    }
03089    gethostname(host, sizeof(host) - 1);
03090    if (strchr(srcemail, '@'))
03091       ast_copy_string(who, srcemail, sizeof(who));
03092    else {
03093       snprintf(who, sizeof(who), "%s@%s", srcemail, host);
03094    }
03095    snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
03096    strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm));
03097    fprintf(p, "Date: %s" ENDL, date);
03098 
03099    /* Set date format for voicemail mail */
03100    strftime(date, sizeof(date), emaildateformat, &tm);
03101 
03102    if (*fromstring) {
03103       struct ast_channel *ast;
03104       if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Substitution/voicemail"))) {
03105          char *ptr;
03106          memset(passdata2, 0, len_passdata2);
03107          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, enc_cidnum, enc_cidname, dur, date, passdata2, len_passdata2, category);
03108          pbx_substitute_variables_helper(ast, fromstring, passdata2, len_passdata2);
03109          len_passdata = strlen(passdata2) * 3 + 300;
03110          passdata = alloca(len_passdata);
03111          if (check_mime(passdata2)) {
03112             int first_line = 1;
03113             encode_mime_str(passdata2, passdata, len_passdata, strlen("From: "), strlen(who) + 3);
03114             while ((ptr = strchr(passdata, ' '))) {
03115                *ptr = '\0';
03116                fprintf(p, "%s %s" ENDL, first_line ? "From:" : "", passdata);
03117                first_line = 0;
03118                passdata = ptr + 1;
03119             }
03120             fprintf(p, "%s %s <%s>" ENDL, first_line ? "From:" : "", passdata, who);
03121          } else {
03122             fprintf(p, "From: %s <%s>" ENDL, quote(passdata2, passdata, len_passdata), who);
03123          }
03124          ast_channel_free(ast);
03125       } else
03126          ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
03127    } else
03128       fprintf(p, "From: Asterisk PBX <%s>" ENDL, who);
03129 
03130    if (check_mime(vmu->fullname)) {
03131       int first_line = 1;
03132       char *ptr;
03133       encode_mime_str(vmu->fullname, passdata2, len_passdata2, strlen("To: "), strlen(vmu->email) + 3);
03134       while ((ptr = strchr(passdata2, ' '))) {
03135          *ptr = '\0';
03136          fprintf(p, "%s %s" ENDL, first_line ? "To:" : "", passdata2);
03137          first_line = 0;
03138          passdata2 = ptr + 1;
03139       }
03140       fprintf(p, "%s %s <%s>" ENDL, first_line ? "To:" : "", passdata2, vmu->email);
03141    } else {
03142       fprintf(p, "To: %s <%s>" ENDL, quote(vmu->fullname, passdata2, len_passdata2), vmu->email);
03143    }
03144    if (emailsubject) {
03145       struct ast_channel *ast;
03146       if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Substitution/voicemail"))) {
03147          int vmlen = strlen(emailsubject) * 3 + 200;
03148          /* Only allocate more space if the previous was not large enough */
03149          if (vmlen > len_passdata) {
03150             passdata = alloca(vmlen);
03151             len_passdata = vmlen;
03152          }
03153 
03154          memset(passdata, 0, len_passdata);
03155          prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, len_passdata, category);
03156          pbx_substitute_variables_helper(ast, emailsubject, passdata, len_passdata);
03157          if (check_mime(passdata)) {
03158             int first_line = 1;
03159             char *ptr;
03160             encode_mime_str(passdata, passdata2, len_passdata2, strlen("Subject: "), 0);
03161             while ((ptr = strchr(passdata2, ' '))) {
03162                *ptr = '\0';
03163                fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", passdata2);
03164                first_line = 0;
03165                passdata2 = ptr + 1;
03166             }
03167             fprintf(p, "%s %s" ENDL, first_line ? "Subject:" : "", passdata2);
03168          } else {
03169             fprintf(p, "Subject: %s" ENDL, passdata);
03170          }
03171          ast_channel_free(ast);
03172       } else {
03173          ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
03174       }
03175    } else   if (*emailtitle) {
03176       fprintf(p, emailtitle, msgnum + 1, mailbox) ;
03177       fprintf(p, ENDL) ;
03178    } else if (ast_test_flag((&globalflags), VM_PBXSKIP)) {
03179       fprintf(p, "Subject: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
03180    } else {
03181       fprintf(p, "Subject: [PBX]: New message %d in mailbox %s" ENDL, msgnum + 1, mailbox);
03182    }
03183    fprintf(p, "Message-ID: <Asterisk-%d-%d-%s-%d@%s>" ENDL, msgnum + 1, (unsigned int)ast_random(), mailbox, (int)getpid(), host);
03184    if (imap) {
03185       /* additional information needed for IMAP searching */
03186       fprintf(p, "X-Asterisk-VM-Message-Num: %d" ENDL, msgnum + 1);
03187       /* fprintf(p, "X-Asterisk-VM-Orig-Mailbox: %s" ENDL, ext); */
03188       fprintf(p, "X-Asterisk-VM-Server-Name: %s" ENDL, fromstring);
03189       fprintf(p, "X-Asterisk-VM-Context: %s" ENDL, context);
03190       fprintf(p, "X-Asterisk-VM-Extension: %s" ENDL, mailbox);
03191       fprintf(p, "X-Asterisk-VM-Priority: %d" ENDL, chan->priority);
03192       fprintf(p, "X-Asterisk-VM-Caller-channel: %s" ENDL, chan->name);
03193       fprintf(p, "X-Asterisk-VM-Caller-ID-Num: %s" ENDL, enc_cidnum);
03194       fprintf(p, "X-Asterisk-VM-Caller-ID-Name: %s" ENDL, enc_cidname);
03195       fprintf(p, "X-Asterisk-VM-Duration: %d" ENDL, duration);
03196       if (!ast_strlen_zero(category)) {
03197          fprintf(p, "X-Asterisk-VM-Category: %s" ENDL, category);
03198       }
03199       fprintf(p, "X-Asterisk-VM-Orig-date: %s" ENDL, date);
03200       fprintf(p, "X-Asterisk-VM-Orig-time: %ld" ENDL, (long)time(NULL));
03201    }
03202    if (!ast_strlen_zero(cidnum)) {
03203       fprintf(p, "X-Asterisk-CallerID: %s" ENDL, enc_cidnum);
03204    }
03205    if (!ast_strlen_zero(cidname)) {
03206       fprintf(p, "X-Asterisk-CallerIDName: %s" ENDL, enc_cidname);
03207    }
03208    fprintf(p, "MIME-Version: 1.0" ENDL);
03209    if (attach_user_voicemail) {
03210       /* Something unique. */
03211       snprintf(bound, sizeof(bound), "----voicemail_%d%s%d%d", msgnum + 1, mailbox, (int)getpid(), (unsigned int)ast_random());
03212 
03213       fprintf(p, "Content-Type: multipart/mixed; boundary=\"%s\"" ENDL, bound);
03214       fprintf(p, ENDL ENDL "This is a multi-part message in MIME format." ENDL ENDL);
03215       fprintf(p, "--%s" ENDL, bound);
03216    }
03217    fprintf(p, "Content-Type: text/plain; charset=%s" ENDL "Content-Transfer-Encoding: 8bit" ENDL ENDL, charset);
03218    if (emailbody) {
03219       struct ast_channel *ast;
03220       if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Substitution/voicemail"))) {
03221          char *passdata;
03222          int vmlen = strlen(emailbody)*3 + 200;
03223          if ((passdata = alloca(vmlen))) {
03224             memset(passdata, 0, vmlen);
03225             prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
03226             pbx_substitute_variables_helper(ast, emailbody, passdata, vmlen);
03227             fprintf(p, "%s" ENDL, passdata);
03228          } else
03229             ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
03230          ast_channel_free(ast);
03231       } else
03232          ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
03233    } else {
03234       fprintf(p, "Dear %s:" ENDL ENDL "\tJust wanted to let you know you were just left a %s long message (number %d)" ENDL
03235 
03236       "in mailbox %s from %s, on %s so you might" ENDL
03237       "want to check it when you get a chance.  Thanks!" ENDL ENDL "\t\t\t\t--Asterisk" ENDL ENDL, vmu->fullname, 
03238       dur, msgnum + 1, mailbox, (cidname ? cidname : (cidnum ? cidnum : "an unknown caller")), date);
03239    }
03240    if (attach_user_voicemail) {
03241       /* Eww. We want formats to tell us their own MIME type */
03242       char *ctype = (!strcasecmp(format, "ogg")) ? "application/" : "audio/x-";
03243       char tmpdir[256], newtmp[256];
03244       int tmpfd = -1;
03245    
03246       if (vmu->volgain < -.001 || vmu->volgain > .001) {
03247          create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, vmu->mailbox, "tmp");
03248          snprintf(newtmp, sizeof(newtmp), "%s/XXXXXX", tmpdir);
03249          tmpfd = mkstemp(newtmp);
03250          chmod(newtmp, VOICEMAIL_FILE_MODE & ~my_umask);
03251          if (option_debug > 2)
03252             ast_log(LOG_DEBUG, "newtmp: %s\n", newtmp);
03253          if (tmpfd > -1) {
03254             int soxstatus;
03255             snprintf(tmpcmd, sizeof(tmpcmd), "sox -v %.4f %s.%s %s.%s", vmu->volgain, attach, format, newtmp, format);
03256             if ((soxstatus = ast_safe_system(tmpcmd)) == 0) {
03257                attach = newtmp;
03258                if (option_debug > 2) {
03259                   ast_log(LOG_DEBUG, "VOLGAIN: Stored at: %s.%s - Level: %.4f - Mailbox: %s\n", attach, format, vmu->volgain, mailbox);
03260                }
03261             } else {
03262                ast_log(LOG_WARNING, "Sox failed to reencode %s.%s: %s (have you installed support for all sox file formats?)\n", attach, format,
03263                   soxstatus == 1 ? "Problem with command line options" : "An error occurred during file processing");
03264                ast_log(LOG_WARNING, "Voicemail attachment will have no volume gain.\n");
03265             }
03266          }
03267       }
03268       fprintf(p, "--%s" ENDL, bound);
03269       fprintf(p, "Content-Type: %s%s; name=\"msg%04d.%s\"" ENDL, ctype, format, msgnum + 1, format);
03270       fprintf(p, "Content-Transfer-Encoding: base64" ENDL);
03271       fprintf(p, "Content-Description: Voicemail sound attachment." ENDL);
03272       fprintf(p, "Content-Disposition: attachment; filename=\"msg%04d.%s\"" ENDL ENDL, msgnum + 1, format);
03273       snprintf(fname, sizeof(fname), "%s.%s", attach, format);
03274       base_encode(fname, p);
03275       fprintf(p, ENDL "--%s--" ENDL "." ENDL, bound);
03276       if (tmpfd > -1) {
03277          unlink(fname);
03278          close(tmpfd);
03279          unlink(newtmp);
03280       }
03281    }
03282 #undef ENDL
03283 }
03284 static int sendmail(char *srcemail, struct ast_vm_user *vmu, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, char *attach, char *format, int duration, int attach_user_voicemail, struct ast_channel *chan, const char *category)
03285 {
03286    FILE *p=NULL;
03287    char tmp[80] = "/tmp/astmail-XXXXXX";
03288    char tmp2[256];
03289 
03290    if (vmu && ast_strlen_zero(vmu->email)) {
03291       ast_log(LOG_WARNING, "E-mail address missing for mailbox [%s].  E-mail will not be sent.\n", vmu->mailbox);
03292       return(0);
03293    }
03294    if (!strcmp(format, "wav49"))
03295       format = "WAV";
03296    if (option_debug > 2)
03297       ast_log(LOG_DEBUG, "Attaching file '%s', format '%s', uservm is '%d', global is %d\n", attach, format, attach_user_voicemail, ast_test_flag((&globalflags), VM_ATTACH));
03298    /* Make a temporary file instead of piping directly to sendmail, in case the mail
03299       command hangs */
03300    if ((p = vm_mkftemp(tmp)) == NULL) {
03301       ast_log(LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
03302       return -1;
03303    } else {
03304       make_email_file(p, srcemail, vmu, msgnum, context, mailbox, cidnum, cidname, attach, format, duration, attach_user_voicemail, chan, category, 0);
03305       fclose(p);
03306       snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
03307       ast_safe_system(tmp2);
03308       if (option_debug > 2)
03309          ast_log(LOG_DEBUG, "Sent mail to %s with command '%s'\n", vmu->email, mailcmd);
03310    }
03311    return 0;
03312 }
03313 
03314 static int sendpage(char *srcemail, char *pager, int msgnum, char *context, char *mailbox, char *cidnum, char *cidname, int duration, struct ast_vm_user *vmu, const char *category)
03315 {
03316    char date[256];
03317    char host[MAXHOSTNAMELEN] = "";
03318    char who[256];
03319    char dur[PATH_MAX];
03320    char tmp[80] = "/tmp/astmail-XXXXXX";
03321    char tmp2[PATH_MAX];
03322    struct tm tm;
03323    FILE *p;
03324 
03325    if ((p = vm_mkftemp(tmp)) == NULL) {
03326       ast_log(LOG_WARNING, "Unable to launch '%s' (can't create temporary file)\n", mailcmd);
03327       return -1;
03328    } else {
03329       gethostname(host, sizeof(host)-1);
03330       if (strchr(srcemail, '@'))
03331          ast_copy_string(who, srcemail, sizeof(who));
03332       else {
03333          snprintf(who, sizeof(who), "%s@%s", srcemail, host);
03334       }
03335       snprintf(dur, sizeof(dur), "%d:%02d", duration / 60, duration % 60);
03336       strftime(date, sizeof(date), "%a, %d %b %Y %H:%M:%S %z", vmu_tm(vmu, &tm));
03337       fprintf(p, "Date: %s\n", date);
03338 
03339       if (*pagerfromstring) {
03340          struct ast_channel *ast;
03341          if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Substitution/voicemail"))) {
03342             char *passdata;
03343             int vmlen = strlen(fromstring)*3 + 200;
03344             if ((passdata = alloca(vmlen))) {
03345                memset(passdata, 0, vmlen);
03346                prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
03347                pbx_substitute_variables_helper(ast, pagerfromstring, passdata, vmlen);
03348                fprintf(p, "From: %s <%s>\n", passdata, who);
03349             } else 
03350                ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
03351             ast_channel_free(ast);
03352          } else ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
03353       } else
03354          fprintf(p, "From: Asterisk PBX <%s>\n", who);
03355       fprintf(p, "To: %s\n", pager);
03356       if (pagersubject) {
03357          struct ast_channel *ast;
03358          if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Substitution/voicemail"))) {
03359             char *passdata;
03360             int vmlen = strlen(pagersubject) * 3 + 200;
03361             if ((passdata = alloca(vmlen))) {
03362                memset(passdata, 0, vmlen);
03363                prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
03364                pbx_substitute_variables_helper(ast, pagersubject, passdata, vmlen);
03365                fprintf(p, "Subject: %s\n\n", passdata);
03366             } else ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
03367             ast_channel_free(ast);
03368          } else ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
03369       } else
03370          fprintf(p, "Subject: New VM\n\n");
03371       strftime(date, sizeof(date), "%A, %B %d, %Y at %r", &tm);
03372       if (pagerbody) {
03373          struct ast_channel *ast;
03374          if ((ast = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, "", "", "", 0, "Substitution/voicemail"))) {
03375             char *passdata;
03376             int vmlen = strlen(pagerbody)*3 + 200;
03377             if ((passdata = alloca(vmlen))) {
03378                memset(passdata, 0, vmlen);
03379                prep_email_sub_vars(ast, vmu, msgnum + 1, context, mailbox, cidnum, cidname, dur, date, passdata, vmlen, category);
03380                pbx_substitute_variables_helper(ast, pagerbody, passdata, vmlen);
03381                fprintf(p, "%s\n", passdata);
03382             } else ast_log(LOG_WARNING, "Cannot allocate workspace for variable substitution\n");
03383          ast_channel_free(ast);
03384          } else ast_log(LOG_WARNING, "Cannot allocate the channel for variables substitution\n");
03385       } else {
03386          fprintf(p, "New %s long msg in box %s\n"
03387                "from %s, on %s", dur, mailbox, (cidname ? cidname : (cidnum ? cidnum : "unknown")), date);
03388       }
03389       fclose(p);
03390       snprintf(tmp2, sizeof(tmp2), "( %s < %s ; rm -f %s ) &", mailcmd, tmp, tmp);
03391       ast_safe_system(tmp2);
03392       if (option_debug > 2)
03393          ast_log(LOG_DEBUG, "Sent page to %s with command '%s'\n", pager, mailcmd);
03394    }
03395    return 0;
03396 }
03397 
03398 static int get_date(char *s, int len)
03399 {
03400    struct tm tm;
03401    time_t t;
03402 
03403    time(&t);
03404 
03405    ast_localtime(&t, &tm, NULL);
03406 
03407    return strftime(s, len, "%a %b %e %r %Z %Y", &tm);
03408 }
03409 
03410 static int play_greeting(struct ast_channel *chan, struct ast_vm_user *vmu, char *filename, char *ecodes)
03411 {
03412    int res = -2;
03413 
03414 #ifdef ODBC_STORAGE
03415    int success = 
03416 #endif
03417    RETRIEVE(filename, -1, vmu);
03418    if (ast_fileexists(filename, NULL, NULL) > 0) {
03419       res = ast_streamfile(chan, filename, chan->language);
03420       if (res > -1) 
03421          res = ast_waitstream(chan, ecodes);
03422 #ifdef ODBC_STORAGE
03423       if (success == -1) {
03424          /* We couldn't retrieve the file from the database, but we found it on the file system. Let's put it in the database. */
03425          if (option_debug)
03426             ast_log(LOG_DEBUG, "Greeting not retrieved from database, but found in file storage. Inserting into database\n");
03427          store_file(filename, vmu->mailbox, vmu->context, -1);
03428       }
03429 #endif
03430    }
03431    DISPOSE(filename, -1);
03432 
03433    return res;
03434 }
03435 
03436 static int invent_message(struct ast_channel *chan, struct ast_vm_user *vmu, char *ext, int busy, char *ecodes)
03437 {
03438    int res;
03439    char fn[PATH_MAX];
03440    char dest[PATH_MAX];
03441 
03442    snprintf(fn, sizeof(fn), "%s%s/%s/greet", VM_SPOOL_DIR, vmu->context, ext);
03443 
03444    if ((res = create_dirpath(dest, sizeof(dest), vmu->context, ext, "greet"))) {
03445       ast_log(LOG_WARNING, "Failed to make directory(%s)\n", fn);
03446       return -1;
03447    }
03448 
03449    res = play_greeting(chan, vmu, fn, ecodes);
03450    if (res == -2) {
03451       /* File did not exist */
03452       res = ast_stream_and_wait(chan, "vm-theperson", chan->language, ecodes);
03453       if (res)
03454          return res;
03455       res = ast_say_digit_str(chan, ext, ecodes, chan->language);
03456    }
03457 
03458    if (res)
03459       return res;
03460 
03461    res = ast_stream_and_wait(chan, busy ? "vm-isonphone" : "vm-isunavail", chan->language, ecodes);
03462    return res;
03463 }
03464 
03465 static void free_zone(struct vm_zone *z)
03466 {
03467    free(z);
03468 }
03469 
03470 #ifdef ODBC_STORAGE
03471 /*! XXX \todo Fix this function to support multiple mailboxes in the intput string */
03472 static int inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
03473 {
03474    int x = -1;
03475    int res;
03476    SQLHSTMT stmt;
03477    char sql[PATH_MAX];
03478    char rowdata[20];
03479    char tmp[PATH_MAX] = "";
03480    struct odbc_obj *obj;
03481    char *context;
03482    struct generic_prepare_struct gps = { .sql = sql, .argc = 0 };
03483 
03484    if (newmsgs)
03485       *newmsgs = 0;
03486    if (oldmsgs)
03487       *oldmsgs = 0;
03488 
03489    /* If no mailbox, return immediately */
03490    if (ast_strlen_zero(mailbox))
03491       return 0;
03492 
03493    ast_copy_string(tmp, mailbox, sizeof(tmp));
03494    
03495    context = strchr(tmp, '@');
03496    if (context) {
03497       *context = '\0';
03498       context++;
03499    } else
03500       context = "default";
03501    
03502    obj = ast_odbc_request_obj(odbc_database, 0);
03503    if (obj) {
03504       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "INBOX");
03505       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03506       if (!stmt) {
03507          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03508          ast_odbc_release_obj(obj);
03509          goto yuck;
03510       }
03511       res = SQLFetch(stmt);
03512       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03513          ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
03514          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03515          ast_odbc_release_obj(obj);
03516          goto yuck;
03517       }
03518       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
03519       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03520          ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
03521          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03522          ast_odbc_release_obj(obj);
03523          goto yuck;
03524       }
03525       *newmsgs = atoi(rowdata);
03526       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03527 
03528       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, tmp, "Old");
03529       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03530       if (!stmt) {
03531          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03532          ast_odbc_release_obj(obj);
03533          goto yuck;
03534       }
03535       res = SQLFetch(stmt);
03536       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03537          ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
03538          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03539          ast_odbc_release_obj(obj);
03540          goto yuck;
03541       }
03542       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
03543       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03544          ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
03545          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03546          ast_odbc_release_obj(obj);
03547          goto yuck;
03548       }
03549       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03550       ast_odbc_release_obj(obj);
03551       *oldmsgs = atoi(rowdata);
03552       x = 0;
03553    } else
03554       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03555       
03556 yuck: 
03557    return x;
03558 }
03559 
03560 static int messagecount(const char *context, const char *mailbox, const char *folder)
03561 {
03562    struct odbc_obj *obj = NULL;
03563    int nummsgs = 0;
03564    int res;
03565    SQLHSTMT stmt = NULL;
03566    char sql[PATH_MAX];
03567    char rowdata[20];
03568    struct generic_prepare_struct gps = { .sql = sql, .argc = 0 };
03569    if (!folder)
03570       folder = "INBOX";
03571    /* If no mailbox, return immediately */
03572    if (ast_strlen_zero(mailbox))
03573       return 0;
03574 
03575    obj = ast_odbc_request_obj(odbc_database, 0);
03576    if (obj) {
03577       snprintf(sql, sizeof(sql), "SELECT COUNT(*) FROM %s WHERE dir = '%s%s/%s/%s'", odbc_table, VM_SPOOL_DIR, context, mailbox, folder);
03578       stmt = ast_odbc_prepare_and_execute(obj, generic_prepare, &gps);
03579       if (!stmt) {
03580          ast_log(LOG_WARNING, "SQL Execute error!\n[%s]\n\n", sql);
03581          goto yuck;
03582       }
03583       res = SQLFetch(stmt);
03584       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03585          ast_log(LOG_WARNING, "SQL Fetch error!\n[%s]\n\n", sql);
03586          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03587          goto yuck;
03588       }
03589       res = SQLGetData(stmt, 1, SQL_CHAR, rowdata, sizeof(rowdata), NULL);
03590       if ((res != SQL_SUCCESS) && (res != SQL_SUCCESS_WITH_INFO)) {
03591          ast_log(LOG_WARNING, "SQL Get Data error!\n[%s]\n\n", sql);
03592          SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03593          goto yuck;
03594       }
03595       nummsgs = atoi(rowdata);
03596       SQLFreeHandle (SQL_HANDLE_STMT, stmt);
03597    } else
03598       ast_log(LOG_WARNING, "Failed to obtain database object for '%s'!\n", odbc_database);
03599 
03600 yuck:
03601    if (obj)
03602       ast_odbc_release_obj(obj);
03603    return nummsgs;
03604 }
03605 
03606 static int has_voicemail(const char *mailbox, const char *folder)
03607 {
03608    char tmp[256], *tmp2 = tmp, *mbox, *context;
03609    ast_copy_string(tmp, mailbox, sizeof(tmp));
03610    while ((context = mbox = strsep(&tmp2, ","))) {
03611       strsep(&context, "@");
03612       if (ast_strlen_zero(context))
03613          context = "default";
03614       if (messagecount(context, mbox, folder))
03615          return 1;
03616    }
03617    return 0;
03618 }
03619 #endif
03620 #ifndef IMAP_STORAGE
03621 /* copy message only used by file storage */
03622 static int copy_message(struct ast_channel *chan, struct ast_vm_user *vmu, int imbox, int msgnum, long duration, struct ast_vm_user *recip, char *fmt, char *dir)
03623 {
03624    char fromdir[PATH_MAX], todir[PATH_MAX], frompath[PATH_MAX], topath[PATH_MAX];
03625    const char *frombox = mbox(imbox);
03626    int recipmsgnum;
03627 
03628    ast_log(LOG_NOTICE, "Copying message from %s@%s to %s@%s\n", vmu->mailbox, vmu->context, recip->mailbox, recip->context);
03629 
03630    create_dirpath(todir, sizeof(todir), recip->context, recip->mailbox, "INBOX");
03631    
03632    if (!dir)
03633       make_dir(fromdir, sizeof(fromdir), vmu->context, vmu->mailbox, frombox);
03634    else
03635       ast_copy_string(fromdir, dir, sizeof(fromdir));
03636 
03637    make_file(frompath, sizeof(frompath), fromdir, msgnum);
03638 
03639    if (vm_lock_path(todir))
03640       return ERROR_LOCK_PATH;
03641 
03642    recipmsgnum = 0;
03643    do {
03644       make_file(topath, sizeof(topath), todir, recipmsgnum);
03645       if (!EXISTS(todir, recipmsgnum, topath, chan->language))
03646          break;
03647       recipmsgnum++;
03648    } while (recipmsgnum < recip->maxmsg);
03649    if (recipmsgnum < recip->maxmsg) {
03650       if (EXISTS(fromdir, msgnum, frompath, chan->language)) {
03651          COPY(fromdir, msgnum, todir, recipmsgnum, recip->mailbox, recip->context, frompath, topath);
03652       } else {
03653          /* For ODBC storage, if the file we want to copy isn't yet in the database, then the SQL
03654           * copy will fail. Instead, we need to create a local copy, store it, and delete the local
03655           * copy. We don't have to #ifdef this because if file storage reaches this point, there's a
03656           * much worse problem happening and IMAP storage doesn't call this function
03657           */
03658          copy_plain_file(frompath, topath);
03659          STORE(todir, recip->mailbox, recip->context, recipmsgnum, chan, recip, fmt, duration, NULL);
03660          vm_delete(topath);
03661       }
03662    } else {
03663       ast_log(LOG_ERROR, "Recipient mailbox %s@%s is full\n", recip->mailbox, recip->context);
03664    }
03665    ast_unlock_path(todir);
03666    notify_new_message(chan, recip, recipmsgnum, duration, fmt, S_OR(chan->cid.cid_num, NULL), S_OR(chan->cid.cid_name, NULL));
03667    
03668    return 0;
03669 }
03670 #endif
03671 #if !(defined(IMAP_STORAGE) || defined(ODBC_STORAGE))
03672 static int messagecount(const char *context, const char *mailbox, const char *folder)
03673 {
03674    return __has_voicemail(context, mailbox, folder, 0);
03675 }
03676 
03677 
03678 static int __has_voicemail(const char *context, const char *mailbox, const char *folder, int shortcircuit)
03679 {
03680    DIR *dir;
03681    struct dirent *de;
03682    char fn[256];
03683    int ret = 0;
03684    if (!folder)
03685       folder = "INBOX";
03686    /* If no mailbox, return immediately */
03687    if (ast_strlen_zero(mailbox))
03688       return 0;
03689    if (!context)
03690       context = "default";
03691    snprintf(fn, sizeof(fn), "%s%s/%s/%s", VM_SPOOL_DIR, context, mailbox, folder);
03692    dir = opendir(fn);
03693    if (!dir)
03694       return 0;
03695    while ((de = readdir(dir))) {
03696       if (!strncasecmp(de->d_name, "msg", 3)) {
03697          if (shortcircuit) {
03698             ret = 1;
03699             break;
03700          } else if (!strncasecmp(de->d_name + 8, "txt", 3))
03701             ret++;
03702       }
03703    }
03704    closedir(dir);
03705    return ret;
03706 }
03707 
03708 
03709 static int has_voicemail(const char *mailbox, const char *folder)
03710 {
03711    char tmp[256], *tmp2 = tmp, *mbox, *context;
03712    ast_copy_string(tmp, mailbox, sizeof(tmp));
03713    while ((mbox = strsep(&tmp2, ","))) {
03714       if ((context = strchr(mbox, '@')))
03715          *context++ = '\0';
03716       else
03717          context = "default";
03718       if (__has_voicemail(context, mbox, folder, 1))
03719          return 1;
03720    }
03721    return 0;
03722 }
03723 
03724 
03725 static int inboxcount(const char *mailbox, int *newmsgs, int *oldmsgs)
03726 {
03727    char tmp[256];
03728    char *context;
03729 
03730    if (newmsgs)
03731       *newmsgs = 0;
03732    if (oldmsgs)
03733       *oldmsgs = 0;
03734    /* If no mailbox, return immediately */
03735    if (ast_strlen_zero(mailbox))
03736       return 0;
03737    if (strchr(mailbox, ',')) {
03738       int tmpnew, tmpold;
03739       char *mb, *cur;
03740 
03741       ast_copy_string(tmp, mailbox, sizeof(tmp));
03742       mb = tmp;
03743       while ((cur = strsep(&mb, ", "))) {
03744          if (!ast_strlen_zero(cur)) {
03745             if (inboxcount(cur, newmsgs ? &tmpnew : NULL, oldmsgs ? &tmpold : NULL))
03746                return -1;
03747             else {
03748                if (newmsgs)
03749                   *newmsgs += tmpnew; 
03750                if (oldmsgs)
03751                   *oldmsgs += tmpold;
03752             }
03753          }
03754       }
03755       return 0;
03756    }
03757    ast_copy_string(tmp, mailbox, sizeof(tmp));
03758    context = strchr(tmp, '@');
03759    if (context) {
03760       *context = '\0';
03761       context++;
03762    } else
03763       context = "default";
03764    if (newmsgs)
03765       *newmsgs = __has_voicemail(context, tmp, "INBOX", 0);
03766    if (oldmsgs)
03767       *oldmsgs = __has_voicemail(context, tmp, "Old", 0);
03768    return 0;
03769 }
03770 
03771 #endif
03772 
03773 static void run_externnotify(char *context, char *extension)
03774 {
03775    char arguments[255];
03776    char ext_context[256] = "";
03777    int newvoicemails = 0, oldvoicemails = 0;
03778    struct ast_smdi_mwi_message *mwi_msg;
03779 
03780    if (!ast_strlen_zero(context))
03781       snprintf(ext_context, sizeof(ext_context), "%s@%s", extension, context);
03782    else
03783       ast_copy_string(ext_context, extension, sizeof(ext_context));
03784 
03785    if (!strcasecmp(externnotify, "smdi")) {
03786       if (ast_app_has_voicemail(ext_context, NULL)) 
03787          ast_smdi_mwi_set(smdi_iface, extension);
03788       else
03789          ast_smdi_mwi_unset(smdi_iface, extension);
03790 
03791       if ((mwi_msg = ast_smdi_mwi_message_wait_station(smdi_iface, SMDI_MWI_WAIT_TIMEOUT, extension))) {
03792          ast_log(LOG_ERROR, "Error executing SMDI MWI change for %s\n", extension);
03793          if (!strncmp(mwi_msg->cause, "INV", 3))
03794             ast_log(LOG_ERROR, "Invalid MWI extension: %s\n", mwi_msg->fwd_st);
03795          else if (!strncmp(mwi_msg->cause, "BLK", 3))
03796             ast_log(LOG_WARNING, "MWI light was already on or off for %s\n", mwi_msg->fwd_st);
03797          ast_log(LOG_WARNING, "The switch reported '%s'\n", mwi_msg->cause);
03798          ASTOBJ_UNREF(mwi_msg, ast_smdi_mwi_message_destroy);
03799       } else {
03800          if (option_debug)
03801             ast_log(LOG_DEBUG, "Successfully executed SMDI MWI change for %s\n", extension);
03802       }
03803    } else if (!ast_strlen_zero(externnotify)) {
03804       if (inboxcount(ext_context, &newvoicemails, &oldvoicemails)) {
03805          ast_log(LOG_ERROR, "Problem in calculating number of voicemail messages available for extension %s\n", extension);
03806       } else {
03807          snprintf(arguments, sizeof(arguments), "%s %s %s %d&", externnotify, context, extension, newvoicemails);
03808          if (option_debug)
03809             ast_log(LOG_DEBUG, "Executing %s\n", arguments);
03810          ast_safe_system(arguments);
03811       }
03812    }
03813 }
03814 
03815 struct leave_vm_options {
03816    unsigned int flags;
03817    signed char record_gain;
03818 };
03819 
03820 static int leave_voicemail(struct ast_channel *chan, char *ext, struct leave_vm_options *options)
03821 {
03822 #ifdef IMAP_STORAGE
03823    int newmsgs, oldmsgs;
03824 #endif
03825    struct vm_state *vms = NULL;
03826    char txtfile[PATH_MAX], tmptxtfile[PATH_MAX];
03827    char callerid[256];
03828    FILE *txt;
03829    char date[256];
03830    int txtdes;
03831    int res = 0;
03832    int msgnum;
03833    int duration = 0;
03834    int ausemacro = 0;
03835    int ousemacro = 0;
03836    int ouseexten = 0;
03837    char dir[PATH_MAX], tmpdir[PATH_MAX];
03838    char dest[PATH_MAX];
03839    char fn[PATH_MAX];
03840    char prefile[PATH_MAX] = "";
03841    char tempfile[PATH_MAX] = "";
03842    char ext_context[256] = "";
03843    char fmt[80];
03844    char *context;
03845    char ecodes[16] = "#";
03846    char tmp[1024] = "", *tmpptr;
03847    struct ast_vm_user *vmu;
03848    struct ast_vm_user svm;
03849    const char *category = NULL;
03850 
03851    ast_copy_string(tmp, ext, sizeof(tmp));
03852    ext = tmp;
03853    context = strchr(tmp, '@');
03854    if (context) {
03855       *context++ = '\0';
03856       tmpptr = strchr(context, '&');
03857    } else {
03858       tmpptr = strchr(ext, '&');
03859    }
03860 
03861    if (tmpptr)
03862       *tmpptr++ = '\0';
03863 
03864    category = pbx_builtin_getvar_helper(chan, "VM_CATEGORY");
03865 
03866    if (option_debug > 2)
03867       ast_log(LOG_DEBUG, "Before find_user\n");
03868    if (!(vmu = find_user(&svm, context, ext))) {
03869       ast_log(LOG_WARNING, "No entry in voicemail config file for '%s'\n", ext);
03870       if (ast_test_flag(options, OPT_PRIORITY_JUMP) || ast_opt_priority_jumping)
03871          ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101);
03872       pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
03873       return res;
03874    }
03875    /* Setup pre-file if appropriate */
03876    if (strcmp(vmu->context, "default"))
03877       snprintf(ext_context, sizeof(ext_context), "%s@%s", ext, vmu->context);
03878    else
03879       ast_copy_string(ext_context, vmu->mailbox, sizeof(ext_context));
03880    if (ast_test_flag(options, OPT_BUSY_GREETING)) {
03881       res = create_dirpath(dest, sizeof(dest), vmu->context, ext, "busy");
03882       snprintf(prefile, sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, ext);
03883    } else if (ast_test_flag(options, OPT_UNAVAIL_GREETING)) {
03884       res = create_dirpath(dest, sizeof(dest), vmu->context, ext, "unavail");
03885       snprintf(prefile, sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, ext);
03886    }
03887    snprintf(tempfile, sizeof(tempfile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, ext);
03888    if ((res = create_dirpath(dest, sizeof(dest), vmu->context, ext, "temp"))) {
03889       ast_log(LOG_WARNING, "Failed to make directory (%s)\n", tempfile);
03890       return -1;
03891    }
03892    RETRIEVE(tempfile, -1, vmu);
03893    if (ast_fileexists(tempfile, NULL, NULL) > 0)
03894       ast_copy_string(prefile, tempfile, sizeof(prefile));
03895    DISPOSE(tempfile, -1);
03896    /* It's easier just to try to make it than to check for its existence */
03897    create_dirpath(dir, sizeof(dir), vmu->context, ext, "INBOX");
03898    create_dirpath(tmpdir, sizeof(tmpdir), vmu->context, ext, "tmp");
03899 
03900    /* Check current or macro-calling context for special extensions */
03901    if (ast_test_flag(vmu, VM_OPERATOR)) {
03902       if (!ast_strlen_zero(vmu->exit)) {
03903          if (ast_exists_extension(chan, vmu->exit, "o", 1, chan->cid.cid_num)) {
03904             strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
03905             ouseexten = 1;
03906          }
03907       } else if (ast_exists_extension(chan, chan->context, "o", 1, chan->cid.cid_num)) {
03908          strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
03909          ouseexten = 1;
03910       }
03911       else if (!ast_strlen_zero(chan->macrocontext) && ast_exists_extension(chan, chan->macrocontext, "o", 1, chan->cid.cid_num)) {
03912       strncat(ecodes, "0", sizeof(ecodes) - strlen(ecodes) - 1);
03913       ousemacro = 1;
03914       }
03915    }
03916 
03917    if (!ast_strlen_zero(vmu->exit)) {
03918       if (ast_exists_extension(chan, vmu->exit, "a", 1, chan->cid.cid_num))
03919          strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
03920    } else if (ast_exists_extension(chan, chan->context, "a", 1, chan->cid.cid_num))
03921       strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
03922    else if (!ast_strlen_zero(chan->macrocontext) && ast_exists_extension(chan, chan->macrocontext, "a", 1, chan->cid.cid_num)) {
03923       strncat(ecodes, "*", sizeof(ecodes) - strlen(ecodes) - 1);
03924       ausemacro = 1;
03925    }
03926 
03927    /* Play the beginning intro if desired */
03928    if (!ast_strlen_zero(prefile)) {
03929       res = play_greeting(chan, vmu, prefile, ecodes);
03930       if (res == -2) {
03931          /* The file did not exist */
03932          if (option_debug)
03933             ast_log(LOG_DEBUG, "%s doesn't exist, doing what we can\n", prefile);
03934          res = invent_message(chan, vmu, ext, ast_test_flag(options, OPT_BUSY_GREETING), ecodes);
03935       }
03936       if (res < 0) {
03937          if (option_debug)
03938             ast_log(LOG_DEBUG, "Hang up during prefile playback\n");
03939          free_user(vmu);
03940          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
03941          return -1;
03942       }
03943    }
03944    if (res == '#') {
03945       /* On a '#' we skip the instructions */
03946       ast_set_flag(options, OPT_SILENT);
03947       res = 0;
03948    }
03949    if (!res && !ast_test_flag(options, OPT_SILENT)) {
03950       res = ast_stream_and_wait(chan, INTRO, chan->language, ecodes);
03951       if (res == '#') {
03952          ast_set_flag(options, OPT_SILENT);
03953          res = 0;
03954       }
03955    }
03956    if (res > 0)
03957       ast_stopstream(chan);
03958    /* Check for a '*' here in case the caller wants to escape from voicemail to something
03959     other than the operator -- an automated attendant or mailbox login for example */
03960    if (res == '*') {
03961       chan->exten[0] = 'a';
03962       chan->exten[1] = '\0';
03963       if (!ast_strlen_zero(vmu->exit)) {
03964          ast_copy_string(chan->context, vmu->exit, sizeof(chan->context));
03965       } else if (ausemacro && !ast_strlen_zero(chan->macrocontext)) {
03966          ast_copy_string(chan->context, chan->macrocontext, sizeof(chan->context));
03967       }
03968       chan->priority = 0;
03969       free_user(vmu);
03970       pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
03971       return 0;
03972    }
03973 
03974    /* Check for a '0' here */
03975    if (res == '0') {
03976    transfer:
03977       if (ouseexten || ousemacro) {
03978          chan->exten[0] = 'o';
03979          chan->exten[1] = '\0';
03980          if (!ast_strlen_zero(vmu->exit)) {
03981             ast_copy_string(chan->context, vmu->exit, sizeof(chan->context));
03982          } else if (ousemacro && !ast_strlen_zero(chan->macrocontext)) {
03983             ast_copy_string(chan->context, chan->macrocontext, sizeof(chan->context));
03984          }
03985          ast_play_and_wait(chan, "transfer");
03986          chan->priority = 0;
03987          free_user(vmu);
03988          pbx_builtin_setvar_helper(chan, "VMSTATUS", "USEREXIT");
03989       }
03990       return 0;
03991    }
03992    if (res < 0) {
03993       free_user(vmu);
03994       pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
03995       return -1;
03996    }
03997    /* The meat of recording the message...  All the announcements and beeps have been played*/
03998    ast_copy_string(fmt, vmfmts, sizeof(fmt));
03999    if (!ast_strlen_zero(fmt)) {
04000       msgnum = 0;
04001 
04002 #ifdef IMAP_STORAGE
04003       /* Is ext a mailbox? */
04004       /* must open stream for this user to get info! */
04005       res = inboxcount(ext_context, &newmsgs, &oldmsgs);
04006       if (res < 0) {
04007          ast_log(LOG_NOTICE,"Can not leave voicemail, unable to count messages\n");
04008          return -1;
04009       }
04010       if (!(vms = get_vm_state_by_mailbox(ext, context, 0))) {
04011       /*It is possible under certain circumstances that inboxcount did not create a vm_state when it was needed. This is a catchall which will
04012        * rarely be used*/
04013          if (!(vms = create_vm_state_from_user(vmu))) {
04014             ast_log(LOG_ERROR, "Couldn't allocate necessary space\n");
04015             return -1;
04016          }
04017       }
04018       vms->newmessages++;
04019       /* here is a big difference! We add one to it later */
04020       msgnum = newmsgs + oldmsgs;
04021       if (option_debug > 2)
04022          ast_log(LOG_DEBUG, "Messagecount set to %d\n",msgnum);
04023       snprintf(fn, sizeof(fn), "%s/imap/msg%s%04d", VM_SPOOL_DIR, vmu->mailbox, msgnum);
04024       /* set variable for compatability */
04025       pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", "IMAP_STORAGE");
04026 
04027       /* Check if mailbox is full */
04028       check_quota(vms, imapfolder);
04029       if (vms->quota_limit && vms->quota_usage >= vms->quota_limit) {
04030          if (option_debug)
04031             ast_log(LOG_DEBUG, "*** QUOTA EXCEEDED!! %u >= %u\n", vms->quota_usage, vms->quota_limit);
04032          ast_play_and_wait(chan, "vm-mailboxfull");
04033          return -1;
04034       }
04035       if (option_debug > 2)
04036          ast_log(LOG_DEBUG, "Checking message number quota - mailbox has %d messages, maximum is set to %d\n",msgnum,vmu->maxmsg);
04037       if (msgnum >= vmu->maxmsg) {
04038          res = ast_streamfile(chan, "vm-mailboxfull", chan->language);
04039          if (!res)
04040             res = ast_waitstream(chan, "");
04041          ast_log(LOG_WARNING, "No more messages possible\n");
04042          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
04043          goto leave_vm_out;
04044       }
04045 
04046       /* Check if we have exceeded maxmsg */
04047       if (msgnum >= vmu->maxmsg) {
04048          ast_log(LOG_WARNING, "Unable to leave message since we will exceed the maximum number of messages allowed (%u > %u)\n", msgnum, vmu->maxmsg);
04049          ast_play_and_wait(chan, "vm-mailboxfull");
04050          return -1;
04051       }
04052 #else
04053       if (count_messages(vmu, dir) >= vmu->maxmsg) {
04054          res = ast_streamfile(chan, "vm-mailboxfull", chan->language);
04055          if (!res)
04056             res = ast_waitstream(chan, "");
04057          ast_log(LOG_WARNING, "No more messages possible\n");
04058          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
04059          goto leave_vm_out;
04060       }
04061 
04062 #endif
04063       snprintf(tmptxtfile, sizeof(tmptxtfile), "%s/XXXXXX", tmpdir);
04064       txtdes = mkstemp(tmptxtfile);
04065       chmod(tmptxtfile, VOICEMAIL_FILE_MODE & ~my_umask);
04066       if (txtdes < 0) {
04067          res = ast_streamfile(chan, "vm-mailboxfull", chan->language);
04068          if (!res)
04069             res = ast_waitstream(chan, "");
04070          ast_log(LOG_ERROR, "Unable to create message file: %s\n", strerror(errno));
04071          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
04072          goto leave_vm_out;
04073       }
04074 
04075       /* Now play the beep once we have the message number for our next message. */
04076       if (res >= 0) {
04077          /* Unless we're *really* silent, try to send the beep */
04078          res = ast_stream_and_wait(chan, "beep", chan->language, "");
04079       }
04080             
04081       /* Store information */
04082       txt = fdopen(txtdes, "w+");
04083       if (txt) {
04084          get_date(date, sizeof(date));
04085          fprintf(txt, 
04086             ";\n"
04087             "; Message Information file\n"
04088             ";\n"
04089             "[message]\n"
04090             "origmailbox=%s\n"
04091             "context=%s\n"
04092             "macrocontext=%s\n"
04093             "exten=%s\n"
04094             "priority=%d\n"
04095             "callerchan=%s\n"
04096             "callerid=%s\n"
04097             "origdate=%s\n"
04098             "origtime=%ld\n"
04099             "category=%s\n",
04100             ext,
04101             chan->context,
04102             chan->macrocontext, 
04103             chan->exten,
04104             chan->priority,
04105             chan->name,
04106             ast_callerid_merge(callerid, sizeof(callerid), S_OR(chan->cid.cid_name, NULL), S_OR(chan->cid.cid_num, NULL), "Unknown"),
04107             date, (long)time(NULL),
04108             category ? category : ""); 
04109       } else
04110          ast_log(LOG_WARNING, "Error opening text file for output\n");
04111       res = play_record_review(chan, NULL, tmptxtfile, vmmaxmessage, fmt, 1, vmu, &duration, NULL, options->record_gain, vms);
04112 
04113       if (txt) {
04114          if (duration < vmminmessage) {
04115             fclose(txt);
04116             if (option_verbose > 2) 
04117                ast_verbose( VERBOSE_PREFIX_3 "Recording was %d seconds long but needs to be at least %d - abandoning\n", duration, vmminmessage);
04118             ast_filedelete(tmptxtfile, NULL);
04119             unlink(tmptxtfile);
04120          } else {
04121             fprintf(txt, "duration=%d\n", duration);
04122             fclose(txt);
04123             if (vm_lock_path(dir)) {
04124                ast_log(LOG_ERROR, "Couldn't lock directory %s.  Voicemail will be lost.\n", dir);
04125                /* Delete files */
04126                ast_filedelete(tmptxtfile, NULL);
04127                unlink(tmptxtfile);
04128             } else if (ast_fileexists(tmptxtfile, NULL, NULL) <= 0) {
04129                if (option_debug) 
04130                   ast_log(LOG_DEBUG, "The recorded media file is gone, so we should remove the .txt file too!\n");
04131                unlink(tmptxtfile);
04132                ast_unlock_path(dir);
04133             } else {
04134                for (;;) {
04135                   make_file(fn, sizeof(fn), dir, msgnum);
04136                   if (!EXISTS(dir, msgnum, fn, NULL))
04137                      break;
04138                   msgnum++;
04139                }
04140 
04141                /* assign a variable with the name of the voicemail file */ 
04142 #ifndef IMAP_STORAGE
04143                pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", fn);
04144 #else
04145                pbx_builtin_setvar_helper(chan, "VM_MESSAGEFILE", "IMAP_STORAGE");
04146 #endif
04147 
04148                snprintf(txtfile, sizeof(txtfile), "%s.txt", fn);
04149                ast_filerename(tmptxtfile, fn, NULL);
04150                rename(tmptxtfile, txtfile);
04151 
04152                ast_unlock_path(dir);
04153                /* We must store the file first, before copying the message, because
04154                 * ODBC storage does the entire copy with SQL.
04155                 */
04156                if (ast_fileexists(fn, NULL, NULL) > 0) {
04157                   STORE(dir, vmu->mailbox, vmu->context, msgnum, chan, vmu, fmt, duration, vms);
04158                }
04159 
04160                /* Are there to be more recipients of this message? */
04161                while (tmpptr) {
04162                   struct ast_vm_user recipu, *recip;
04163                   char *exten, *context;
04164                
04165                   exten = strsep(&tmpptr, "&");
04166                   context = strchr(exten, '@');
04167                   if (context) {
04168                      *context = '\0';
04169                      context++;
04170                   }
04171                   if ((recip = find_user(&recipu, context, exten))) {
04172                      copy_message(chan, vmu, 0, msgnum, duration, recip, fmt, dir);
04173                      free_user(recip);
04174                   }
04175                }
04176                /* Notification and disposal needs to happen after the copy, though. */
04177                if (ast_fileexists(fn, NULL, NULL)) {
04178                   notify_new_message(chan, vmu, msgnum, duration, fmt, S_OR(chan->cid.cid_num, NULL), S_OR(chan->cid.cid_name, NULL));
04179                   DISPOSE(dir, msgnum);
04180                }
04181             }
04182          }
04183       }
04184       if (res == '0') {
04185          goto transfer;
04186       } else if (res > 0)
04187          res = 0;
04188 
04189       if (duration < vmminmessage)
04190          /* XXX We should really give a prompt too short/option start again, with leave_vm_out called only after a timeout XXX */
04191          pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
04192       else
04193          pbx_builtin_setvar_helper(chan, "VMSTATUS", "SUCCESS");
04194    } else
04195       ast_log(LOG_WARNING, "No format for saving voicemail?\n");
04196 leave_vm_out:
04197    free_user(vmu);
04198    
04199    return res;
04200 }
04201 
04202 #ifndef IMAP_STORAGE
04203 static int resequence_mailbox(struct ast_vm_user *vmu, char *dir)
04204 {
04205    /* we know max messages, so stop process when number is hit */
04206 
04207    int x,dest;
04208    char sfn[PATH_MAX];
04209    char dfn[PATH_MAX];
04210 
04211    if (vm_lock_path(dir))
04212       return ERROR_LOCK_PATH;
04213 
04214    for (x = 0, dest = 0; x < vmu->maxmsg; x++) {
04215       make_file(sfn, sizeof(sfn), dir, x);
04216       if (EXISTS(dir, x, sfn, NULL)) {
04217          
04218          if (x != dest) {
04219             make_file(dfn, sizeof(dfn), dir, dest);
04220             RENAME(dir, x, vmu->mailbox, vmu->context, dir, dest, sfn, dfn);
04221          }
04222          
04223          dest++;
04224       }
04225    }
04226    ast_unlock_path(dir);
04227 
04228    return 0;
04229 }
04230 #endif
04231 
04232 static int say_and_wait(struct ast_channel *chan, int num, const char *language)
04233 {
04234    int d;
04235    d = ast_say_number(chan, num, AST_DIGIT_ANY, language, (char *) NULL);
04236    return d;
04237 }
04238 
04239 static int save_to_folder(struct ast_vm_user *vmu, struct vm_state *vms, int msg, int box)
04240 {
04241 #ifdef IMAP_STORAGE
04242    /* we must use mbox(x) folder names, and copy the message there */
04243    /* simple. huh? */
04244    char sequence[10];
04245    /* get the real IMAP message number for this message */
04246    snprintf(sequence, sizeof(sequence), "%ld", vms->msgArray[msg]);
04247    if (option_debug > 2)
04248       ast_log(LOG_DEBUG, "Copying sequence %s to mailbox %s\n",sequence,(char *) mbox(box));
04249    if (box == 1) {
04250       mail_setflag(vms->mailstream, sequence, "\\Seen");
04251    } else if (box == 0) {
04252       mail_clearflag(vms->mailstream, sequence, "\\Seen");
04253    }
04254    if (!strcasecmp(mbox(0), vms->curbox) && (box == 0 || box == 1))
04255       return 0;
04256    else 
04257       return !mail_copy(vms->mailstream,sequence,(char *) mbox(box)); 
04258 #else
04259    char *dir = vms->curdir;
04260    char *username = vms->username;
04261    char *context = vmu->context;
04262    char sfn[PATH_MAX];
04263    char dfn[PATH_MAX];
04264    char ddir[PATH_MAX];
04265    const char *dbox = mbox(box);
04266    int x;
04267    make_file(sfn, sizeof(sfn), dir, msg);
04268    create_dirpath(ddir, sizeof(ddir), context, username, dbox);
04269 
04270    if (vm_lock_path(ddir))
04271       return ERROR_LOCK_PATH;
04272 
04273    for (x = 0; x < vmu->maxmsg; x++) {
04274       make_file(dfn, sizeof(dfn), ddir, x);
04275       if (!EXISTS(ddir, x, dfn, NULL))
04276          break;
04277    }
04278    if (x >= vmu->maxmsg) {
04279       ast_unlock_path(ddir);
04280       return ERROR_MAILBOX_FULL;
04281    }
04282    if (strcmp(sfn, dfn)) {
04283       COPY(dir, msg, ddir, x, username, context, sfn, dfn);
04284    }
04285    ast_unlock_path(ddir);
04286 #endif
04287    return 0;
04288 }
04289 
04290 static int adsi_logo(unsigned char *buf)
04291 {
04292    int bytes = 0;
04293    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_CENT, 0, "Comedian Mail", "");
04294    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_CENT, 0, "(C)2002-2006 Digium, Inc.", "");
04295    return bytes;
04296 }
04297 
04298 static int adsi_load_vmail(struct ast_channel *chan, int *useadsi)
04299 {
04300    unsigned char buf[256];
04301    int bytes=0;
04302    int x;
04303    char num[5];
04304 
04305    *useadsi = 0;
04306    bytes += ast_adsi_data_mode(buf + bytes);
04307    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04308 
04309    bytes = 0;
04310    bytes += adsi_logo(buf);
04311    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Downloading Scripts", "");
04312 #ifdef DISPLAY
04313    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   .", "");
04314 #endif
04315    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04316    bytes += ast_adsi_data_mode(buf + bytes);
04317    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04318 
04319    if (ast_adsi_begin_download(chan, addesc, adsifdn, adsisec, adsiver)) {
04320       bytes = 0;
04321       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Load Cancelled.", "");
04322       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "ADSI Unavailable", "");
04323       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04324       bytes += ast_adsi_voice_mode(buf + bytes, 0);
04325       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04326       return 0;
04327    }
04328 
04329 #ifdef DISPLAY
04330    /* Add a dot */
04331    bytes = 0;
04332    bytes += ast_adsi_logo(buf);
04333    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Downloading Scripts", "");
04334    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   ..", "");
04335    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04336    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04337 #endif
04338    bytes = 0;
04339    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 0, "Listen", "Listen", "1", 1);
04340    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 1, "Folder", "Folder", "2", 1);
04341    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 2, "Advanced", "Advnced", "3", 1);
04342    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 3, "Options", "Options", "0", 1);
04343    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 4, "Help", "Help", "*", 1);
04344    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 5, "Exit", "Exit", "#", 1);
04345    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
04346 
04347 #ifdef DISPLAY
04348    /* Add another dot */
04349    bytes = 0;
04350    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   ...", "");
04351    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04352 
04353    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04354    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04355 #endif
04356 
04357    bytes = 0;
04358    /* These buttons we load but don't use yet */
04359    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 6, "Previous", "Prev", "4", 1);
04360    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 8, "Repeat", "Repeat", "5", 1);
04361    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 7, "Delete", "Delete", "7", 1);
04362    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 9, "Next", "Next", "6", 1);
04363    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 10, "Save", "Save", "9", 1);
04364    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 11, "Undelete", "Restore", "7", 1);
04365    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
04366 
04367 #ifdef DISPLAY
04368    /* Add another dot */
04369    bytes = 0;
04370    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   ....", "");
04371    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04372    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04373 #endif
04374 
04375    bytes = 0;
04376    for (x=0;x<5;x++) {
04377       snprintf(num, sizeof(num), "%d", x);
04378       bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 12 + x, mbox(x), mbox(x), num, 1);
04379    }
04380    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 12 + 5, "Cancel", "Cancel", "#", 1);
04381    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
04382 
04383 #ifdef DISPLAY
04384    /* Add another dot */
04385    bytes = 0;
04386    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, "   .....", "");
04387    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04388    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04389 #endif
04390 
04391    if (ast_adsi_end_download(chan)) {
04392       bytes = 0;
04393       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Download Unsuccessful.", "");
04394       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "ADSI Unavailable", "");
04395       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04396       bytes += ast_adsi_voice_mode(buf + bytes, 0);
04397       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04398       return 0;
04399    }
04400    bytes = 0;
04401    bytes += ast_adsi_download_disconnect(buf + bytes);
04402    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04403    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DOWNLOAD);
04404 
04405    if (option_debug)
04406       ast_log(LOG_DEBUG, "Done downloading scripts...\n");
04407 
04408 #ifdef DISPLAY
04409    /* Add last dot */
04410    bytes = 0;
04411    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "   ......", "");
04412    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04413 #endif
04414    if (option_debug)
04415       ast_log(LOG_DEBUG, "Restarting session...\n");
04416 
04417    bytes = 0;
04418    /* Load the session now */
04419    if (ast_adsi_load_session(chan, adsifdn, adsiver, 1) == 1) {
04420       *useadsi = 1;
04421       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Scripts Loaded!", "");
04422    } else
04423       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Load Failed!", "");
04424 
04425    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04426    return 0;
04427 }
04428 
04429 static void adsi_begin(struct ast_channel *chan, int *useadsi)
04430 {
04431    int x;
04432    if (!ast_adsi_available(chan))
04433       return;
04434    x = ast_adsi_load_session(chan, adsifdn, adsiver, 1);
04435    if (x < 0)
04436       return;
04437    if (!x) {
04438       if (adsi_load_vmail(chan, useadsi)) {
04439          ast_log(LOG_WARNING, "Unable to upload voicemail scripts\n");
04440          return;
04441       }
04442    } else
04443       *useadsi = 1;
04444 }
04445 
04446 static void adsi_login(struct ast_channel *chan)
04447 {
04448    unsigned char buf[256];
04449    int bytes=0;
04450    unsigned char keys[8];
04451    int x;
04452    if (!ast_adsi_available(chan))
04453       return;
04454 
04455    for (x=0;x<8;x++)
04456       keys[x] = 0;
04457    /* Set one key for next */
04458    keys[3] = ADSI_KEY_APPS + 3;
04459 
04460    bytes += adsi_logo(buf + bytes);
04461    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, " ", "");
04462    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, " ", "");
04463    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04464    bytes += ast_adsi_input_format(buf + bytes, 1, ADSI_DIR_FROM_LEFT, 0, "Mailbox: ******", "");
04465    bytes += ast_adsi_input_control(buf + bytes, ADSI_COMM_PAGE, 4, 1, 1, ADSI_JUST_LEFT);
04466    bytes += ast_adsi_load_soft_key(buf + bytes, ADSI_KEY_APPS + 3, "Enter", "Enter", "#", 1);
04467    bytes += ast_adsi_set_keys(buf + bytes, keys);
04468    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04469    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04470 }
04471 
04472 static void adsi_password(struct ast_channel *chan)
04473 {
04474    unsigned char buf[256];
04475    int bytes=0;
04476    unsigned char keys[8];
04477    int x;
04478    if (!ast_adsi_available(chan))
04479       return;
04480 
04481    for (x=0;x<8;x++)
04482       keys[x] = 0;
04483    /* Set one key for next */
04484    keys[3] = ADSI_KEY_APPS + 3;
04485 
04486    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04487    bytes += ast_adsi_input_format(buf + bytes, 1, ADSI_DIR_FROM_LEFT, 0, "Password: ******", "");
04488    bytes += ast_adsi_input_control(buf + bytes, ADSI_COMM_PAGE, 4, 0, 1, ADSI_JUST_LEFT);
04489    bytes += ast_adsi_set_keys(buf + bytes, keys);
04490    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04491    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04492 }
04493 
04494 static void adsi_folders(struct ast_channel *chan, int start, char *label)
04495 {
04496    unsigned char buf[256];
04497    int bytes=0;
04498    unsigned char keys[8];
04499    int x,y;
04500 
04501    if (!ast_adsi_available(chan))
04502       return;
04503 
04504    for (x=0;x<5;x++) {
04505       y = ADSI_KEY_APPS + 12 + start + x;
04506       if (y > ADSI_KEY_APPS + 12 + 4)
04507          y = 0;
04508       keys[x] = ADSI_KEY_SKT | y;
04509    }
04510    keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 17);
04511    keys[6] = 0;
04512    keys[7] = 0;
04513 
04514    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_CENT, 0, label, "");
04515    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_CENT, 0, " ", "");
04516    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04517    bytes += ast_adsi_set_keys(buf + bytes, keys);
04518    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04519 
04520    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04521 }
04522 
04523 static void adsi_message(struct ast_channel *chan, struct vm_state *vms)
04524 {
04525    int bytes=0;
04526    unsigned char buf[256]; 
04527    char buf1[256], buf2[256];
04528    char fn2[PATH_MAX];
04529 
04530    char cid[256]="";
04531    char *val;
04532    char *name, *num;
04533    char datetime[21]="";
04534    FILE *f;
04535 
04536    unsigned char keys[8];
04537 
04538    int x;
04539 
04540    if (!ast_adsi_available(chan))
04541       return;
04542 
04543    /* Retrieve important info */
04544    snprintf(fn2, sizeof(fn2), "%s.txt", vms->fn);
04545    f = fopen(fn2, "r");
04546    if (f) {
04547       while (!feof(f)) {   
04548          if (!fgets((char *)buf, sizeof(buf), f)) {
04549             continue;
04550          }
04551          if (!feof(f)) {
04552             char *stringp=NULL;
04553             stringp = (char *)buf;
04554             strsep(&stringp, "=");
04555             val = strsep(&stringp, "=");
04556             if (!ast_strlen_zero(val)) {
04557                if (!strcmp((char *)buf, "callerid"))
04558                   ast_copy_string(cid, val, sizeof(cid));
04559                if (!strcmp((char *)buf, "origdate"))
04560                   ast_copy_string(datetime, val, sizeof(datetime));
04561             }
04562          }
04563       }
04564       fclose(f);
04565    }
04566    /* New meaning for keys */
04567    for (x=0;x<5;x++)
04568       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 6 + x);
04569    keys[6] = 0x0;
04570    keys[7] = 0x0;
04571 
04572    if (!vms->curmsg) {
04573       /* No prev key, provide "Folder" instead */
04574       keys[0] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
04575    }
04576    if (vms->curmsg >= vms->lastmsg) {
04577       /* If last message ... */
04578       if (vms->curmsg) {
04579          /* but not only message, provide "Folder" instead */
04580          keys[3] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
04581          bytes += ast_adsi_voice_mode(buf + bytes, 0);
04582 
04583       } else {
04584          /* Otherwise if only message, leave blank */
04585          keys[3] = 1;
04586       }
04587    }
04588 
04589    if (!ast_strlen_zero(cid)) {
04590       ast_callerid_parse(cid, &name, &num);
04591       if (!name)
04592          name = num;
04593    } else
04594       name = "Unknown Caller";
04595 
04596    /* If deleted, show "undeleted" */
04597 
04598    if (vms->deleted[vms->curmsg])
04599       keys[1] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 11);
04600 
04601    /* Except "Exit" */
04602    keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 5);
04603    snprintf(buf1, sizeof(buf1), "%s%s", vms->curbox,
04604       strcasecmp(vms->curbox, "INBOX") ? " Messages" : "");
04605    snprintf(buf2, sizeof(buf2), "Message %d of %d", vms->curmsg + 1, vms->lastmsg + 1);
04606 
04607    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
04608    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
04609    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, name, "");
04610    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_LEFT, 0, datetime, "");
04611    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04612    bytes += ast_adsi_set_keys(buf + bytes, keys);
04613    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04614 
04615    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04616 }
04617 
04618 static void adsi_delete(struct ast_channel *chan, struct vm_state *vms)
04619 {
04620    int bytes=0;
04621    unsigned char buf[256];
04622    unsigned char keys[8];
04623 
04624    int x;
04625 
04626    if (!ast_adsi_available(chan))
04627       return;
04628 
04629    /* New meaning for keys */
04630    for (x=0;x<5;x++)
04631       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 6 + x);
04632 
04633    keys[6] = 0x0;
04634    keys[7] = 0x0;
04635 
04636    if (!vms->curmsg) {
04637       /* No prev key, provide "Folder" instead */
04638       keys[0] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
04639    }
04640    if (vms->curmsg >= vms->lastmsg) {
04641       /* If last message ... */
04642       if (vms->curmsg) {
04643          /* but not only message, provide "Folder" instead */
04644          keys[3] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 1);
04645       } else {
04646          /* Otherwise if only message, leave blank */
04647          keys[3] = 1;
04648       }
04649    }
04650 
04651    /* If deleted, show "undeleted" */
04652    if (vms->deleted[vms->curmsg]) 
04653       keys[1] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 11);
04654 
04655    /* Except "Exit" */
04656    keys[5] = ADSI_KEY_SKT | (ADSI_KEY_APPS + 5);
04657    bytes += ast_adsi_set_keys(buf + bytes, keys);
04658    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04659 
04660    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04661 }
04662 
04663 static void adsi_status(struct ast_channel *chan, struct vm_state *vms)
04664 {
04665    unsigned char buf[256] = "";
04666    char buf1[256] = "", buf2[256] = "";
04667    int bytes=0;
04668    unsigned char keys[8];
04669    int x;
04670 
04671    char *newm = (vms->newmessages == 1) ? "message" : "messages";
04672    char *oldm = (vms->oldmessages == 1) ? "message" : "messages";
04673    if (!ast_adsi_available(chan))
04674       return;
04675    if (vms->newmessages) {
04676       snprintf(buf1, sizeof(buf1), "You have %d new", vms->newmessages);
04677       if (vms->oldmessages) {
04678          strncat(buf1, " and", sizeof(buf1) - strlen(buf1) - 1);
04679          snprintf(buf2, sizeof(buf2), "%d old %s.", vms->oldmessages, oldm);
04680       } else {
04681          snprintf(buf2, sizeof(buf2), "%s.", newm);
04682       }
04683    } else if (vms->oldmessages) {
04684       snprintf(buf1, sizeof(buf1), "You have %d old", vms->oldmessages);
04685       snprintf(buf2, sizeof(buf2), "%s.", oldm);
04686    } else {
04687       strcpy(buf1, "You have no messages.");
04688       buf2[0] = ' ';
04689       buf2[1] = '\0';
04690    }
04691    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
04692    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
04693    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04694 
04695    for (x=0;x<6;x++)
04696       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + x);
04697    keys[6] = 0;
04698    keys[7] = 0;
04699 
04700    /* Don't let them listen if there are none */
04701    if (vms->lastmsg < 0)
04702       keys[0] = 1;
04703    bytes += ast_adsi_set_keys(buf + bytes, keys);
04704 
04705    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04706 
04707    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04708 }
04709 
04710 static void adsi_status2(struct ast_channel *chan, struct vm_state *vms)
04711 {
04712    unsigned char buf[256] = "";
04713    char buf1[256] = "", buf2[256] = "";
04714    int bytes=0;
04715    unsigned char keys[8];
04716    int x;
04717 
04718    char *mess = (vms->lastmsg == 0) ? "message" : "messages";
04719 
04720    if (!ast_adsi_available(chan))
04721       return;
04722 
04723    /* Original command keys */
04724    for (x=0;x<6;x++)
04725       keys[x] = ADSI_KEY_SKT | (ADSI_KEY_APPS + x);
04726 
04727    keys[6] = 0;
04728    keys[7] = 0;
04729 
04730    if ((vms->lastmsg + 1) < 1)
04731       keys[0] = 0;
04732 
04733    snprintf(buf1, sizeof(buf1), "%s%s has", vms->curbox,
04734       strcasecmp(vms->curbox, "INBOX") ? " folder" : "");
04735 
04736    if (vms->lastmsg + 1)
04737       snprintf(buf2, sizeof(buf2), "%d %s.", vms->lastmsg + 1, mess);
04738    else
04739       strcpy(buf2, "no messages.");
04740    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 1, ADSI_JUST_LEFT, 0, buf1, "");
04741    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 2, ADSI_JUST_LEFT, 0, buf2, "");
04742    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, "", "");
04743    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04744    bytes += ast_adsi_set_keys(buf + bytes, keys);
04745 
04746    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04747 
04748    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04749    
04750 }
04751 
04752 /*
04753 static void adsi_clear(struct ast_channel *chan)
04754 {
04755    char buf[256];
04756    int bytes=0;
04757    if (!ast_adsi_available(chan))
04758       return;
04759    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04760    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04761 
04762    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04763 }
04764 */
04765 
04766 static void adsi_goodbye(struct ast_channel *chan)
04767 {
04768    unsigned char buf[256];
04769    int bytes=0;
04770 
04771    if (!ast_adsi_available(chan))
04772       return;
04773    bytes += adsi_logo(buf + bytes);
04774    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_LEFT, 0, " ", "");
04775    bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Goodbye", "");
04776    bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
04777    bytes += ast_adsi_voice_mode(buf + bytes, 0);
04778 
04779    ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
04780 }
04781 
04782 /*--- get_folder: Folder menu ---*/
04783 /* Plays "press 1 for INBOX messages" etc
04784    Should possibly be internationalized
04785  */
04786 static int get_folder(struct ast_channel *chan, int start)
04787 {
04788    int x;
04789    int d;
04790    char fn[PATH_MAX];
04791    d = ast_play_and_wait(chan, "vm-press");  /* "Press" */
04792    if (d)
04793       return d;
04794    for (x = start; x< 5; x++) {  /* For all folders */
04795       if ((d = ast_say_number(chan, x, AST_DIGIT_ANY, chan->language, (char *) NULL)))
04796          return d;
04797       d = ast_play_and_wait(chan, "vm-for"); /* "for" */
04798       if (d)
04799          return d;
04800       snprintf(fn, sizeof(fn), "vm-%s", mbox(x));  /* Folder name */
04801       d = vm_play_folder_name(chan, fn);
04802       if (d)
04803          return d;
04804       d = ast_waitfordigit(chan, 500);
04805       if (d)
04806          return d;
04807    }
04808    d = ast_play_and_wait(chan, "vm-tocancel"); /* "or pound to cancel" */
04809    if (d)
04810       return d;
04811    d = ast_waitfordigit(chan, 4000);
04812    return d;
04813 }
04814 
04815 static int get_folder2(struct ast_channel *chan, char *fn, int start)
04816 {
04817    int res = 0;
04818    res = ast_play_and_wait(chan, fn);  /* Folder name */
04819    while (((res < '0') || (res > '9')) &&
04820          (res != '#') && (res >= 0)) {
04821       res = get_folder(chan, 0);
04822    }
04823    return res;
04824 }
04825 
04826 static int vm_forwardoptions(struct ast_channel *chan, struct ast_vm_user *vmu, char *curdir, int curmsg, char *vmfmts,
04827               char *context, signed char record_gain, long *duration, struct vm_state *vms)
04828 {
04829    int cmd = 0;
04830    int retries = 0, prepend_duration = 0, already_recorded = 0;
04831    signed char zero_gain = 0;
04832    struct ast_config *msg_cfg;
04833    const char *duration_str;
04834    char msgfile[PATH_MAX], backup[PATH_MAX];
04835    char textfile[PATH_MAX];
04836 
04837    /* Must always populate duration correctly */
04838    make_file(msgfile, sizeof(msgfile), curdir, curmsg);
04839    strcpy(textfile, msgfile);
04840    strcpy(backup, msgfile);
04841    strncat(textfile, ".txt", sizeof(textfile) - strlen(textfile) - 1);
04842    strncat(backup, "-bak", sizeof(backup) - strlen(backup) - 1);
04843 
04844    if (!(msg_cfg = ast_config_load(textfile))) {
04845       return -1;
04846    }
04847 
04848    *duration = 0;
04849    if ((duration_str = ast_variable_retrieve(msg_cfg, "message", "duration")))
04850       *duration = atoi(duration_str);
04851 
04852    while ((cmd >= 0) && (cmd != 't') && (cmd != '*')) {
04853       if (cmd)
04854          retries = 0;
04855       switch (cmd) {
04856       case '1': 
04857          /* prepend a message to the current message, update the metadata and return */
04858       {
04859          prepend_duration = 0;
04860 
04861          /* if we can't read the message metadata, stop now */
04862          if (!msg_cfg) {
04863             cmd = 0;
04864             break;
04865          }
04866 
04867          /* Back up the original file, so we can retry the prepend */
04868          if (already_recorded)
04869             ast_filecopy(backup, msgfile, NULL);
04870          else
04871             ast_filecopy(msgfile, backup, NULL);
04872          already_recorded = 1;
04873 
04874          if (record_gain)
04875             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &record_gain, sizeof(record_gain), 0);
04876 
04877          cmd = ast_play_and_prepend(chan, NULL, msgfile, 0, vmfmts, &prepend_duration, 1, silencethreshold, maxsilence);
04878          if (record_gain)
04879             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &zero_gain, sizeof(zero_gain), 0);
04880 
04881          if (prepend_duration) {
04882             struct ast_category *msg_cat;
04883             /* need enough space for a maximum-length message duration */
04884             char duration_str[12];
04885 
04886             prepend_duration += *duration;
04887             msg_cat = ast_category_get(msg_cfg, "message");
04888             snprintf(duration_str, 11, "%d", prepend_duration);
04889             if (!ast_variable_update(msg_cat, "duration", duration_str, NULL, 0)) {
04890                config_text_file_save(textfile, msg_cfg, "app_voicemail");
04891             }
04892          }
04893 
04894          break;
04895       }
04896       case '2': 
04897          cmd = 't';
04898          break;
04899       case '*':
04900          cmd = '*';
04901          break;
04902       default: 
04903          cmd = ast_play_and_wait(chan,"vm-forwardoptions");
04904             /* "Press 1 to prepend a message or 2 to forward the message without prepending" */
04905          if (!cmd)
04906             cmd = ast_play_and_wait(chan,"vm-starmain");
04907             /* "press star to return to the main menu" */
04908          if (!cmd)
04909             cmd = ast_waitfordigit(chan,6000);
04910          if (!cmd)
04911             retries++;
04912          if (retries > 3)
04913             cmd = 't';
04914       }
04915    }
04916 
04917    ast_config_destroy(msg_cfg);
04918    if (already_recorded)
04919       ast_filedelete(backup, NULL);
04920    if (prepend_duration)
04921       *duration = prepend_duration;
04922 
04923    if (cmd == 't' || cmd == 'S')
04924       cmd = 0;
04925    return cmd;
04926 }
04927 
04928 static int notify_new_message(struct ast_channel *chan, struct ast_vm_user *vmu, int msgnum, long duration, char *fmt, char *cidnum, char *cidname)
04929 {
04930    char todir[PATH_MAX], fn[PATH_MAX], ext_context[PATH_MAX], *stringp;
04931    int newmsgs = 0, oldmsgs = 0;
04932    const char *category = pbx_builtin_getvar_helper(chan, "VM_CATEGORY");
04933 
04934    make_dir(todir, sizeof(todir), vmu->context, vmu->mailbox, "INBOX");
04935    make_file(fn, sizeof(fn), todir, msgnum);
04936    snprintf(ext_context, sizeof(ext_context), "%s@%s", vmu->mailbox, vmu->context);
04937 
04938    if (!ast_strlen_zero(vmu->attachfmt)) {
04939       if (strstr(fmt, vmu->attachfmt)) {
04940          fmt = vmu->attachfmt;
04941       } else {
04942          ast_log(LOG_WARNING, "Attachment format '%s' is not one of the recorded formats '%s'.  Falling back to default format for '%s@%s'.\n", vmu->attachfmt, fmt, vmu->mailbox, vmu->context);
04943       }
04944    }
04945 
04946    /* Attach only the first format */
04947    fmt = ast_strdupa(fmt);
04948    stringp = fmt;
04949    strsep(&stringp, "|");
04950 
04951    if (!ast_strlen_zero(vmu->email)) {
04952       int attach_user_voicemail = ast_test_flag((&globalflags), VM_ATTACH);
04953       char *myserveremail = serveremail;
04954       attach_user_voicemail = ast_test_flag(vmu, VM_ATTACH);
04955       if (!ast_strlen_zero(vmu->serveremail))
04956          myserveremail = vmu->serveremail;
04957       
04958       if (attach_user_voicemail)
04959          RETRIEVE(todir, msgnum, vmu);
04960 
04961       /*XXX possible imap issue, should category be NULL XXX*/
04962       sendmail(myserveremail, vmu, msgnum, vmu->context, vmu->mailbox, cidnum, cidname, fn, fmt, duration, attach_user_voicemail, chan, category);
04963 
04964       if (attach_user_voicemail)
04965          DISPOSE(todir, msgnum);
04966    }
04967 
04968    if (!ast_strlen_zero(vmu->pager)) {
04969       char *myserveremail = serveremail;
04970       if (!ast_strlen_zero(vmu->serveremail))
04971          myserveremail = vmu->serveremail;
04972       sendpage(myserveremail, vmu->pager, msgnum, vmu->context, vmu->mailbox, cidnum, cidname, duration, vmu, category);
04973    }
04974 
04975    if (ast_test_flag(vmu, VM_DELETE)) {
04976       DELETE(todir, msgnum, fn, vmu);
04977    }
04978 
04979    /* Leave voicemail for someone */
04980    if (ast_app_has_voicemail(ext_context, NULL)) {
04981       ast_app_inboxcount(ext_context, &newmsgs, &oldmsgs);
04982    }
04983    manager_event(EVENT_FLAG_CALL, "MessageWaiting", "Mailbox: %s@%s\r\nWaiting: %d\r\nNew: %d\r\nOld: %d\r\n", vmu->mailbox, vmu->context, ast_app_has_voicemail(ext_context, NULL), newmsgs, oldmsgs);
04984    run_externnotify(vmu->context, vmu->mailbox);
04985    return 0;
04986 }
04987 
04988 static int forward_message(struct ast_channel *chan, char *context, struct vm_state *vms, struct ast_vm_user *sender, char *fmt, int flag, signed char record_gain)
04989 {
04990 #ifdef IMAP_STORAGE
04991    int todircount=0;
04992    struct vm_state *dstvms;
04993 #endif
04994    char username[70]="";
04995    int res = 0, cmd = 0;
04996    struct ast_vm_user *receiver = NULL, *vmtmp;
04997    AST_LIST_HEAD_NOLOCK_STATIC(extensions, ast_vm_user);
04998    char *stringp;
04999    const char *s;
05000    int saved_messages = 0, found = 0;
05001    int valid_extensions = 0;
05002    char *dir;
05003    int curmsg;
05004 
05005    if (vms == NULL) return -1;
05006    dir = vms->curdir;
05007    curmsg = vms->curmsg;
05008    
05009    while (!res && !valid_extensions) {
05010       int use_directory = 0;
05011       if (ast_test_flag((&globalflags), VM_DIRECFORWARD)) {
05012          int done = 0;
05013          int retries = 0;
05014          cmd=0;
05015          while ((cmd >= 0) && !done ){
05016             if (cmd)
05017                retries = 0;
05018             switch (cmd) {
05019             case '1': 
05020                use_directory = 0;
05021                done = 1;
05022                break;
05023             case '2': 
05024                use_directory = 1;
05025                done=1;
05026                break;
05027             case '*': 
05028                cmd = 't';
05029                done = 1;
05030                break;
05031             default: 
05032                /* Press 1 to enter an extension press 2 to use the directory */
05033                cmd = ast_play_and_wait(chan,"vm-forward");
05034                if (!cmd)
05035                   cmd = ast_waitfordigit(chan,3000);
05036                if (!cmd)
05037                   retries++;
05038                if (retries > 3)
05039                {
05040                   cmd = 't';
05041                   done = 1;
05042                }
05043                
05044             }
05045          }
05046          if (cmd < 0 || cmd == 't')
05047             break;
05048       }
05049       
05050       if (use_directory) {
05051          /* use app_directory */
05052          
05053          char old_context[sizeof(chan->context)];
05054          char old_exten[sizeof(chan->exten)];
05055          int old_priority;
05056          struct ast_app* app;
05057 
05058          
05059          app = pbx_findapp("Directory");
05060          if (app) {
05061             char vmcontext[256];
05062             /* make backup copies */
05063             memcpy(old_context, chan->context, sizeof(chan->context));
05064             memcpy(old_exten, chan->exten, sizeof(chan->exten));
05065             old_priority = chan->priority;
05066             
05067             /* call the the Directory, changes the channel */
05068             snprintf(vmcontext, sizeof(vmcontext), "%s||v", context ? context : "default");
05069             res = pbx_exec(chan, app, vmcontext);
05070             
05071             ast_copy_string(username, chan->exten, sizeof(username));
05072             
05073             /* restore the old context, exten, and priority */
05074             memcpy(chan->context, old_context, sizeof(chan->context));
05075             memcpy(chan->exten, old_exten, sizeof(chan->exten));
05076             chan->priority = old_priority;
05077             
05078          } else {
05079             ast_log(LOG_WARNING, "Could not find the Directory application, disabling directory_forward\n");
05080             ast_clear_flag((&globalflags), VM_DIRECFORWARD);   
05081          }
05082       } else {
05083          /* Ask for an extension */
05084          res = ast_streamfile(chan, "vm-extension", chan->language); /* "extension" */
05085          if (res)
05086             break;
05087          if ((res = ast_readstring(chan, username, sizeof(username) - 1, 2000, 10000, "#") < 0))
05088             break;
05089       }
05090       
05091       /* start all over if no username */
05092       if (ast_strlen_zero(username))
05093          continue;
05094       stringp = username;
05095       s = strsep(&stringp, "*");
05096       /* start optimistic */
05097       valid_extensions = 1;
05098       while (s) {
05099          /* Don't forward to ourselves but allow leaving a message for ourselves (flag == 1).  find_user is going to malloc since we have a NULL as first argument */
05100          if ((flag == 1 || strcmp(s,sender->mailbox)) && (receiver = find_user(NULL, context, s))) {
05101             AST_LIST_INSERT_HEAD(&extensions, receiver, list);
05102             found++;
05103          } else {
05104             valid_extensions = 0;
05105             break;
05106          }
05107          s = strsep(&stringp, "*");
05108       }
05109       /* break from the loop of reading the extensions */
05110       if (valid_extensions)
05111          break;
05112       /* "I am sorry, that's not a valid extension.  Please try again." */
05113       res = ast_play_and_wait(chan, "pbx-invalid");
05114    }
05115    /* check if we're clear to proceed */
05116    if (AST_LIST_EMPTY(&extensions) || !valid_extensions)
05117       return res;
05118    if (flag==1) {
05119       struct leave_vm_options leave_options;
05120       char mailbox[AST_MAX_EXTENSION * 2 + 2];
05121       /* Make sure that context doesn't get set as a literal "(null)" (or else find_user won't find it) */
05122       if (context)
05123          snprintf(mailbox, sizeof(mailbox), "%s@%s", username, context);
05124       else
05125          ast_copy_string(mailbox, username, sizeof(mailbox));
05126 
05127       /* Send VoiceMail */
05128       memset(&leave_options, 0, sizeof(leave_options));
05129       leave_options.record_gain = record_gain;
05130       cmd = leave_voicemail(chan, mailbox, &leave_options);
05131    } else {
05132       /* Forward VoiceMail */
05133       long duration = 0;
05134       char origmsgfile[PATH_MAX], msgfile[PATH_MAX];
05135       struct vm_state vmstmp;
05136 
05137       memcpy(&vmstmp, vms, sizeof(vmstmp));
05138 
05139       make_file(origmsgfile, sizeof(origmsgfile), dir, curmsg);
05140       create_dirpath(vmstmp.curdir, sizeof(vmstmp.curdir), sender->context, vmstmp.username, "tmp");
05141       make_file(msgfile, sizeof(msgfile), vmstmp.curdir, curmsg);
05142 
05143       RETRIEVE(dir, curmsg, sender);
05144 
05145       /* Alter a surrogate file, only */
05146       copy_plain_file(origmsgfile, msgfile);
05147 
05148       cmd = vm_forwardoptions(chan, sender, vmstmp.curdir, curmsg, vmfmts, S_OR(context, "default"), record_gain, &duration, &vmstmp);
05149       if (!cmd) {
05150          AST_LIST_TRAVERSE_SAFE_BEGIN(&extensions, vmtmp, list) {
05151 #ifdef IMAP_STORAGE
05152             char *myserveremail;
05153             int attach_user_voicemail;
05154             /* get destination mailbox */
05155             dstvms = get_vm_state_by_mailbox(vmtmp->mailbox, vmtmp->context, 0);
05156             if (!dstvms) {
05157                dstvms = create_vm_state_from_user(vmtmp);
05158             }
05159             if (dstvms) {
05160                init_mailstream(dstvms, 0);
05161                if (!dstvms->mailstream) {
05162                   ast_log (LOG_ERROR,"IMAP mailstream for %s is NULL\n",vmtmp->mailbox);
05163                } else {
05164                   STORE(vmstmp.curdir, vmtmp->mailbox, vmtmp->context, dstvms->curmsg, chan, vmtmp, fmt, duration, dstvms);
05165                   run_externnotify(vmtmp->context, vmtmp->mailbox); 
05166                }
05167             } else {
05168                ast_log (LOG_ERROR,"Could not find state information for mailbox %s\n",vmtmp->mailbox);
05169             }
05170             myserveremail = serveremail;
05171             if (!ast_strlen_zero(vmtmp->serveremail))
05172                myserveremail = vmtmp->serveremail;
05173             attach_user_voicemail = ast_test_flag(vmtmp, VM_ATTACH);
05174             /* NULL category for IMAP storage */
05175             sendmail(myserveremail, vmtmp, todircount, vmtmp->context, vmtmp->mailbox, S_OR(chan->cid.cid_num, NULL), S_OR(chan->cid.cid_name, NULL), vms->fn, fmt, duration, attach_user_voicemail, chan, NULL);
05176 #else
05177             copy_message(chan, sender, -1, curmsg, duration, vmtmp, fmt, vmstmp.curdir);
05178 #endif
05179             saved_messages++;
05180             AST_LIST_REMOVE_CURRENT(&extensions, list);
05181             free_user(vmtmp);
05182             if (res)
05183                break;
05184          }
05185          AST_LIST_TRAVERSE_SAFE_END;
05186          if (saved_messages > 0) {
05187             /* give confirmation that the message was saved */
05188             /* commented out since we can't forward batches yet
05189             if (saved_messages == 1)
05190                res = ast_play_and_wait(chan, "vm-message");
05191             else
05192                res = ast_play_and_wait(chan, "vm-messages");
05193             if (!res)
05194                res = ast_play_and_wait(chan, "vm-saved"); */
05195             res = ast_play_and_wait(chan, "vm-msgsaved");
05196          }  
05197       }
05198 
05199       /* Remove surrogate file */
05200       vm_delete(msgfile);
05201       DISPOSE(dir, curmsg);
05202    }
05203 
05204    /* If anything failed above, we still have this list to free */
05205    while ((vmtmp = AST_LIST_REMOVE_HEAD(&extensions, list)))
05206       free_user(vmtmp);
05207    return res ? res : cmd;
05208 }
05209 
05210 static int wait_file2(struct ast_channel *chan, struct vm_state *vms, char *file)
05211 {
05212    int res;
05213    if ((res = ast_stream_and_wait(chan, file, chan->language, AST_DIGIT_ANY)) < 0) 
05214       ast_log(LOG_WARNING, "Unable to play message %s\n", file); 
05215    return res;
05216 }
05217 
05218 static int wait_file(struct ast_channel *chan, struct vm_state *vms, char *file) 
05219 {
05220    return ast_control_streamfile(chan, file, "#", "*", "1456789", "0", "2", skipms);
05221 }
05222 
05223 static int play_message_category(struct ast_channel *chan, const char *category)
05224 {
05225    int res = 0;
05226 
05227    if (!ast_strlen_zero(category))
05228       res = ast_play_and_wait(chan, category);
05229 
05230    if (res) {
05231       ast_log(LOG_WARNING, "No sound file for category '%s' was found.\n", category);
05232       res = 0;
05233    }
05234 
05235    return res;
05236 }
05237 
05238 static int play_message_datetime(struct ast_channel *chan, struct ast_vm_user *vmu, const char *origtime, const char *filename)
05239 {
05240    int res = 0;
05241    struct vm_zone *the_zone = NULL;
05242    time_t t;
05243 
05244    if (ast_get_time_t(origtime, &t, 0, NULL)) {
05245       ast_log(LOG_WARNING, "Couldn't find origtime in %s\n", filename);
05246       return 0;
05247    }
05248 
05249    /* Does this user have a timezone specified? */
05250    if (!ast_strlen_zero(vmu->zonetag)) {
05251       /* Find the zone in the list */
05252       struct vm_zone *z;
05253       AST_LIST_LOCK(&zones);
05254       AST_LIST_TRAVERSE(&zones, z, list) {
05255          if (!strcmp(z->name, vmu->zonetag)) {
05256             the_zone = z;
05257             break;
05258          }
05259       }
05260       AST_LIST_UNLOCK(&zones);
05261    }
05262 
05263 /* No internal variable parsing for now, so we'll comment it out for the time being */
05264 #if 0
05265    /* Set the DIFF_* variables */
05266    ast_localtime(&t, &time_now, NULL);
05267    tv_now = ast_tvnow();
05268    tnow = tv_now.tv_sec;
05269    ast_localtime(&tnow, &time_then, NULL);
05270 
05271    /* Day difference */
05272    if (time_now.tm_year == time_then.tm_year)
05273       snprintf(temp,sizeof(temp),"%d",time_now.tm_yday);
05274    else
05275       snprintf(temp,sizeof(temp),"%d",(time_now.tm_year - time_then.tm_year) * 365 + (time_now.tm_yday - time_then.tm_yday));
05276    pbx_builtin_setvar_helper(chan, "DIFF_DAY", temp);
05277 
05278    /* Can't think of how other diffs might be helpful, but I'm sure somebody will think of something. */
05279 #endif
05280    if (the_zone)
05281       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, the_zone->msg_format, the_zone->timezone);
05282    else if (!strcasecmp(chan->language,"pl"))       /* POLISH syntax */
05283       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Q HM", NULL);
05284    else if (!strcasecmp(chan->language,"se"))       /* SWEDISH syntax */
05285       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' dB 'digits/at' k 'and' M", NULL);
05286    else if (!strcasecmp(chan->language,"no"))       /* NORWEGIAN syntax */
05287       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Q 'digits/at' HM", NULL);
05288    else if (!strcasecmp(chan->language,"de"))       /* GERMAN syntax */
05289       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Q 'digits/at' HM", NULL);
05290    else if (!strcasecmp(chan->language,"nl"))      /* DUTCH syntax */
05291       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q 'digits/nl-om' HM", NULL);
05292    else if (!strcasecmp(chan->language,"it"))      /* ITALIAN syntax */
05293       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q 'digits/at' 'digits/hours' k 'digits/e' M 'digits/minutes'", NULL);
05294    else if (!strcasecmp(chan->language,"gr"))
05295       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q  H 'digits/kai' M ", NULL);
05296    else if (!strcasecmp(chan->language,"pt_BR"))
05297       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Ad 'digits/pt-de' B 'digits/pt-de' Y 'digits/pt-as' HM ", NULL);      
05298    else if (!strcasecmp(chan->language,"he"))
05299       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' Ad 'at2' kM", NULL);
05300    else
05301       res = ast_say_date_with_format(chan, t, AST_DIGIT_ANY, chan->language, "'vm-received' q 'digits/at' IMp", NULL);
05302 #if 0
05303    pbx_builtin_setvar_helper(chan, "DIFF_DAY", NULL);
05304 #endif
05305    return res;
05306 }
05307 
05308 
05309 
05310 static int play_message_callerid(struct ast_channel *chan, struct vm_state *vms, char *cid, const char *context, int callback)
05311 {
05312    int res = 0;
05313    int i;
05314    char *callerid, *name;
05315    char prefile[PATH_MAX] = "";
05316    
05317 
05318    /* If voicemail cid is not enabled, or we didn't get cid or context from the attribute file, leave now. */
05319    /* BB: Still need to change this so that if this function is called by the message envelope (and someone is explicitly requesting to hear the CID), it does not check to see if CID is enabled in the config file */
05320    if ((cid == NULL)||(context == NULL))
05321       return res;
05322 
05323    /* Strip off caller ID number from name */
05324    if (option_debug > 2)
05325       ast_log(LOG_DEBUG, "VM-CID: composite caller ID received: %s, context: %s\n", cid, context);
05326    ast_callerid_parse(cid, &name, &callerid);
05327    if ((!ast_strlen_zero(callerid)) && strcmp(callerid, "Unknown")) {
05328       /* Check for internal contexts and only */
05329       /* say extension when the call didn't come from an internal context in the list */
05330       for (i = 0 ; i < MAX_NUM_CID_CONTEXTS ; i++){
05331          if (option_debug > 2)
05332             ast_log(LOG_DEBUG, "VM-CID: comparing internalcontext: %s\n", cidinternalcontexts[i]);
05333          if ((strcmp(cidinternalcontexts[i], context) == 0))
05334             break;
05335       }
05336       if (i != MAX_NUM_CID_CONTEXTS){ /* internal context? */
05337          if (!res) {
05338             snprintf(prefile, sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, context, callerid);
05339             if (!ast_strlen_zero(prefile)) {
05340             /* See if we can find a recorded name for this person instead of their extension number */
05341                if (ast_fileexists(prefile, NULL, NULL) > 0) {
05342                   if (option_verbose > 2)
05343                      ast_verbose(VERBOSE_PREFIX_3 "Playing envelope info: CID number '%s' matches mailbox number, playing recorded name\n", callerid);
05344                   if (!callback)
05345                      res = wait_file2(chan, vms, "vm-from");
05346                   res = ast_stream_and_wait(chan, prefile, chan->language, "");
05347                } else {
05348                   if (option_verbose > 2)
05349                      ast_verbose(VERBOSE_PREFIX_3 "Playing envelope info: message from '%s'\n", callerid);
05350                   /* BB: Say "from extension" as one saying to sound smoother */
05351                   if (!callback)
05352                      res = wait_file2(chan, vms, "vm-from-extension");
05353                   res = ast_say_digit_str(chan, callerid, "", chan->language);
05354                }
05355             }
05356          }
05357       }
05358 
05359       else if (!res){
05360          if (option_debug > 2)
05361             ast_log(LOG_DEBUG, "VM-CID: Numeric caller id: (%s)\n",callerid);
05362          /* BB: Since this is all nicely figured out, why not say "from phone number" in this case" */
05363          if (!callback)
05364             res = wait_file2(chan, vms, "vm-from-phonenumber");
05365          res = ast_say_digit_str(chan, callerid, AST_DIGIT_ANY, chan->language);
05366       }
05367    } else {
05368       /* Number unknown */
05369       if (option_debug)
05370          ast_log(LOG_DEBUG, "VM-CID: From an unknown number\n");
05371       /* Say "from an unknown caller" as one phrase - it is already recorded by "the voice" anyhow */
05372       res = wait_file2(chan, vms, "vm-unknown-caller");
05373    }
05374    return res;
05375 }
05376 
05377 static int play_message_duration(struct ast_channel *chan, struct vm_state *vms, const char *duration, int minduration)
05378 {
05379    int res = 0;
05380    int durationm;
05381    int durations;
05382    /* Verify that we have a duration for the message */
05383    if (duration == NULL)
05384       return res;
05385 
05386    /* Convert from seconds to minutes */
05387    durations=atoi(duration);
05388    durationm=(durations / 60);
05389 
05390    if (option_debug > 2)
05391       ast_log(LOG_DEBUG, "VM-Duration: duration is: %d seconds converted to: %d minutes\n", durations, durationm);
05392 
05393    if ((!res) && (durationm >= minduration)) {
05394       res = wait_file2(chan, vms, "vm-duration");
05395 
05396       /* POLISH syntax */
05397       if (!strcasecmp(chan->language, "pl")) {
05398          div_t num = div(durationm, 10);
05399 
05400          if (durationm == 1) {
05401             res = ast_play_and_wait(chan, "digits/1z");
05402             res = res ? res : ast_play_and_wait(chan, "vm-minute-ta");
05403          } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
05404             if (num.rem == 2) {
05405                if (!num.quot) {
05406                   res = ast_play_and_wait(chan, "digits/2-ie");
05407                } else {
05408                   res = say_and_wait(chan, durationm - 2 , chan->language);
05409                   res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
05410                }
05411             } else {
05412                res = say_and_wait(chan, durationm, chan->language);
05413             }
05414             res = res ? res : ast_play_and_wait(chan, "vm-minute-ty");
05415          } else {
05416             res = say_and_wait(chan, durationm, chan->language);
05417             res = res ? res : ast_play_and_wait(chan, "vm-minute-t");
05418          }
05419       /* DEFAULT syntax */
05420       } else {
05421          res = ast_say_number(chan, durationm, AST_DIGIT_ANY, chan->language, NULL);
05422          res = wait_file2(chan, vms, "vm-minutes");
05423       }
05424    }
05425    return res;
05426 }
05427 
05428 static int play_message(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms)
05429 {
05430    int res = 0;
05431    char filename[256], *cid;
05432    const char *origtime, *context, *category, *duration;
05433    struct ast_config *msg_cfg;
05434 
05435    vms->starting = 0; 
05436    make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
05437    adsi_message(chan, vms);
05438    if (!strcasecmp(chan->language, "he")) {  /* HEBREW FORMAT */
05439       /*
05440        * The syntax in hebrew for counting the number of message is up side down
05441        * in comparison to english.
05442        */
05443       if (!vms->curmsg) {
05444          res = wait_file2(chan, vms, "vm-message");
05445          res = wait_file2(chan, vms, "vm-first");    /* "First" */
05446       } else if (vms->curmsg == vms->lastmsg) {
05447          res = wait_file2(chan, vms, "vm-message");
05448          res = wait_file2(chan, vms, "vm-last");     /* "last" */
05449       } else {
05450          res = wait_file2(chan, vms, "vm-message");  /* "message" */
05451          if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
05452             ast_log(LOG_DEBUG, "curmsg: %d\n", vms->curmsg);
05453             ast_log(LOG_DEBUG, "lagmsg: %d\n", vms->lastmsg);
05454             if (!res) {
05455                res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, chan->language, "f");
05456             }
05457          }
05458       }
05459    } else {
05460       if (!vms->curmsg)
05461          res = wait_file2(chan, vms, "vm-first");  /* "First" */
05462       else if (vms->curmsg == vms->lastmsg)
05463          res = wait_file2(chan, vms, "vm-last");      /* "last" */
05464    }
05465    if (!res) {
05466       /* POLISH syntax */
05467       if (!strcasecmp(chan->language, "pl")) { 
05468          if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
05469             int ten, one;
05470             char nextmsg[256];
05471             ten = (vms->curmsg + 1) / 10;
05472             one = (vms->curmsg + 1) % 10;
05473             
05474             if (vms->curmsg < 20) {
05475                snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", vms->curmsg + 1);
05476                res = wait_file2(chan, vms, nextmsg);
05477             } else {
05478                snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", ten * 10);
05479                res = wait_file2(chan, vms, nextmsg);
05480                if (one > 0) {
05481                   if (!res) {
05482                      snprintf(nextmsg, sizeof(nextmsg), "digits/n-%d", one);
05483                      res = wait_file2(chan, vms, nextmsg);
05484                   }
05485                }
05486             }
05487          }
05488          if (!res)
05489             res = wait_file2(chan, vms, "vm-message");
05490       } else {
05491          if (!strcasecmp(chan->language, "se")) /* SWEDISH syntax */
05492             res = wait_file2(chan, vms, "vm-meddelandet");  /* "message" */
05493          else /* DEFAULT syntax */
05494             res = wait_file2(chan, vms, "vm-message");
05495          if (vms->curmsg && (vms->curmsg != vms->lastmsg)) {
05496             if (!res)
05497                res = ast_say_number(chan, vms->curmsg + 1, AST_DIGIT_ANY, chan->language, NULL);
05498          }
05499       }
05500    }
05501 
05502    /* Retrieve info from VM attribute file */
05503    make_file(vms->fn2, sizeof(vms->fn2), vms->curdir, vms->curmsg);
05504    snprintf(filename, sizeof(filename), "%s.txt", vms->fn2);
05505    RETRIEVE(vms->curdir, vms->curmsg, vmu);
05506    msg_cfg = ast_config_load(filename);
05507    if (!msg_cfg) {
05508       ast_log(LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
05509       return 0;
05510    }
05511 
05512    if (!(origtime = ast_variable_retrieve(msg_cfg, "message", "origtime"))) {
05513       ast_log(LOG_WARNING, "No origtime?!\n");
05514       DISPOSE(vms->curdir, vms->curmsg);
05515       ast_config_destroy(msg_cfg);
05516       return 0;
05517    }
05518 
05519    cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
05520    duration = ast_variable_retrieve(msg_cfg, "message", "duration");
05521    category = ast_variable_retrieve(msg_cfg, "message", "category");
05522 
05523    context = ast_variable_retrieve(msg_cfg, "message", "context");
05524    if (!strncasecmp("macro",context,5)) /* Macro names in contexts are useless for our needs */
05525       context = ast_variable_retrieve(msg_cfg, "message","macrocontext");
05526    if (!res)
05527       res = play_message_category(chan, category);
05528    if ((!res) && (ast_test_flag(vmu, VM_ENVELOPE)))
05529       res = play_message_datetime(chan, vmu, origtime, filename);
05530    if ((!res) && (ast_test_flag(vmu, VM_SAYCID)))
05531       res = play_message_callerid(chan, vms, cid, context, 0);
05532    if ((!res) && (ast_test_flag(vmu, VM_SAYDURATION)))
05533       res = play_message_duration(chan, vms, duration, vmu->saydurationm);
05534    /* Allow pressing '1' to skip envelope / callerid */
05535    if (res == '1')
05536       res = 0;
05537    ast_config_destroy(msg_cfg);
05538 
05539    if (!res) {
05540       make_file(vms->fn, sizeof(vms->fn), vms->curdir, vms->curmsg);
05541       vms->heard[vms->curmsg] = 1;
05542       if ((res = wait_file(chan, vms, vms->fn)) < 0) {
05543          ast_log(LOG_WARNING, "Playback of message %s failed\n", vms->fn);
05544          res = 0;
05545       }
05546    }
05547    DISPOSE(vms->curdir, vms->curmsg);
05548    return res;
05549 }
05550 
05551 #ifndef IMAP_STORAGE
05552 static int open_mailbox(struct vm_state *vms, struct ast_vm_user *vmu,int box)
05553 {
05554    int res = 0;
05555    int count_msg, last_msg;
05556 
05557    ast_copy_string(vms->curbox, mbox(box), sizeof(vms->curbox));
05558    
05559    /* Rename the member vmbox HERE so that we don't try to return before
05560     * we know what's going on.
05561     */
05562    snprintf(vms->vmbox, sizeof(vms->vmbox), "vm-%s", vms->curbox);
05563    
05564    /* Faster to make the directory than to check if it exists. */
05565    create_dirpath(vms->curdir, sizeof(vms->curdir), vmu->context, vms->username, vms->curbox);
05566 
05567    count_msg = count_messages(vmu, vms->curdir);
05568    if (count_msg < 0)
05569       return count_msg;
05570    else
05571       vms->lastmsg = count_msg - 1;
05572 
05573    /*
05574    The following test is needed in case sequencing gets messed up.
05575    There appears to be more than one way to mess up sequence, so
05576    we will not try to find all of the root causes--just fix it when
05577    detected.
05578    */
05579 
05580    last_msg = last_message_index(vmu, vms->curdir);
05581    if (last_msg < 0)
05582       return last_msg;
05583    else if (vms->lastmsg != last_msg)
05584    {
05585       ast_log(LOG_NOTICE, "Resequencing Mailbox: %s\n", vms->curdir);
05586       res = resequence_mailbox(vmu, vms->curdir);
05587       if (res)
05588          return res;
05589    }
05590 
05591    return 0;
05592 }
05593 #endif
05594 
05595 static int close_mailbox(struct vm_state *vms, struct ast_vm_user *vmu)
05596 {
05597    int x = 0;
05598 #ifndef IMAP_STORAGE
05599    int res = 0, nummsg;
05600 #endif
05601 
05602    if (vms->lastmsg <= -1)
05603       goto done;
05604 
05605    vms->curmsg = -1; 
05606 #ifndef IMAP_STORAGE
05607    /* Get the deleted messages fixed */ 
05608    if (vm_lock_path(vms->curdir))
05609       return ERROR_LOCK_PATH;
05610     
05611    for (x = 0; x < vmu->maxmsg; x++) { 
05612       if (!vms->deleted[x] && (strcasecmp(vms->curbox, "INBOX") || !vms->heard[x])) { 
05613          /* Save this message.  It's not in INBOX or hasn't been heard */ 
05614          make_file(vms->fn, sizeof(vms->fn), vms->curdir, x); 
05615          if (!EXISTS(vms->curdir, x, vms->fn, NULL)) 
05616             break;
05617          vms->curmsg++; 
05618          make_file(vms->fn2, sizeof(vms->fn2), vms->curdir, vms->curmsg); 
05619          if (strcmp(vms->fn, vms->fn2)) { 
05620             RENAME(vms->curdir, x, vmu->mailbox,vmu->context, vms->curdir, vms->curmsg, vms->fn, vms->fn2);
05621          } 
05622       } else if (!strcasecmp(vms->curbox, "INBOX") && vms->heard[x] && !vms->deleted[x]) { 
05623          /* Move to old folder before deleting */ 
05624          res = save_to_folder(vmu, vms, x, 1);
05625          if (res == ERROR_LOCK_PATH || res == ERROR_MAILBOX_FULL) {
05626             /* If save failed do not delete the message */
05627             ast_log(LOG_WARNING, "Save failed.  Not moving message: %s.\n", res == ERROR_LOCK_PATH ? "unable to lock path" : "destination folder full");
05628             vms->deleted[x] = 0;
05629             vms->heard[x] = 0;
05630             --x;
05631          } 
05632       } 
05633    } 
05634 
05635    /* Delete ALL remaining messages */
05636    nummsg = x - 1;
05637    for (x = vms->curmsg + 1; x <= nummsg; x++) {
05638       make_file(vms->fn, sizeof(vms->fn), vms->curdir, x);
05639       if (EXISTS(vms->curdir, x, vms->fn, NULL))
05640          DELETE(vms->curdir, x, vms->fn, vmu);
05641    }
05642    ast_unlock_path(vms->curdir);
05643 #else
05644    if (vms->deleted) {
05645       for (x=0;x < vmu->maxmsg;x++) { 
05646          if (vms->deleted[x]) { 
05647             if (option_debug > 2)
05648                ast_log(LOG_DEBUG,"IMAP delete of %d\n",x);
05649             DELETE(vms->curdir, x, vms->fn, vmu);
05650          }
05651       }
05652    }
05653 #endif
05654 
05655 done:
05656    if (vms->deleted)
05657       memset(vms->deleted, 0, vmu->maxmsg * sizeof(int)); 
05658    if (vms->heard)
05659       memset(vms->heard, 0, vmu->maxmsg * sizeof(int)); 
05660 
05661    return 0;
05662 }
05663 
05664 /* In Greek even though we CAN use a syntax like "friends messages"
05665  * ("filika mynhmata") it is not elegant. This also goes for "work/family messages"
05666  * ("ergasiaka/oikogeniaka mynhmata"). Therefore it is better to use a reversed 
05667  * syntax for the above three categories which is more elegant. 
05668  */
05669 
05670 static int vm_play_folder_name_gr(struct ast_channel *chan, char *mbox)
05671 {
05672    int cmd;
05673    char *buf;
05674 
05675    buf = alloca(strlen(mbox)+2); 
05676    strcpy(buf, mbox);
05677    strcat(buf,"s");
05678 
05679    if (!strcasecmp(mbox, "vm-INBOX") || !strcasecmp(mbox, "vm-Old")){
05680       cmd = ast_play_and_wait(chan, buf); /* "NEA / PALIA" */
05681       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages"); /* "messages" -> "MYNHMATA" */
05682    } else {
05683       cmd = ast_play_and_wait(chan, "vm-messages"); /* "messages" -> "MYNHMATA" */
05684       return cmd ? cmd : ast_play_and_wait(chan, mbox); /* friends/family/work... -> "FILWN"/"OIKOGENIAS"/"DOULEIAS"*/
05685    }
05686 }
05687 
05688 static int vm_play_folder_name_pl(struct ast_channel *chan, char *mbox)
05689 {
05690    int cmd;
05691 
05692    if (!strcasecmp(mbox, "vm-INBOX") || !strcasecmp(mbox, "vm-Old")) {
05693       if (!strcasecmp(mbox, "vm-INBOX"))
05694          cmd = ast_play_and_wait(chan, "vm-new-e");
05695       else
05696          cmd = ast_play_and_wait(chan, "vm-old-e");
05697       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages");
05698    } else {
05699       cmd = ast_play_and_wait(chan, "vm-messages");
05700       return cmd ? cmd : ast_play_and_wait(chan, mbox);
05701    }
05702 }
05703 
05704 static int vm_play_folder_name_ua(struct ast_channel *chan, char *mbox)
05705 {
05706    int cmd;
05707 
05708    if (!strcasecmp(mbox, "vm-Family") || !strcasecmp(mbox, "vm-Friends") || !strcasecmp(mbox, "vm-Work")){
05709       cmd = ast_play_and_wait(chan, "vm-messages");
05710       return cmd ? cmd : ast_play_and_wait(chan, mbox);
05711    } else {
05712       cmd = ast_play_and_wait(chan, mbox);
05713       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages");
05714    }
05715 }
05716 
05717 static int vm_play_folder_name(struct ast_channel *chan, char *mbox)
05718 {
05719    int cmd;
05720 
05721    if (!strcasecmp(chan->language, "it") || !strcasecmp(chan->language, "es") || !strcasecmp(chan->language, "pt") || !strcasecmp(chan->language, "pt_BR")) { /* Italian, Spanish, French or Portuguese syntax */
05722       cmd = ast_play_and_wait(chan, "vm-messages"); /* "messages */
05723       return cmd ? cmd : ast_play_and_wait(chan, mbox);
05724    } else if (!strcasecmp(chan->language, "gr")){
05725       return vm_play_folder_name_gr(chan, mbox);
05726    } else if (!strcasecmp(chan->language, "pl")){
05727       return vm_play_folder_name_pl(chan, mbox);
05728    } else if (!strcasecmp(chan->language, "ua")){  /* Ukrainian syntax */
05729       return vm_play_folder_name_ua(chan, mbox);
05730    } else if (!strcasecmp(chan->language, "he")){  /* Hebrew syntax */
05731       cmd = ast_play_and_wait(chan, mbox);
05732       return cmd;
05733    } else {  /* Default English */
05734       cmd = ast_play_and_wait(chan, mbox);
05735       return cmd ? cmd : ast_play_and_wait(chan, "vm-messages"); /* "messages */
05736    }
05737 }
05738 
05739 /* GREEK SYNTAX 
05740    In greek the plural for old/new is
05741    different so we need the following files
05742    We also need vm-denExeteMynhmata because 
05743    this syntax is different.
05744    
05745    -> vm-Olds.wav : "Palia"
05746    -> vm-INBOXs.wav : "Nea"
05747    -> vm-denExeteMynhmata : "den exete mynhmata"
05748 */
05749                
05750    
05751 static int vm_intro_gr(struct ast_channel *chan, struct vm_state *vms)
05752 {
05753    int res = 0;
05754 
05755    if (vms->newmessages) {
05756       res = ast_play_and_wait(chan, "vm-youhave");
05757       if (!res) 
05758          res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, NULL);
05759       if (!res) {
05760          if ((vms->newmessages == 1)) {
05761             res = ast_play_and_wait(chan, "vm-INBOX");
05762             if (!res)
05763                res = ast_play_and_wait(chan, "vm-message");
05764          } else {
05765             res = ast_play_and_wait(chan, "vm-INBOXs");
05766             if (!res)
05767                res = ast_play_and_wait(chan, "vm-messages");
05768          }
05769       }
05770    } else if (vms->oldmessages){
05771       res = ast_play_and_wait(chan, "vm-youhave");
05772       if (!res)
05773          res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, NULL);
05774       if ((vms->oldmessages == 1)){
05775          res = ast_play_and_wait(chan, "vm-Old");
05776          if (!res)
05777             res = ast_play_and_wait(chan, "vm-message");
05778       } else {
05779          res = ast_play_and_wait(chan, "vm-Olds");
05780          if (!res)
05781             res = ast_play_and_wait(chan, "vm-messages");
05782       }
05783    } else if (!vms->oldmessages && !vms->newmessages) 
05784       res = ast_play_and_wait(chan, "vm-denExeteMynhmata"); 
05785    return res;
05786 }
05787    
05788 /* Default English syntax */
05789 static int vm_intro_en(struct ast_channel *chan, struct vm_state *vms)
05790 {
05791    int res;
05792 
05793    /* Introduce messages they have */
05794    res = ast_play_and_wait(chan, "vm-youhave");
05795    if (!res) {
05796       if (vms->newmessages) {
05797          res = say_and_wait(chan, vms->newmessages, chan->language);
05798          if (!res)
05799             res = ast_play_and_wait(chan, "vm-INBOX");
05800          if (vms->oldmessages && !res)
05801             res = ast_play_and_wait(chan, "vm-and");
05802          else if (!res) {
05803             if ((vms->newmessages == 1))
05804                res = ast_play_and_wait(chan, "vm-message");
05805             else
05806                res = ast_play_and_wait(chan, "vm-messages");
05807          }
05808             
05809       }
05810       if (!res && vms->oldmessages) {
05811          res = say_and_wait(chan, vms->oldmessages, chan->language);
05812          if (!res)
05813             res = ast_play_and_wait(chan, "vm-Old");
05814          if (!res) {
05815             if (vms->oldmessages == 1)
05816                res = ast_play_and_wait(chan, "vm-message");
05817             else
05818                res = ast_play_and_wait(chan, "vm-messages");
05819          }
05820       }
05821       if (!res) {
05822          if (!vms->oldmessages && !vms->newmessages) {
05823             res = ast_play_and_wait(chan, "vm-no");
05824             if (!res)
05825                res = ast_play_and_wait(chan, "vm-messages");
05826          }
05827       }
05828    }
05829    return res;
05830 }
05831 
05832 /* Default Hebrew syntax */
05833 static int vm_intro_he(struct ast_channel *chan, struct vm_state *vms)
05834 {
05835    int res=0;
05836 
05837    /* Introduce messages they have */
05838    if (!res) {
05839       if ((vms->newmessages) || (vms->oldmessages)) {
05840          res = ast_play_and_wait(chan, "vm-youhave");
05841       }
05842       /*
05843        * The word "shtei" refers to the number 2 in hebrew when performing a count
05844        * of elements. In Hebrew, there are 6 forms of enumerating the number 2 for
05845        * an element, this is one of them.
05846        */
05847       if (vms->newmessages) {
05848          if (!res) {
05849             if (vms->newmessages == 1) {
05850                res = ast_play_and_wait(chan, "vm-INBOX1");
05851             } else {
05852                if (vms->newmessages == 2) {
05853                   res = ast_play_and_wait(chan, "vm-shtei");
05854                } else {
05855                   res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, "f");
05856                }
05857                res = ast_play_and_wait(chan, "vm-INBOX");
05858             }
05859          }
05860          if (vms->oldmessages && !res) {
05861             res = ast_play_and_wait(chan, "vm-and");
05862             if (vms->oldmessages == 1) {
05863                res = ast_play_and_wait(chan, "vm-Old1");
05864             } else {
05865                if (vms->oldmessages == 2) {
05866                   res = ast_play_and_wait(chan, "vm-shtei");
05867                } else {
05868                   res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");
05869                }
05870                res = ast_play_and_wait(chan, "vm-Old");
05871             }
05872          }
05873       }
05874       if (!res && vms->oldmessages && !vms->newmessages) {
05875          if (!res) {
05876             if (vms->oldmessages == 1) {
05877                res = ast_play_and_wait(chan, "vm-Old1");
05878             } else {
05879                if (vms->oldmessages == 2) {
05880                   res = ast_play_and_wait(chan, "vm-shtei");
05881                } else {
05882                   res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");            
05883                }
05884                res = ast_play_and_wait(chan, "vm-Old");
05885             }
05886          }
05887       }
05888       if (!res) {
05889          if (!vms->oldmessages && !vms->newmessages) {
05890             if (!res) {
05891                res = ast_play_and_wait(chan, "vm-nomessages");
05892             }
05893          }
05894       }
05895    }
05896    return res;
05897 }
05898 
05899 
05900 /* ITALIAN syntax */
05901 static int vm_intro_it(struct ast_channel *chan, struct vm_state *vms)
05902 {
05903    /* Introduce messages they have */
05904    int res;
05905    if (!vms->oldmessages && !vms->newmessages)
05906       res = ast_play_and_wait(chan, "vm-no") ||
05907          ast_play_and_wait(chan, "vm-message");
05908    else
05909       res = ast_play_and_wait(chan, "vm-youhave");
05910    if (!res && vms->newmessages) {
05911       res = (vms->newmessages == 1) ?
05912          ast_play_and_wait(chan, "digits/un") ||
05913          ast_play_and_wait(chan, "vm-nuovo") ||
05914          ast_play_and_wait(chan, "vm-message") :
05915          /* 2 or more new messages */
05916          say_and_wait(chan, vms->newmessages, chan->language) ||
05917          ast_play_and_wait(chan, "vm-nuovi") ||
05918          ast_play_and_wait(chan, "vm-messages");
05919       if (!res && vms->oldmessages)
05920          res = ast_play_and_wait(chan, "vm-and");
05921    }
05922    if (!res && vms->oldmessages) {
05923       res = (vms->oldmessages == 1) ?
05924          ast_play_and_wait(chan, "digits/un") ||
05925          ast_play_and_wait(chan, "vm-vecchio") ||
05926          ast_play_and_wait(chan, "vm-message") :
05927          /* 2 or more old messages */
05928          say_and_wait(chan, vms->oldmessages, chan->language) ||
05929          ast_play_and_wait(chan, "vm-vecchi") ||
05930          ast_play_and_wait(chan, "vm-messages");
05931    }
05932    return res;
05933 }
05934 
05935 /* POLISH syntax */
05936 static int vm_intro_pl(struct ast_channel *chan, struct vm_state *vms)
05937 {
05938    /* Introduce messages they have */
05939    int res;
05940    div_t num;
05941 
05942    if (!vms->oldmessages && !vms->newmessages) {
05943       res = ast_play_and_wait(chan, "vm-no");
05944       res = res ? res : ast_play_and_wait(chan, "vm-messages");
05945       return res;
05946    } else {
05947       res = ast_play_and_wait(chan, "vm-youhave");
05948    }
05949 
05950    if (vms->newmessages) {
05951       num = div(vms->newmessages, 10);
05952       if (vms->newmessages == 1) {
05953          res = ast_play_and_wait(chan, "digits/1-a");
05954          res = res ? res : ast_play_and_wait(chan, "vm-new-a");
05955          res = res ? res : ast_play_and_wait(chan, "vm-message");
05956       } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
05957          if (num.rem == 2) {
05958             if (!num.quot) {
05959                res = ast_play_and_wait(chan, "digits/2-ie");
05960             } else {
05961                res = say_and_wait(chan, vms->newmessages - 2 , chan->language);
05962                res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
05963             }
05964          } else {
05965             res = say_and_wait(chan, vms->newmessages, chan->language);
05966          }
05967          res = res ? res : ast_play_and_wait(chan, "vm-new-e");
05968          res = res ? res : ast_play_and_wait(chan, "vm-messages");
05969       } else {
05970          res = say_and_wait(chan, vms->newmessages, chan->language);
05971          res = res ? res : ast_play_and_wait(chan, "vm-new-ych");
05972          res = res ? res : ast_play_and_wait(chan, "vm-messages");
05973       }
05974       if (!res && vms->oldmessages)
05975          res = ast_play_and_wait(chan, "vm-and");
05976    }
05977    if (!res && vms->oldmessages) {
05978       num = div(vms->oldmessages, 10);
05979       if (vms->oldmessages == 1) {
05980          res = ast_play_and_wait(chan, "digits/1-a");
05981          res = res ? res : ast_play_and_wait(chan, "vm-old-a");
05982          res = res ? res : ast_play_and_wait(chan, "vm-message");
05983       } else if (num.rem > 1 && num.rem < 5 && num.quot != 1) {
05984          if (num.rem == 2) {
05985             if (!num.quot) {
05986                res = ast_play_and_wait(chan, "digits/2-ie");
05987             } else {
05988                res = say_and_wait(chan, vms->oldmessages - 2 , chan->language);
05989                res = res ? res : ast_play_and_wait(chan, "digits/2-ie");
05990             }
05991          } else {
05992             res = say_and_wait(chan, vms->oldmessages, chan->language);
05993          }
05994          res = res ? res : ast_play_and_wait(chan, "vm-old-e");
05995          res = res ? res : ast_play_and_wait(chan, "vm-messages");
05996       } else {
05997          res = say_and_wait(chan, vms->oldmessages, chan->language);
05998          res = res ? res : ast_play_and_wait(chan, "vm-old-ych");
05999          res = res ? res : ast_play_and_wait(chan, "vm-messages");
06000       }
06001    }
06002 
06003    return res;
06004 }
06005 
06006 /* SWEDISH syntax */
06007 static int vm_intro_se(struct ast_channel *chan, struct vm_state *vms)
06008 {
06009    /* Introduce messages they have */
06010    int res;
06011 
06012    res = ast_play_and_wait(chan, "vm-youhave");
06013    if (res)
06014       return res;
06015 
06016    if (!vms->oldmessages && !vms->newmessages) {
06017       res = ast_play_and_wait(chan, "vm-no");
06018       res = res ? res : ast_play_and_wait(chan, "vm-messages");
06019       return res;
06020    }
06021 
06022    if (vms->newmessages) {
06023       if ((vms->newmessages == 1)) {
06024          res = ast_play_and_wait(chan, "digits/ett");
06025          res = res ? res : ast_play_and_wait(chan, "vm-nytt");
06026          res = res ? res : ast_play_and_wait(chan, "vm-message");
06027       } else {
06028          res = say_and_wait(chan, vms->newmessages, chan->language);
06029          res = res ? res : ast_play_and_wait(chan, "vm-nya");
06030          res = res ? res : ast_play_and_wait(chan, "vm-messages");
06031       }
06032       if (!res && vms->oldmessages)
06033          res = ast_play_and_wait(chan, "vm-and");
06034    }
06035    if (!res && vms->oldmessages) {
06036       if (vms->oldmessages == 1) {
06037          res = ast_play_and_wait(chan, "digits/ett");
06038          res = res ? res : ast_play_and_wait(chan, "vm-gammalt");
06039          res = res ? res : ast_play_and_wait(chan, "vm-message");
06040       } else {
06041          res = say_and_wait(chan, vms->oldmessages, chan->language);
06042          res = res ? res : ast_play_and_wait(chan, "vm-gamla");
06043          res = res ? res : ast_play_and_wait(chan, "vm-messages");
06044       }
06045    }
06046 
06047    return res;
06048 }
06049 
06050 /* NORWEGIAN syntax */
06051 static int vm_intro_no(struct ast_channel *chan,struct vm_state *vms)
06052 {
06053    /* Introduce messages they have */
06054    int res;
06055 
06056    res = ast_play_and_wait(chan, "vm-youhave");
06057    if (res)
06058       return res;
06059 
06060    if (!vms->oldmessages && !vms->newmessages) {
06061       res = ast_play_and_wait(chan, "vm-no");
06062       res = res ? res : ast_play_and_wait(chan, "vm-messages");
06063       return res;
06064    }
06065 
06066    if (vms->newmessages) {
06067       if ((vms->newmessages == 1)) {
06068          res = ast_play_and_wait(chan, "digits/1");
06069          res = res ? res : ast_play_and_wait(chan, "vm-ny");
06070          res = res ? res : ast_play_and_wait(chan, "vm-message");
06071       } else {
06072          res = say_and_wait(chan, vms->newmessages, chan->language);
06073          res = res ? res : ast_play_and_wait(chan, "vm-nye");
06074          res = res ? res : ast_play_and_wait(chan, "vm-messages");
06075       }
06076       if (!res && vms->oldmessages)
06077          res = ast_play_and_wait(chan, "vm-and");
06078    }
06079    if (!res && vms->oldmessages) {
06080       if (vms->oldmessages == 1) {
06081          res = ast_play_and_wait(chan, "digits/1");
06082          res = res ? res : ast_play_and_wait(chan, "vm-gamel");
06083          res = res ? res : ast_play_and_wait(chan, "vm-message");
06084       } else {
06085          res = say_and_wait(chan, vms->oldmessages, chan->language);
06086          res = res ? res : ast_play_and_wait(chan, "vm-gamle");
06087          res = res ? res : ast_play_and_wait(chan, "vm-messages");
06088       }
06089    }
06090 
06091    return res;
06092 }
06093 
06094 /* GERMAN syntax */
06095 static int vm_intro_de(struct ast_channel *chan,struct vm_state *vms)
06096 {
06097    /* Introduce messages they have */
06098    int res;
06099    res = ast_play_and_wait(chan, "vm-youhave");
06100    if (!res) {
06101       if (vms->newmessages) {
06102          if ((vms->newmessages == 1))
06103             res = ast_play_and_wait(chan, "digits/1F");
06104          else
06105             res = say_and_wait(chan, vms->newmessages, chan->language);
06106          if (!res)
06107             res = ast_play_and_wait(chan, "vm-INBOX");
06108          if (vms->oldmessages && !res)
06109             res = ast_play_and_wait(chan, "vm-and");
06110          else if (!res) {
06111             if ((vms->newmessages == 1))
06112                res = ast_play_and_wait(chan, "vm-message");
06113             else
06114                res = ast_play_and_wait(chan, "vm-messages");
06115          }
06116             
06117       }
06118       if (!res && vms->oldmessages) {
06119          if (vms->oldmessages == 1)
06120             res = ast_play_and_wait(chan, "digits/1F");
06121          else
06122             res = say_and_wait(chan, vms->oldmessages, chan->language);
06123          if (!res)
06124             res = ast_play_and_wait(chan, "vm-Old");
06125          if (!res) {
06126             if (vms->oldmessages == 1)
06127                res = ast_play_and_wait(chan, "vm-message");
06128             else
06129                res = ast_play_and_wait(chan, "vm-messages");
06130          }
06131       }
06132       if (!res) {
06133          if (!vms->oldmessages && !vms->newmessages) {
06134             res = ast_play_and_wait(chan, "vm-no");
06135             if (!res)
06136                res = ast_play_and_wait(chan, "vm-messages");
06137          }
06138       }
06139    }
06140    return res;
06141 }
06142 
06143 /* SPANISH syntax */
06144 static int vm_intro_es(struct ast_channel *chan,struct vm_state *vms)
06145 {
06146    /* Introduce messages they have */
06147    int res;
06148    if (!vms->oldmessages && !vms->newmessages) {
06149       res = ast_play_and_wait(chan, "vm-youhaveno");
06150       if (!res)
06151          res = ast_play_and_wait(chan, "vm-messages");
06152    } else {
06153       res = ast_play_and_wait(chan, "vm-youhave");
06154    }
06155    if (!res) {
06156       if (vms->newmessages) {
06157          if (!res) {
06158             if ((vms->newmessages == 1)) {
06159                res = ast_play_and_wait(chan, "digits/1M");
06160                if (!res)
06161                   res = ast_play_and_wait(chan, "vm-message");
06162                if (!res)
06163                   res = ast_play_and_wait(chan, "vm-INBOXs");
06164             } else {
06165                res = say_and_wait(chan, vms->newmessages, chan->language);
06166                if (!res)
06167                   res = ast_play_and_wait(chan, "vm-messages");
06168                if (!res)
06169                   res = ast_play_and_wait(chan, "vm-INBOX");
06170             }
06171          }
06172          if (vms->oldmessages && !res)
06173             res = ast_play_and_wait(chan, "vm-and");
06174       }
06175       if (vms->oldmessages) {
06176          if (!res) {
06177             if (vms->oldmessages == 1) {
06178                res = ast_play_and_wait(chan, "digits/1M");
06179                if (!res)
06180                   res = ast_play_and_wait(chan, "vm-message");
06181                if (!res)
06182                   res = ast_play_and_wait(chan, "vm-Olds");
06183             } else {
06184                res = say_and_wait(chan, vms->oldmessages, chan->language);
06185                if (!res)
06186                   res = ast_play_and_wait(chan, "vm-messages");
06187                if (!res)
06188                   res = ast_play_and_wait(chan, "vm-Old");
06189             }
06190          }
06191       }
06192    }
06193 return res;
06194 }
06195 
06196 /* BRAZILIAN PORTUGUESE syntax */
06197 static int vm_intro_pt_BR(struct ast_channel *chan,struct vm_state *vms) {
06198    /* Introduce messages they have */
06199    int res;
06200    if (!vms->oldmessages && !vms->newmessages) {
06201       res = ast_play_and_wait(chan, "vm-nomessages");
06202       return res;
06203    }
06204    else {
06205       res = ast_play_and_wait(chan, "vm-youhave");
06206    }
06207    if (vms->newmessages) {
06208       if (!res)
06209          res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, "f");
06210       if ((vms->newmessages == 1)) {
06211          if (!res)
06212             res = ast_play_and_wait(chan, "vm-message");
06213          if (!res)
06214             res = ast_play_and_wait(chan, "vm-INBOXs");
06215       }
06216       else {
06217          if (!res)
06218             res = ast_play_and_wait(chan, "vm-messages");
06219          if (!res)
06220             res = ast_play_and_wait(chan, "vm-INBOX");
06221       }
06222       if (vms->oldmessages && !res)
06223          res = ast_play_and_wait(chan, "vm-and");
06224    }
06225    if (vms->oldmessages) {
06226       if (!res)
06227          res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");
06228       if (vms->oldmessages == 1) {
06229          if (!res)
06230             res = ast_play_and_wait(chan, "vm-message");
06231          if (!res)
06232             res = ast_play_and_wait(chan, "vm-Olds");
06233       }
06234       else {
06235          if (!res)
06236       res = ast_play_and_wait(chan, "vm-messages");
06237          if (!res)
06238             res = ast_play_and_wait(chan, "vm-Old");
06239       }
06240    }
06241    return res;
06242 }
06243 
06244 /* FRENCH syntax */
06245 static int vm_intro_fr(struct ast_channel *chan,struct vm_state *vms)
06246 {
06247    /* Introduce messages they have */
06248    int res;
06249    res = ast_play_and_wait(chan, "vm-youhave");
06250    if (!res) {
06251       if (vms->newmessages) {
06252          res = say_and_wait(chan, vms->newmessages, chan->language);
06253          if (!res)
06254             res = ast_play_and_wait(chan, "vm-INBOX");
06255          if (vms->oldmessages && !res)
06256             res = ast_play_and_wait(chan, "vm-and");
06257          else if (!res) {
06258             if ((vms->newmessages == 1))
06259                res = ast_play_and_wait(chan, "vm-message");
06260             else
06261                res = ast_play_and_wait(chan, "vm-messages");
06262          }
06263             
06264       }
06265       if (!res && vms->oldmessages) {
06266          res = say_and_wait(chan, vms->oldmessages, chan->language);
06267          if (!res)
06268             res = ast_play_and_wait(chan, "vm-Old");
06269          if (!res) {
06270             if (vms->oldmessages == 1)
06271                res = ast_play_and_wait(chan, "vm-message");
06272             else
06273                res = ast_play_and_wait(chan, "vm-messages");
06274          }
06275       }
06276       if (!res) {
06277          if (!vms->oldmessages && !vms->newmessages) {
06278             res = ast_play_and_wait(chan, "vm-no");
06279             if (!res)
06280                res = ast_play_and_wait(chan, "vm-messages");
06281          }
06282       }
06283    }
06284    return res;
06285 }
06286 
06287 /* DUTCH syntax */
06288 static int vm_intro_nl(struct ast_channel *chan,struct vm_state *vms)
06289 {
06290    /* Introduce messages they have */
06291    int res;
06292    res = ast_play_and_wait(chan, "vm-youhave");
06293    if (!res) {
06294       if (vms->newmessages) {
06295          res = say_and_wait(chan, vms->newmessages, chan->language);
06296          if (!res) {
06297             if (vms->newmessages == 1)
06298                res = ast_play_and_wait(chan, "vm-INBOXs");
06299             else
06300                res = ast_play_and_wait(chan, "vm-INBOX");
06301          }
06302          if (vms->oldmessages && !res)
06303             res = ast_play_and_wait(chan, "vm-and");
06304          else if (!res) {
06305             if ((vms->newmessages == 1))
06306                res = ast_play_and_wait(chan, "vm-message");
06307             else
06308                res = ast_play_and_wait(chan, "vm-messages");
06309          }
06310             
06311       }
06312       if (!res && vms->oldmessages) {
06313          res = say_and_wait(chan, vms->oldmessages, chan->language);
06314          if (!res) {
06315             if (vms->oldmessages == 1)
06316                res = ast_play_and_wait(chan, "vm-Olds");
06317             else
06318                res = ast_play_and_wait(chan, "vm-Old");
06319          }
06320          if (!res) {
06321             if (vms->oldmessages == 1)
06322                res = ast_play_and_wait(chan, "vm-message");
06323             else
06324                res = ast_play_and_wait(chan, "vm-messages");
06325          }
06326       }
06327       if (!res) {
06328          if (!vms->oldmessages && !vms->newmessages) {
06329             res = ast_play_and_wait(chan, "vm-no");
06330             if (!res)
06331                res = ast_play_and_wait(chan, "vm-messages");
06332          }
06333       }
06334    }
06335    return res;
06336 }
06337 
06338 /* PORTUGUESE syntax */
06339 static int vm_intro_pt(struct ast_channel *chan,struct vm_state *vms)
06340 {
06341    /* Introduce messages they have */
06342    int res;
06343    res = ast_play_and_wait(chan, "vm-youhave");
06344    if (!res) {
06345       if (vms->newmessages) {
06346          res = ast_say_number(chan, vms->newmessages, AST_DIGIT_ANY, chan->language, "f");
06347          if (!res) {
06348             if ((vms->newmessages == 1)) {
06349                res = ast_play_and_wait(chan, "vm-message");
06350                if (!res)
06351                   res = ast_play_and_wait(chan, "vm-INBOXs");
06352             } else {
06353                res = ast_play_and_wait(chan, "vm-messages");
06354                if (!res)
06355                   res = ast_play_and_wait(chan, "vm-INBOX");
06356             }
06357          }
06358          if (vms->oldmessages && !res)
06359             res = ast_play_and_wait(chan, "vm-and");
06360       }
06361       if (!res && vms->oldmessages) {
06362          res = ast_say_number(chan, vms->oldmessages, AST_DIGIT_ANY, chan->language, "f");
06363          if (!res) {
06364             if (vms->oldmessages == 1) {
06365                res = ast_play_and_wait(chan, "vm-message");
06366                if (!res)
06367                   res = ast_play_and_wait(chan, "vm-Olds");
06368             } else {
06369                res = ast_play_and_wait(chan, "vm-messages");
06370                if (!res)
06371                   res = ast_play_and_wait(chan, "vm-Old");
06372             }
06373          }
06374       }
06375       if (!res) {
06376          if (!vms->oldmessages && !vms->newmessages) {
06377             res = ast_play_and_wait(chan, "vm-no");
06378             if (!res)
06379                res = ast_play_and_wait(chan, "vm-messages");
06380          }
06381       }
06382    }
06383    return res;
06384 }
06385 
06386 
06387 /* CZECH syntax */
06388 /* in czech there must be declension of word new and message
06389  * czech        : english        : czech      : english
06390  * --------------------------------------------------------
06391  * vm-youhave   : you have 
06392  * vm-novou     : one new        : vm-zpravu  : message
06393  * vm-nove      : 2-4 new        : vm-zpravy  : messages
06394  * vm-novych    : 5-infinite new : vm-zprav   : messages
06395  * vm-starou   : one old
06396  * vm-stare     : 2-4 old 
06397  * vm-starych   : 5-infinite old
06398  * jednu        : one   - falling 4. 
06399  * vm-no        : no  ( no messages )
06400  */
06401 
06402 static int vm_intro_cz(struct ast_channel *chan,struct vm_state *vms)
06403 {
06404    int res;
06405    res = ast_play_and_wait(chan, "vm-youhave");
06406    if (!res) {
06407       if (vms->newmessages) {
06408          if (vms->newmessages == 1) {
06409             res = ast_play_and_wait(chan, "digits/jednu");
06410          } else {
06411             res = say_and_wait(chan, vms->newmessages, chan->language);
06412          }
06413          if (!res) {
06414             if ((vms->newmessages == 1))
06415                res = ast_play_and_wait(chan, "vm-novou");
06416             if ((vms->newmessages) > 1 && (vms->newmessages < 5))
06417                res = ast_play_and_wait(chan, "vm-nove");
06418             if (vms->newmessages > 4)
06419                res = ast_play_and_wait(chan, "vm-novych");
06420          }
06421          if (vms->oldmessages && !res)
06422             res = ast_play_and_wait(chan, "vm-and");
06423          else if (!res) {
06424             if ((vms->newmessages == 1))
06425                res = ast_play_and_wait(chan, "vm-zpravu");
06426             if ((vms->newmessages) > 1 && (vms->newmessages < 5))
06427                res = ast_play_and_wait(chan, "vm-zpravy");
06428             if (vms->newmessages > 4)
06429                res = ast_play_and_wait(chan, "vm-zprav");
06430          }
06431       }
06432       if (!res && vms->oldmessages) {
06433          res = say_and_wait(chan, vms->oldmessages, chan->language);
06434          if (!res) {
06435             if ((vms->oldmessages == 1))
06436                res = ast_play_and_wait(chan, "vm-starou");
06437             if ((vms->oldmessages) > 1 && (vms->oldmessages < 5))
06438                res = ast_play_and_wait(chan, "vm-stare");
06439             if (vms->oldmessages > 4)
06440                res = ast_play_and_wait(chan, "vm-starych");
06441          }
06442          if (!res) {
06443             if ((vms->oldmessages == 1))
06444                res = ast_play_and_wait(chan, "vm-zpravu");
06445             if ((vms->oldmessages) > 1 && (vms->oldmessages < 5))
06446                res = ast_play_and_wait(chan, "vm-zpravy");
06447             if (vms->oldmessages > 4)
06448                res = ast_play_and_wait(chan, "vm-zprav");
06449          }
06450       }
06451       if (!res) {
06452          if (!vms->oldmessages && !vms->newmessages) {
06453             res = ast_play_and_wait(chan, "vm-no");
06454             if (!res)
06455                res = ast_play_and_wait(chan, "vm-zpravy");
06456          }
06457       }
06458    }
06459    return res;
06460 }
06461 
06462 static int get_lastdigits(int num)
06463 {
06464    num %= 100;
06465    return (num < 20) ? num : num % 10;
06466 }
06467 
06468 static int vm_intro_ru(struct ast_channel *chan,struct vm_state *vms)
06469 {
06470    int res;
06471    int lastnum = 0;
06472    int dcnum;
06473 
06474    res = ast_play_and_wait(chan, "vm-youhave");
06475    if (!res && vms->newmessages) {
06476       lastnum = get_lastdigits(vms->newmessages);
06477       dcnum = vms->newmessages - lastnum;
06478       if (dcnum)
06479          res = say_and_wait(chan, dcnum, chan->language);
06480       if (!res && lastnum) {
06481          if (lastnum == 1) 
06482             res = ast_play_and_wait(chan, "digits/odno");
06483          else
06484             res = say_and_wait(chan, lastnum, chan->language);
06485       }
06486 
06487       if (!res)
06488          res = ast_play_and_wait(chan, (lastnum == 1) ? "vm-novoe" : "vm-novyh");
06489 
06490       if (!res && vms->oldmessages)
06491          res = ast_play_and_wait(chan, "vm-and");
06492    }
06493 
06494    if (!res && vms->oldmessages) {
06495       lastnum = get_lastdigits(vms->oldmessages);
06496       dcnum = vms->oldmessages - lastnum;
06497       if (dcnum)
06498          res = say_and_wait(chan, dcnum, chan->language);
06499       if (!res && lastnum) {
06500          if (lastnum == 1) 
06501             res = ast_play_and_wait(chan, "digits/odno");
06502          else
06503             res = say_and_wait(chan, lastnum, chan->language);
06504       }
06505 
06506       if (!res)
06507          res = ast_play_and_wait(chan, (lastnum == 1) ? "vm-staroe" : "vm-staryh");
06508    }
06509 
06510    if (!res && !vms->newmessages && !vms->oldmessages) {
06511       lastnum = 0;
06512       res = ast_play_and_wait(chan, "vm-no");
06513    }
06514 
06515    if (!res) {
06516       switch (lastnum) {
06517       case 1:
06518          res = ast_play_and_wait(chan, "vm-soobshenie");
06519          break;
06520       case 2:
06521       case 3:
06522       case 4:
06523          res = ast_play_and_wait(chan, "vm-soobsheniya");
06524          break;
06525       default:
06526          res = ast_play_and_wait(chan, "vm-soobsheniy");
06527          break;
06528       }
06529    }
06530 
06531    return res;
06532 }
06533 
06534 /* UKRAINIAN syntax */
06535 /* in ukrainian the syntax is different so we need the following files
06536  * --------------------------------------------------------
06537  * /digits/ua/1e 'odne'
06538  * vm-nove       'nove'
06539  * vm-stare      'stare'
06540  */
06541 
06542 static int vm_intro_ua(struct ast_channel *chan,struct vm_state *vms)
06543 {
06544    int res;
06545    int lastnum = 0;
06546    int dcnum;
06547 
06548    res = ast_play_and_wait(chan, "vm-youhave");
06549    if (!res && vms->newmessages) {
06550       lastnum = get_lastdigits(vms->newmessages);
06551       dcnum = vms->newmessages - lastnum;
06552       if (dcnum)
06553          res = say_and_wait(chan, dcnum, chan->language);
06554       if (!res && lastnum) {
06555          if (lastnum == 1) 
06556             res = ast_play_and_wait(chan, "digits/ua/1e");
06557          else
06558             res = say_and_wait(chan, lastnum, chan->language);
06559       }
06560 
06561       if (!res)
06562          res = ast_play_and_wait(chan, (lastnum == 1) ? "vm-nove" : "vm-INBOX");
06563 
06564       if (!res && vms->oldmessages)
06565          res = ast_play_and_wait(chan, "vm-and");
06566    }
06567 
06568    if (!res && vms->oldmessages) {
06569       lastnum = get_lastdigits(vms->oldmessages);
06570       dcnum = vms->oldmessages - lastnum;
06571       if (dcnum)
06572          res = say_and_wait(chan, dcnum, chan->language);
06573       if (!res && lastnum) {
06574          if (lastnum == 1) 
06575             res = ast_play_and_wait(chan, "digits/ua/1e");
06576          else
06577             res = say_and_wait(chan, lastnum, chan->language);
06578       }
06579 
06580       if (!res)
06581          res = ast_play_and_wait(chan, (lastnum == 1) ? "vm-stare" : "vm-Old");
06582    }
06583 
06584    if (!res && !vms->newmessages && !vms->oldmessages) {
06585       lastnum = 0;
06586       res = ast_play_and_wait(chan, "vm-no");
06587    }
06588 
06589    if (!res) {
06590       switch (lastnum) {
06591       case 1:
06592       case 2:
06593       case 3:
06594       case 4:
06595          res = ast_play_and_wait(chan, "vm-message");
06596          break;
06597       default:
06598          res = ast_play_and_wait(chan, "vm-messages");
06599          break;
06600       }
06601    }
06602 
06603    return res;
06604 }
06605 
06606 
06607 static int vm_intro(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms)
06608 {
06609    char prefile[256];
06610    
06611    /* Notify the user that the temp greeting is set and give them the option to remove it */
06612    snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
06613    if (ast_test_flag(vmu, VM_TEMPGREETWARN)) {
06614       RETRIEVE(prefile, -1, vmu);
06615       if (ast_fileexists(prefile, NULL, NULL) > 0)
06616          ast_play_and_wait(chan, "vm-tempgreetactive");
06617       DISPOSE(prefile, -1);
06618    }
06619 
06620    /* Play voicemail intro - syntax is different for different languages */
06621    if (!strcasecmp(chan->language, "de")) {  /* GERMAN syntax */
06622       return vm_intro_de(chan, vms);
06623    } else if (!strcasecmp(chan->language, "es")) { /* SPANISH syntax */
06624       return vm_intro_es(chan, vms);
06625    } else if (!strcasecmp(chan->language, "it")) { /* ITALIAN syntax */
06626       return vm_intro_it(chan, vms);
06627    } else if (!strcasecmp(chan->language, "fr")) { /* FRENCH syntax */
06628       return vm_intro_fr(chan, vms);
06629    } else if (!strcasecmp(chan->language, "nl")) { /* DUTCH syntax */
06630       return vm_intro_nl(chan, vms);
06631    } else if (!strcasecmp(chan->language, "pt")) { /* PORTUGUESE syntax */
06632       return vm_intro_pt(chan, vms);
06633    } else if (!strcasecmp(chan->language, "pt_BR")) { /* BRAZILIAN PORTUGUESE syntax */
06634       return vm_intro_pt_BR(chan, vms);      
06635    } else if (!strcasecmp(chan->language, "cz")) { /* CZECH syntax */
06636       return vm_intro_cz(chan, vms);
06637    } else if (!strcasecmp(chan->language, "gr")) { /* GREEK syntax */
06638       return vm_intro_gr(chan, vms);
06639    } else if (!strcasecmp(chan->language, "pl")) { /* POLISH syntax */
06640       return vm_intro_pl(chan, vms);
06641    } else if (!strcasecmp(chan->language, "se")) { /* SWEDISH syntax */
06642       return vm_intro_se(chan, vms);
06643    } else if (!strcasecmp(chan->language, "no")) { /* NORWEGIAN syntax */
06644       return vm_intro_no(chan, vms);
06645    } else if (!strcasecmp(chan->language, "ru")) { /* RUSSIAN syntax */
06646       return vm_intro_ru(chan, vms);
06647    } else if (!strcasecmp(chan->language, "ua")) { /* UKRAINIAN syntax */
06648       return vm_intro_ua(chan, vms);
06649    } else if (!strcasecmp(chan->language, "he")) { /* HEBREW syntax */
06650       return vm_intro_he(chan, vms);
06651    } else {             /* Default to ENGLISH */
06652       return vm_intro_en(chan, vms);
06653    }
06654 }
06655 
06656 static int vm_instructions(struct ast_channel *chan, struct vm_state *vms, int skipadvanced)
06657 {
06658    int res = 0;
06659    /* Play instructions and wait for new command */
06660    while (!res) {
06661       if (vms->starting) {
06662          if (vms->lastmsg > -1) {
06663             res = ast_play_and_wait(chan, "vm-onefor");
06664             if (!strcasecmp(chan->language, "he")) 
06665                res = ast_play_and_wait(chan, "vm-for");
06666             if (!res)
06667                res = vm_play_folder_name(chan, vms->vmbox);
06668          }
06669          if (!res)
06670             res = ast_play_and_wait(chan, "vm-opts");
06671       } else {
06672          if (vms->curmsg)
06673             res = ast_play_and_wait(chan, "vm-prev");
06674          if (!res && !skipadvanced)
06675             res = ast_play_and_wait(chan, "vm-advopts");
06676          if (!res)
06677             res = ast_play_and_wait(chan, "vm-repeat");
06678          if (!res && (vms->curmsg != vms->lastmsg))
06679             res = ast_play_and_wait(chan, "vm-next");
06680          if (!res) {
06681             if (!vms->deleted[vms->curmsg])
06682                res = ast_play_and_wait(chan, "vm-delete");
06683             else
06684                res = ast_play_and_wait(chan, "vm-undelete");
06685             if (!res)
06686                res = ast_play_and_wait(chan, "vm-toforward");
06687             if (!res)
06688                res = ast_play_and_wait(chan, "vm-savemessage");
06689          }
06690       }
06691       if (!res)
06692          res = ast_play_and_wait(chan, "vm-helpexit");
06693       if (!res)
06694          res = ast_waitfordigit(chan, 6000);
06695       if (!res) {
06696          vms->repeats++;
06697          if (vms->repeats > 2) {
06698             res = 't';
06699          }
06700       }
06701    }
06702    return res;
06703 }
06704 
06705 static int vm_newuser(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
06706 {
06707    int cmd = 0;
06708    int duration = 0;
06709    int tries = 0;
06710    char newpassword[80] = "";
06711    char newpassword2[80] = "";
06712    char prefile[PATH_MAX] = "";
06713    unsigned char buf[256];
06714    int bytes=0;
06715 
06716    if (ast_adsi_available(chan)) {
06717       bytes += adsi_logo(buf + bytes);
06718       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "New User Setup", "");
06719       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
06720       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06721       bytes += ast_adsi_voice_mode(buf + bytes, 0);
06722       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06723    }
06724 
06725    /* First, have the user change their password 
06726       so they won't get here again */
06727    for (;;) {
06728       newpassword[1] = '\0';
06729       newpassword[0] = cmd = ast_play_and_wait(chan,"vm-newpassword");
06730       if (cmd == '#')
06731          newpassword[0] = '\0';
06732       if (cmd < 0 || cmd == 't' || cmd == '#')
06733          return cmd;
06734       cmd = ast_readstring(chan,newpassword + strlen(newpassword),sizeof(newpassword)-1,2000,10000,"#");
06735       if (cmd < 0 || cmd == 't' || cmd == '#')
06736          return cmd;
06737       newpassword2[1] = '\0';
06738       newpassword2[0] = cmd = ast_play_and_wait(chan,"vm-reenterpassword");
06739       if (cmd == '#')
06740          newpassword2[0] = '\0';
06741       if (cmd < 0 || cmd == 't' || cmd == '#')
06742          return cmd;
06743       cmd = ast_readstring(chan,newpassword2 + strlen(newpassword2),sizeof(newpassword2)-1,2000,10000,"#");
06744       if (cmd < 0 || cmd == 't' || cmd == '#')
06745          return cmd;
06746       if (!strcmp(newpassword, newpassword2))
06747          break;
06748       ast_log(LOG_NOTICE,"Password mismatch for user %s (%s != %s)\n", vms->username, newpassword, newpassword2);
06749       cmd = ast_play_and_wait(chan, "vm-mismatch");
06750       if (++tries == 3)
06751          return -1;
06752    }
06753    if (ast_strlen_zero(ext_pass_cmd)) 
06754       vm_change_password(vmu,newpassword);
06755    else 
06756       vm_change_password_shell(vmu,newpassword);
06757    if (option_debug > 2)
06758       ast_log(LOG_DEBUG,"User %s set password to %s of length %d\n",vms->username,newpassword,(int)strlen(newpassword));
06759    cmd = ast_play_and_wait(chan,"vm-passchanged");
06760 
06761    /* If forcename is set, have the user record their name */  
06762    if (ast_test_flag(vmu, VM_FORCENAME)) {
06763       snprintf(prefile,sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, vmu->context, vms->username);
06764       if (ast_fileexists(prefile, NULL, NULL) < 1) {
06765          cmd = play_record_review(chan, "vm-rec-name", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06766          if (cmd < 0 || cmd == 't' || cmd == '#')
06767             return cmd;
06768       }
06769    }
06770 
06771    /* If forcegreetings is set, have the user record their greetings */
06772    if (ast_test_flag(vmu, VM_FORCEGREET)) {
06773       snprintf(prefile,sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, vms->username);
06774       if (ast_fileexists(prefile, NULL, NULL) < 1) {
06775          cmd = play_record_review(chan, "vm-rec-unv", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06776          if (cmd < 0 || cmd == 't' || cmd == '#')
06777             return cmd;
06778       }
06779 
06780       snprintf(prefile,sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, vms->username);
06781       if (ast_fileexists(prefile, NULL, NULL) < 1) {
06782          cmd = play_record_review(chan, "vm-rec-busy", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06783          if (cmd < 0 || cmd == 't' || cmd == '#')
06784             return cmd;
06785       }
06786    }
06787 
06788    return cmd;
06789 }
06790 
06791 static int vm_options(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
06792 {
06793    int cmd = 0;
06794    int retries = 0;
06795    int duration = 0;
06796    char newpassword[80] = "";
06797    char newpassword2[80] = "";
06798    char prefile[PATH_MAX] = "";
06799    unsigned char buf[256];
06800    int bytes=0;
06801 
06802    if (ast_adsi_available(chan))
06803    {
06804       bytes += adsi_logo(buf + bytes);
06805       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Options Menu", "");
06806       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
06807       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06808       bytes += ast_adsi_voice_mode(buf + bytes, 0);
06809       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06810    }
06811    while ((cmd >= 0) && (cmd != 't')) {
06812       if (cmd)
06813          retries = 0;
06814       switch (cmd) {
06815       case '1':
06816          snprintf(prefile,sizeof(prefile), "%s%s/%s/unavail", VM_SPOOL_DIR, vmu->context, vms->username);
06817          cmd = play_record_review(chan,"vm-rec-unv",prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06818          break;
06819       case '2': 
06820          snprintf(prefile,sizeof(prefile), "%s%s/%s/busy", VM_SPOOL_DIR, vmu->context, vms->username);
06821          cmd = play_record_review(chan,"vm-rec-busy",prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06822          break;
06823       case '3': 
06824          snprintf(prefile,sizeof(prefile), "%s%s/%s/greet", VM_SPOOL_DIR, vmu->context, vms->username);
06825          cmd = play_record_review(chan,"vm-rec-name",prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06826          break;
06827       case '4': 
06828          cmd = vm_tempgreeting(chan, vmu, vms, fmtc, record_gain);
06829          break;
06830       case '5':
06831          if (vmu->password[0] == '-') {
06832             cmd = ast_play_and_wait(chan, "vm-no");
06833             break;
06834          }
06835          newpassword[1] = '\0';
06836          newpassword[0] = cmd = ast_play_and_wait(chan,"vm-newpassword");
06837          if (cmd == '#')
06838             newpassword[0] = '\0';
06839          else {
06840             if (cmd < 0)
06841                break;
06842             if ((cmd = ast_readstring(chan,newpassword + strlen(newpassword),sizeof(newpassword)-1,2000,10000,"#")) < 0) {
06843                break;
06844             }
06845          }
06846          newpassword2[1] = '\0';
06847          newpassword2[0] = cmd = ast_play_and_wait(chan,"vm-reenterpassword");
06848          if (cmd == '#')
06849             newpassword2[0] = '\0';
06850          else {
06851             if (cmd < 0)
06852                break;
06853 
06854             if ((cmd = ast_readstring(chan,newpassword2 + strlen(newpassword2),sizeof(newpassword2)-1,2000,10000,"#")) < 0) {
06855                break;
06856             }
06857          }
06858          if (strcmp(newpassword, newpassword2)) {
06859             ast_log(LOG_NOTICE,"Password mismatch for user %s (%s != %s)\n", vms->username, newpassword, newpassword2);
06860             cmd = ast_play_and_wait(chan, "vm-mismatch");
06861             break;
06862          }
06863          if (ast_strlen_zero(ext_pass_cmd)) 
06864             vm_change_password(vmu,newpassword);
06865          else 
06866             vm_change_password_shell(vmu,newpassword);
06867          if (option_debug > 2)
06868             ast_log(LOG_DEBUG,"User %s set password to %s of length %d\n",vms->username,newpassword,(int)strlen(newpassword));
06869          cmd = ast_play_and_wait(chan,"vm-passchanged");
06870          break;
06871       case '*': 
06872          cmd = 't';
06873          break;
06874       default: 
06875          cmd = 0;
06876          snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
06877          RETRIEVE(prefile, -1, vmu);
06878          if (ast_fileexists(prefile, NULL, NULL))
06879             cmd = ast_play_and_wait(chan, "vm-tmpexists");
06880          DISPOSE(prefile, -1);
06881          if (!cmd)
06882             cmd = ast_play_and_wait(chan, "vm-options");
06883          if (!cmd)
06884             cmd = ast_waitfordigit(chan,6000);
06885          if (!cmd)
06886             retries++;
06887          if (retries > 3)
06888             cmd = 't';
06889       }
06890    }
06891    if (cmd == 't')
06892       cmd = 0;
06893    return cmd;
06894 }
06895 
06896 static int vm_tempgreeting(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, char *fmtc, signed char record_gain)
06897 {
06898    int res;
06899    int cmd = 0;
06900    int retries = 0;
06901    int duration = 0;
06902    char prefile[PATH_MAX] = "";
06903    unsigned char buf[256];
06904    char dest[PATH_MAX];
06905    int bytes = 0;
06906 
06907    if (ast_adsi_available(chan)) {
06908       bytes += adsi_logo(buf + bytes);
06909       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 3, ADSI_JUST_CENT, 0, "Temp Greeting Menu", "");
06910       bytes += ast_adsi_display(buf + bytes, ADSI_COMM_PAGE, 4, ADSI_JUST_CENT, 0, "Not Done", "");
06911       bytes += ast_adsi_set_line(buf + bytes, ADSI_COMM_PAGE, 1);
06912       bytes += ast_adsi_voice_mode(buf + bytes, 0);
06913       ast_adsi_transmit_message(chan, buf, bytes, ADSI_MSG_DISPLAY);
06914    }
06915 
06916    snprintf(prefile, sizeof(prefile), "%s%s/%s/temp", VM_SPOOL_DIR, vmu->context, vms->username);
06917    if ((res = create_dirpath(dest, sizeof(dest), vmu->context, vms->username, "temp"))) {
06918       ast_log(LOG_WARNING, "Failed to create directory (%s).\n", prefile);
06919       return -1;
06920    }
06921    while ((cmd >= 0) && (cmd != 't')) {
06922       if (cmd)
06923          retries = 0;
06924       RETRIEVE(prefile, -1, vmu);
06925       if (ast_fileexists(prefile, NULL, NULL) <= 0) {
06926          play_record_review(chan, "vm-rec-temp", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06927          cmd = 't';  
06928       } else {
06929          switch (cmd) {
06930          case '1':
06931             cmd = play_record_review(chan, "vm-rec-temp", prefile, maxgreet, fmtc, 0, vmu, &duration, NULL, record_gain, vms);
06932             break;
06933          case '2':
06934             DELETE(prefile, -1, prefile, vmu);
06935             ast_play_and_wait(chan, "vm-tempremoved");
06936             cmd = 't';  
06937             break;
06938          case '*': 
06939             cmd = 't';
06940             break;
06941          default:
06942             cmd = ast_play_and_wait(chan,
06943                ast_fileexists(prefile, NULL, NULL) > 0 ? /* XXX always true ? */
06944                   "vm-tempgreeting2" : "vm-tempgreeting");
06945             if (!cmd)
06946                cmd = ast_waitfordigit(chan,6000);
06947             if (!cmd)
06948                retries++;
06949             if (retries > 3)
06950                cmd = 't';
06951          }
06952       }
06953       DISPOSE(prefile, -1);
06954    }
06955    if (cmd == 't')
06956       cmd = 0;
06957    return cmd;
06958 }
06959 
06960 /* GREEK SYNTAX */
06961    
06962 static int vm_browse_messages_gr(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
06963 {
06964    int cmd=0;
06965 
06966    if (vms->lastmsg > -1) {
06967       cmd = play_message(chan, vmu, vms);
06968    } else {
06969       cmd = ast_play_and_wait(chan, "vm-youhaveno");
06970       if (!strcasecmp(vms->vmbox, "vm-INBOX") ||!strcasecmp(vms->vmbox, "vm-Old")){
06971          if (!cmd) {
06972             snprintf(vms->fn, sizeof(vms->fn), "vm-%ss", vms->curbox);
06973             cmd = ast_play_and_wait(chan, vms->fn);
06974          }
06975          if (!cmd)
06976             cmd = ast_play_and_wait(chan, "vm-messages");
06977       } else {
06978          if (!cmd)
06979             cmd = ast_play_and_wait(chan, "vm-messages");
06980          if (!cmd) {
06981             snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
06982             cmd = ast_play_and_wait(chan, vms->fn);
06983          }
06984       }
06985    } 
06986    return cmd;
06987 }
06988 
06989 /* Default English syntax */
06990 static int vm_browse_messages_en(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
06991 {
06992    int cmd=0;
06993 
06994    if (vms->lastmsg > -1) {
06995       cmd = play_message(chan, vmu, vms);
06996    } else {
06997       cmd = ast_play_and_wait(chan, "vm-youhave");
06998       if (!cmd) 
06999          cmd = ast_play_and_wait(chan, "vm-no");
07000       if (!cmd) {
07001          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
07002          cmd = ast_play_and_wait(chan, vms->fn);
07003       }
07004       if (!cmd)
07005          cmd = ast_play_and_wait(chan, "vm-messages");
07006    }
07007    return cmd;
07008 }
07009 
07010 /* Hebrew Syntax */
07011 static int vm_browse_messages_he(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
07012 {
07013    int cmd = 0;
07014 
07015    if (vms->lastmsg > -1) {
07016       cmd = play_message(chan, vmu, vms);
07017    } else {
07018       if (!strcasecmp(vms->fn, "INBOX")) {
07019          cmd = ast_play_and_wait(chan, "vm-nonewmessages");
07020       } else {
07021          cmd = ast_play_and_wait(chan, "vm-nomessages");
07022       }
07023    }
07024    return cmd;
07025 }
07026 
07027 
07028 /* ITALIAN syntax */
07029 static int vm_browse_messages_it(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
07030 {
07031    int cmd=0;
07032 
07033    if (vms->lastmsg > -1) {
07034       cmd = play_message(chan, vmu, vms);
07035    } else {
07036       cmd = ast_play_and_wait(chan, "vm-no");
07037       if (!cmd)
07038          cmd = ast_play_and_wait(chan, "vm-message");
07039       if (!cmd) {
07040          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
07041          cmd = ast_play_and_wait(chan, vms->fn);
07042       }
07043    }
07044    return cmd;
07045 }
07046 
07047 /* SPANISH syntax */
07048 static int vm_browse_messages_es(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
07049 {
07050    int cmd=0;
07051 
07052    if (vms->lastmsg > -1) {
07053       cmd = play_message(chan, vmu, vms);
07054    } else {
07055       cmd = ast_play_and_wait(chan, "vm-youhaveno");
07056       if (!cmd)
07057          cmd = ast_play_and_wait(chan, "vm-messages");
07058       if (!cmd) {
07059          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
07060          cmd = ast_play_and_wait(chan, vms->fn);
07061       }
07062    }
07063    return cmd;
07064 }
07065 
07066 /* PORTUGUESE syntax */
07067 static int vm_browse_messages_pt(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
07068 {
07069    int cmd=0;
07070 
07071    if (vms->lastmsg > -1) {
07072       cmd = play_message(chan, vmu, vms);
07073    } else {
07074       cmd = ast_play_and_wait(chan, "vm-no");
07075       if (!cmd) {
07076          snprintf(vms->fn, sizeof(vms->fn), "vm-%s", vms->curbox);
07077          cmd = ast_play_and_wait(chan, vms->fn);
07078       }
07079       if (!cmd)
07080          cmd = ast_play_and_wait(chan, "vm-messages");
07081    }
07082    return cmd;
07083 }
07084 
07085 static int vm_browse_messages(struct ast_channel *chan, struct vm_state *vms, struct ast_vm_user *vmu)
07086 {
07087    if (!strcasecmp(chan->language, "es")) {  /* SPANISH */
07088       return vm_browse_messages_es(chan, vms, vmu);
07089    } else if (!strcasecmp(chan->language, "it")) { /* ITALIAN */
07090       return vm_browse_messages_it(chan, vms, vmu);
07091    } else if (!strcasecmp(chan->language, "pt") || !strcasecmp(chan->language, "pt_BR")) {   /* PORTUGUESE */
07092       return vm_browse_messages_pt(chan, vms, vmu);
07093    } else if (!strcasecmp(chan->language, "gr")){
07094       return vm_browse_messages_gr(chan, vms, vmu);   /* GREEK */
07095    } else if (!strcasecmp(chan->language, "he")) {
07096       return vm_browse_messages_he(chan, vms, vmu); /* HEBREW */ 
07097    } else { /* Default to English syntax */
07098       return vm_browse_messages_en(chan, vms, vmu);
07099    }
07100 }
07101 
07102 static int vm_authenticate(struct ast_channel *chan, char *mailbox, int mailbox_size,
07103          struct ast_vm_user *res_vmu, const char *context, const char *prefix,
07104          int skipuser, int maxlogins, int silent)
07105 {
07106    int useadsi=0, valid=0, logretries=0;
07107    char password[AST_MAX_EXTENSION]="", *passptr;
07108    struct ast_vm_user vmus, *vmu = NULL;
07109 
07110    /* If ADSI is supported, setup login screen */
07111    adsi_begin(chan, &useadsi);
07112    if (!skipuser && useadsi)
07113       adsi_login(chan);
07114    if (!silent && !skipuser && ast_streamfile(chan, "vm-login", chan->language)) {
07115       ast_log(LOG_WARNING, "Couldn't stream login file\n");
07116       return -1;
07117    }
07118    
07119    /* Authenticate them and get their mailbox/password */
07120    
07121    while (!valid && (logretries < maxlogins)) {
07122       /* Prompt for, and read in the username */
07123       if (!skipuser && ast_readstring(chan, mailbox, mailbox_size - 1, 2000, 10000, "#") < 0) {
07124          ast_log(LOG_WARNING, "Couldn't read username\n");
07125          return -1;
07126       }
07127       if (ast_strlen_zero(mailbox)) {
07128          if (chan->cid.cid_num) {
07129             ast_copy_string(mailbox, chan->cid.cid_num, mailbox_size);
07130          } else {
07131             if (option_verbose > 2)
07132                ast_verbose(VERBOSE_PREFIX_3 "Username not entered\n");  
07133             return -1;
07134          }
07135       }
07136       if (useadsi)
07137          adsi_password(chan);
07138 
07139       if (!ast_strlen_zero(prefix)) {
07140          char fullusername[80] = "";
07141          ast_copy_string(fullusername, prefix, sizeof(fullusername));
07142          strncat(fullusername, mailbox, sizeof(fullusername) - 1 - strlen(fullusername));
07143          ast_copy_string(mailbox, fullusername, mailbox_size);
07144       }
07145 
07146       if (option_debug)
07147          ast_log(LOG_DEBUG, "Before find user for mailbox %s\n",mailbox);
07148       vmu = find_user(&vmus, context, mailbox);
07149       if (vmu && (vmu->password[0] == '\0' || (vmu->password[0] == '-' && vmu->password[1] == '\0'))) {
07150          /* saved password is blank, so don't bother asking */
07151          password[0] = '\0';
07152       } else {
07153          if (ast_streamfile(chan, "vm-password", chan->language)) {
07154             ast_log(LOG_WARNING, "Unable to stream password file\n");
07155             return -1;
07156          }
07157          if (ast_readstring(chan, password, sizeof(password) - 1, 2000, 10000, "#") < 0) {
07158             ast_log(LOG_WARNING, "Unable to read password\n");
07159             return -1;
07160          }
07161       }
07162 
07163       if (vmu) {
07164          passptr = vmu->password;
07165          if (passptr[0] == '-') passptr++;
07166       }
07167       if (vmu && !strcmp(passptr, password))
07168          valid++;
07169       else {
07170          if (option_verbose > 2)
07171             ast_verbose( VERBOSE_PREFIX_3 "Incorrect password '%s' for user '%s' (context = %s)\n", password, mailbox, context ? context : "default");
07172          if (!ast_strlen_zero(prefix))
07173             mailbox[0] = '\0';
07174       }
07175       logretries++;
07176       if (!valid) {
07177          if (skipuser || logretries >= maxlogins) {
07178             if (ast_streamfile(chan, "vm-incorrect", chan->language)) {
07179                ast_log(LOG_WARNING, "Unable to stream incorrect message\n");
07180                return -1;
07181             }
07182          } else {
07183             if (useadsi)
07184                adsi_login(chan);
07185             if (ast_streamfile(chan, "vm-incorrect-mailbox", chan->language)) {
07186                ast_log(LOG_WARNING, "Unable to stream incorrect mailbox message\n");
07187                return -1;
07188             }
07189          }
07190          if (ast_waitstream(chan, "")) /* Channel is hung up */
07191             return -1;
07192       }
07193    }
07194    if (!valid && (logretries >= maxlogins)) {
07195       ast_stopstream(chan);
07196       ast_play_and_wait(chan, "vm-goodbye");
07197       return -1;
07198    }
07199    if (vmu && !skipuser) {
07200       memcpy(res_vmu, vmu, sizeof(struct ast_vm_user));
07201    }
07202    return 0;
07203 }
07204 
07205 static int vm_execmain(struct ast_channel *chan, void *data)
07206 {
07207    /* XXX This is, admittedly, some pretty horrendus code.  For some
07208       reason it just seemed a lot easier to do with GOTO's.  I feel
07209       like I'm back in my GWBASIC days. XXX */
07210    int res=-1;
07211    int cmd=0;
07212    int valid = 0;
07213    struct ast_module_user *u;
07214    char prefixstr[80] ="";
07215    char ext_context[256]="";
07216    int box;
07217    int useadsi = 0;
07218    int skipuser = 0;
07219    struct vm_state vms;
07220    struct ast_vm_user *vmu = NULL, vmus;
07221    char *context=NULL;
07222    int silentexit = 0;
07223    struct ast_flags flags = { 0 };
07224    signed char record_gain = 0;
07225    int play_auto = 0;
07226    int play_folder = 0;
07227 #ifdef IMAP_STORAGE
07228    int deleted = 0;
07229 #endif
07230    u = ast_module_user_add(chan);
07231 
07232    /* Add the vm_state to the active list and keep it active */
07233    memset(&vms, 0, sizeof(vms));
07234    vms.lastmsg = -1;
07235 
07236    memset(&vmus, 0, sizeof(vmus));
07237 
07238    if (chan->_state != AST_STATE_UP) {
07239       if (option_debug)
07240          ast_log(LOG_DEBUG, "Before ast_answer\n");
07241       ast_answer(chan);
07242    }
07243 
07244    if (!ast_strlen_zero(data)) {
07245       char *opts[OPT_ARG_ARRAY_SIZE];
07246       char *parse;
07247       AST_DECLARE_APP_ARGS(args,
07248          AST_APP_ARG(argv0);
07249          AST_APP_ARG(argv1);
07250       );
07251 
07252       parse = ast_strdupa(data);
07253 
07254       AST_STANDARD_APP_ARGS(args, parse);
07255 
07256       if (args.argc == 2) {
07257          if (ast_app_parse_options(vm_app_options, &flags, opts, args.argv1)) {
07258             ast_module_user_remove(u);
07259             return -1;
07260          }
07261          if (ast_test_flag(&flags, OPT_RECORDGAIN)) {
07262             int gain;
07263             if (!ast_strlen_zero(opts[OPT_ARG_RECORDGAIN])) {
07264                if (sscanf(opts[OPT_ARG_RECORDGAIN], "%d", &gain) != 1) {
07265                   ast_log(LOG_WARNING, "Invalid value '%s' provided for record gain option\n", opts[OPT_ARG_RECORDGAIN]);
07266                   ast_module_user_remove(u);
07267                   return -1;
07268                } else {
07269                   record_gain = (signed char) gain;
07270                }
07271             } else {
07272                ast_log(LOG_WARNING, "Invalid Gain level set with option g\n");
07273             }
07274          }
07275          if (ast_test_flag(&flags, OPT_AUTOPLAY) ) {
07276             play_auto = 1;
07277             if (opts[OPT_ARG_PLAYFOLDER]) {
07278                if (sscanf(opts[OPT_ARG_PLAYFOLDER], "%d", &play_folder) != 1) {
07279                   ast_log(LOG_WARNING, "Invalid value '%s' provided for folder autoplay option\n", opts[OPT_ARG_PLAYFOLDER]);
07280                }
07281             } else {
07282                ast_log(LOG_WARNING, "Invalid folder set with option a\n");
07283             }  
07284             if ( play_folder > 9 || play_folder < 0) {
07285                ast_log(LOG_WARNING, "Invalid value '%d' provided for folder autoplay option\n", play_folder);
07286                play_folder = 0;
07287             }
07288          }
07289       } else {
07290          /* old style options parsing */
07291          while (*(args.argv0)) {
07292             if (*(args.argv0) == 's')
07293                ast_set_flag(&flags, OPT_SILENT);
07294             else if (*(args.argv0) == 'p')
07295                ast_set_flag(&flags, OPT_PREPEND_MAILBOX);
07296             else 
07297                break;
07298             (args.argv0)++;
07299          }
07300 
07301       }
07302 
07303       valid = ast_test_flag(&flags, OPT_SILENT);
07304 
07305       if ((context = strchr(args.argv0, '@')))
07306          *context++ = '\0';
07307 
07308       if (ast_test_flag(&flags, OPT_PREPEND_MAILBOX))
07309          ast_copy_string(prefixstr, args.argv0, sizeof(prefixstr));
07310       else
07311          ast_copy_string(vms.username, args.argv0, sizeof(vms.username));
07312 
07313       if (!ast_strlen_zero(vms.username) && (vmu = find_user(&vmus, context ,vms.username)))
07314          skipuser++;
07315       else
07316          valid = 0;
07317    }
07318 
07319    if (!valid)
07320       res = vm_authenticate(chan, vms.username, sizeof(vms.username), &vmus, context, prefixstr, skipuser, maxlogins, 0);
07321 
07322    if (option_debug)
07323       ast_log(LOG_DEBUG, "After vm_authenticate\n");
07324    if (!res) {
07325       valid = 1;
07326       if (!skipuser)
07327          vmu = &vmus;
07328    } else {
07329       res = 0;
07330    }
07331 
07332    /* If ADSI is supported, setup login screen */
07333    adsi_begin(chan, &useadsi);
07334 
07335 #ifdef IMAP_STORAGE
07336    vms.interactive = 1;
07337    vms.updated = 1;
07338    ast_copy_string(vms.context, vmu->context, sizeof(vms.context));
07339    vmstate_insert(&vms);
07340    init_vm_state(&vms);
07341 #endif
07342    if (!valid)
07343       goto out;
07344 
07345    if (!(vms.deleted = ast_calloc(vmu->maxmsg, sizeof(int)))) {
07346       /* TODO: Handle memory allocation failure */
07347    }
07348    if (!(vms.heard = ast_calloc(vmu->maxmsg, sizeof(int)))) {
07349       /* TODO: Handle memory allocation failure */
07350    }
07351    
07352    /* Set language from config to override channel language */
07353    if (!ast_strlen_zero(vmu->language))
07354       ast_string_field_set(chan, language, vmu->language);
07355    create_dirpath(vms.curdir, sizeof(vms.curdir), vmu->context, vms.username, "");
07356    /* Retrieve old and new message counts */
07357    if (option_debug)
07358       ast_log(LOG_DEBUG, "Before open_mailbox\n");
07359    res = open_mailbox(&vms, vmu, 1);
07360    if (res == ERROR_LOCK_PATH)
07361       goto out;
07362    vms.oldmessages = vms.lastmsg + 1;
07363    if (option_debug > 2)
07364       ast_log(LOG_DEBUG, "Number of old messages: %d\n",vms.oldmessages);
07365    /* Start in INBOX */
07366    res = open_mailbox(&vms, vmu, 0);
07367    if (res == ERROR_LOCK_PATH)
07368       goto out;
07369    vms.newmessages = vms.lastmsg + 1;
07370    if (option_debug > 2)
07371       ast_log(LOG_DEBUG, "Number of new messages: %d\n",vms.newmessages);
07372       
07373    /* Select proper mailbox FIRST!! */
07374    if (play_auto) {
07375       res = open_mailbox(&vms, vmu, play_folder);
07376       if (res == ERROR_LOCK_PATH)
07377          goto out;
07378 
07379       /* If there are no new messages, inform the user and hangup */
07380       if (vms.lastmsg == -1) {
07381          cmd = vm_browse_messages(chan, &vms, vmu);
07382          res = 0;
07383          goto out;
07384       }
07385    } else {
07386       if (!vms.newmessages && vms.oldmessages) {
07387          /* If we only have old messages start here */
07388          res = open_mailbox(&vms, vmu, 1);
07389          play_folder = 1;
07390          if (res == ERROR_LOCK_PATH)
07391             goto out;
07392       }
07393    }
07394 
07395    if (useadsi)
07396       adsi_status(chan, &vms);
07397    res = 0;
07398 
07399    /* Check to see if this is a new user */
07400    if (!strcasecmp(vmu->mailbox, vmu->password) && 
07401       (ast_test_flag(vmu, VM_FORCENAME | VM_FORCEGREET))) {
07402       if (ast_play_and_wait(chan, "vm-newuser") == -1)
07403          ast_log(LOG_WARNING, "Couldn't stream new user file\n");
07404       cmd = vm_newuser(chan, vmu, &vms, vmfmts, record_gain);
07405       if ((cmd == 't') || (cmd == '#')) {
07406          /* Timeout */
07407          res = 0;
07408          goto out;
07409       } else if (cmd < 0) {
07410          /* Hangup */
07411          res = -1;
07412          goto out;
07413       }
07414    }
07415 #ifdef IMAP_STORAGE
07416       if (option_debug > 2)
07417          ast_log(LOG_DEBUG, "Checking quotas: comparing %u to %u\n",vms.quota_usage,vms.quota_limit);
07418       if (vms.quota_limit && vms.quota_usage >= vms.quota_limit) {
07419          if (option_debug)
07420             ast_log(LOG_DEBUG, "*** QUOTA EXCEEDED!!\n");
07421          cmd = ast_play_and_wait(chan, "vm-mailboxfull");
07422       }
07423       if (option_debug > 2)
07424          ast_log(LOG_DEBUG, "Checking quotas: User has %d messages and limit is %d.\n",(vms.newmessages + vms.oldmessages),vmu->maxmsg);
07425       if ((vms.newmessages + vms.oldmessages) >= vmu->maxmsg) {
07426          ast_log(LOG_WARNING, "No more messages possible.  User has %d messages and limit is %d.\n",(vms.newmessages + vms.oldmessages),vmu->maxmsg);
07427          cmd = ast_play_and_wait(chan, "vm-mailboxfull");
07428       }
07429 #endif
07430    if (play_auto) {
07431       cmd = '1';
07432    } else {
07433       cmd = vm_intro(chan, vmu, &vms);
07434    }
07435 
07436    vms.repeats = 0;
07437    vms.starting = 1;
07438    while ((cmd > -1) && (cmd != 't') && (cmd != '#')) {
07439       /* Run main menu */
07440       switch (cmd) {
07441       case '1':
07442          vms.curmsg = 0;
07443          /* Fall through */
07444       case '5':
07445          cmd = vm_browse_messages(chan, &vms, vmu);
07446          break;
07447       case '2': /* Change folders */
07448          if (useadsi)
07449             adsi_folders(chan, 0, "Change to folder...");
07450          cmd = get_folder2(chan, "vm-changeto", 0);
07451          if (cmd == '#') {
07452             cmd = 0;
07453          } else if (cmd > 0) {
07454             cmd = cmd - '0';
07455             res = close_mailbox(&vms, vmu);
07456             if (res == ERROR_LOCK_PATH)
07457                goto out;
07458             res = open_mailbox(&vms, vmu, cmd);
07459             if (res == ERROR_LOCK_PATH)
07460                goto out;
07461             play_folder = cmd;
07462             cmd = 0;
07463          }
07464          if (useadsi)
07465             adsi_status2(chan, &vms);
07466             
07467          if (!cmd)
07468             cmd = vm_play_folder_name(chan, vms.vmbox);
07469 
07470          vms.starting = 1;
07471          break;
07472       case '3': /* Advanced options */
07473          cmd = 0;
07474          vms.repeats = 0;
07475          while ((cmd > -1) && (cmd != 't') && (cmd != '#')) {
07476             switch (cmd) {
07477             case '1': /* Reply */
07478                if (vms.lastmsg > -1 && !vms.starting) {
07479                   cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 1, record_gain);
07480                   if (cmd == ERROR_LOCK_PATH) {
07481                      res = cmd;
07482                      goto out;
07483                   }
07484                } else
07485                   cmd = ast_play_and_wait(chan, "vm-sorry");
07486                cmd = 't';
07487                break;
07488             case '2': /* Callback */
07489                if (option_verbose > 2 && !vms.starting)
07490                   ast_verbose( VERBOSE_PREFIX_3 "Callback Requested\n");
07491                if (!ast_strlen_zero(vmu->callback) && vms.lastmsg > -1 && !vms.starting) {
07492                   cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 2, record_gain);
07493                   if (cmd == 9) {
07494                      silentexit = 1;
07495                      goto out;
07496                   } else if (cmd == ERROR_LOCK_PATH) {
07497                      res = cmd;
07498                      goto out;
07499                   }
07500                }
07501                else 
07502                   cmd = ast_play_and_wait(chan, "vm-sorry");
07503                cmd = 't';
07504                break;
07505             case '3': /* Envelope */
07506                if (vms.lastmsg > -1 && !vms.starting) {
07507                   cmd = advanced_options(chan, vmu, &vms, vms.curmsg, 3, record_gain);
07508                   if (cmd == ERROR_LOCK_PATH) {
07509                      res = cmd;
07510                      goto out;
07511                   }
07512                } else
07513                   cmd = ast_play_and_wait(chan, "vm-sorry");
07514                cmd = 't';
07515                break;
07516             case '4': /* Dialout */
07517                if (!ast_strlen_zero(vmu->dialout)) {
07518                   cmd = dialout(chan, vmu, NULL, vmu->dialout);
07519                   if (cmd == 9) {
07520                      silentexit = 1;
07521                      goto out;
07522                   }
07523                }
07524                else 
07525                   cmd = ast_play_and_wait(chan, "vm-sorry");
07526                cmd = 't';
07527                break;
07528 
07529             case '5': /* Leave VoiceMail */
07530                if (ast_test_flag(vmu, VM_SVMAIL)) {
07531                   cmd = forward_message(chan, context, &vms, vmu, vmfmts, 1, record_gain);
07532                   if (cmd == ERROR_LOCK_PATH) {
07533                      res = cmd;
07534                      ast_log(LOG_WARNING, "forward_message failed to lock path.\n");
07535                      goto out;
07536                   }
07537                } else
07538                   cmd = ast_play_and_wait(chan,"vm-sorry");
07539                cmd='t';
07540                break;
07541                
07542             case '*': /* Return to main menu */
07543                cmd = 't';
07544                break;
07545 
07546             default:
07547                cmd = 0;
07548                if (!vms.starting) {
07549                   cmd = ast_play_and_wait(chan, "vm-toreply");
07550                }
07551                if (!ast_strlen_zero(vmu->callback) && !vms.starting && !cmd) {
07552                   cmd = ast_play_and_wait(chan, "vm-tocallback");
07553                }
07554                if (!cmd && !vms.starting) {
07555                   cmd = ast_play_and_wait(chan, "vm-tohearenv");
07556                }
07557                if (!ast_strlen_zero(vmu->dialout) && !cmd) {
07558                   cmd = ast_play_and_wait(chan, "vm-tomakecall");
07559                }
07560                if (ast_test_flag(vmu, VM_SVMAIL) && !cmd)
07561                   cmd=ast_play_and_wait(chan, "vm-leavemsg");
07562                if (!cmd)
07563                   cmd = ast_play_and_wait(chan, "vm-starmain");
07564                if (!cmd)
07565                   cmd = ast_waitfordigit(chan,6000);
07566                if (!cmd)
07567                   vms.repeats++;
07568                if (vms.repeats > 3)
07569                   cmd = 't';
07570             }
07571          }
07572          if (cmd == 't') {
07573             cmd = 0;
07574             vms.repeats = 0;
07575          }
07576          break;
07577       case '4':
07578          if (vms.curmsg > 0) {
07579             vms.curmsg--;
07580             cmd = play_message(chan, vmu, &vms);
07581          } else {
07582             cmd = ast_play_and_wait(chan, "vm-nomore");
07583          }
07584          break;
07585       case '6':
07586          if (vms.curmsg < vms.lastmsg) {
07587             vms.curmsg++;
07588             cmd = play_message(chan, vmu, &vms);
07589          } else {
07590             cmd = ast_play_and_wait(chan, "vm-nomore");
07591          }
07592          break;
07593       case '7':
07594          if (vms.curmsg >= 0 && vms.curmsg <= vms.lastmsg) {
07595             vms.deleted[vms.curmsg] = !vms.deleted[vms.curmsg];
07596             if (useadsi)
07597                adsi_delete(chan, &vms);
07598             if (vms.deleted[vms.curmsg]) {
07599                if (play_folder == 0)
07600                   vms.newmessages--;
07601                else if (play_folder == 1)
07602                   vms.oldmessages--;
07603                cmd = ast_play_and_wait(chan, "vm-deleted");
07604             }
07605             else {
07606                if (play_folder == 0)
07607                   vms.newmessages++;
07608                else if (play_folder == 1)
07609                   vms.oldmessages++;
07610                cmd = ast_play_and_wait(chan, "vm-undeleted");
07611             }
07612             if (ast_test_flag((&globalflags), VM_SKIPAFTERCMD)) {
07613                if (vms.curmsg < vms.lastmsg) {
07614                   vms.curmsg++;
07615                   cmd = play_message(chan, vmu, &vms);
07616                } else {
07617                   cmd = ast_play_and_wait(chan, "vm-nomore");
07618                }
07619             }
07620          } else /* Delete not valid if we haven't selected a message */
07621             cmd = 0;
07622 #ifdef IMAP_STORAGE
07623          deleted = 1;
07624 #endif
07625          break;
07626    
07627       case '8':
07628          if (vms.lastmsg > -1) {
07629             cmd = forward_message(chan, context, &vms, vmu, vmfmts, 0, record_gain);
07630             if (cmd == ERROR_LOCK_PATH) {
07631                res = cmd;
07632                goto out;
07633             }
07634          } else
07635             cmd = ast_play_and_wait(chan, "vm-nomore");
07636          break;
07637       case '9':
07638          if (vms.curmsg < 0 || vms.curmsg > vms.lastmsg) {
07639             /* No message selected */
07640             cmd = 0;
07641             break;
07642          }
07643          if (useadsi)
07644             adsi_folders(chan, 1, "Save to folder...");
07645          cmd = get_folder2(chan, "vm-savefolder", 1);
07646          box = 0; /* Shut up compiler */
07647          if (cmd == '#') {
07648             cmd = 0;
07649             break;
07650          } else if (cmd > 0) {
07651             box = cmd = cmd - '0';
07652             cmd = save_to_folder(vmu, &vms, vms.curmsg, cmd);
07653             if (cmd == ERROR_LOCK_PATH) {
07654                res = cmd;
07655                goto out;
07656 #ifndef IMAP_STORAGE
07657             } else if (!cmd) {
07658                vms.deleted[vms.curmsg] = 1;
07659 #endif
07660             } else {
07661                vms.deleted[vms.curmsg] = 0;
07662                vms.heard[vms.curmsg] = 0;
07663             }
07664          }
07665          make_file(vms.fn, sizeof(vms.fn), vms.curdir, vms.curmsg);
07666          if (useadsi)
07667             adsi_message(chan, &vms);
07668          snprintf(vms.fn, sizeof(vms.fn), "vm-%s", mbox(box));
07669          if (!cmd) {
07670             cmd = ast_play_and_wait(chan, "vm-message");
07671             if (!cmd)
07672                cmd = say_and_wait(chan, vms.curmsg + 1, chan->language);
07673             if (!cmd)
07674                cmd = ast_play_and_wait(chan, "vm-savedto");
07675             if (!cmd)
07676                cmd = vm_play_folder_name(chan, vms.fn);
07677          } else {
07678             cmd = ast_play_and_wait(chan, "vm-mailboxfull");
07679          }
07680          if (ast_test_flag((&globalflags), VM_SKIPAFTERCMD)) {
07681             if (vms.curmsg < vms.lastmsg) {
07682                vms.curmsg++;
07683                cmd = play_message(chan, vmu, &vms);
07684             } else {
07685                cmd = ast_play_and_wait(chan, "vm-nomore");
07686             }
07687          }
07688          break;
07689       case '*':
07690          if (!vms.starting) {
07691             cmd = ast_play_and_wait(chan, "vm-onefor");
07692             if (!strcasecmp(chan->language, "he")) 
07693                cmd = ast_play_and_wait(chan, "vm-for");
07694             if (!cmd)
07695                cmd = vm_play_folder_name(chan, vms.vmbox);
07696             if (!cmd)
07697                cmd = ast_play_and_wait(chan, "vm-opts");
07698             if (!cmd)
07699                cmd = vm_instructions(chan, &vms, 1);
07700          } else
07701             cmd = 0;
07702          break;
07703       case '0':
07704          cmd = vm_options(chan, vmu, &vms, vmfmts, record_gain);
07705          if (useadsi)
07706             adsi_status(chan, &vms);
07707          break;
07708       default: /* Nothing */
07709          cmd = vm_instructions(chan, &vms, 0);
07710          break;
07711       }
07712    }
07713    if ((cmd == 't') || (cmd == '#')) {
07714       /* Timeout */
07715       res = 0;
07716    } else {
07717       /* Hangup */
07718       res = -1;
07719    }
07720 
07721 out:
07722    if (res > -1) {
07723       ast_stopstream(chan);
07724       adsi_goodbye(chan);
07725       if (valid) {
07726          if (silentexit)
07727             res = ast_play_and_wait(chan, "vm-dialout");
07728          else 
07729             res = ast_play_and_wait(chan, "vm-goodbye");
07730          if (res > 0)
07731             res = 0;
07732       }
07733       if (useadsi)
07734          ast_adsi_unload_session(chan);
07735    }
07736    if (vmu)
07737       close_mailbox(&vms, vmu);
07738    if (valid) {
07739       snprintf(ext_context, sizeof(ext_context), "%s@%s", vms.username, vmu->context);
07740       manager_event(EVENT_FLAG_CALL, "MessageWaiting", "Mailbox: %s\r\nWaiting: %d\r\n", ext_context, has_voicemail(ext_context, NULL));
07741       run_externnotify(vmu->context, vmu->mailbox);
07742    }
07743 #ifdef IMAP_STORAGE
07744    /* expunge message - use UID Expunge if supported on IMAP server*/
07745    if (option_debug > 2)
07746       ast_log(LOG_DEBUG, "*** Checking if we can expunge, deleted set to %d, expungeonhangup set to %d\n",deleted,expungeonhangup);
07747    if (vmu && deleted == 1 && expungeonhangup == 1 && vms.mailstream != NULL) {
07748 #ifdef HAVE_IMAP_TK2006
07749       if (LEVELUIDPLUS (vms.mailstream)) {
07750          mail_expunge_full(vms.mailstream,NIL,EX_UID);
07751       } else 
07752 #endif
07753          mail_expunge(vms.mailstream);
07754    }
07755    /*  before we delete the state, we should copy pertinent info
07756     *  back to the persistent model */
07757    vmstate_delete(&vms);
07758 #endif
07759    if (vmu)
07760       free_user(vmu);
07761    if (vms.deleted)
07762       free(vms.deleted);
07763    if (vms.heard)
07764       free(vms.heard);
07765    ast_module_user_remove(u);
07766 
07767    return res;
07768 }
07769 
07770 static int vm_exec(struct ast_channel *chan, void *data)
07771 {
07772    int res = 0;
07773    struct ast_module_user *u;
07774    char *tmp;
07775    struct leave_vm_options leave_options;
07776    struct ast_flags flags = { 0 };
07777    static int deprecate_warning = 0;
07778    char *opts[OPT_ARG_ARRAY_SIZE];
07779    AST_DECLARE_APP_ARGS(args,
07780       AST_APP_ARG(argv0);
07781       AST_APP_ARG(argv1);
07782    );
07783 
07784    u = ast_module_user_add(chan);
07785    
07786    memset(&leave_options, 0, sizeof(leave_options));
07787 
07788    if (chan->_state != AST_STATE_UP)
07789       ast_answer(chan);
07790 
07791    if (!ast_strlen_zero(data)) {
07792       tmp = ast_strdupa(data);
07793       AST_STANDARD_APP_ARGS(args, tmp);
07794       if (args.argc == 2) {
07795          if (ast_app_parse_options(vm_app_options, &flags, opts, args.argv1)) {
07796             ast_module_user_remove(u);
07797             return -1;
07798          }
07799          ast_copy_flags(&leave_options, &flags, OPT_SILENT | OPT_BUSY_GREETING | OPT_UNAVAIL_GREETING | OPT_PRIORITY_JUMP);
07800          if (ast_test_flag(&flags, OPT_RECORDGAIN)) {
07801             int gain;
07802 
07803             if (sscanf(opts[OPT_ARG_RECORDGAIN], "%d", &gain) != 1) {
07804                ast_log(LOG_WARNING, "Invalid value '%s' provided for record gain option\n", opts[OPT_ARG_RECORDGAIN]);
07805                ast_module_user_remove(u);
07806                return -1;
07807             } else {
07808                leave_options.record_gain = (signed char) gain;
07809             }
07810          }
07811       } else {
07812          /* old style options parsing */
07813          int old = 0;
07814          char *orig_argv0 = args.argv0;
07815          while (*(args.argv0)) {
07816             if (*(args.argv0) == 's') {
07817                old = 1;
07818                ast_set_flag(&leave_options, OPT_SILENT);
07819             } else if (*(args.argv0) == 'b') {
07820                old = 1;
07821                ast_set_flag(&leave_options, OPT_BUSY_GREETING);
07822             } else if (*(args.argv0) == 'u') {
07823                old = 1;
07824                ast_set_flag(&leave_options, OPT_UNAVAIL_GREETING);
07825             } else if (*(args.argv0) == 'j') {
07826                old = 1;
07827                ast_set_flag(&leave_options, OPT_PRIORITY_JUMP);
07828             } else
07829                break;
07830             (args.argv0)++;
07831          }
07832          if (!deprecate_warning && old) {
07833             deprecate_warning = 1;
07834             ast_log(LOG_WARNING, "Prefixing the mailbox with an option is deprecated ('%s').\n", orig_argv0);
07835             ast_log(LOG_WARNING, "Please move all leading options to the second argument.\n");
07836          }
07837       }
07838    } else {
07839       char tmp[256];
07840       res = ast_app_getdata(chan, "vm-whichbox", tmp, sizeof(tmp) - 1, 0);
07841       if (res < 0) {
07842          ast_module_user_remove(u);
07843          return res;
07844       }
07845       if (ast_strlen_zero(tmp)) {
07846          ast_module_user_remove(u);
07847          return 0;
07848       }
07849       args.argv0 = ast_strdupa(tmp);
07850    }
07851 
07852    res = leave_voicemail(chan, args.argv0, &leave_options);
07853 
07854    if (res == ERROR_LOCK_PATH) {
07855       ast_log(LOG_ERROR, "Could not leave voicemail. The path is already locked.\n");
07856       /*Send the call to n+101 priority, where n is the current priority*/
07857       if (ast_test_flag(&leave_options, OPT_PRIORITY_JUMP) || ast_opt_priority_jumping)
07858          if (ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101))
07859             ast_log(LOG_WARNING, "Extension %s, priority %d doesn't exist.\n", chan->exten, chan->priority + 101);
07860       pbx_builtin_setvar_helper(chan, "VMSTATUS", "FAILED");
07861       res = 0;
07862    }
07863    
07864    ast_module_user_remove(u);
07865 
07866    return res;
07867 }
07868 
07869 static struct ast_vm_user *find_or_create(char *context, char *mbox)
07870 {
07871    struct ast_vm_user *vmu;
07872    AST_LIST_TRAVERSE(&users, vmu, list) {
07873       if (ast_test_flag((&globalflags), VM_SEARCH) && !strcasecmp(mbox, vmu->mailbox))
07874          break;
07875       if (context && (!strcasecmp(context, vmu->context)) && (!strcasecmp(mbox, vmu->mailbox)))
07876          break;
07877    }
07878    
07879    if (!vmu) {
07880       if ((vmu = ast_calloc(1, sizeof(*vmu)))) {
07881          ast_copy_string(vmu->context, context, sizeof(vmu->context));
07882          ast_copy_string(vmu->mailbox, mbox, sizeof(vmu->mailbox));
07883          AST_LIST_INSERT_TAIL(&users, vmu, list);
07884       }
07885    }
07886    return vmu;
07887 }
07888 
07889 static int append_mailbox(char *context, char *mbox, char *data)
07890 {
07891    /* Assumes lock is already held */
07892    char *tmp;
07893    char *stringp;
07894    char *s;
07895    struct ast_vm_user *vmu;
07896 
07897    tmp = ast_strdupa(data);
07898 
07899    if ((vmu = find_or_create(context, mbox))) {
07900       populate_defaults(vmu);
07901 
07902       stringp = tmp;
07903       if ((s = strsep(&stringp, ","))) 
07904          ast_copy_string(vmu->password, s, sizeof(vmu->password));
07905       if (stringp && (s = strsep(&stringp, ","))) 
07906          ast_copy_string(vmu->fullname, s, sizeof(vmu->fullname));
07907       if (stringp && (s = strsep(&stringp, ","))) 
07908          ast_copy_string(vmu->email, s, sizeof(vmu->email));
07909       if (stringp && (s = strsep(&stringp, ","))) 
07910          ast_copy_string(vmu->pager, s, sizeof(vmu->pager));
07911       if (stringp && (s = strsep(&stringp, ","))) 
07912          apply_options(vmu, s);
07913    }
07914    return 0;
07915 }
07916 
07917 static int vm_box_exists(struct ast_channel *chan, void *data) 
07918 {
07919    struct ast_module_user *u;
07920    struct ast_vm_user svm;
07921    char *context, *box;
07922    int priority_jump = 0;
07923    AST_DECLARE_APP_ARGS(args,
07924       AST_APP_ARG(mbox);
07925       AST_APP_ARG(options);
07926    );
07927 
07928    if (ast_strlen_zero(data)) {
07929       ast_log(LOG_ERROR, "MailboxExists requires an argument: (vmbox[@context][|options])\n");
07930       return -1;
07931    }
07932 
07933    u = ast_module_user_add(chan);
07934 
07935    box = ast_strdupa(data);
07936 
07937    AST_STANDARD_APP_ARGS(args, box);
07938 
07939    if (args.options) {
07940       if (strchr(args.options, 'j'))
07941          priority_jump = 1;
07942    }
07943 
07944    if ((context = strchr(args.mbox, '@'))) {
07945       *context = '\0';
07946       context++;
07947    }
07948 
07949    if (find_user(&svm, context, args.mbox)) {
07950       pbx_builtin_setvar_helper(chan, "VMBOXEXISTSSTATUS", "SUCCESS");
07951       if (priority_jump || ast_opt_priority_jumping)
07952          if (ast_goto_if_exists(chan, chan->context, chan->exten, chan->priority + 101)) 
07953             ast_log(LOG_WARNING, "VM box %s@%s exists, but extension %s, priority %d doesn't exist\n", box, context, chan->exten, chan->priority + 101);
07954    } else
07955       pbx_builtin_setvar_helper(chan, "VMBOXEXISTSSTATUS", "FAILED");
07956    ast_module_user_remove(u);
07957    return 0;
07958 }
07959 
07960 static int vmauthenticate(struct ast_channel *chan, void *data)
07961 {
07962    struct ast_module_user *u;
07963    char *s = data, *user=NULL, *context=NULL, mailbox[AST_MAX_EXTENSION] = "";
07964    struct ast_vm_user vmus;
07965    char *options = NULL;
07966    int silent = 0, skipuser = 0;
07967    int res = -1;
07968 
07969    u = ast_module_user_add(chan);
07970    
07971    if (s) {
07972       s = ast_strdupa(s);
07973       user = strsep(&s, "|");
07974       options = strsep(&s, "|");
07975       if (user) {
07976          s = user;
07977          user = strsep(&s, "@");
07978          context = strsep(&s, "");
07979          if (!ast_strlen_zero(user))
07980             skipuser++;
07981          ast_copy_string(mailbox, user, sizeof(mailbox));
07982       }
07983    }
07984 
07985    if (options) {
07986       silent = (strchr(options, 's')) != NULL;
07987    }
07988 
07989    if (!vm_authenticate(chan, mailbox, sizeof(mailbox), &vmus, context, NULL, skipuser, 3, silent)) {
07990       pbx_builtin_setvar_helper(chan, "AUTH_MAILBOX", mailbox);
07991       pbx_builtin_setvar_helper(chan, "AUTH_CONTEXT", vmus.context);
07992       ast_play_and_wait(chan, "auth-thankyou");
07993       res = 0;
07994    }
07995 
07996    ast_module_user_remove(u);
07997    return res;
07998 }
07999 
08000 static char voicemail_show_users_help[] =
08001 "Usage: voicemail show users [for <context>]\n"
08002 "       Lists all mailboxes currently set up\n";
08003 
08004 static char voicemail_show_zones_help[] =
08005 "Usage: voicemail show zones\n"
08006 "       Lists zone message formats\n";
08007 
08008 static int handle_voicemail_show_users(int fd, int argc, char *argv[])
08009 {
08010    struct ast_vm_user *vmu;
08011    char *output_format = "%-10s %-5s %-25s %-10s %6s\n";
08012 
08013    if ((argc < 3) || (argc > 5) || (argc == 4)) return RESULT_SHOWUSAGE;
08014    else if ((argc == 5) && strcmp(argv[3],"for")) return RESULT_SHOWUSAGE;
08015 
08016    AST_LIST_LOCK(&users);
08017    if (!AST_LIST_EMPTY(&users)) {
08018       if (argc == 3)
08019          ast_cli(fd, output_format, "Context", "Mbox", "User", "Zone", "NewMsg");
08020       else {
08021          int count = 0;
08022          AST_LIST_TRAVERSE(&users, vmu, list) {
08023             if (!strcmp(argv[4],vmu->context))
08024                count++;
08025          }
08026          if (count) {
08027             ast_cli(fd, output_format, "Context", "Mbox", "User", "Zone", "NewMsg");
08028          } else {
08029             ast_cli(fd, "No such voicemail context \"%s\"\n", argv[4]);
08030             AST_LIST_UNLOCK(&users);
08031             return RESULT_FAILURE;
08032          }
08033       }
08034       AST_LIST_TRAVERSE(&users, vmu, list) {
08035          int newmsgs = 0, oldmsgs = 0;
08036          char count[12], tmp[256] = "";
08037 
08038          if ((argc == 3) || ((argc == 5) && !strcmp(argv[4],vmu->context))) {
08039             snprintf(tmp, sizeof(tmp), "%s@%s", vmu->mailbox, ast_strlen_zero(vmu->context) ? "default" : vmu->context);
08040             inboxcount(tmp, &newmsgs, &oldmsgs);
08041             snprintf(count,sizeof(count),"%d",newmsgs);
08042             ast_cli(fd, output_format, vmu->context, vmu->mailbox, vmu->fullname, vmu->zonetag, count);
08043          }
08044       }
08045    } else {
08046       ast_cli(fd, "There are no voicemail users currently defined\n");
08047       AST_LIST_UNLOCK(&users);
08048       return RESULT_FAILURE;
08049    }
08050    AST_LIST_UNLOCK(&users);
08051    return RESULT_SUCCESS;
08052 }
08053 
08054 static int handle_voicemail_show_zones(int fd, int argc, char *argv[])
08055 {
08056    struct vm_zone *zone;
08057    char *output_format = "%-15s %-20s %-45s\n";
08058    int res = RESULT_SUCCESS;
08059 
08060    if (argc != 3)
08061       return RESULT_SHOWUSAGE;
08062 
08063    AST_LIST_LOCK(&zones);
08064    if (!AST_LIST_EMPTY(&zones)) {
08065       ast_cli(fd, output_format, "Zone", "Timezone", "Message Format");
08066       AST_LIST_TRAVERSE(&zones, zone, list) {
08067          ast_cli(fd, output_format, zone->name, zone->timezone, zone->msg_format);
08068       }
08069    } else {
08070       ast_cli(fd, "There are no voicemail zones currently defined\n");
08071       res = RESULT_FAILURE;
08072    }
08073    AST_LIST_UNLOCK(&zones);
08074 
08075    return res;
08076 }
08077 
08078 static char *complete_voicemail_show_users(const char *line, const char *word, int pos, int state)
08079 {
08080    int which = 0;
08081    int wordlen;
08082    struct ast_vm_user *vmu;
08083    const char *context = "";
08084 
08085    /* 0 - show; 1 - voicemail; 2 - users; 3 - for; 4 - <context> */
08086    if (pos > 4)
08087       return NULL;
08088    if (pos == 3)
08089       return (state == 0) ? ast_strdup("for") : NULL;
08090    wordlen = strlen(word);
08091    AST_LIST_TRAVERSE(&users, vmu, list) {
08092       if (!strncasecmp(word, vmu->context, wordlen)) {
08093          if (context && strcmp(context, vmu->context) && ++which > state)
08094             return ast_strdup(vmu->context);
08095          /* ignore repeated contexts ? */
08096          context = vmu->context;
08097       }
08098    }
08099    return NULL;
08100 }
08101 
08102 static struct ast_cli_entry cli_show_voicemail_users_deprecated = {
08103    { "show", "voicemail", "users", NULL },
08104    handle_voicemail_show_users, NULL,
08105    NULL, complete_voicemail_show_users };
08106 
08107 static struct ast_cli_entry cli_show_voicemail_zones_deprecated = {
08108    { "show", "voicemail", "zones", NULL },
08109    handle_voicemail_show_zones, NULL,
08110    NULL, NULL };
08111 
08112 static struct ast_cli_entry cli_voicemail[] = {
08113    { { "voicemail", "show", "users", NULL },
08114    handle_voicemail_show_users, "List defined voicemail boxes",
08115    voicemail_show_users_help, complete_voicemail_show_users, &cli_show_voicemail_users_deprecated },
08116 
08117    { { "voicemail", "show", "zones", NULL },
08118    handle_voicemail_show_zones, "List zone message formats",
08119    voicemail_show_zones_help, NULL, &cli_show_voicemail_zones_deprecated },
08120 };
08121 
08122 static void free_vm_users(void)
08123 {
08124    struct ast_vm_user *cur;
08125    struct vm_zone *zcur;
08126 
08127    AST_LIST_LOCK(&users);
08128    while ((cur = AST_LIST_REMOVE_HEAD(&users, list))) {
08129       ast_set_flag(cur, VM_ALLOCED);
08130       free_user(cur);
08131    }
08132    AST_LIST_UNLOCK(&users);
08133 
08134    AST_LIST_LOCK(&zones);
08135    while ((zcur = AST_LIST_REMOVE_HEAD(&zones, list))) {
08136       free_zone(zcur);
08137    }
08138    AST_LIST_UNLOCK(&zones);
08139 }
08140 
08141 static int load_config(void)
08142 {
08143    struct ast_vm_user *cur;
08144    struct ast_config *cfg, *ucfg;
08145    char *cat;
08146    struct ast_variable *var;
08147    const char *notifystr = NULL;
08148    const char *smdistr = NULL;
08149    const char *astattach;
08150    const char *astsearch;
08151    const char *astsaycid;
08152    const char *send_voicemail;
08153 #ifdef IMAP_STORAGE
08154    const char *imap_server;
08155    const char *imap_port;
08156    const char *imap_flags;
08157    const char *imap_folder;
08158    const char *auth_user;
08159    const char *auth_password;
08160    const char *expunge_on_hangup;
08161    const char *imap_timeout;
08162 #endif
08163    const char *astcallop;
08164    const char *astreview;
08165    const char *asttempgreetwarn;
08166    const char *astskipcmd;
08167    const char *asthearenv;
08168    const char *astsaydurationinfo;
08169    const char *astsaydurationminfo;
08170    const char *silencestr;
08171    const char *maxmsgstr;
08172    const char *astdirfwd;
08173    const char *thresholdstr;
08174    const char *fmt;
08175    const char *astemail;
08176    const char *ucontext;
08177    const char *astmailcmd = SENDMAIL;
08178    const char *astforcename;
08179    const char *astforcegreet;
08180    const char *s;
08181    char *q,*stringp;
08182    const char *dialoutcxt = NULL;
08183    const char *callbackcxt = NULL;  
08184    const char *exitcxt = NULL;   
08185    const char *extpc;
08186    const char *emaildateformatstr;
08187    const char *volgainstr;
08188    int x;
08189    int tmpadsi[4];
08190 
08191    cfg = ast_config_load(VOICEMAIL_CONFIG);
08192 
08193    free_vm_users();
08194 
08195    AST_LIST_LOCK(&users);
08196 
08197    memset(ext_pass_cmd, 0, sizeof(ext_pass_cmd));
08198 
08199    if (cfg) {
08200       /* General settings */
08201 
08202       if (!(ucontext = ast_variable_retrieve(cfg, "general", "userscontext")))
08203          ucontext = "default";
08204       ast_copy_string(userscontext, ucontext, sizeof(userscontext));
08205       /* Attach voice message to mail message ? */
08206       if (!(astattach = ast_variable_retrieve(cfg, "general", "attach"))) 
08207          astattach = "yes";
08208       ast_set2_flag((&globalflags), ast_true(astattach), VM_ATTACH); 
08209 
08210       if (!(astsearch = ast_variable_retrieve(cfg, "general", "searchcontexts")))
08211          astsearch = "no";
08212       ast_set2_flag((&globalflags), ast_true(astsearch), VM_SEARCH);
08213 
08214       volgain = 0.0;
08215       if ((volgainstr = ast_variable_retrieve(cfg, "general", "volgain")))
08216          sscanf(volgainstr, "%lf", &volgain);
08217 
08218 #ifdef ODBC_STORAGE
08219       strcpy(odbc_database, "asterisk");
08220       if ((thresholdstr = ast_variable_retrieve(cfg, "general", "odbcstorage"))) {
08221          ast_copy_string(odbc_database, thresholdstr, sizeof(odbc_database));
08222       }
08223       strcpy(odbc_table, "voicemessages");
08224       if ((thresholdstr = ast_variable_retrieve(cfg, "general", "odbctable"))) {
08225          ast_copy_string(odbc_table, thresholdstr, sizeof(odbc_table));
08226       }
08227 #endif      
08228       /* Mail command */
08229       strcpy(mailcmd, SENDMAIL);
08230       if ((astmailcmd = ast_variable_retrieve(cfg, "general", "mailcmd")))
08231          ast_copy_string(mailcmd, astmailcmd, sizeof(mailcmd)); /* User setting */
08232 
08233       maxsilence = 0;
08234       if ((silencestr = ast_variable_retrieve(cfg, "general", "maxsilence"))) {
08235          maxsilence = atoi(silencestr);
08236          if (maxsilence > 0)
08237             maxsilence *= 1000;
08238       }
08239       
08240       if (!(maxmsgstr = ast_variable_retrieve(cfg, "general", "maxmsg"))) {
08241          maxmsg = MAXMSG;
08242       } else {
08243          maxmsg = atoi(maxmsgstr);
08244          if (maxmsg <= 0) {
08245             ast_log(LOG_WARNING, "Invalid number of messages per folder '%s'. Using default value %i\n", maxmsgstr, MAXMSG);
08246             maxmsg = MAXMSG;
08247          } else if (maxmsg > MAXMSGLIMIT) {
08248             ast_log(LOG_WARNING, "Maximum number of messages per folder is %i. Cannot accept value '%s'\n", MAXMSGLIMIT, maxmsgstr);
08249             maxmsg = MAXMSGLIMIT;
08250          }
08251       }
08252 
08253       /* Load date format config for voicemail mail */
08254       if ((emaildateformatstr = ast_variable_retrieve(cfg, "general", "emaildateformat"))) {
08255          ast_copy_string(emaildateformat, emaildateformatstr, sizeof(emaildateformat));
08256       }
08257 
08258       /* External password changing command */
08259       if ((extpc = ast_variable_retrieve(cfg, "general", "externpass"))) {
08260          ast_copy_string(ext_pass_cmd,extpc,sizeof(ext_pass_cmd));
08261       }
08262 #ifdef IMAP_STORAGE
08263       /* IMAP server address */
08264       if ((imap_server = ast_variable_retrieve(cfg, "general", "imapserver"))) {
08265          ast_copy_string(imapserver, imap_server, sizeof(imapserver));
08266       } else {
08267          ast_copy_string(imapserver,"localhost", sizeof(imapserver));
08268       }
08269       /* IMAP server port */
08270       if ((imap_port = ast_variable_retrieve(cfg, "general", "imapport"))) {
08271          ast_copy_string(imapport, imap_port, sizeof(imapport));
08272       } else {
08273          ast_copy_string(imapport,"143", sizeof(imapport));
08274       }
08275       /* IMAP server flags */
08276       if ((imap_flags = ast_variable_retrieve(cfg, "general", "imapflags"))) {
08277          ast_copy_string(imapflags, imap_flags, sizeof(imapflags));
08278       }
08279       /* IMAP server master username */
08280       if ((auth_user = ast_variable_retrieve(cfg, "general", "authuser"))) {
08281          ast_copy_string(authuser, auth_user, sizeof(authuser));
08282       }
08283       /* IMAP server master password */
08284       if ((auth_password = ast_variable_retrieve(cfg, "general", "authpassword"))) {
08285          ast_copy_string(authpassword, auth_password, sizeof(authpassword));
08286       }
08287       /* Expunge on exit */
08288       if ((expunge_on_hangup = ast_variable_retrieve(cfg, "general", "expungeonhangup"))) {
08289          if (ast_false(expunge_on_hangup))
08290             expungeonhangup = 0;
08291          else
08292             expungeonhangup = 1;
08293       } else {
08294          expungeonhangup = 1;
08295       }
08296       /* IMAP voicemail folder */
08297       if ((imap_folder = ast_variable_retrieve(cfg, "general", "imapfolder"))) {
08298          ast_copy_string(imapfolder, imap_folder, sizeof(imapfolder));
08299       } else {
08300          ast_copy_string(imapfolder,"INBOX", sizeof(imapfolder));
08301       }
08302 
08303       /* There is some very unorthodox casting done here. This is due
08304        * to the way c-client handles the argument passed in. It expects a 
08305        * void pointer and casts the pointer directly to a long without
08306        * first dereferencing it. */
08307 
08308       if ((imap_timeout = ast_variable_retrieve(cfg, "general", "imapreadtimeout"))) {
08309          mail_parameters(NIL, SET_READTIMEOUT, (void *) (atol(imap_timeout)));
08310       } else {
08311          mail_parameters(NIL, SET_READTIMEOUT, (void *) DEFAULT_IMAP_TCP_TIMEOUT);
08312       }
08313 
08314       if ((imap_timeout = ast_variable_retrieve(cfg, "general", "imapwritetimeout"))) {
08315          mail_parameters(NIL, SET_WRITETIMEOUT, (void *) (atol(imap_timeout)));
08316       } else {
08317          mail_parameters(NIL, SET_WRITETIMEOUT, (void *) DEFAULT_IMAP_TCP_TIMEOUT);
08318       }
08319 
08320       if ((imap_timeout = ast_variable_retrieve(cfg, "general", "imapopentimeout"))) {
08321          mail_parameters(NIL, SET_OPENTIMEOUT, (void *) (atol(imap_timeout)));
08322       } else {
08323          mail_parameters(NIL, SET_OPENTIMEOUT, (void *) DEFAULT_IMAP_TCP_TIMEOUT);
08324       }
08325 
08326       if ((imap_timeout = ast_variable_retrieve(cfg, "general", "imapclosetimeout"))) {
08327          mail_parameters(NIL, SET_CLOSETIMEOUT, (void *) (atol(imap_timeout)));
08328       } else {
08329          mail_parameters(NIL, SET_CLOSETIMEOUT, (void *) DEFAULT_IMAP_TCP_TIMEOUT);
08330       }
08331 
08332 #endif
08333       /* External voicemail notify application */
08334       
08335       if ((notifystr = ast_variable_retrieve(cfg, "general", "externnotify"))) {
08336          ast_copy_string(externnotify, notifystr, sizeof(externnotify));
08337          if (option_debug > 2)
08338             ast_log(LOG_DEBUG, "found externnotify: %s\n", externnotify);
08339          if (!strcasecmp(externnotify, "smdi")) {
08340             if (option_debug)
08341                ast_log(LOG_DEBUG, "Using SMDI for external voicemail notification\n");
08342             if ((smdistr = ast_variable_retrieve(cfg, "general", "smdiport"))) {
08343                smdi_iface = ast_smdi_interface_find(smdistr);
08344             } else {
08345                if (option_debug)
08346                   ast_log(LOG_DEBUG, "No SMDI interface set, trying default (/dev/ttyS0)\n");
08347                smdi_iface = ast_smdi_interface_find("/dev/ttyS0");
08348             }
08349 
08350             if (!smdi_iface) {
08351                ast_log(LOG_ERROR, "No valid SMDI interface specfied, disabling external voicemail notification\n");
08352                externnotify[0] = '\0';
08353             }
08354          }
08355       } else {
08356          externnotify[0] = '\0';
08357       }
08358 
08359       /* Silence treshold */
08360       silencethreshold = 256;
08361       if ((thresholdstr = ast_variable_retrieve(cfg, "general", "silencethreshold")))
08362          silencethreshold = atoi(thresholdstr);
08363       
08364       if (!(astemail = ast_variable_retrieve(cfg, "general", "serveremail"))) 
08365          astemail = ASTERISK_USERNAME;
08366       ast_copy_string(serveremail, astemail, sizeof(serveremail));
08367       
08368       vmmaxmessage = 0;
08369       if ((s = ast_variable_retrieve(cfg, "general", "maxmessage"))) {
08370          if (sscanf(s, "%d", &x) == 1) {
08371             vmmaxmessage = x;
08372          } else {
08373             ast_log(LOG_WARNING, "Invalid max message time length\n");
08374          }
08375       }
08376 
08377       vmminmessage = 0;
08378       if ((s = ast_variable_retrieve(cfg, "general", "minmessage"))) {
08379          if (sscanf(s, "%d", &x) == 1) {
08380             vmminmessage = x;
08381             if (maxsilence <= vmminmessage)
08382                ast_log(LOG_WARNING, "maxsilence should be less than minmessage or you may get empty messages\n");
08383          } else {
08384             ast_log(LOG_WARNING, "Invalid min message time length\n");
08385          }
08386       }
08387       fmt = ast_variable_retrieve(cfg, "general", "format");
08388       if (!fmt)
08389          fmt = "wav";   
08390       ast_copy_string(vmfmts, fmt, sizeof(vmfmts));
08391 
08392       skipms = 3000;
08393       if ((s = ast_variable_retrieve(cfg, "general", "maxgreet"))) {
08394          if (sscanf(s, "%d", &x) == 1) {
08395             maxgreet = x;
08396          } else {
08397             ast_log(LOG_WARNING, "Invalid max message greeting length\n");
08398          }
08399       }
08400 
08401       if ((s = ast_variable_retrieve(cfg, "general", "skipms"))) {
08402          if (sscanf(s, "%d", &x) == 1) {
08403             skipms = x;
08404          } else {
08405             ast_log(LOG_WARNING, "Invalid skipms value\n");
08406          }
08407       }
08408 
08409       maxlogins = 3;
08410       if ((s = ast_variable_retrieve(cfg, "general", "maxlogins"))) {
08411          if (sscanf(s, "%d", &x) == 1) {
08412             maxlogins = x;
08413          } else {
08414             ast_log(LOG_WARNING, "Invalid max failed login attempts\n");
08415          }
08416       }
08417 
08418       /* Force new user to record name ? */
08419       if (!(astforcename = ast_variable_retrieve(cfg, "general", "forcename"))) 
08420          astforcename = "no";
08421       ast_set2_flag((&globalflags), ast_true(astforcename), VM_FORCENAME);
08422 
08423       /* Force new user to record greetings ? */
08424       if (!(astforcegreet = ast_variable_retrieve(cfg, "general", "forcegreetings"))) 
08425          astforcegreet = "no";
08426       ast_set2_flag((&globalflags), ast_true(astforcegreet), VM_FORCEGREET);
08427 
08428       if ((s = ast_variable_retrieve(cfg, "general", "cidinternalcontexts"))){
08429          if (option_debug > 2)
08430             ast_log(LOG_DEBUG,"VM_CID Internal context string: %s\n",s);
08431          stringp = ast_strdupa(s);
08432          for (x = 0 ; x < MAX_NUM_CID_CONTEXTS ; x++){
08433             if (!ast_strlen_zero(stringp)) {
08434                q = strsep(&stringp,",");
08435                while ((*q == ' ')||(*q == '\t')) /* Eat white space between contexts */
08436                   q++;
08437                ast_copy_string(cidinternalcontexts[x], q, sizeof(cidinternalcontexts[x]));
08438                if (option_debug > 2)
08439                   ast_log(LOG_DEBUG,"VM_CID Internal context %d: %s\n", x, cidinternalcontexts[x]);
08440             } else {
08441                cidinternalcontexts[x][0] = '\0';
08442             }
08443          }
08444       }
08445       if (!(astreview = ast_variable_retrieve(cfg, "general", "review"))){
08446          if (option_debug)
08447             ast_log(LOG_DEBUG,"VM Review Option disabled globally\n");
08448          astreview = "no";
08449       }
08450       ast_set2_flag((&globalflags), ast_true(astreview), VM_REVIEW); 
08451 
08452       /*Temperary greeting reminder */
08453       if (!(asttempgreetwarn = ast_variable_retrieve(cfg, "general", "tempgreetwarn"))) {
08454          if (option_debug)
08455             ast_log(LOG_DEBUG, "VM Temperary Greeting Reminder Option disabled globally\n");
08456          asttempgreetwarn = "no";
08457       } else {
08458          if (option_debug)
08459             ast_log(LOG_DEBUG, "VM Temperary Greeting Reminder Option enabled globally\n");
08460       }
08461       ast_set2_flag((&globalflags), ast_true(asttempgreetwarn), VM_TEMPGREETWARN);
08462 
08463       if (!(astcallop = ast_variable_retrieve(cfg, "general", "operator"))){
08464          if (option_debug)
08465             ast_log(LOG_DEBUG,"VM Operator break disabled globally\n");
08466          astcallop = "no";
08467       }
08468       ast_set2_flag((&globalflags), ast_true(astcallop), VM_OPERATOR);  
08469 
08470       if (!(astsaycid = ast_variable_retrieve(cfg, "general", "saycid"))) {
08471          if (option_debug)
08472             ast_log(LOG_DEBUG,"VM CID Info before msg disabled globally\n");
08473          astsaycid = "no";
08474       } 
08475       ast_set2_flag((&globalflags), ast_true(astsaycid), VM_SAYCID); 
08476 
08477       if (!(send_voicemail = ast_variable_retrieve(cfg,"general", "sendvoicemail"))){
08478          if (option_debug)
08479             ast_log(LOG_DEBUG,"Send Voicemail msg disabled globally\n");
08480          send_voicemail = "no";
08481       }
08482       ast_set2_flag((&globalflags), ast_true(send_voicemail), VM_SVMAIL);
08483    
08484       if (!(asthearenv = ast_variable_retrieve(cfg, "general", "envelope"))) {
08485          if (option_debug)
08486             ast_log(LOG_DEBUG,"ENVELOPE before msg enabled globally\n");
08487          asthearenv = "yes";
08488       }
08489       ast_set2_flag((&globalflags), ast_true(asthearenv), VM_ENVELOPE); 
08490 
08491       if (!(astsaydurationinfo = ast_variable_retrieve(cfg, "general", "sayduration"))) {
08492          if (option_debug)
08493             ast_log(LOG_DEBUG,"Duration info before msg enabled globally\n");
08494          astsaydurationinfo = "yes";
08495       }
08496       ast_set2_flag((&globalflags), ast_true(astsaydurationinfo), VM_SAYDURATION);  
08497 
08498       saydurationminfo = 2;
08499       if ((astsaydurationminfo = ast_variable_retrieve(cfg, "general", "saydurationm"))) {
08500          if (sscanf(astsaydurationminfo, "%d", &x) == 1) {
08501             saydurationminfo = x;
08502          } else {
08503             ast_log(LOG_WARNING, "Invalid min duration for say duration\n");
08504          }
08505       }
08506 
08507       if (!(astskipcmd = ast_variable_retrieve(cfg, "general", "nextaftercmd"))) {
08508          if (option_debug)
08509             ast_log(LOG_DEBUG,"We are not going to skip to the next msg after save/delete\n");
08510          astskipcmd = "no";
08511       }
08512       ast_set2_flag((&globalflags), ast_true(astskipcmd), VM_SKIPAFTERCMD);
08513 
08514       if ((dialoutcxt = ast_variable_retrieve(cfg, "general", "dialout"))) {
08515          ast_copy_string(dialcontext, dialoutcxt, sizeof(dialcontext));
08516          if (option_debug)
08517             ast_log(LOG_DEBUG, "found dialout context: %s\n", dialcontext);
08518       } else {
08519          dialcontext[0] = '\0';  
08520       }
08521       
08522       if ((callbackcxt = ast_variable_retrieve(cfg, "general", "callback"))) {
08523          ast_copy_string(callcontext, callbackcxt, sizeof(callcontext));
08524          if (option_debug)
08525             ast_log(LOG_DEBUG, "found callback context: %s\n", callcontext);
08526       } else {
08527          callcontext[0] = '\0';
08528       }
08529 
08530       if ((exitcxt = ast_variable_retrieve(cfg, "general", "exitcontext"))) {
08531          ast_copy_string(exitcontext, exitcxt, sizeof(exitcontext));
08532          if (option_debug)
08533             ast_log(LOG_DEBUG, "found operator context: %s\n", exitcontext);
08534       } else {
08535          exitcontext[0] = '\0';
08536       }
08537 
08538       if (!(astdirfwd = ast_variable_retrieve(cfg, "general", "usedirectory"))) 
08539          astdirfwd = "no";
08540       ast_set2_flag((&globalflags), ast_true(astdirfwd), VM_DIRECFORWARD); 
08541       if ((ucfg = ast_config_load("users.conf"))) {   
08542          for (cat = ast_category_browse(ucfg, NULL); cat ; cat = ast_category_browse(ucfg, cat)) {
08543             if (!ast_true(ast_config_option(ucfg, cat, "hasvoicemail")))
08544                continue;
08545             if ((cur = find_or_create(userscontext, cat))) {
08546                populate_defaults(cur);
08547                apply_options_full(cur, ast_variable_browse(ucfg, cat));
08548                ast_copy_string(cur->context, userscontext, sizeof(cur->context));
08549             }
08550          }
08551          ast_config_destroy(ucfg);
08552       }
08553       cat = ast_category_browse(cfg, NULL);
08554       while (cat) {
08555          if (strcasecmp(cat, "general")) {
08556             var = ast_variable_browse(cfg, cat);
08557             if (strcasecmp(cat, "zonemessages")) {
08558                /* Process mailboxes in this context */
08559                while (var) {
08560                   append_mailbox(cat, var->name, var->value);
08561                   var = var->next;
08562                }
08563             } else {
08564                /* Timezones in this context */
08565                while (var) {
08566                   struct vm_zone *z;
08567                   if ((z = ast_malloc(sizeof(*z)))) {
08568                      char *msg_format, *timezone;
08569                      msg_format = ast_strdupa(var->value);
08570                      timezone = strsep(&msg_format, "|");
08571                      if (msg_format) {
08572                         ast_copy_string(z->name, var->name, sizeof(z->name));
08573                         ast_copy_string(z->timezone, timezone, sizeof(z->timezone));
08574                         ast_copy_string(z->msg_format, msg_format, sizeof(z->msg_format));
08575                         AST_LIST_LOCK(&zones);
08576                         AST_LIST_INSERT_HEAD(&zones, z, list);
08577                         AST_LIST_UNLOCK(&zones);
08578                      } else {
08579                         ast_log(LOG_WARNING, "Invalid timezone definition at line %d\n", var->lineno);
08580                         free(z);
08581                      }
08582                   } else {
08583                      free(z);
08584                      AST_LIST_UNLOCK(&users);
08585                      ast_config_destroy(cfg);
08586                      return -1;
08587                   }
08588                   var = var->next;
08589                }
08590             }
08591          }
08592          cat = ast_category_browse(cfg, cat);
08593       }
08594       memset(fromstring,0,sizeof(fromstring));
08595       memset(pagerfromstring,0,sizeof(pagerfromstring));
08596       memset(emailtitle,0,sizeof(emailtitle));
08597       strcpy(charset, "ISO-8859-1");
08598       if (emailbody) {
08599          free(emailbody);
08600          emailbody = NULL;
08601       }
08602       if (emailsubject) {
08603          free(emailsubject);
08604          emailsubject = NULL;
08605       }
08606       if (pagerbody) {
08607          free(pagerbody);
08608          pagerbody = NULL;
08609       }
08610       if (pagersubject) {
08611          free(pagersubject);
08612          pagersubject = NULL;
08613       }
08614       if ((s = ast_variable_retrieve(cfg, "general", "pbxskip")))
08615          ast_set2_flag((&globalflags), ast_true(s), VM_PBXSKIP);
08616       if ((s = ast_variable_retrieve(cfg, "general", "fromstring")))
08617          ast_copy_string(fromstring,s,sizeof(fromstring));
08618       if ((s = ast_variable_retrieve(cfg, "general", "pagerfromstring")))
08619          ast_copy_string(pagerfromstring,s,sizeof(pagerfromstring));
08620       if ((s = ast_variable_retrieve(cfg, "general", "charset")))
08621          ast_copy_string(charset,s,sizeof(charset));
08622       if ((s = ast_variable_retrieve(cfg, "general", "adsifdn"))) {
08623          sscanf(s, "%2x%2x%2x%2x", &tmpadsi[0], &tmpadsi[1], &tmpadsi[2], &tmpadsi[3]);
08624          for (x = 0; x < 4; x++) {
08625             memcpy(&adsifdn[x], &tmpadsi[x], 1);
08626          }
08627       }
08628       if ((s = ast_variable_retrieve(cfg, "general", "adsisec"))) {
08629          sscanf(s, "%2x%2x%2x%2x", &tmpadsi[0], &tmpadsi[1], &tmpadsi[2], &tmpadsi[3]);
08630          for (x = 0; x < 4; x++) {
08631             memcpy(&adsisec[x], &tmpadsi[x], 1);
08632          }
08633       }
08634       if ((s = ast_variable_retrieve(cfg, "general", "adsiver")))
08635          if (atoi(s)) {
08636             adsiver = atoi(s);
08637          }
08638       if ((s = ast_variable_retrieve(cfg, "general", "emailtitle"))) {
08639          ast_log(LOG_NOTICE, "Keyword 'emailtitle' is DEPRECATED, please use 'emailsubject' instead.\n");
08640          ast_copy_string(emailtitle,s,sizeof(emailtitle));
08641       }
08642       if ((s = ast_variable_retrieve(cfg, "general", "emailsubject")))
08643          emailsubject = ast_strdup(s);
08644       if ((s = ast_variable_retrieve(cfg, "general", "emailbody"))) {
08645          char *tmpread, *tmpwrite;
08646          emailbody = ast_strdup(s);
08647 
08648          /* substitute strings \t and \n into the appropriate characters */
08649          tmpread = tmpwrite = emailbody;
08650          while ((tmpwrite = strchr(tmpread,'\\'))) {
08651             switch (tmpwrite[1]) {
08652             case 'r':
08653                memmove(tmpwrite + 1, tmpwrite + 2, strlen(tmpwrite + 2) + 1);
08654                *tmpwrite = '\r';
08655                break;
08656             case 'n':
08657                memmove(tmpwrite + 1, tmpwrite + 2, strlen(tmpwrite + 2) + 1);
08658                *tmpwrite = '\n';
08659                break;
08660             case 't':
08661                memmove(tmpwrite + 1, tmpwrite + 2, strlen(tmpwrite + 2) + 1);
08662                *tmpwrite = '\t';
08663                break;
08664             default:
08665                ast_log(LOG_NOTICE, "Substitution routine does not support this character: %c\n", tmpwrite[1]);
08666             }
08667             tmpread = tmpwrite + 1;
08668          }
08669       }
08670       if ((s = ast_variable_retrieve(cfg, "general", "tz"))) {
08671          ast_copy_string(zonetag, s, sizeof(zonetag));
08672       }
08673       if ((s = ast_variable_retrieve(cfg, "general", "pagersubject")))
08674          pagersubject = ast_strdup(s);
08675       if ((s = ast_variable_retrieve(cfg, "general", "pagerbody"))) {
08676          char *tmpread, *tmpwrite;
08677          pagerbody = ast_strdup(s);
08678 
08679          /* substitute strings \t and \n into the appropriate characters */
08680          tmpread = tmpwrite = pagerbody;
08681          while ((tmpwrite = strchr(tmpread, '\\'))) {
08682             switch (tmpwrite[1]) {
08683             case 'r':
08684                memmove(tmpwrite + 1, tmpwrite + 2, strlen(tmpwrite + 2) + 1);
08685                *tmpwrite = '\r';
08686                break;
08687             case 'n':
08688                memmove(tmpwrite + 1, tmpwrite + 2, strlen(tmpwrite + 2) + 1);
08689                *tmpwrite = '\n';
08690                break;
08691             case 't':
08692                memmove(tmpwrite + 1, tmpwrite + 2, strlen(tmpwrite + 2) + 1);
08693                *tmpwrite = '\t';
08694                break;
08695             default:
08696                ast_log(LOG_NOTICE, "Substitution routine does not support this character: %c\n", tmpwrite[1]);
08697             }
08698             tmpread = tmpwrite + 1;
08699          }
08700       }
08701       AST_LIST_UNLOCK(&users);
08702       ast_config_destroy(cfg);
08703       return 0;
08704    } else {
08705       AST_LIST_UNLOCK(&users);
08706       ast_log(LOG_WARNING, "Failed to load configuration file.\n");
08707       return 0;
08708    }
08709 }
08710 
08711 static int reload(void)
08712 {
08713    return(load_config());
08714 }
08715 
08716 static int unload_module(void)
08717 {
08718    int res;
08719    
08720    res = ast_unregister_application(app);
08721    res |= ast_unregister_application(app2);
08722    res |= ast_unregister_application(app3);
08723    res |= ast_unregister_application(app4);
08724    ast_cli_unregister_multiple(cli_voicemail, sizeof(cli_voicemail) / sizeof(struct ast_cli_entry));
08725    ast_uninstall_vm_functions();
08726    
08727    ast_module_user_hangup_all();
08728 
08729    return res;
08730 }
08731 
08732 static int load_module(void)
08733 {
08734    int res;
08735    char *adsi_loaded = ast_module_helper("", "res_adsi.so", 0, 0, 0, 0);
08736    free(adsi_loaded);
08737    if (!adsi_loaded) {
08738       /* If embedded, res_adsi may be known as "res_adsi" not "res_adsi.so" */
08739       adsi_loaded = ast_module_helper("", "res_adsi", 0, 0, 0, 0);
08740       ast_free(adsi_loaded);
08741       if (!adsi_loaded) {
08742          ast_log(LOG_ERROR, "app_voicemail.so depends upon res_adsi.so\n");
08743          return AST_MODULE_LOAD_DECLINE;
08744       }
08745    }
08746 
08747    my_umask = umask(0);
08748    umask(my_umask);
08749    res = ast_register_application(app, vm_exec, synopsis_vm, descrip_vm);
08750    res |= ast_register_application(app2, vm_execmain, synopsis_vmain, descrip_vmain);
08751    res |= ast_register_application(app3, vm_box_exists, synopsis_vm_box_exists, descrip_vm_box_exists);
08752    res |= ast_register_application(app4, vmauthenticate, synopsis_vmauthenticate, descrip_vmauthenticate);
08753    if (res)
08754       return(res);
08755 
08756    if ((res=load_config())) {
08757       return(res);
08758    }
08759 
08760    ast_cli_register_multiple(cli_voicemail, sizeof(cli_voicemail) / sizeof(struct ast_cli_entry));
08761 
08762    /* compute the location of the voicemail spool directory */
08763    snprintf(VM_SPOOL_DIR, sizeof(VM_SPOOL_DIR), "%s/voicemail/", ast_config_AST_SPOOL_DIR);
08764 
08765    ast_install_vm_functions(has_voicemail, inboxcount, messagecount);
08766 
08767    return res;
08768 }
08769 
08770 static int dialout(struct ast_channel *chan, struct ast_vm_user *vmu, char *num, char *outgoing_context) 
08771 {
08772    int cmd = 0;
08773    char destination[80] = "";
08774    int retries = 0;
08775 
08776    if (!num) {
08777       if (option_verbose > 2)
08778          ast_verbose( VERBOSE_PREFIX_3 "Destination number will be entered manually\n");
08779       while (retries < 3 && cmd != 't') {
08780          destination[1] = '\0';
08781          destination[0] = cmd = ast_play_and_wait(chan,"vm-enter-num-to-call");
08782          if (!cmd)
08783             destination[0] = cmd = ast_play_and_wait(chan, "vm-then-pound");
08784          if (!cmd)
08785             destination[0] = cmd = ast_play_and_wait(chan, "vm-star-cancel");
08786          if (!cmd) {
08787             cmd = ast_waitfordigit(chan, 6000);
08788             if (cmd)
08789                destination[0] = cmd;
08790          }
08791          if (!cmd) {
08792             retries++;
08793          } else {
08794 
08795             if (cmd < 0)
08796                return 0;
08797             if (cmd == '*') {
08798                if (option_verbose > 2)
08799                   ast_verbose( VERBOSE_PREFIX_3 "User hit '*' to cancel outgoing call\n");
08800                return 0;
08801             }
08802             if ((cmd = ast_readstring(chan,destination + strlen(destination),sizeof(destination)-1,6000,10000,"#")) < 0) 
08803                retries++;
08804             else
08805                cmd = 't';
08806          }
08807       }
08808       if (retries >= 3) {
08809          return 0;
08810       }
08811       
08812    } else {
08813       if (option_verbose > 2)
08814          ast_verbose( VERBOSE_PREFIX_3 "Destination number is CID number '%s'\n", num);
08815       ast_copy_string(destination, num, sizeof(destination));
08816    }
08817 
08818    if (!ast_strlen_zero(destination)) {
08819       if (destination[strlen(destination) -1 ] == '*')
08820          return 0; 
08821       if (option_verbose > 2)
08822          ast_verbose( VERBOSE_PREFIX_3 "Placing outgoing call to extension '%s' in context '%s' from context '%s'\n", destination, outgoing_context, chan->context);
08823       ast_copy_string(chan->exten, destination, sizeof(chan->exten));
08824       ast_copy_string(chan->context, outgoing_context, sizeof(chan->context));
08825       chan->priority = 0;
08826       return 9;
08827    }
08828    return 0;
08829 }
08830 
08831 static int advanced_options(struct ast_channel *chan, struct ast_vm_user *vmu, struct vm_state *vms, int msg, int option, signed char record_gain)
08832 {
08833    int res = 0;
08834    char filename[PATH_MAX];
08835    struct ast_config *msg_cfg = NULL;
08836    const char *origtime, *context;
08837    char *cid, *name, *num;
08838    int retries = 0;
08839 
08840    vms->starting = 0; 
08841    make_file(vms->fn, sizeof(vms->fn), vms->curdir, msg);
08842 
08843    /* Retrieve info from VM attribute file */
08844    make_file(vms->fn2, sizeof(vms->fn2), vms->curdir, vms->curmsg);
08845    snprintf(filename,sizeof(filename), "%s.txt", vms->fn2);
08846    RETRIEVE(vms->curdir, vms->curmsg, vmu);
08847    msg_cfg = ast_config_load(filename);
08848    DISPOSE(vms->curdir, vms->curmsg);
08849    if (!msg_cfg) {
08850       ast_log(LOG_WARNING, "No message attribute file?!! (%s)\n", filename);
08851       return 0;
08852    }
08853 
08854    if (!(origtime = ast_variable_retrieve(msg_cfg, "message", "origtime"))) {
08855       ast_config_destroy(msg_cfg);
08856       return 0;
08857    }
08858 
08859    cid = ast_strdupa(ast_variable_retrieve(msg_cfg, "message", "callerid"));
08860 
08861    context = ast_variable_retrieve(msg_cfg, "message", "context");
08862    if (!strncasecmp("macro",context,5)) /* Macro names in contexts are useless for our needs */
08863       context = ast_variable_retrieve(msg_cfg, "message","macrocontext");
08864    switch (option) {
08865    case 3:
08866       if (!res)
08867          res = play_message_datetime(chan, vmu, origtime, filename);
08868       if (!res)
08869          res = play_message_callerid(chan, vms, cid, context, 0);
08870 
08871       res = 't';
08872       break;
08873 
08874    case 2:  /* Call back */
08875 
08876       if (ast_strlen_zero(cid))
08877          break;
08878 
08879       ast_callerid_parse(cid, &name, &num);
08880       while ((res > -1) && (res != 't')) {
08881          switch (res) {
08882          case '1':
08883             if (num) {
08884                /* Dial the CID number */
08885                res = dialout(chan, vmu, num, vmu->callback);
08886                if (res) {
08887                   ast_config_destroy(msg_cfg);
08888                   return 9;
08889                }
08890             } else {
08891                res = '2';
08892             }
08893             break;
08894 
08895          case '2':
08896             /* Want to enter a different number, can only do this if there's a dialout context for this user */
08897             if (!ast_strlen_zero(vmu->dialout)) {
08898                res = dialout(chan, vmu, NULL, vmu->dialout);
08899                if (res) {
08900                   ast_config_destroy(msg_cfg);
08901                   return 9;
08902                }
08903             } else {
08904                if (option_verbose > 2)
08905                   ast_verbose( VERBOSE_PREFIX_3 "Caller can not specify callback number - no dialout context available\n");
08906                res = ast_play_and_wait(chan, "vm-sorry");
08907             }
08908             ast_config_destroy(msg_cfg);
08909             return res;
08910          case '*':
08911             res = 't';
08912             break;
08913          case '3':
08914          case '4':
08915          case '5':
08916          case '6':
08917          case '7':
08918          case '8':
08919          case '9':
08920          case '0':
08921 
08922             res = ast_play_and_wait(chan, "vm-sorry");
08923             retries++;
08924             break;
08925          default:
08926             if (num) {
08927                if (option_verbose > 2)
08928                   ast_verbose( VERBOSE_PREFIX_3 "Confirm CID number '%s' is number to use for callback\n", num);
08929                res = ast_play_and_wait(chan, "vm-num-i-have");
08930                if (!res)
08931                   res = play_message_callerid(chan, vms, num, vmu->context, 1);
08932                if (!res)
08933                   res = ast_play_and_wait(chan, "vm-tocallnum");
08934                /* Only prompt for a caller-specified number if there is a dialout context specified */
08935                if (!ast_strlen_zero(vmu->dialout)) {
08936                   if (!res)
08937                      res = ast_play_and_wait(chan, "vm-calldiffnum");
08938                }
08939             } else {
08940                res = ast_play_and_wait(chan, "vm-nonumber");
08941                if (!ast_strlen_zero(vmu->dialout)) {
08942                   if (!res)
08943                      res = ast_play_and_wait(chan, "vm-toenternumber");
08944                }
08945             }
08946             if (!res)
08947                res = ast_play_and_wait(chan, "vm-star-cancel");
08948             if (!res)
08949                res = ast_waitfordigit(chan, 6000);
08950             if (!res) {
08951                retries++;
08952                if (retries > 3)
08953                   res = 't';
08954             }
08955             break; 
08956             
08957          }
08958          if (res == 't')
08959             res = 0;
08960          else if (res == '*')
08961             res = -1;
08962       }
08963       break;
08964       
08965    case 1:  /* Reply */
08966       /* Send reply directly to sender */
08967       if (ast_strlen_zero(cid))
08968          break;
08969 
08970       ast_callerid_parse(cid, &name, &num);
08971       if (!num) {
08972          if (option_verbose > 2)
08973             ast_verbose(VERBOSE_PREFIX_3 "No CID number available, no reply sent\n");
08974          if (!res)
08975             res = ast_play_and_wait(chan, "vm-nonumber");
08976          ast_config_destroy(msg_cfg);
08977          return res;
08978       } else {
08979          struct ast_vm_user vmu2;
08980          if (find_user(&vmu2, vmu->context, num)) {
08981             struct leave_vm_options leave_options;
08982             char mailbox[AST_MAX_EXTENSION * 2 + 2];
08983             snprintf(mailbox, sizeof(mailbox), "%s@%s", num, vmu->context);
08984 
08985             if (option_verbose > 2)
08986                ast_verbose(VERBOSE_PREFIX_3 "Leaving voicemail for '%s' in context '%s'\n", num, vmu->context);
08987             
08988             memset(&leave_options, 0, sizeof(leave_options));
08989             leave_options.record_gain = record_gain;
08990             res = leave_voicemail(chan, mailbox, &leave_options);
08991             if (!res)
08992                res = 't';
08993             ast_config_destroy(msg_cfg);
08994             return res;
08995          } else {
08996             /* Sender has no mailbox, can't reply */
08997             if (option_verbose > 2)
08998                ast_verbose( VERBOSE_PREFIX_3 "No mailbox number '%s' in context '%s', no reply sent\n", num, vmu->context);
08999             ast_play_and_wait(chan, "vm-nobox");
09000             res = 't';
09001             ast_config_destroy(msg_cfg);
09002             return res;
09003          }
09004       } 
09005       res = 0;
09006 
09007       break;
09008    }
09009 
09010 #ifndef IMAP_STORAGE
09011    ast_config_destroy(msg_cfg);
09012 
09013    if (!res) {
09014       make_file(vms->fn, sizeof(vms->fn), vms->curdir, msg);
09015       vms->heard[msg] = 1;
09016       res = wait_file(chan, vms, vms->fn);
09017    }
09018 #endif
09019    return res;
09020 }
09021 
09022 static int play_record_review(struct ast_channel *chan, char *playfile, char *recordfile, int maxtime, char *fmt,
09023          int outsidecaller, struct ast_vm_user *vmu, int *duration, const char *unlockdir,
09024          signed char record_gain, struct vm_state *vms)
09025 {
09026    /* Record message & let caller review or re-record it, or set options if applicable */
09027    int res = 0;
09028    int cmd = 0;
09029    int max_attempts = 3;
09030    int attempts = 0;
09031    int recorded = 0;
09032    int message_exists = 0;
09033    signed char zero_gain = 0;
09034    char tempfile[PATH_MAX];
09035    char *acceptdtmf = "#";
09036    char *canceldtmf = "";
09037 
09038    /* Note that urgent and private are for flagging messages as such in the future */
09039 
09040    /* barf if no pointer passed to store duration in */
09041    if (duration == NULL) {
09042       ast_log(LOG_WARNING, "Error play_record_review called without duration pointer\n");
09043       return -1;
09044    }
09045 
09046    if (!outsidecaller)
09047       snprintf(tempfile, sizeof(tempfile), "%s.tmp", recordfile);
09048    else
09049       ast_copy_string(tempfile, recordfile, sizeof(tempfile));
09050 
09051    cmd = '3';  /* Want to start by recording */
09052 
09053    while ((cmd >= 0) && (cmd != 't')) {
09054       switch (cmd) {
09055       case '1':
09056          if (!message_exists) {
09057             /* In this case, 1 is to record a message */
09058             cmd = '3';
09059             break;
09060          } else {
09061             /* Otherwise 1 is to save the existing message */
09062             if (option_verbose > 2)
09063                ast_verbose(VERBOSE_PREFIX_3 "Saving message as is\n");
09064             if (!outsidecaller)
09065                ast_filerename(tempfile, recordfile, NULL);
09066             ast_stream_and_wait(chan, "vm-msgsaved", chan->language, "");
09067             if (!outsidecaller) {
09068                STORE(recordfile, vmu->mailbox, vmu->context, -1, chan, vmu, fmt, *duration, vms);
09069                DISPOSE(recordfile, -1);
09070             }
09071             cmd = 't';
09072             return res;
09073          }
09074       case '2':
09075          /* Review */
09076          if (option_verbose > 2)
09077             ast_verbose(VERBOSE_PREFIX_3 "Reviewing the message\n");
09078          cmd = ast_stream_and_wait(chan, tempfile, chan->language, AST_DIGIT_ANY);
09079          break;
09080       case '3':
09081          message_exists = 0;
09082          /* Record */
09083          if (recorded == 1) {
09084             if (option_verbose > 2)
09085                ast_verbose(VERBOSE_PREFIX_3 "Re-recording the message\n");
09086          } else { 
09087             if (option_verbose > 2)
09088                ast_verbose(VERBOSE_PREFIX_3 "Recording the message\n");
09089          }
09090          if (recorded && outsidecaller) {
09091             cmd = ast_play_and_wait(chan, INTRO);
09092             cmd = ast_play_and_wait(chan, "beep");
09093          }
09094          recorded = 1;
09095          /* After an attempt has been made to record message, we have to take care of INTRO and beep for incoming messages, but not for greetings */
09096          if (record_gain)
09097             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &record_gain, sizeof(record_gain), 0);
09098          if (ast_test_flag(vmu, VM_OPERATOR))
09099             canceldtmf = "0";
09100          cmd = ast_play_and_record_full(chan, playfile, tempfile, maxtime, fmt, duration, silencethreshold, maxsilence, unlockdir, acceptdtmf, canceldtmf);
09101          if (record_gain)
09102             ast_channel_setoption(chan, AST_OPTION_RXGAIN, &zero_gain, sizeof(zero_gain), 0);
09103          if (cmd == -1) {
09104             /* User has hung up, no options to give */
09105             if (!outsidecaller) {
09106                /* user was recording a greeting and they hung up, so let's delete the recording. */
09107                ast_filedelete(tempfile, NULL);
09108             }
09109             return cmd;
09110          }
09111          if (cmd == '0') {
09112             break;
09113          } else if (cmd == '*') {
09114             break;
09115          } 
09116 #if 0       
09117          else if (vmu->review && (*duration < 5)) {
09118             /* Message is too short */
09119             if (option_verbose > 2)
09120                ast_verbose(VERBOSE_PREFIX_3 "Message too short\n");
09121             cmd = ast_play_and_wait(chan, "vm-tooshort");
09122             cmd = ast_filedelete(tempfile, NULL);
09123             break;
09124          }
09125          else if (vmu->review && (cmd == 2 && *duration < (maxsilence + 3))) {
09126             /* Message is all silence */
09127             if (option_verbose > 2)
09128                ast_verbose(VERBOSE_PREFIX_3 "Nothing recorded\n");
09129             cmd = ast_filedelete(tempfile, NULL);
09130             cmd = ast_play_and_wait(chan, "vm-nothingrecorded");
09131             if (!cmd)
09132                cmd = ast_play_and_wait(chan, "vm-speakup");
09133             break;
09134          }
09135 #endif
09136          else {
09137             /* If all is well, a message exists */
09138             message_exists = 1;
09139             cmd = 0;
09140          }
09141          break;
09142       case '4':
09143       case '5':
09144       case '6':
09145       case '7':
09146       case '8':
09147       case '9':
09148       case '*':
09149       case '#':
09150          cmd = ast_play_and_wait(chan, "vm-sorry");
09151          break;
09152 #if 0 
09153 /*  XXX Commented out for the moment because of the dangers of deleting
09154     a message while recording (can put the message numbers out of sync) */
09155       case '*':
09156          /* Cancel recording, delete message, offer to take another message*/
09157          cmd = ast_play_and_wait(chan, "vm-deleted");
09158          cmd = ast_filedelete(tempfile, NULL);
09159          if (outsidecaller) {
09160             res = vm_exec(chan, NULL);
09161             return res;
09162          }
09163          else
09164             return 1;
09165 #endif
09166       case '0':
09167          if (!ast_test_flag(vmu, VM_OPERATOR)) {
09168             cmd = ast_play_and_wait(chan, "vm-sorry");
09169             break;
09170          }
09171          if (message_exists || recorded) {
09172             cmd = ast_play_and_wait(chan, "vm-saveoper");
09173             if (!cmd)
09174                cmd = ast_waitfordigit(chan, 3000);
09175             if (cmd == '1') {
09176                ast_play_and_wait(chan, "vm-msgsaved");
09177                cmd = '0';
09178             } else {
09179                ast_play_and_wait(chan, "vm-deleted");
09180                DELETE(recordfile, -1, recordfile, vmu);
09181                cmd = '0';
09182             }
09183          }
09184          return cmd;
09185       default:
09186          /* If the caller is an ouside caller, and the review option is enabled,
09187             allow them to review the message, but let the owner of the box review
09188             their OGM's */
09189          if (outsidecaller && !ast_test_flag(vmu, VM_REVIEW))
09190             return cmd;
09191          if (message_exists) {
09192             cmd = ast_play_and_wait(chan, "vm-review");
09193          }
09194          else {
09195             cmd = ast_play_and_wait(chan, "vm-torerecord");
09196             if (!cmd)
09197                cmd = ast_waitfordigit(chan, 600);
09198          }
09199          
09200          if (!cmd && outsidecaller && ast_test_flag(vmu, VM_OPERATOR)) {
09201             cmd = ast_play_and_wait(chan, "vm-reachoper");
09202             if (!cmd)
09203                cmd = ast_waitfordigit(chan, 600);
09204          }
09205 #if 0
09206          if (!cmd)
09207             cmd = ast_play_and_wait(chan, "vm-tocancelmsg");
09208 #endif
09209          if (!cmd)
09210             cmd = ast_waitfordigit(chan, 6000);
09211          if (!cmd) {
09212             attempts++;
09213          }
09214          if (attempts > max_attempts) {
09215             cmd = 't';
09216          }
09217       }
09218    }
09219    if (outsidecaller)
09220       ast_play_and_wait(chan, "vm-goodbye");
09221    if (cmd == 't')
09222       cmd = 0;
09223    return cmd;
09224 }
09225 
09226 /* This is a workaround so that menuselect displays a proper description
09227  * AST_MODULE_INFO(, , "Comedian Mail (Voicemail System)"
09228  */
09229  
09230 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, tdesc,
09231       .load = load_module,
09232       .unload = unload_module,
09233       .reload = reload,
09234       );

Generated on Fri Jul 3 20:35:33 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9