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
|
/** -*-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.
*/
module Webapp;
import Prelude;
import System;
import Strings;
import Crypto;
import Regex;
import IO;
import WebCommon;
type HTML = String;
globals {
[HTML] pagecontent;
[String] headers;
Bool headersdone;
[(String,String)] queryVars;
[(String,String)] postVars;
[(String,String)] cookies;
[(Char,String)] esctable;
}
public Exception UnrecognisedVariable(String err) = Exception(err,520);
public Exception IllegalHandler = Exception("Illegal handler called",521);
public Exception UnexpectedType(String err) = Exception(err,522);
public Exception OutOfRange = Exception("Value out of range",523);
"Add a header."
public Void header(String h)
{
push(headers, h);
}
"Add some content"
public Void content(HTML c)
{
push(pagecontent, c);
}
"Initialise the web app.
Automatically run if the program is declared to be a webapp."
public Void initWebApp()
{
headers = [];
pagecontent = [];
headersdone = false;
initVars();
}
String encodeChar(Char x) {
if (x==' ') { return "+"; }
if (Int(x)>127 || isPunctuation(x))
/* (x `elem` ['!','&','$','+',',','/',':',';','=','?','@',
'"','<','>','#','%','{','}','|','\\','^',
'~','[',']','`']))*/
{
return "%"+stringBase(Int(x),16);
}
return String(x);
}
[(String,String)] parseVars(String vars, String delim)
{
varlist = Regex::split(delim,vars);
pairs = [];
for v in varlist {
// left = right, urldecode the thing
def = Regex::split("=",v);
push(pairs,(urlDecode(def[0]),urlDecode(def[1])));
}
return pairs;
}
"Return the value of a GET var"
public String httpGetVar(String x) {
for v in queryVars {
if (v.fst==x) return v.snd;
}
throw(UnrecognisedVariable(x+" is not a GET variable"));
}
"Return the value of a POST var"
public String httpPostVar(String x) {
for v in postVars {
if (v.fst==x) return v.snd;
}
throw(UnrecognisedVariable(x+" is not a POST variable"));
}
"Return the value of a GET/POST var.
Returns POST vars as preference, if a variable is defined in both."
public String httpVar(String x) {
for v in postVars {
if (v.fst==x) return v.snd;
}
for v in queryVars {
if (v.fst==x) return v.snd;
}
return "";
}
"Return the value of a cookie.
Checks that the cookie is set, and throws an Exception if not"
public String cookie(String x) {
for v in cookies {
if (v.fst==x) return v.snd;
}
throw(UnrecognisedVariable(x+" is not a cookie"));
}
Void initVars()
{
query = getEnv("QUERY_STRING");
cookie = getEnv("HTTP_COOKIE");
len = Int(getEnv("CONTENT_LENGTH"));
postvars = "";
for x in [1..len] {
postvars += getChar(stdin);
}
queryVars = parseVars(query,"&");
postVars = parseVars(postvars,"&");
cookies = parseVars(cookie,"; ");
}
"Output 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."
public Void flushHeaders()
{
contenttype = false;
if (!headersdone) {
for h in headers {
putStrLn(h);
if (substr(h,0,12)=="Content-type") {
contenttype=true;
}
}
// 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";
}
"Output the content.
This only makes sense with headers, so output them first."
public Void flushContent()
{
flushHeaders();
// print "Flushing content "+String(size(pagecontent));
for c in pagecontent {
putStrLn(c);
}
pagecontent = [];
}
"Replace a string in the current output.
Replaces <em>str</em> in <em>new</em>
wherever it occurs in the headers/content."
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;
}
"Output all headers and content.
This need not be called by the user, as it is done automatically at the end of
a webapp's execution. It may be useful for debugging purposes, however."
public Void flush()
{
flushContent();
// print "Flushing ";
}
"Set a cookie"
public Void setCookie(String name,String value)
{
header("Set-Cookie: "+name+"="+urlEncode(value));
}
"Return the integer in a GET/POST variable.
Throws an exception if it's not a valid integer."
public Int httpInt(String v)
{
x = httpVar(v);
if (quickMatch("^[+-]?[0-9]*$", x)) {
return Int(x);
} else {
throw(UnexpectedType(x+" is not an integer in http variable "+v));
}
}
"Return the float in a GET/POST variable.
Throws an exception if it's not a valid float."
public Float httpFloat(String v)
{
x = httpVar(v);
// 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+" is not a float in http variable "+v));
}
}
"Create a submit button.
The String return is HTML to create the button. Typical usage is:<br>
<code>content(submit(\"Submit\")</code>"
public HTML submit(String text)
{
submitname = "kaya_submit";
return "<input type=\"submit\" value=\""+text+"\" name=\"" +
submitname +"\">";
}
"Create a reset button.
The String return is HTML to create the button. Typical usage is:<br>
<code>content(reset(\"Reset\")</code>"
public HTML reset(String text) = "<input type=\"reset\" value=\""+text+"\">";
"
Returns the text on the submit button used to submit the form currently
being processed."
public String submitUsed = httpVar("kaya_submit");
String scriptName() {
nms = Regex::split("\/",progName());
return nms[size(nms)-1];
}
"Set up a form.
The <em>fn</em> is a function used to process the form.
When processing the
form, <em>fn</em> is passed the value <em>dat</em>.
<em>prepost</em> determines whether <em>PreContent</em> and
<em>PostContent</em> are called for this link. Default is to call them, but
it can be useful to turn it off if the content type of the link is not
text/html."
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;
}
"Set up a file upload form.
NOTE: Still in development. This doesn't work yet, and the interface
will probably change."
public HTML fileFormHandler(Void(a) fn, a dat, Int maxsize,
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;
}
public HTML uploadButton(String name)
= "<input name=\""+name+"\" type=\"file\">";
// 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;
}
"
Set up a link, handled by the function <em>fn</em>.
When processing the
link, <em>fn</em> is passed the value <em>dat</em>.
<em>inf</em> is the link text.
<em>others</em> is a list of pairs of variables and values to be
passed through the query string.
<em>prepost</em> determines whether <em>PreContent</em> and
<em>PostContent</em> are called for this link. Default is to call them, but
it can be useful to turn it off if the content type of the link is not
text/html."
public HTML linkHandler(Void(a) fn, a dat, String inf,
[(String,String)] others = [], Bool prepost = true)
{
url = scriptName()+"?"+handlerQuery(fn,dat,prepost);
for o in others {
url = url + "&" + o.fst + "=" + o.snd;
}
return "<a href=\""+url+"\">"+inf+"</a>";
}
"Embed an image.
<em>fn</em> is the function which generates the image, and is passed the
value <em>dat</em>. <em>alt</em> is the (required!) ALT text.
<em>width</em> and <em>height</em> can be given optionally, as can
a list of other attributes."
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+">";
}
"Link to the default function."
public HTML goDefault(String inf)
{
url = scriptName();
return "<a href=\""+url+"\">"+inf+"</a>";
}
"Pass a variable to a form."
public HTML passVar(String httpvar, String value)
{
return "<input type=\"hidden\" name=\""+httpvar+"\" value=\""+value+"\">";
}
"Create a text box"
public HTML textBox(String name, String value="", Int len = 20)
{
return "<input type=\"text\" size="+String(len)+" name=\""+name+"\" value=\""+value+"\">";
}
"Create a password box"
public HTML passwordBox(String name, Int len = 20)
{
return "<input type=\"password\" size="+String(len)+" name=\""+name+"\">";
}
"Create a selection box.
The possible values are listed in <em>opts</em>, and the default
selection is passed in <em>def</em>."
public HTML selBox(String name, Int len, [String] opts, String def = "")
{
str = "<select name=\""+name+"\" size="+ String(len)+">";
for entry in opts {
if (entry==def) {
str+="<option selected>";
}
else {
str+="<option>";
}
str+=entry+"</option>";
}
str+="</select>";
return str;
}
"Make a checkbox.
<em>def</em> denotes whether this is the default value."
public HTML checkBox(String name,Bool def = false)
{
str = "<input type=\"checkbox\" name=\""+name+"\" ";
if (def) str+="checked>"; else str+=">";
return str;
}
"Return whether a checkbox was checked."
public Bool checked(String name)
{
return httpVar(name)=="on";
}
"Create a radio button."
public HTML radio(String name, String val, Bool set = false)
{
str = "<input type=\"radio\" name=\""+name+"\" value=\""+val+"\" ";
if (set) str+="checked>"; else str+=">";
return str;
}
/// Create a file upload thingy
/// Won't work yet though. Need to handle enctype="multipart/form-data"
/*
String fileUpload(String name)
= "<input type=\"file\" name=\""+name+"\" size=20>";
*/
"End a form
Simply returns <code></form></code>"
public HTML closeForm()
{
return "</form>";
}
"Output a table."
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 = [('&',"&"),
('<',"<"),
('>',">"),
('',"£")];
}
for p in esctable {
if (x==p.fst)
return p.snd;
}
return String(x);
}
"Transforms HTML special chars.
Transforms chars like '<', '>' and others in HTML form, like '&lt' and '&gt'"
public String htmlEscape(String x)
{
str = x;
current = "";
while(str!="") {
c = head(str);
str = tail(str);
current += htmlEncodeChar(c);
}
return current;
}
/// Safe cast functions
"Convert a string to an Int.
If the resulting Int is out of the specified range, throws an exception."
public Int safeInt(String x, Int min, Int max)
{
num = Int(x);
if (num<min || num>max) {
throw(OutOfRange);
}
return num;
}
"Convert a string to a Float.
If the resulting Float is out of the specified range, throws an exception."
public Float safeFloat(String x, Float min, Float max)
{
num = Float(x);
if (num<min || num>max) {
throw(OutOfRange);
}
return num;
}
|