9d483ba177dea2b89840559574079b0b6964fc6e
[citadel.git] / webcit / subst.c
1 /*
2  * $Id$
3  */
4 /**
5  * \defgroup Subst Variable substitution type stuff
6  * \ingroup CitadelConfig
7  */
8
9 /*@{*/
10
11 #include "sysdep.h"
12 #include <sys/types.h>
13 #include <sys/stat.h>
14 #include <unistd.h>
15 #include <dirent.h>
16 #include <errno.h>
17 #include <stdarg.h>
18 #define SHOW_ME_VAPPEND_PRINTF
19
20 #include "webcit.h"
21 #include "webserver.h"
22
23 extern char *static_dirs[PATH_MAX];  /**< Disk representation */
24
25 HashList *WirelessTemplateCache;
26 HashList *WirelessLocalTemplateCache;
27 HashList *TemplateCache;
28 HashList *LocalTemplateCache;
29
30 HashList *GlobalNS;
31 HashList *Iterators;
32 HashList *Contitionals;
33
34 int LoadTemplates = 0;
35
36 #define SV_GETTEXT 1
37 #define SV_CONDITIONAL 2
38 #define SV_NEG_CONDITIONAL 3
39 #define SV_CUST_STR_CONDITIONAL 4
40 #define SV_SUBTEMPL 5
41
42 typedef struct _WCTemplate {
43         StrBuf *Data;
44         StrBuf *FileName;
45         int nTokensUsed;
46         int TokenSpace;
47         WCTemplateToken **Tokens;
48 } WCTemplate;
49
50 typedef struct _HashHandler {
51         int nMinArgs;
52         int nMaxArgs;
53         WCHandlerFunc HandlerFunc;
54 }HashHandler;
55
56 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere);
57
58 void RegisterNS(const char *NSName, long len, int nMinArgs, int nMaxArgs, WCHandlerFunc HandlerFunc)
59 {
60         HashHandler *NewHandler;
61         
62         NewHandler = (HashHandler*) malloc(sizeof(HashHandler));
63         NewHandler->nMinArgs = nMinArgs;
64         NewHandler->nMaxArgs = nMaxArgs;
65         NewHandler->HandlerFunc = HandlerFunc;  
66         Put(GlobalNS, NSName, len, NewHandler, NULL);
67 }
68
69
70 /**
71  * \brief debugging function to print array to log
72  */
73 void VarPrintTransition(void *vVar1, void *vVar2, int odd){}
74 /**
75  * \brief debugging function to print array to log
76  */
77 void VarPrintEntry(const char *Key, void *vSubst, int odd)
78 {
79         wcsubst *ptr;
80         lprintf(1,"Subst[%s] : ", Key);
81         ptr = (wcsubst*) vSubst;
82
83         switch(ptr->wcs_type) {
84         case WCS_STRING:
85                 lprintf(1, "  -> %s\n", ChrPtr(ptr->wcs_value));
86                 break;
87         case WCS_SERVCMD:
88                 lprintf(1, "  -> Server [%s]\n", ChrPtr(ptr->wcs_value));
89                 break;
90         case WCS_FUNCTION:
91                 lprintf(1, "  -> function at [%0xd]\n", ptr->wcs_function);
92                 break;
93         default:
94                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", ptr->wcs_type);
95         }
96 }
97
98
99
100 /**
101  * \brief Clear out the list of substitution variables local to this session
102  */
103 void clear_substs(struct wcsession *wc) {
104
105         if (wc->vars != NULL) {
106                 DeleteHash(&wc->vars);
107         }
108 }
109
110 /**
111  * \brief Clear out the list of substitution variables local to this session
112  */
113 void clear_local_substs(void) {
114         clear_substs (WC);
115 }
116
117 int NeedNewBuf(type)
118 {
119         switch(type) {
120         case WCS_STRING:
121         case WCS_SERVCMD:
122         case WCS_STRBUF:
123                 return 1;
124         case WCS_FUNCTION:
125         case WCS_STRBUF_REF:
126         case WCS_LONG:
127         default:
128                 return 0;
129         }
130 }
131
132 void FlushPayload(wcsubst *ptr, int reusestrbuf, int type)
133 {
134         int NeedNew = NeedNewBuf(type);
135         switch(ptr->wcs_type) {
136         case WCS_STRING:
137         case WCS_SERVCMD:
138         case WCS_STRBUF:
139                 if (reusestrbuf && NeedNew) {
140                         FlushStrBuf(ptr->wcs_value);
141                 }
142                 else {
143                         
144                         FreeStrBuf(&ptr->wcs_value);
145                         ptr->wcs_value = NULL;
146                 }
147                 break;
148         case WCS_FUNCTION:
149                 ptr->wcs_function = NULL;
150                 if (reusestrbuf && NeedNew)
151                         ptr->wcs_value = NewStrBuf();
152                 break;
153         case WCS_STRBUF_REF:
154                 ptr->wcs_value = NULL;
155                 if (reusestrbuf && NeedNew)
156                         ptr->wcs_value = NewStrBuf();
157                 break;
158         case WCS_LONG:
159                 ptr->lvalue = 0;
160                 if (reusestrbuf && NeedNew)
161                         ptr->wcs_value = NewStrBuf();
162                 break;
163         default:
164                 if (reusestrbuf && NeedNew)
165                         ptr->wcs_value = NewStrBuf();
166                 break;
167         }
168 }
169
170 /**
171  * \brief destructor; kill one entry.
172  */
173 void deletevar(void *data)
174 {
175         wcsubst *ptr = (wcsubst*)data;
176         FlushPayload(ptr, 0, ptr->wcs_type);
177         free(ptr);      
178 }
179
180
181 wcsubst *NewSubstVar(const char *keyname, int keylen, int type)
182 {
183         wcsubst* ptr;
184         struct wcsession *WCC = WC;
185
186         ptr = (wcsubst *) malloc(sizeof(wcsubst));
187         memset(ptr, 0, sizeof(wcsubst));
188
189         ptr->wcs_type = type;
190         safestrncpy(ptr->wcs_key, keyname, sizeof ptr->wcs_key);
191         Put(WCC->vars, keyname, keylen, ptr,  deletevar);
192
193         switch(ptr->wcs_type) {
194         case WCS_STRING:
195         case WCS_SERVCMD:
196                 ptr->wcs_value = NewStrBuf();
197                 break;
198         case WCS_STRBUF:
199         case WCS_FUNCTION:
200         case WCS_STRBUF_REF:
201         case WCS_LONG:
202         default:
203                 break;
204         }
205         return ptr;
206 }
207
208
209 /**
210  * \brief Add a substitution variable (local to this session) (strlen version...)
211  * \param keyname the replacementstring to substitute
212  * \param keytype the kind of the key
213  * \param format the format string ala printf
214  * \param ... the arguments to substitute in the formatstring
215  */
216 void SVPRINTF(char *keyname, int keytype, const char *format,...)
217 {
218         va_list arg_ptr;
219         void *vPtr;
220         wcsubst *ptr = NULL;
221         size_t keylen;
222         struct wcsession *WCC = WC;
223         
224         keylen = strlen(keyname);
225         /**
226          * First look if we're doing a replacement of
227          * an existing key
228          */
229         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
230         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
231                 ptr = (wcsubst*)vPtr;
232                 FlushPayload(ptr, keytype, keytype);
233                 ptr->wcs_type = keytype;
234         }
235         else    /** Otherwise allocate a new one */
236         {
237                 ptr = NewSubstVar(keyname, keylen, keytype);
238         }
239
240         /** Format the string */
241         va_start(arg_ptr, format);
242         StrBufVAppendPrintf(ptr->wcs_value, format, arg_ptr);
243         va_end(arg_ptr);
244 }
245
246 /**
247  * \brief Add a substitution variable (local to this session)
248  * \param keyname the replacementstring to substitute
249  * \param keytype the kind of the key
250  * \param format the format string ala printf
251  * \param ... the arguments to substitute in the formatstring
252  */
253 void svprintf(char *keyname, size_t keylen, int keytype, const char *format,...)
254 {
255         va_list arg_ptr;
256         void *vPtr;
257         wcsubst *ptr = NULL;
258         struct wcsession *WCC = WC;
259                 
260         /**
261          * First look if we're doing a replacement of
262          * an existing key
263          */
264         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
265         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
266                 ptr = (wcsubst*)vPtr;
267                 FlushPayload(ptr, 1, keytype);
268                 ptr->wcs_type = keytype;
269         }
270         else    /** Otherwise allocate a new one */
271         {
272                 ptr = NewSubstVar(keyname, keylen, keytype);
273         }
274
275         /** Format the string and save it */
276         va_start(arg_ptr, format);
277         StrBufVAppendPrintf(ptr->wcs_value, format, arg_ptr);
278         va_end(arg_ptr);
279 }
280
281 /**
282  * \brief Add a substitution variable (local to this session)
283  * \param keyname the replacementstring to substitute
284  * \param keytype the kind of the key
285  * \param format the format string ala printf
286  * \param ... the arguments to substitute in the formatstring
287  */
288 void SVPut(char *keyname, size_t keylen, int keytype, char *Data)
289 {
290         void *vPtr;
291         wcsubst *ptr = NULL;
292         struct wcsession *WCC = WC;
293
294         
295         /**
296          * First look if we're doing a replacement of
297          * an existing key
298          */
299         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
300         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
301                 ptr = (wcsubst*)vPtr;
302                 FlushPayload(ptr, 1, keytype);
303                 ptr->wcs_type = keytype;
304         }
305         else    /** Otherwise allocate a new one */
306         {
307                 ptr = NewSubstVar(keyname, keylen, keytype);
308         }
309         StrBufAppendBufPlain(ptr->wcs_value, Data, -1, 0);
310 }
311
312 /**
313  * \brief Add a substitution variable (local to this session)
314  * \param keyname the replacementstring to substitute
315  * \param keytype the kind of the key
316  * \param format the format string ala printf
317  * \param ... the arguments to substitute in the formatstring
318  */
319 void SVPutLong(char *keyname, size_t keylen, long Data)
320 {
321         void *vPtr;
322         wcsubst *ptr = NULL;
323         struct wcsession *WCC = WC;
324
325         
326         /**
327          * First look if we're doing a replacement of
328          * an existing key
329          */
330         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
331         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
332                 ptr = (wcsubst*)vPtr;
333                 FlushPayload(ptr, 1, WCS_LONG);
334                 ptr->wcs_type = WCS_LONG;
335         }
336         else    /** Otherwise allocate a new one */
337         {
338                 ptr = NewSubstVar(keyname, keylen, WCS_LONG);
339         }
340         ptr->lvalue = Data;
341 }
342
343 /**
344  * \brief Add a substitution variable (local to this session) that does a callback
345  * \param keyname the keystring to substitute
346  * \param fcn_ptr the function callback to give the substitution string
347  */
348 void SVCallback(char *keyname, size_t keylen, var_callback_fptr fcn_ptr)
349 {
350         wcsubst *ptr;
351         void *vPtr;
352         struct wcsession *WCC = WC;
353
354         /**
355          * First look if we're doing a replacement of
356          * an existing key
357          */
358         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
359         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
360                 ptr = (wcsubst*)vPtr;
361                 FlushPayload(ptr, 1, WCS_FUNCTION);
362                 ptr->wcs_type = WCS_FUNCTION;
363         }
364         else    /** Otherwise allocate a new one */
365         {
366                 ptr = NewSubstVar(keyname, keylen, WCS_FUNCTION);
367         }
368
369         ptr->wcs_function = fcn_ptr;
370 }
371 inline void SVCALLBACK(char *keyname, var_callback_fptr fcn_ptr)
372 {
373         SVCallback(keyname, strlen(keyname), fcn_ptr);
374 }
375
376
377
378 void SVPUTBuf(const char *keyname, int keylen, StrBuf *Buf, int ref)
379 {
380         wcsubst *ptr;
381         void *vPtr;
382         struct wcsession *WCC = WC;
383
384         /**
385          * First look if we're doing a replacement of
386          * an existing key
387          */
388         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
389         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
390                 ptr = (wcsubst*)vPtr;
391                 FlushPayload(ptr, 0, (ref)?WCS_STRBUF_REF:WCS_STRBUF);
392                 ptr->wcs_type = (ref)?WCS_STRBUF_REF:WCS_STRBUF;
393         }
394         else    /** Otherwise allocate a new one */
395         {
396                 ptr = NewSubstVar(keyname, keylen, (ref)?WCS_STRBUF_REF:WCS_STRBUF);
397         }
398         ptr->wcs_value = Buf;
399 }
400
401 /**
402  * \brief back end for print_value_of() ... does a server command
403  * \param servcmd server command to execute on the citadel server
404  */
405 void pvo_do_cmd(StrBuf *Target, StrBuf *servcmd) {
406         char buf[SIZ];
407         int len;
408
409         serv_puts(ChrPtr(servcmd));
410         len = serv_getln(buf, sizeof buf);
411
412         switch(buf[0]) {
413                 case '2':
414                 case '3':
415                 case '5':
416                         StrBufAppendPrintf(Target, "%s\n", &buf[4]);
417                         break;
418                 case '1':
419                         _fmout(Target, "CENTER");
420                         break;
421                 case '4':
422                         StrBufAppendPrintf(Target, "%s\n", &buf[4]);
423                         serv_puts("000");
424                         break;
425         }
426 }
427
428 /**
429  * \brief Print the value of a variable
430  * \param keyname get a key to print
431  */
432 void print_value_of(StrBuf *Target, const char *keyname, size_t keylen) {
433         struct wcsession *WCC = WC;
434         wcsubst *ptr;
435         void *fcn();
436         void *vVar;
437
438         /*if (WCC->vars != NULL) PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
439         /// TODO: debricated!
440         if (keyname[0] == '=') {
441                 DoTemplate(keyname+1, keylen - 1, NULL, NULL);
442         }
443
444 //////TODO: if param[1] == "U" -> urlescape
445 /// X -> escputs
446         /** Page-local variables */
447         if ((WCC->vars!= NULL) && GetHash(WCC->vars, keyname, keylen, &vVar)) {
448                 ptr = (wcsubst*) vVar;
449                 switch(ptr->wcs_type) {
450                 case WCS_STRING:
451                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
452                         break;
453                 case WCS_SERVCMD:
454                         pvo_do_cmd(Target, ptr->wcs_value);
455                         break;
456                 case WCS_FUNCTION:
457                         (*ptr->wcs_function) ();
458                         break;
459                 case WCS_STRBUF:
460                 case WCS_STRBUF_REF:
461                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
462                         break;
463                 case WCS_LONG:
464                         StrBufAppendPrintf(Target, "%ld", ptr->lvalue);
465                         break;
466                 default:
467                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!", keyname);
468                 }
469         }
470 }
471
472
473 void PutNewToken(WCTemplate *Template, WCTemplateToken *NewToken)
474 {
475         if (Template->nTokensUsed + 1 >= Template->TokenSpace) {
476                 if (Template->TokenSpace <= 0) {
477                         Template->Tokens = (WCTemplateToken**)malloc(
478                                 sizeof(WCTemplateToken*) * 10);
479                         Template->TokenSpace = 10;
480                 }
481                 else {
482                         WCTemplateToken **NewTokens;
483                         NewTokens= (WCTemplateToken**)malloc(
484                                 sizeof(WCTemplateToken*) * 
485                                 Template->TokenSpace * 2);
486                         memcpy(NewTokens, Template->Tokens, 
487                                sizeof(WCTemplateToken*) * Template->nTokensUsed);
488                         free(Template->Tokens);
489                         Template->TokenSpace *= 2;
490                         Template->Tokens = NewTokens;
491                 }
492         }
493         Template->Tokens[(Template->nTokensUsed)++] = NewToken;
494 }
495
496 TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe, WCTemplateToken *Token, WCTemplate *pTmpl)
497 {
498         const char *pch = *pCh;
499         const char *pchs, *pche;
500         TemplateParam *Parm = (TemplateParam *) malloc(sizeof(TemplateParam));
501         char quote = '\0';
502         
503         /* Skip leading whitespaces */
504         while ((*pch == ' ' )||
505                (*pch == '\t')||
506                (*pch == '\r')||
507                (*pch == '\n')) pch ++;
508         if (*pch == '"')
509                 quote = '"';
510         else if (*pch == '\'')
511                 quote = '\'';
512         if (quote != '\0') {
513                 pch ++;
514                 pchs = pch;
515                 Parm->Type = TYPE_STR;
516                 while (pch <= pe &&
517                        ((*pch != quote) ||
518                         ( (pch > pchs) && (*(pch - 1) == '\\'))
519                                )) {
520                         pch ++;
521                 }
522                 pche = pch;
523                 if (*pch != quote) {
524                         lprintf(1, "Error (in '%s' line %ld); "
525                                 "evaluating template param [%s] in Token [%s]\n",
526                                 ChrPtr(pTmpl->FileName),
527                                 Token->Line,
528                                 ChrPtr(Token->FlatToken),
529                                 *pCh);
530                         pch ++;
531                         free(Parm);
532                         return NULL;
533                 }
534                 else {
535                         StrBufPeek(Buf, pch, -1, '\0');         
536                         if (LoadTemplates > 1) {                        
537                                 lprintf(1, "DBG: got param [%s] %ld %ld\n", 
538                                         pchs, pche - pchs, strlen(pchs));
539                         }
540                         Parm->Start = pchs;
541                         Parm->len = pche - pchs;
542                         pch ++; /* move after trailing quote */
543                 }
544         }
545         else {
546                 Parm->Type = TYPE_LONG;
547                 pchs = pch;
548                 while ((pch <= pe) &&
549                        (isdigit(*pch) ||
550                         (*pch == '+') ||
551                         (*pch == '-')))
552                         pch ++;
553                 pch ++;
554                 if (pch - pchs > 1){
555                         StrBufPeek(Buf, pch, -1, '\0');
556                         Parm->lvalue = atol(pchs);
557                         Parm->Start = pchs;
558                         pch++;
559                 }
560                 else {
561                         Parm->lvalue = 0;
562                         lprintf(1, "Error (in '%s' line %ld); "
563                                 "evaluating long template param [%s] in Token [%s]\n",
564                                 ChrPtr(pTmpl->FileName),
565                                 Token->Line,
566                                 ChrPtr(Token->FlatToken),
567                                 *pCh);
568                         free(Parm);
569                         return NULL;
570                 }
571         }
572         while ((*pch == ' ' )||
573                (*pch == '\t')||
574                (*pch == '\r')||
575                (*pch == ',' )||
576                (*pch == '\n')) pch ++;
577
578         *pCh = pch;
579         return Parm;
580 }
581
582 WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf, 
583                                        const char *pStart, 
584                                        const char *pTmplStart, 
585                                        const char *pTmplEnd, 
586                                        long Line,
587                                        WCTemplate *pTmpl)
588 {
589         const char *pch;
590         TemplateParam *Param;
591         WCTemplateToken *NewToken = (WCTemplateToken*)malloc(sizeof(WCTemplateToken));
592
593         NewToken->Flags = 0;
594         NewToken->Line = Line + 1;
595         NewToken->pTokenStart = pTmplStart;
596         NewToken->TokenStart = pTmplStart - pStart;
597         NewToken->TokenEnd =  (pTmplEnd - pStart) - NewToken->TokenStart;
598         NewToken->pTokenEnd = pTmplEnd;
599         NewToken->NameEnd = NewToken->TokenEnd - 2;
600         NewToken->FlatToken = NewStrBufPlain(pTmplStart, pTmplEnd - pTmplStart);
601         
602         StrBufPeek(Buf, pTmplStart, + 1, '\0');
603         StrBufPeek(Buf, pTmplEnd, -1, '\0');
604         pch = NewToken->pName = pTmplStart + 2;
605
606         NewToken->HaveParameters = 0;;
607         NewToken->nParameters = 0;
608
609         while (pch < pTmplEnd - 1) {
610                 if (*pch == '(') {
611                         StrBufPeek(Buf, pch, -1, '\0');
612                         NewToken->NameEnd = pch - NewToken->pName;
613                         pch ++;
614                         while (pch < pTmplEnd - 1) {
615                                 Param = GetNextParameter(Buf, &pch, pTmplEnd - 1, NewToken, pTmpl);
616                                 if (Param != NULL) {
617                                         NewToken->HaveParameters = 1;
618                                         if (NewToken->nParameters > MAXPARAM) {
619                                                 lprintf(1, "Only %ld Tokens supported!\n", MAXPARAM);
620                                                 free(Param);
621                                                 return NULL;
622                                         }
623                                         NewToken->Params[NewToken->nParameters++] = Param;
624                                 }
625                                 else break;
626                         }
627                         if((NewToken->NameEnd == 1) &&
628                            (NewToken->HaveParameters == 1))
629                            
630                         {
631                                 if ((NewToken->nParameters == 1) &&
632                                     (*(NewToken->pName) == '_'))
633                                         NewToken->Flags = SV_GETTEXT;
634                                 else if ((NewToken->nParameters == 1) &&
635                                          (*(NewToken->pName) == '='))
636                                         NewToken->Flags = SV_SUBTEMPL;
637                                 else if ((NewToken->nParameters >= 2) &&
638                                          (*(NewToken->pName) == '%'))
639                                         NewToken->Flags = SV_CUST_STR_CONDITIONAL;
640                                 else if ((NewToken->nParameters >= 2) &&
641                                          (*(NewToken->pName) == '?'))
642                                         NewToken->Flags = SV_CONDITIONAL;
643                                 else if ((NewToken->nParameters >=2) &&
644                                          (*(NewToken->pName) == '!'))
645                                         NewToken->Flags = SV_NEG_CONDITIONAL;
646                         }
647                 }
648                 else pch ++;            
649         }
650         return NewToken;
651 }
652
653 void FreeToken(WCTemplateToken **Token)
654 {
655         int i; 
656         FreeStrBuf(&(*Token)->FlatToken);
657         if ((*Token)->HaveParameters) 
658                 for (i = 0; i < (*Token)->nParameters; i++)
659                         free((*Token)->Params[i]);
660         free(*Token);
661         *Token = NULL;
662 }
663
664
665
666 void FreeWCTemplate(void *vFreeMe)
667 {
668         int i;
669         WCTemplate *FreeMe = (WCTemplate*)vFreeMe;
670
671         if (FreeMe->TokenSpace > 0) {
672                 for (i = 0; i < FreeMe->nTokensUsed; i ++) {
673                         FreeToken(&FreeMe->Tokens[i]);
674                 }
675                 free(FreeMe->Tokens);
676         }
677         FreeStrBuf(&FreeMe->FileName);
678         FreeStrBuf(&FreeMe->Data);
679         free(FreeMe);
680 }
681
682
683 int EvaluateConditional(WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int Neg, int state)
684 {
685         void *vConditional;
686         ConditionalStruct *Cond;
687
688         if ((Token->Params[0]->len == 1) &&
689             (Token->Params[0]->Start[0] == 'X'))
690                 return (state != 0)?Token->Params[1]->lvalue:0;
691
692         if (!GetHash(Contitionals, 
693                  Token->Params[0]->Start,
694                  Token->Params[0]->len,
695                  &vConditional)) {
696                 lprintf(1, "Conditional [%s] (in '%s' line %ld); Not found![%s]\n", 
697                         Token->Params[0]->Start,
698                         ChrPtr(pTmpl->FileName),
699                         Token->Line,
700                         ChrPtr(Token->FlatToken));
701         }
702             
703         Cond = (ConditionalStruct *) vConditional;
704
705         if (Cond == NULL) {
706                 lprintf(1, "Conditional [%s] (in '%s' line %ld); Not found![%s]\n", 
707                         Token->Params[0]->Start,
708                         ChrPtr(pTmpl->FileName),
709                         Token->Line,
710                         ChrPtr(Token->FlatToken));
711                 return 0;
712         }
713         if (Token->nParameters < Cond->nParams) {
714                 lprintf(1, "Conditional [%s] (in '%s' line %ld); needs %ld Params![%s]\n", 
715                         Token->Params[0]->Start,
716                         ChrPtr(pTmpl->FileName),
717                         Token->Line,
718                         Cond->nParams,
719                         ChrPtr(Token->FlatToken));
720                 return 0;
721         }
722         if (Cond->CondF(Token, Context) == Neg)
723                 return Token->Params[1]->lvalue;
724         return 0;
725 }
726
727 int EvaluateToken(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int state)
728 {
729         void *vVar;
730 // much output, since pName is not terminated...
731 //      lprintf(1,"Doing token: %s\n",Token->pName);
732         switch (Token->Flags) {
733         case SV_GETTEXT:
734                 TmplGettext(Target, Token->nParameters, Token);
735                 break;
736         case SV_CONDITIONAL: /** Forward conditional evaluation */
737                 return EvaluateConditional(Token, pTmpl, Context, 1, state);
738                 break;
739         case SV_NEG_CONDITIONAL: /** Reverse conditional evaluation */
740                 return EvaluateConditional(Token, pTmpl, Context, 0, state);
741                 break;
742         case SV_CUST_STR_CONDITIONAL: /** Conditional put custom strings from params */
743                 if (Token->nParameters >= 6) {
744                         if (EvaluateConditional(Token, pTmpl, Context, 0, state))
745                                 StrBufAppendBufPlain(Target, 
746                                                      Token->Params[5]->Start,
747                                                      Token->Params[5]->len,
748                                                      0);
749                         else
750                                 StrBufAppendBufPlain(Target, 
751                                                      Token->Params[4]->Start,
752                                                      Token->Params[4]->len,
753                                                      0);
754                 }
755                 break;
756         case SV_SUBTEMPL:
757                 if (Token->nParameters == 1)
758                         DoTemplate(Token->Params[0]->Start, Token->Params[0]->len, NULL, NULL);
759                 break;
760         default:
761                 if (GetHash(GlobalNS, Token->pName, Token->NameEnd, &vVar)) {
762                         HashHandler *Handler;
763                         Handler = (HashHandler*) vVar;
764                         if ((Token->nParameters < Handler->nMinArgs) || 
765                             (Token->nParameters > Handler->nMaxArgs)) {
766                                 lprintf(1, "Handler [%s] doesn't work with %ld params", 
767                                         Token->pName,
768                                         Token->nParameters);
769                         }
770                         else {
771                                 Handler->HandlerFunc(Target, 
772                                                      Token->nParameters,
773                                                      Token,
774                                                      Context); /*TODO: subset of that */
775                                 
776                                 
777                         }
778                 }
779                 else {
780                         print_value_of(Target, Token->pName, Token->NameEnd);
781                 }
782         }
783         return 0;
784 }
785
786 void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context)
787 {
788         WCTemplate *pTmpl = Tmpl;
789         int done = 0;
790         int i, state;
791         const char *pData, *pS;
792         long len;
793
794         if (LoadTemplates != 0) {                       
795                 if (LoadTemplates > 1)
796                         lprintf(1, "DBG: ----- loading:  [%s] ------ \n", 
797                                 ChrPtr(Tmpl->FileName));
798                 pTmpl = load_template(Tmpl->FileName, NULL, NULL);
799         }
800
801         pS = pData = ChrPtr(pTmpl->Data);
802         len = StrLength(pTmpl->Data);
803         i = 0;
804         state = 0;
805         while (!done) {
806                 if (i >= pTmpl->nTokensUsed) {
807                         StrBufAppendBufPlain(Target, 
808                                              pData, 
809                                              len - (pData - pS), 0);
810                         done = 1;
811                 }
812                 else {
813                         StrBufAppendBufPlain(
814                                 Target, pData, 
815                                 pTmpl->Tokens[i]->pTokenStart - pData, 0);
816                         state = EvaluateToken(Target, pTmpl->Tokens[i], pTmpl, Context, state);
817                         while ((state != 0) && (i+1 < pTmpl->nTokensUsed)) {
818                         /* condition told us to skip till its end condition */
819                                 i++;
820                                 if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
821                                     (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL)) {
822                                         if (state == EvaluateConditional(pTmpl->Tokens[i], 
823                                                                          pTmpl,
824                                                                          Context, 
825                                                                          pTmpl->Tokens[i]->Flags,
826                                                                          state))
827                                                 state = 0;
828                                 }
829                         }
830                         pData = pTmpl->Tokens[i++]->pTokenEnd + 1;
831                         if (i > pTmpl->nTokensUsed)
832                                 done = 1;
833                 }
834         }
835         if (LoadTemplates != 0) {
836                 FreeWCTemplate(pTmpl);
837         }
838 }
839
840
841 /**
842  * \brief Display a variable-substituted template
843  * \param templatename template file to load
844  */
845 void *prepare_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
846 {
847         WCTemplate *NewTemplate;
848         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
849         NewTemplate->Data = NULL;
850         NewTemplate->FileName = NewStrBufDup(filename);
851         NewTemplate->nTokensUsed = 0;
852         NewTemplate->TokenSpace = 0;
853         NewTemplate->Tokens = NULL;
854
855         Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
856         return NewTemplate;
857 }
858
859 /**
860  * \brief Display a variable-substituted template
861  * \param templatename template file to load
862  */
863 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
864 {
865         int fd;
866         struct stat statbuf;
867         const char *pS, *pE, *pch, *Err;
868         long Line;
869         int pos;
870         WCTemplate *NewTemplate;
871
872         fd = open(ChrPtr(filename), O_RDONLY);
873         if (fd <= 0) {
874                 lprintf(1, "ERROR: could not open template '%s' - %s\n",
875                         ChrPtr(filename), strerror(errno));
876                 return NULL;
877         }
878
879         if (fstat(fd, &statbuf) == -1) {
880                 lprintf(1, "ERROR: could not stat template '%s' - %s\n",
881                         ChrPtr(filename), strerror(errno));
882                 return NULL;
883         }
884
885         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
886         NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size);
887         NewTemplate->FileName = NewStrBufDup(filename);
888         NewTemplate->nTokensUsed = 0;
889         NewTemplate->TokenSpace = 0;
890         NewTemplate->Tokens = NULL;
891         if (StrBufReadBLOB(NewTemplate->Data, &fd, 1, statbuf.st_size, &Err) < 0) {
892                 close(fd);
893                 FreeWCTemplate(NewTemplate);
894                 lprintf(1, "ERROR: reading template '%s' - %s<br />\n",
895                         ChrPtr(filename), strerror(errno));
896                 return NULL;
897         }
898         close(fd);
899
900         Line = 0;
901         pS = pch = ChrPtr(NewTemplate->Data);
902         pE = pS + StrLength(NewTemplate->Data);
903         while (pch < pE) {
904                 const char *pts, *pte;
905                 int InQuotes = 0;
906                 int InDoubleQuotes = 0;
907                 pos = (-1);
908                 for (; pch < pE; pch ++) {
909                         if ((*pch=='<')&&(*(pch + 1)=='?'))
910                                 break;
911                         if (*pch=='\n') Line ++;
912                 }
913                 if (pch >= pE)
914                         continue;
915                 pts = pch;
916                 for (; pch < pE - 1; pch ++) {
917                         if (*pch == '"')
918                                 InDoubleQuotes = ! InDoubleQuotes;
919                         else if (*pch == '\'')
920                                 InQuotes = ! InQuotes;
921                         else if ((!InQuotes  && !InDoubleQuotes) &&
922                                  ((*pch!='\\')&&(*(pch + 1)=='>'))) {
923                                 pch ++;
924                                 break;
925                         }
926                 }
927                 if (pch + 1 >= pE)
928                         continue;
929                 pte = pch;
930                 PutNewToken(NewTemplate, 
931                             NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate));
932                 pch ++;
933         }
934         if (LoadTemplates == 0)
935                 Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
936         return NewTemplate;
937 }
938
939
940 ///void PrintTemplate(const char *Key, void *vSubst, int odd)
941 const char* PrintTemplate(void *vSubst)
942 {
943         WCTemplate *Tmpl = vSubst;
944
945         return ChrPtr(Tmpl->FileName);
946
947 }
948
949
950 /**
951  * \brief Display a variable-substituted template
952  * \param templatename template file to load
953  */
954 void DoTemplate(const char *templatename, long len, void *Context, StrBuf *Target) 
955 {
956         HashList *Static;
957         HashList *StaticLocal;
958         void *vTmpl;
959         
960         if (Target == NULL)
961                 Target = WC->WBuf;
962         if (WC->is_mobile) {
963                 Static = WirelessTemplateCache;
964                 StaticLocal = WirelessLocalTemplateCache;
965         }
966         else {
967                 Static = TemplateCache;
968                 StaticLocal = LocalTemplateCache;
969         }
970
971         if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
972             !GetHash(Static, templatename, len, &vTmpl)) {
973                 printf ("didn't find %s %ld %ld\n", templatename, len , (long)strlen(templatename));
974 ///             dbg_PrintHash(Static, PrintTemplate, NULL);
975 //              PrintHash(Static, VarPrintTransition, PrintTemplate);
976                 return;
977         }
978         if (vTmpl == NULL) 
979                 return;
980         ProcessTemplate(vTmpl, Target, Context);        
981 }
982
983 int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
984 {
985         StrBuf *FileName;
986         StrBuf *Tag;
987         StrBuf *Dir;
988         DIR *filedir = NULL;
989         struct dirent *filedir_entry;
990         int d_namelen;
991         int d_without_ext;
992         int IsMobile;
993         
994         Dir = NewStrBuf();
995         StrBufPrintf(Dir, "%s/t", DirName);
996         filedir = opendir (ChrPtr(Dir));
997         if (filedir == NULL) {
998                 return 0;
999         }
1000
1001         FileName = NewStrBuf();
1002         Tag = NewStrBuf();
1003         while ((filedir_entry = readdir(filedir)))
1004         {
1005                 char *MinorPtr;
1006                 char *PStart;
1007 #ifdef _DIRENT_HAVE_D_NAMELEN
1008                 d_namelen = filedir_entry->d_namelen;
1009 #else
1010                 d_namelen = strlen(filedir_entry->d_name);
1011 #endif
1012                 d_without_ext = d_namelen;
1013                 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1014                         d_without_ext --;
1015                 if ((d_without_ext == 0) || (d_namelen < 3))
1016                         continue;
1017
1018                 IsMobile = (strstr(filedir_entry->d_name, ".m.html")!= NULL);
1019                 PStart = filedir_entry->d_name;
1020                 StrBufPrintf(FileName, "%s/%s", ChrPtr(Dir),  filedir_entry->d_name);
1021                 MinorPtr = strchr(filedir_entry->d_name, '.');
1022                 if (MinorPtr != NULL)
1023                         *MinorPtr = '\0';
1024                 StrBufPlain(Tag, filedir_entry->d_name, MinorPtr - filedir_entry->d_name);
1025
1026
1027                 printf("%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
1028                 if (LoadTemplates == 0)
1029                         load_template(FileName, Tag, (IsMobile)?wireless:big);
1030                 else
1031                         prepare_template(FileName, Tag, (IsMobile)?wireless:big);
1032         }
1033         closedir(filedir);
1034         FreeStrBuf(&FileName);
1035         FreeStrBuf(&Tag);
1036         FreeStrBuf(&Dir);
1037         return 1;
1038 }
1039
1040 void InitTemplateCache(void)
1041 {
1042         LoadTemplateDir(static_dirs[0],
1043                         WirelessTemplateCache,
1044                         TemplateCache);
1045         LoadTemplateDir(static_dirs[1],
1046                         WirelessLocalTemplateCache,
1047                         LocalTemplateCache);
1048 }
1049
1050 void tmplput_serv_ip(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1051 {
1052         StrBufAppendPrintf(Target, "%d", WC->ctdl_pid);
1053 }
1054
1055 void tmplput_serv_nodename(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1056 {
1057         StrEscAppend(Target, NULL, serv_info.serv_nodename, 0, 0);
1058 }
1059
1060 void tmplput_serv_humannode(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1061 {
1062         StrEscAppend(Target, NULL, serv_info.serv_humannode, 0, 0);
1063 }
1064
1065 void tmplput_serv_fqdn(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1066 {
1067         StrEscAppend(Target, NULL, serv_info.serv_fqdn, 0, 0);
1068 }
1069
1070 void tmmplput_serv_software(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1071 {
1072         StrEscAppend(Target, NULL, serv_info.serv_software, 0, 0);
1073 }
1074
1075 void tmplput_serv_rev_level(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1076 {
1077         StrBufAppendPrintf(Target, "%d.%02d",
1078                             serv_info.serv_rev_level / 100,
1079                             serv_info.serv_rev_level % 100);
1080 }
1081
1082 void tmmplput_serv_bbs_city(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1083 {
1084         StrEscAppend(Target, NULL, serv_info.serv_bbs_city, 0, 0);
1085 }
1086
1087 void tmplput_current_user(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1088 {
1089         StrEscAppend(Target, NULL, WC->wc_fullname, 0, 0);
1090 }
1091
1092 void tmplput_current_room(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1093 {
1094         StrEscAppend(Target, NULL, WC->wc_roomname, 0, 0);
1095 }
1096
1097
1098 typedef struct _HashIterator {
1099         HashList *StaticList;
1100         RetrieveHashlistFunc GetHash;
1101         HashDestructorFunc Destructor;
1102         SubTemplFunc DoSubTemplate;
1103 } HashIterator;
1104
1105 void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1106 {
1107         void *vIt;
1108         HashIterator *It;
1109         HashList *List;
1110         HashPos  *it;
1111         long len; 
1112         const char *Key;
1113         void *vContext;
1114         StrBuf *SubBuf;
1115         int oddeven = 0;
1116         
1117         if (!GetHash(Iterators, 
1118                      Tokens->Params[0]->Start,
1119                      Tokens->Params[0]->len,
1120                      &vIt))
1121                 return;
1122         It = (HashIterator*) vIt;
1123         if (It->StaticList == NULL)
1124                 List = It->GetHash();
1125         else
1126                 List = It->StaticList;
1127
1128         SubBuf = NewStrBuf();
1129         it = GetNewHashPos();
1130         while (GetNextHashPos(List, it, &len, &Key, &vContext)) {
1131                 svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", (oddeven)?"odd":"even");
1132                 It->DoSubTemplate(SubBuf, vContext);
1133                 DoTemplate(Tokens->Params[1]->Start,
1134                            Tokens->Params[1]->len,
1135                            vContext, SubBuf);
1136                         
1137                 StrBufAppendBuf(Target, SubBuf, 0);
1138                 FlushStrBuf(SubBuf);
1139                 oddeven = ~ oddeven;
1140         }
1141         FreeStrBuf(&SubBuf);
1142         DeleteHashPos(&it);
1143         It->Destructor(List);
1144 }
1145
1146 int ConditionalVar(WCTemplateToken *Tokens, void *Context)
1147 {
1148         void *vsubst;
1149         wcsubst *subst;
1150         
1151         if (!GetHash(WC->vars, 
1152                      Tokens->Params[2]->Start,
1153                      Tokens->Params[2]->len,
1154                      &vsubst))
1155                 return 0;
1156         subst = (wcsubst*) vsubst;
1157         switch(subst->wcs_type) {
1158         case WCS_FUNCTION:
1159                 return (subst->wcs_function!=NULL);
1160         case WCS_SERVCMD:
1161                 lprintf(1, "  -> Server [%s]\n", subst->wcs_value);////todo
1162                 return 1;
1163         case WCS_STRING:
1164         case WCS_STRBUF:
1165         case WCS_STRBUF_REF:
1166                 if (Tokens->nParameters < 4)
1167                         return 1;
1168                 return (strcmp(Tokens->Params[3]->Start, ChrPtr(subst->wcs_value)) == 0);
1169         case WCS_LONG:
1170                 if (Tokens->nParameters < 4)
1171                         return (subst->lvalue != 0);
1172                 return (subst->lvalue == Tokens->Params[3]->lvalue);
1173         default:
1174                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", subst->wcs_type);
1175         }
1176         return 0;
1177 }
1178
1179 void RegisterITERATOR(const char *Name, long len, 
1180                       HashList *StaticList, 
1181                       RetrieveHashlistFunc GetHash, 
1182                       SubTemplFunc DoSubTempl,
1183                       HashDestructorFunc Destructor)
1184 {
1185         HashIterator *It = (HashIterator*)malloc(sizeof(HashIterator));
1186         It->StaticList = StaticList;
1187         It->GetHash = GetHash;
1188         It->DoSubTemplate = DoSubTempl;
1189         It->Destructor = Destructor;
1190         Put(Iterators, Name, len, It, NULL);
1191 }
1192
1193 void RegisterConditional(const char *Name, long len, 
1194                          int nParams,
1195                          WCConditionalFunc CondF)
1196 {
1197         ConditionalStruct *Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
1198         Cond->nParams = nParams;
1199         Cond->CondF = CondF;
1200         Put(Contitionals, Name, len, Cond, NULL);
1201 }
1202
1203 void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1204 {
1205         if (nArgs == 2) {
1206                 StrBuf *Headline = NewStrBuf();
1207                 DoTemplate(Tokens->Params[1]->Start, 
1208                            Tokens->Params[1]->len,
1209                            Context, 
1210                            Headline);
1211                 SVPutBuf("BOXTITLE", Headline, 0);
1212         }
1213
1214         DoTemplate(HKEY("beginbox"), Context, Target);
1215         DoTemplate(Tokens->Params[0]->Start, 
1216                    Tokens->Params[0]->len,
1217                    Context, 
1218                    Target);
1219         DoTemplate(HKEY("endbox"), Context, Target);
1220 }
1221
1222 void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context)
1223 {
1224         StrBuf **TabNames;
1225         int i, ntabs, nTabs;
1226
1227         nTabs = ntabs = Tokens->nParameters / 2;
1228         TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
1229
1230         for (i = 0; i < ntabs; i++) {
1231                 TabNames[i] = NewStrBuf();
1232                 if (Tokens->Params[i * 2]->len > 0) {
1233                         DoTemplate(Tokens->Params[i * 2]->Start, 
1234                                    Tokens->Params[i * 2]->len,
1235                                    Context,
1236                                    TabNames[i]);
1237                 }
1238                 else { 
1239                         /** A Tab without subject? we can't count that, add it as silent */
1240                         nTabs --;
1241                 }
1242         }
1243
1244         StrTabbedDialog(Target, nTabs, TabNames);
1245         for (i = 0; i < ntabs; i++) {
1246                 StrBeginTab(Target, i, nTabs);
1247
1248                 DoTemplate(Tokens->Params[i * 2 + 1]->Start, 
1249                            Tokens->Params[i * 2 + 1]->len,
1250                            Context, 
1251                            Target);
1252                 StrEndTab(Target, i, nTabs);
1253         }
1254 }
1255
1256 void 
1257 InitModule_SUBST
1258 (void)
1259 {
1260         RegisterNamespace("SERV:PID", 0, 0, tmplput_serv_ip);
1261         RegisterNamespace("SERV:NODENAME", 0, 0, tmplput_serv_nodename);
1262         RegisterNamespace("SERV:HUMANNODE", 0, 0, tmplput_serv_humannode);
1263         RegisterNamespace("SERV:FQDN", 0, 0, tmplput_serv_fqdn);
1264         RegisterNamespace("SERV:SOFTWARE", 0, 0, tmmplput_serv_software);
1265         RegisterNamespace("SERV:REV_LEVEL", 0, 0, tmplput_serv_rev_level);
1266         RegisterNamespace("SERV:BBS_CITY", 0, 0, tmmplput_serv_bbs_city);
1267 ///     RegisterNamespace("SERV:LDAP_SUPP", 0, 0, tmmplput_serv_ldap_enabled);
1268         RegisterNamespace("CURRENT_USER", 0, 0, tmplput_current_user);
1269         RegisterNamespace("CURRENT_ROOM", 0, 0, tmplput_current_room);
1270         RegisterNamespace("ITERATE", 2, 4, tmpl_iterate_subtmpl);
1271         RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed);
1272         RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed);
1273         RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar);
1274 }
1275
1276 /*@}*/