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