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:
32
/** Removes all children of a given DOM element
33
* \param elem A DOM Element. Will be modified.
35
function dom_removechildren(elem)
37
while (elem.lastChild != null)
38
elem.removeChild(elem.lastChild);
41
/** Creates a DOM element with simple text inside it.
42
* \param tagname String. Name of the element's tag (eg. "p").
43
* \param text String. Text to be placed inside the element.
44
* \param title String, optional. Tooltip for the text.
45
* (Note, title creates a span element around the text).
46
* \return DOM Element object.
48
function dom_make_text_elem(tagname, text, title)
50
if (text == null) text = "";
51
var elem = document.createElement(tagname);
54
textnode = document.createTextNode(text);
57
textnode = document.createElement("span");
58
textnode.setAttribute("title", title);
59
textnode.appendChild(document.createTextNode(text));
61
elem.appendChild(textnode);
65
/** Creates a DOM element with hyperlinked text inside it.
66
* \param tagname String. Name of the element's tag (eg. "p").
67
* \param text String. Text to be placed inside the element.
68
* \param title String, optional. Sets a tooltip for the link.
69
* \param href String. URL the text will link to. This is a raw string,
70
* it will automatically be URL-encoded.
71
* \param onclick Optional string. Will be set as the "onclick" attribute
73
* \param dontencode Optional boolean. If true, will not encode the href.
74
* if including query strings, you must set this to true and use build_url
75
* to escape the URI correctly.
76
* \return DOM Element object.
78
function dom_make_link_elem(tagname, text, title, href, onclick, dontencode)
80
if (text == null) text = "";
81
if (href == null) href = "";
82
var elem = document.createElement(tagname);
83
var link = document.createElement("a");
84
if (dontencode != true)
85
href = urlencode_path(href);
86
link.setAttribute("href", href);
88
link.setAttribute("title", title);
90
link.setAttribute("onclick", onclick);
91
link.appendChild(document.createTextNode(text));
92
elem.appendChild(link);
96
/** Creates a DOM img element. All parameters are optional except src.
97
* If alt (compulsory in HTML) is omitted, will be set to "".
99
function dom_make_img(src, width, height, title, alt)
101
var img = document.createElement("img");
102
img.setAttribute("src", urlencode_path(src));
104
img.setAttribute("width", width);
106
img.setAttribute("height", height);
108
img.setAttribute("title", title);
109
if (alt == null) alt = "";
110
img.setAttribute("alt", alt);
114
/** Given a number of bytes, returns a string representing the file size in a
115
* human-readable format.
116
* eg. nice_filesize(6) -> "6 bytes"
117
* nice_filesize(81275) -> "79.4 kB"
118
* nice_filesize(13498346) -> "12.9 MB"
119
* \param bytes Number of bytes. Must be an integer.
122
function nice_filesize(bytes)
124
if (bytes == null) return "";
127
return bytes.toString() + " B";
130
return size.toFixed(1) + " kB";
133
return size.toFixed(1) + " MB";
135
return size.toFixed(1) + " GB";
138
/** Given a URL, returns an object containing a number of attributes
139
* describing the components of the URL, similar to CGI request variables.
140
* The object has the following attributes:
147
* The first five of these are strings, which comprise the URL as follows:
148
* <scheme> "://" <server_name> ":" <server_port> <path> "?" <query_string>
149
* Any of these strings may be set to null if not found.
151
* "args" is an object whose attributes are the query_string arguments broken
153
* Args values are strings for single values, arrays of strings for values
154
* whose names appear multiple times.
155
* args is never null, though it may be empty.
157
* All strings are decoded/unescaped. Reserved characters
158
* (; , / ? : @ & = + * $) are not decoded except in args and path.
160
* \param url String. A URL. To read from the current browser window, use
161
* window.location.href.
162
* \return The above described object.
164
function parse_url(url)
171
/* Split scheme from rest */
172
index = url.indexOf("://");
177
obj.scheme = url.substr(0, index);
178
url = url.substr(index+3);
181
/* Split server name/port from rest */
182
index = url.indexOf("/");
190
serverpart = url.substr(0, index);
191
url = url.substr(index);
194
/* Split server name from port */
195
index = serverpart.indexOf(":");
198
obj.server_name = serverpart;
199
obj.server_port = null;
203
obj.server_name = serverpart.substr(0, index);
204
obj.server_port = serverpart.substr(index+1);
207
/* Split path from query string */
211
obj.query_string = null;
215
index = url.indexOf("?");
219
obj.query_string = null;
223
obj.path = url.substr(0, index);
224
obj.query_string = url.substr(index+1);
227
obj.path = decodeURIComponent(obj.path);
229
/* Split query string into arguments */
231
if (obj.query_string != null)
233
var args_strs = obj.query_string.split("&");
235
var arg_key, arg_val;
236
for (var i=0; i<args_strs.length; i++)
238
arg_str = args_strs[i];
239
index = arg_str.indexOf("=");
240
/* Ignore malformed args */
243
arg_key = decodeURIComponent(arg_str.substr(0, index));
244
arg_val = decodeURIComponent(arg_str.substr(index+1));
247
/* Collision - make an array */
248
if (args[arg_key] instanceof Array)
249
args[arg_key][args[arg_key].length] = arg_val;
251
args[arg_key] = [args[arg_key], arg_val];
254
args[arg_key] = arg_val;
263
/** Builds a query_string from an args object. Encodes the arguments.
264
* \param args Args object as described in parse_url.
265
* \return Query string portion of a URL.
267
function make_query_string(args)
269
var query_string = "";
271
for (var arg_key in args)
273
arg_val = args[arg_key];
274
if (arg_val instanceof Array)
275
for (var i=0; i<arg_val.length; i++)
276
query_string += "&" + encodeURIComponent(arg_key) + "=" +
277
encodeURIComponent(arg_val[i]);
279
query_string += "&" + encodeURIComponent(arg_key) + "=" +
280
encodeURIComponent(arg_val);
282
if (query_string != "")
283
/* Drop the first "&" */
284
query_string = query_string.substr(1);
289
/** Given an object exactly of the form described for the output of parseurl,
290
* returns a URL string built from those parameters. The URL is properly
292
* parseurl and buildurl are strict inverses of each other.
293
* Note that either query_string or args may be supplied. If both are
294
* supplied, query_string is preferred (because it keeps the argument order).
295
* If you take a url from parseurl, modify args, and pass to buildurl,
296
* you need to set query_string to null to use the new args.
297
* \param obj Object as returned by parseurl.
298
* \return String, a URL.
300
function build_url(obj)
303
var query_string = null;
305
if (("scheme" in obj) && obj.scheme != null)
306
url = obj.scheme.toString() + "://";
307
if (("server_name" in obj) && obj.server_name != null)
308
url += obj.server_name.toString();
309
if (("server_port" in obj) && obj.server_port != null)
310
url += ":" + obj.server_port.toString();
311
if (("path" in obj) && obj.path != null)
313
var path = urlencode_path(obj.path.toString());
314
if (url.length > 0 && path.length > 0 && path.charAt(0) != "/")
318
if (("query_string" in obj) && obj.query_string != null)
319
query_string = encodeURI(obj.query_string.toString());
320
else if (("args" in obj) && obj.args != null)
321
query_string = make_query_string(obj.args);
323
if (query_string != "" && query_string != null)
324
url += "?" + query_string;
329
/** URL-encodes a path. This is a special case of URL encoding as all
330
* characters *except* the slash must be encoded.
332
function urlencode_path(path)
334
/* Split up the path, URLEncode each segment with encodeURIComponent,
337
var split = path.split('/');
338
for (var i=0; i<split.length; i++)
339
split[i] = encodeURIComponent(split[i]);
340
path = path_join.apply(null, split);
341
if (split[0] == "" && split.length > 1) path = "/" + path;
345
/** Writes a JSONable object to the cookie under a particular key
346
* (JSON encoded and URL encoded).
348
function write_cookie(key, value)
350
var sendstr = encodeURIComponent(key) + "="
351
+ encodeURIComponent(JSON.stringify(value))
352
+ "; path=" + urlencode_path(root_dir);
353
/* This actually just assigns to the key, not replacing the whole cookie
354
* as it appears to. */
355
document.cookie = sendstr;
357
/** Reads a cookie which has a JSONable object encoded as its value.
358
* Returns the object, parsed from JSON.
360
function read_cookie(key)
362
var cookies = document.cookie.split(";");
363
var checkstart = encodeURIComponent(key) + "=";
364
var checklen = checkstart.length;
365
for (var i=0; i<cookies.length; i++)
367
var cookie = cookies[i];
368
while (cookie[0] == ' ')
369
cookie = cookie.substr(1);
370
if (cookie.substr(0, checklen) == checkstart)
372
var valstr = cookie.substr(checklen);
373
valstr = decodeURIComponent(valstr);
374
return JSON.parse(valstr);
379
/** Given an argument map, as output in the args parameter of the return of
380
* parseurl, gets the first occurence of an argument in the URL string.
381
* If the argument was not found, returns null.
382
* If there was a single argument, returns the argument.
383
* If there were multiple arguments, returns the first.
384
* \param args Object mapping arguments to strings or arrays of strings.
385
* \param arg String. Argument name.
388
function arg_getfirst(args, arg)
393
if (r instanceof Array)
399
/** Given an argument map, as output in the args parameter of the return of
400
* parseurl, gets all occurences of an argument in the URL string, as an
402
* If the argument was not found, returns [].
403
* Otherwise, returns all occurences as an array, even if there was only one.
404
* \param args Object mapping arguments to strings or arrays of strings.
405
* \param arg String. Argument name.
406
* \return Array of strings.
408
function arg_getlist(args, arg)
413
if (r instanceof Array)
419
/** Joins one or more paths together. Accepts 1 or more arguments.
421
function path_join(path1 /*, path2, ... */)
425
for (var i=0; i<arguments.length; i++)
428
if (arg.length == 0) continue;
429
if (arg.charAt(0) == '/')
433
if (path.length > 0 && path.charAt(path.length-1) != '/')
442
/** Builds a multipart_formdata string from an args object. Similar to
443
* make_query_string, but it returns data of type "multipart/form-data"
444
* instead of "application/x-www-form-urlencoded". This is good for
445
* encoding large strings such as text objects from the editor.
446
* Should be written with a Content-Type of
447
* "multipart/form-data, boundary=<boundary>".
448
* All fields are sent with a Content-Type of text/plain.
449
* \param args Args object as described in parse_url.
450
* \param boundary Random "magic" string which DOES NOT appear in any of
451
* the argument values. This should match the "boundary=" value written to
452
* the Content-Type header.
453
* \return String in multipart/form-data format.
455
function make_multipart_formdata(args, boundary)
460
var extend_data = function(arg_key, arg_val)
462
/* FIXME: Encoding not supported here (should not matter if we
463
* only use ASCII names */
464
data += "--" + boundary + "\r\n"
465
+ "Content-Disposition: form-data; name=\"" + arg_key
470
for (var arg_key in args)
472
arg_val = args[arg_key];
473
if (arg_val instanceof Array)
474
for (var i=0; i<arg_val.length; i++)
476
extend_data(arg_key, arg_val[i]);
479
extend_data(arg_key, arg_val);
482
data += "--" + boundary + "--\r\n";
487
/** Converts a list of directories into a path name, with a slash at the end.
488
* \param pathlist List of strings.
491
function pathlist_to_path(pathlist)
493
ret = path_join.apply(null, pathlist);
494
if (ret.charAt(ret.length-1) != '/')
499
/** Given a path relative to the IVLE root, gives a path relative to
502
function make_path(path)
504
return path_join(root_dir, path);
507
/** Shorthand for make_path(path_join(app, ...))
508
* Creates an absolute path for a given path within a given app.
510
function app_path(app /*,...*/)
512
return make_path(path_join.apply(null, arguments));
515
/** Generates an absolute URL to a public application
517
function public_app_path(app /*,...*/)
519
return location.protocol + "//" + public_host
520
+ make_path(path_join.apply(null, arguments));
523
/** Given a path, gets the "basename" (the last path segment).
525
function path_basename(path)
527
segments = path.split("/");
528
if (segments[segments.length-1].length == 0)
529
return segments[segments.length-2];
531
return segments[segments.length-1];
534
/** Given a string str, determines whether it ends with substr */
535
function endswith(str, substring)
537
if (str.length < substring.length) return false;
538
return str.substr(str.length - substring.length) == substring;
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
/** Creates a random string of length length,
598
* consisting of alphanumeric characters.
600
var rand_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ"
601
+ "abcdefghiklmnopqrstuvwxyz";
602
function random_string(length)
604
var str = Array(length);
606
for (var i=0; i<length; i++)
608
v = Math.floor(Math.random() * rand_chars.length);
609
str[i] = rand_chars.charAt(v);
614
/** Makes an XMLHttpRequest call to the server.
615
* Sends the XMLHttpRequest object containing the completed response to a
616
* specified callback function.
618
* \param callback A callback function. Will be called when the response is
619
* complete. Passed 1 parameter, an XMLHttpRequest object containing the
620
* completed response. If callback is null this is a syncronous request
621
* otherwise this is an asynchronous request.
622
* \param app IVLE app to call (such as "fileservice").
623
* \param path URL path to make the request to, within the application.
624
* \param args Argument object, as described in parse_url and friends.
625
* \param method String; "GET" or "POST"
626
* \param content_type String, optional. Only applies if method is "POST".
627
* May be "application/x-www-form-urlencoded" or "multipart/form-data".
628
* Defaults to "application/x-www-form-urlencoded".
630
function ajax_call(callback, app, path, args, method, content_type)
632
if (content_type != "multipart/form-data")
633
content_type = "application/x-www-form-urlencoded";
634
path = app_path(app, path);
636
/* A random string, for multipart/form-data
637
* (This is not checked against anywhere else, it is solely defined and
638
* used within this function) */
639
var boundary = random_string(20);
640
var xhr = new_xmlhttprequest();
641
var asyncronous = callback != null;
644
xhr.onreadystatechange = function()
646
if (xhr.readyState == 4)
654
/* GET sends the args in the URL */
655
url = build_url({"path": path, "args": args});
656
/* open's 3rd argument = true -> asynchronous */
657
xhr.open(method, url, asyncronous);
662
/* POST sends the args in application/x-www-form-urlencoded */
663
url = encodeURI(path);
664
xhr.open(method, url, asyncronous);
666
if (content_type == "multipart/form-data")
668
xhr.setRequestHeader("Content-Type",
669
"multipart/form-data; boundary=" + boundary);
670
message = make_multipart_formdata(args, boundary);
674
xhr.setRequestHeader("Content-Type", content_type);
675
message = make_query_string(args);
679
/* Only return the XHR for syncronous requests */
686
/** Attempts to JSON decodes a response object
687
* If a non-200 response or the JSON decode fails then returns null
689
function decode_response(response)
691
if (response.status == 200)
695
var responseText = response.responseText;
696
return JSON.parse(responseText);