4d102045bd0d9ab7a3481fed3989d3de3cc8d9bd
[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 *Conditionals;
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 #define SV_PREEVALUATED 6
42
43 typedef struct _WCTemplate {
44         StrBuf *Data;
45         StrBuf *FileName;
46         int nTokensUsed;
47         int TokenSpace;
48         WCTemplateToken **Tokens;
49 } WCTemplate;
50
51 typedef struct _HashHandler {
52         int nMinArgs;
53         int nMaxArgs;
54         int ContextRequired;
55         WCHandlerFunc HandlerFunc;
56 }HashHandler;
57
58 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere);
59
60 void RegisterNS(const char *NSName, 
61                 long len, 
62                 int nMinArgs, 
63                 int nMaxArgs, 
64                 WCHandlerFunc HandlerFunc, 
65                 int ContextRequired)
66 {
67         HashHandler *NewHandler;
68         
69         NewHandler = (HashHandler*) malloc(sizeof(HashHandler));
70         NewHandler->nMinArgs = nMinArgs;
71         NewHandler->nMaxArgs = nMaxArgs;
72         NewHandler->HandlerFunc = HandlerFunc;  
73         NewHandler->ContextRequired = ContextRequired;
74         Put(GlobalNS, NSName, len, NewHandler, NULL);
75 }
76
77 void FreeToken(WCTemplateToken **Token)
78 {
79         int i; 
80         FreeStrBuf(&(*Token)->FlatToken);
81         if ((*Token)->HaveParameters) 
82                 for (i = 0; i < (*Token)->nParameters; i++)
83                         free((*Token)->Params[i]);
84         free(*Token);
85         *Token = NULL;
86 }
87
88
89
90 void FreeWCTemplate(void *vFreeMe)
91 {
92         int i;
93         WCTemplate *FreeMe = (WCTemplate*)vFreeMe;
94
95         if (FreeMe->TokenSpace > 0) {
96                 for (i = 0; i < FreeMe->nTokensUsed; i ++) {
97                         FreeToken(&FreeMe->Tokens[i]);
98                 }
99                 free(FreeMe->Tokens);
100         }
101         FreeStrBuf(&FreeMe->FileName);
102         FreeStrBuf(&FreeMe->Data);
103         free(FreeMe);
104 }
105
106
107 /**
108  * \brief debugging function to print array to log
109  */
110 void VarPrintTransition(void *vVar1, void *vVar2, int odd){}
111 /**
112  * \brief debugging function to print array to log
113  */
114 void VarPrintEntry(const char *Key, void *vSubst, int odd)
115 {
116         wcsubst *ptr;
117         lprintf(1,"Subst[%s] : ", Key);
118         ptr = (wcsubst*) vSubst;
119
120         switch(ptr->wcs_type) {
121         case WCS_STRING:
122                 lprintf(1, "  -> %s\n", ChrPtr(ptr->wcs_value));
123                 break;
124         case WCS_SERVCMD:
125                 lprintf(1, "  -> Server [%s]\n", ChrPtr(ptr->wcs_value));
126                 break;
127         case WCS_FUNCTION:
128                 lprintf(1, "  -> function at [%0xd]\n", ptr->wcs_function);
129                 break;
130         default:
131                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", ptr->wcs_type);
132         }
133 }
134
135
136
137 /**
138  * \brief Clear out the list of substitution variables local to this session
139  */
140 void clear_substs(struct wcsession *wc) {
141
142         if (wc->vars != NULL) {
143                 DeleteHash(&wc->vars);
144         }
145 }
146
147 /**
148  * \brief Clear out the list of substitution variables local to this session
149  */
150 void clear_local_substs(void) {
151         clear_substs (WC);
152 }
153
154 int NeedNewBuf(type)
155 {
156         switch(type) {
157         case WCS_STRING:
158         case WCS_SERVCMD:
159         case WCS_STRBUF:
160                 return 1;
161         case WCS_FUNCTION:
162         case WCS_STRBUF_REF:
163         case WCS_LONG:
164         default:
165                 return 0;
166         }
167 }
168
169 void FlushPayload(wcsubst *ptr, int reusestrbuf, int type)
170 {
171         int NeedNew = NeedNewBuf(type);
172         switch(ptr->wcs_type) {
173         case WCS_STRING:
174         case WCS_SERVCMD:
175         case WCS_STRBUF:
176                 if (reusestrbuf && NeedNew) {
177                         FlushStrBuf(ptr->wcs_value);
178                 }
179                 else {
180                         
181                         FreeStrBuf(&ptr->wcs_value);
182                         ptr->wcs_value = NULL;
183                 }
184                 break;
185         case WCS_FUNCTION:
186                 ptr->wcs_function = NULL;
187                 if (reusestrbuf && NeedNew)
188                         ptr->wcs_value = NewStrBuf();
189                 break;
190         case WCS_STRBUF_REF:
191                 ptr->wcs_value = NULL;
192                 if (reusestrbuf && NeedNew)
193                         ptr->wcs_value = NewStrBuf();
194                 break;
195         case WCS_LONG:
196                 ptr->lvalue = 0;
197                 if (reusestrbuf && NeedNew)
198                         ptr->wcs_value = NewStrBuf();
199                 break;
200         default:
201                 if (reusestrbuf && NeedNew)
202                         ptr->wcs_value = NewStrBuf();
203                 break;
204         }
205 }
206
207
208 /**
209  * \brief destructor; kill one entry.
210  */
211 void deletevar(void *data)
212 {
213         wcsubst *ptr = (wcsubst*)data;
214         FlushPayload(ptr, 0, ptr->wcs_type);
215         free(ptr);      
216 }
217
218
219 wcsubst *NewSubstVar(const char *keyname, int keylen, int type)
220 {
221         wcsubst* ptr;
222         struct wcsession *WCC = WC;
223
224         ptr = (wcsubst *) malloc(sizeof(wcsubst));
225         memset(ptr, 0, sizeof(wcsubst));
226
227         ptr->wcs_type = type;
228         safestrncpy(ptr->wcs_key, keyname, sizeof ptr->wcs_key);
229         Put(WCC->vars, keyname, keylen, ptr,  deletevar);
230
231         switch(ptr->wcs_type) {
232         case WCS_STRING:
233         case WCS_SERVCMD:
234                 ptr->wcs_value = NewStrBuf();
235                 break;
236         case WCS_STRBUF:
237         case WCS_FUNCTION:
238         case WCS_STRBUF_REF:
239         case WCS_LONG:
240         default:
241                 break;
242         }
243         return ptr;
244 }
245
246
247 /**
248  * \brief Add a substitution variable (local to this session) (strlen version...)
249  * \param keyname the replacementstring to substitute
250  * \param keytype the kind of the key
251  * \param format the format string ala printf
252  * \param ... the arguments to substitute in the formatstring
253  */
254 void SVPRINTF(char *keyname, int keytype, const char *format,...)
255 {
256         va_list arg_ptr;
257         void *vPtr;
258         wcsubst *ptr = NULL;
259         size_t keylen;
260         struct wcsession *WCC = WC;
261         
262         keylen = strlen(keyname);
263         /**
264          * First look if we're doing a replacement of
265          * an existing key
266          */
267         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
268         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
269                 ptr = (wcsubst*)vPtr;
270                 FlushPayload(ptr, keytype, keytype);
271                 ptr->wcs_type = keytype;
272         }
273         else    /** Otherwise allocate a new one */
274         {
275                 ptr = NewSubstVar(keyname, keylen, keytype);
276         }
277
278         /** Format the string */
279         va_start(arg_ptr, format);
280         StrBufVAppendPrintf(ptr->wcs_value, format, arg_ptr);
281         va_end(arg_ptr);
282 }
283
284 /**
285  * \brief Add a substitution variable (local to this session)
286  * \param keyname the replacementstring to substitute
287  * \param keytype the kind of the key
288  * \param format the format string ala printf
289  * \param ... the arguments to substitute in the formatstring
290  */
291 void svprintf(char *keyname, size_t keylen, int keytype, const char *format,...)
292 {
293         va_list arg_ptr;
294         void *vPtr;
295         wcsubst *ptr = NULL;
296         struct wcsession *WCC = WC;
297                 
298         /**
299          * First look if we're doing a replacement of
300          * an existing key
301          */
302         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
303         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
304                 ptr = (wcsubst*)vPtr;
305                 FlushPayload(ptr, 1, keytype);
306                 ptr->wcs_type = keytype;
307         }
308         else    /** Otherwise allocate a new one */
309         {
310                 ptr = NewSubstVar(keyname, keylen, keytype);
311         }
312
313         /** Format the string and save it */
314         va_start(arg_ptr, format);
315         StrBufVAppendPrintf(ptr->wcs_value, format, arg_ptr);
316         va_end(arg_ptr);
317 }
318
319 /**
320  * \brief Add a substitution variable (local to this session)
321  * \param keyname the replacementstring to substitute
322  * \param keytype the kind of the key
323  * \param format the format string ala printf
324  * \param ... the arguments to substitute in the formatstring
325  */
326 void SVPut(char *keyname, size_t keylen, int keytype, char *Data)
327 {
328         void *vPtr;
329         wcsubst *ptr = NULL;
330         struct wcsession *WCC = WC;
331
332         
333         /**
334          * First look if we're doing a replacement of
335          * an existing key
336          */
337         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
338         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
339                 ptr = (wcsubst*)vPtr;
340                 FlushPayload(ptr, 1, keytype);
341                 ptr->wcs_type = keytype;
342         }
343         else    /** Otherwise allocate a new one */
344         {
345                 ptr = NewSubstVar(keyname, keylen, keytype);
346         }
347         StrBufAppendBufPlain(ptr->wcs_value, Data, -1, 0);
348 }
349
350 /**
351  * \brief Add a substitution variable (local to this session)
352  * \param keyname the replacementstring to substitute
353  * \param keytype the kind of the key
354  * \param format the format string ala printf
355  * \param ... the arguments to substitute in the formatstring
356  */
357 void SVPutLong(char *keyname, size_t keylen, long Data)
358 {
359         void *vPtr;
360         wcsubst *ptr = NULL;
361         struct wcsession *WCC = WC;
362
363         
364         /**
365          * First look if we're doing a replacement of
366          * an existing key
367          */
368         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
369         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
370                 ptr = (wcsubst*)vPtr;
371                 FlushPayload(ptr, 1, WCS_LONG);
372                 ptr->wcs_type = WCS_LONG;
373         }
374         else    /** Otherwise allocate a new one */
375         {
376                 ptr = NewSubstVar(keyname, keylen, WCS_LONG);
377         }
378         ptr->lvalue = Data;
379 }
380
381 /**
382  * \brief Add a substitution variable (local to this session) that does a callback
383  * \param keyname the keystring to substitute
384  * \param fcn_ptr the function callback to give the substitution string
385  */
386 void SVCallback(char *keyname, size_t keylen, WCHandlerFunc fcn_ptr)
387 {
388         wcsubst *ptr;
389         void *vPtr;
390         struct wcsession *WCC = WC;
391
392         /**
393          * First look if we're doing a replacement of
394          * an existing key
395          */
396         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
397         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
398                 ptr = (wcsubst*)vPtr;
399                 FlushPayload(ptr, 1, WCS_FUNCTION);
400                 ptr->wcs_type = WCS_FUNCTION;
401         }
402         else    /** Otherwise allocate a new one */
403         {
404                 ptr = NewSubstVar(keyname, keylen, WCS_FUNCTION);
405         }
406
407         ptr->wcs_function = fcn_ptr;
408 }
409 inline void SVCALLBACK(char *keyname, WCHandlerFunc fcn_ptr)
410 {
411         SVCallback(keyname, strlen(keyname), fcn_ptr);
412 }
413
414
415
416 void SVPUTBuf(const char *keyname, int keylen, const StrBuf *Buf, int ref)
417 {
418         wcsubst *ptr;
419         void *vPtr;
420         struct wcsession *WCC = WC;
421
422         /**
423          * First look if we're doing a replacement of
424          * an existing key
425          */
426         /*PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
427         if (GetHash(WCC->vars, keyname, keylen, &vPtr)) {
428                 ptr = (wcsubst*)vPtr;
429                 FlushPayload(ptr, 0, (ref)?WCS_STRBUF_REF:WCS_STRBUF);
430                 ptr->wcs_type = (ref)?WCS_STRBUF_REF:WCS_STRBUF;
431         }
432         else    /** Otherwise allocate a new one */
433         {
434                 ptr = NewSubstVar(keyname, keylen, (ref)?WCS_STRBUF_REF:WCS_STRBUF);
435         }
436         ptr->wcs_value = (StrBuf*)Buf;
437 }
438
439 /**
440  * \brief back end for print_value_of() ... does a server command
441  * \param servcmd server command to execute on the citadel server
442  */
443 void pvo_do_cmd(StrBuf *Target, StrBuf *servcmd) {
444         char buf[SIZ];
445         int len;
446
447         serv_puts(ChrPtr(servcmd));
448         len = serv_getln(buf, sizeof buf);
449
450         switch(buf[0]) {
451                 case '2':
452                 case '3':
453                 case '5':
454                         StrBufAppendPrintf(Target, "%s\n", &buf[4]);
455                         break;
456                 case '1':
457                         _fmout(Target, "CENTER");
458                         break;
459                 case '4':
460                         StrBufAppendPrintf(Target, "%s\n", &buf[4]);
461                         serv_puts("000");
462                         break;
463         }
464 }
465
466
467 /**
468  * \brief puts string into the template and computes which escape methon we should use
469  * \param Source the string we should put into the template
470  * \param FormatTypeIndex where should we look for escape types if?
471  */
472 void StrBufAppendTemplate(StrBuf *Target, 
473                           int nArgs, 
474                           WCTemplateToken *Tokens,
475                           void *Context, int ContextType,
476                           const StrBuf *Source, int FormatTypeIndex)
477 {
478         struct wcsession *WCC;
479         StrBuf *Buf;
480         char EscapeAs = ' ';
481
482         if ((FormatTypeIndex < Tokens->nParameters) &&
483             (Tokens->Params[FormatTypeIndex]->Type == TYPE_STR) &&
484             (Tokens->Params[FormatTypeIndex]->len == 1)) {
485                 EscapeAs = *Tokens->Params[FormatTypeIndex]->Start;
486         }
487
488         switch(EscapeAs)
489         {
490         case 'H':
491                 WCC = WC;
492                 Buf = NewStrBufPlain(NULL, StrLength(Buf));
493                 StrBuf_RFC822_to_Utf8(Buf, 
494                                       Source, 
495                                       (WCC!=NULL)? WCC->DefaultCharset : NULL, 
496                                       NULL);
497                 StrEscAppend(Target, Buf, NULL, 0, 0);
498                 FreeStrBuf(&Buf);
499                 break;
500         case 'X':
501                 StrEscAppend(Target, Source, NULL, 0, 0);
502                 break;
503         default:
504                 StrBufAppendBuf(Target, Source, 0);
505         }
506 }
507
508
509 void GetTemplateTokenString(WCTemplateToken *Tokens,
510                             int N, 
511                             const char **Value, 
512                             long *len)
513 {
514         StrBuf *Buf;
515
516         if (Tokens->HaveParameters < N) {
517                 *Value = "";
518                 *len = 0;
519                 return;
520         }
521
522         switch (Tokens->Params[N]->Type) {
523
524         case TYPE_STR:
525                 *Value = Tokens->Params[N]->Start;
526                 *len = Tokens->Params[N]->len;
527                 break;
528         case TYPE_BSTR:
529                 Buf = (StrBuf*) SBstr(Tokens->Params[N]->Start, 
530                                       Tokens->Params[N]->len);
531                 *Value = ChrPtr(Buf);
532                 *len = StrLength(Buf);
533                 break;
534         case TYPE_PREFSTR:
535                 get_PREFERENCE(
536                         Tokens->Params[N]->Start, 
537                         Tokens->Params[N]->len, 
538                         &Buf);
539                 *Value = ChrPtr(Buf);
540                 *len = StrLength(Buf);
541                 break;
542         case TYPE_LONG:
543         case TYPE_PREFINT:
544                 break; ///todo: string to text?
545         case TYPE_GETTEXT:
546                 *Value = _(Tokens->Params[N]->Start);
547                 *len = strlen(*Value);
548                 break;
549         default:
550                 break;
551 //todo log error
552         }
553 }
554
555
556
557 /**
558  * \brief Print the value of a variable
559  * \param keyname get a key to print
560  */
561 void print_value_of(StrBuf *Target, WCTemplateToken *Token, void *Context, int ContextType) {
562         struct wcsession *WCC = WC;
563         wcsubst *ptr;
564         void *vVar;
565
566         /*if (WCC->vars != NULL) PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
567         /// TODO: debricated!
568         if (Token->pName[0] == '=') {
569                 DoTemplate(Token->pName+1, Token->NameEnd - 1, NULL, NULL, 0);
570         }
571
572 //////TODO: if param[1] == "U" -> urlescape
573 /// X -> escputs
574         /** Page-local variables */
575         if ((WCC->vars!= NULL) && GetHash(WCC->vars, Token->pName, Token->NameEnd, &vVar)) {
576                 ptr = (wcsubst*) vVar;
577                 switch(ptr->wcs_type) {
578                 case WCS_STRING:
579                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
580                         break;
581                 case WCS_SERVCMD:
582                         pvo_do_cmd(Target, ptr->wcs_value);
583                         break;
584                 case WCS_FUNCTION:
585                         (*ptr->wcs_function) (Target, Token->nParameters, Token, Context, ContextType);
586                         break;
587                 case WCS_STRBUF:
588                 case WCS_STRBUF_REF:
589                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
590                         break;
591                 case WCS_LONG:
592                         StrBufAppendPrintf(Target, "%ld", ptr->lvalue);
593                         break;
594                 default:
595                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", Token->pName);
596                         StrBufAppendPrintf(Target, "<pre>WARNING: \ninvalid value in SV-Hash at %s!\n</pre>", Token->pName);
597                 }
598         }
599         else {
600                 lprintf(1, "didn't find Handler [%s] (in '%s' line %ld); "
601                         " [%s]\n", 
602                         Token->pName,
603                         ChrPtr(Token->FileName),
604                         Token->Line,
605                         ChrPtr(Token->FlatToken));
606                 wc_backtrace();
607         }
608 }
609
610 int CompareSubstToToken(TemplateParam *ParamToCompare, TemplateParam *ParamToLookup)
611 {
612         struct wcsession *WCC = WC;
613         wcsubst *ptr;
614         void *vVar;
615
616         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
617                                           ParamToLookup->len, &vVar)) {
618                 ptr = (wcsubst*) vVar;
619                 switch(ptr->wcs_type) {
620                 case WCS_STRING:
621                 case WCS_STRBUF:
622                 case WCS_STRBUF_REF:
623                         if (ParamToCompare->Type == TYPE_STR)
624                                 return ((ParamToCompare->len == StrLength(ptr->wcs_value)) &&
625                                         (strcmp(ParamToCompare->Start, ChrPtr(ptr->wcs_value)) == 0));
626                         else
627                                 return ParamToCompare->lvalue == StrTol(ptr->wcs_value);
628                         break;
629                 case WCS_SERVCMD:
630                         return 1; 
631                         break;
632                 case WCS_FUNCTION:
633                         return 1;
634                 case WCS_LONG:
635                         if (ParamToCompare->Type == TYPE_STR)
636                                 return 0;
637                         else 
638                                 return ParamToCompare->lvalue == ptr->lvalue;
639                         break;
640                 default:
641                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
642                                 ParamToLookup->Start);
643                 }
644         }
645         return 0;
646 }
647
648 int CompareSubstToStrBuf(StrBuf *Compare, TemplateParam *ParamToLookup)
649 {
650         struct wcsession *WCC = WC;
651         wcsubst *ptr;
652         void *vVar;
653
654         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
655                                           ParamToLookup->len, &vVar)) {
656                 ptr = (wcsubst*) vVar;
657                 switch(ptr->wcs_type) {
658                 case WCS_STRING:
659                 case WCS_STRBUF:
660                 case WCS_STRBUF_REF:
661                         return ((StrLength(Compare) == StrLength(ptr->wcs_value)) &&
662                                 (strcmp(ChrPtr(Compare), ChrPtr(ptr->wcs_value)) == 0));
663                 case WCS_SERVCMD:
664                         return 1; 
665                         break;
666                 case WCS_FUNCTION:
667                         return 1;
668                 case WCS_LONG:
669                         return StrTol(Compare) == ptr->lvalue;
670                 default:
671                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
672                                 ParamToLookup->Start);
673                 }
674         }
675         return 0;
676 }
677
678
679 void PutNewToken(WCTemplate *Template, WCTemplateToken *NewToken)
680 {
681         if (Template->nTokensUsed + 1 >= Template->TokenSpace) {
682                 if (Template->TokenSpace <= 0) {
683                         Template->Tokens = (WCTemplateToken**)malloc(
684                                 sizeof(WCTemplateToken*) * 10);
685                         Template->TokenSpace = 10;
686                 }
687                 else {
688                         WCTemplateToken **NewTokens;
689                         NewTokens= (WCTemplateToken**)malloc(
690                                 sizeof(WCTemplateToken*) * 
691                                 Template->TokenSpace * 2);
692                         memcpy(NewTokens, Template->Tokens, 
693                                sizeof(WCTemplateToken*) * Template->nTokensUsed);
694                         free(Template->Tokens);
695                         Template->TokenSpace *= 2;
696                         Template->Tokens = NewTokens;
697                 }
698         }
699         Template->Tokens[(Template->nTokensUsed)++] = NewToken;
700 }
701
702 TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe, WCTemplateToken *Token, WCTemplate *pTmpl)
703 {
704         const char *pch = *pCh;
705         const char *pchs, *pche;
706         TemplateParam *Parm = (TemplateParam *) malloc(sizeof(TemplateParam));
707         char quote = '\0';
708         
709
710         Parm->Type = TYPE_STR;
711
712         /* Skip leading whitespaces */
713         while ((*pch == ' ' )||
714                (*pch == '\t')||
715                (*pch == '\r')||
716                (*pch == '\n')) pch ++;
717
718         if (*pch == ':') {
719                 Parm->Type = TYPE_PREFSTR;
720                 pch ++;
721         }
722         else if (*pch == ';') {
723                 Parm->Type = TYPE_PREFINT;
724                 pch ++;
725         }
726         else if (*pch == '_') {
727                 Parm->Type = TYPE_GETTEXT;
728                 pch ++;
729         }
730         else if (*pch == 'B') {
731                 Parm->Type = TYPE_BSTR;
732                 pch ++;
733         }
734
735
736         if (*pch == '"')
737                 quote = '"';
738         else if (*pch == '\'')
739                 quote = '\'';
740         if (quote != '\0') {
741                 pch ++;
742                 pchs = pch;
743                 while (pch <= pe &&
744                        ((*pch != quote) ||
745                         ( (pch > pchs) && (*(pch - 1) == '\\'))
746                                )) {
747                         pch ++;
748                 }
749                 pche = pch;
750                 if (*pch != quote) {
751                         lprintf(1, "Error (in '%s' line %ld); "
752                                 "evaluating template param [%s] in Token [%s]\n",
753                                 ChrPtr(pTmpl->FileName),
754                                 Token->Line,
755                                 ChrPtr(Token->FlatToken),
756                                 *pCh);
757                         pch ++;
758                         free(Parm);
759                         return NULL;
760                 }
761                 else {
762                         StrBufPeek(Buf, pch, -1, '\0');         
763                         if (LoadTemplates > 1) {                        
764                                 lprintf(1, "DBG: got param [%s] %ld %ld\n", 
765                                         pchs, pche - pchs, strlen(pchs));
766                         }
767                         Parm->Start = pchs;
768                         Parm->len = pche - pchs;
769                         pch ++; /* move after trailing quote */
770                 }
771         }
772         else {
773                 Parm->Type = TYPE_LONG;
774                 pchs = pch;
775                 while ((pch <= pe) &&
776                        (isdigit(*pch) ||
777                         (*pch == '+') ||
778                         (*pch == '-')))
779                         pch ++;
780                 pch ++;
781                 if (pch - pchs > 1){
782                         StrBufPeek(Buf, pch, -1, '\0');
783                         Parm->lvalue = atol(pchs);
784                         Parm->Start = pchs;
785                         pch++;
786                 }
787                 else {
788                         Parm->lvalue = 0;
789                         lprintf(1, "Error (in '%s' line %ld); "
790                                 "evaluating long template param [%s] in Token [%s]\n",
791                                 ChrPtr(pTmpl->FileName),
792                                 Token->Line,
793                                 ChrPtr(Token->FlatToken),
794                                 *pCh);
795                         free(Parm);
796                         return NULL;
797                 }
798         }
799         while ((*pch == ' ' )||
800                (*pch == '\t')||
801                (*pch == '\r')||
802                (*pch == ',' )||
803                (*pch == '\n')) pch ++;
804
805         *pCh = pch;
806         return Parm;
807 }
808
809 WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf, 
810                                        const char *pStart, 
811                                        const char *pTmplStart, 
812                                        const char *pTmplEnd, 
813                                        long Line,
814                                        WCTemplate *pTmpl)
815 {
816         void *vVar;
817         const char *pch;
818         TemplateParam *Param;
819         WCTemplateToken *NewToken = (WCTemplateToken*)malloc(sizeof(WCTemplateToken));
820
821         NewToken->FileName = pTmpl->FileName; /* to print meaningfull log messages... */
822         NewToken->Flags = 0;
823         NewToken->Line = Line + 1;
824         NewToken->pTokenStart = pTmplStart;
825         NewToken->TokenStart = pTmplStart - pStart;
826         NewToken->TokenEnd =  (pTmplEnd - pStart) - NewToken->TokenStart;
827         NewToken->pTokenEnd = pTmplEnd;
828         NewToken->NameEnd = NewToken->TokenEnd - 2;
829         NewToken->PreEval = NULL;
830         NewToken->FlatToken = NewStrBufPlain(pTmplStart + 2, pTmplEnd - pTmplStart - 2);
831         
832         StrBufPeek(Buf, pTmplStart, + 1, '\0');
833         StrBufPeek(Buf, pTmplEnd, -1, '\0');
834         pch = NewToken->pName = pTmplStart + 2;
835
836         NewToken->HaveParameters = 0;;
837         NewToken->nParameters = 0;
838
839         while (pch < pTmplEnd - 1) {
840                 if (*pch == '(') {
841                         StrBufPeek(Buf, pch, -1, '\0');
842                         NewToken->NameEnd = pch - NewToken->pName;
843                         pch ++;
844                         if (*(pTmplEnd - 1) != ')') {
845                                 lprintf(1, "Warning, Non welformed Token; missing right parenthesis (in '%s' line %ld); "
846                                         "[%s]\n", 
847                                         ChrPtr(pTmpl->FileName),
848                                         NewToken->Line,
849                                         ChrPtr(NewToken->FlatToken));
850                         }
851                         while (pch < pTmplEnd - 1) {
852                                 Param = GetNextParameter(Buf, &pch, pTmplEnd - 1, NewToken, pTmpl);
853                                 if (Param != NULL) {
854                                         NewToken->HaveParameters = 1;
855                                         if (NewToken->nParameters > MAXPARAM) {
856                                                 lprintf(1, "Error (in '%s' line %ld); "
857                                                         "only [%ld] Params allowed in Tokens [%s]\n",
858                                                         ChrPtr(pTmpl->FileName),
859                                                         NewToken->Line,
860                                                         MAXPARAM,
861                                                         ChrPtr(NewToken->FlatToken));
862                                                 free(Param);
863                                                 FreeToken(&NewToken);
864                                                 return NULL;
865                                         }
866                                         NewToken->Params[NewToken->nParameters++] = Param;
867                                 }
868                                 else break;
869                         }
870                         if((NewToken->NameEnd == 1) &&
871                            (NewToken->HaveParameters == 1))
872                            
873                         {
874                                 if (*(NewToken->pName) == '_')
875                                         NewToken->Flags = SV_GETTEXT;
876                                 else if (*(NewToken->pName) == '=')
877                                         NewToken->Flags = SV_SUBTEMPL;
878                                 else if (*(NewToken->pName) == '%')
879                                         NewToken->Flags = SV_CUST_STR_CONDITIONAL;
880                                 else if (*(NewToken->pName) == '?')
881                                         NewToken->Flags = SV_CONDITIONAL;
882                                 else if (*(NewToken->pName) == '!')
883                                         NewToken->Flags = SV_NEG_CONDITIONAL;
884                         }
885                 }
886                 else pch ++;            
887         }
888         
889         switch (NewToken->Flags) {
890         case 0:
891                 /* If we're able to find out more about the token, do it now while its fresh. */
892                 if (GetHash(GlobalNS, NewToken->pName, NewToken->NameEnd, &vVar)) {
893                         HashHandler *Handler;
894                         Handler = (HashHandler*) vVar;
895                         if ((NewToken->nParameters < Handler->nMinArgs) || 
896                             (NewToken->nParameters > Handler->nMaxArgs)) {
897                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
898                                         "doesn't work with %ld params [%s]\n", 
899                                         NewToken->pName,
900                                         ChrPtr(pTmpl->FileName),
901                                         NewToken->Line,
902                                         NewToken->nParameters, 
903                                         ChrPtr(NewToken->FlatToken));
904                         }
905                         else {
906                                 NewToken->PreEval = Handler;
907                                 NewToken->Flags = SV_PREEVALUATED;              
908                         }
909                 }
910                 break;
911         case SV_GETTEXT:
912                 if (NewToken->nParameters !=1) {
913                         lprintf(1, "Gettext (in '%s' line %ld); "
914                                 "requires exactly 1 parameter, you gave %ld params [%s]\n", 
915                                 ChrPtr(pTmpl->FileName),
916                                 NewToken->Line,
917                                 NewToken->nParameters, 
918                                 ChrPtr(NewToken->FlatToken));
919                         NewToken->Flags = 0;
920                         break;
921                 }
922                 break;
923         case SV_SUBTEMPL:
924                 if (NewToken->nParameters != 1) {
925                         lprintf(1, "Subtemplates (in '%s' line %ld); "
926                                 "require exactly 1 parameter, you gave %ld params [%s]\n", 
927                                 ChrPtr(pTmpl->FileName),
928                                 NewToken->Line,
929                                 NewToken->nParameters, 
930                                 ChrPtr(NewToken->FlatToken));
931                         break;
932                 }
933                 break;
934         case SV_CUST_STR_CONDITIONAL:
935         case SV_CONDITIONAL:
936         case SV_NEG_CONDITIONAL:
937                 if (NewToken->nParameters <2) {
938                         lprintf(1, "Conditional (in '%s' line %ld); "
939                                 "require at least 2 parameters, you gave %ld params [%s]\n", 
940                                 ChrPtr(pTmpl->FileName),
941                                 NewToken->Line,
942                                 NewToken->nParameters, 
943                                 ChrPtr(NewToken->FlatToken));
944                         NewToken->Flags = 0;
945                         break;
946                 }
947                 if (!GetHash(Conditionals, 
948                              NewToken->Params[0]->Start,
949                              NewToken->Params[0]->len,
950                              &vVar) || 
951                     (vVar == NULL)) {
952                         if ((NewToken->Params[0]->len == 1) &&
953                             (NewToken->Params[0]->Start[0] == 'X'))
954                                 break;
955                         lprintf(1, "Conditional [%s] (in '%s' line %ld); Not found![%s]\n", 
956                                 NewToken->Params[0]->Start,
957                                 ChrPtr(pTmpl->FileName),
958                                 NewToken->Line,
959                                 ChrPtr(NewToken->FlatToken));
960 /*
961                         NewToken->Error = NewStrBuf();
962                         StrBufAppendPrintf(
963                                 NewToken->Error, 
964                                 "<pre>\nConditional [%s] (in '%s' line %ld); Not found!\n[%s]\n</pre>\n", 
965                                 NewToken->Params[0]->Start,
966                                 ChrPtr(pTmpl->FileName),
967                                 NewToken->Line,
968                                 ChrPtr(NewToken->FlatToken));
969 */
970                 }
971                 else {
972                         NewToken->PreEval = vVar;
973                 }
974                 break;
975         }
976         return NewToken;
977 }
978
979
980
981 int EvaluateConditional(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int Neg, int state, int ContextType)
982 {
983         ConditionalStruct *Cond;
984
985         if ((Token->Params[0]->len == 1) &&
986             (Token->Params[0]->Start[0] == 'X'))
987                 return (state != 0)?Token->Params[1]->lvalue:0;
988             
989         Cond = (ConditionalStruct *) Token->PreEval;
990         if (Cond == NULL) {
991                 lprintf(1, "Conditional [%s] (in '%s' line %ld); unknown![%s]\n", 
992                         Token->Params[0]->Start,
993                         ChrPtr(pTmpl->FileName),
994                         Token->Line,
995                         ChrPtr(Token->FlatToken));
996                 return 1;
997         }
998
999         if (Token->nParameters < Cond->nParams) {
1000                 lprintf(1, "Conditional [%s] (in '%s' line %ld); needs %ld Params![%s]\n", 
1001                         Token->Params[0]->Start,
1002                         ChrPtr(pTmpl->FileName),
1003                         Token->Line,
1004                         Cond->nParams,
1005                         ChrPtr(Token->FlatToken));
1006                 StrBufAppendPrintf(
1007                         Target, 
1008                         "<pre>\nConditional [%s] (in '%s' line %ld); needs %ld Params!\n[%s]\n</pre>\n", 
1009                         Token->Params[0]->Start,
1010                         ChrPtr(pTmpl->FileName),
1011                         Token->Line,
1012                         Cond->nParams,
1013                         ChrPtr(Token->FlatToken));
1014                 return 0;
1015         }
1016         if (Cond->CondF(Token, Context, ContextType) == Neg)
1017                 return Token->Params[1]->lvalue;
1018         return 0;
1019 }
1020
1021 /**
1022  * \brief executes one token
1023  * \param Target buffer to append to
1024  * \param Token da to  process.
1025  * \param Template we're iterating
1026  * \param Context Contextpoointer to pass in
1027  * \param state are we in conditional state?
1028  * \param ContextType what type of information does context giv us?
1029  */
1030 int EvaluateToken(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int state, int ContextType)
1031 {
1032         HashHandler *Handler;
1033         void *vVar;
1034 // much output, since pName is not terminated...
1035 //      lprintf(1,"Doing token: %s\n",Token->pName);
1036
1037         switch (Token->Flags) {
1038         case SV_GETTEXT:
1039                 TmplGettext(Target, Token->nParameters, Token);
1040                 break;
1041         case SV_CONDITIONAL: /** Forward conditional evaluation */
1042                 return EvaluateConditional(Target, Token, pTmpl, Context, 1, state, ContextType);
1043                 break;
1044         case SV_NEG_CONDITIONAL: /** Reverse conditional evaluation */
1045                 return EvaluateConditional(Target, Token, pTmpl, Context, 0, state, ContextType);
1046                 break;
1047         case SV_CUST_STR_CONDITIONAL: /** Conditional put custom strings from params */
1048                 if (Token->nParameters >= 6) {
1049                         if (EvaluateConditional(Target, Token, pTmpl, Context, 0, state, ContextType))
1050                                 StrBufAppendBufPlain(Target, 
1051                                                      Token->Params[5]->Start,
1052                                                      Token->Params[5]->len,
1053                                                      0);
1054                         else
1055                                 StrBufAppendBufPlain(Target, 
1056                                                      Token->Params[4]->Start,
1057                                                      Token->Params[4]->len,
1058                                                      0);
1059                 }
1060                 break;
1061         case SV_SUBTEMPL:
1062                 if (Token->nParameters == 1)
1063                         DoTemplate(Token->Params[0]->Start, Token->Params[0]->len, NULL, NULL, ContextType);
1064                 break;
1065         case SV_PREEVALUATED:
1066                 Handler = (HashHandler*) Token->PreEval;
1067                 if ((Handler->ContextRequired != CTX_NONE) &&
1068                     (Handler->ContextRequired != ContextType)) {
1069                         lprintf(1, "Handler [%s] (in '%s' line %ld); "
1070                                 "requires context of type %ld, have %ld [%s]\n", 
1071                                 Token->pName,
1072                                 ChrPtr(pTmpl->FileName),
1073                                 Token->Line,
1074                                 Handler->ContextRequired, 
1075                                 ContextType,
1076                                 ChrPtr(Token->FlatToken));
1077                         StrBufAppendPrintf(
1078                                 Target, 
1079                                 "<pre>\nHandler [%s] (in '%s' line %ld);"
1080                                 " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1081                                 Token->pName,
1082                                 ChrPtr(pTmpl->FileName),
1083                                 Token->Line,
1084                                 Handler->ContextRequired, 
1085                                 ContextType,
1086                                 ChrPtr(Token->FlatToken));
1087                         return -1;
1088
1089                 }
1090                 Handler->HandlerFunc(Target, 
1091                                      Token->nParameters,
1092                                      Token,
1093                                      Context, 
1094                                      ContextType); 
1095                 break;          
1096         default:
1097                 if (GetHash(GlobalNS, Token->pName, Token->NameEnd, &vVar)) {
1098                         Handler = (HashHandler*) vVar;
1099                         if ((Handler->ContextRequired != CTX_NONE) &&
1100                             (Handler->ContextRequired != ContextType)) {
1101                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
1102                                         "requires context of type %ld, have %ld [%s]\n", 
1103                                         Token->pName,
1104                                         ChrPtr(pTmpl->FileName),
1105                                         Token->Line,
1106                                         Handler->ContextRequired, 
1107                                         ContextType,
1108                                         ChrPtr(Token->FlatToken));
1109                                 StrBufAppendPrintf(
1110                                         Target, 
1111                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
1112                                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1113                                         Token->pName,
1114                                         ChrPtr(pTmpl->FileName),
1115                                         Token->Line,
1116                                         Handler->ContextRequired, 
1117                                         ContextType,
1118                                         ChrPtr(Token->FlatToken));
1119                                 return -1;
1120                         }
1121                         else if ((Token->nParameters < Handler->nMinArgs) || 
1122                                  (Token->nParameters > Handler->nMaxArgs)) {
1123                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
1124                                         "doesn't work with %ld params [%s]\n", 
1125                                         Token->pName,
1126                                         ChrPtr(pTmpl->FileName),
1127                                         Token->Line,
1128                                         Token->nParameters, 
1129                                         ChrPtr(Token->FlatToken));
1130                                 StrBufAppendPrintf(
1131                                         Target, 
1132                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
1133                                         " doesn't work with %ld params!\n[%s]\n</pre>\n", 
1134                                         Token->pName,
1135                                         ChrPtr(pTmpl->FileName),
1136                                         Token->Line,
1137                                         Token->nParameters,
1138                                         ChrPtr(Token->FlatToken));
1139                         }
1140                         else {
1141                                 Handler->HandlerFunc(Target, 
1142                                                      Token->nParameters,
1143                                                      Token,
1144                                                      Context, 
1145                                                      ContextType); /*TODO: subset of that */
1146                                 
1147                         }
1148                 }
1149                 else {
1150                         print_value_of(Target, Token, Context, ContextType);
1151                 }
1152         }
1153         return 0;
1154 }
1155
1156 void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context, int ContextType)
1157 {
1158         WCTemplate *pTmpl = Tmpl;
1159         int done = 0;
1160         int i, state;
1161         const char *pData, *pS;
1162         long len;
1163
1164         if (LoadTemplates != 0) {                       
1165                 if (LoadTemplates > 1)
1166                         lprintf(1, "DBG: ----- loading:  [%s] ------ \n", 
1167                                 ChrPtr(Tmpl->FileName));
1168
1169                 pTmpl = load_template(Tmpl->FileName, NULL, NULL);
1170                 if(pTmpl == NULL) {
1171                         StrBufAppendPrintf(
1172                                 Target, 
1173                                 "<pre>\nError loading Template [%s]\n See Logfile for details\n</pre>\n", 
1174                                 ChrPtr(Tmpl->FileName));
1175                         return;
1176                 }
1177
1178         }
1179
1180         pS = pData = ChrPtr(pTmpl->Data);
1181         len = StrLength(pTmpl->Data);
1182         i = 0;
1183         state = 0;
1184         while (!done) {
1185                 if (i >= pTmpl->nTokensUsed) {
1186                         StrBufAppendBufPlain(Target, 
1187                                              pData, 
1188                                              len - (pData - pS), 0);
1189                         done = 1;
1190                 }
1191                 else {
1192                         StrBufAppendBufPlain(
1193                                 Target, pData, 
1194                                 pTmpl->Tokens[i]->pTokenStart - pData, 0);
1195                         state = EvaluateToken(Target, pTmpl->Tokens[i], pTmpl, Context, state, ContextType);
1196                         while ((state != 0) && (i+1 < pTmpl->nTokensUsed)) {
1197                         /* condition told us to skip till its end condition */
1198                                 i++;
1199                                 if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
1200                                     (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL)) {
1201                                         if (state == EvaluateConditional(
1202                                                     Target,
1203                                                     pTmpl->Tokens[i], 
1204                                                     pTmpl,
1205                                                     Context, 
1206                                                     pTmpl->Tokens[i]->Flags,
1207                                                     state, 
1208                                                     ContextType))
1209                                                 state = 0;
1210                                 }
1211                         }
1212                         pData = pTmpl->Tokens[i++]->pTokenEnd + 1;
1213                         if (i > pTmpl->nTokensUsed)
1214                                 done = 1;
1215                 }
1216         }
1217         if (LoadTemplates != 0) {
1218                 FreeWCTemplate(pTmpl);
1219         }
1220 }
1221
1222
1223 /**
1224  * \brief Display a variable-substituted template
1225  * \param templatename template file to load
1226  */
1227 void *prepare_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1228 {
1229         WCTemplate *NewTemplate;
1230         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1231         NewTemplate->Data = NULL;
1232         NewTemplate->FileName = NewStrBufDup(filename);
1233         NewTemplate->nTokensUsed = 0;
1234         NewTemplate->TokenSpace = 0;
1235         NewTemplate->Tokens = NULL;
1236
1237         Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1238         return NewTemplate;
1239 }
1240
1241 /**
1242  * \brief Display a variable-substituted template
1243  * \param templatename template file to load
1244  */
1245 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1246 {
1247         int fd;
1248         struct stat statbuf;
1249         const char *pS, *pE, *pch, *Err;
1250         long Line;
1251         int pos;
1252         WCTemplate *NewTemplate;
1253
1254         fd = open(ChrPtr(filename), O_RDONLY);
1255         if (fd <= 0) {
1256                 lprintf(1, "ERROR: could not open template '%s' - %s\n",
1257                         ChrPtr(filename), strerror(errno));
1258                 return NULL;
1259         }
1260
1261         if (fstat(fd, &statbuf) == -1) {
1262                 lprintf(1, "ERROR: could not stat template '%s' - %s\n",
1263                         ChrPtr(filename), strerror(errno));
1264                 return NULL;
1265         }
1266
1267         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1268         NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size);
1269         NewTemplate->FileName = NewStrBufDup(filename);
1270         NewTemplate->nTokensUsed = 0;
1271         NewTemplate->TokenSpace = 0;
1272         NewTemplate->Tokens = NULL;
1273         if (StrBufReadBLOB(NewTemplate->Data, &fd, 1, statbuf.st_size, &Err) < 0) {
1274                 close(fd);
1275                 FreeWCTemplate(NewTemplate);
1276                 lprintf(1, "ERROR: reading template '%s' - %s<br />\n",
1277                         ChrPtr(filename), strerror(errno));
1278                 return NULL;
1279         }
1280         close(fd);
1281
1282         Line = 0;
1283         pS = pch = ChrPtr(NewTemplate->Data);
1284         pE = pS + StrLength(NewTemplate->Data);
1285         while (pch < pE) {
1286                 const char *pts, *pte;
1287                 int InQuotes = 0;
1288                 int InDoubleQuotes = 0;
1289
1290                 /** Find one <? > */
1291                 pos = (-1);
1292                 for (; pch < pE; pch ++) {
1293                         if ((*pch=='<')&&(*(pch + 1)=='?'))
1294                                 break;
1295                         if (*pch=='\n') Line ++;
1296                 }
1297                 if (pch >= pE)
1298                         continue;
1299                 pts = pch;
1300
1301                 /** Found one? parse it. */
1302                 for (; pch < pE - 1; pch ++) {
1303                         if (*pch == '"')
1304                                 InDoubleQuotes = ! InDoubleQuotes;
1305                         else if (*pch == '\'')
1306                                 InQuotes = ! InQuotes;
1307                         else if ((!InQuotes  && !InDoubleQuotes) &&
1308                                  ((*pch!='\\')&&(*(pch + 1)=='>'))) {
1309                                 pch ++;
1310                                 break;
1311                         }
1312                 }
1313                 if (pch + 1 >= pE)
1314                         continue;
1315                 pte = pch;
1316                 PutNewToken(NewTemplate, 
1317                             NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate));
1318                 pch ++;
1319         }
1320         if (LoadTemplates == 0)
1321                 Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1322         return NewTemplate;
1323 }
1324
1325
1326 ///void PrintTemplate(const char *Key, void *vSubst, int odd)
1327 const char* PrintTemplate(void *vSubst)
1328 {
1329         WCTemplate *Tmpl = vSubst;
1330
1331         return ChrPtr(Tmpl->FileName);
1332
1333 }
1334
1335
1336 /**
1337  * \brief Display a variable-substituted template
1338  * \param templatename template file to load
1339  */
1340 void DoTemplate(const char *templatename, long len, StrBuf *Target, void *Context, int ContextType) 
1341 {
1342         HashList *Static;
1343         HashList *StaticLocal;
1344         void *vTmpl;
1345         
1346         if (Target == NULL)
1347                 Target = WC->WBuf;
1348         if (WC->is_mobile) {
1349                 Static = WirelessTemplateCache;
1350                 StaticLocal = WirelessLocalTemplateCache;
1351         }
1352         else {
1353                 Static = TemplateCache;
1354                 StaticLocal = LocalTemplateCache;
1355         }
1356
1357         if (len == 0)
1358         {
1359                 lprintf (1, "Can't to load a template with empty name!\n");
1360                 StrBufAppendPrintf(Target, "<pre>\nCan't to load a template with empty name!\n</pre>");
1361                 return;
1362         }
1363
1364         if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
1365             !GetHash(Static, templatename, len, &vTmpl)) {
1366                 lprintf (1, "didn't find Template [%s] %ld %ld\n", templatename, len , (long)strlen(templatename));
1367                 StrBufAppendPrintf(Target, "<pre>\ndidn't find Template [%s] %ld %ld\n</pre>", 
1368                                    templatename, len, 
1369                                    (long)strlen(templatename));
1370 ///             dbg_PrintHash(Static, PrintTemplate, NULL);
1371 //              PrintHash(Static, VarPrintTransition, PrintTemplate);
1372                 return;
1373         }
1374         if (vTmpl == NULL) 
1375                 return;
1376         ProcessTemplate(vTmpl, Target, Context, ContextType);
1377 }
1378
1379 int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
1380 {
1381         StrBuf *FileName;
1382         StrBuf *Tag;
1383         StrBuf *Dir;
1384         DIR *filedir = NULL;
1385         struct dirent *filedir_entry;
1386         int d_namelen;
1387         int d_without_ext;
1388         int IsMobile;
1389         
1390         Dir = NewStrBuf();
1391         StrBufPrintf(Dir, "%s/t", DirName);
1392         filedir = opendir (ChrPtr(Dir));
1393         if (filedir == NULL) {
1394                 FreeStrBuf(&Dir);
1395                 return 0;
1396         }
1397
1398         FileName = NewStrBuf();
1399         Tag = NewStrBuf();
1400         while ((filedir_entry = readdir(filedir)))
1401         {
1402                 char *MinorPtr;
1403                 char *PStart;
1404 #ifdef _DIRENT_HAVE_D_NAMELEN
1405                 d_namelen = filedir_entry->d_namelen;
1406 #else
1407                 d_namelen = strlen(filedir_entry->d_name);
1408 #endif
1409                 d_without_ext = d_namelen;
1410                 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1411                         d_without_ext --;
1412                 if ((d_without_ext == 0) || (d_namelen < 3))
1413                         continue;
1414                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
1415                         continue; /* Ignore backup files... */
1416
1417                 IsMobile = (strstr(filedir_entry->d_name, ".m.html")!= NULL);
1418                 PStart = filedir_entry->d_name;
1419                 StrBufPrintf(FileName, "%s/%s", ChrPtr(Dir),  filedir_entry->d_name);
1420                 MinorPtr = strchr(filedir_entry->d_name, '.');
1421                 if (MinorPtr != NULL)
1422                         *MinorPtr = '\0';
1423                 StrBufPlain(Tag, filedir_entry->d_name, MinorPtr - filedir_entry->d_name);
1424
1425                 if (LoadTemplates > 1)
1426                         lprintf(1, "%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
1427                 if (LoadTemplates == 0)
1428                         load_template(FileName, Tag, (IsMobile)?wireless:big);
1429                 else
1430                         prepare_template(FileName, Tag, (IsMobile)?wireless:big);
1431         }
1432         closedir(filedir);
1433         FreeStrBuf(&FileName);
1434         FreeStrBuf(&Tag);
1435         FreeStrBuf(&Dir);
1436         return 1;
1437 }
1438
1439 void InitTemplateCache(void)
1440 {
1441         LoadTemplateDir(static_dirs[0],
1442                         WirelessTemplateCache,
1443                         TemplateCache);
1444         LoadTemplateDir(static_dirs[1],
1445                         WirelessLocalTemplateCache,
1446                         LocalTemplateCache);
1447 }
1448
1449
1450
1451 typedef struct _HashIterator {
1452         HashList *StaticList;
1453         int AdditionalParams;
1454         int ContextType;
1455         int XPectContextType;
1456         RetrieveHashlistFunc GetHash;
1457         HashDestructorFunc Destructor;
1458         SubTemplFunc DoSubTemplate;
1459 } HashIterator;
1460
1461 void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1462 {
1463         void *vIt;
1464         HashIterator *It;
1465         HashList *List;
1466         HashPos  *it;
1467         long len; 
1468         const char *Key;
1469         void *vContext;
1470         StrBuf *SubBuf;
1471         int oddeven = 0;
1472         
1473         if (!GetHash(Iterators, 
1474                      Tokens->Params[0]->Start,
1475                      Tokens->Params[0]->len,
1476                      &vIt)) {
1477                 lprintf(1, "unknown Iterator [%s] (in '%s' line %ld); "
1478                         " [%s]\n", 
1479                         Tokens->Params[0]->Start,
1480                         ChrPtr(Tokens->FileName),
1481                         Tokens->Line,
1482                         ChrPtr(Tokens->FlatToken));
1483                 StrBufAppendPrintf(
1484                         Target,
1485                         "<pre>\nunknown Iterator [%s] (in '%s' line %ld); \n"
1486                         " [%s]\n</pre>", 
1487                         Tokens->Params[0]->Start,
1488                         ChrPtr(Tokens->FileName),
1489                         Tokens->Line,
1490                         ChrPtr(Tokens->FlatToken));
1491                 return;
1492         }
1493
1494         It = (HashIterator*) vIt;
1495
1496         if (Tokens->nParameters < It->AdditionalParams + 2) {
1497                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1498                         "doesn't work with %ld params [%s]\n", 
1499                         Tokens->Params[0]->Start,
1500                         ChrPtr(Tokens->FileName),
1501                         Tokens->Line,
1502                         Tokens->nParameters, 
1503                         ChrPtr(Tokens->FlatToken));
1504                 StrBufAppendPrintf(
1505                         Target,
1506                         "<pre>Iterator [%s] \n(in '%s' line %ld);\n"
1507                         "doesn't work with %ld params \n[%s]\n</pre>", 
1508                         Tokens->Params[0]->Start,
1509                         ChrPtr(Tokens->FileName),
1510                         Tokens->Line,
1511                         Tokens->nParameters, 
1512                         ChrPtr(Tokens->FlatToken));
1513                 return;
1514         }
1515
1516         if ((It->XPectContextType != CTX_NONE) &&
1517             (It->XPectContextType != ContextType)) {
1518                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1519                         "requires context of type %ld, have %ld [%s]\n", 
1520                         Tokens->pName,
1521                         ChrPtr(Tokens->FileName),
1522                         Tokens->Line,
1523                         It->XPectContextType, 
1524                         ContextType,
1525                         ChrPtr(Tokens->FlatToken));
1526                 StrBufAppendPrintf(
1527                         Target, 
1528                         "<pre>\nIterator [%s] (in '%s' line %ld);"
1529                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1530                         Tokens->pName,
1531                         ChrPtr(Tokens->FileName),
1532                         Tokens->Line,
1533                         It->XPectContextType, 
1534                         ContextType,
1535                         ChrPtr(Tokens->FlatToken));
1536                 return ;
1537                 
1538         }
1539
1540
1541
1542
1543         if (It->StaticList == NULL)
1544                 List = It->GetHash(Target, nArgs, Tokens, Context, ContextType);
1545         else
1546                 List = It->StaticList;
1547
1548         SubBuf = NewStrBuf();
1549         it = GetNewHashPos();
1550         while (GetNextHashPos(List, it, &len, &Key, &vContext)) {
1551                 svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", 
1552                          (oddeven) ? "odd" : "even");
1553                 svprintf(HKEY("ITERATE:KEY"), WCS_STRING, "%s", Key);
1554
1555                 if (It->DoSubTemplate != NULL)
1556                         It->DoSubTemplate(SubBuf, vContext, Tokens);
1557                 DoTemplate(Tokens->Params[1]->Start,
1558                            Tokens->Params[1]->len,
1559                            SubBuf, vContext,
1560                            It->ContextType);
1561                         
1562                 StrBufAppendBuf(Target, SubBuf, 0);
1563                 FlushStrBuf(SubBuf);
1564                 oddeven = ~ oddeven;
1565         }
1566         FreeStrBuf(&SubBuf);
1567         DeleteHashPos(&it);
1568         if (It->Destructor != NULL)
1569                 It->Destructor(&List);
1570 }
1571
1572 int ConditionalVar(WCTemplateToken *Tokens, void *Context, int ContextType)
1573 {
1574         void *vsubst;
1575         wcsubst *subst;
1576         
1577         if (!GetHash(WC->vars, 
1578                      Tokens->Params[2]->Start,
1579                      Tokens->Params[2]->len,
1580                      &vsubst))
1581                 return 0;
1582         subst = (wcsubst*) vsubst;
1583         if ((subst->ContextRequired != CTX_NONE) &&
1584             (subst->ContextRequired != ContextType)) {
1585                 lprintf(1,"  WARNING: Conditional requires Context: [%ld]!\n", Tokens->Params[2]->Start);
1586                 return -1;
1587         }
1588
1589         switch(subst->wcs_type) {
1590         case WCS_FUNCTION:
1591                 return (subst->wcs_function!=NULL);
1592         case WCS_SERVCMD:
1593                 lprintf(1, "  -> Server [%s]\n", subst->wcs_value);////todo
1594                 return 1;
1595         case WCS_STRING:
1596         case WCS_STRBUF:
1597         case WCS_STRBUF_REF:
1598                 if (Tokens->nParameters < 4)
1599                         return 1;
1600                 return (strcmp(Tokens->Params[3]->Start, ChrPtr(subst->wcs_value)) == 0);
1601         case WCS_LONG:
1602                 if (Tokens->nParameters < 4)
1603                         return (subst->lvalue != 0);
1604                 return (subst->lvalue == Tokens->Params[3]->lvalue);
1605         default:
1606                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", subst->wcs_type);
1607                 return -1;
1608         }
1609         return 0;
1610 }
1611
1612 void RegisterITERATOR(const char *Name, long len, 
1613                       int AdditionalParams, 
1614                       HashList *StaticList, 
1615                       RetrieveHashlistFunc GetHash, 
1616                       SubTemplFunc DoSubTempl,
1617                       HashDestructorFunc Destructor,
1618                       int ContextType, 
1619                       int XPectContextType)
1620 {
1621         HashIterator *It = (HashIterator*)malloc(sizeof(HashIterator));
1622         It->StaticList = StaticList;
1623         It->AdditionalParams = AdditionalParams;
1624         It->GetHash = GetHash;
1625         It->DoSubTemplate = DoSubTempl;
1626         It->Destructor = Destructor;
1627         It->ContextType = ContextType;
1628         It->XPectContextType = XPectContextType;
1629         Put(Iterators, Name, len, It, NULL);
1630 }
1631
1632 void RegisterConditional(const char *Name, long len, 
1633                          int nParams,
1634                          WCConditionalFunc CondF, 
1635                          int ContextRequired)
1636 {
1637         ConditionalStruct *Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
1638         Cond->nParams = nParams;
1639         Cond->CondF = CondF;
1640         Cond->ContextRequired = ContextRequired;
1641         Put(Conditionals, Name, len, Cond, NULL);
1642 }
1643
1644
1645 void tmplput_ContextString(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1646 {
1647         StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType, (StrBuf*)Context, 0);
1648 }
1649 int ConditionalContextStr(WCTemplateToken *Tokens, void *Context, int ContextType)
1650 {
1651         StrBuf *EmailAddr = (StrBuf*) Context;
1652         const char *CompareToken;
1653         long len;
1654
1655         GetTemplateTokenString(Tokens, 3, &CompareToken, &len);
1656         return strcmp(ChrPtr(EmailAddr), CompareToken) == 0;
1657 }
1658
1659
1660 void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1661 {
1662         StrBuf *Headline;
1663         if (nArgs == 2) {
1664                 if (Tokens->Params[1]->Type == TYPE_STR) {
1665                         Headline = NewStrBuf();
1666                         DoTemplate(Tokens->Params[1]->Start, 
1667                                    Tokens->Params[1]->len,
1668                                    Headline, 
1669                                    Context, 
1670                                    ContextType);
1671                 }
1672                 else {
1673                         const char *Ch;
1674                         long *len;
1675                         GetTemplateTokenString(Tokens, 
1676                                                1,
1677                                                &Ch,
1678                                                &len);
1679                         Headline = NewStrBufPlain(Ch, len);
1680                 }
1681         }
1682         
1683         DoTemplate(HKEY("beginbox"), Target, Headline, CTX_STRBUF);
1684         DoTemplate(Tokens->Params[0]->Start, 
1685                    Tokens->Params[0]->len,
1686                    Target, 
1687                    Context, 
1688                    ContextType);
1689         DoTemplate(HKEY("endbox"), Target, Context, ContextType);
1690 }
1691
1692
1693 void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1694 {
1695         StrBuf **TabNames;
1696         int i, ntabs, nTabs;
1697
1698         nTabs = ntabs = Tokens->nParameters / 2;
1699         TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
1700
1701         for (i = 0; i < ntabs; i++) {
1702                 TabNames[i] = NewStrBuf();
1703                 if (Tokens->Params[i * 2]->len > 0) {
1704                         DoTemplate(Tokens->Params[i * 2]->Start, 
1705                                    Tokens->Params[i * 2]->len,
1706                                    TabNames[i],
1707                                    Context,
1708                                    ContextType);
1709                 }
1710                 else { 
1711                         /** A Tab without subject? we can't count that, add it as silent */
1712                         nTabs --;
1713                 }
1714         }
1715
1716         StrTabbedDialog(Target, nTabs, TabNames);
1717         for (i = 0; i < ntabs; i++) {
1718                 StrBeginTab(Target, i, nTabs);
1719
1720                 DoTemplate(Tokens->Params[i * 2 + 1]->Start, 
1721                            Tokens->Params[i * 2 + 1]->len,
1722                            Target,
1723                            Context, 
1724                            ContextType);
1725                 StrEndTab(Target, i, nTabs);
1726         }
1727 }
1728
1729 void 
1730 InitModule_SUBST
1731 (void)
1732 {
1733         RegisterNamespace("CONTEXTSTR", 0, 1, tmplput_ContextString, CTX_STRBUF);
1734         RegisterNamespace("ITERATE", 2, 100, tmpl_iterate_subtmpl, CTX_NONE);
1735         RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed, CTX_NONE);
1736         RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed, CTX_NONE);
1737         RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar, CTX_NONE);
1738         RegisterConditional(HKEY("COND:CONTEXT"), 3, ConditionalContextStr, CTX_NONE);
1739
1740 }
1741
1742 /*@}*/