1
/* IVLE - Informatics Virtual Learning Environment
2
* Copyright (C) 2007-2008 The University of Melbourne
4
* This program is free software; you can redistribute it and/or modify
5
* it under the terms of the GNU General Public License as published by
6
* the Free Software Foundation; either version 2 of the License, or
7
* (at your option) any later version.
9
* This program is distributed in the hope that it will be useful,
10
* but WITHOUT ANY WARRANTY; without even the implied warranty of
11
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
* GNU General Public License for more details.
14
* You should have received a copy of the GNU General Public License
15
* along with this program; if not, write to the Free Software
16
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18
* Module: JavaScript Utilities
22
* Defines some generic JavaScript utility functions.
25
/* Expects the following variables to have been declared by JavaScript in
26
* the HTML generated by the server:
31
/** Removes all children of a given DOM element
32
* \param elem A DOM Element. Will be modified.
34
function dom_removechildren(elem)
36
while (elem.lastChild != null)
37
elem.removeChild(elem.lastChild);
40
/** Creates a DOM element with simple text inside it.
41
* \param tagname String. Name of the element's tag (eg. "p").
42
* \param text String. Text to be placed inside the element.
43
* \param title String, optional. Tooltip for the text.
44
* (Note, title creates a span element around the text).
45
* \return DOM Element object.
47
function dom_make_text_elem(tagname, text, title)
49
if (text == null) text = "";
50
var elem = document.createElement(tagname);
53
textnode = document.createTextNode(text);
56
textnode = document.createElement("span");
57
textnode.setAttribute("title", title);
58
textnode.appendChild(document.createTextNode(text));
60
elem.appendChild(textnode);
64
/** Creates a DOM element with hyperlinked text inside it.
65
* \param tagname String. Name of the element's tag (eg. "p").
66
* \param text String. Text to be placed inside the element.
67
* \param title String, optional. Sets a tooltip for the link.
68
* \param href String. URL the text will link to. This is a raw string,
69
* it will automatically be URL-encoded.
70
* \param onclick Optional string. Will be set as the "onclick" attribute
72
* \param dontencode Optional boolean. If true, will not encode the href.
73
* if including query strings, you must set this to true and use build_url
74
* to escape the URI correctly.
75
* \return DOM Element object.
77
function dom_make_link_elem(tagname, text, title, href, onclick, dontencode)
79
if (text == null) text = "";
80
if (href == null) href = "";
81
var elem = document.createElement(tagname);
82
var link = document.createElement("a");
83
if (dontencode != true)
84
href = urlencode_path(href);
85
link.setAttribute("href", href);
87
link.setAttribute("title", title);
89
link.setAttribute("onclick", onclick);
90
link.appendChild(document.createTextNode(text));
91
elem.appendChild(link);
95
/** Creates a DOM img element. All parameters are optional except src.
96
* If alt (compulsory in HTML) is omitted, will be set to "".
98
function dom_make_img(src, width, height, title, alt)
100
var img = document.createElement("img");
101
img.setAttribute("src", urlencode_path(src));
103
img.setAttribute("width", width);
105
img.setAttribute("height", height);
107
img.setAttribute("title", title);
108
if (alt == null) alt = "";
109
img.setAttribute("alt", alt);
113
/** Given a number of bytes, returns a string representing the file size in a
114
* human-readable format.
115
* eg. nice_filesize(6) -> "6 bytes"
116
* nice_filesize(81275) -> "79.4 kB"
117
* nice_filesize(13498346) -> "12.9 MB"
118
* \param bytes Number of bytes. Must be an integer.
121
function nice_filesize(bytes)
123
if (bytes == null) return "";
126
return bytes.toString() + " B";
129
return size.toFixed(1) + " kB";
132
return size.toFixed(1) + " MB";
134
return size.toFixed(1) + " GB";
137
/** Given a URL, returns an object containing a number of attributes
138
* describing the components of the URL, similar to CGI request variables.
139
* The object has the following attributes:
146
* The first five of these are strings, which comprise the URL as follows:
147
* <scheme> "://" <server_name> ":" <server_port> <path> "?" <query_string>
148
* Any of these strings may be set to null if not found.
150
* "args" is an object whose attributes are the query_string arguments broken
152
* Args values are strings for single values, arrays of strings for values
153
* whose names appear multiple times.
154
* args is never null, though it may be empty.
156
* All strings are decoded/unescaped. Reserved characters
157
* (; , / ? : @ & = + * $) are not decoded except in args and path.
159
* \param url String. A URL. To read from the current browser window, use
160
* window.location.href.
161
* \return The above described object.
163
function parse_url(url)
170
/* Split scheme from rest */
171
index = url.indexOf("://");
176
obj.scheme = url.substr(0, index);
177
url = url.substr(index+3);
180
/* Split server name/port from rest */
181
index = url.indexOf("/");
189
serverpart = url.substr(0, index);
190
url = url.substr(index);
193
/* Split server name from port */
194
index = serverpart.indexOf(":");
197
obj.server_name = serverpart;
198
obj.server_port = null;
202
obj.server_name = serverpart.substr(0, index);
203
obj.server_port = serverpart.substr(index+1);
206
/* Split path from query string */
210
obj.query_string = null;
214
index = url.indexOf("?");
218
obj.query_string = null;
222
obj.path = url.substr(0, index);
223
obj.query_string = url.substr(index+1);
226
obj.path = decodeURIComponent(obj.path);
228
/* Split query string into arguments */
230
if (obj.query_string != null)
232
var args_strs = obj.query_string.split("&");
234
var arg_key, arg_val;
235
for (var i=0; i<args_strs.length; i++)
237
arg_str = args_strs[i];
238
index = arg_str.indexOf("=");
239
/* Ignore malformed args */
242
arg_key = decodeURIComponent(arg_str.substr(0, index));
243
arg_val = decodeURIComponent(arg_str.substr(index+1));
246
/* Collision - make an array */
247
if (args[arg_key] instanceof Array)
248
args[arg_key][args[arg_key].length] = arg_val;
250
args[arg_key] = [args[arg_key], arg_val];
253
args[arg_key] = arg_val;
262
/** Builds a query_string from an args object. Encodes the arguments.
263
* \param args Args object as described in parse_url.
264
* \return Query string portion of a URL.
266
function make_query_string(args)
268
var query_string = "";
270
for (var arg_key in args)
272
arg_val = args[arg_key];
273
if (arg_val instanceof Array)
274
for (var i=0; i<arg_val.length; i++)
275
query_string += "&" + encodeURIComponent(arg_key) + "=" +
276
encodeURIComponent(arg_val[i]);
278
query_string += "&" + encodeURIComponent(arg_key) + "=" +
279
encodeURIComponent(arg_val);
281
if (query_string != "")
282
/* Drop the first "&" */
283
query_string = query_string.substr(1);
288
/** Given an object exactly of the form described for the output of parseurl,
289
* returns a URL string built from those parameters. The URL is properly
291
* parseurl and buildurl are strict inverses of each other.
292
* Note that either query_string or args may be supplied. If both are
293
* supplied, query_string is preferred (because it keeps the argument order).
294
* If you take a url from parseurl, modify args, and pass to buildurl,
295
* you need to set query_string to null to use the new args.
296
* \param obj Object as returned by parseurl.
297
* \return String, a URL.
299
function build_url(obj)
302
var query_string = null;
304
if (("scheme" in obj) && obj.scheme != null)
305
url = obj.scheme.toString() + "://";
306
if (("server_name" in obj) && obj.server_name != null)
307
url += obj.server_name.toString();
308
if (("server_port" in obj) && obj.server_port != null)
309
url += ":" + obj.server_port.toString();
310
if (("path" in obj) && obj.path != null)
312
var path = urlencode_path(obj.path.toString());
313
if (url.length > 0 && path.length > 0 && path[0] != "/")
317
if (("query_string" in obj) && obj.query_string != null)
318
query_string = encodeURI(obj.query_string.toString());
319
else if (("args" in obj) && obj.args != null)
320
query_string = make_query_string(obj.args);
322
if (query_string != "" && query_string != null)
323
url += "?" + query_string;
328
/** URL-encodes a path. This is a special case of URL encoding as all
329
* characters *except* the slash must be encoded.
331
function urlencode_path(path)
333
/* Split up the path, URLEncode each segment with encodeURIComponent,
336
var split = path.split('/');
337
for (var i=0; i<split.length; i++)
338
split[i] = encodeURIComponent(split[i]);
339
path = path_join.apply(null, split);
340
if (split[0] == "" && split.length > 1) path = "/" + path;
344
/** Writes a JSONable object to the cookie under a particular key
345
* (JSON encoded and URL encoded).
347
function write_cookie(key, value)
349
var sendstr = encodeURIComponent(key) + "="
350
+ encodeURIComponent(JSON.stringify(value))
351
+ "; path=" + urlencode_path(root_dir);
352
/* This actually just assigns to the key, not replacing the whole cookie
353
* as it appears to. */
354
document.cookie = sendstr;
356
/** Reads a cookie which has a JSONable object encoded as its value.
357
* Returns the object, parsed from JSON.
359
function read_cookie(key)
361
var cookies = document.cookie.split(";");
362
var checkstart = encodeURIComponent(key) + "=";
363
var checklen = checkstart.length;
364
for (var i=0; i<cookies.length; i++)
366
var cookie = cookies[i];
367
while (cookie[0] == ' ')
368
cookie = cookie.substr(1);
369
if (cookie.substr(0, checklen) == checkstart)
371
var valstr = cookie.substr(checklen);
372
valstr = decodeURIComponent(valstr);
373
return JSON.parse(valstr);
378
/** Given an argument map, as output in the args parameter of the return of
379
* parseurl, gets the first occurence of an argument in the URL string.
380
* If the argument was not found, returns null.
381
* If there was a single argument, returns the argument.
382
* If there were multiple arguments, returns the first.
383
* \param args Object mapping arguments to strings or arrays of strings.
384
* \param arg String. Argument name.
387
function arg_getfirst(args, arg)
392
if (r instanceof Array)
398
/** Given an argument map, as output in the args parameter of the return of
399
* parseurl, gets all occurences of an argument in the URL string, as an
401
* If the argument was not found, returns [].
402
* Otherwise, returns all occurences as an array, even if there was only one.
403
* \param args Object mapping arguments to strings or arrays of strings.
404
* \param arg String. Argument name.
405
* \return Array of strings.
407
function arg_getlist(args, arg)
412
if (r instanceof Array)
418
/** Joins one or more paths together. Accepts 1 or more arguments.
420
function path_join(path1 /*, path2, ... */)
424
for (var i=0; i<arguments.length; i++)
427
if (arg.length == 0) continue;
432
if (path.length > 0 && path[path.length-1] != '/')
441
/** Builds a multipart_formdata string from an args object. Similar to
442
* make_query_string, but it returns data of type "multipart/form-data"
443
* instead of "application/x-www-form-urlencoded". This is good for
444
* encoding large strings such as text objects from the editor.
445
* Should be written with a Content-Type of
446
* "multipart/form-data, boundary=<boundary>".
447
* All fields are sent with a Content-Type of text/plain.
448
* \param args Args object as described in parse_url.
449
* \param boundary Random "magic" string which DOES NOT appear in any of
450
* the argument values. This should match the "boundary=" value written to
451
* the Content-Type header.
452
* \return String in multipart/form-data format.
454
function make_multipart_formdata(args, boundary)
459
var extend_data = function(arg_key, arg_val)
461
/* FIXME: Encoding not supported here (should not matter if we
462
* only use ASCII names */
463
data += "--" + boundary + "\r\n"
464
+ "Content-Disposition: form-data; name=\"" + arg_key
469
for (var arg_key in args)
471
arg_val = args[arg_key];
472
if (arg_val instanceof Array)
473
for (var i=0; i<arg_val.length; i++)
475
extend_data(arg_key, arg_val[i]);
478
extend_data(arg_key, arg_val);
481
data += "--" + boundary + "--\r\n";
486
/** Converts a list of directories into a path name, with a slash at the end.
487
* \param pathlist List of strings.
490
function pathlist_to_path(pathlist)
492
ret = path_join.apply(null, pathlist);
493
if (ret[ret.length-1] != '/')
498
/** Given a path relative to the IVLE root, gives a path relative to
501
function make_path(path)
503
return path_join(root_dir, path);
506
/** Shorthand for make_path(path_join(app, ...))
507
* Creates an absolute path for a given path within a given app.
509
function app_path(app /*,...*/)
511
return make_path(path_join.apply(null, arguments));
514
/** Given a path, gets the "basename" (the last path segment).
516
function path_basename(path)
518
segments = path.split("/");
519
if (segments[segments.length-1].length == 0)
520
return segments[segments.length-2];
522
return segments[segments.length-1];
525
/** Given a string str, determines whether it ends with substr */
526
function endswith(str, substring)
528
if (str.length < substring.length) return false;
529
return str.substr(str.length - substring.length) == substring;
532
/** Equivalent to Python's repr.
533
* Gets the JavaScript string representation.
534
* Actually just calls JSON.stringify.
538
return JSON.stringify(str);
541
/** Removes all occurences of a value from an array.
543
Array.prototype.removeall = function(val)
548
for (i=0; i<arr.length; i++)
551
if (arr[i] != val) j++;
556
/** Shallow-clones an object */
557
function shallow_clone_object(obj)
565
/** Returns a new XMLHttpRequest object, in a somewhat browser-agnostic
568
function new_xmlhttprequest()
573
return new XMLHttpRequest();
577
/* Internet Explorer */
580
return new ActiveXObject("Msxml2.XMLHTTP");
586
return new ActiveXObject("Microsoft.XMLHTTP");
590
throw("Your browser does not support AJAX. "
591
+ "IVLE requires a modern browser.");
597
/** Makes an asynchronous XMLHttpRequest call to the server.
598
* Sends the XMLHttpRequest object containing the completed response to a
599
* specified callback function.
601
* \param callback A callback function. Will be called when the response is
602
* complete. Passed 1 parameter, an XMLHttpRequest object containing the
603
* completed response.
604
* \param app IVLE app to call (such as "fileservice").
605
* \param path URL path to make the request to, within the application.
606
* \param args Argument object, as described in parse_url and friends.
607
* \param method String; "GET" or "POST"
608
* \param content_type String, optional. Only applies if method is "POST".
609
* May be "application/x-www-form-urlencoded" or "multipart/form-data".
610
* Defaults to "application/x-www-form-urlencoded".
612
function ajax_call(callback, app, path, args, method, content_type)
614
if (content_type != "multipart/form-data")
615
content_type = "application/x-www-form-urlencoded";
616
path = app_path(app, path);
618
/* A random string, for multipart/form-data
619
* (This is not checked against anywhere else, it is solely defined and
620
* used within this function) */
621
var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
622
var xhr = new_xmlhttprequest();
623
xhr.onreadystatechange = function()
625
if (xhr.readyState == 4)
632
/* GET sends the args in the URL */
633
url = build_url({"path": path, "args": args});
634
/* open's 3rd argument = true -> asynchronous */
635
xhr.open(method, url, true);
640
/* POST sends the args in application/x-www-form-urlencoded */
641
url = encodeURI(path);
642
xhr.open(method, url, true);
644
if (content_type == "multipart/form-data")
646
xhr.setRequestHeader("Content-Type",
647
"multipart/form-data, boundary=" + boundary);
648
message = make_multipart_formdata(args, boundary);
652
xhr.setRequestHeader("Content-Type", content_type);
653
message = make_query_string(args);
655
xhr.setRequestHeader("Content-Length", message.length);