validate_recipients() now strips out duplicate recipients ... probably some 15 years...
[citadel] / webcit / subst.c
1 #include "sysdep.h"
2
3
4 #include <sys/types.h>
5 #include <sys/stat.h>
6 #include <dirent.h>
7 #include <errno.h>
8
9 #include <unistd.h>
10 #include <stdio.h>
11 #include <stdarg.h>
12 #include <stddef.h>
13
14 #define SHOW_ME_VAPPEND_PRINTF
15
16 #include "webcit.h"
17 #include "webserver.h"
18
19 extern char *static_dirs[PATH_MAX];  /* Disk representation */
20
21 HashList *TemplateCache;
22 HashList *LocalTemplateCache;
23
24 HashList *GlobalNS;
25 HashList *Iterators;
26 HashList *Conditionals;
27 HashList *SortHash;
28 HashList *Defines;
29
30 int DumpTemplateI18NStrings = 0;
31 int LoadTemplates = 0;
32 int dbg_backtrace_template_errors = 0;
33 WCTemplputParams NoCtx;
34 StrBuf *I18nDump = NULL;
35
36 const char EmptyStr[]="";
37
38 #define SV_GETTEXT 1
39 #define SV_CONDITIONAL 2
40 #define SV_NEG_CONDITIONAL 3
41 #define SV_CUST_STR_CONDITIONAL 4
42 #define SV_SUBTEMPL 5
43 #define SV_PREEVALUATED 6
44
45
46
47 /*
48  * Dynamic content for variable substitution in templates
49  */
50 typedef struct _wcsubst {
51         ContextFilter Filter;
52         int wcs_type;                           /* which type of Substitution are we */
53         char wcs_key[32];                       /* copy of our hashkey for debugging */
54         StrBuf *wcs_value;                      /* if we're a string, keep it here */
55         long lvalue;                            /* type long? keep data here */
56         WCHandlerFunc wcs_function;             /* funcion hook ???*/
57 } wcsubst;
58
59
60 typedef struct _WCTemplate {
61         StrBuf *Data;
62         StrBuf *FileName;
63         int nTokensUsed;
64         int TokenSpace;
65         StrBuf *MimeType;
66         WCTemplateToken **Tokens;
67 } WCTemplate;
68
69 typedef struct _HashHandler {
70         ContextFilter Filter;
71         WCPreevalFunc PreEvalFunc;
72         WCHandlerFunc HandlerFunc;
73 }HashHandler;
74
75 typedef enum _estate {
76         eNext,
77         eSkipTilEnd
78 } TemplState;
79
80 void *load_template(StrBuf *Target, WCTemplate *NewTemplate);
81 int EvaluateConditional(StrBuf *Target, int Neg, int state, WCTemplputParams **TPP);
82
83
84
85 typedef struct _SortStruct {
86         StrBuf *Name;
87         StrBuf *PrefPrepend;
88         CompareFunc Forward;
89         CompareFunc Reverse;
90         CompareFunc GroupChange;
91
92         CtxType ContextType;
93 }SortStruct;
94
95 HashList *CtxList = NULL;
96
97 static CtxType CtxCounter = CTX_NONE;
98
99 CtxType CTX_STRBUF = CTX_NONE;
100 CtxType CTX_STRBUFARR = CTX_NONE;
101 CtxType CTX_LONGVECTOR = CTX_NONE;
102
103 CtxType CTX_ITERATE = CTX_NONE;
104 CtxType CTX_TAB = CTX_NONE;
105
106 void HFreeContextType(void *pCtx)
107 {
108         CtxTypeStruct *FreeStruct = (CtxTypeStruct *) pCtx;
109         FreeStrBuf(&FreeStruct->Name);
110         free(FreeStruct);
111 }
112 void PutContextType(const char *name, long len, CtxType TheCtx)
113 {
114         CtxTypeStruct *NewStruct;
115
116         NewStruct = (CtxTypeStruct*) malloc(sizeof(CtxTypeStruct));
117         NewStruct->Name = NewStrBufPlain(name, len);
118         NewStruct->Type = TheCtx;
119
120         Put(CtxList, IKEY(NewStruct->Type), NewStruct, HFreeContextType);
121 }
122 void RegisterContextType(const char *name, long len, CtxType *TheCtx)
123 {
124         if (*TheCtx != CTX_NONE)
125                 return;
126
127         *TheCtx = ++CtxCounter;
128         PutContextType(name, len, *TheCtx);
129 }
130
131 CtxTypeStruct *GetContextType(CtxType Type)
132 {
133         void *pv = NULL;
134         GetHash(CtxList, IKEY(Type), &pv);
135         return pv;
136 }
137
138 const char *UnknownContext = "CTX_UNKNOWN";
139
140 const char *ContextName(CtxType ContextType)
141 {
142         CtxTypeStruct *pCtx;
143
144         pCtx = GetContextType(ContextType);
145
146         if (pCtx != NULL) 
147                 return ChrPtr(pCtx->Name);
148         else
149                 return UnknownContext;
150 }
151
152 void StackDynamicContext(WCTemplputParams *Super, 
153                          WCTemplputParams *Sub, 
154                          void *Context,
155                          CtxType ContextType,
156                          int nArgs,
157                          WCTemplateToken *Tokens, 
158                          WCConditionalFunc ExitCtx, 
159                          long ExitCTXID)
160 {
161         memset(Sub, 0, sizeof(WCTemplputParams));
162
163         if (Super != NULL) {
164                 Sub->Sub = Super->Sub;
165                 Super->Sub = Sub;
166         }
167         if (Sub->Sub != NULL)
168                 Sub->Sub->Super = Sub;
169         Sub->Super = Super;
170         
171         Sub->Context = Context;
172         Sub->Filter.ContextType = ContextType;
173         Sub->nArgs = nArgs;
174         Sub->Tokens = Tokens;
175         Sub->ExitCtx = ExitCtx;
176         Sub->ExitCTXID = ExitCTXID;
177 }
178
179 void UnStackContext(WCTemplputParams *Sub)
180 {
181         if (Sub->Super != NULL)
182         {
183                 Sub->Super->Sub = Sub->Sub;
184         }
185         if (Sub->Sub != NULL)
186         {
187                 Sub->Sub->Super = Sub->Super;
188         }
189 }
190 void UnStackDynamicContext(StrBuf *Target, WCTemplputParams **TPP)
191 {
192         WCTemplputParams *TP = *TPP;
193         WCTemplputParams *Super = TP->Super;
194         TP->ExitCtx(Target, TP);
195         *TPP = Super;
196 }
197
198 void *GetContextPayload(WCTemplputParams *TP, CtxType ContextType)
199 {
200         WCTemplputParams *whichTP = TP;
201
202         if (ContextType == CTX_NONE)
203                 return TP->Context;
204
205         while ((whichTP != NULL) && (whichTP->Filter.ContextType != ContextType))
206                 whichTP = whichTP->Super;
207
208         return whichTP->Context;        
209 }
210
211 void DestroySortStruct(void *vSort)
212 {
213         SortStruct *Sort = (SortStruct*) vSort;
214         FreeStrBuf(&Sort->Name);
215         FreeStrBuf(&Sort->PrefPrepend);
216         free (Sort);
217 }
218
219
220 void LogTemplateError (StrBuf *Target, const char *Type, int ErrorPos, WCTemplputParams *TP, const char *Format, ...)
221 {
222         wcsession *WCC;
223         StrBuf *Error;
224         StrBuf *Info;
225         va_list arg_ptr;
226         const char *Err = NULL;
227
228         Info = NewStrBuf();
229         Error = NewStrBuf();
230
231         va_start(arg_ptr, Format);
232         StrBufVAppendPrintf(Error, Format, arg_ptr);
233         va_end(arg_ptr);
234
235         switch (ErrorPos) {
236         case ERR_NAME: /* the main token name... */ 
237                 Err = (TP->Tokens!= NULL)? TP->Tokens->pName:"";
238                 break;
239         default:
240                 Err = ((TP->Tokens!= NULL) && 
241                        (TP->Tokens->nParameters > ErrorPos - 1))? 
242                         TP->Tokens->Params[ErrorPos - 1]->Start : "";
243                 break;
244         }
245         if (TP->Tokens != NULL) 
246         {
247                 syslog(LOG_WARNING, "%s [%s]  (in '%s' line %ld); %s; [%s]\n", 
248                        Type, 
249                        Err, 
250                        ChrPtr(TP->Tokens->FileName),
251                        TP->Tokens->Line, 
252                        ChrPtr(Error), 
253                        ChrPtr(TP->Tokens->FlatToken));
254         }
255         else 
256         {
257                 syslog(LOG_WARNING, "%s: %s;\n", 
258                        Type, 
259                        ChrPtr(Error));
260         }
261         WCC = WC;
262         if (WCC == NULL) {
263                 FreeStrBuf(&Info);
264                 FreeStrBuf(&Error);
265                 return; 
266         }
267
268         if (WCC->WFBuf == NULL) WCC->WFBuf = NewStrBuf();
269         if (TP->Tokens != NULL) 
270         {
271                 /* deprecated: 
272                 StrBufAppendPrintf(                                                          
273                         Target,                                                              
274                         "<pre>\n%s [%s] (in '%s' line %ld); %s\n[%s]\n</pre>\n",
275                         Type, 
276                         Err, 
277                         ChrPtr(TP->Tokens->FileName),
278                         TP->Tokens->Line,
279                         ChrPtr(Error),
280                         ChrPtr(TP->Tokens->FlatToken));
281                 */
282                 StrBufPrintf(Info, "%s [%s]  %s; [%s]", 
283                              Type, 
284                              Err, 
285                              ChrPtr(Error), 
286                              ChrPtr(TP->Tokens->FlatToken));
287
288
289                 SerializeJson(WCC->WFBuf, WildFireException(SKEY(TP->Tokens->FileName),
290                                                         TP->Tokens->Line,
291                                                         Info,
292                                                         1), 1);
293 /*
294                 SerializeJson(Header, WildFireMessage(SKEY(TP->Tokens->FileName),
295                                                       TP->Tokens->Line,
296                                                       Error,
297                                                       eERROR), 1);
298 */
299                 
300         }
301         else
302         {
303                 /* deprecated.
304                 StrBufAppendPrintf(                                                          
305                         Target,                                                              
306                         "<pre>\n%s: %s\n</pre>\n",
307                         Type, 
308                         ChrPtr(Error));
309                 */
310                 StrBufPrintf(Info, "%s [%s]  %s; [%s]", 
311                              Type, 
312                              Err, 
313                              ChrPtr(Error), 
314                              ChrPtr(TP->Tokens->FlatToken));
315                 SerializeJson(WCC->WFBuf, WildFireException(HKEY(__FILE__), __LINE__, Info, 1), 1);
316         }
317         FreeStrBuf(&Info);
318         FreeStrBuf(&Error);
319 /*
320         if (dbg_backtrace_template_errors)
321                 wc_backtrace(LOG_DEBUG); 
322 */
323 }
324
325 void LogError (StrBuf *Target, const char *Type, const char *Format, ...)
326 {
327         wcsession *WCC;
328         StrBuf *Error;
329         StrBuf *Info;
330         va_list arg_ptr;
331
332         Info = NewStrBuf();
333         Error = NewStrBuf();
334
335         va_start(arg_ptr, Format);
336         StrBufVAppendPrintf(Error, Format, arg_ptr);
337         va_end(arg_ptr);
338
339         syslog(LOG_WARNING, "%s", ChrPtr(Error));
340
341         WCC = WC;
342         if (WCC->WFBuf == NULL) WCC->WFBuf = NewStrBuf();
343
344         SerializeJson(WCC->WFBuf, WildFireException(Type, strlen(Type),
345                                                     0,
346                                                     Info,
347                                                     1), 1);
348
349         FreeStrBuf(&Info);
350         FreeStrBuf(&Error);
351 /*
352         if (dbg_backtrace_template_errors)
353                 wc_backtrace(LOG_DEBUG); 
354 */
355 }
356
357
358 void RegisterNS(const char *NSName, 
359                 long len, 
360                 int nMinArgs, 
361                 int nMaxArgs, 
362                 WCHandlerFunc HandlerFunc, 
363                 WCPreevalFunc PreevalFunc,
364                 CtxType ContextRequired)
365 {
366         HashHandler *NewHandler;
367         
368         NewHandler = (HashHandler*) malloc(sizeof(HashHandler));
369         memset(NewHandler, 0, sizeof(HashHandler));
370         NewHandler->Filter.nMinArgs = nMinArgs;
371         NewHandler->Filter.nMaxArgs = nMaxArgs;
372         NewHandler->Filter.ContextType = ContextRequired;
373
374         NewHandler->PreEvalFunc = PreevalFunc;
375         NewHandler->HandlerFunc = HandlerFunc;  
376         Put(GlobalNS, NSName, len, NewHandler, NULL);
377 }
378
379
380
381 int CheckContext(StrBuf *Target, ContextFilter *Need, WCTemplputParams *TP, const char *ErrType)
382 {
383         WCTemplputParams *TPP = TP;
384         
385         if ((Need != NULL) &&
386             (Need->ContextType != CTX_NONE) && 
387             (Need->ContextType != TPP->Filter.ContextType)) {
388
389                 while ((TPP != NULL) && 
390                        (Need->ContextType != TPP->Filter.ContextType))
391                 {
392                         TPP = TPP->Super;
393                 }
394
395                 if (TPP != NULL)
396                         return 1;
397
398                 LogTemplateError(
399                         Target, ErrType, ERR_NAME, TP,
400                         "  WARNING: requires Context: [%s], have [%s]!", 
401                         ContextName(Need->ContextType), 
402                         ContextName(TP->Filter.ContextType));
403                 return 0;
404         }
405 /*                      
406         if (TP->Tokens->nParameters < Need->nMinArgs) {
407                 LogTemplateError(Target, ErrType, ERR_NAME, TP,
408                                  "needs at least %ld params, have %ld", 
409                                  Need->nMinArgs, 
410                                  TP->Tokens->nParameters);
411                 return 0;
412
413         }
414         else if (TP->Tokens->nParameters > Need->nMaxArgs) {
415                 LogTemplateError(Target, ErrType, ERR_NAME, TP,
416                                  "just needs %ld params, you gave %ld",
417                                  Need->nMaxArgs,
418                                  TP->Tokens->nParameters); 
419                 return 0;
420
421         }
422 */
423         return 1;
424 }
425
426 void FreeToken(WCTemplateToken **Token)
427 {
428         int i; 
429         FreeStrBuf(&(*Token)->FlatToken);
430         if ((*Token)->HaveParameters) 
431                 for (i = 0; i < (*Token)->nParameters; i++)
432                         free((*Token)->Params[i]);
433         free(*Token);
434         *Token = NULL;
435 }
436
437
438
439 void FreeWCTemplate(void *vFreeMe)
440 {
441         int i;
442         WCTemplate *FreeMe = (WCTemplate*)vFreeMe;
443
444         if (FreeMe->TokenSpace > 0) {
445                 for (i = 0; i < FreeMe->nTokensUsed; i ++) {
446                         FreeToken(&FreeMe->Tokens[i]);
447                 }
448                 free(FreeMe->Tokens);
449         }
450         FreeStrBuf(&FreeMe->FileName);
451         FreeStrBuf(&FreeMe->Data);
452         FreeStrBuf(&FreeMe->MimeType);
453         free(FreeMe);
454 }
455
456 int HaveTemplateTokenString(StrBuf *Target, 
457                             WCTemplputParams *TP,
458                             int N,
459                             const char **Value, 
460                             long *len)
461 {
462         if (N >= TP->Tokens->nParameters) {
463                 return 0;
464         }
465
466         switch (TP->Tokens->Params[N]->Type) {
467         case TYPE_INTDEFINE:
468         case TYPE_STR:
469         case TYPE_BSTR:
470         case TYPE_PREFSTR:
471         case TYPE_ROOMPREFSTR:
472         case TYPE_GETTEXT:
473         case TYPE_SUBTEMPLATE:
474                 return 1;
475         case TYPE_LONG:
476         case TYPE_PREFINT:
477         default:
478                 return 0;
479         }
480 }
481
482 void GetTemplateTokenString(StrBuf *Target, 
483                             WCTemplputParams *TP,
484                             int N,
485                             const char **Value, 
486                             long *len)
487 {
488         StrBuf *Buf;
489
490         if (N >= TP->Tokens->nParameters) {
491                 LogTemplateError(Target, 
492                                  "TokenParameter", N, TP, 
493                                  "invalid token %d. this shouldn't have come till here.\n", N);
494                 *Value = "";
495                 *len = 0;
496                 return;
497         }
498
499         switch (TP->Tokens->Params[N]->Type) {
500
501         case TYPE_INTDEFINE:
502         case TYPE_STR:
503                 *Value = TP->Tokens->Params[N]->Start;
504                 *len = TP->Tokens->Params[N]->len;
505                 break;
506         case TYPE_BSTR:
507                 if (TP->Tokens->Params[N]->len == 0) {
508                         LogTemplateError(Target, 
509                                          "TokenParameter", N, TP, 
510                                          "Requesting parameter %d; of type BSTR, empty lookup string not admitted.", N);
511                         *len = 0;
512                         *Value = EmptyStr;
513                         break;
514                 }
515                 Buf = (StrBuf*) SBstr(TKEY(N));
516                 *Value = ChrPtr(Buf);
517                 *len = StrLength(Buf);
518                 break;
519         case TYPE_PREFSTR:
520                 if (TP->Tokens->Params[N]->len == 0) {
521                         LogTemplateError(Target, 
522                                          "TokenParameter", N, TP, 
523                                          "Requesting parameter %d; of type PREFSTR, empty lookup string not admitted.", N);
524                         *len = 0;
525                         *Value = EmptyStr;
526                         break;
527                 }
528                 get_PREFERENCE(TKEY(N), &Buf);
529                 *Value = ChrPtr(Buf);
530                 *len = StrLength(Buf);
531                 break;
532         case TYPE_ROOMPREFSTR:
533                 if (TP->Tokens->Params[N]->len == 0) {
534                         LogTemplateError(Target, 
535                                          "TokenParameter", N, TP, 
536                                          "Requesting parameter %d; of type PREFSTR, empty lookup string not admitted.", N);
537                         *len = 0;
538                         *Value = EmptyStr;
539                         break;
540                 }
541                 Buf = get_ROOM_PREFS(TKEY(N));
542                 *Value = ChrPtr(Buf);
543                 *len = StrLength(Buf);
544                 break;
545         case TYPE_LONG:
546                 LogTemplateError(Target, 
547                                  "TokenParameter", N, TP, 
548                                  "Requesting parameter %d; of type LONG, want string.", N);
549                 break;
550         case TYPE_PREFINT:
551                 LogTemplateError(Target, 
552                                  "TokenParameter", N, TP, 
553                                  "Requesting parameter %d; of type PREFINT, want string.", N);
554                 break;
555         case TYPE_GETTEXT:
556                 *Value = _(TP->Tokens->Params[N]->Start);
557                 *len = strlen(*Value);
558                 break;
559         case TYPE_SUBTEMPLATE:
560                 if (TP->Tokens->Params[N]->len == 0) {
561                         LogTemplateError(Target, 
562                                          "TokenParameter", N, TP, 
563                                          "Requesting parameter %d; of type SUBTEMPLATE, empty lookup string not admitted.", N);
564                         *len = 0;
565                         *Value = EmptyStr;
566                         break;
567                 }
568
569                 Buf = NewStrBuf();
570                 DoTemplate(TKEY(N), Buf, TP);
571
572                 *Value = ChrPtr(Buf);
573                 *len = StrLength(Buf);
574                 /* we can't free it here, so we put it into the subst so its discarded later on. */
575                 PutRequestLocalMem(Buf, HFreeStrBuf);
576                 break;
577
578         default:
579                 LogTemplateError(Target, 
580                                  "TokenParameter", N, TP, 
581                                  "unknown param type %d; [%d]", N, TP->Tokens->Params[N]->Type);
582                 break;
583         }
584 }
585
586 long GetTemplateTokenNumber(StrBuf *Target, WCTemplputParams *TP, int N, long dflt)
587 {
588         long Ret;
589         if (N >= TP->Tokens->nParameters) {
590                 LogTemplateError(Target, 
591                                  "TokenParameter", N, TP, 
592                                  "invalid token %d. this shouldn't have come till here.\n", N);
593                 wc_backtrace(LOG_DEBUG); 
594                 return 0;
595         }
596
597         switch (TP->Tokens->Params[N]->Type) {
598
599         case TYPE_STR:
600                 return atol(TP->Tokens->Params[N]->Start);
601                 break;
602         case TYPE_BSTR:
603                 if (TP->Tokens->Params[N]->len == 0) {
604                         LogTemplateError(Target, 
605                                          "TokenParameter", N, TP, 
606                                          "Requesting parameter %d; of type BSTR, empty lookup string not admitted.", N);
607                         return 0;
608                 }
609                 return  LBstr(TKEY(N));
610                 break;
611         case TYPE_PREFSTR:
612                 LogTemplateError(Target, 
613                                  "TokenParameter", N, TP, 
614                                  "requesting a prefstring in param %d want a number", N);
615                 if (TP->Tokens->Params[N]->len == 0) {
616                         LogTemplateError(Target, 
617                                          "TokenParameter", N, TP, 
618                                          "Requesting parameter %d; of type PREFSTR, empty lookup string not admitted.", N);
619                         return 0;
620                 }
621                 if (get_PREF_LONG(TKEY(N), &Ret, dflt))
622                         return Ret;
623                 return 0;
624         case TYPE_ROOMPREFSTR:
625                 LogTemplateError(Target, 
626                                  "TokenParameter", N, TP, 
627                                  "requesting a prefstring in param %d want a number", N);
628                 if (TP->Tokens->Params[N]->len == 0) {
629                         LogTemplateError(Target, 
630                                          "TokenParameter", N, TP, 
631                                          "Requesting parameter %d; of type PREFSTR, empty lookup string not admitted.", N);
632                         return 0;
633                 }
634                 if (get_ROOM_PREFS_LONG(TKEY(N), &Ret, dflt))
635                         return Ret;
636                 return 0;
637         case TYPE_INTDEFINE:
638         case TYPE_LONG:
639                 return TP->Tokens->Params[N]->lvalue;
640         case TYPE_PREFINT:
641                 if (TP->Tokens->Params[N]->len == 0) {
642                         LogTemplateError(Target, 
643                                          "TokenParameter", N, TP, 
644                                          "Requesting parameter %d; of type PREFINT, empty lookup string not admitted.", N);
645                         return 0;
646                 }
647                 if (get_PREF_LONG(TKEY(N), &Ret, dflt))
648                         return Ret;
649                 return 0;               
650         case TYPE_GETTEXT:
651                 LogTemplateError(Target, 
652                                  "TokenParameter", N, TP, 
653                                  "requesting a I18N string in param %d; want a number", N);
654                 return 0;
655         case TYPE_SUBTEMPLATE:
656                 LogTemplateError(Target, 
657                                  "TokenParameter", N, TP, 
658                                  "requesting a subtemplate in param %d; not supported for numbers", N);
659                 return 0;
660         default:
661                 LogTemplateError(Target, 
662                                  "TokenParameter", N, TP, 
663                                  "unknown param type %d; [%d]", N, TP->Tokens->Params[N]->Type);
664                 return 0;
665         }
666 }
667
668
669 /*
670  * puts string into the template and computes which escape methon we should use
671  * Source = the string we should put into the template
672  * FormatTypeIndex = where should we look for escape types if?
673  */
674 void StrBufAppendTemplate(StrBuf *Target, 
675                           WCTemplputParams *TP,
676                           const StrBuf *Source, int FormatTypeIndex)
677 {
678         const char *pFmt = NULL;
679         char EscapeAs = ' ';
680
681         if ((FormatTypeIndex < TP->Tokens->nParameters) &&
682             (TP->Tokens->Params[FormatTypeIndex] != NULL) &&
683             (TP->Tokens->Params[FormatTypeIndex]->Type == TYPE_STR) &&
684             (TP->Tokens->Params[FormatTypeIndex]->len >= 1)) {
685                 pFmt = TP->Tokens->Params[FormatTypeIndex]->Start;
686                 EscapeAs = *pFmt;
687         }
688
689         switch(EscapeAs)
690         {
691         case 'H':
692                 StrEscAppend(Target, Source, NULL, 0, 2);
693                 break;
694         case 'X':
695                 StrEscAppend(Target, Source, NULL, 0, 0);
696                 break;
697         case 'J':
698                 StrECMAEscAppend(Target, Source, NULL);
699                 break;
700         case 'K':
701                 StrHtmlEcmaEscAppend(Target, Source, NULL, 0, 0);
702                 break;
703         case 'U':
704                 StrBufUrlescAppend(Target, Source, NULL);
705                 break;
706         case 'F':
707                 if (pFmt != NULL)       pFmt++;
708                 else                    pFmt = "JUSTIFY";
709                 if (*pFmt == '\0')      pFmt = "JUSTIFY";
710                 FmOut(Target, pFmt, Source);
711                 break;
712         default:
713                 StrBufAppendBuf(Target, Source, 0);
714         }
715 }
716
717 /*
718  * puts string into the template and computes which escape methon we should use
719  * Source = the string we should put into the template
720  * FormatTypeIndex = where should we look for escape types if?
721  */
722 void StrBufAppendTemplateStr(StrBuf *Target, 
723                              WCTemplputParams *TP,
724                              const char *Source, int FormatTypeIndex)
725 {
726         const char *pFmt = NULL;
727         char EscapeAs = ' ';
728
729         if ((FormatTypeIndex < TP->Tokens->nParameters) &&
730             (TP->Tokens->Params[FormatTypeIndex]->Type == TYPE_STR) &&
731             (TP->Tokens->Params[FormatTypeIndex]->len >= 1)) {
732                 pFmt = TP->Tokens->Params[FormatTypeIndex]->Start;
733                 EscapeAs = *pFmt;
734         }
735
736         switch(EscapeAs)
737         {
738         case 'H':
739                 StrEscAppend(Target, NULL, Source, 0, 2);
740                 break;
741         case 'X':
742                 StrEscAppend(Target, NULL, Source, 0, 0);
743                 break;
744         case 'J':
745                 StrECMAEscAppend(Target, NULL, Source);
746           break;
747         case 'K':
748                 StrHtmlEcmaEscAppend(Target, NULL, Source, 0, 0);
749           break;
750         case 'U':
751                 StrBufUrlescAppend(Target, NULL, Source);
752                 break;
753 /*
754         case 'F':
755                 if (pFmt != NULL)       pFmt++;
756                 else                    pFmt = "JUSTIFY";
757                 if (*pFmt == '\0')      pFmt = "JUSTIFY";
758                 FmOut(Target, pFmt, Source);
759                 break;
760 */
761         default:
762                 StrBufAppendBufPlain(Target, Source, -1, 0);
763         }
764 }
765
766
767 void PutNewToken(WCTemplate *Template, WCTemplateToken *NewToken)
768 {
769         if (Template->nTokensUsed + 1 >= Template->TokenSpace) {
770                 if (Template->TokenSpace <= 0) {
771                         Template->Tokens = (WCTemplateToken**)malloc(
772                                 sizeof(WCTemplateToken*) * 10);
773                         memset(Template->Tokens, 0, sizeof(WCTemplateToken*) * 10);
774                         Template->TokenSpace = 10;
775                 }
776                 else {
777                         WCTemplateToken **NewTokens;
778
779                         NewTokens= (WCTemplateToken**) malloc(
780                                 sizeof(WCTemplateToken*) * Template->TokenSpace * 2);
781
782                         memset(NewTokens, 
783                                0, sizeof(WCTemplateToken*) * Template->TokenSpace * 2);
784
785                         memcpy(NewTokens, 
786                                Template->Tokens, 
787                                sizeof(WCTemplateToken*) * Template->nTokensUsed);
788
789                         free(Template->Tokens);
790                         Template->TokenSpace *= 2;
791                         Template->Tokens = NewTokens;
792                 }
793         }
794         Template->Tokens[(Template->nTokensUsed)++] = NewToken;
795 }
796
797 int GetNextParameter(StrBuf *Buf, 
798                      const char **pCh, 
799                      const char *pe, 
800                      WCTemplateToken *Tokens, 
801                      WCTemplate *pTmpl, 
802                      WCTemplputParams *TP, 
803                      TemplateParam **pParm)
804 {
805         const char *pch = *pCh;
806         const char *pchs, *pche;
807         TemplateParam *Parm;
808         char quote = '\0';
809         int ParamBrace = 0;
810
811         *pParm = Parm = (TemplateParam *) malloc(sizeof(TemplateParam));
812         memset(Parm, 0, sizeof(TemplateParam));
813         Parm->Type = TYPE_STR;
814
815         /* Skip leading whitespaces */
816         while ((*pch == ' ' )||
817                (*pch == '\t')||
818                (*pch == '\r')||
819                (*pch == '\n')) pch ++;
820
821         if (*pch == ':') {
822                 Parm->Type = TYPE_PREFSTR;
823                 pch ++;
824                 if (*pch == '(') {
825                         pch ++;
826                         ParamBrace = 1;
827                 }
828         }
829         else if (*pch == '.') {
830                 Parm->Type = TYPE_ROOMPREFSTR;
831                 pch ++;
832                 if (*pch == '(') {
833                         pch ++;
834                         ParamBrace = 1;
835                 }
836         }
837         else if (*pch == ';') {
838                 Parm->Type = TYPE_PREFINT;
839                 pch ++;
840                 if (*pch == '(') {
841                         pch ++;
842                         ParamBrace = 1;
843                 }
844         }
845         else if (*pch == '#') {
846                 Parm->Type = TYPE_INTDEFINE;
847                 pch ++;
848         }
849         else if (*pch == '_') {
850                 Parm->Type = TYPE_GETTEXT;
851                 pch ++;
852                 if (*pch == '(') {
853                         pch ++;
854                         ParamBrace = 1;
855                 }
856         }
857         else if (*pch == 'B') {
858                 Parm->Type = TYPE_BSTR;
859                 pch ++;
860                 if (*pch == '(') {
861                         pch ++;
862                         ParamBrace = 1;
863                 }
864         }
865         else if (*pch == '=') {
866                 Parm->Type = TYPE_SUBTEMPLATE;
867                 pch ++;
868                 if (*pch == '(') {
869                         pch ++;
870                         ParamBrace = 1;
871                 }
872         }
873
874
875         if (*pch == '"')
876                 quote = '"';
877         else if (*pch == '\'')
878                 quote = '\'';
879         if (quote != '\0') {
880                 pch ++;
881                 pchs = pch;
882                 while (pch <= pe &&
883                        ((*pch != quote) ||
884                         ( (pch > pchs) && (*(pch - 1) == '\\'))
885                                )) {
886                         pch ++;
887                 }
888                 pche = pch;
889                 if (*pch != quote) {
890                         syslog(LOG_WARNING, "Error (in '%s' line %ld); "
891                                 "evaluating template param [%s] in Token [%s]\n",
892                                 ChrPtr(pTmpl->FileName),
893                                 Tokens->Line,
894                                 ChrPtr(Tokens->FlatToken),
895                                 *pCh);
896                         pch ++;
897                         free(Parm);
898                         *pParm = NULL;
899                         return 0;
900                 }
901                 else {
902                         StrBufPeek(Buf, pch, -1, '\0');         
903                         if (LoadTemplates > 1) {                        
904                                 syslog(LOG_DEBUG,
905                                         "DBG: got param [%s] "SIZE_T_FMT" "SIZE_T_FMT"\n", 
906                                         pchs, pche - pchs, strlen(pchs)
907                                 );
908                         }
909                         Parm->Start = pchs;
910                         Parm->len = pche - pchs;
911                         pch ++; /* move after trailing quote */
912                         if (ParamBrace && (*pch == ')')) {
913                                 pch ++;
914                         }
915
916                 }
917         }
918         else {
919                 Parm->Type = TYPE_LONG;
920                 pchs = pch;
921                 while ((pch <= pe) &&
922                        (isdigit(*pch) ||
923                         (*pch == '+') ||
924                         (*pch == '-')))
925                         pch ++;
926                 pch ++;
927                 if (pch - pchs > 1){
928                         StrBufPeek(Buf, pch, -1, '\0');
929                         Parm->lvalue = atol(pchs);
930                         Parm->Start = pchs;
931                         pch++;
932                 }
933                 else {
934                         Parm->lvalue = 0;
935 /* TODO whUT?
936                         syslog(LOG_DEBUG, "Error (in '%s' line %ld); "
937                                 "evaluating long template param [%s] in Token [%s]\n",
938                                 ChrPtr(pTmpl->FileName),
939                                 Tokens->Line,
940                                 ChrPtr(Tokens->FlatToken),
941                                 *pCh);
942                                 */
943                         free(Parm);
944                         *pParm = NULL;
945                         return 0;
946                 }
947         }
948         while ((*pch == ' ' )||
949                (*pch == '\t')||
950                (*pch == '\r')||
951                (*pch == ',' )||
952                (*pch == '\n')) pch ++;
953
954         switch (Parm->Type)
955         {
956         case TYPE_GETTEXT:
957                 if (DumpTemplateI18NStrings) {
958                         StrBufAppendPrintf(I18nDump, "_(\"%s\");\n", Parm->Start);
959                 }
960                 break;
961         case TYPE_INTDEFINE: {
962                 void *vPVal;
963                 
964                 if (GetHash(Defines, Parm->Start, Parm->len, &vPVal) &&
965                     (vPVal != NULL))
966                 {
967                         long *PVal;
968                         PVal = (long*) vPVal;
969                 
970                         Parm->lvalue = *PVal;
971                 }
972                 else if (strchr(Parm->Start, '|') != NULL)
973                 {
974                         const char *Pos;
975                         StrBuf *pToken;
976                         StrBuf *Match;
977
978                         Parm->MaskBy = eOR;
979                         pToken = NewStrBufPlain (Parm->Start, Parm->len);
980                         Match = NewStrBufPlain (NULL, Parm->len);
981                         Pos = ChrPtr(pToken);
982                         
983                         while ((Pos != NULL) && (Pos != StrBufNOTNULL))
984                         {
985                                 StrBufExtract_NextToken(Match, pToken, &Pos, '|');
986                                 StrBufTrim(Match);
987                                 if (StrLength (Match) > 0)
988                                 {
989                                         if (GetHash(Defines, SKEY(Match), &vPVal) &&
990                                             (vPVal != NULL))
991                                         {
992                                                 long *PVal;
993                                                 PVal = (long*) vPVal;
994                                                 
995                                                 Parm->lvalue |= *PVal;
996                                         }
997                                         else {
998                                                 LogTemplateError(NULL, "Define", 
999                                                                  Tokens->nParameters,
1000                                                                  TP,
1001                                                                  "%s isn't known!!",
1002                                                                  ChrPtr(Match));
1003
1004                                         }
1005                                 }
1006                         }
1007                         FreeStrBuf(&pToken);
1008                         FreeStrBuf(&Match);
1009                 }
1010                 else if (strchr(Parm->Start, '&') != NULL)
1011                 {
1012                         const char *Pos;
1013                         StrBuf *pToken;
1014                         StrBuf *Match;
1015
1016                         Parm->MaskBy = eAND;
1017                         pToken = NewStrBufPlain (Parm->Start, Parm->len);
1018                         Match = NewStrBufPlain (NULL, Parm->len);
1019                         Pos = ChrPtr(pToken);
1020                         
1021                         while ((Pos != NULL) && (Pos != StrBufNOTNULL))
1022                         {
1023                                 StrBufExtract_NextToken(Match, pToken, &Pos, '&');
1024                                 StrBufTrim(Match);
1025                                 if (StrLength (Match) > 0)
1026                                 {
1027                                         if (GetHash(Defines, SKEY(Match), &vPVal) &&
1028                                             (vPVal != NULL))
1029                                         {
1030                                                 long *PVal;
1031                                                 PVal = (long*) vPVal;
1032                                                 
1033                                                 Parm->lvalue |= *PVal;
1034                                         }
1035                                         else {
1036                                                 LogTemplateError(NULL, "Define", 
1037                                                                  Tokens->nParameters,
1038                                                                  TP,
1039                                                                  "%s isn't known!!",
1040                                                                  ChrPtr(Match));
1041
1042                                         }
1043                                 }
1044                         }
1045                         FreeStrBuf(&Match);
1046                         FreeStrBuf(&pToken);
1047                 }
1048                 else {
1049
1050
1051                         LogTemplateError(NULL, "Define", 
1052                                          Tokens->nParameters,
1053                                          TP,
1054                                          "%s isn't known!!",
1055                                          Parm->Start);
1056                 }}
1057                 break;
1058         case TYPE_SUBTEMPLATE:{
1059                 void *vTmpl;
1060                 /* well, we don't check the mobile stuff here... */
1061                 if (!GetHash(LocalTemplateCache, Parm->Start, Parm->len, &vTmpl) &&
1062                     !GetHash(TemplateCache, Parm->Start, Parm->len, &vTmpl)) {
1063                         LogTemplateError(NULL, 
1064                                          "SubTemplate", 
1065                                          Tokens->nParameters,
1066                                          TP,
1067                                          "referenced here doesn't exist");
1068                 }}
1069                 break;
1070         }
1071         *pCh = pch;
1072         return 1;
1073 }
1074
1075 WCTemplateToken *NewTemplateSubstitute(StrBuf *Buf, 
1076                                        const char *pStart, 
1077                                        const char *pTokenStart, 
1078                                        const char *pTokenEnd, 
1079                                        long Line,
1080                                        WCTemplate *pTmpl)
1081 {
1082         void *vVar;
1083         const char *pch;
1084         WCTemplateToken *NewToken;
1085         WCTemplputParams TP;
1086
1087         NewToken = (WCTemplateToken*)malloc(sizeof(WCTemplateToken));
1088         memset(NewToken, 0, sizeof(WCTemplateToken));
1089         TP.Tokens = NewToken;
1090         NewToken->FileName = pTmpl->FileName; /* to print meaningfull log messages... */
1091         NewToken->Flags = 0;
1092         NewToken->Line = Line + 1;
1093         NewToken->pTokenStart = pTokenStart;
1094         NewToken->TokenStart = pTokenStart - pStart;
1095         NewToken->TokenEnd =  (pTokenEnd - pStart) - NewToken->TokenStart;
1096         NewToken->pTokenEnd = pTokenEnd;
1097         NewToken->NameEnd = NewToken->TokenEnd - 2;
1098         NewToken->PreEval = NULL;
1099         NewToken->FlatToken = NewStrBufPlain(pTokenStart + 2, pTokenEnd - pTokenStart - 2);
1100         StrBufShrinkToFit(NewToken->FlatToken, 1);
1101
1102         StrBufPeek(Buf, pTokenStart, + 1, '\0');
1103         StrBufPeek(Buf, pTokenEnd, -1, '\0');
1104         pch = NewToken->pName = pTokenStart + 2;
1105
1106         NewToken->HaveParameters = 0;;
1107         NewToken->nParameters = 0;
1108
1109         while (pch < pTokenEnd - 1) {
1110                 if (*pch == '(') {
1111                         StrBufPeek(Buf, pch, -1, '\0');
1112                         NewToken->NameEnd = pch - NewToken->pName;
1113                         pch ++;
1114                         if (*(pTokenEnd - 1) != ')') {
1115                                 LogTemplateError(
1116                                         NULL, "Parseerror", ERR_NAME, &TP, 
1117                                         "Warning, Non welformed Token; missing right parenthesis");
1118                         }
1119                         while (pch < pTokenEnd - 1) {
1120                                 NewToken->nParameters++;
1121                                 if (GetNextParameter(Buf, 
1122                                                      &pch, 
1123                                                      pTokenEnd - 1, 
1124                                                      NewToken, 
1125                                                      pTmpl, 
1126                                                      &TP, 
1127                                                      &NewToken->Params[NewToken->nParameters - 1]))
1128                                 {
1129                                         NewToken->HaveParameters = 1;
1130                                         if (NewToken->nParameters >= MAXPARAM) {
1131                                                 LogTemplateError(
1132                                                         NULL, "Parseerror", ERR_NAME, &TP,
1133                                                         "only [%d] Params allowed in Tokens",
1134                                                         MAXPARAM);
1135
1136                                                 FreeToken(&NewToken);
1137                                                 return NULL;
1138                                         }
1139                                 }
1140                                 else break;
1141                         }
1142                         if((NewToken->NameEnd == 1) &&
1143                            (NewToken->HaveParameters == 1))
1144                            
1145                         {
1146                                 if (*(NewToken->pName) == '_')
1147                                         NewToken->Flags = SV_GETTEXT;
1148                                 else if (*(NewToken->pName) == '=')
1149                                         NewToken->Flags = SV_SUBTEMPL;
1150                                 else if (*(NewToken->pName) == '%')
1151                                         NewToken->Flags = SV_CUST_STR_CONDITIONAL;
1152                                 else if (*(NewToken->pName) == '?')
1153                                         NewToken->Flags = SV_CONDITIONAL;
1154                                 else if (*(NewToken->pName) == '!')
1155                                         NewToken->Flags = SV_NEG_CONDITIONAL;
1156                         }
1157                 }
1158                 else pch ++;            
1159         }
1160         
1161         switch (NewToken->Flags) {
1162         case 0:
1163                 /* If we're able to find out more about the token, do it now while its fresh. */
1164                 pch = NewToken->pName;
1165                 while (pch <  NewToken->pName + NewToken->NameEnd)
1166                 {
1167                         if (((*pch >= 'A') && (*pch <= 'Z')) || 
1168                             ((*pch >= '0') && (*pch <= '9')) ||
1169                             (*pch == ':') || 
1170                             (*pch == '-') ||
1171                             (*pch == '_')) 
1172                                 pch ++;
1173                         else
1174                         {
1175                                 LogTemplateError(
1176                                         NULL, "Token Name", ERR_NAME, &TP,
1177                                         "contains illegal char: '%c'", 
1178                                         *pch);
1179                                 pch++;
1180                         }
1181
1182                 }
1183                 if (GetHash(GlobalNS, NewToken->pName, NewToken->NameEnd, &vVar)) {
1184                         HashHandler *Handler;
1185                         Handler = (HashHandler*) vVar;
1186                         if ((NewToken->nParameters < Handler->Filter.nMinArgs) || 
1187                             (NewToken->nParameters > Handler->Filter.nMaxArgs)) {
1188                                 LogTemplateError(
1189                                         NULL, "Token", ERR_NAME, &TP,
1190                                         "doesn't work with %d params", 
1191                                         NewToken->nParameters);
1192
1193                         }
1194                         else {
1195                                 NewToken->PreEval = Handler;
1196                                 NewToken->Flags = SV_PREEVALUATED;              
1197                                 if (Handler->PreEvalFunc != NULL)
1198                                         Handler->PreEvalFunc(NewToken);
1199                         }
1200                 } else {
1201                         LogTemplateError(
1202                                 NULL, "Token ", ERR_NAME, &TP,
1203                                 " isn't known to us.");
1204                 }
1205                 break;
1206         case SV_GETTEXT:
1207                 if ((NewToken->nParameters < 1) || (NewToken->nParameters > 2)) {
1208                         LogTemplateError(                               
1209                                 NULL, "Gettext", ERR_NAME, &TP,
1210                                 "requires 1 or 2 parameter, you gave %d params", 
1211                                 NewToken->nParameters);
1212                         NewToken->Flags = 0;
1213                         break;
1214                 }
1215                 if (DumpTemplateI18NStrings) {
1216                         StrBufAppendPrintf(I18nDump, "_(\"%s\");\n", NewToken->Params[0]->Start);
1217                 }
1218                 break;
1219         case SV_SUBTEMPL:
1220                 if (NewToken->nParameters != 1) {
1221                         LogTemplateError(
1222                                 NULL, "Subtemplates", ERR_NAME, &TP,
1223                                 "require exactly 1 parameter, you gave %d params", 
1224                                 NewToken->nParameters);
1225                         break;
1226                 }
1227                 else {
1228                         void *vTmpl;
1229                         /* well, we don't check the mobile stuff here... */
1230                         if (!GetHash(LocalTemplateCache, 
1231                                      NewToken->Params[0]->Start, 
1232                                      NewToken->Params[0]->len, 
1233                                      &vTmpl) &&
1234                             !GetHash(TemplateCache, 
1235                                      NewToken->Params[0]->Start, 
1236                                      NewToken->Params[0]->len, 
1237                                      &vTmpl)) {
1238                                 LogTemplateError(
1239                                         NULL, "SubTemplate", ERR_PARM1, &TP,
1240                                         "doesn't exist");
1241                         }
1242                 }
1243                 break;
1244         case SV_CUST_STR_CONDITIONAL:
1245         case SV_CONDITIONAL:
1246         case SV_NEG_CONDITIONAL:
1247                 if (NewToken->nParameters <2) {
1248                         LogTemplateError(
1249                                 NULL, "Conditional", ERR_PARM1, &TP,
1250                                 "require at least 2 parameters, you gave %d params", 
1251                                 NewToken->nParameters);
1252                         NewToken->Flags = 0;
1253                         break;
1254                 }
1255                 if (NewToken->Params[1]->lvalue == 0) {
1256                         LogTemplateError(
1257                                 NULL, "Conditional", ERR_PARM1, &TP,
1258                                 "Conditional ID (Parameter 1) mustn't be 0!");
1259                         NewToken->Flags = 0;
1260                         break;
1261                 }
1262                 if (!GetHash(Conditionals, 
1263                              NewToken->Params[0]->Start, 
1264                              NewToken->Params[0]->len, 
1265                              &vVar) || 
1266                     (vVar == NULL)) {
1267                         if ((NewToken->Params[0]->len == 1) &&
1268                             (NewToken->Params[0]->Start[0] == 'X'))
1269                                 break;
1270                         LogTemplateError(
1271                                 NULL, "Conditional", ERR_PARM1, &TP,
1272                                 "Not found!");
1273 /*
1274                         NewToken->Error = NewStrBuf();
1275                         StrBufAppendPrintf(
1276                                 NewToken->Error, 
1277                                 "<pre>\nConditional [%s] (in '%s' line %ld); Not found!\n[%s]\n</pre>\n", 
1278                                 NewToken->Params[0]->Start,
1279                                 ChrPtr(pTmpl->FileName),
1280                                 NewToken->Line,
1281                                 ChrPtr(NewToken->FlatToken));
1282 */
1283                 }
1284                 else {
1285                         NewToken->PreEval = vVar;
1286                 }
1287                 break;
1288         }
1289         return NewToken;
1290 }
1291
1292
1293
1294
1295
1296 /**
1297  * \brief Display a variable-substituted template
1298  * \param templatename template file to load
1299  */
1300 void *prepare_template(StrBuf *filename, StrBuf *Key, HashList *PutThere)
1301 {
1302         WCTemplate *NewTemplate;
1303
1304         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1305         memset(NewTemplate, 0, sizeof(WCTemplate));
1306         NewTemplate->Data = NULL;
1307         NewTemplate->FileName = NewStrBufDup(filename);
1308         StrBufShrinkToFit(NewTemplate->FileName, 1);
1309         NewTemplate->nTokensUsed = 0;
1310         NewTemplate->TokenSpace = 0;
1311         NewTemplate->Tokens = NULL;
1312         NewTemplate->MimeType = NewStrBufPlain(GuessMimeByFilename (SKEY(NewTemplate->FileName)), -1);
1313         if (strstr(ChrPtr(NewTemplate->MimeType), "text") != NULL) {
1314                 StrBufAppendBufPlain(NewTemplate->MimeType, HKEY("; charset=utf-8"), 0);
1315         }
1316
1317         if (strstr(ChrPtr(NewTemplate->MimeType), "text") != NULL) {
1318                 StrBufAppendBufPlain(NewTemplate->MimeType, HKEY("; charset=utf-8"), 0);
1319         }
1320
1321         Put(PutThere, ChrPtr(Key), StrLength(Key), NewTemplate, FreeWCTemplate);
1322         return NewTemplate;
1323 }
1324
1325 /**
1326  * \brief Display a variable-substituted template
1327  * \param templatename template file to load
1328  */
1329 void *duplicate_template(WCTemplate *OldTemplate)
1330 {
1331         WCTemplate *NewTemplate;
1332
1333         NewTemplate = (WCTemplate *) malloc(sizeof(WCTemplate));
1334         memset(NewTemplate, 0, sizeof(WCTemplate));
1335         NewTemplate->Data = NULL;
1336         NewTemplate->FileName = NewStrBufDup(OldTemplate->FileName);
1337         StrBufShrinkToFit(NewTemplate->FileName, 1);
1338         NewTemplate->nTokensUsed = 0;
1339         NewTemplate->TokenSpace = 0;
1340         NewTemplate->Tokens = NULL;
1341         NewTemplate->MimeType = NewStrBufDup(OldTemplate->MimeType);
1342         return NewTemplate;
1343 }
1344
1345
1346 void SanityCheckTemplate(StrBuf *Target, WCTemplate *CheckMe)
1347 {
1348         int i = 0;
1349         int j;
1350         int FoundConditionalEnd;
1351
1352         for (i = 0; i < CheckMe->nTokensUsed; i++)
1353         {
1354                 switch(CheckMe->Tokens[i]->Flags)
1355                 {
1356                 case SV_CONDITIONAL:
1357                 case SV_NEG_CONDITIONAL:
1358                         FoundConditionalEnd = 0;
1359                         if ((CheckMe->Tokens[i]->Params[0]->len == 1) && 
1360                             (CheckMe->Tokens[i]->Params[0]->Start[0] == 'X'))
1361                                 break;
1362                         for (j = i + 1; j < CheckMe->nTokensUsed; j++)
1363                         {
1364                                 if (((CheckMe->Tokens[j]->Flags == SV_CONDITIONAL) ||
1365                                      (CheckMe->Tokens[j]->Flags == SV_NEG_CONDITIONAL)) && 
1366                                     (CheckMe->Tokens[i]->Params[1]->lvalue == 
1367                                      CheckMe->Tokens[j]->Params[1]->lvalue))
1368                                 {
1369                                         FoundConditionalEnd = 1;
1370                                         break;
1371                                 }
1372
1373                         }
1374                         if (!FoundConditionalEnd)
1375                         {
1376                                 WCTemplputParams TP;
1377                                 memset(&TP, 0, sizeof(WCTemplputParams));
1378                                 TP.Tokens = CheckMe->Tokens[i];
1379                                 LogTemplateError(
1380                                         Target, "Token", ERR_PARM1, &TP,
1381                                         "Conditional without Endconditional"
1382                                         );
1383                         }
1384                         break;
1385                 default:
1386                         break;
1387                 }
1388         }
1389 }
1390
1391 /**
1392  * \brief Display a variable-substituted template
1393  * \param templatename template file to load
1394  */
1395 void *load_template(StrBuf *Target, WCTemplate *NewTemplate)
1396 {
1397         int fd;
1398         struct stat statbuf;
1399         const char *pS, *pE, *pch, *Err;
1400         long Line;
1401
1402         fd = open(ChrPtr(NewTemplate->FileName), O_RDONLY);
1403         if (fd <= 0) {
1404                 syslog(LOG_WARNING, "ERROR: could not open template '%s' - %s\n",
1405                         ChrPtr(NewTemplate->FileName), strerror(errno));
1406                 return NULL;
1407         }
1408
1409         if (fstat(fd, &statbuf) == -1) {
1410                 syslog(LOG_WARNING, "ERROR: could not stat template '%s' - %s\n",
1411                         ChrPtr(NewTemplate->FileName), strerror(errno));
1412                 return NULL;
1413         }
1414
1415         NewTemplate->Data = NewStrBufPlain(NULL, statbuf.st_size + 1);
1416         if (StrBufReadBLOB(NewTemplate->Data, &fd, 1, statbuf.st_size, &Err) < 0) {
1417                 close(fd);
1418                 syslog(LOG_WARNING, "ERROR: reading template '%s' - %s<br>\n",
1419                         ChrPtr(NewTemplate->FileName), strerror(errno));
1420                 return NULL;
1421         }
1422         close(fd);
1423
1424         Line = 0;
1425         StrBufShrinkToFit(NewTemplate->Data, 1);
1426         StrBufShrinkToFit(NewTemplate->MimeType, 1);
1427         pS = pch = ChrPtr(NewTemplate->Data);
1428         pE = pS + StrLength(NewTemplate->Data);
1429         while (pch < pE) {
1430                 const char *pts, *pte;
1431                 char InQuotes = '\0';
1432                 void *pv;
1433
1434                 /** Find one <? > */
1435                 for (; pch < pE; pch ++) {
1436                         if ((*pch=='<')&&(*(pch + 1)=='?') &&
1437                             !((pch == pS) && /* we must ommit a <?xml */
1438                               (*(pch + 2) == 'x') && 
1439                               (*(pch + 3) == 'm') && 
1440                               (*(pch + 4) == 'l')))                          
1441                                 break;
1442                         if (*pch=='\n') Line ++;
1443                 }
1444                 if (pch >= pE)
1445                         continue;
1446                 pts = pch;
1447
1448                 /** Found one? parse it. */
1449                 for (; pch <= pE - 1; pch ++) {
1450                         if ((!InQuotes) &&
1451                             ((*pch == '\'') || (*pch == '"')))
1452                         {
1453                                 InQuotes = *pch;
1454                         }
1455                         else if (InQuotes && (InQuotes == *pch))
1456                         {
1457                                 InQuotes = '\0';
1458                         }
1459                         else if ((InQuotes) &&
1460                                  (*pch == '\\') &&
1461                                  (*(pch + 1) == InQuotes))
1462                         {
1463                                 pch++;
1464                         }
1465                         else if ((!InQuotes) && 
1466                                  (*pch == '>'))
1467                         {
1468                                 break;
1469                         }
1470                 }
1471                 if (pch + 1 > pE)
1472                         continue;
1473                 pte = pch;
1474                 pv = NewTemplateSubstitute(NewTemplate->Data, pS, pts, pte, Line, NewTemplate);
1475                 if (pv != NULL) {
1476                         PutNewToken(NewTemplate, pv);
1477                         pch ++;
1478                 }
1479         }
1480
1481         SanityCheckTemplate(NULL, NewTemplate);
1482         return NewTemplate;
1483 }
1484
1485
1486 const char* PrintTemplate(void *vSubst)
1487 {
1488         WCTemplate *Tmpl = vSubst;
1489
1490         return ChrPtr(Tmpl->FileName);
1491
1492 }
1493
1494 int LoadTemplateDir(const StrBuf *DirName, HashList *big, const StrBuf *BaseKey)
1495 {
1496         int Toplevel;
1497         StrBuf *FileName;
1498         StrBuf *Key;
1499         StrBuf *SubKey;
1500         StrBuf *SubDirectory;
1501         DIR *filedir = NULL;
1502         struct dirent *filedir_entry;
1503         struct dirent *d;
1504         int d_type = 0;
1505         int d_namelen;
1506         int d_without_ext;
1507         
1508         d = (struct dirent *)malloc(offsetof(struct dirent, d_name) + PATH_MAX + 1);
1509         if (d == NULL) {
1510                 return 0;
1511         }
1512
1513         filedir = opendir (ChrPtr(DirName));
1514         if (filedir == NULL) {
1515                 free(d);
1516                 return 0;
1517         }
1518
1519         Toplevel = StrLength(BaseKey) == 0;
1520         SubDirectory = NewStrBuf();
1521         SubKey = NewStrBuf();
1522         FileName = NewStrBufPlain(NULL, PATH_MAX);
1523         Key = NewStrBuf();
1524         while ((readdir_r(filedir, d, &filedir_entry) == 0) &&
1525                (filedir_entry != NULL))
1526         {
1527                 char *MinorPtr;
1528
1529 #ifdef _DIRENT_HAVE_D_NAMLEN
1530                 d_namelen = filedir_entry->d_namlen;
1531 #else
1532                 d_namelen = strlen(filedir_entry->d_name);
1533 #endif
1534
1535 #ifdef _DIRENT_HAVE_D_TYPE
1536                 d_type = filedir_entry->d_type;
1537 #else
1538
1539 #ifndef DT_UNKNOWN
1540 #define DT_UNKNOWN     0
1541 #define DT_DIR         4
1542 #define DT_REG         8
1543 #define DT_LNK         10
1544
1545 #define IFTODT(mode)   (((mode) & 0170000) >> 12)
1546 #define DTTOIF(dirtype)        ((dirtype) << 12)
1547 #endif
1548                 d_type = DT_UNKNOWN;
1549 #endif
1550                 d_without_ext = d_namelen;
1551
1552                 if ((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~')
1553                         continue; /* Ignore backup files... */
1554
1555                 if ((d_namelen == 1) && 
1556                     (filedir_entry->d_name[0] == '.'))
1557                         continue;
1558
1559                 if ((d_namelen == 2) && 
1560                     (filedir_entry->d_name[0] == '.') &&
1561                     (filedir_entry->d_name[1] == '.'))
1562                         continue;
1563
1564                 if (d_type == DT_UNKNOWN) {
1565                         struct stat s;
1566                         char path[PATH_MAX];
1567                         snprintf(path, PATH_MAX, "%s/%s", 
1568                                  ChrPtr(DirName), filedir_entry->d_name);
1569                         if (lstat(path, &s) == 0) {
1570                                 d_type = IFTODT(s.st_mode);
1571                         }
1572                 }
1573                 switch (d_type)
1574                 {
1575                 case DT_DIR:
1576                         /* Skip directories we are not interested in... */
1577                         if (strcmp(filedir_entry->d_name, ".svn") == 0)
1578                                 continue;
1579
1580                         FlushStrBuf(SubKey);
1581                         if (!Toplevel) {
1582                                 /* If we're not toplevel, the upper dirs count as foo_bar_<local name>*/
1583                                 StrBufAppendBuf(SubKey, BaseKey, 0);
1584                                 StrBufAppendBufPlain(SubKey, HKEY("_"), 0);
1585                         }
1586                         StrBufAppendBufPlain(SubKey, filedir_entry->d_name, d_namelen, 0);
1587
1588                         FlushStrBuf(SubDirectory);
1589                         StrBufAppendBuf(SubDirectory, DirName, 0);
1590                         if (ChrPtr(SubDirectory)[StrLength(SubDirectory) - 1] != '/')
1591                                 StrBufAppendBufPlain(SubDirectory, HKEY("/"), 0);
1592                         StrBufAppendBufPlain(SubDirectory, filedir_entry->d_name, d_namelen, 0);
1593
1594                         LoadTemplateDir(SubDirectory, big, SubKey);
1595
1596                         break;
1597                 case DT_LNK: 
1598                 case DT_REG:
1599
1600
1601                         while ((d_without_ext > 0) && (filedir_entry->d_name[d_without_ext] != '.'))
1602                                 d_without_ext --;
1603                         if ((d_without_ext == 0) || (d_namelen < 3))
1604                                 continue;
1605                         if (((d_namelen > 1) && filedir_entry->d_name[d_namelen - 1] == '~') ||
1606                             (strcmp(&filedir_entry->d_name[d_without_ext], ".orig") == 0) ||
1607                             (strcmp(&filedir_entry->d_name[d_without_ext], ".swp") == 0))
1608                                 continue; /* Ignore backup files... */
1609                         StrBufPrintf(FileName, "%s/%s", ChrPtr(DirName),  filedir_entry->d_name);
1610                         MinorPtr = strchr(filedir_entry->d_name, '.');
1611                         if (MinorPtr != NULL)
1612                                 *MinorPtr = '\0';
1613                         FlushStrBuf(Key);
1614                         if (!Toplevel) {
1615                                 /* If we're not toplevel, the upper dirs count as foo_bar_<local name>*/
1616                                 StrBufAppendBuf(Key, BaseKey, 0);
1617                                 StrBufAppendBufPlain(Key, HKEY("_"), 0);
1618                         }
1619                         StrBufAppendBufPlain(Key, filedir_entry->d_name, MinorPtr - filedir_entry->d_name, 0);
1620
1621                         if (LoadTemplates >= 1)
1622                                 syslog(LOG_DEBUG, "%s %s\n", ChrPtr(FileName), ChrPtr(Key));
1623                         prepare_template(FileName, Key, big);
1624                 default:
1625                         break;
1626                 }
1627         }
1628         free(d);
1629         closedir(filedir);
1630         FreeStrBuf(&FileName);
1631         FreeStrBuf(&Key);
1632         FreeStrBuf(&SubDirectory);
1633         FreeStrBuf(&SubKey);
1634         return 1;
1635 }
1636
1637 void InitTemplateCache(void)
1638 {
1639         int i;
1640         StrBuf *Key;
1641         StrBuf *Dir;
1642         HashList *Templates[2];
1643
1644         Dir = NewStrBuf();
1645         Key = NewStrBuf();
1646
1647         /* Primary Template set... */
1648         StrBufPrintf(Dir, "%s/t", static_dirs[0]);
1649         LoadTemplateDir(Dir,
1650                         TemplateCache, 
1651                         Key);
1652
1653         /* User local Template set */
1654         StrBufPrintf(Dir, "%s/t", static_dirs[1]);
1655         LoadTemplateDir(Dir,
1656                         LocalTemplateCache, 
1657                         Key);
1658         
1659         /* Debug Templates, just to be loaded while debugging. */
1660         
1661         StrBufPrintf(Dir, "%s/dbg", static_dirs[0]);
1662         LoadTemplateDir(Dir,
1663                         TemplateCache, 
1664                         Key);
1665         Templates[0] = TemplateCache;
1666         Templates[1] = LocalTemplateCache;
1667
1668
1669         if (LoadTemplates == 0) 
1670                 for (i=0; i < 2; i++) {
1671                         const char *Key;
1672                         long KLen;
1673                         HashPos *At;
1674                         void *vTemplate;
1675
1676                         At = GetNewHashPos(Templates[i], 0);
1677                         while (GetNextHashPos(Templates[i], 
1678                                               At, 
1679                                               &KLen,
1680                                               &Key, 
1681                                               &vTemplate) && 
1682                                (vTemplate != NULL))
1683                         {
1684                                 load_template(NULL, (WCTemplate *)vTemplate);
1685                         }
1686                         DeleteHashPos(&At);
1687                 }
1688
1689
1690         FreeStrBuf(&Dir);
1691         FreeStrBuf(&Key);
1692 }
1693
1694
1695
1696 /*-----------------------------------------------------------------------------
1697  *                      Filling & processing Templates
1698  */
1699 /**
1700  * \brief executes one token
1701  * \param Target buffer to append to
1702  * \param Token da to  process.
1703  * \param Template we're iterating
1704  * \param Context Contextpoointer to pass in
1705  * \param state are we in conditional state?
1706  * \param ContextType what type of information does context giv us?
1707  */
1708 int EvaluateToken(StrBuf *Target, int state, WCTemplputParams **TPP)
1709 {
1710         const char *AppendMe;
1711         long AppendMeLen;
1712         HashHandler *Handler;
1713         void *vVar;
1714         WCTemplputParams *TP = *TPP;
1715         
1716 /* much output, since pName is not terminated...
1717         syslog(LOG_DEBUG,"Doing token: %s\n",Token->pName);
1718 */
1719
1720         switch (TP->Tokens->Flags) {
1721         case SV_GETTEXT:
1722                 TmplGettext(Target, TP);
1723                 break;
1724         case SV_CONDITIONAL: /** Forward conditional evaluation */
1725                 Handler = (HashHandler*) TP->Tokens->PreEval;
1726                 if (!CheckContext(Target, &Handler->Filter, TP, "Conditional")) {
1727                         return 0;
1728                 }
1729                 return EvaluateConditional(Target, 1, state, TPP);
1730                 break;
1731         case SV_NEG_CONDITIONAL: /** Reverse conditional evaluation */
1732                 Handler = (HashHandler*) TP->Tokens->PreEval;
1733                 if (!CheckContext(Target, &Handler->Filter, TP, "Conditional")) {
1734                         return 0;
1735                 }
1736                 return EvaluateConditional(Target, 0, state, TPP);
1737                 break;
1738         case SV_CUST_STR_CONDITIONAL: /** Conditional put custom strings from params */
1739                 Handler = (HashHandler*) TP->Tokens->PreEval;
1740                 if (!CheckContext(Target, &Handler->Filter, TP, "Conditional")) {
1741                         return 0;
1742                 }
1743                 if (TP->Tokens->nParameters >= 6) {
1744                         if (EvaluateConditional(Target, 0, state, TPP)) {
1745                                 GetTemplateTokenString(Target, TP, 5, &AppendMe, &AppendMeLen);
1746                                 StrBufAppendBufPlain(Target, 
1747                                                      AppendMe, 
1748                                                      AppendMeLen,
1749                                                      0);
1750                         }
1751                         else{
1752                                 GetTemplateTokenString(Target, TP, 4, &AppendMe, &AppendMeLen);
1753                                 StrBufAppendBufPlain(Target, 
1754                                                      AppendMe, 
1755                                                      AppendMeLen,
1756                                                      0);
1757                         }
1758                         if (*TPP != TP)
1759                         {
1760                                 UnStackDynamicContext(Target, TPP);
1761                         }
1762                 }
1763                 else  {
1764                         LogTemplateError(
1765                                 Target, "Conditional", ERR_NAME, TP,
1766                                 "needs at least 6 Params!"); 
1767                 }
1768                 break;
1769         case SV_SUBTEMPL:
1770                 if (TP->Tokens->nParameters == 1)
1771                         DoTemplate(TKEY(0), Target, TP);
1772                 break;
1773         case SV_PREEVALUATED:
1774                 Handler = (HashHandler*) TP->Tokens->PreEval;
1775                 if (!CheckContext(Target, &Handler->Filter, TP, "Token")) {
1776                         return 0;
1777                 }
1778                 Handler->HandlerFunc(Target, TP);
1779                 break;          
1780         default:
1781                 if (GetHash(GlobalNS, TP->Tokens->pName, TP->Tokens->NameEnd, &vVar)) {
1782                         Handler = (HashHandler*) vVar;
1783                         if (!CheckContext(Target, &Handler->Filter, TP, "Token")) {
1784                                 return 0;
1785                         }
1786                         else {
1787                                 Handler->HandlerFunc(Target, TP);
1788                         }
1789                 }
1790                 else {
1791                         LogTemplateError(
1792                                 Target, "Token UNKNOWN", ERR_NAME, TP,
1793                                 "You've specified a token that isn't known to webcit.!");
1794                 }
1795         }
1796         return 0;
1797 }
1798
1799
1800
1801 const StrBuf *ProcessTemplate(WCTemplate *Tmpl, StrBuf *Target, WCTemplputParams *CallingTP)
1802 {
1803         WCTemplate *pTmpl = Tmpl;
1804         int done = 0;
1805         int i;
1806         TemplState state;
1807         const char *pData, *pS;
1808         long len;
1809         WCTemplputParams TP;
1810         WCTemplputParams *TPtr = &TP;
1811
1812         memset(TPtr, 0, sizeof(WCTemplputParams));
1813
1814         memcpy(&TP.Filter, &CallingTP->Filter, sizeof(ContextFilter));
1815
1816         TP.Context = CallingTP->Context;
1817         TP.Sub = CallingTP->Sub;
1818         TP.Super = CallingTP->Super;
1819
1820         if (LoadTemplates != 0) {                       
1821                 if (LoadTemplates > 1)
1822                         syslog(LOG_DEBUG, "DBG: ----- loading:  [%s] ------ \n", 
1823                                 ChrPtr(Tmpl->FileName));
1824                 pTmpl = duplicate_template(Tmpl);
1825                 if(load_template(Target, pTmpl) == NULL) {
1826                         StrBufAppendPrintf(
1827                                 Target, 
1828                                 "<pre>\nError loading Template [%s]\n See Logfile for details\n</pre>\n", 
1829                                 ChrPtr(Tmpl->FileName));
1830                         FreeWCTemplate(pTmpl);
1831                         return NULL;
1832                 }
1833
1834         }
1835
1836         pS = pData = ChrPtr(pTmpl->Data);
1837         len = StrLength(pTmpl->Data);
1838         i = 0;
1839         state = eNext;
1840         while (!done) {
1841                 if (i >= pTmpl->nTokensUsed) {
1842                         StrBufAppendBufPlain(Target, 
1843                                              pData, 
1844                                              len - (pData - pS), 0);
1845                         done = 1;
1846                 }
1847                 else {
1848                         int TokenRc = 0;
1849
1850                         StrBufAppendBufPlain(
1851                                 Target, pData, 
1852                                 pTmpl->Tokens[i]->pTokenStart - pData, 0);
1853                         TPtr->Tokens = pTmpl->Tokens[i];
1854                         TPtr->nArgs = pTmpl->Tokens[i]->nParameters;
1855
1856                         TokenRc = EvaluateToken(Target, TokenRc, &TPtr);
1857                         if (TokenRc > 0)
1858                         {
1859                                 state = eSkipTilEnd;
1860                         }
1861                         else if (TokenRc < 0)
1862                         {
1863                                 if ((TPtr != &TP) &&
1864                                     (TPtr->ExitCTXID == -TokenRc))
1865                                 {
1866                                         UnStackDynamicContext(Target, &TPtr);
1867                                 }
1868                                 TokenRc = 0;
1869                         }
1870
1871                         while ((state != eNext) && (i+1 < pTmpl->nTokensUsed)) {
1872                         /* condition told us to skip till its end condition */
1873                                 i++;
1874                                 TPtr->Tokens = pTmpl->Tokens[i];
1875                                 TPtr->nArgs = pTmpl->Tokens[i]->nParameters;
1876                                 if ((pTmpl->Tokens[i]->Flags == SV_CONDITIONAL) ||
1877                                     (pTmpl->Tokens[i]->Flags == SV_NEG_CONDITIONAL))
1878                                 {
1879                                         int rc;
1880                                         rc = EvaluateConditional(
1881                                                 Target, 
1882                                                 pTmpl->Tokens[i]->Flags, 
1883                                                 TokenRc, 
1884                                                 &TPtr);
1885                                         if (-rc == TokenRc)
1886                                         {
1887                                                 TokenRc = 0;
1888                                                 state = eNext;
1889                                                 if ((TPtr != &TP) &&
1890                                                     (TPtr->ExitCTXID == - rc))
1891                                                 {
1892                                                         UnStackDynamicContext(Target, &TPtr);
1893                                                 }
1894                                         }
1895                                 }
1896                         }
1897
1898                         pData = pTmpl->Tokens[i++]->pTokenEnd + 1;
1899                         if (i > pTmpl->nTokensUsed)
1900                                 done = 1;
1901                 }
1902         }
1903         if (LoadTemplates != 0) {
1904                 FreeWCTemplate(pTmpl);
1905         }
1906         return Tmpl->MimeType;
1907
1908 }
1909
1910
1911 StrBuf *textPlainType;
1912 /**
1913  * \brief Display a variable-substituted template
1914  * \param templatename template file to load
1915  * \returns the mimetype of the template its doing
1916  */
1917 const StrBuf *DoTemplate(const char *templatename, long len, StrBuf *Target, WCTemplputParams *TP) 
1918 {
1919         WCTemplputParams LocalTP;
1920         HashList *Static;
1921         HashList *StaticLocal;
1922         void *vTmpl;
1923         
1924         if (Target == NULL)
1925                 Target = WC->WBuf;
1926         if (TP == NULL) {
1927                 memset(&LocalTP, 0, sizeof(WCTemplputParams));
1928                 TP = &LocalTP;
1929         }
1930
1931         Static = TemplateCache;
1932         StaticLocal = LocalTemplateCache;
1933
1934         if (len == 0)
1935         {
1936                 syslog(LOG_WARNING, "Can't to load a template with empty name!\n");
1937                 StrBufAppendPrintf(Target, "<pre>\nCan't to load a template with empty name!\n</pre>");
1938                 return textPlainType;
1939         }
1940
1941         if (!GetHash(StaticLocal, templatename, len, &vTmpl) &&
1942             !GetHash(Static, templatename, len, &vTmpl)) {
1943                 StrBuf *escapedString = NewStrBufPlain(NULL, len);
1944                 
1945                 StrHtmlEcmaEscAppend(escapedString, NULL, templatename, 1, 1);
1946                 syslog(LOG_WARNING, "didn't find Template [%s] %ld %ld\n", ChrPtr(escapedString), len , (long)strlen(templatename));
1947                 StrBufAppendPrintf(Target, "<pre>\ndidn't find Template [%s] %ld %ld\n</pre>", 
1948                                    ChrPtr(escapedString), len, 
1949                                    (long)strlen(templatename));
1950                 WC->isFailure = 1;
1951 #if 0
1952                 dbg_PrintHash(Static, PrintTemplate, NULL);
1953                 PrintHash(Static, VarPrintTransition, PrintTemplate);
1954 #endif
1955                 FreeStrBuf(&escapedString);
1956                 return textPlainType;
1957         }
1958         if (vTmpl == NULL) 
1959                 return textPlainType;
1960         return ProcessTemplate(vTmpl, Target, TP);
1961
1962 }
1963
1964
1965 void tmplput_Comment(StrBuf *Target, WCTemplputParams *TP)
1966 {
1967         if (LoadTemplates != 0)
1968         {
1969                 StrBuf *Comment;
1970                 const char *pch;
1971                 long len;
1972
1973                 GetTemplateTokenString(Target, TP, 0, &pch, &len);
1974                 Comment = NewStrBufPlain(pch, len);
1975                 StrBufAppendBufPlain(Target, HKEY("<!--"), 0);
1976                 StrBufAppendTemplate(Target, TP, Comment, 1);
1977                 StrBufAppendBufPlain(Target, HKEY("-->"), 0);
1978                 FreeStrBuf(&Comment);
1979         }
1980 }
1981
1982 /*-----------------------------------------------------------------------------
1983  *                      Iterators
1984  */
1985 typedef struct _HashIterator {
1986         HashList *StaticList;
1987         int AdditionalParams;
1988         CtxType ContextType;
1989         CtxType XPectContextType;
1990         int Flags;
1991         RetrieveHashlistFunc GetHash;
1992         HashDestructorFunc Destructor;
1993         SubTemplFunc DoSubTemplate;
1994         FilterByParamFunc Filter;
1995 } HashIterator;
1996
1997 void RegisterITERATOR(const char *Name, long len, 
1998                       int AdditionalParams, 
1999                       HashList *StaticList, 
2000                       RetrieveHashlistFunc GetHash, 
2001                       SubTemplFunc DoSubTempl,
2002                       HashDestructorFunc Destructor,
2003                       FilterByParamFunc Filter,
2004                       CtxType ContextType, 
2005                       CtxType XPectContextType, 
2006                       int Flags)
2007 {
2008         HashIterator *It;
2009
2010         It = (HashIterator*)malloc(sizeof(HashIterator));
2011         memset(It, 0, sizeof(HashIterator));
2012         It->StaticList = StaticList;
2013         It->AdditionalParams = AdditionalParams;
2014         It->GetHash = GetHash;
2015         It->DoSubTemplate = DoSubTempl;
2016         It->Destructor = Destructor;
2017         It->Filter = Filter;
2018         It->ContextType = ContextType;
2019         It->XPectContextType = XPectContextType;
2020         It->Flags = Flags;
2021         Put(Iterators, Name, len, It, NULL);
2022 }
2023
2024 typedef struct _iteratestruct {
2025         int GroupChange;
2026         int oddeven;
2027         const char *Key;
2028         long KeyLen;
2029         int n;
2030         int LastN;
2031         }IterateStruct; 
2032
2033 int preeval_iterate(WCTemplateToken *Token)
2034 {
2035         WCTemplputParams TPP;
2036         WCTemplputParams *TP;
2037         void *vTmpl;
2038         void *vIt;
2039         HashIterator *It;
2040
2041         memset(&TPP, 0, sizeof(WCTemplputParams));
2042         TP = &TPP;
2043         TP->Tokens = Token;
2044         if (!GetHash(Iterators, TKEY(0), &vIt)) {
2045                 LogTemplateError(
2046                         NULL, "Iterator", ERR_PARM1, TP,
2047                         "not found");
2048                 return 0;
2049         }
2050         if (TP->Tokens->Params[1]->Type != TYPE_SUBTEMPLATE) {
2051                 LogTemplateError(NULL, "Iterator", ERR_PARM1, TP,
2052                                  "Need token with type Subtemplate as param 1, have %s", 
2053                                  TP->Tokens->Params[1]->Start);
2054         }
2055         
2056         /* well, we don't check the mobile stuff here... */
2057         if (!GetHash(LocalTemplateCache, TKEY(1), &vTmpl) &&
2058             !GetHash(TemplateCache, TKEY(1), &vTmpl)) {
2059                 LogTemplateError(NULL, "SubTemplate", ERR_PARM1, TP,
2060                                  "referenced here doesn't exist");
2061         }
2062         Token->Preeval2 = vIt;
2063         It = (HashIterator *) vIt;
2064
2065         if (TP->Tokens->nParameters < It->AdditionalParams + 2) {
2066                 LogTemplateError(                               
2067                         NULL, "Iterator", ERR_PARM1, TP,
2068                         "doesn't work with %d params", 
2069                         TP->Tokens->nParameters);
2070         }
2071
2072
2073         return 1;
2074 }
2075
2076 void tmpl_iterate_subtmpl(StrBuf *Target, WCTemplputParams *TP)
2077 {
2078         HashIterator *It;
2079         HashList *List;
2080         HashPos  *it;
2081         SortStruct *SortBy = NULL;
2082         void *vSortBy;
2083         int DetectGroupChange = 0;
2084         int nMembersUsed;
2085         void *vContext;
2086         void *vLastContext = NULL;
2087         StrBuf *SubBuf;
2088         WCTemplputParams IterateTP;
2089         WCTemplputParams SubTP;
2090         IterateStruct Status;
2091
2092         long StartAt = 0;
2093         long StepWidth = 0;
2094         long StopAt = -1;
2095
2096         memset(&Status, 0, sizeof(IterateStruct));
2097         
2098         It = (HashIterator*) TP->Tokens->Preeval2;
2099         if (It == NULL) {
2100                 LogTemplateError(
2101                         Target, "Iterator", ERR_PARM1, TP, "Unknown!");
2102                 return;
2103         }
2104
2105         if (TP->Tokens->nParameters < It->AdditionalParams + 2) {
2106                 LogTemplateError(                               
2107                         Target, "Iterator", ERR_PARM1, TP,
2108                         "doesn't work with %d params", 
2109                         TP->Tokens->nParameters - 1);
2110                 return;
2111         }
2112
2113         if ((It->XPectContextType != CTX_NONE) &&
2114             (It->XPectContextType != TP->Filter.ContextType)) {
2115                 LogTemplateError(
2116                         Target, "Iterator", ERR_PARM1, TP,
2117                         "requires context of type %s, have %s", 
2118                         ContextName(It->XPectContextType), 
2119                         ContextName(TP->Filter.ContextType));
2120                 return ;
2121                 
2122         }
2123
2124         if (It->StaticList == NULL)
2125                 List = It->GetHash(Target, TP);
2126         else
2127                 List = It->StaticList;
2128
2129         DetectGroupChange = (It->Flags & IT_FLAG_DETECT_GROUPCHANGE) != 0;
2130         if (DetectGroupChange) {
2131                 const StrBuf *BSort;
2132                 DetectGroupChange = 0;
2133                 if (havebstr("SortBy")) {
2134                         BSort = sbstr("SortBy");
2135                         if (GetHash(SortHash, SKEY(BSort), &vSortBy) &&
2136                             (vSortBy != NULL)) {
2137                                 SortBy = (SortStruct*)vSortBy;
2138                                 /* first check whether its intended for us... */
2139                                 if ((SortBy->ContextType == It->ContextType)&&
2140                                 /** Ok, its us, lets see in which direction we should sort... */
2141                                     (havebstr("SortOrder"))) {
2142                                         int SortOrder;
2143                                         SortOrder = lbstr("SortOrder");
2144                                         if (SortOrder != 0)
2145                                                 DetectGroupChange = 1;
2146                                 }
2147                         }
2148                 }
2149         }
2150         nMembersUsed = GetCount(List);
2151
2152         StackContext (TP, &IterateTP, &Status, CTX_ITERATE, 0, TP->Tokens);
2153         {
2154                 SubBuf = NewStrBuf();
2155         
2156                 if (HAVE_PARAM(2)) {
2157                         StartAt = GetTemplateTokenNumber(Target, TP, 2, 0);
2158                 }
2159                 if (HAVE_PARAM(3)) {
2160                         StepWidth = GetTemplateTokenNumber(Target, TP, 3, 0);
2161                 }
2162                 if (HAVE_PARAM(4)) {
2163                         StopAt = GetTemplateTokenNumber(Target, TP, 4, -1);
2164                 }
2165                 it = GetNewHashPos(List, StepWidth);
2166                 if (StopAt < 0) {
2167                         StopAt = GetCount(List);
2168                 }
2169                 while (GetNextHashPos(List, it, &Status.KeyLen, &Status.Key, &vContext)) {
2170                         if ((Status.n >= StartAt) && (Status.n <= StopAt)) {
2171
2172                                 if ((It->Filter != NULL) &&
2173                                     !It->Filter(Status.Key, Status.KeyLen, vContext, Target, TP)) 
2174                                 {
2175                                         continue;
2176                                 }
2177
2178                                 if (DetectGroupChange && Status.n > 0) {
2179                                         Status.GroupChange = SortBy->GroupChange(vContext, vLastContext);
2180                                 }
2181                                 Status.LastN = (Status.n + 1) == nMembersUsed;
2182                                 StackContext(&IterateTP, &SubTP, vContext, It->ContextType, 0, NULL);
2183                                 {
2184                                         if (It->DoSubTemplate != NULL)
2185                                                 It->DoSubTemplate(SubBuf, &SubTP);
2186                                         DoTemplate(TKEY(1), SubBuf, &SubTP);
2187
2188                                         StrBufAppendBuf(Target, SubBuf, 0);
2189                                         FlushStrBuf(SubBuf);
2190                                 }
2191                                 UnStackContext(&SubTP);
2192                                 Status.oddeven = ! Status.oddeven;
2193                                 vLastContext = vContext;
2194                         }
2195                         Status.n++;
2196                 }
2197         }
2198         UnStackContext(&IterateTP);
2199         FreeStrBuf(&SubBuf);
2200         DeleteHashPos(&it);
2201         if (It->Destructor != NULL)
2202                 It->Destructor(&List);
2203 }
2204
2205
2206 int conditional_ITERATE_ISGROUPCHANGE(StrBuf *Target, WCTemplputParams *TP)
2207 {
2208         IterateStruct *Ctx = CTX(CTX_ITERATE);
2209         if (TP->Tokens->nParameters < 3)
2210                 return  Ctx->GroupChange;
2211
2212         return TP->Tokens->Params[2]->lvalue == Ctx->GroupChange;
2213 }
2214
2215 void tmplput_ITERATE_ODDEVEN(StrBuf *Target, WCTemplputParams *TP)
2216 {
2217         IterateStruct *Ctx = CTX(CTX_ITERATE);
2218         if (Ctx->oddeven)
2219                 StrBufAppendBufPlain(Target, HKEY("odd"), 0);
2220         else
2221                 StrBufAppendBufPlain(Target, HKEY("even"), 0);
2222 }
2223
2224
2225 void tmplput_ITERATE_KEY(StrBuf *Target, WCTemplputParams *TP)
2226 {
2227         IterateStruct *Ctx = CTX(CTX_ITERATE);
2228
2229         StrBufAppendBufPlain(Target, Ctx->Key, Ctx->KeyLen, 0);
2230 }
2231
2232 void tmplput_ITERATE_N_DIV(StrBuf *Target, WCTemplputParams *TP)
2233 {
2234         IterateStruct *Ctx = CTX(CTX_ITERATE);
2235         long div;
2236         long divisor = GetTemplateTokenNumber(Target, TP, 0, 1);
2237 ///TODO divisor == 0 -> log error exit
2238         div = Ctx->n / divisor;
2239         StrBufAppendPrintf(Target, "%ld", div);
2240 }
2241
2242 void tmplput_ITERATE_N(StrBuf *Target, WCTemplputParams *TP)
2243 {
2244         IterateStruct *Ctx = CTX(CTX_ITERATE);
2245         StrBufAppendPrintf(Target, "%d", Ctx->n);
2246 }
2247
2248 int conditional_ITERATE_FIRSTN(StrBuf *Target, WCTemplputParams *TP)
2249 {
2250         IterateStruct *Ctx = CTX(CTX_ITERATE);
2251         return Ctx->n == 0;
2252 }
2253
2254 int conditional_ITERATE_LASTN(StrBuf *Target, WCTemplputParams *TP)
2255 {
2256         IterateStruct *Ctx = CTX(CTX_ITERATE);
2257         return Ctx->LastN;
2258 }
2259
2260 int conditional_ITERATE_ISMOD(StrBuf *Target, WCTemplputParams *TP)
2261 {
2262         IterateStruct *Ctx = CTX(CTX_ITERATE);
2263
2264         long divisor = GetTemplateTokenNumber(Target, TP, 2, 1);
2265         long expectRemainder = GetTemplateTokenNumber(Target, TP, 3, 0);
2266         
2267         return Ctx->n % divisor == expectRemainder;
2268 }
2269
2270
2271
2272 /*-----------------------------------------------------------------------------
2273  *                      Conditionals
2274  */
2275 int EvaluateConditional(StrBuf *Target, int Neg, int state, WCTemplputParams **TPP)
2276 {
2277         ConditionalStruct *Cond;
2278         int rc = 0;
2279         int res;
2280         WCTemplputParams *TP = *TPP;
2281
2282         if ((TP->Tokens->Params[0]->len == 1) &&
2283             (TP->Tokens->Params[0]->Start[0] == 'X'))
2284         {
2285                 return - (TP->Tokens->Params[1]->lvalue);
2286         }
2287             
2288         Cond = (ConditionalStruct *) TP->Tokens->PreEval;
2289         if (Cond == NULL) {
2290                 LogTemplateError(
2291                         Target, "Conditional", ERR_PARM1, TP,
2292                         "unknown!");
2293                 return 0;
2294         }
2295
2296         if (!CheckContext(Target, &Cond->Filter, TP, "Conditional")) {
2297                 return 0;
2298         }
2299
2300         res = Cond->CondF(Target, TP);
2301         if (res == Neg)
2302                 rc = TP->Tokens->Params[1]->lvalue;
2303
2304         if (LoadTemplates > 5) 
2305                 syslog(LOG_DEBUG, "<%s> : %d %d==%d\n", 
2306                         ChrPtr(TP->Tokens->FlatToken), 
2307                         rc, res, Neg);
2308
2309         if (TP->Sub != NULL)
2310         {
2311                 *TPP = TP->Sub;
2312         }
2313         return rc;
2314 }
2315
2316 void RegisterContextConditional(const char *Name, long len, 
2317                                 int nParams,
2318                                 WCConditionalFunc CondF, 
2319                                 WCConditionalFunc ExitCtxCond,
2320                                 int ContextRequired)
2321 {
2322         ConditionalStruct *Cond;
2323
2324         Cond = (ConditionalStruct*)malloc(sizeof(ConditionalStruct));
2325         memset(Cond, 0, sizeof(ConditionalStruct));
2326         Cond->PlainName = Name;
2327         Cond->Filter.nMaxArgs = nParams;
2328         Cond->Filter.nMinArgs = nParams;
2329         Cond->CondF = CondF;
2330         Cond->CondExitCtx = ExitCtxCond;
2331         Cond->Filter.ContextType = ContextRequired;
2332         Put(Conditionals, Name, len, Cond, NULL);
2333 }
2334
2335 void RegisterTokenParamDefine(const char *Name, long len, 
2336                               long Value)
2337 {
2338         long *PVal;
2339
2340         PVal = (long*)malloc(sizeof(long));
2341         *PVal = Value;
2342         Put(Defines, Name, len, PVal, NULL);
2343 }
2344
2345 long GetTokenDefine(const char *Name, long len, 
2346                     long DefValue)
2347 {
2348         void *vPVal;
2349
2350         if (GetHash(Defines, Name, len, &vPVal) &&
2351              (vPVal != NULL))
2352          {
2353                  return *(long*) vPVal;
2354          }
2355          else
2356          {
2357                  return DefValue;
2358          }
2359 }
2360
2361 void tmplput_DefStr(StrBuf *Target, WCTemplputParams *TP)
2362 {
2363         const char *Str;
2364         long len;
2365         GetTemplateTokenString(Target, TP, 2, &Str, &len);
2366         
2367         StrBufAppendBufPlain(Target, Str, len, 0);
2368 }
2369
2370 void tmplput_DefVal(StrBuf *Target, WCTemplputParams *TP)
2371 {
2372         int val;
2373
2374         val = GetTemplateTokenNumber(Target, TP, 0, 0);
2375         StrBufAppendPrintf(Target, "%d", val);
2376 }
2377
2378 HashList *Defines;
2379
2380 /*-----------------------------------------------------------------------------
2381  *                      Context Strings
2382  */
2383 void tmplput_ContextString(StrBuf *Target, WCTemplputParams *TP)
2384 {
2385         StrBufAppendTemplate(Target, TP, (StrBuf*)CTX(CTX_STRBUF), 0);
2386 }
2387 int ConditionalContextStr(StrBuf *Target, WCTemplputParams *TP)
2388 {
2389         StrBuf *TokenText = (StrBuf*) CTX((CTX_STRBUF));
2390         const char *CompareToken;
2391         long len;
2392
2393         GetTemplateTokenString(Target, TP, 2, &CompareToken, &len);
2394         return strcmp(ChrPtr(TokenText), CompareToken) == 0;
2395 }
2396
2397 void tmplput_ContextStringArray(StrBuf *Target, WCTemplputParams *TP)
2398 {
2399         HashList *Arr = (HashList*) CTX(CTX_STRBUFARR);
2400         void *pV;
2401         int val;
2402
2403         val = GetTemplateTokenNumber(Target, TP, 0, 0);
2404         if (GetHash(Arr, IKEY(val), &pV) && 
2405             (pV != NULL)) {
2406                 StrBufAppendTemplate(Target, TP, (StrBuf*)pV, 1);
2407         }
2408 }
2409 int ConditionalContextStrinArray(StrBuf *Target, WCTemplputParams *TP)
2410 {
2411         HashList *Arr = (HashList*) CTX(CTX_STRBUFARR);
2412         void *pV;
2413         int val;
2414         const char *CompareToken;
2415         long len;
2416
2417         GetTemplateTokenString(Target, TP, 2, &CompareToken, &len);
2418         val = GetTemplateTokenNumber(Target, TP, 0, 0);
2419         if (GetHash(Arr, IKEY(val), &pV) && 
2420             (pV != NULL)) {
2421                 return strcmp(ChrPtr((StrBuf*)pV), CompareToken) == 0;
2422         }
2423         else
2424                 return 0;
2425 }
2426
2427 /*-----------------------------------------------------------------------------
2428  *                      Boxed-API
2429  */
2430
2431 void tmpl_do_boxed(StrBuf *Target, WCTemplputParams *TP)
2432 {
2433         WCTemplputParams SubTP;
2434
2435         StrBuf *Headline = NULL;
2436         if (TP->Tokens->nParameters == 2) {
2437                 if (TP->Tokens->Params[1]->Type == TYPE_STR) {
2438                         Headline = NewStrBuf();
2439                         DoTemplate(TKEY(1), Headline, TP);
2440                 }
2441                 else {
2442                         const char *Ch;
2443                         long len;
2444                         GetTemplateTokenString(Target, 
2445                                                TP, 
2446                                                1,
2447                                                &Ch,
2448                                                &len);
2449                         Headline = NewStrBufPlain(Ch, len);
2450                 }
2451         }
2452         /* else TODO error? logging? */
2453
2454         StackContext (TP, &SubTP, Headline, CTX_STRBUF, 0, NULL);
2455         {
2456                 DoTemplate(HKEY("box_begin"), Target, &SubTP);
2457         }
2458         UnStackContext(&SubTP);
2459         DoTemplate(TKEY(0), Target, TP);
2460         DoTemplate(HKEY("box_end"), Target, TP);
2461         FreeStrBuf(&Headline);
2462 }
2463
2464 /*-----------------------------------------------------------------------------
2465  *                      Tabbed-API
2466  */
2467
2468 typedef struct _tab_struct {
2469         long CurrentTab;
2470         StrBuf *TabTitle;
2471 } tab_struct;
2472
2473 int preeval_do_tabbed(WCTemplateToken *Token)
2474 {
2475         WCTemplputParams TPP;
2476         WCTemplputParams *TP;
2477         const char *Ch;
2478         long len;
2479         int i, nTabs;
2480
2481         memset(&TPP, 0, sizeof(WCTemplputParams));
2482         TP = &TPP;
2483         TP->Tokens = Token;
2484         nTabs = TP->Tokens->nParameters / 2 - 1;
2485         if (TP->Tokens->nParameters % 2 != 0)
2486         {
2487                 LogTemplateError(NULL, "TabbedApi", ERR_PARM1, TP,
2488                                  "need even number of arguments");
2489                 return 0;
2490
2491         }
2492         else for (i = 0; i < nTabs; i++) {
2493                 if (!HaveTemplateTokenString(NULL, 
2494                                              TP, 
2495                                              i * 2,
2496                                              &Ch,
2497                                              &len) || 
2498                     (TP->Tokens->Params[i * 2]->len == 0))
2499                 {
2500                         LogTemplateError(NULL, "TabbedApi", ERR_PARM1, TP,
2501                                          "Tab-Subject %d needs to be able to produce a string, have %s", 
2502                                          i, TP->Tokens->Params[i * 2]->Start);
2503                         return 0;
2504                 }
2505                 if (!HaveTemplateTokenString(NULL, 
2506                                              TP, 
2507                                              i * 2 + 1,
2508                                              &Ch,
2509                                              &len) || 
2510                     (TP->Tokens->Params[i * 2 + 1]->len == 0))
2511                 {
2512                         LogTemplateError(NULL, "TabbedApi", ERR_PARM1, TP,
2513                                          "Tab-Content %d needs to be able to produce a string, have %s", 
2514                                          i, TP->Tokens->Params[i * 2 + 1]->Start);
2515                         return 0;
2516                 }
2517         }
2518
2519         if (!HaveTemplateTokenString(NULL, 
2520                                      TP, 
2521                                      i * 2 + 1,
2522                                      &Ch,
2523                                      &len) || 
2524             (TP->Tokens->Params[i * 2 + 1]->len == 0))
2525         {
2526                 LogTemplateError(NULL, "TabbedApi", ERR_PARM1, TP,
2527                                  "Tab-Content %d needs to be able to produce a string, have %s", 
2528                                  i, TP->Tokens->Params[i * 2 + 1]->Start);
2529                 return 0;
2530         }
2531         return 1;
2532 }
2533
2534
2535 void tmpl_do_tabbed(StrBuf *Target, WCTemplputParams *TP)
2536 {
2537         StrBuf **TabNames;
2538         int i, ntabs, nTabs;
2539         tab_struct TS;
2540         WCTemplputParams SubTP;
2541
2542         memset(&TS, 0, sizeof(tab_struct));
2543
2544         nTabs = ntabs = TP->Tokens->nParameters / 2;
2545         TabNames = (StrBuf **) malloc(ntabs * sizeof(StrBuf*));
2546         memset(TabNames, 0, ntabs * sizeof(StrBuf*));
2547
2548         for (i = 0; i < ntabs; i++) {
2549                 if ((TP->Tokens->Params[i * 2]->Type == TYPE_STR) &&
2550                     (TP->Tokens->Params[i * 2]->len > 0)) {
2551                         TabNames[i] = NewStrBuf();
2552                         DoTemplate(TKEY(i * 2), TabNames[i], TP);
2553                 }
2554                 else if (TP->Tokens->Params[i * 2]->Type == TYPE_GETTEXT) {
2555                         const char *Ch;
2556                         long len;
2557                         GetTemplateTokenString(Target, 
2558                                                TP, 
2559                                                i * 2,
2560                                                &Ch,
2561                                                &len);
2562                         TabNames[i] = NewStrBufPlain(Ch, -1);
2563                 }
2564                 else { 
2565                         /** A Tab without subject? we can't count that, add it as silent */
2566                         nTabs --;
2567                 }
2568         }
2569         StackContext (TP, &SubTP, &TS, CTX_TAB, 0, NULL);
2570         {
2571                 StrTabbedDialog(Target, nTabs, TabNames);
2572                 for (i = 0; i < ntabs; i++) {
2573                         memset(&TS, 0, sizeof(tab_struct));
2574                         TS.CurrentTab = i;
2575                         TS.TabTitle = TabNames[i];
2576                         StrBeginTab(Target, i, nTabs, TabNames);
2577                         DoTemplate(TKEY(i * 2 + 1), Target, &SubTP);
2578                         StrEndTab(Target, i, nTabs);
2579                 }
2580                 for (i = 0; i < ntabs; i++) 
2581                         FreeStrBuf(&TabNames[i]);
2582                 free(TabNames);
2583         }
2584         UnStackContext(&SubTP);
2585 }
2586
2587 void tmplput_TAB_N(StrBuf *Target, WCTemplputParams *TP)
2588 {
2589         tab_struct *Ctx = CTX(CTX_TAB);
2590
2591         StrBufAppendPrintf(Target, "%d", Ctx->CurrentTab);
2592 }
2593
2594 void tmplput_TAB_TITLE(StrBuf *Target, WCTemplputParams *TP)
2595 {
2596         tab_struct *Ctx = CTX(CTX_TAB);
2597         StrBufAppendTemplate(Target, TP, Ctx->TabTitle, 0);
2598 }
2599
2600 /*-----------------------------------------------------------------------------
2601  *                      Sorting-API
2602  */
2603
2604
2605 void RegisterSortFunc(const char *name, long len, 
2606                       const char *prepend, long preplen,
2607                       CompareFunc Forward, 
2608                       CompareFunc Reverse, 
2609                       CompareFunc GroupChange, 
2610                       CtxType ContextType)
2611 {
2612         SortStruct *NewSort;
2613
2614         NewSort = (SortStruct*) malloc(sizeof(SortStruct));
2615         memset(NewSort, 0, sizeof(SortStruct));
2616         NewSort->Name = NewStrBufPlain(name, len);
2617         if (prepend != NULL)
2618                 NewSort->PrefPrepend = NewStrBufPlain(prepend, preplen);
2619         else
2620                 NewSort->PrefPrepend = NULL;
2621         NewSort->Forward = Forward;
2622         NewSort->Reverse = Reverse;
2623         NewSort->GroupChange = GroupChange;
2624         NewSort->ContextType = ContextType;
2625         if (ContextType == CTX_NONE) {
2626                 syslog(LOG_WARNING, "sorting requires a context. CTX_NONE won't make it.\n");
2627                 exit(1);
2628         }
2629                 
2630         Put(SortHash, name, len, NewSort, DestroySortStruct);
2631 }
2632
2633 CompareFunc RetrieveSort(WCTemplputParams *TP, 
2634                          const char *OtherPrefix, long OtherPrefixLen,
2635                          const char *Default, long ldefault, long DefaultDirection)
2636 {
2637         const StrBuf *BSort = NULL;
2638         SortStruct *SortBy;
2639         void *vSortBy;
2640         long SortOrder = -1;
2641         
2642         if (havebstr("SortBy")) {
2643                 BSort = sbstr("SortBy");
2644                 if (OtherPrefix == NULL) {
2645                         set_room_pref("sort", NewStrBufDup(BSort), 0);
2646                 }
2647                 else {
2648                         set_X_PREFS(HKEY("sort"), OtherPrefix, OtherPrefixLen, NewStrBufDup(BSort), 0);
2649                 }
2650         }
2651         else { /** Try to fallback to our remembered values... */
2652                 if (OtherPrefix == NULL) {
2653                         BSort = get_room_pref("sort");
2654                 }
2655                 else {
2656                         BSort = get_X_PREFS(HKEY("sort"), OtherPrefix, OtherPrefixLen);
2657                 }
2658                 if (BSort != NULL)
2659                         putbstr("SortBy", NewStrBufDup(BSort));
2660                 else {
2661                         StrBuf *Buf;
2662
2663                         BSort = Buf = NewStrBufPlain(Default, ldefault);
2664                         putbstr("SortBy", Buf);
2665                 }
2666         }
2667
2668         if (!GetHash(SortHash, SKEY(BSort), &vSortBy) || 
2669             (vSortBy == NULL)) {
2670                 if (!GetHash(SortHash, Default, ldefault, &vSortBy) || 
2671                     (vSortBy == NULL)) {
2672                         LogTemplateError(
2673                                 NULL, "Sorting", ERR_PARM1, TP,
2674                                 "Illegal default sort: [%s]", Default);
2675                         wc_backtrace(LOG_WARNING);
2676                 }
2677         }
2678         SortBy = (SortStruct*)vSortBy;
2679
2680         if (SortBy->ContextType != TP->Filter.ContextType)
2681                 return NULL;
2682
2683         /** Ok, its us, lets see in which direction we should sort... */
2684         if (havebstr("SortOrder")) {
2685                 SortOrder = lbstr("SortOrder");
2686         }
2687         else { /** Try to fallback to our remembered values... */
2688                 StrBuf *Buf = NULL;
2689                 if (SortBy->PrefPrepend == NULL) {
2690                         Buf = get_room_pref("SortOrder");
2691                         SortOrder = StrTol(Buf);
2692                 }
2693                 else {
2694                         BSort = get_X_PREFS(HKEY("SortOrder"), OtherPrefix, OtherPrefixLen);
2695                 }
2696
2697                 if (Buf == NULL)
2698                         SortOrder = DefaultDirection;
2699
2700                 Buf = NewStrBufPlain(NULL, 64);
2701                 StrBufPrintf(Buf, "%ld", SortOrder);
2702                 putbstr("SortOrder", Buf);
2703         }
2704         switch (SortOrder) {
2705         default:
2706         case 0:
2707                 return NULL;
2708         case 1:
2709                 return SortBy->Forward;
2710         case 2:
2711                 return SortBy->Reverse;
2712         }
2713 }
2714
2715
2716 enum {
2717         eNO_SUCH_SORT, 
2718         eNOT_SPECIFIED,
2719         eINVALID_PARAM,
2720         eFOUND
2721 };
2722
2723 ConstStr SortIcons[] = {
2724         {HKEY("static/webcit_icons/sort_none.gif")},
2725         {HKEY("static/webcit_icons/up_pointer.gif")},
2726         {HKEY("static/webcit_icons/down_pointer.gif")},
2727 };
2728
2729 ConstStr SortNextOrder[] = {
2730         {HKEY("1")},
2731         {HKEY("2")},
2732         {HKEY("0")},
2733 };
2734
2735
2736 int GetSortMetric(WCTemplputParams *TP, SortStruct **Next, SortStruct **Param, long *SortOrder, int N)
2737 {
2738         int bSortError = eNOT_SPECIFIED;
2739         const StrBuf *BSort;
2740         void *vSort;
2741         
2742         *SortOrder = 0;
2743         *Next = NULL;
2744         if (!GetHash(SortHash, TKEY(0), &vSort) || 
2745             (vSort == NULL))
2746                 return eNO_SUCH_SORT;
2747         *Param = (SortStruct*) vSort;
2748         
2749
2750         if (havebstr("SortBy")) {
2751                 BSort = sbstr("SortBy");
2752                 bSortError = eINVALID_PARAM;
2753                 if ((*Param)->PrefPrepend == NULL) {
2754                         set_room_pref("sort", NewStrBufDup(BSort), 0);
2755                 }
2756                 else {
2757                         set_X_PREFS(HKEY("sort"), TKEY(N), NewStrBufDup(BSort), 0);
2758                 }
2759         }
2760         else { /** Try to fallback to our remembered values... */
2761                 if ((*Param)->PrefPrepend == NULL) {
2762                         BSort = get_room_pref("sort");
2763                 }
2764                 else {
2765                         BSort = get_X_PREFS(HKEY("sort"), TKEY(N));
2766                 }
2767         }
2768
2769         if (!GetHash(SortHash, SKEY(BSort), &vSort) || 
2770             (vSort == NULL))
2771                 return bSortError;
2772
2773         *Next = (SortStruct*) vSort;
2774
2775         /** Ok, its us, lets see in which direction we should sort... */
2776         if (havebstr("SortOrder")) {
2777                 *SortOrder = lbstr("SortOrder");
2778         }
2779         else { /** Try to fallback to our remembered values... */
2780                 if ((*Param)->PrefPrepend == NULL) {
2781                         *SortOrder = StrTol(get_room_pref("SortOrder"));
2782                 }
2783                 else {
2784                         *SortOrder = StrTol(get_X_PREFS(HKEY("SortOrder"), TKEY(N)));
2785                 }
2786         }
2787         if (*SortOrder > 2)
2788                 *SortOrder = 0;
2789
2790         return eFOUND;
2791 }
2792
2793
2794 void tmplput_SORT_ICON(StrBuf *Target, WCTemplputParams *TP)
2795 {
2796         long SortOrder;
2797         SortStruct *Next;
2798         SortStruct *Param;
2799         const ConstStr *SortIcon;
2800
2801         switch (GetSortMetric(TP, &Next, &Param, &SortOrder, 2)){
2802         case eNO_SUCH_SORT:
2803                 LogTemplateError(
2804                         Target, "Sorter", ERR_PARM1, TP,
2805                         " Sorter [%s] unknown!", 
2806                         TP->Tokens->Params[0]->Start);
2807                 break;          
2808         case eINVALID_PARAM:
2809                 LogTemplateError(NULL, "Sorter", ERR_PARM1, TP,
2810                                  " Sorter specified by BSTR 'SortBy' [%s] unknown!", 
2811                                  bstr("SortBy"));
2812         case eNOT_SPECIFIED:
2813         case eFOUND:
2814                 if (Next == Param) {
2815                         SortIcon = &SortIcons[SortOrder];
2816                 }
2817                 else { /** Not Us... */
2818                         SortIcon = &SortIcons[0];
2819                 }
2820                 StrBufAppendBufPlain(Target, SortIcon->Key, SortIcon->len, 0);
2821         }
2822 }
2823
2824 void tmplput_SORT_NEXT(StrBuf *Target, WCTemplputParams *TP)
2825 {
2826         long SortOrder;
2827         SortStruct *Next;
2828         SortStruct *Param;
2829
2830         switch (GetSortMetric(TP, &Next, &Param, &SortOrder, 2)){
2831         case eNO_SUCH_SORT:
2832                 LogTemplateError(
2833                         Target, "Sorter", ERR_PARM1, TP,                                  
2834                         " Sorter [%s] unknown!", 
2835                         TP->Tokens->Params[0]->Start);
2836                 break;          
2837         case eINVALID_PARAM:
2838                 LogTemplateError(
2839                         NULL, "Sorter", ERR_PARM1, TP,
2840                         " Sorter specified by BSTR 'SortBy' [%s] unknown!", 
2841                         bstr("SortBy"));
2842         case eNOT_SPECIFIED:
2843         case eFOUND:
2844                 StrBufAppendBuf(Target, Param->Name, 0);
2845                 
2846         }
2847 }
2848
2849 void tmplput_SORT_ORDER(StrBuf *Target, WCTemplputParams *TP)
2850 {
2851         long SortOrder;
2852         const ConstStr *SortOrderStr;
2853         SortStruct *Next;
2854         SortStruct *Param;
2855
2856         switch (GetSortMetric(TP, &Next, &Param, &SortOrder, 2)){
2857         case eNO_SUCH_SORT:
2858                 LogTemplateError(
2859                         Target, "Sorter", ERR_PARM1, TP,
2860                         " Sorter [%s] unknown!",
2861                         TP->Tokens->Params[0]->Start);
2862                 break;          
2863         case eINVALID_PARAM:
2864                 LogTemplateError(
2865                         NULL, "Sorter", ERR_PARM1, TP,
2866                         " Sorter specified by BSTR 'SortBy' [%s] unknown!",
2867                         bstr("SortBy"));
2868         case eNOT_SPECIFIED:
2869         case eFOUND:
2870                 if (Next == Param) {
2871                         SortOrderStr = &SortNextOrder[SortOrder];
2872                 }
2873                 else { /** Not Us... */
2874                         SortOrderStr = &SortNextOrder[0];
2875                 }
2876                 StrBufAppendBufPlain(Target, SortOrderStr->Key, SortOrderStr->len, 0);
2877         }
2878 }
2879
2880
2881 void tmplput_long_vector(StrBuf *Target, WCTemplputParams *TP)
2882 {
2883         long *LongVector = (long*) CTX(CTX_LONGVECTOR);
2884
2885         if ((TP->Tokens->Params[0]->Type == TYPE_LONG) && 
2886             (TP->Tokens->Params[0]->lvalue <= LongVector[0]))
2887         {
2888                 StrBufAppendPrintf(Target, "%ld", LongVector[TP->Tokens->Params[0]->lvalue]);
2889         }
2890         else
2891         {
2892                 if (TP->Tokens->Params[0]->Type != TYPE_LONG) {
2893                         LogTemplateError(
2894                                 Target, "Longvector", ERR_NAME, TP,
2895                                 "needs a numerical Parameter!");
2896                 }
2897                 else {
2898                         LogTemplateError(
2899                                 Target, "LongVector", ERR_PARM1, TP,
2900                                 "doesn't have %ld Parameters, its just the size of %ld!", 
2901                                 TP->Tokens->Params[0]->lvalue,
2902                                 LongVector[0]);
2903                 }
2904         }
2905 }
2906
2907 void dbg_print_longvector(long *LongVector)
2908 {
2909         StrBuf *Buf = NewStrBufPlain(HKEY("Longvector: ["));
2910         int nItems = LongVector[0];
2911         int i;
2912
2913         for (i = 0; i < nItems; i++) {
2914                 if (i + 1 < nItems)
2915                         StrBufAppendPrintf(Buf, "%d: %ld | ", i, LongVector[i]);
2916                 else
2917                         StrBufAppendPrintf(Buf, "%d: %ld]\n", i, LongVector[i]);
2918
2919         }
2920         syslog(LOG_DEBUG, "%s", ChrPtr(Buf));
2921         FreeStrBuf(&Buf);
2922 }
2923
2924 int ConditionalLongVector(StrBuf *Target, WCTemplputParams *TP)
2925 {
2926         long *LongVector = (long*) CTX(CTX_LONGVECTOR);
2927
2928         if ((TP->Tokens->Params[2]->Type == TYPE_LONG) && 
2929             (TP->Tokens->Params[2]->lvalue <= LongVector[0])&&
2930             (TP->Tokens->Params[3]->Type == TYPE_LONG) && 
2931             (TP->Tokens->Params[3]->lvalue <= LongVector[0]))
2932         {
2933                 return LongVector[TP->Tokens->Params[2]->lvalue] == 
2934                         LongVector[TP->Tokens->Params[3]->lvalue];
2935         }
2936         else
2937         {
2938                 if ((TP->Tokens->Params[2]->Type == TYPE_LONG) ||
2939                     (TP->Tokens->Params[2]->Type == TYPE_LONG)) {
2940                         LogTemplateError(
2941                                 Target, "ConditionalLongvector", ERR_PARM1, TP,
2942                                 "needs two long Parameter!");
2943                 }
2944                 else {
2945                         LogTemplateError(
2946                                 Target, "Longvector", ERR_PARM1, TP,
2947                                 "doesn't have %ld / %ld Parameters, its just the size of %ld!",
2948                                 TP->Tokens->Params[2]->lvalue,
2949                                 TP->Tokens->Params[3]->lvalue,
2950                                 LongVector[0]);
2951                 }
2952         }
2953         return 0;
2954 }
2955
2956
2957 void tmplput_CURRENT_FILE(StrBuf *Target, WCTemplputParams *TP)
2958 {
2959         StrBufAppendTemplate(Target, TP, TP->Tokens->FileName, 0);
2960 }
2961
2962 void 
2963 InitModule_SUBST
2964 (void)
2965 {
2966         RegisterCTX(CTX_TAB);
2967         RegisterCTX(CTX_ITERATE);
2968
2969         memset(&NoCtx, 0, sizeof(WCTemplputParams));
2970         RegisterNamespace("--", 0, 2, tmplput_Comment, NULL, CTX_NONE);
2971         RegisterNamespace("SORT:ICON", 1, 2, tmplput_SORT_ICON, NULL, CTX_NONE);
2972         RegisterNamespace("SORT:ORDER", 1, 2, tmplput_SORT_ORDER, NULL, CTX_NONE);
2973         RegisterNamespace("SORT:NEXT", 1, 2, tmplput_SORT_NEXT, NULL, CTX_NONE);
2974         RegisterNamespace("CONTEXTSTR", 0, 1, tmplput_ContextString, NULL, CTX_STRBUF);
2975         RegisterNamespace("CONTEXTSTRARR", 1, 2, tmplput_ContextStringArray, NULL, CTX_STRBUFARR);
2976         RegisterNamespace("ITERATE", 2, 100, tmpl_iterate_subtmpl, preeval_iterate, CTX_NONE);
2977         RegisterNamespace("DOBOXED", 1, 2, tmpl_do_boxed, NULL, CTX_NONE);
2978         RegisterNamespace("DOTABBED", 2, 100, tmpl_do_tabbed, preeval_do_tabbed, CTX_NONE);
2979         RegisterNamespace("TAB:N", 0, 0, tmplput_TAB_N, NULL, CTX_TAB);
2980         RegisterNamespace("TAB:SUBJECT", 0, 1, tmplput_TAB_TITLE, NULL, CTX_TAB);
2981
2982
2983         RegisterNamespace("LONGVECTOR", 1, 1, tmplput_long_vector, NULL, CTX_LONGVECTOR);
2984
2985
2986         RegisterConditional("COND:CONTEXTSTR", 3, ConditionalContextStr, CTX_STRBUF);
2987         RegisterConditional("COND:CONTEXTSTRARR", 4, ConditionalContextStrinArray, CTX_STRBUFARR);
2988         RegisterConditional("COND:LONGVECTOR", 4, ConditionalLongVector, CTX_LONGVECTOR);
2989
2990
2991         RegisterConditional("COND:ITERATE:ISGROUPCHANGE", 2, 
2992                             conditional_ITERATE_ISGROUPCHANGE, 
2993                             CTX_ITERATE);
2994         RegisterConditional("COND:ITERATE:LASTN", 2, 
2995                             conditional_ITERATE_LASTN, 
2996                             CTX_ITERATE);
2997         RegisterConditional("COND:ITERATE:FIRSTN", 2, 
2998                             conditional_ITERATE_FIRSTN, 
2999                             CTX_ITERATE);
3000         RegisterConditional("COND:ITERATE:ISMOD", 3, 
3001                             conditional_ITERATE_ISMOD, 
3002                             CTX_ITERATE);
3003
3004         RegisterNamespace("ITERATE:ODDEVEN", 0, 0, tmplput_ITERATE_ODDEVEN, NULL, CTX_ITERATE);
3005         RegisterNamespace("ITERATE:KEY", 0, 0, tmplput_ITERATE_KEY, NULL, CTX_ITERATE);
3006         RegisterNamespace("ITERATE:N", 0, 0, tmplput_ITERATE_N, NULL, CTX_ITERATE);
3007         RegisterNamespace("ITERATE:N:DIV", 1, 1, tmplput_ITERATE_N_DIV, NULL, CTX_ITERATE);
3008         RegisterNamespace("CURRENTFILE", 0, 1, tmplput_CURRENT_FILE, NULL, CTX_NONE);
3009         RegisterNamespace("DEF:STR", 1, 1, tmplput_DefStr, NULL, CTX_NONE);
3010         RegisterNamespace("DEF:VAL", 1, 1, tmplput_DefVal, NULL, CTX_NONE);
3011
3012
3013
3014
3015 }
3016
3017 void
3018 ServerStartModule_SUBST
3019 (void)
3020 {
3021         textPlainType = NewStrBufPlain(HKEY("text/plain"));
3022         LocalTemplateCache = NewHash(1, NULL);
3023         TemplateCache = NewHash(1, NULL);
3024         GlobalNS = NewHash(1, NULL);
3025         Iterators = NewHash(1, NULL);
3026         Conditionals = NewHash(1, NULL);
3027         SortHash = NewHash(1, NULL);
3028         Defines = NewHash(1, NULL);
3029         CtxList = NewHash(1, NULL);
3030         
3031         PutContextType(HKEY("CTX_NONE"), 0);
3032
3033         RegisterCTX(CTX_STRBUF);
3034         RegisterCTX(CTX_STRBUFARR);
3035         RegisterCTX(CTX_LONGVECTOR);
3036 }
3037
3038 void
3039 FinalizeModule_SUBST
3040 (void)
3041 {
3042
3043 }
3044
3045 void 
3046 ServerShutdownModule_SUBST
3047 (void)
3048 {
3049         FreeStrBuf(&textPlainType);
3050
3051         DeleteHash(&TemplateCache);
3052         DeleteHash(&LocalTemplateCache);
3053         
3054         DeleteHash(&GlobalNS);
3055         DeleteHash(&Iterators);
3056         DeleteHash(&Conditionals);
3057         DeleteHash(&SortHash);
3058         DeleteHash(&Defines);
3059         DeleteHash(&CtxList);
3060 }
3061
3062
3063 void
3064 SessionNewModule_SUBST
3065 (wcsession *sess)
3066 {
3067
3068 }
3069
3070 void
3071 SessionAttachModule_SUBST
3072 (wcsession *sess)
3073 {
3074 }
3075
3076 void
3077 SessionDetachModule_SUBST
3078 (wcsession *sess)
3079 {
3080         FreeStrBuf(&sess->WFBuf);
3081 }
3082
3083 void 
3084 SessionDestroyModule_SUBST  
3085 (wcsession *sess)
3086 {
3087
3088 }