a1879ba9d39628b7b070502b7a783e04b1dfb2f4
[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->nParameters < 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                 else  {
1061                         lprintf(1, "Conditional [%s] (in '%s' line %ld); needs at least 6 Params![%s]\n", 
1062                                 Token->Params[0]->Start,
1063                                 ChrPtr(pTmpl->FileName),
1064                                 Token->Line,
1065                                 ChrPtr(Token->FlatToken));
1066                         StrBufAppendPrintf(
1067                                 Target, 
1068                                 "<pre>\nConditional [%s] (in '%s' line %ld); needs 6 Params!\n[%s]\n</pre>\n", 
1069                                 Token->Params[0]->Start,
1070                                 ChrPtr(pTmpl->FileName),
1071                                 Token->Line,
1072                                 ChrPtr(Token->FlatToken));
1073                 }
1074                 break;
1075         case SV_SUBTEMPL:
1076                 if (Token->nParameters == 1)
1077                         DoTemplate(Token->Params[0]->Start, Token->Params[0]->len, NULL, NULL, ContextType);
1078                 break;
1079         case SV_PREEVALUATED:
1080                 Handler = (HashHandler*) Token->PreEval;
1081                 if ((Handler->ContextRequired != CTX_NONE) &&
1082                     (Handler->ContextRequired != ContextType)) {
1083                         lprintf(1, "Handler [%s] (in '%s' line %ld); "
1084                                 "requires context of type %ld, have %ld [%s]\n", 
1085                                 Token->pName,
1086                                 ChrPtr(pTmpl->FileName),
1087                                 Token->Line,
1088                                 Handler->ContextRequired, 
1089                                 ContextType,
1090                                 ChrPtr(Token->FlatToken));
1091                         StrBufAppendPrintf(
1092                                 Target, 
1093                                 "<pre>\nHandler [%s] (in '%s' line %ld);"
1094                                 " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1095                                 Token->pName,
1096                                 ChrPtr(pTmpl->FileName),
1097                                 Token->Line,
1098                                 Handler->ContextRequired, 
1099                                 ContextType,
1100                                 ChrPtr(Token->FlatToken));
1101                         return -1;
1102
1103                 }
1104                 Handler->HandlerFunc(Target, 
1105                                      Token->nParameters,
1106                                      Token,
1107                                      Context, 
1108                                      ContextType); 
1109                 break;          
1110         default:
1111                 if (GetHash(GlobalNS, Token->pName, Token->NameEnd, &vVar)) {
1112                         Handler = (HashHandler*) vVar;
1113                         if ((Handler->ContextRequired != CTX_NONE) &&
1114                             (Handler->ContextRequired != ContextType)) {
1115                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
1116                                         "requires context of type %ld, have %ld [%s]\n", 
1117                                         Token->pName,
1118                                         ChrPtr(pTmpl->FileName),
1119                                         Token->Line,
1120                                         Handler->ContextRequired, 
1121                                         ContextType,
1122                                         ChrPtr(Token->FlatToken));
1123                                 StrBufAppendPrintf(
1124                                         Target, 
1125                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
1126                                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1127                                         Token->pName,
1128                                         ChrPtr(pTmpl->FileName),
1129                                         Token->Line,
1130                                         Handler->ContextRequired, 
1131                                         ContextType,
1132                                         ChrPtr(Token->FlatToken));
1133                                 return -1;
1134                         }
1135                         else if ((Token->nParameters < Handler->nMinArgs) || 
1136                                  (Token->nParameters > Handler->nMaxArgs)) {
1137                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
1138                                         "doesn't work with %ld params [%s]\n", 
1139                                         Token->pName,
1140                                         ChrPtr(pTmpl->FileName),
1141                                         Token->Line,
1142                                         Token->nParameters, 
1143                                         ChrPtr(Token->FlatToken));
1144                                 StrBufAppendPrintf(
1145                                         Target, 
1146                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
1147                                         " doesn't work with %ld params!\n[%s]\n</pre>\n", 
1148                                         Token->pName,
1149                                         ChrPtr(pTmpl->FileName),
1150                                         Token->Line,
1151                                         Token->nParameters,
1152                                         ChrPtr(Token->FlatToken));
1153                         }
1154                         else {
1155                                 Handler->HandlerFunc(Target, 
1156                                                      Token->nParameters,
1157                                                      Token,
1158                                                      Context, 
1159                                                      ContextType); /*TODO: subset of that */
1160                                 
1161                         }
1162                 }
1163                 else {
1164                         print_value_of(Target, Token, Context, ContextType);
1165                 }
1166         }
1167         return 0;
1168 }
1169
1170 void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context, int ContextType)
1171 {
1172         WCTemplate *pTmpl = Tmpl;
1173         int done = 0;
1174         int i, state;
1175         const char *pData, *pS;
1176         long len;
1177
1178         if (LoadTemplates != 0) {                       
1179                 if (LoadTemplates > 1)
1180                         lprintf(1, "DBG: ----- loading:  [%s] ------ \n", 
1181                                 ChrPtr(Tmpl->FileName));
1182
1183                 pTmpl = load_template(Tmpl->FileName, NULL, NULL);
1184                 if(pTmpl == NULL) {
1185                         StrBufAppendPrintf(
1186                                 Target, 
1187                                 "<pre>\nError loading Template [%s]\n See Logfile for details\n</pre>\n", 
1188                                 ChrPtr(Tmpl->FileName));
1189                         return;
1190                 }
1191
1192         }
1193
1194         pS = pData = ChrPtr(pTmpl->Data);
1195         len = StrLength(pTmpl->Data);
1196         i = 0;
1197         state = 0;
1198         while (!done) {
1199                 if (i >= pTmpl->nTokensUsed) {
1200                         StrBufAppendBufPlain(Target, 
1201                                              pData, 
1202                                              len - (pData - pS), 0);
1203                         done = 1;
1204                 }
1205                 else {
1206                         StrBufAppendBufPlain(
1207                                 Target, pData, 
1208                                 pTmpl->Tokens[i]->pTokenStart - pData, 0);
1209                         state = EvaluateToken(Target, pTmpl->Tokens[i], pTmpl, Context, state, ContextType);
1210                         while ((state != 0) && (i+1 < pTmpl->nTokensUsed)) {
1211                         /* condition told us to skip till its end condition */
1212                                 i++;
1213                                 if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
1214                                     (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL)) {
1215                                         if (state == EvaluateConditional(
1216                                                     Target,
1217                                                     pTmpl->Tokens[i], 
1218                                                     pTmpl,
1219                                                     Context, 
1220                                                     pTmpl->Tokens[i]->Flags,
1221                                                     state, 
1222                                                     ContextType))
1223                                                 state = 0;
1224                                 }
1225                         }
1226                         pData = pTmpl->Tokens[i++]->pTokenEnd + 1;
1227                         if (i > pTmpl->nTokensUsed)
1228                                 done = 1;
1229                 }
1230         }
1231         if (LoadTemplates != 0) {
1232                 FreeWCTemplate(pTmpl);
1233         }
1234 }
1235
1236
1237 /**
1238  * \brief Display a variable-substituted template
1239  * \param templatename template file to load
1240  */
1241 void *prepare_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1242 {
1243         WCTemplate *NewTemplate;
1244         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1245         NewTemplate->Data = NULL;
1246         NewTemplate->FileName = NewStrBufDup(filename);
1247         NewTemplate->nTokensUsed = 0;
1248         NewTemplate->TokenSpace = 0;
1249         NewTemplate->Tokens = NULL;
1250
1251         Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1252         return NewTemplate;
1253 }
1254
1255 /**
1256  * \brief Display a variable-substituted template
1257  * \param templatename template file to load
1258  */
1259 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1260 {
1261         int fd;
1262         struct stat statbuf;
1263         const char *pS, *pE, *pch, *Err;
1264         long Line;
1265         int pos;
1266         WCTemplate *NewTemplate;
1267
1268         fd = open(ChrPtr(filename), O_RDONLY);
1269         if (fd <= 0) {
1270                 lprintf(1, "ERROR: could not open template '%s' - %s\n",
1271                         ChrPtr(filename), strerror(errno));
1272                 return NULL;
1273         }
1274
1275         if (fstat(fd, &statbuf) == -1) {
1276                 lprintf(1, "ERROR: could not stat template '%s' - %s\n",
1277                         ChrPtr(filename), strerror(errno));
1278                 return NULL;
1279         }
1280
1281         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1282         NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size);
1283         NewTemplate->FileName = NewStrBufDup(filename);
1284         NewTemplate->nTokensUsed = 0;
1285         NewTemplate->TokenSpace = 0;
1286         NewTemplate->Tokens = NULL;
1287         if (StrBufReadBLOB(NewTemplate->Data, &fd, 1, statbuf.st_size, &Err) < 0) {
1288                 close(fd);
1289                 FreeWCTemplate(NewTemplate);
1290                 lprintf(1, "ERROR: reading template '%s' - %s<br />\n",
1291                         ChrPtr(filename), strerror(errno));
1292                 return NULL;
1293         }
1294         close(fd);
1295
1296         Line = 0;
1297         pS = pch = ChrPtr(NewTemplate->Data);
1298         pE = pS + StrLength(NewTemplate->Data);
1299         while (pch < pE) {
1300                 const char *pts, *pte;
1301                 int InQuotes = 0;
1302                 int InDoubleQuotes = 0;
1303
1304                 /** Find one <? > */
1305                 pos = (-1);
1306                 for (; pch < pE; pch ++) {
1307                         if ((*pch=='<')&&(*(pch + 1)=='?'))
1308                                 break;
1309                         if (*pch=='\n') Line ++;
1310                 }
1311                 if (pch >= pE)
1312                         continue;
1313                 pts = pch;
1314
1315                 /** Found one? parse it. */
1316                 for (; pch < pE - 1; pch ++) {
1317                         if (*pch == '"')
1318                                 InDoubleQuotes = ! InDoubleQuotes;
1319                         else if (*pch == '\'')
1320                                 InQuotes = ! InQuotes;
1321                         else if ((!InQuotes  && !InDoubleQuotes) &&
1322                                  ((*pch!='\\')&&(*(pch + 1)=='>'))) {
1323                                 pch ++;
1324                                 break;
1325                         }
1326                 }
1327                 if (pch + 1 >= pE)
1328                         continue;
1329                 pte = pch;
1330                 PutNewToken(NewTemplate, 
1331                             NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate));
1332                 pch ++;
1333         }
1334         if (LoadTemplates == 0)
1335                 Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1336         return NewTemplate;
1337 }
1338
1339
1340 ///void PrintTemplate(const char *Key, void *vSubst, int odd)
1341 const char* PrintTemplate(void *vSubst)
1342 {
1343         WCTemplate *Tmpl = vSubst;
1344
1345         return ChrPtr(Tmpl->FileName);
1346
1347 }
1348
1349
1350 /**
1351  * \brief Display a variable-substituted template
1352  * \param templatename template file to load
1353  */
1354 void DoTemplate(const char *templatename, long len, StrBuf *Target, void *Context, int ContextType) 
1355 {
1356         HashList *Static;
1357         HashList *StaticLocal;
1358         void *vTmpl;
1359         
1360         if (Target == NULL)
1361                 Target = WC->WBuf;
1362         if (WC->is_mobile) {
1363                 Static = WirelessTemplateCache;
1364                 StaticLocal = WirelessLocalTemplateCache;
1365         }
1366         else {
1367                 Static = TemplateCache;
1368                 StaticLocal = LocalTemplateCache;
1369         }
1370
1371         if (len == 0)
1372         {
1373                 lprintf (1, "Can't to load a template with empty name!\n");
1374                 StrBufAppendPrintf(Target, "<pre>\nCan't to load a template with empty name!\n</pre>");
1375                 return;
1376         }
1377
1378         if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
1379             !GetHash(Static, templatename, len, &vTmpl)) {
1380                 lprintf (1, "didn't find Template [%s] %ld %ld\n", templatename, len , (long)strlen(templatename));
1381                 StrBufAppendPrintf(Target, "<pre>\ndidn't find Template [%s] %ld %ld\n</pre>", 
1382                                    templatename, len, 
1383                                    (long)strlen(templatename));
1384 ///             dbg_PrintHash(Static, PrintTemplate, NULL);
1385 //              PrintHash(Static, VarPrintTransition, PrintTemplate);
1386                 return;
1387         }
1388         if (vTmpl == NULL) 
1389                 return;
1390         ProcessTemplate(vTmpl, Target, Context, ContextType);
1391 }
1392
1393 int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
1394 {
1395         StrBuf *FileName;
1396         StrBuf *Tag;
1397         StrBuf *Dir;
1398         DIR *filedir = NULL;
1399         struct dirent *filedir_entry;
1400         int d_namelen;
1401         int d_without_ext;
1402         int IsMobile;
1403         
1404         Dir = NewStrBuf();
1405         StrBufPrintf(Dir, "%s/t", DirName);
1406         filedir = opendir (ChrPtr(Dir));
1407         if (filedir == NULL) {
1408                 FreeStrBuf(&Dir);
1409                 return 0;
1410         }
1411
1412         FileName = NewStrBuf();
1413         Tag = NewStrBuf();
1414         while ((filedir_entry = readdir(filedir)))
1415         {
1416                 char *MinorPtr;
1417                 char *PStart;
1418 #ifdef _DIRENT_HAVE_D_NAMELEN
1419                 d_namelen = filedir_entry->d_namelen;
1420 #else
1421                 d_namelen = strlen(filedir_entry->d_name);
1422 #endif
1423                 d_without_ext = d_namelen;
1424                 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1425                         d_without_ext --;
1426                 if ((d_without_ext == 0) || (d_namelen < 3))
1427                         continue;
1428                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
1429                         continue; /* Ignore backup files... */
1430
1431                 IsMobile = (strstr(filedir_entry->d_name, ".m.html")!= NULL);
1432                 PStart = filedir_entry->d_name;
1433                 StrBufPrintf(FileName, "%s/%s", ChrPtr(Dir),  filedir_entry->d_name);
1434                 MinorPtr = strchr(filedir_entry->d_name, '.');
1435                 if (MinorPtr != NULL)
1436                         *MinorPtr = '\0';
1437                 StrBufPlain(Tag, filedir_entry->d_name, MinorPtr - filedir_entry->d_name);
1438
1439                 if (LoadTemplates > 1)
1440                         lprintf(1, "%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
1441                 if (LoadTemplates == 0)
1442                         load_template(FileName, Tag, (IsMobile)?wireless:big);
1443                 else
1444                         prepare_template(FileName, Tag, (IsMobile)?wireless:big);
1445         }
1446         closedir(filedir);
1447         FreeStrBuf(&FileName);
1448         FreeStrBuf(&Tag);
1449         FreeStrBuf(&Dir);
1450         return 1;
1451 }
1452
1453 void InitTemplateCache(void)
1454 {
1455         LoadTemplateDir(static_dirs[0],
1456                         WirelessTemplateCache,
1457                         TemplateCache);
1458         LoadTemplateDir(static_dirs[1],
1459                         WirelessLocalTemplateCache,
1460                         LocalTemplateCache);
1461 }
1462
1463
1464
1465 typedef struct _HashIterator {
1466         HashList *StaticList;
1467         int AdditionalParams;
1468         int ContextType;
1469         int XPectContextType;
1470         RetrieveHashlistFunc GetHash;
1471         HashDestructorFunc Destructor;
1472         SubTemplFunc DoSubTemplate;
1473 } HashIterator;
1474
1475 void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1476 {
1477         void *vIt;
1478         HashIterator *It;
1479         HashList *List;
1480         HashPos  *it;
1481         long len; 
1482         const char *Key;
1483         void *vContext;
1484         StrBuf *SubBuf;
1485         int oddeven = 0;
1486         
1487         if (!GetHash(Iterators, 
1488                      Tokens->Params[0]->Start,
1489                      Tokens->Params[0]->len,
1490                      &vIt)) {
1491                 lprintf(1, "unknown Iterator [%s] (in '%s' line %ld); "
1492                         " [%s]\n", 
1493                         Tokens->Params[0]->Start,
1494                         ChrPtr(Tokens->FileName),
1495                         Tokens->Line,
1496                         ChrPtr(Tokens->FlatToken));
1497                 StrBufAppendPrintf(
1498                         Target,
1499                         "<pre>\nunknown Iterator [%s] (in '%s' line %ld); \n"
1500                         " [%s]\n</pre>", 
1501                         Tokens->Params[0]->Start,
1502                         ChrPtr(Tokens->FileName),
1503                         Tokens->Line,
1504                         ChrPtr(Tokens->FlatToken));
1505                 return;
1506         }
1507
1508         It = (HashIterator*) vIt;
1509
1510         if (Tokens->nParameters < It->AdditionalParams + 2) {
1511                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1512                         "doesn't work with %ld params [%s]\n", 
1513                         Tokens->Params[0]->Start,
1514                         ChrPtr(Tokens->FileName),
1515                         Tokens->Line,
1516                         Tokens->nParameters, 
1517                         ChrPtr(Tokens->FlatToken));
1518                 StrBufAppendPrintf(
1519                         Target,
1520                         "<pre>Iterator [%s] \n(in '%s' line %ld);\n"
1521                         "doesn't work with %ld params \n[%s]\n</pre>", 
1522                         Tokens->Params[0]->Start,
1523                         ChrPtr(Tokens->FileName),
1524                         Tokens->Line,
1525                         Tokens->nParameters, 
1526                         ChrPtr(Tokens->FlatToken));
1527                 return;
1528         }
1529
1530         if ((It->XPectContextType != CTX_NONE) &&
1531             (It->XPectContextType != ContextType)) {
1532                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1533                         "requires context of type %ld, have %ld [%s]\n", 
1534                         Tokens->pName,
1535                         ChrPtr(Tokens->FileName),
1536                         Tokens->Line,
1537                         It->XPectContextType, 
1538                         ContextType,
1539                         ChrPtr(Tokens->FlatToken));
1540                 StrBufAppendPrintf(
1541                         Target, 
1542                         "<pre>\nIterator [%s] (in '%s' line %ld);"
1543                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1544                         Tokens->pName,
1545                         ChrPtr(Tokens->FileName),
1546                         Tokens->Line,
1547                         It->XPectContextType, 
1548                         ContextType,
1549                         ChrPtr(Tokens->FlatToken));
1550                 return ;
1551                 
1552         }
1553
1554
1555
1556
1557         if (It->StaticList == NULL)
1558                 List = It->GetHash(Target, nArgs, Tokens, Context, ContextType);
1559         else
1560                 List = It->StaticList;
1561
1562         SubBuf = NewStrBuf();
1563         it = GetNewHashPos();
1564         while (GetNextHashPos(List, it, &len, &Key, &vContext)) {
1565                 svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", 
1566                          (oddeven) ? "odd" : "even");
1567                 svprintf(HKEY("ITERATE:KEY"), WCS_STRING, "%s", Key);
1568
1569                 if (It->DoSubTemplate != NULL)
1570                         It->DoSubTemplate(SubBuf, vContext, Tokens);
1571                 DoTemplate(Tokens->Params[1]->Start,
1572                            Tokens->Params[1]->len,
1573                            SubBuf, vContext,
1574                            It->ContextType);
1575                         
1576                 StrBufAppendBuf(Target, SubBuf, 0);
1577                 FlushStrBuf(SubBuf);
1578                 oddeven = ~ oddeven;
1579         }
1580         FreeStrBuf(&SubBuf);
1581         DeleteHashPos(&it);
1582         if (It->Destructor != NULL)
1583                 It->Destructor(&List);
1584 }
1585
1586 int ConditionalVar(WCTemplateToken *Tokens, void *Context, int ContextType)
1587 {
1588         void *vsubst;
1589         wcsubst *subst;
1590         
1591         if (!GetHash(WC->vars, 
1592                      Tokens->Params[2]->Start,
1593                      Tokens->Params[2]->len,
1594                      &vsubst))
1595                 return 0;
1596         subst = (wcsubst*) vsubst;
1597         if ((subst->ContextRequired != CTX_NONE) &&
1598             (subst->ContextRequired != ContextType)) {
1599                 lprintf(1,"  WARNING: Conditional requires Context: [%ld]!\n", Tokens->Params[2]->Start);
1600                 return -1;
1601         }
1602
1603         switch(subst->wcs_type) {
1604         case WCS_FUNCTION:
1605                 return (subst->wcs_function!=NULL);
1606         case WCS_SERVCMD:
1607                 lprintf(1, "  -> Server [%s]\n", subst->wcs_value);////todo
1608                 return 1;
1609         case WCS_STRING:
1610         case WCS_STRBUF:
1611         case WCS_STRBUF_REF:
1612                 if (Tokens->nParameters < 4)
1613                         return 1;
1614                 return (strcmp(Tokens->Params[3]->Start, ChrPtr(subst->wcs_value)) == 0);
1615         case WCS_LONG:
1616                 if (Tokens->nParameters < 4)
1617                         return (subst->lvalue != 0);
1618                 return (subst->lvalue == Tokens->Params[3]->lvalue);
1619         default:
1620                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", subst->wcs_type);
1621                 return -1;
1622         }
1623         return 0;
1624 }
1625
1626 void RegisterITERATOR(const char *Name, long len, 
1627                       int AdditionalParams, 
1628                       HashList *StaticList, 
1629                       RetrieveHashlistFunc GetHash, 
1630                       SubTemplFunc DoSubTempl,
1631                       HashDestructorFunc Destructor,
1632                       int ContextType, 
1633                       int XPectContextType)
1634 {
1635         HashIterator *It = (HashIterator*)malloc(sizeof(HashIterator));
1636         It->StaticList = StaticList;
1637         It->AdditionalParams = AdditionalParams;
1638         It->GetHash = GetHash;
1639         It->DoSubTemplate = DoSubTempl;
1640         It->Destructor = Destructor;
1641         It->ContextType = ContextType;
1642         It->XPectContextType = XPectContextType;
1643         Put(Iterators, Name, len, It, NULL);
1644 }
1645
1646 void RegisterConditional(const char *Name, long len, 
1647                          int nParams,
1648                          WCConditionalFunc CondF, 
1649                          int ContextRequired)
1650 {
1651         ConditionalStruct *Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
1652         Cond->PlainName = Name;
1653         Cond->nParams = nParams;
1654         Cond->CondF = CondF;
1655         Cond->ContextRequired = ContextRequired;
1656         Put(Conditionals, Name, len, Cond, NULL);
1657 }
1658
1659
1660 void tmplput_ContextString(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1661 {
1662         StrBufAppendTemplate(Target, nArgs, Tokens, Context, ContextType, (StrBuf*)Context, 0);
1663 }
1664 int ConditionalContextStr(WCTemplateToken *Tokens, void *Context, int ContextType)
1665 {
1666         StrBuf *TokenText = (StrBuf*) Context;
1667         const char *CompareToken;
1668         long len;
1669
1670         GetTemplateTokenString(Tokens, 2, &CompareToken, &len);
1671         return strcmp(ChrPtr(TokenText), CompareToken) == 0;
1672 }
1673
1674
1675 void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1676 {
1677         StrBuf *Headline;
1678         if (nArgs == 2) {
1679                 if (Tokens->Params[1]->Type == TYPE_STR) {
1680                         Headline = NewStrBuf();
1681                         DoTemplate(Tokens->Params[1]->Start, 
1682                                    Tokens->Params[1]->len,
1683                                    Headline, 
1684                                    Context, 
1685                                    ContextType);
1686                 }
1687                 else {
1688                         const char *Ch;
1689                         long len;
1690                         GetTemplateTokenString(Tokens, 
1691                                                1,
1692                                                &Ch,
1693                                                &len);
1694                         Headline = NewStrBufPlain(Ch, len);
1695                 }
1696         }
1697         
1698         DoTemplate(HKEY("beginbox"), Target, Headline, CTX_STRBUF);
1699         DoTemplate(Tokens->Params[0]->Start, 
1700                    Tokens->Params[0]->len,
1701                    Target, 
1702                    Context, 
1703                    ContextType);
1704         DoTemplate(HKEY("endbox"), Target, Context, ContextType);
1705 }
1706
1707
1708 void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1709 {
1710         StrBuf **TabNames;
1711         int i, ntabs, nTabs;
1712
1713         nTabs = ntabs = Tokens->nParameters / 2;
1714         TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
1715
1716         for (i = 0; i < ntabs; i++) {
1717                 TabNames[i] = NewStrBuf();
1718                 if (Tokens->Params[i * 2]->len > 0) {
1719                         DoTemplate(Tokens->Params[i * 2]->Start, 
1720                                    Tokens->Params[i * 2]->len,
1721                                    TabNames[i],
1722                                    Context,
1723                                    ContextType);
1724                 }
1725                 else { 
1726                         /** A Tab without subject? we can't count that, add it as silent */
1727                         nTabs --;
1728                 }
1729         }
1730
1731         StrTabbedDialog(Target, nTabs, TabNames);
1732         for (i = 0; i < ntabs; i++) {
1733                 StrBeginTab(Target, i, nTabs);
1734
1735                 DoTemplate(Tokens->Params[i * 2 + 1]->Start, 
1736                            Tokens->Params[i * 2 + 1]->len,
1737                            Target,
1738                            Context, 
1739                            ContextType);
1740                 StrEndTab(Target, i, nTabs);
1741         }
1742 }
1743
1744 void 
1745 InitModule_SUBST
1746 (void)
1747 {
1748         RegisterNamespace("CONTEXTSTR", 0, 1, tmplput_ContextString, CTX_STRBUF);
1749         RegisterNamespace("ITERATE", 2, 100, tmpl_iterate_subtmpl, CTX_NONE);
1750         RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed, CTX_NONE);
1751         RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed, CTX_NONE);
1752         RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar, CTX_NONE);
1753         RegisterConditional(HKEY("COND:CONTEXTSTR"), 3, ConditionalContextStr, CTX_STRBUF);
1754 }
1755
1756 /*@}*/