~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to www/media/common/util.js

  • Committer: mattgiuca
  • Date: 2008-03-15 04:20:30 UTC
  • Revision ID: svn-v3-trunk0:2b9c9e99-6f39-0410-b283-7f802c844ae2:trunk:693
db: get_problem_problemid now automatically inserts a new entry if the problem
    doesn't exist (now it is no longer referentially transparent, but it is
    idempotent).
    Removed insert_problem - you can just call get_problem_problemid to do
    this.
tutorialservice: No longer tries to insert a new entry if problem doesnt
    exist, just expects db to do this.
    No longer calls insert_problem (removed).

Show diffs side-by-side

added added

removed removed

Lines of Context:
22
22
 * Defines some generic JavaScript utility functions.
23
23
 */
24
24
 
 
25
/* Expects the following variables to have been declared by JavaScript in
 
26
 * the HTML generated by the server:
 
27
 * - root_dir
 
28
 * - username
 
29
 */
 
30
 
25
31
/** Removes all children of a given DOM element
26
32
 * \param elem A DOM Element. Will be modified.
27
33
 */
34
40
/** Creates a DOM element with simple text inside it.
35
41
 * \param tagname String. Name of the element's tag (eg. "p").
36
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).
37
45
 * \return DOM Element object.
38
46
 */
39
 
function dom_make_text_elem(tagname, text)
 
47
function dom_make_text_elem(tagname, text, title)
40
48
{
 
49
    if (text == null) text = "";
41
50
    var elem = document.createElement(tagname);
42
 
    elem.appendChild(document.createTextNode(text));
 
51
    var textnode;
 
52
    if (title == null)
 
53
        textnode = document.createTextNode(text);
 
54
    else
 
55
    {
 
56
        textnode = document.createElement("span");
 
57
        textnode.setAttribute("title", title);
 
58
        textnode.appendChild(document.createTextNode(text));
 
59
    }
 
60
    elem.appendChild(textnode);
43
61
    return elem;
44
62
}
45
63
 
46
64
/** Creates a DOM element with hyperlinked text inside it.
47
65
 * \param tagname String. Name of the element's tag (eg. "p").
48
66
 * \param text String. Text to be placed inside the element.
 
67
 * \param title String, optional. Sets a tooltip for the link.
49
68
 * \param href String. URL the text will link to. This is a raw string,
50
69
 *  it will automatically be URL-encoded.
51
70
 * \param onclick Optional string. Will be set as the "onclick" attribute
52
71
 *  of the "a" element.
 
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.
53
75
 * \return DOM Element object.
54
76
 */
55
 
function dom_make_link_elem(tagname, text, href, onclick)
 
77
function dom_make_link_elem(tagname, text, title, href, onclick, dontencode)
56
78
{
 
79
    if (text == null) text = "";
 
80
    if (href == null) href = "";
57
81
    var elem = document.createElement(tagname);
58
82
    var link = document.createElement("a");
59
 
    link.setAttribute("href", encodeURI(href));
 
83
    if (dontencode != true)
 
84
        href = urlencode_path(href);
 
85
    link.setAttribute("href", href);
 
86
    if (title != null)
 
87
        link.setAttribute("title", title);
60
88
    if (onclick != null)
61
89
        link.setAttribute("onclick", onclick);
62
90
    link.appendChild(document.createTextNode(text));
64
92
    return elem;
65
93
}
66
94
 
 
95
/** Creates a DOM img element. All parameters are optional except src.
 
96
 * If alt (compulsory in HTML) is omitted, will be set to "".
 
97
 */
 
98
function dom_make_img(src, width, height, title, alt)
 
99
{
 
100
    var img = document.createElement("img");
 
101
    img.setAttribute("src", urlencode_path(src));
 
102
    if (width != null)
 
103
        img.setAttribute("width", width);
 
104
    if (height != null)
 
105
        img.setAttribute("height", height);
 
106
    if (title != null)
 
107
        img.setAttribute("title", title);
 
108
    if (alt == null) alt = "";
 
109
    img.setAttribute("alt", alt);
 
110
    return img;
 
111
}
 
112
 
67
113
/** Given a number of bytes, returns a string representing the file size in a
68
114
 * human-readable format.
69
115
 * eg. nice_filesize(6) -> "6 bytes"
74
120
 */
75
121
function nice_filesize(bytes)
76
122
{
 
123
    if (bytes == null) return "";
77
124
    var size;
78
125
    if (bytes < 1024)
79
 
        return bytes.toString() + " bytes";
 
126
        return bytes.toString() + " B";
80
127
    size = bytes / 1024;
81
128
    if (size < 1024)
82
129
        return size.toFixed(1) + " kB";
107
154
 * args is never null, though it may be empty.
108
155
 *
109
156
 * All strings are decoded/unescaped. Reserved characters
110
 
 * (; , / ? : @ & = + * $) are not decoded except in args.
 
157
 * (; , / ? : @ & = + * $) are not decoded except in args and path.
111
158
 *
112
159
 * \param url String. A URL. To read from the current browser window, use
113
160
 *  window.location.href.
120
167
    var serverpart;
121
168
    var args;
122
169
 
123
 
    url = decodeURI(url);
124
 
 
125
170
    /* Split scheme from rest */
126
171
    index = url.indexOf("://");
127
172
    if (index < 0)
142
187
    else
143
188
    {
144
189
        serverpart = url.substr(0, index);
145
 
        url = url.substr(index+1);
 
190
        url = url.substr(index);
146
191
    }
147
192
 
148
193
    /* Split server name from port */
178
223
            obj.query_string = url.substr(index+1);
179
224
        }
180
225
    }
 
226
    obj.path = decodeURIComponent(obj.path);
181
227
 
182
228
    /* Split query string into arguments */
183
229
    args = {};
232
278
            query_string += "&" + encodeURIComponent(arg_key) + "=" +
233
279
                encodeURIComponent(arg_val);
234
280
    }
235
 
    if (query_string == "")
236
 
        query_string = null;
237
 
    else
 
281
    if (query_string != "")
238
282
        /* Drop the first "&" */
239
283
        query_string = query_string.substr(1);
240
284
 
265
309
        url += ":" + obj.server_port.toString();
266
310
    if (("path" in obj) && obj.path != null)
267
311
    {
268
 
        var path = obj.path.toString();
 
312
        var path = urlencode_path(obj.path.toString());
269
313
        if (url.length > 0 && path.length > 0 && path[0] != "/")
270
314
            path = "/" + path;
271
315
        url += path;
272
316
    }
273
317
    if (("query_string" in obj) && obj.query_string != null)
274
 
        query_string = obj.query_string.toString();
 
318
        query_string = encodeURI(obj.query_string.toString());
275
319
    else if (("args" in obj) && obj.args != null)
276
320
        query_string = make_query_string(obj.args);
277
321
 
278
 
    if (query_string != null)
 
322
    if (query_string != "" && query_string != null)
279
323
        url += "?" + query_string;
280
324
 
281
 
    return encodeURI(url);
 
325
    return url;
 
326
}
 
327
 
 
328
/** URL-encodes a path. This is a special case of URL encoding as all
 
329
 * characters *except* the slash must be encoded.
 
330
 */
 
331
function urlencode_path(path)
 
332
{
 
333
    /* Split up the path, URLEncode each segment with encodeURIComponent,
 
334
     * and rejoin.
 
335
     */
 
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;
 
341
    return path;
 
342
}
 
343
 
 
344
/** Writes a JSONable object to the cookie under a particular key
 
345
 * (JSON encoded and URL encoded).
 
346
 */
 
347
function write_cookie(key, value)
 
348
{
 
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;
 
355
}
 
356
/** Reads a cookie which has a JSONable object encoded as its value.
 
357
 * Returns the object, parsed from JSON.
 
358
 */
 
359
function read_cookie(key)
 
360
{
 
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++)
 
365
    {
 
366
        var cookie = cookies[i];
 
367
        while (cookie[0] == ' ')
 
368
            cookie = cookie.substr(1);
 
369
        if (cookie.substr(0, checklen) == checkstart)
 
370
        {
 
371
            var valstr = cookie.substr(checklen);
 
372
            valstr = decodeURIComponent(valstr);
 
373
            return JSON.parse(valstr);
 
374
        }
 
375
    }
282
376
}
283
377
 
284
378
/** Given an argument map, as output in the args parameter of the return of
326
420
function path_join(path1 /*, path2, ... */)
327
421
{
328
422
    var arg;
329
 
    path = path1;
330
 
    for (var i=1; i<arguments.length; i++)
 
423
    var path = "";
 
424
    for (var i=0; i<arguments.length; i++)
331
425
    {
332
426
        arg = arguments[i];
333
427
        if (arg.length == 0) continue;
335
429
            path = arg;
336
430
        else
337
431
        {
338
 
            if (path[path.length-1] != '/')
 
432
            if (path.length > 0 && path[path.length-1] != '/')
339
433
                path += '/';
340
434
            path += arg;
341
435
        }
366
460
    {
367
461
        /* FIXME: Encoding not supported here (should not matter if we
368
462
         * only use ASCII names */
369
 
        data += "--" + boundary + "\n"
 
463
        data += "--" + boundary + "\r\n"
370
464
            + "Content-Disposition: form-data; name=\"" + arg_key
371
 
            + "\"\n\n"
372
 
            + arg_val + "\n";
 
465
            + "\"\r\n\r\n"
 
466
            + arg_val + "\r\n";
373
467
    }
374
468
 
375
469
    for (var arg_key in args)
384
478
            extend_data(arg_key, arg_val);
385
479
    }
386
480
    /* End boundary */
387
 
    data += "--" + boundary + "--\n";
 
481
    data += "--" + boundary + "--\r\n";
388
482
 
389
483
    return data;
390
484
}
409
503
    return path_join(root_dir, path);
410
504
}
411
505
 
412
 
/** Makes an XMLHttpRequest call to the server. Waits (synchronously) for a
413
 
 * response, and returns an XMLHttpRequest object containing the completed
414
 
 * response.
 
506
/** Shorthand for make_path(path_join(app, ...))
 
507
 * Creates an absolute path for a given path within a given app.
 
508
 */
 
509
function app_path(app /*,...*/)
 
510
{
 
511
    return make_path(path_join.apply(null, arguments));
 
512
}
 
513
 
 
514
/** Given a path, gets the "basename" (the last path segment).
 
515
 */
 
516
function path_basename(path)
 
517
{
 
518
    segments = path.split("/");
 
519
    if (segments[segments.length-1].length == 0)
 
520
        return segments[segments.length-2];
 
521
    else
 
522
        return segments[segments.length-1];
 
523
}
 
524
 
 
525
/** Given a string str, determines whether it ends with substr */
 
526
function endswith(str, substring)
 
527
{
 
528
    if (str.length < substring.length) return false;
 
529
    return str.substr(str.length - substring.length) == substring;
 
530
}
 
531
 
 
532
/** Equivalent to Python's repr.
 
533
 * Gets the JavaScript string representation.
 
534
 * Actually just calls JSON.stringify.
 
535
 */
 
536
function repr(str)
 
537
{
 
538
    return JSON.stringify(str);
 
539
}
 
540
 
 
541
/** Removes all occurences of a value from an array.
 
542
 */
 
543
Array.prototype.removeall = function(val)
 
544
{
 
545
    var i, j;
 
546
    var arr = this;
 
547
    j = 0;
 
548
    for (i=0; i<arr.length; i++)
 
549
    {
 
550
        arr[j] = arr[i];
 
551
        if (arr[i] != val) j++;
 
552
    }
 
553
    arr.splice(j, i-j);
 
554
}
 
555
 
 
556
/** Shallow-clones an object */
 
557
function shallow_clone_object(obj)
 
558
{
 
559
    o = {};
 
560
    for (k in obj)
 
561
        o[k] = obj[k];
 
562
    return o;
 
563
}
 
564
 
 
565
/** Returns a new XMLHttpRequest object, in a somewhat browser-agnostic
 
566
 * fashion.
 
567
 */
 
568
function new_xmlhttprequest()
 
569
{
 
570
    try
 
571
    {
 
572
        /* Real Browsers */
 
573
        return new XMLHttpRequest();
 
574
    }
 
575
    catch (e)
 
576
    {
 
577
        /* Internet Explorer */
 
578
        try
 
579
        {
 
580
            return new ActiveXObject("Msxml2.XMLHTTP");
 
581
        }
 
582
        catch (e)
 
583
        {
 
584
            try
 
585
            {
 
586
                return new ActiveXObject("Microsoft.XMLHTTP");
 
587
            }
 
588
            catch (e)
 
589
            {
 
590
                throw("Your browser does not support AJAX. "
 
591
                    + "IVLE requires a modern browser.");
 
592
            }
 
593
        }
 
594
    }
 
595
}
 
596
 
 
597
/** Makes an asynchronous XMLHttpRequest call to the server.
 
598
 * Sends the XMLHttpRequest object containing the completed response to a
 
599
 * specified callback function.
415
600
 *
 
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.
416
604
 * \param app IVLE app to call (such as "fileservice").
417
605
 * \param path URL path to make the request to, within the application.
418
606
 * \param args Argument object, as described in parse_url and friends.
420
608
 * \param content_type String, optional. Only applies if method is "POST".
421
609
 *      May be "application/x-www-form-urlencoded" or "multipart/form-data".
422
610
 *      Defaults to "application/x-www-form-urlencoded".
423
 
 * \return An XMLHttpRequest object containing the completed response.
424
611
 */
425
 
function ajax_call(app, path, args, method, content_type)
 
612
function ajax_call(callback, app, path, args, method, content_type)
426
613
{
427
614
    if (content_type != "multipart/form-data")
428
615
        content_type = "application/x-www-form-urlencoded";
429
 
    path = make_path(path_join(app, path));
 
616
    path = app_path(app, path);
430
617
    var url;
431
618
    /* A random string, for multipart/form-data
432
619
     * (This is not checked against anywhere else, it is solely defined and
433
620
     * used within this function) */
434
621
    var boundary = "48234n334nu7n4n2ynonjn234t683jyh80j";
435
 
    var xhr = new XMLHttpRequest();
 
622
    var xhr = new_xmlhttprequest();
 
623
    xhr.onreadystatechange = function()
 
624
        {
 
625
            if (xhr.readyState == 4)
 
626
            {
 
627
                callback(xhr);
 
628
            }
 
629
        }
436
630
    if (method == "GET")
437
631
    {
438
632
        /* GET sends the args in the URL */
439
633
        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);
443
 
        xhr.send("");
 
634
        /* open's 3rd argument = true -> asynchronous */
 
635
        xhr.open(method, url, true);
 
636
        xhr.send(null);
444
637
    }
445
638
    else
446
639
    {
447
640
        /* POST sends the args in application/x-www-form-urlencoded */
448
641
        url = encodeURI(path);
449
 
        xhr.open(method, url, false);
 
642
        xhr.open(method, url, true);
450
643
        var message;
451
644
        if (content_type == "multipart/form-data")
452
645
        {
459
652
            xhr.setRequestHeader("Content-Type", content_type);
460
653
            message = make_query_string(args);
461
654
        }
 
655
        xhr.setRequestHeader("Content-Length", message.length);
462
656
        xhr.send(message);
463
657
    }
464
 
    return xhr;
465
658
}
466
659