8fd62ef1a56a92020bf995488c8a1792a8a7efa6
[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                           StrBuf *Source, int FormatTypeIndex)
477 {
478         char EscapeAs = ' ';
479
480
481
482         switch(EscapeAs)
483         {
484
485         case 'X':
486                 StrEscAppend(Target, Source, NULL, 0, 0);
487                 break;
488         default:
489                 StrBufAppendBuf(Target, Source, 0);
490         }
491 }
492
493
494 /**
495  * \brief Print the value of a variable
496  * \param keyname get a key to print
497  */
498 void print_value_of(StrBuf *Target, WCTemplateToken *Token, void *Context, int ContextType) {
499         struct wcsession *WCC = WC;
500         wcsubst *ptr;
501         void *vVar;
502
503         /*if (WCC->vars != NULL) PrintHash(WCC->vars, VarPrintTransition, VarPrintEntry);*/
504         /// TODO: debricated!
505         if (Token->pName[0] == '=') {
506                 DoTemplate(Token->pName+1, Token->NameEnd - 1, NULL, NULL, 0);
507         }
508
509 //////TODO: if param[1] == "U" -> urlescape
510 /// X -> escputs
511         /** Page-local variables */
512         if ((WCC->vars!= NULL) && GetHash(WCC->vars, Token->pName, Token->NameEnd, &vVar)) {
513                 ptr = (wcsubst*) vVar;
514                 switch(ptr->wcs_type) {
515                 case WCS_STRING:
516                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
517                         break;
518                 case WCS_SERVCMD:
519                         pvo_do_cmd(Target, ptr->wcs_value);
520                         break;
521                 case WCS_FUNCTION:
522                         (*ptr->wcs_function) (Target, Token->nParameters, Token, Context, ContextType);
523                         break;
524                 case WCS_STRBUF:
525                 case WCS_STRBUF_REF:
526                         StrBufAppendBuf(Target, ptr->wcs_value, 0);
527                         break;
528                 case WCS_LONG:
529                         StrBufAppendPrintf(Target, "%ld", ptr->lvalue);
530                         break;
531                 default:
532                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", Token->pName);
533                         StrBufAppendPrintf(Target, "<pre>WARNING: \ninvalid value in SV-Hash at %s!\n</pre>", Token->pName);
534                 }
535         }
536         else {
537                 lprintf(1, "didn't find Handler [%s] (in '%s' line %ld); "
538                         " [%s]\n", 
539                         Token->pName,
540                         ChrPtr(Token->FileName),
541                         Token->Line,
542                         ChrPtr(Token->FlatToken));
543                 wc_backtrace();
544         }
545 }
546
547 int CompareSubstToToken(TemplateParam *ParamToCompare, TemplateParam *ParamToLookup)
548 {
549         struct wcsession *WCC = WC;
550         wcsubst *ptr;
551         void *vVar;
552
553         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
554                                           ParamToLookup->len, &vVar)) {
555                 ptr = (wcsubst*) vVar;
556                 switch(ptr->wcs_type) {
557                 case WCS_STRING:
558                 case WCS_STRBUF:
559                 case WCS_STRBUF_REF:
560                         if (ParamToCompare->Type == TYPE_STR)
561                                 return ((ParamToCompare->len == StrLength(ptr->wcs_value)) &&
562                                         (strcmp(ParamToCompare->Start, ChrPtr(ptr->wcs_value)) == 0));
563                         else
564                                 return ParamToCompare->lvalue == StrTol(ptr->wcs_value);
565                         break;
566                 case WCS_SERVCMD:
567                         return 1; 
568                         break;
569                 case WCS_FUNCTION:
570                         return 1;
571                 case WCS_LONG:
572                         if (ParamToCompare->Type == TYPE_STR)
573                                 return 0;
574                         else 
575                                 return ParamToCompare->lvalue == ptr->lvalue;
576                         break;
577                 default:
578                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
579                                 ParamToLookup->Start);
580                 }
581         }
582         return 0;
583 }
584
585 int CompareSubstToStrBuf(StrBuf *Compare, TemplateParam *ParamToLookup)
586 {
587         struct wcsession *WCC = WC;
588         wcsubst *ptr;
589         void *vVar;
590
591         if ((WCC->vars!= NULL) && GetHash(WCC->vars, ParamToLookup->Start, 
592                                           ParamToLookup->len, &vVar)) {
593                 ptr = (wcsubst*) vVar;
594                 switch(ptr->wcs_type) {
595                 case WCS_STRING:
596                 case WCS_STRBUF:
597                 case WCS_STRBUF_REF:
598                         return ((StrLength(Compare) == StrLength(ptr->wcs_value)) &&
599                                 (strcmp(ChrPtr(Compare), ChrPtr(ptr->wcs_value)) == 0));
600                 case WCS_SERVCMD:
601                         return 1; 
602                         break;
603                 case WCS_FUNCTION:
604                         return 1;
605                 case WCS_LONG:
606                         return StrTol(Compare) == ptr->lvalue;
607                 default:
608                         lprintf(1,"WARNING: invalid value in SV-Hash at %s!\n", 
609                                 ParamToLookup->Start);
610                 }
611         }
612         return 0;
613 }
614
615
616 void PutNewToken(WCTemplate *Template, WCTemplateToken *NewToken)
617 {
618         if (Template->nTokensUsed + 1 >= Template->TokenSpace) {
619                 if (Template->TokenSpace <= 0) {
620                         Template->Tokens = (WCTemplateToken**)malloc(
621                                 sizeof(WCTemplateToken*) * 10);
622                         Template->TokenSpace = 10;
623                 }
624                 else {
625                         WCTemplateToken **NewTokens;
626                         NewTokens= (WCTemplateToken**)malloc(
627                                 sizeof(WCTemplateToken*) * 
628                                 Template->TokenSpace * 2);
629                         memcpy(NewTokens, Template->Tokens, 
630                                sizeof(WCTemplateToken*) * Template->nTokensUsed);
631                         free(Template->Tokens);
632                         Template->TokenSpace *= 2;
633                         Template->Tokens = NewTokens;
634                 }
635         }
636         Template->Tokens[(Template->nTokensUsed)++] = NewToken;
637 }
638
639 TemplateParam *GetNextParameter(StrBuf *Buf, const char **pCh, const char *pe, WCTemplateToken *Token, WCTemplate *pTmpl)
640 {
641         const char *pch = *pCh;
642         const char *pchs, *pche;
643         TemplateParam *Parm = (TemplateParam *) malloc(sizeof(TemplateParam));
644         char quote = '\0';
645         
646         /* Skip leading whitespaces */
647         while ((*pch == ' ' )||
648                (*pch == '\t')||
649                (*pch == '\r')||
650                (*pch == '\n')) pch ++;
651         if (*pch == '"')
652                 quote = '"';
653         else if (*pch == '\'')
654                 quote = '\'';
655         if (quote != '\0') {
656                 pch ++;
657                 pchs = pch;
658                 Parm->Type = TYPE_STR;
659                 while (pch <= pe &&
660                        ((*pch != quote) ||
661                         ( (pch > pchs) && (*(pch - 1) == '\\'))
662                                )) {
663                         pch ++;
664                 }
665                 pche = pch;
666                 if (*pch != quote) {
667                         lprintf(1, "Error (in '%s' line %ld); "
668                                 "evaluating template param [%s] in Token [%s]\n",
669                                 ChrPtr(pTmpl->FileName),
670                                 Token->Line,
671                                 ChrPtr(Token->FlatToken),
672                                 *pCh);
673                         pch ++;
674                         free(Parm);
675                         return NULL;
676                 }
677                 else {
678                         StrBufPeek(Buf, pch, -1, '\0');         
679                         if (LoadTemplates > 1) {                        
680                                 lprintf(1, "DBG: got param [%s] %ld %ld\n", 
681                                         pchs, pche - pchs, strlen(pchs));
682                         }
683                         Parm->Start = pchs;
684                         Parm->len = pche - pchs;
685                         pch ++; /* move after trailing quote */
686                 }
687         }
688         else {
689                 Parm->Type = TYPE_LONG;
690                 pchs = pch;
691                 while ((pch <= pe) &&
692                        (isdigit(*pch) ||
693                         (*pch == '+') ||
694                         (*pch == '-')))
695                         pch ++;
696                 pch ++;
697                 if (pch - pchs > 1){
698                         StrBufPeek(Buf, pch, -1, '\0');
699                         Parm->lvalue = atol(pchs);
700                         Parm->Start = pchs;
701                         pch++;
702                 }
703                 else {
704                         Parm->lvalue = 0;
705                         lprintf(1, "Error (in '%s' line %ld); "
706                                 "evaluating long template param [%s] in Token [%s]\n",
707                                 ChrPtr(pTmpl->FileName),
708                                 Token->Line,
709                                 ChrPtr(Token->FlatToken),
710                                 *pCh);
711                         free(Parm);
712                         return NULL;
713                 }
714         }
715         while ((*pch == ' ' )||
716                (*pch == '\t')||
717                (*pch == '\r')||
718                (*pch == ',' )||
719                (*pch == '\n')) pch ++;
720
721         *pCh = pch;
722         return Parm;
723 }
724
725 WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf, 
726                                        const char *pStart, 
727                                        const char *pTmplStart, 
728                                        const char *pTmplEnd, 
729                                        long Line,
730                                        WCTemplate *pTmpl)
731 {
732         void *vVar;
733         const char *pch;
734         TemplateParam *Param;
735         WCTemplateToken *NewToken = (WCTemplateToken*)malloc(sizeof(WCTemplateToken));
736
737         NewToken->FileName = pTmpl->FileName; /* to print meaningfull log messages... */
738         NewToken->Flags = 0;
739         NewToken->Line = Line + 1;
740         NewToken->pTokenStart = pTmplStart;
741         NewToken->TokenStart = pTmplStart - pStart;
742         NewToken->TokenEnd =  (pTmplEnd - pStart) - NewToken->TokenStart;
743         NewToken->pTokenEnd = pTmplEnd;
744         NewToken->NameEnd = NewToken->TokenEnd - 2;
745         NewToken->PreEval = NULL;
746         NewToken->FlatToken = NewStrBufPlain(pTmplStart + 2, pTmplEnd - pTmplStart - 2);
747         
748         StrBufPeek(Buf, pTmplStart, + 1, '\0');
749         StrBufPeek(Buf, pTmplEnd, -1, '\0');
750         pch = NewToken->pName = pTmplStart + 2;
751
752         NewToken->HaveParameters = 0;;
753         NewToken->nParameters = 0;
754
755         while (pch < pTmplEnd - 1) {
756                 if (*pch == '(') {
757                         StrBufPeek(Buf, pch, -1, '\0');
758                         NewToken->NameEnd = pch - NewToken->pName;
759                         pch ++;
760                         if (*(pTmplEnd - 1) != ')') {
761                                 lprintf(1, "Warning, Non welformed Token; missing right parenthesis (in '%s' line %ld); "
762                                         "[%s]\n", 
763                                         ChrPtr(pTmpl->FileName),
764                                         NewToken->Line,
765                                         ChrPtr(NewToken->FlatToken));
766                         }
767                         while (pch < pTmplEnd - 1) {
768                                 Param = GetNextParameter(Buf, &pch, pTmplEnd - 1, NewToken, pTmpl);
769                                 if (Param != NULL) {
770                                         NewToken->HaveParameters = 1;
771                                         if (NewToken->nParameters > MAXPARAM) {
772                                                 lprintf(1, "Error (in '%s' line %ld); "
773                                                         "only [%ld] Params allowed in Tokens [%s]\n",
774                                                         ChrPtr(pTmpl->FileName),
775                                                         NewToken->Line,
776                                                         MAXPARAM,
777                                                         ChrPtr(NewToken->FlatToken));
778                                                 free(Param);
779                                                 FreeToken(&NewToken);
780                                                 return NULL;
781                                         }
782                                         NewToken->Params[NewToken->nParameters++] = Param;
783                                 }
784                                 else break;
785                         }
786                         if((NewToken->NameEnd == 1) &&
787                            (NewToken->HaveParameters == 1))
788                            
789                         {
790                                 if (*(NewToken->pName) == '_')
791                                         NewToken->Flags = SV_GETTEXT;
792                                 else if (*(NewToken->pName) == '=')
793                                         NewToken->Flags = SV_SUBTEMPL;
794                                 else if (*(NewToken->pName) == '%')
795                                         NewToken->Flags = SV_CUST_STR_CONDITIONAL;
796                                 else if (*(NewToken->pName) == '?')
797                                         NewToken->Flags = SV_CONDITIONAL;
798                                 else if (*(NewToken->pName) == '!')
799                                         NewToken->Flags = SV_NEG_CONDITIONAL;
800                         }
801                 }
802                 else pch ++;            
803         }
804         
805         switch (NewToken->Flags) {
806         case 0:
807                 /* If we're able to find out more about the token, do it now while its fresh. */
808                 if (GetHash(GlobalNS, NewToken->pName, NewToken->NameEnd, &vVar)) {
809                         HashHandler *Handler;
810                         Handler = (HashHandler*) vVar;
811                         if ((NewToken->nParameters < Handler->nMinArgs) || 
812                             (NewToken->nParameters > Handler->nMaxArgs)) {
813                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
814                                         "doesn't work with %ld params [%s]\n", 
815                                         NewToken->pName,
816                                         ChrPtr(pTmpl->FileName),
817                                         NewToken->Line,
818                                         NewToken->nParameters, 
819                                         ChrPtr(NewToken->FlatToken));
820                         }
821                         else {
822                                 NewToken->PreEval = Handler;
823                                 NewToken->Flags = SV_PREEVALUATED;              
824                         }
825                 }
826                 break;
827         case SV_GETTEXT:
828                 if (NewToken->nParameters !=1) {
829                         lprintf(1, "Gettext (in '%s' line %ld); "
830                                 "requires exactly 1 parameter, yau gave %ld params [%s]\n", 
831                                 ChrPtr(pTmpl->FileName),
832                                 NewToken->Line,
833                                 NewToken->nParameters, 
834                                 ChrPtr(NewToken->FlatToken));
835                         break;
836                 }
837                 break;
838         case SV_SUBTEMPL:
839                 if (NewToken->nParameters != 1) {
840                         lprintf(1, "Subtemplates (in '%s' line %ld); "
841                                 "require exactly 1 parameter, yau gave %ld params [%s]\n", 
842                                 ChrPtr(pTmpl->FileName),
843                                 NewToken->Line,
844                                 NewToken->nParameters, 
845                                 ChrPtr(NewToken->FlatToken));
846                         break;
847                 }
848                 break;
849         case SV_CUST_STR_CONDITIONAL:
850         case SV_CONDITIONAL:
851         case SV_NEG_CONDITIONAL:
852                 if (NewToken->nParameters <2) {
853                         lprintf(1, "Conditional (in '%s' line %ld); "
854                                 "require at least 2 parameters, yau gave %ld params [%s]\n", 
855                                 ChrPtr(pTmpl->FileName),
856                                 NewToken->Line,
857                                 NewToken->nParameters, 
858                                 ChrPtr(NewToken->FlatToken));
859                         break;
860                 }
861                 if (!GetHash(Conditionals, 
862                              NewToken->Params[0]->Start,
863                              NewToken->Params[0]->len,
864                              &vVar) || 
865                     (vVar == NULL)) {
866                         if ((NewToken->Params[0]->len == 1) &&
867                             (NewToken->Params[0]->Start[0] == 'X'))
868                                 break;
869                         lprintf(1, "Conditional [%s] (in '%s' line %ld); Not found![%s]\n", 
870                                 NewToken->Params[0]->Start,
871                                 ChrPtr(pTmpl->FileName),
872                                 NewToken->Line,
873                                 ChrPtr(NewToken->FlatToken));
874 /*
875                         NewToken->Error = NewStrBuf();
876                         StrBufAppendPrintf(
877                                 NewToken->Error, 
878                                 "<pre>\nConditional [%s] (in '%s' line %ld); Not found!\n[%s]\n</pre>\n", 
879                                 NewToken->Params[0]->Start,
880                                 ChrPtr(pTmpl->FileName),
881                                 NewToken->Line,
882                                 ChrPtr(NewToken->FlatToken));
883 */
884                 }
885                 else {
886                         NewToken->PreEval = vVar;
887                 }
888                 break;
889         }
890         return NewToken;
891 }
892
893
894
895 int EvaluateConditional(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int Neg, int state, int ContextType)
896 {
897         ConditionalStruct *Cond;
898
899         if ((Token->Params[0]->len == 1) &&
900             (Token->Params[0]->Start[0] == 'X'))
901                 return (state != 0)?Token->Params[1]->lvalue:0;
902             
903         Cond = (ConditionalStruct *) Token->PreEval;
904
905         if (Token->nParameters < Cond->nParams) {
906                 lprintf(1, "Conditional [%s] (in '%s' line %ld); needs %ld Params![%s]\n", 
907                         Token->Params[0]->Start,
908                         ChrPtr(pTmpl->FileName),
909                         Token->Line,
910                         Cond->nParams,
911                         ChrPtr(Token->FlatToken));
912                 StrBufAppendPrintf(
913                         Target, 
914                         "<pre>\nConditional [%s] (in '%s' line %ld); needs %ld Params!\n[%s]\n</pre>\n", 
915                         Token->Params[0]->Start,
916                         ChrPtr(pTmpl->FileName),
917                         Token->Line,
918                         Cond->nParams,
919                         ChrPtr(Token->FlatToken));
920                 return 0;
921         }
922         if (Cond->CondF(Token, Context, ContextType) == Neg)
923                 return Token->Params[1]->lvalue;
924         return 0;
925 }
926
927 /**
928  * \brief executes one token
929  * \param Target buffer to append to
930  * \param Token da to  process.
931  * \param Template we're iterating
932  * \param Context Contextpoointer to pass in
933  * \param state are we in conditional state?
934  * \param ContextType what type of information does context giv us?
935  */
936 int EvaluateToken(StrBuf *Target, WCTemplateToken *Token, WCTemplate *pTmpl, void *Context, int state, int ContextType)
937 {
938         HashHandler *Handler;
939         void *vVar;
940 // much output, since pName is not terminated...
941 //      lprintf(1,"Doing token: %s\n",Token->pName);
942
943         switch (Token->Flags) {
944         case SV_GETTEXT:
945                 TmplGettext(Target, Token->nParameters, Token);
946                 break;
947         case SV_CONDITIONAL: /** Forward conditional evaluation */
948                 return EvaluateConditional(Target, Token, pTmpl, Context, 1, state, ContextType);
949                 break;
950         case SV_NEG_CONDITIONAL: /** Reverse conditional evaluation */
951                 return EvaluateConditional(Target, Token, pTmpl, Context, 0, state, ContextType);
952                 break;
953         case SV_CUST_STR_CONDITIONAL: /** Conditional put custom strings from params */
954                 if (Token->nParameters >= 6) {
955                         if (EvaluateConditional(Target, Token, pTmpl, Context, 0, state, ContextType))
956                                 StrBufAppendBufPlain(Target, 
957                                                      Token->Params[5]->Start,
958                                                      Token->Params[5]->len,
959                                                      0);
960                         else
961                                 StrBufAppendBufPlain(Target, 
962                                                      Token->Params[4]->Start,
963                                                      Token->Params[4]->len,
964                                                      0);
965                 }
966                 break;
967         case SV_SUBTEMPL:
968                 if (Token->nParameters == 1)
969                         DoTemplate(Token->Params[0]->Start, Token->Params[0]->len, NULL, NULL, ContextType);
970                 break;
971         case SV_PREEVALUATED:
972                 Handler = (HashHandler*) Token->PreEval;
973                 if ((Handler->ContextRequired != CTX_NONE) &&
974                     (Handler->ContextRequired != ContextType)) {
975                         lprintf(1, "Handler [%s] (in '%s' line %ld); "
976                                 "requires context of type %ld, have %ld [%s]\n", 
977                                 Token->pName,
978                                 ChrPtr(pTmpl->FileName),
979                                 Token->Line,
980                                 Handler->ContextRequired, 
981                                 ContextType,
982                                 ChrPtr(Token->FlatToken));
983                         StrBufAppendPrintf(
984                                 Target, 
985                                 "<pre>\nHandler [%s] (in '%s' line %ld);"
986                                 " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
987                                 Token->pName,
988                                 ChrPtr(pTmpl->FileName),
989                                 Token->Line,
990                                 Handler->ContextRequired, 
991                                 ContextType,
992                                 ChrPtr(Token->FlatToken));
993                         return -1;
994
995                 }
996                 Handler->HandlerFunc(Target, 
997                                      Token->nParameters,
998                                      Token,
999                                      Context, 
1000                                      ContextType); 
1001                 break;          
1002         default:
1003                 if (GetHash(GlobalNS, Token->pName, Token->NameEnd, &vVar)) {
1004                         Handler = (HashHandler*) vVar;
1005                         if ((Handler->ContextRequired != CTX_NONE) &&
1006                             (Handler->ContextRequired != ContextType)) {
1007                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
1008                                         "requires context of type %ld, have %ld [%s]\n", 
1009                                         Token->pName,
1010                                         ChrPtr(pTmpl->FileName),
1011                                         Token->Line,
1012                                         Handler->ContextRequired, 
1013                                         ContextType,
1014                                         ChrPtr(Token->FlatToken));
1015                                 StrBufAppendPrintf(
1016                                         Target, 
1017                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
1018                                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1019                                         Token->pName,
1020                                         ChrPtr(pTmpl->FileName),
1021                                         Token->Line,
1022                                         Handler->ContextRequired, 
1023                                         ContextType,
1024                                         ChrPtr(Token->FlatToken));
1025                                 return -1;
1026                         }
1027                         else if ((Token->nParameters < Handler->nMinArgs) || 
1028                                  (Token->nParameters > Handler->nMaxArgs)) {
1029                                 lprintf(1, "Handler [%s] (in '%s' line %ld); "
1030                                         "doesn't work with %ld params [%s]\n", 
1031                                         Token->pName,
1032                                         ChrPtr(pTmpl->FileName),
1033                                         Token->Line,
1034                                         Token->nParameters, 
1035                                         ChrPtr(Token->FlatToken));
1036                                 StrBufAppendPrintf(
1037                                         Target, 
1038                                         "<pre>\nHandler [%s] (in '%s' line %ld);"
1039                                         " doesn't work with %ld params!\n[%s]\n</pre>\n", 
1040                                         Token->pName,
1041                                         ChrPtr(pTmpl->FileName),
1042                                         Token->Line,
1043                                         Token->nParameters,
1044                                         ChrPtr(Token->FlatToken));
1045                         }
1046                         else {
1047                                 Handler->HandlerFunc(Target, 
1048                                                      Token->nParameters,
1049                                                      Token,
1050                                                      Context, 
1051                                                      ContextType); /*TODO: subset of that */
1052                                 
1053                         }
1054                 }
1055                 else {
1056                         print_value_of(Target, Token, Context, ContextType);
1057                 }
1058         }
1059         return 0;
1060 }
1061
1062 void ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, void *Context, int ContextType)
1063 {
1064         WCTemplate *pTmpl = Tmpl;
1065         int done = 0;
1066         int i, state;
1067         const char *pData, *pS;
1068         long len;
1069
1070         if (LoadTemplates != 0) {                       
1071                 if (LoadTemplates > 1)
1072                         lprintf(1, "DBG: ----- loading:  [%s] ------ \n", 
1073                                 ChrPtr(Tmpl->FileName));
1074
1075                 pTmpl = load_template(Tmpl->FileName, NULL, NULL);
1076                 if(pTmpl == NULL) {
1077                         StrBufAppendPrintf(
1078                                 Target, 
1079                                 "<pre>\nError loading Template [%s]\n See Logfile for details\n</pre>\n", 
1080                                 ChrPtr(Tmpl->FileName));
1081                         return;
1082                 }
1083
1084         }
1085
1086         pS = pData = ChrPtr(pTmpl->Data);
1087         len = StrLength(pTmpl->Data);
1088         i = 0;
1089         state = 0;
1090         while (!done) {
1091                 if (i >= pTmpl->nTokensUsed) {
1092                         StrBufAppendBufPlain(Target, 
1093                                              pData, 
1094                                              len - (pData - pS), 0);
1095                         done = 1;
1096                 }
1097                 else {
1098                         StrBufAppendBufPlain(
1099                                 Target, pData, 
1100                                 pTmpl->Tokens[i]->pTokenStart - pData, 0);
1101                         state = EvaluateToken(Target, pTmpl->Tokens[i], pTmpl, Context, state, ContextType);
1102                         while ((state != 0) && (i+1 < pTmpl->nTokensUsed)) {
1103                         /* condition told us to skip till its end condition */
1104                                 i++;
1105                                 if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
1106                                     (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL)) {
1107                                         if (state == EvaluateConditional(
1108                                                     Target,
1109                                                     pTmpl->Tokens[i], 
1110                                                     pTmpl,
1111                                                     Context, 
1112                                                     pTmpl->Tokens[i]->Flags,
1113                                                     state, 
1114                                                     ContextType))
1115                                                 state = 0;
1116                                 }
1117                         }
1118                         pData = pTmpl->Tokens[i++]->pTokenEnd + 1;
1119                         if (i > pTmpl->nTokensUsed)
1120                                 done = 1;
1121                 }
1122         }
1123         if (LoadTemplates != 0) {
1124                 FreeWCTemplate(pTmpl);
1125         }
1126 }
1127
1128
1129 /**
1130  * \brief Display a variable-substituted template
1131  * \param templatename template file to load
1132  */
1133 void *prepare_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1134 {
1135         WCTemplate *NewTemplate;
1136         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1137         NewTemplate->Data = NULL;
1138         NewTemplate->FileName = NewStrBufDup(filename);
1139         NewTemplate->nTokensUsed = 0;
1140         NewTemplate->TokenSpace = 0;
1141         NewTemplate->Tokens = NULL;
1142
1143         Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1144         return NewTemplate;
1145 }
1146
1147 /**
1148  * \brief Display a variable-substituted template
1149  * \param templatename template file to load
1150  */
1151 void *load_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1152 {
1153         int fd;
1154         struct stat statbuf;
1155         const char *pS, *pE, *pch, *Err;
1156         long Line;
1157         int pos;
1158         WCTemplate *NewTemplate;
1159
1160         fd = open(ChrPtr(filename), O_RDONLY);
1161         if (fd <= 0) {
1162                 lprintf(1, "ERROR: could not open template '%s' - %s\n",
1163                         ChrPtr(filename), strerror(errno));
1164                 return NULL;
1165         }
1166
1167         if (fstat(fd, &statbuf) == -1) {
1168                 lprintf(1, "ERROR: could not stat template '%s' - %s\n",
1169                         ChrPtr(filename), strerror(errno));
1170                 return NULL;
1171         }
1172
1173         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1174         NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size);
1175         NewTemplate->FileName = NewStrBufDup(filename);
1176         NewTemplate->nTokensUsed = 0;
1177         NewTemplate->TokenSpace = 0;
1178         NewTemplate->Tokens = NULL;
1179         if (StrBufReadBLOB(NewTemplate->Data, &fd, 1, statbuf.st_size, &Err) < 0) {
1180                 close(fd);
1181                 FreeWCTemplate(NewTemplate);
1182                 lprintf(1, "ERROR: reading template '%s' - %s<br />\n",
1183                         ChrPtr(filename), strerror(errno));
1184                 return NULL;
1185         }
1186         close(fd);
1187
1188         Line = 0;
1189         pS = pch = ChrPtr(NewTemplate->Data);
1190         pE = pS + StrLength(NewTemplate->Data);
1191         while (pch < pE) {
1192                 const char *pts, *pte;
1193                 int InQuotes = 0;
1194                 int InDoubleQuotes = 0;
1195
1196                 /** Find one <? > */
1197                 pos = (-1);
1198                 for (; pch < pE; pch ++) {
1199                         if ((*pch=='<')&&(*(pch + 1)=='?'))
1200                                 break;
1201                         if (*pch=='\n') Line ++;
1202                 }
1203                 if (pch >= pE)
1204                         continue;
1205                 pts = pch;
1206
1207                 /** Found one? parse it. */
1208                 for (; pch < pE - 1; pch ++) {
1209                         if (*pch == '"')
1210                                 InDoubleQuotes = ! InDoubleQuotes;
1211                         else if (*pch == '\'')
1212                                 InQuotes = ! InQuotes;
1213                         else if ((!InQuotes  && !InDoubleQuotes) &&
1214                                  ((*pch!='\\')&&(*(pch + 1)=='>'))) {
1215                                 pch ++;
1216                                 break;
1217                         }
1218                 }
1219                 if (pch + 1 >= pE)
1220                         continue;
1221                 pte = pch;
1222                 PutNewToken(NewTemplate, 
1223                             NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate));
1224                 pch ++;
1225         }
1226         if (LoadTemplates == 0)
1227                 Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1228         return NewTemplate;
1229 }
1230
1231
1232 ///void PrintTemplate(const char *Key, void *vSubst, int odd)
1233 const char* PrintTemplate(void *vSubst)
1234 {
1235         WCTemplate *Tmpl = vSubst;
1236
1237         return ChrPtr(Tmpl->FileName);
1238
1239 }
1240
1241
1242 /**
1243  * \brief Display a variable-substituted template
1244  * \param templatename template file to load
1245  */
1246 void DoTemplate(const char *templatename, long len, StrBuf *Target, void *Context, int ContextType) 
1247 {
1248         HashList *Static;
1249         HashList *StaticLocal;
1250         void *vTmpl;
1251         
1252         if (Target == NULL)
1253                 Target = WC->WBuf;
1254         if (WC->is_mobile) {
1255                 Static = WirelessTemplateCache;
1256                 StaticLocal = WirelessLocalTemplateCache;
1257         }
1258         else {
1259                 Static = TemplateCache;
1260                 StaticLocal = LocalTemplateCache;
1261         }
1262
1263         if (len == 0)
1264         {
1265                 lprintf (1, "Can't to load a template with empty name!\n");
1266                 StrBufAppendPrintf(Target, "<pre>\nCan't to load a template with empty name!\n</pre>");
1267                 return;
1268         }
1269
1270         if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
1271             !GetHash(Static, templatename, len, &vTmpl)) {
1272                 lprintf (1, "didn't find Template [%s] %ld %ld\n", templatename, len , (long)strlen(templatename));
1273                 StrBufAppendPrintf(Target, "<pre>\ndidn't find Template [%s] %ld %ld\n</pre>", 
1274                                    templatename, len, 
1275                                    (long)strlen(templatename));
1276 ///             dbg_PrintHash(Static, PrintTemplate, NULL);
1277 //              PrintHash(Static, VarPrintTransition, PrintTemplate);
1278                 return;
1279         }
1280         if (vTmpl == NULL) 
1281                 return;
1282         ProcessTemplate(vTmpl, Target, Context, ContextType);
1283 }
1284
1285 int LoadTemplateDir(const char *DirName, HashList *wireless, HashList *big)
1286 {
1287         StrBuf *FileName;
1288         StrBuf *Tag;
1289         StrBuf *Dir;
1290         DIR *filedir = NULL;
1291         struct dirent *filedir_entry;
1292         int d_namelen;
1293         int d_without_ext;
1294         int IsMobile;
1295         
1296         Dir = NewStrBuf();
1297         StrBufPrintf(Dir, "%s/t", DirName);
1298         filedir = opendir (ChrPtr(Dir));
1299         if (filedir == NULL) {
1300                 FreeStrBuf(&Dir);
1301                 return 0;
1302         }
1303
1304         FileName = NewStrBuf();
1305         Tag = NewStrBuf();
1306         while ((filedir_entry = readdir(filedir)))
1307         {
1308                 char *MinorPtr;
1309                 char *PStart;
1310 #ifdef _DIRENT_HAVE_D_NAMELEN
1311                 d_namelen = filedir_entry->d_namelen;
1312 #else
1313                 d_namelen = strlen(filedir_entry->d_name);
1314 #endif
1315                 d_without_ext = d_namelen;
1316                 while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1317                         d_without_ext --;
1318                 if ((d_without_ext == 0) || (d_namelen < 3))
1319                         continue;
1320                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
1321                         continue; /* Ignore backup files... */
1322
1323                 IsMobile = (strstr(filedir_entry->d_name, ".m.html")!= NULL);
1324                 PStart = filedir_entry->d_name;
1325                 StrBufPrintf(FileName, "%s/%s", ChrPtr(Dir),  filedir_entry->d_name);
1326                 MinorPtr = strchr(filedir_entry->d_name, '.');
1327                 if (MinorPtr != NULL)
1328                         *MinorPtr = '\0';
1329                 StrBufPlain(Tag, filedir_entry->d_name, MinorPtr - filedir_entry->d_name);
1330
1331                 if (LoadTemplates > 1)
1332                         lprintf(1, "%s %d %s\n",ChrPtr(FileName), IsMobile, ChrPtr(Tag));
1333                 if (LoadTemplates == 0)
1334                         load_template(FileName, Tag, (IsMobile)?wireless:big);
1335                 else
1336                         prepare_template(FileName, Tag, (IsMobile)?wireless:big);
1337         }
1338         closedir(filedir);
1339         FreeStrBuf(&FileName);
1340         FreeStrBuf(&Tag);
1341         FreeStrBuf(&Dir);
1342         return 1;
1343 }
1344
1345 void InitTemplateCache(void)
1346 {
1347         LoadTemplateDir(static_dirs[0],
1348                         WirelessTemplateCache,
1349                         TemplateCache);
1350         LoadTemplateDir(static_dirs[1],
1351                         WirelessLocalTemplateCache,
1352                         LocalTemplateCache);
1353 }
1354
1355
1356
1357 typedef struct _HashIterator {
1358         HashList *StaticList;
1359         int AdditionalParams;
1360         int ContextType;
1361         int XPectContextType;
1362         RetrieveHashlistFunc GetHash;
1363         HashDestructorFunc Destructor;
1364         SubTemplFunc DoSubTemplate;
1365 } HashIterator;
1366
1367 void tmpl_iterate_subtmpl(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1368 {
1369         void *vIt;
1370         HashIterator *It;
1371         HashList *List;
1372         HashPos  *it;
1373         long len; 
1374         const char *Key;
1375         void *vContext;
1376         StrBuf *SubBuf;
1377         int oddeven = 0;
1378         
1379         if (!GetHash(Iterators, 
1380                      Tokens->Params[0]->Start,
1381                      Tokens->Params[0]->len,
1382                      &vIt)) {
1383                 lprintf(1, "unknown Iterator [%s] (in '%s' line %ld); "
1384                         " [%s]\n", 
1385                         Tokens->Params[0]->Start,
1386                         ChrPtr(Tokens->FileName),
1387                         Tokens->Line,
1388                         ChrPtr(Tokens->FlatToken));
1389                 StrBufAppendPrintf(
1390                         Target,
1391                         "<pre>\nunknown Iterator [%s] (in '%s' line %ld); \n"
1392                         " [%s]\n</pre>", 
1393                         Tokens->Params[0]->Start,
1394                         ChrPtr(Tokens->FileName),
1395                         Tokens->Line,
1396                         ChrPtr(Tokens->FlatToken));
1397                 return;
1398         }
1399
1400         It = (HashIterator*) vIt;
1401
1402         if (Tokens->nParameters < It->AdditionalParams + 2) {
1403                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1404                         "doesn't work with %ld params [%s]\n", 
1405                         Tokens->Params[0]->Start,
1406                         ChrPtr(Tokens->FileName),
1407                         Tokens->Line,
1408                         Tokens->nParameters, 
1409                         ChrPtr(Tokens->FlatToken));
1410                 StrBufAppendPrintf(
1411                         Target,
1412                         "<pre>Iterator [%s] \n(in '%s' line %ld);\n"
1413                         "doesn't work with %ld params \n[%s]\n</pre>", 
1414                         Tokens->Params[0]->Start,
1415                         ChrPtr(Tokens->FileName),
1416                         Tokens->Line,
1417                         Tokens->nParameters, 
1418                         ChrPtr(Tokens->FlatToken));
1419                 return;
1420         }
1421
1422         if ((It->XPectContextType != CTX_NONE) &&
1423             (It->XPectContextType != ContextType)) {
1424                 lprintf(1, "Iterator [%s] (in '%s' line %ld); "
1425                         "requires context of type %ld, have %ld [%s]\n", 
1426                         Tokens->pName,
1427                         ChrPtr(Tokens->FileName),
1428                         Tokens->Line,
1429                         It->XPectContextType, 
1430                         ContextType,
1431                         ChrPtr(Tokens->FlatToken));
1432                 StrBufAppendPrintf(
1433                         Target, 
1434                         "<pre>\nIterator [%s] (in '%s' line %ld);"
1435                         " requires context of type %ld, have %ld!\n[%s]\n</pre>\n", 
1436                         Tokens->pName,
1437                         ChrPtr(Tokens->FileName),
1438                         Tokens->Line,
1439                         It->XPectContextType, 
1440                         ContextType,
1441                         ChrPtr(Tokens->FlatToken));
1442                 return ;
1443                 
1444         }
1445
1446
1447
1448
1449         if (It->StaticList == NULL)
1450                 List = It->GetHash(Target, nArgs, Tokens, Context, ContextType);
1451         else
1452                 List = It->StaticList;
1453
1454         SubBuf = NewStrBuf();
1455         it = GetNewHashPos();
1456         while (GetNextHashPos(List, it, &len, &Key, &vContext)) {
1457                 svprintf(HKEY("ITERATE:ODDEVEN"), WCS_STRING, "%s", 
1458                          (oddeven) ? "odd" : "even");
1459                 svprintf(HKEY("ITERATE:KEY"), WCS_STRING, "%s", Key);
1460
1461                 if (It->DoSubTemplate != NULL)
1462                         It->DoSubTemplate(SubBuf, vContext, Tokens);
1463                 DoTemplate(Tokens->Params[1]->Start,
1464                            Tokens->Params[1]->len,
1465                            SubBuf, vContext,
1466                            It->ContextType);
1467                         
1468                 StrBufAppendBuf(Target, SubBuf, 0);
1469                 FlushStrBuf(SubBuf);
1470                 oddeven = ~ oddeven;
1471         }
1472         FreeStrBuf(&SubBuf);
1473         DeleteHashPos(&it);
1474         if (It->Destructor != NULL)
1475                 It->Destructor(&List);
1476 }
1477
1478 int ConditionalVar(WCTemplateToken *Tokens, void *Context, int ContextType)
1479 {
1480         void *vsubst;
1481         wcsubst *subst;
1482         
1483         if (!GetHash(WC->vars, 
1484                      Tokens->Params[2]->Start,
1485                      Tokens->Params[2]->len,
1486                      &vsubst))
1487                 return 0;
1488         subst = (wcsubst*) vsubst;
1489         if ((subst->ContextRequired != CTX_NONE) &&
1490             (subst->ContextRequired != ContextType)) {
1491                 lprintf(1,"  WARNING: Conditional requires Context: [%ld]!\n", Tokens->Params[2]->Start);
1492                 return -1;
1493         }
1494
1495         switch(subst->wcs_type) {
1496         case WCS_FUNCTION:
1497                 return (subst->wcs_function!=NULL);
1498         case WCS_SERVCMD:
1499                 lprintf(1, "  -> Server [%s]\n", subst->wcs_value);////todo
1500                 return 1;
1501         case WCS_STRING:
1502         case WCS_STRBUF:
1503         case WCS_STRBUF_REF:
1504                 if (Tokens->nParameters < 4)
1505                         return 1;
1506                 return (strcmp(Tokens->Params[3]->Start, ChrPtr(subst->wcs_value)) == 0);
1507         case WCS_LONG:
1508                 if (Tokens->nParameters < 4)
1509                         return (subst->lvalue != 0);
1510                 return (subst->lvalue == Tokens->Params[3]->lvalue);
1511         default:
1512                 lprintf(1,"  WARNING: invalid type: [%ld]!\n", subst->wcs_type);
1513                 return -1;
1514         }
1515         return 0;
1516 }
1517
1518 void RegisterITERATOR(const char *Name, long len, 
1519                       int AdditionalParams, 
1520                       HashList *StaticList, 
1521                       RetrieveHashlistFunc GetHash, 
1522                       SubTemplFunc DoSubTempl,
1523                       HashDestructorFunc Destructor,
1524                       int ContextType, 
1525                       int XPectContextType)
1526 {
1527         HashIterator *It = (HashIterator*)malloc(sizeof(HashIterator));
1528         It->StaticList = StaticList;
1529         It->AdditionalParams = AdditionalParams;
1530         It->GetHash = GetHash;
1531         It->DoSubTemplate = DoSubTempl;
1532         It->Destructor = Destructor;
1533         It->ContextType = ContextType;
1534         It->XPectContextType = XPectContextType;
1535         Put(Iterators, Name, len, It, NULL);
1536 }
1537
1538 void RegisterConditional(const char *Name, long len, 
1539                          int nParams,
1540                          WCConditionalFunc CondF, 
1541                          int ContextRequired)
1542 {
1543         ConditionalStruct *Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
1544         Cond->nParams = nParams;
1545         Cond->CondF = CondF;
1546         Cond->ContextRequired = ContextRequired;
1547         Put(Conditionals, Name, len, Cond, NULL);
1548 }
1549
1550 void tmpl_do_boxed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1551 {
1552         if (nArgs == 2) {
1553                 StrBuf *Headline = NewStrBuf();
1554                 DoTemplate(Tokens->Params[1]->Start, 
1555                            Tokens->Params[1]->len,
1556                            Headline, 
1557                            Context, 
1558                            ContextType);
1559                 SVPutBuf("BOXTITLE", Headline, 0);
1560         }
1561         
1562         DoTemplate(HKEY("beginbox"), Target, Context, ContextType);
1563         DoTemplate(Tokens->Params[0]->Start, 
1564                    Tokens->Params[0]->len,
1565                    Target, 
1566                    Context, 
1567                    ContextType);
1568         DoTemplate(HKEY("endbox"), Target, Context, ContextType);
1569 }
1570
1571 void tmpl_do_tabbed(StrBuf *Target, int nArgs, WCTemplateToken *Tokens, void *Context, int ContextType)
1572 {
1573         StrBuf **TabNames;
1574         int i, ntabs, nTabs;
1575
1576         nTabs = ntabs = Tokens->nParameters / 2;
1577         TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
1578
1579         for (i = 0; i < ntabs; i++) {
1580                 TabNames[i] = NewStrBuf();
1581                 if (Tokens->Params[i * 2]->len > 0) {
1582                         DoTemplate(Tokens->Params[i * 2]->Start, 
1583                                    Tokens->Params[i * 2]->len,
1584                                    TabNames[i],
1585                                    Context,
1586                                    ContextType);
1587                 }
1588                 else { 
1589                         /** A Tab without subject? we can't count that, add it as silent */
1590                         nTabs --;
1591                 }
1592         }
1593
1594         StrTabbedDialog(Target, nTabs, TabNames);
1595         for (i = 0; i < ntabs; i++) {
1596                 StrBeginTab(Target, i, nTabs);
1597
1598                 DoTemplate(Tokens->Params[i * 2 + 1]->Start, 
1599                            Tokens->Params[i * 2 + 1]->len,
1600                            Target,
1601                            Context, 
1602                            ContextType);
1603                 StrEndTab(Target, i, nTabs);
1604         }
1605 }
1606
1607 void 
1608 InitModule_SUBST
1609 (void)
1610 {
1611         RegisterNamespace("ITERATE", 2, 100, tmpl_iterate_subtmpl, CTX_NONE);
1612         RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed, CTX_NONE);
1613         RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed, CTX_NONE);
1614         RegisterConditional(HKEY("COND:SUBST"), 3, ConditionalVar, CTX_NONE);
1615 }
1616
1617 /*@}*/