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
/** Removes all children of a given DOM element
26
* \param elem A DOM Element. Will be modified.
28
function dom_removechildren(elem)
30
while (elem.lastChild != null)
31
elem.removeChild(elem.lastChild);
34
/** Creates a DOM element with simple text inside it.
35
* \param tagname String. Name of the element's tag (eg. "p").
36
* \param text String. Text to be placed inside the element.
37
* \return DOM Element object.
39
function dom_make_text_elem(tagname, text)
41
if (text == null) text = "";
42
var elem = document.createElement(tagname);
43
elem.appendChild(document.createTextNode(text));
47
/** Creates a DOM element with hyperlinked text inside it.
48
* \param tagname String. Name of the element's tag (eg. "p").
49
* \param text String. Text to be placed inside the element.
50
* \param href String. URL the text will link to. This is a raw string,
51
* it will automatically be URL-encoded.
52
* \param onclick Optional string. Will be set as the "onclick" attribute
54
* \return DOM Element object.
56
function dom_make_link_elem(tagname, text, href, onclick)
58
if (text == null) text = "";
59
if (href == null) href = "";
60
var elem = document.createElement(tagname);
61
var link = document.createElement("a");
62
link.setAttribute("href", encodeURI(href));
64
link.setAttribute("onclick", onclick);
65
link.appendChild(document.createTextNode(text));
66
elem.appendChild(link);
70
/** Creates a DOM img element. All parameters are optional except src.
71
* If alt (compulsory in HTML) is omitted, will be set to "".
73
function dom_make_img(src, width, height, title, alt)
75
var img = document.createElement("img");
76
img.setAttribute("src", src);
78
img.setAttribute("width", width);
80
img.setAttribute("height", height);
82
img.setAttribute("title", title);
83
if (alt == null) alt = "";
84
img.setAttribute("alt", alt);
88
/** Given a number of bytes, returns a string representing the file size in a
89
* human-readable format.
90
* eg. nice_filesize(6) -> "6 bytes"
91
* nice_filesize(81275) -> "79.4 kB"
92
* nice_filesize(13498346) -> "12.9 MB"
93
* \param bytes Number of bytes. Must be an integer.
96
function nice_filesize(bytes)
98
if (bytes == null) return "";
101
return bytes.toString() + " B";
104
return size.toFixed(1) + " kB";
107
return size.toFixed(1) + " MB";
109
return size.toFixed(1) + " GB";
112
/** Given a URL, returns an object containing a number of attributes
113
* describing the components of the URL, similar to CGI request variables.
114
* The object has the following attributes:
121
* The first five of these are strings, which comprise the URL as follows:
122
* <scheme> "://" <server_name> ":" <server_port> <path> "?" <query_string>
123
* Any of these strings may be set to null if not found.
125
* "args" is an object whose attributes are the query_string arguments broken
127
* Args values are strings for single values, arrays of strings for values
128
* whose names appear multiple times.
129
* args is never null, though it may be empty.
131
* All strings are decoded/unescaped. Reserved characters
132
* (; , / ? : @ & = + * $) are not decoded except in args.
134
* \param url String. A URL. To read from the current browser window, use
135
* window.location.href.
136
* \return The above described object.
138
function parse_url(url)
145
url = decodeURI(url);
147
/* Split scheme from rest */
148
index = url.indexOf("://");
153
obj.scheme = url.substr(0, index);
154
url = url.substr(index+3);
157
/* Split server name/port from rest */
158
index = url.indexOf("/");
166
serverpart = url.substr(0, index);
167
url = url.substr(index);
170
/* Split server name from port */
171
index = serverpart.indexOf(":");
174
obj.server_name = serverpart;
175
obj.server_port = null;
179
obj.server_name = serverpart.substr(0, index);
180
obj.server_port = serverpart.substr(index+1);
183
/* Split path from query string */
187
obj.query_string = null;
191
index = url.indexOf("?");
195
obj.query_string = null;
199
obj.path = url.substr(0, index);
200
obj.query_string = url.substr(index+1);
204
/* Split query string into arguments */
206
if (obj.query_string != null)
208
var args_strs = obj.query_string.split("&");
210
var arg_key, arg_val;
211
for (var i=0; i<args_strs.length; i++)
213
arg_str = args_strs[i];
214
index = arg_str.indexOf("=");
215
/* Ignore malformed args */
218
arg_key = decodeURIComponent(arg_str.substr(0, index));
219
arg_val = decodeURIComponent(arg_str.substr(index+1));
222
/* Collision - make an array */
223
if (args[arg_key] instanceof Array)
224
args[arg_key][args[arg_key].length] = arg_val;
226
args[arg_key] = [args[arg_key], arg_val];
229
args[arg_key] = arg_val;
238
/** Builds a query_string from an args object. Encodes the arguments.
239
* \param args Args object as described in parse_url.
240
* \return Query string portion of a URL.
242
function make_query_string(args)
244
var query_string = "";
246
for (var arg_key in args)
248
arg_val = args[arg_key];
249
if (arg_val instanceof Array)
250
for (var i=0; i<arg_val.length; i++)
251
query_string += "&" + encodeURIComponent(arg_key) + "=" +
252
encodeURIComponent(arg_val[i]);
254
query_string += "&" + encodeURIComponent(arg_key) + "=" +
255
encodeURIComponent(arg_val);
257
if (query_string == "")
260
/* Drop the first "&" */
261
query_string = query_string.substr(1);
266
/** Given an object exactly of the form described for the output of parseurl,
267
* returns a URL string built from those parameters. The URL is properly
269
* parseurl and buildurl are strict inverses of each other.
270
* Note that either query_string or args may be supplied. If both are
271
* supplied, query_string is preferred (because it keeps the argument order).
272
* If you take a url from parseurl, modify args, and pass to buildurl,
273
* you need to set query_string to null to use the new args.
274
* \param obj Object as returned by parseurl.
275
* \return String, a URL.
277
function build_url(obj)
280
var query_string = null;
282
if (("scheme" in obj) && obj.scheme != null)
283
url = obj.scheme.toString() + "://";
284
if (("server_name" in obj) && obj.server_name != null)
285
url += obj.server_name.toString();
286
if (("server_port" in obj) && obj.server_port != null)
287
url += ":" + obj.server_port.toString();
288
if (("path" in obj) && obj.path != null)
290
var path = obj.path.toString();
291
if (url.length > 0 && path.length > 0 && path[0] != "/")
295
if (("query_string" in obj) && obj.query_string != null)
296
query_string = obj.query_string.toString();
297
else if (("args" in obj) && obj.args != null)
298
query_string = make_query_string(obj.args);
300
if (query_string != null)
301
url += "?" + query_string;
303
return encodeURI(url);
306
/** Given an argument map, as output in the args parameter of the return of
307
* parseurl, gets the first occurence of an argument in the URL string.
308
* If the argument was not found, returns null.
309
* If there was a single argument, returns the argument.
310
* If there were multiple arguments, returns the first.
311
* \param args Object mapping arguments to strings or arrays of strings.
312
* \param arg String. Argument name.
315
function arg_getfirst(args, arg)
320
if (r instanceof Array)
326
/** Given an argument map, as output in the args parameter of the return of
327
* parseurl, gets all occurences of an argument in the URL string, as an
329
* If the argument was not found, returns [].
330
* Otherwise, returns all occurences as an array, even if there was only one.
331
* \param args Object mapping arguments to strings or arrays of strings.
332
* \param arg String. Argument name.
333
* \return Array of strings.
335
function arg_getlist(args, arg)
340
if (r instanceof Array)
346
/** Joins one or more paths together. Accepts 1 or more arguments.
348
function path_join(path1 /*, path2, ... */)
352
for (var i=1; i<arguments.length; i++)
355
if (arg.length == 0) continue;
360
if (path[path.length-1] != '/')
369
/** Builds a multipart_formdata string from an args object. Similar to
370
* make_query_string, but it returns data of type "multipart/form-data"
371
* instead of "application/x-www-form-urlencoded". This is good for
372
* encoding large strings such as text objects from the editor.
373
* Should be written with a Content-Type of
374
* "multipart/form-data, boundary=<boundary>".
375
* All fields are sent with a Content-Type of text/plain.
376
* \param args Args object as described in parse_url.
377
* \param boundary Random "magic" string which DOES NOT appear in any of
378
* the argument values. This should match the "boundary=" value written to
379
* the Content-Type header.
380
* \return String in multipart/form-data format.
382
function make_multipart_formdata(args, boundary)
387
var extend_data = function(arg_key, arg_val)
389
/* FIXME: Encoding not supported here (should not matter if we
390
* only use ASCII names */
391
data += "--" + boundary + "\n"
392
+ "Content-Disposition: form-data; name=\"" + arg_key
397
for (var arg_key in args)
399
arg_val = args[arg_key];
400
if (arg_val instanceof Array)
401
for (var i=0; i<arg_val.length; i++)
403
extend_data(arg_key, arg_val[i]);
406
extend_data(arg_key, arg_val);
409
data += "--" + boundary + "--\n";
414
/** Converts a list of directories into a path name, with a slash at the end.
415
* \param pathlist List of strings.
418
function pathlist_to_path(pathlist)
420
ret = path_join.apply(null, pathlist);
421
if (ret[ret.length-1] != '/')
426
/** Given a path relative to the IVLE root, gives a path relative to
429
function make_path(path)
431
return path_join(root_dir, path);
434
/** Makes an XMLHttpRequest call to the server. Waits (synchronously) for a
435
* response, and returns an XMLHttpRequest object containing the completed
438
* \param app IVLE app to call (such as "fileservice").
439
* \param path URL path to make the request to, within the application.
440
* \param args Argument object, as described in parse_url and friends.
441
* \param method String; "GET" or "POST"
442
* \param content_type String, optional. Only applies if method is "POST".
443
* May be "application/x-www-form-urlencoded" or "multipart/form-data".
444
* Defaults to "application/x-www-form-urlencoded".
445
* \return An XMLHttpRequest object containing the completed response.
447
function ajax_call(app, path, args, method, content_type)
449
if (content_type != "multipart/form-data")
450
content_type = "application/x-www-form-urlencoded";
451
path = make_path(path_join(app, path));
453
/* A random string, for multipart/form-data
454
* (This is not checked against anywhere else, it is solely defined and
455
* used within this function) */
456
var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
457
var xhr = new XMLHttpRequest();
460
/* GET sends the args in the URL */
461
url = build_url({"path": path, "args": args});
462
/* open's 3rd argument = false -> SYNCHRONOUS (wait for response)
463
* (No need for a callback function) */
464
xhr.open(method, url, false);
469
/* POST sends the args in application/x-www-form-urlencoded */
470
url = encodeURI(path);
471
xhr.open(method, url, false);
473
if (content_type == "multipart/form-data")
475
xhr.setRequestHeader("Content-Type",
476
"multipart/form-data, boundary=" + boundary);
477
message = make_multipart_formdata(args, boundary);
481
xhr.setRequestHeader("Content-Type", content_type);
482
message = make_query_string(args);