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
var elem = document.createElement(tagname);
42
elem.appendChild(document.createTextNode(text));
46
/** Creates a DOM element with hyperlinked text inside it.
47
* \param tagname String. Name of the element's tag (eg. "p").
48
* \param text String. Text to be placed inside the element.
49
* \param href String. URL the text will link to. This is a raw string,
50
* it will automatically be URL-encoded.
51
* \param onclick Optional string. Will be set as the "onclick" attribute
53
* \return DOM Element object.
55
function dom_make_link_elem(tagname, text, href, onclick)
57
var elem = document.createElement(tagname);
58
var link = document.createElement("a");
59
link.setAttribute("href", encodeURI(href));
61
link.setAttribute("onclick", onclick);
62
link.appendChild(document.createTextNode(text));
63
elem.appendChild(link);
67
/** Given a number of bytes, returns a string representing the file size in a
68
* human-readable format.
69
* eg. nice_filesize(6) -> "6 bytes"
70
* nice_filesize(81275) -> "79.4 kB"
71
* nice_filesize(13498346) -> "12.9 MB"
72
* \param bytes Number of bytes. Must be an integer.
75
function nice_filesize(bytes)
79
return bytes.toString() + " bytes";
82
return size.toFixed(1) + " kB";
85
return size.toFixed(1) + " MB";
87
return size.toFixed(1) + " GB";
90
/** Given a URL, returns an object containing a number of attributes
91
* describing the components of the URL, similar to CGI request variables.
92
* The object has the following attributes:
99
* The first five of these are strings, which comprise the URL as follows:
100
* <scheme> "://" <server_name> ":" <server_port> <path> "?" <query_string>
101
* Any of these strings may be set to null if not found.
103
* "args" is an object whose attributes are the query_string arguments broken
105
* Args values are strings for single values, arrays of strings for values
106
* whose names appear multiple times.
107
* args is never null, though it may be empty.
109
* All strings are decoded/unescaped. Reserved characters
110
* (; , / ? : @ & = + * $) are not decoded except in args.
112
* \param url String. A URL. To read from the current browser window, use
113
* window.location.href.
114
* \return The above described object.
116
function parse_url(url)
123
url = decodeURI(url);
125
/* Split scheme from rest */
126
index = url.indexOf("://");
131
obj.scheme = url.substr(0, index);
132
url = url.substr(index+3);
135
/* Split server name/port from rest */
136
index = url.indexOf("/");
144
serverpart = url.substr(0, index);
145
url = url.substr(index+1);
148
/* Split server name from port */
149
index = serverpart.indexOf(":");
152
obj.server_name = serverpart;
153
obj.server_port = null;
157
obj.server_name = serverpart.substr(0, index);
158
obj.server_port = serverpart.substr(index+1);
161
/* Split path from query string */
165
obj.query_string = null;
169
index = url.indexOf("?");
173
obj.query_string = null;
177
obj.path = url.substr(0, index);
178
obj.query_string = url.substr(index+1);
182
/* Split query string into arguments */
184
if (obj.query_string != null)
186
var args_strs = obj.query_string.split("&");
188
var arg_key, arg_val;
189
for (var i=0; i<args_strs.length; i++)
191
arg_str = args_strs[i];
192
index = arg_str.indexOf("=");
193
/* Ignore malformed args */
196
arg_key = decodeURIComponent(arg_str.substr(0, index));
197
arg_val = decodeURIComponent(arg_str.substr(index+1));
200
/* Collision - make an array */
201
if (args[arg_key] instanceof Array)
202
args[arg_key][args[arg_key].length] = arg_val;
204
args[arg_key] = [args[arg_key], arg_val];
207
args[arg_key] = arg_val;
216
/** Builds a query_string from an args object. Encodes the arguments.
217
* \param args Args object as described in parse_url.
218
* \return Query string portion of a URL.
220
function make_query_string(args)
222
var query_string = "";
224
for (var arg_key in args)
226
arg_val = args[arg_key];
227
if (arg_val instanceof Array)
228
for (var i=0; i<arg_val.length; i++)
229
query_string += "&" + encodeURIComponent(arg_key) + "=" +
230
encodeURIComponent(arg_val[i]);
232
query_string += "&" + encodeURIComponent(arg_key) + "=" +
233
encodeURIComponent(arg_val);
235
if (query_string == "")
238
/* Drop the first "&" */
239
query_string = query_string.substr(1);
244
/** Given an object exactly of the form described for the output of parseurl,
245
* returns a URL string built from those parameters. The URL is properly
247
* parseurl and buildurl are strict inverses of each other.
248
* Note that either query_string or args may be supplied. If both are
249
* supplied, query_string is preferred (because it keeps the argument order).
250
* If you take a url from parseurl, modify args, and pass to buildurl,
251
* you need to set query_string to null to use the new args.
252
* \param obj Object as returned by parseurl.
253
* \return String, a URL.
255
function build_url(obj)
258
var query_string = null;
260
if (("scheme" in obj) && obj.scheme != null)
261
url = obj.scheme.toString() + "://";
262
if (("server_name" in obj) && obj.server_name != null)
263
url += obj.server_name.toString();
264
if (("server_port" in obj) && obj.server_port != null)
265
url += ":" + obj.server_port.toString();
266
if (("path" in obj) && obj.path != null)
268
var path = obj.path.toString();
269
if (url.length > 0 && path.length > 0 && path[0] != "/")
273
if (("query_string" in obj) && obj.query_string != null)
274
query_string = obj.query_string.toString();
275
else if (("args" in obj) && obj.args != null)
276
query_string = make_query_string(obj.args);
278
if (query_string != null)
279
url += "?" + query_string;
281
return encodeURI(url);
284
/** Given an argument map, as output in the args parameter of the return of
285
* parseurl, gets the first occurence of an argument in the URL string.
286
* If the argument was not found, returns null.
287
* If there was a single argument, returns the argument.
288
* If there were multiple arguments, returns the first.
289
* \param args Object mapping arguments to strings or arrays of strings.
290
* \param arg String. Argument name.
293
function arg_getfirst(args, arg)
298
if (r instanceof Array)
304
/** Given an argument map, as output in the args parameter of the return of
305
* parseurl, gets all occurences of an argument in the URL string, as an
307
* If the argument was not found, returns [].
308
* Otherwise, returns all occurences as an array, even if there was only one.
309
* \param args Object mapping arguments to strings or arrays of strings.
310
* \param arg String. Argument name.
311
* \return Array of strings.
313
function arg_getlist(args, arg)
318
if (r instanceof Array)
324
/** Joins one or more paths together. Accepts 1 or more arguments.
326
function path_join(path1 /*, path2, ... */)
330
for (var i=1; i<arguments.length; i++)
333
if (arg.length == 0) continue;
338
if (path[path.length-1] != '/')
347
/** Builds a multipart_formdata string from an args object. Similar to
348
* make_query_string, but it returns data of type "multipart/form-data"
349
* instead of "application/x-www-form-urlencoded". This is good for
350
* encoding large strings such as text objects from the editor.
351
* Should be written with a Content-Type of
352
* "multipart/form-data, boundary=<boundary>".
353
* All fields are sent with a Content-Type of text/plain.
354
* \param args Args object as described in parse_url.
355
* \param boundary Random "magic" string which DOES NOT appear in any of
356
* the argument values. This should match the "boundary=" value written to
357
* the Content-Type header.
358
* \return String in multipart/form-data format.
360
function make_multipart_formdata(args, boundary)
365
var extend_data = function(arg_key, arg_val)
367
/* FIXME: Encoding not supported here (should not matter if we
368
* only use ASCII names */
369
data += "--" + boundary + "\n"
370
+ "Content-Disposition: form-data; name=\"" + arg_key
375
for (var arg_key in args)
377
arg_val = args[arg_key];
378
if (arg_val instanceof Array)
379
for (var i=0; i<arg_val.length; i++)
381
extend_data(arg_key, arg_val[i]);
384
extend_data(arg_key, arg_val);
387
data += "--" + boundary + "--\n";
392
/** Converts a list of directories into a path name, with a slash at the end.
393
* \param pathlist List of strings.
396
function pathlist_to_path(pathlist)
398
ret = path_join.apply(null, pathlist);
399
if (ret[ret.length-1] != '/')
404
/** Given a path relative to the IVLE root, gives a path relative to
407
function make_path(path)
409
return path_join(root_dir, path);
412
/** Makes an XMLHttpRequest call to the server. Waits (synchronously) for a
413
* response, and returns an XMLHttpRequest object containing the completed
416
* \param app IVLE app to call (such as "fileservice").
417
* \param path URL path to make the request to, within the application.
418
* \param args Argument object, as described in parse_url and friends.
419
* \param method String; "GET" or "POST"
420
* \param content_type String, optional. Only applies if method is "POST".
421
* May be "application/x-www-form-urlencoded" or "multipart/form-data".
422
* Defaults to "application/x-www-form-urlencoded".
423
* \return An XMLHttpRequest object containing the completed response.
425
function ajax_call(app, path, args, method, content_type)
427
if (content_type != "multipart/form-data")
428
content_type = "application/x-www-form-urlencoded";
429
path = make_path(path_join(app, path));
431
/* A random string, for multipart/form-data
432
* (This is not checked against anywhere else, it is solely defined and
433
* used within this function) */
434
var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
435
var xhr = new XMLHttpRequest();
438
/* GET sends the args in the URL */
439
url = build_url({"path": path, "args": args});
440
/* open's 3rd argument = false -> SYNCHRONOUS (wait for response)
441
* (No need for a callback function) */
442
xhr.open(method, url, false);
447
/* POST sends the args in application/x-www-form-urlencoded */
448
url = encodeURI(path);
449
xhr.open(method, url, false);
451
if (content_type == "multipart/form-data")
453
xhr.setRequestHeader("Content-Type",
454
"multipart/form-data, boundary=" + boundary);
455
message = make_multipart_formdata(args, boundary);
459
xhr.setRequestHeader("Content-Type", content_type);
460
message = make_query_string(args);