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