SUBST: Dynamicaly generate contexts
[citadel.git] / webcit / subst.h
1 /**
2  * @defgroup subst Template processing functions
3  */
4
5 extern HashList *Conditionals;
6 extern HashList *GlobalNS;
7 extern HashList *Iterators;
8 extern HashList *WirelessTemplateCache;
9 extern HashList *WirelessLocalTemplateCache;
10 extern HashList *TemplateCache;
11 extern HashList *LocalTemplateCache;
12
13
14 #define TYPE_STR   1
15 #define TYPE_LONG  2
16 #define TYPE_PREFSTR 3
17 #define TYPE_PREFINT 4
18 #define TYPE_GETTEXT 5
19 #define TYPE_BSTR 6
20 #define TYPE_SUBTEMPLATE 7
21 #define TYPE_INTDEFINE 8
22 #define MAXPARAM  25
23
24 #define IS_NUMBER(a) ((a == TYPE_LONG) || (a == TYPE_PREFINT) || (a == TYPE_INTDEFINE))
25
26 /*
27  * \brief Values for wcs_type
28  */
29 enum {
30         WCS_STRING,       /* its a string */
31         WCS_FUNCTION,     /* its a function callback */
32         WCS_SERVCMD,      /* its a command to send to the citadel server */
33         WCS_STRBUF,       /* its a strbuf we own */
34         WCS_STRBUF_REF,   /* its a strbuf we mustn't free */
35         WCS_LONG          /* its an integer */
36 };
37
38 #define CTX_NONE 0
39
40 typedef int CtxType;
41 typedef struct __CtxTypeStruct {
42         CtxType Type;
43         StrBuf *Name;
44 } CtxTypeStruct;
45
46 CtxTypeStruct *GetContextType(CtxType Type);
47 void RegisterContextType(const char *name, long len, CtxType *TheCtx);
48 #define RegisterCTX(a) RegisterContextType(#a, sizeof(#a) - 1, &a)
49
50 extern CtxType CTX_STRBUF;
51 extern CtxType CTX_STRBUFARR;
52 extern CtxType CTX_LONGVECTOR;
53
54 /**
55  * @ingroup subst
56  * ContextFilter resembles our RTTI information. With this structure
57  * we can make shure a tmplput function can live with the environment
58  * we call it in.
59  * if not, we will log/print an error and refuse to call it.
60  */
61 typedef struct _contexts {
62         CtxType ContextType;                /* do we require a User Context ? */
63         int nMinArgs;                   /* How many arguments do we need at least? */
64         int nMaxArgs;                   /* up to how many arguments can we handle? */
65 } ContextFilter;
66
67
68 /* Forward declarations... */
69 typedef struct WCTemplateToken WCTemplateToken;
70 typedef struct WCTemplputParams WCTemplputParams;
71
72 /* this is the signature of a tmplput function */
73 typedef void (*WCHandlerFunc)(StrBuf *Target, WCTemplputParams *TP);
74
75 /* if you want to pre-evaluate parts of your token, or do additional syntax, use this. */ 
76 typedef int (*WCPreevalFunc)(WCTemplateToken *Token);
77
78 /* make a template token a lookup key: */
79 #define TKEY(a) TP->Tokens->Params[a]->Start, TP->Tokens->Params[a]->len
80
81 void *GetContextPayload(WCTemplputParams *TP, CtxType ContextType);
82 #define CTX(a) GetContextPayload(TP, a)
83
84 /**
85  * @ingroup subst
86  * this is the signature of a conditional function 
87  * Note: Target is just passed in for error messages; don't write onto it in regular cases.
88  */
89 typedef int (*WCConditionalFunc)(StrBuf *Target, WCTemplputParams *TP);
90
91 typedef enum _eBitMask {
92         eNO = 0,
93         eOR,
94         eAND
95 }eBitMask;
96
97 typedef struct _TemplateParam {
98         /* are we a string or a number? */
99         int Type;
100         /* string data: */
101         const char *Start;
102         long len;
103         /* if we're a number: */
104         long lvalue;
105         eBitMask MaskBy;
106 } TemplateParam;
107
108
109 /**
110  * @ingroup subst
111  * Representation of a token; everything thats inbetween <? and >
112  */ 
113 struct WCTemplateToken {
114         /* Reference to the filename we're in to print error messages; not to be freed */
115         const StrBuf *FileName; 
116         /* Raw copy of our original token; for error printing */
117         StrBuf *FlatToken;
118         /* Which line did the template parser pick us up in? For error printing */
119         long Line;
120
121         /* our position in the template cache buffer */
122         const char *pTokenStart;
123         /* our token length */
124         size_t TokenStart;
125         size_t TokenEnd;
126         /* point after us */
127         const char *pTokenEnd;
128         /* just our token name: */
129         const char *pName;
130         size_t NameEnd;
131
132         /* stuff the pre-evaluater finds out: */
133         int Flags;
134         /* pointer to our runntime evaluator; so we can cache this and save hash-lookups */
135         void *PreEval;
136         void *Preeval2;
137
138         /* if we have parameters here we go: */
139         /* do we have parameters or not? */
140         int HaveParameters;
141         /* How many of them? */
142         int nParameters;
143         /* the parameters */
144         TemplateParam *Params[MAXPARAM];
145 };
146
147
148
149 struct WCTemplputParams {
150         ContextFilter Filter;
151         void *Context;
152         int nArgs;
153         WCTemplateToken *Tokens;
154         WCTemplputParams *Sub, *Super;
155 };
156
157
158
159 typedef struct _ConditionalStruct {
160         ContextFilter Filter;
161         const char *PlainName;
162         WCConditionalFunc CondF;
163 } ConditionalStruct;
164
165
166 typedef void (*SubTemplFunc)(StrBuf *TemplBuffer, WCTemplputParams *TP);
167 typedef HashList *(*RetrieveHashlistFunc)(StrBuf *Target, WCTemplputParams *TP);
168 typedef void (*HashDestructorFunc) (HashList **KillMe);
169
170
171 extern WCTemplputParams NoCtx;
172
173 #define HAVE_PARAM(a) (TP->Tokens->nParameters > a)
174
175
176 #define ERR_NAME 0
177 #define ERR_PARM1 1
178 #define ERR_PARM2 2
179 /**
180  * @ingroup subst
181  * @brief log an error while evaluating a token; print it to the actual template 
182  * @param Target your Target Buffer to print the error message next to the log
183  * @param Type What sort of thing are we talking about? Tokens? Conditionals?
184  * @param TP grab our set of default information here
185  * @param Format for the custom error message
186  */ 
187 void LogTemplateError (StrBuf *Target, 
188                        const char *Type, 
189                        int ErrorPos, 
190                        WCTemplputParams *TP, 
191                        const char *Format, ...)__attribute__((__format__(__printf__,5,6)));
192
193
194 /**
195  * @ingroup subst
196  * @brief log an error while in global context; print it to Wildfire / Target
197  * @param Target your Target Buffer to print the error message next to the log
198  * @param Type What sort of thing are we talking about? Tokens? Conditionals?
199  * @param Format for the custom error message
200  */ 
201 void LogError (StrBuf *Target, const char *Type, const char *Format, ...);
202
203 /**
204  * @ingroup subst
205  * @brief get the actual value of a token parameter
206  * in your tmplputs or conditionals use this function to access parameters that can also be 
207  * retrieved from dynamic facilities:
208  *  _ -> Gettext; retrieve this token from the i18n facilities
209  *  : -> lookup a setting of that name
210  *  B -> bstr; an URL-Parameter
211  *  = -> subtemplate; parse a template by this name, and treat its content as this tokens value 
212  * 
213  * @param N which token do you want to lookup?
214  * @param Value reference to the string of the token; don't free me.
215  * @param len the length of Value
216  */
217 void GetTemplateTokenString(StrBuf *Target, 
218                             WCTemplputParams *TP,
219                             int N,
220                             const char **Value, 
221                             long *len);
222 /**
223  * @ingroup subst
224  * @return whether @ref GetTemplateTokenString would be able to give you a string
225  */
226 int HaveTemplateTokenString(StrBuf *Target, 
227                             WCTemplputParams *TP,
228                             int N,
229                             const char **Value, 
230                             long *len);
231
232
233
234 /**
235  * @ingroup subst
236  * @brief get the actual integer value of a token parameter
237  * in your tmplputs or conditionals use this function to access parameters that can also be 
238  * retrieved from dynamic facilities:
239  *  _ -> Gettext; retrieve this token from the i18n facilities
240  *  : -> lookup a setting of that name
241  *  B -> bstr; an URL-Parameter
242  *  = -> subtemplate; parse a template by this name, and treat its content as this tokens value 
243  * 
244  * @param N which token do you want to lookup?
245  * @param dflt default value to be retrieved if not found in preferences
246  * \returns the long value
247  */
248 long GetTemplateTokenNumber(StrBuf *Target, 
249                             WCTemplputParams *TP, 
250                             int N, long dflt);
251
252 /**
253  * @brief put a token value into the template
254  * use this function to append your strings into a Template. 
255  * it can escape your string according to the token at FormattypeIndex:
256  *  H: de-QP and utf8-ify
257  *  X: escapize for HTML
258  *  J: JSON Escapize
259  * @param Target the destination buffer
260  * @param TP the template token information
261  * @param Source string to append
262  * @param FormatTypeIndex which parameter contains the escaping functionality?
263  *        if this token doesn't have as much parameters, plain append is done.
264  */
265 void StrBufAppendTemplate(StrBuf *Target, 
266                           WCTemplputParams *TP,
267                           const StrBuf *Source, 
268                           int FormatTypeIndex);
269
270
271 #define RegisterNamespace(a, b, c, d, e, f) RegisterNS(a, sizeof(a)-1, b, c, d, e, f)
272 /**
273  * @ingroup subst
274  * @brief register a template token handler
275  * call this function in your InitModule_MODULENAME which will be called at the server start
276  * @param nMinArgs how much parameters does your token require at least?
277  * @param nMaxArgs how many parameters does your token accept?
278  * @param HandlerFunc your callback when the template is rendered and your token is there 
279  * @param PreEvalFunc is called when the template is parsed; you can do additional 
280  *        syntax checks here or pre-evaluate stuff for better performance
281  * @param ContextRequired if your token requires a specific context, else say CTX_NONE here.
282  */
283 void RegisterNS(const char *NSName, long len, 
284                 int nMinArgs, 
285                 int nMaxArgs, 
286                 WCHandlerFunc HandlerFunc,
287                 WCPreevalFunc PreEvalFunc,
288                 int ContextRequired);
289
290 /**
291  * @ingroup subst
292  * @brief register a conditional token <pair> handler
293  * call this function in your InitModule_MODULENAME which will be called at the server start
294  * conditionals can be ? or ! with a pair or % similar to an implicit if
295  * @param Name whats the name of your conditional? should start with COND:
296  * @param len the token length so we don't have to measure it.
297  * @param nParams how many parameters does your conditional need on top of the default conditional parameters
298  * @param CondF your Callback to be called when the template is evaluated at runtime; return 0 or 1 to us please.
299  * @param ContextRequired if your token requires a specific context, else say CTX_NONE here.
300  */
301 void RegisterConditional(const char *Name, long len, 
302                          int nParams,
303                          WCConditionalFunc CondF, 
304                          int ContextRequired);
305
306 /**
307  * @ingroup subst
308  * @brief register a string that will represent a long value
309  * this will allow to resolve <?...(#"Name")> to Value; that way 
310  * plain strings can be used an lexed in templates without having the 
311  * lookup overhead at runtime.
312  * @param Name The name of the define
313  * @param len length of Name
314  * @param Value the value to associate with Name
315  */
316 void RegisterTokenParamDefine(const char *Name, long len, 
317                               long Value);
318 /**
319  * teh r0x0r! forward your favourite define from C to the templates with one easy call!
320  */
321 #define REGISTERTokenParamDefine(a) RegisterTokenParamDefine(#a, sizeof(#a) - 1, a);
322
323 /**
324  * @ingroup subst
325  * @brief retrieve the long value of a registered string define
326  * @param Name The name of the define
327  * @param len length of Name
328  * @param Value the value to return if not found
329  */
330 long GetTokenDefine(const char *Name, 
331                     long len, 
332                     long DefValue);
333
334
335 #define IT_NOFLAG 0
336 #define IT_FLAG_DETECT_GROUPCHANGE (1<<0)
337 #define RegisterIterator(a, b, c, d, e, f, g, h, i) RegisterITERATOR(a, sizeof(a)-1, b, c, d, e, f, g, h, i)
338 void RegisterITERATOR(const char *Name, long len, /* Our identifier */
339                       int AdditionalParams,       /* doe we use more parameters? */
340                       HashList *StaticList,       /* pointer to webcit lifetime hashlists */
341                       RetrieveHashlistFunc GetHash, /* else retrieve the hashlist by calling this function */
342                       SubTemplFunc DoSubTempl,       /* call this function on each iteration for svput & friends */
343                       HashDestructorFunc Destructor, /* use this function to shut down the hash; NULL if its a reference */
344                       CtxType ContextType,               /* which context do we provide to the subtemplate? */
345                       CtxType XPectContextType,          /* which context do we expct to be called in? */
346                       int Flags);
347
348
349
350 void StackContext(WCTemplputParams *Super, 
351                   WCTemplputParams *Sub, 
352                   void *Context,
353                   CtxType ContextType,
354                   int nArgs,
355                   WCTemplateToken *Tokens);
356
357 void UnStackContext(WCTemplputParams *Sub);
358
359
360
361 CompareFunc RetrieveSort(WCTemplputParams *TP, 
362                          const char *OtherPrefix, long OtherPrefixLen,  
363                          const char *Default, long ldefault, 
364                          long DefaultDirection);
365 void RegisterSortFunc(const char *name, long len, 
366                       const char *prepend, long preplen,
367                       CompareFunc Forward, 
368                       CompareFunc Reverse, 
369                       CompareFunc GroupChange, 
370                       CtxType ContextType);
371
372 void dbg_print_longvector(long *LongVector);
373
374 #define do_template(a) DoTemplate(a, sizeof(a) -1, NULL, &NoCtx)
375 const StrBuf *DoTemplate(const char *templatename, long len, StrBuf *Target, WCTemplputParams *TP);
376 void url_do_template(void);
377
378
379 int CompareSubstToToken(TemplateParam *ParamToCompare, TemplateParam *ParamToLookup);
380 int CompareSubstToStrBuf(StrBuf *Compare, TemplateParam *ParamToLookup);