File: CGI.k

package info (click to toggle)
kaya 0.4.2-4
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 4,448 kB
  • ctags: 1,694
  • sloc: cpp: 9,536; haskell: 7,461; sh: 3,013; yacc: 910; makefile: 816; perl: 90
file content (760 lines) | stat: -rw-r--r-- 29,741 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
/** -*-C-*-ish
    Kaya standard library
    Copyright (C) 2004, 2005 Edwin Brady

    This file is distributed under the terms of the GNU Lesser General
    Public Licence. See COPYING for licence.
*/

"<summary>Simple CGI application interface</summary>
<prose>This module provides a simple low-level CGI application interface, for development of small web applications and prototypes. For larger web applications, the <moduleref>Webapp</moduleref> module may be more suitable due to tighter integration with <moduleref>HTMLDocument</moduleref>.</prose>
<prose>This module now includes experimental support for AJAX programming. These functions are likely to change in future releases.</prose>"
module CGI;

import Prelude;
import System;
import Strings;
import Crypto;
import Regex;
import IO;
import public WebCommon;

type HTML = String;

globals {
    [HTML] pagecontent = [];
    [String] headers = [];
    Bool headersdone = false;
    // list of pairs rather than a dict because we look up both ways
    [(String, String)] shortURLs = [];
    [(Char,String)] esctable;
}

"<summary>Unrecognised variable</summary>
<prose>This Exception is thrown by <functionref>httpGetVar</functionref> and others when the variable requested was not submitted by the browser.</prose>"
Exception UnrecognisedVariable(String err);
"<summary>Illegal handler</summary>
<prose>This exception is thrown when an illegal handler is used.</prose>"
Exception IllegalHandler();
"<summary>Unexpected type</summary>
<prose>This exception is thrown when an incoming variable is not of the expected type.</prose>"
Exception UnexpectedType(String err, String ty, String variable);
"<summary>Variable outside expected range</summary>
<prose>This exception is thrown when an incoming variable is outside the expected range.</prose>"
Exception ValueOutOfRange();
"<argument name='h'>The bad header</argument>
<summary>Malformed HTTP header</summary>
<prose>The HTTP header is not valid. Only a limited set of characters are permitted.</prose>"
Exception BadHeader(String h);

"<summary>Events to be handled by Ajax actions</summary>
<prose>Events which may be handled by an XMLHttpRequest</prose>"
public data AjaxEvent 
    = OnAbort | OnBlur | OnChange | OnClick | OnDblClick 
    | OnError | OnFocus | OnKeyDown | OnKeyPress | OnKeyUp 
    | OnLoad | OnMouseDown | OnMouseMove | OnMouseOut
    | OnMouseOver | OnMouseUp | OnReset | OnResize | OnSelect
    | OnSubmit | OnUnload;

"<summary>Ajax data requests</summary>
<prose>Methods for requesting additional data for ajax commands, e.g.
retrieving the value of an element in the DOM or event data.
</prose>"
public data AjaxData
   = JSValue(String js)
   | ThisValue
   | Data(String val)
   | InputValue(String id)
   | InnerHTML(String htmlId);

"<summary>Ajax action to take when an event occurs</summary>
<prose>Either run a kaya function on the server, run some generic javascript,
or update a form value</prose>"
public data AjaxAction
   = KayaFunction(Void() fn)
   | JSAction(String js)
   | Update(String, AjaxData jsvalue)
   | UpdateValue(String, String value)
   | Actions([AjaxAction] acts);

String jsAjaxData(AjaxData d) {
  case d of {
      JSValue(s) -> return s;
      | ThisValue -> return "this.value";
      | Data(s) -> return "'"+s+"'";
      | InputValue(id) -> return "document.getElementById('"+id+"').value";
      | InnerHTML(id) -> return "document.getElementById('"+id+"').innerHTML";
  };
}
 
String jsAjaxEvent(AjaxEvent h) =
  case h of {
      OnAbort -> "onabort";
    | OnBlur -> "onblur";
    | OnChange -> "onchange";
    | OnClick -> "onclick";
    | OnDblClick -> "ondblclick";
    | OnError -> "onerror";
    | OnFocus -> "onfocus";
    | OnKeyDown  -> "onkeydown";
    | OnKeyPress -> "onkeyup";
    | OnKeyUp -> "onkeyup";
    | OnLoad -> "onload";
    | OnMouseDown -> "onmousedown";
    | OnMouseMove -> "onmousemove";
    | OnMouseOut -> "onmouseout";
    | OnMouseOver -> "onmouseover";
    | OnMouseUp -> "onmouseup";
    | OnReset -> "onreset";
    | OnResize -> "onresize";
    | OnSelect -> "onselect";
    | OnSubmit -> "onselect";
    | OnUnload -> "onunload";
  };

"<summary>Get additional data sent to an Ajax request</summary>
<prose>Get additional data sent to an Ajax request</prose>"
public [String] getAjaxData() {
    dat = incomingValue("kaya_jsdata", DataRequest);
    vals = split(",", dat, 0, true);
    return vals;
}

"<summary>Some basic javascript for handling Ajax calls</summary>
<prose>This needs to be added as content by any application intending
to use Ajax features.</prose>"
public HTML ajaxHeader = 
"<script type=\"text/javascript\">
function kayaRunHandler(url,result,extradata) {
  var xmlHttp;
  try {
    xmlHttp=new XMLHttpRequest();
  }
  catch (e) {
    try {
      xmlHttp=new ActiveXObject(\"Msxml2.XMLHTTP\");
    } catch (e) {
      try {
        xmlHttp=new ActiveXObject(\"Microsoft.XMLHTTP\");
      }
      catch (e) {
        // This is never going to work, silently fail.
        return false;
      }
    }
  }

  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState==4) {
      document.getElementById(result).innerHTML=xmlHttp.responseText; 
    }
  }  
  xmlHttp.open(\"GET\",url+\";kaya_jsdata=\"+extradata,true);
  xmlHttp.send(null);
}
</script>";

"<summary>Add a HTTP header</summary>
<prose>Add a new HTTP header to the output.</prose>
<example>header(\"Content-type: text/html; charset=UTF-8\")</example>
<related><functionref>flushHeaders</functionref></related>"
public Void header(String h)
{
    push(headers, h);
}

"<summary>Get tag information for linking an ajax call to an event on a tag</summary>
<prose>
When the event <variable>h</variable>
occurs on the tag, apply the action and if applicable updates the contents 
of the tag 
with id <variable>resultID</variable> with the result of the handler.
</prose>
<example>
content(\"<h1 \"+ajaxTag(\"header\", OnClick, updateHeader, 0, \"header\")+\">Title</h1>\");
</example>"
public String ajaxTag(AjaxEvent h, AjaxAction act, String resultID = "",
		      [AjaxData] extras = []) 
{
    return jsAjaxEvent(h)+"=\"" + ajaxTagData(act, resultID, extras) + "\"";
}

public String ajaxTagData(AjaxAction act, 
			  String resultID = "", [AjaxData] extras = []) 
{
    case act of {
	KayaFunction(fn) ->
	    ext = "var ext = ''; ";
	    for extra@i in extras {
		ext += "ext = ext.concat(encodeURIComponent(" + jsAjaxData(extra) +")); ";
		if (i<size(extras)-1) {
		    ext += "ext = ext.concat(',');";
		}
	    }
	    return ext + " kayaRunHandler('" +
		linkURL(kHandler@(@fn), 0, [], false) + "', '" + resultID + "', ext);";
      | JSAction(jsact) -> return jsact+";";
      | UpdateValue(fld,val) -> return "document.getElementById('"+fld+"').value='"+val+"';";
      | Update(fld, js) -> return "document.getElementById('"+fld+"').value="+jsAjaxData(js)+";";
      | Actions(acts) ->
	    action = "";
	    for act in acts {
		action+=ajaxTagData(act,resultID,extras);
	    }
	    action += "\"";
	    return action;
    }
}

Void kHandler(Void() fn, Int dummy) {
    fn();
}

"<summary>Add new content</summary>
<prose>Add some content to the page. Because of the nature of the CGI interface, this must be used instead of <functionref>Prelude::putStr</functionref>.</prose>
<related><functionref>flushContent</functionref></related>"
public Void content(HTML c)
{
    push(pagecontent, c);
}

String encodeChar(Char x) {
    if (x==' ') { return "+"; }
    if (Int(x)>127 || isPunct(x))
/*	(x `elem` ['!','&','$','+',',','/',':',';','=','?','@',
		  '"','<','>','#','%','{','}','|','\\','^',
		  '~','[',']','`']))*/
    {
	return "%"+stringBase(Int(x),16);
    }
    return String(x);
}



"<summary>Output headers. </summary>
<prose>Output the HTTP headers. Outputs a Content-type:text/html header if none has been given. This only works once; after outputting the headers, only content can be added.</prose>
<related><functionref>flushAll</functionref></related>
<related><functionref>header</functionref></related>"
public Void flushHeaders()
{
    contenttype = false;
    if (!headersdone) {
	for h in headers {
	  validheader = compile("^[^()<>@,;:\\\"/[\\]?={}[:cntrl:]\r\n]+:[^[:cntrl:]\r\n]+$");
	  if (quickMatch(validheader,h)) {

	    putStrLn(h);
	    if (substr(h,0,12)=="Content-type") {
		contenttype=true;
	    }
	  } else {
	    throw(BadHeader(h));
	  }
	}
	// If we haven't had a Content-type header, output the default one.
	if (!contenttype) {
	    putStrLn("Content-type: text/html;charset=UTF-8");
	}
	putStrLn("");
	headersdone = true;
    }
//    print "Flushing headers";
}

"<summary>Output the content. </summary>
<prose>Output the content. If <functionref>flushHeaders</functionref> has not been called, it will be called before the first use of this function. The web server (and indeed any intermediate proxies) are under no obligation to send this content to the browser immediately.</prose>
<related><functionref>content</functionref></related>
<related><functionref>flushAll</functionref></related>"
public Void flushContent()
{
    flushHeaders();
//    print "Flushing content "+String(size(pagecontent));
    for c in pagecontent {
	putStrLn(c);
    }
    pagecontent = [];
}

"<argument name='str'>The string (a regular expression) to replace</argument>
<argument name='new'>The replacement</argument>
<summary>Replace a string in the current output.</summary>
<prose>Replaces <variable>str</variable> with <variable>new</variable> 
wherever it occurs in the headers or content. This only affects content that has not yet been flushed to the user.</prose>"
public Void replaceContent(HTML str, HTML new)
{
    for h in headers {
	replace(str,new,h,[Global]);
    }
    newc = [];
    for c in pagecontent {
	replace(str,new,c,[Global]);
	push(newc,c);
    }
    pagecontent = newc;
}

"<summary>Output all headers and content. </summary>
<prose>Output all headers and content. This need not be called by the user, as it is done automatically at the end of a CGI's execution. It may be useful for debugging purposes, however.</prose>"
public Void flushAll()
{
    flushContent();
//    print "Flushing ";
}

"<argument name='name'>The cookie name</argument>
<argument name='value'>The cookie value</argument>
<summary>Set a cookie</summary>
<prose>Set a cookie. This must be called before <functionref>flushHeaders</functionref> to have any effect. Remember that cookies are <emphasis>not</emphasis> available to the script that sets them.</prose>
<prose>For more flexible setting of cookies, use <functionref>WebCommon::setCookie</functionref> instead.</prose>"
public Void setCookie(String name,String value)
{
    header("Set-Cookie: "+name+"="+urlEncode(value));
}

"<argument name='v'>The variable name</argument>
<summary>Return the integer in a GET/POST variable.</summary>
<prose>Return the integer value of a GET or POST variable. An exception is thrown if the variable is not a valid integer.</prose>
<related><functionref>httpFloat</functionref></related>"
public Int httpInt(String v)
{
    x = incomingValue(v,DataRequest);
    if (quickMatch("^[+-]?[0-9]*$", x)) {
	return Int(x);
    } else {
	throw(UnexpectedType(x, "Integer", v));
    }
}

"<argument name='v'>The variable name</argument>
<summary>Return the floating-point number in a GET/POST variable.</summary>
<prose>Return the floating-point value of a GET or POST variable. An exception is thrown if the variable is not a valid Float.</prose>
<related><functionref>httpInt</functionref></related>"
public Float httpFloat(String v)
{
    x = incomingValue(v,DataRequest);
    // FIXME: This isn't quite right, but it'll do for now.
    if (quickMatch("[0-9]*\.?[0-9]*e?[+-][0-9]*", x)) {
	return Float(x);
    } else {
	throw(UnexpectedType(x,"Float",v));
    }
}

"<argument name='text'>The button's label</argument>
<summary>Create a submit button.</summary>
<prose>Returns a string of HTML to create a submit button for a form.
<variable>extra</variable> contains any extra attributes needed.
</prose>
<example>content(submit(\"Submit\"));</example>"
public HTML submit(String text, String id ="", String extra = "")
{
    submitname = "kaya_submit";
    if (id!="") { idtext = "id=\""+id+"\" "; }
    return "<input type=\"submit\" value=\""+text+"\" name=\"" + 
	    submitname + " " + idtext + extra + "\">";
}

"<argument name='text'>The button's label</argument>
<summary>Create a reset button.</summary>
<prose>Returns a string of HTML to create a reset button for a form.</prose>
<example>content(reset(\"Reset form\"));</example>"
public HTML reset(String text, String id = "", String extra="") {
    if (id!="") { idtext = "id=\""+id+"\" "; }
    return "<input type=\"reset\" value=\""+text+"\" "+ idtext + extra +">";
}

"<summary>Get the last submit button</summary>
<prose>Returns the label of the submit button used to submit the form currently
being processed (or throws an Exception if no form is being processed).</prose>"
public String submitUsed = incomingValue("kaya_submit",DataRequest);

String scriptName() {
    nms = Regex::split("\/",progName());
    return nms[size(nms)-1];
}

"<argument name='fn'>The handler function</argument>
<argument name='dat'>Data to pass to the handler function</argument>
<argument name='prepost'>Whether to run the <code>PreContent</code> and <code>PostContent</code> functions after submitting the form. This defaults to true, but may be useful to disable if the form results are not HTML.</argument> 
<summary>Set up a form.</summary>
<prose>Set up a form, which when submitted calls <code><variable>fn</variable>(<variable>dat</variable>)</code>.</prose>"
public HTML formHandler(Void(a) fn, a dat, Bool prepost = true)
{
    str = "<form action=\""+ scriptName()+"\" method=\"POST\">\n";
    str += "<input type=\"hidden\" name=\"kaya_function\" value=\""+
	encode(marshal(fn,888))+"\">\n";
    str += "<input type=\"hidden\" name=\"kaya_arg\" value=\""+
	encode(marshal(dat,fnid(fn)))+"\">";
    if (!prepost) {
	str += "<input type=\"hidden\" name=\"kaya_prepost\" value=\""+
	    encode(marshal(prepost,0))+"\">";
    }
    return str;
}

"<argument name='fn'>The handler function</argument>
<argument name='dat'>Data to pass to the handler function</argument>
<argument name='prepost'>Whether to run the <code>PreContent</code> and <code>PostContent</code> functions after submitting the form. This defaults to true, but may be useful to disable if the form results are not HTML.</argument> 
<summary>Set up a file upload form.</summary>
<prose>Set up a form capable of uploading files, which when submitted calls <code><variable>fn</variable>(<variable>dat</variable>)</code>.</prose>
<prose>You will need to call <functionref>WebCommon::allowFileUploads</functionref> in your <code>webconfig</code> function to allow file uploads to be processed.</prose>
<related><functionref>uploadButton</functionref></related>"
public HTML fileFormHandler(Void(a) fn, a dat, Bool prepost = true)
{
    str = "<form enctype=\"multipart/form-data\" action=\""+ 
	scriptName()+"\" method=\"POST\">\n";
//    str += "<input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\""+maxsize+
//	"\">";
    str += "<input type=\"hidden\" name=\"kaya_function\" value=\""+
	encode(String(fnid(fn)))+"\">\n";
    str += "<input type=\"hidden\" name=\"kaya_arg\" value=\""+
	encode(marshal(dat,fnid(fn)))+"\">";
    if (!prepost) {
	str += "<input type=\"hidden\" name=\"kaya_prepost\" value=\""+
	    encode(marshal(prepost,0))+"\">";
    }
    return str;
}


"<argument name='name'>The file upload's name</argument>
<summary>Create a file upload field.</summary>
<prose>Returns a string of HTML to create a file upload field for a form.</prose>
<example>content(uploadButton(\"image\"));</example>"
public HTML uploadButton(String name, String id = "", String extra = "") {
    if (id!="") { idtext = "id=\""+id+"\" "; }
    return "<input name=\""+name+"\" type=\"file\" " + idtext + extra + ">";
}


// Helper for linkHandler.
String handlerQuery(Void(a) fn, a dat, Bool prepost) {
    str = "kaya_function="+urlEncode(encode(marshal(fn,888)));
    str += ";kaya_arg="+urlEncode(encode(marshal(dat,fnid(fn))));
    if (!prepost) {
	str += ";kaya_prepost="+urlEncode(encode(marshal(prepost,0)));
    }

    return str;
}

public HTML linkURL(Void(a) fn, a dat,
		    [(String,String)] others = [], Bool prepost = true) 
{
    hq = handlerQuery(fn,dat,prepost);

    for x in shortURLs {
	if (x.snd == hq) {
	    hq = x.fst;
	}
    }

    url = "?"+hq;
    for o in others {
	url = url + ";" + o.fst + "=" + o.snd;
    }
    return url;
}

"<argument name='fn'>The handler function</argument>
<argument name='dat'>Data to pass to the handler function</argument>
<argument name='inf'>The link text</argument>
<argument name='others'>A list of name-value pairs of additional variables to add in the link, defaulting to the empty list.</argument>
<argument name='prepost'>Whether to run the <code>PreContent</code> and <code>PostContent</code> functions after submitting the form. This defaults to true, but may be useful to disable if the form results are not HTML.</argument> 
<summary>Create a hyperlink.</summary>
<prose>Return the HTML for a hyperlink, which when followed calls <code><variable>fn</variable>(<variable>dat</variable>)</code>.</prose>"
public HTML linkHandler(Void(a) fn, a dat, String inf, 
			  [(String,String)] others = [], Bool prepost = true) 
{
    return "<a href=\""+scriptName()+linkURL(fn,dat,others,prepost)+"\">"+inf+"</a>";
}

"<argument name='shortName'>The short handler name</argument>
<argument name='fn'>The handler function</argument>
<argument name='dat'>Data to pass to the handler function</argument>
<argument name='prepost'>Whether to run the <code>PreContent</code> and <code>PostContent</code> functions after submitting the form. This defaults to true, but may be useful to disable if the form results are not HTML.</argument> 
<summary>Register a handler to get a short URL</summary>
<prose>Register a handler to get a short URL. If the same <variable>fn</variable>, <variable>dat</variable> and <variable>prepost</variable> settings are later used by <functionref>linkHandler</functionref>, the long string of encrypted state information will be replaced by a short handler string.</prose>"
public Void addHandler(String shortName, Void(a) fn, a dat, 
		       Bool prepost = true) 
{
    push(shortURLs, (shortName, handlerQuery(fn, dat, prepost)));
}

"<argument name='shortName'>The short name to look up</argument>
<summary>Look up a short name to get a fully expanded query string.</summary>
<prose>This function looks up a short name to get the fully expanded query string, returning the full string, or an empty string if no expansion is available.</prose>"
public String expandQuery(String shortName) {
    re = compile(r"\&");
    case match(re, shortName) of {
	noMatch -> rest = "";
	| matches(m,before,after) -> shortName = before; rest = "&"+after;
    }
    for x in shortURLs {
	if (x.fst == shortName) {
	    return x.snd + rest;
	}
    }
    return ""; // Not expandable
}

"<argument name='fn'>The image generating function</argument>
<argument name='dat'>A parameter for the image generating function</argument>
<argument name='alt'>The alternative text for the image</argument>
<argument name='width'>The width of the image in pixels (optional)</argument>
<argument name='height'>The height of the image in pixels (optional, but must be specified if width is specified)</argument>
<argument name='attribs'>Additional image attributes (e.g. <input>\"title='Graph 1' id='gr1'\"</input>) (this value is not filtered in any way, and so user-supplied data should not be used here).</argument>
<summary>Embed an image.</summary>
<prose>Return the HTML to add an image to a page, where the image is generated by one of the functions in the CGI application.</prose>
<related><moduleref>Image</moduleref></related>"
public HTML imageHandler(Void(a) fn, a dat, String alt, 
			 Int width = -1, Int height =-1, String attribs="")
{
    url = scriptName()+"?"+handlerQuery(fn,dat,false);
    if (width!=-1) {
	size = "width="+width+" height="+height;
    }
    else {
	size = "";
    }
    return "<img src=\""+url+"\" alt=\""+alt+"\" "+size+" "+attribs+">";
}

"<argument name='inf'>Link text</argument>
<summary>Link to the default function.</summary>
<prose>Return the HTML for a hyperlink that when followed calls the default function.</prose>"
public HTML goDefault(String inf)
{
    url = scriptName();
    return "<a href=\""+url+"\">"+inf+"</a>";
}

"<argument name='httpvar'>The variable name</argument>
<argument name='value'>The variable value</argument>
<summary>Pass a variable to a form.</summary>
<prose>Pass a variable to a form. This returns the HTML for a hidden input field. Note that neither parameter is escaped by this function, so you must ensure that neither contains a '\"' character yourself.</prose>"
public HTML passVar(String httpvar, String value)
{
    return "<input type=\"hidden\" name=\""+httpvar+"\" value=\""+value+"\">";
}

"<argument name='name'>The variable name</argument>
<argument name='value'>The variable value</argument>
<argument name='len'>The suggested size of the input field</argument>
<summary>Create a text input field.</summary>
<prose>Returns the HTML for a text input field. Note that neither the <variable>name</variable> nor the <variable>value</variable> parameter is escaped by this function, so you must ensure that neither contains a '\"' character yourself.</prose>"
public HTML textBox(String name, String value="", Int len = 20, 
		    String id = "", String extra = "")
{
    if (id!="") { idtext = "id=\""+id+"\" "; }
    return "<input type=\"text\" size="+String(len)+" name=\""+name+"\" value=\""+value+"\" " + idtext + extra + ">";
}

"<argument name='name'>The variable name</argument>
<argument name='value'>The variable value</argument>
<argument name='len'>The suggested size of the input field</argument>
<summary>Create a text area input field.</summary>
<prose>Returns the HTML for a text area input field. Note that neither the <variable>name</variable> nor the <variable>value</variable> parameter is escaped by this function, so you must ensure that neither contains a '\"' character yourself.</prose>"
public HTML textArea(String name, Int width, Int height,
		     String value="",
		     String id = "", String extra = "")
{
    if (id!="") { idtext = "id=\""+id+"\" "; }
    return "<textarea cols="+String(width)+" rows="+String(height)+" name=\""+name+"\" " + idtext + extra + ">"+value+"</textarea>";
}

"<argument name='name'>The variable name</argument>
<argument name='len'>The suggested size of the input field</argument>
<summary>Create a password input field.</summary>
<prose>Returns the HTML for a password input field. Note that the <variable>name</variable> parameter is not escaped by this function, so you must ensure that it contains no '\"' characters yourself.</prose>"
public HTML passwordBox(String name, Int len = 20, String id = "", 
			String extra = "")
{
    if (id!="") { idtext = "id=\""+id+"\" "; }
    return "<input type=\"password\" size="+String(len)+" name=\""+name+"\" " + idtext + extra + ">";
}

"<argument name='name'>The name of the selector</argument>
<argument name='len'>The size of the selector (use 0 for a drop-down selection box)</argument>
<argument name='opts'>The options for the selector</argument>
<argument name='def'>The default option</argument>
<summary>Create a selection box.</summary>
<prose>Returns the HTML for a selection box. Note that none of the input values are escaped, so you must ensure that <variable>name</variable> contains no '\"' characters, and <variable>opts</variable> contains no values containing '&lt;' characters.</prose>"
public HTML selBox(String name, Int len, [String] opts, String def = "", 
		   String id = "", String extra = "")
{
    if (id!="") { idtext = "id=\""+id+"\" "; }
    str = "<select name=\""+name+"\" size="+ String(len)+" " + 
	   idtext + extra + ">";
    for entry in opts {
	if (entry==def) {
	    str+="<option selected>";
	}
	else {
	    str+="<option>";
	}
	str+=entry+"</option>";
    }
    str+="</select>";
    return str;
}

"<argument name='name'>The name of the checkbox</argument>
<argument name='def'>If this is true, the checkbox will start checked.</argument>
<summary>Make a checkbox.</summary>
<prose>Returns the HTML for a checkbox.</prose>
<related><functionref>checked</functionref></related>"
public HTML checkBox(String name,Bool def = false, String id = "",
		     String extra = "")
{
    if (id!="") { idtext = "id=\""+id+"\" "; }
    str = "<input type=\"checkbox\" name=\""+name+"\" " + idtext + extra + " ";
    if (def) str+="checked>"; else str+=">";
    return str;
}

"<argument name='name'>The checkbox name</argument>
<summary>Return whether a checkbox was checked.</summary>
<prose>Return whether a checkbox was checked in the previous form submission.</prose>
<related><functionref>checkBox</functionref></related>"
public Bool checked(String name) 
{
    return incomingExists(name,DataRequest);
}

"<argument name='name'>The name of the radio button. Only one radio button with a given name may be selected at once</argument>
<argument name='val'>The value of the radio button.</argument>
<argument name='set'>If this is true, the radio button will start checked. Browser behaviour is undefined unless exactly one radio button out of each set begins checked.</argument>
<summary>Make a radio button.</summary>
<prose>Returns the HTML for a radio button. Note that neither the <variable>name</variable> nor the <variable>value</variable> parameter is escaped by this function, so you must ensure that neither contains a '\"' character yourself.</prose>"
public HTML radio(String name, String val, Bool set = false, String id = "",
		  String extra = "")
{
    if (id!="") { idtext = "id=\""+id+"\" "; }
    str = "<input type=\"radio\" name=\""+name+"\" value=\""+val+"\" " + 
	  idtext + extra + " ";
    if (set) str+="checked>"; else str+=">";
    return str;
}

"<summary>End a form</summary>
<prose>Returns the HTML to close the currently open form.</prose>"
public HTML closeForm()
{
    return "</form>";
}

"<argument name='titles'>A list of strings, corresponding to the column headers from left to right</argument>
<argument name='rows'>A list of rows, each row being a list of strings. Rows are added to the table top to bottom, with each row being added left to right.</argument>
<argument name='tableattribs'>The attributes for the table as a whole, for example <input>\"class='numericdata' title='Table 1.2'\"</input></argument>
<argument name='headattribs'>Any attributes to apply to all table header cells.</argument> 
<argument name='dataattribs'>Any attributes to apply to all table data cells.</argument>
<summary>Output a table.</summary>
<prose>Returns the HTML for a table</prose>"
public HTML table([String] titles, [[String]] rows, 
		    String tableattribs="",
		    String headattribs="",
		    String dataattribs="")
{
    str = "<table "+tableattribs+">";
    if (titles!=[]) {
	str+=tablerow("th",headattribs, titles)+"\n";
    }

    for row in rows {
	str+=tablerow("td",dataattribs, row)+"\n";
    }

    return str+"</table>";
}

String tablerow(String tag,String attribs,[String] stuff)
{
    str = "";
    str += "<tr>";
    for t in stuff {
	str+="<"+tag+" "+attribs+">"+t+"</"+tag+">";
    }
    str += "</tr>";
    return str;
}

/*
Void webappMain(Void() headerfn, Void() defaultfn, Void() footerfn)
{
    foreign Void storeHTTPargs();
    try {
	dfun = httparg("kaya_function");
	darg = httparg("kaya_arg");

	id = Int(decode(dfun));
...
    }
    catch(e) {
	defaultfn();
    }
}*/

String htmlEncodeChar(Char x) {
    if (size(esctable)==0) {
	esctable = [('&',"&amp;"),
		    ('<',"&lt;"),
		    ('>',"&gt;"),
		    (Char(163),"&pound;")];
    }

    for p in esctable {
	if (x==p.fst)
	    return p.snd;
    }
    return String(x);
}

"<argument name='x'>The un-encoded string</argument>
<summary>Encodes HTML special chars.</summary>
<prose>Converts '&amp;', '&lt;' and '>' to '&amp;amp;', '&amp;lt;' and '&amp;gt;'. It does not convert '\"' to '&amp;quot;', which you will need to do manually for function attribute values.</prose>"
public String htmlEscape(String x)
{
    str = x;
    current = "";
    while(str!="") {
	c = head(str);
	str = tail(str);
	current += htmlEncodeChar(c);
    }
    return current;
}

/// Safe cast functions

"<argument name='x'>The string to convert</argument>
<argument name='min'>The minimum value</argument>
<argument name='max'>The maximum value</argument>
<summary>Convert a string to an Int.</summary>
<prose>Convert a string to an Int, throwing an Exception if the resulting Int
is out of the specified range.</prose>
<related><functionref>safeFloat</functionref></related>"
public Int safeInt(String x, Int min, Int max)
{
    num = Int(x);
    if (num<min || num>max) {
        throw(ValueOutOfRange);
    }
    return num;
} 

"<argument name='x'>The string to convert</argument>
<argument name='min'>The minimum value</argument>
<argument name='max'>The maximum value</argument>
<summary>Convert a string to a Float.</summary>
<prose>Convert a string to a Float, throwing an Exception if the resulting Float is out of the specified range (note that due to floating-point inaccuracies, values very close to the minimum or maximum value may be incorrectly rejected or accepted).</prose>
<related><functionref>safeInt</functionref></related>"
public Float safeFloat(String x, Float min, Float max)
{
    num = Float(x);
    if (num<min || num>max) {
	throw(ValueOutOfRange);
    }
    return num;
}