web.php 54.8 KB
Newer Older
1
2
<?php
/**
Nigel McNie's avatar
Nigel McNie committed
3
 * This program is part of Mahara
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * @package    mahara
 * @subpackage core
 * @author     Penny Leach <penny@catalyst.net.nz>
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
 * @copyright  (C) 2006,2007 Catalyst IT Ltd http://catalyst.net.nz
 * @copyright  (C) portions from Moodle, (C) Martin Dougiamas http://dougiamas.com
 */

defined('INTERNAL') || die();


/**
 * This function creates a Smarty object and sets it up for use within our
 * podclass app, setting up some variables.
 *
 * The variables that it sets up are:
 *
 * - THEMEURL: The base url for static content
37
 * - WWWROOT: The base url for the Mahara system
38
39
40
41
42
 * - USER: The user object
 * - JAVASCRIPT: A list of javascript files to include in the header.  This
 *   list is passed into this function (see below).
 * - HEADERS: An array of any further headers to set.  Each header is just
 *   straight HTML (see below).
43
44
 * - PUBLIC: Set true if this page is a public page
 * - MAINNAV: Array defining the main navigation
45
 *
46
47
48
49
50
 * @param $javascript A list of javascript includes.  Each include should be just
 *                    the name of a file, and reside in {$THEMEURL}js/{filename}
 * @param $headers    A list of additional headers.  These are to be specified as
 *                    actual HTML.
 * @param $strings    A list of language strings required by the javascript code.
51
52
 * @return Smarty
 */
53
54

//smarty(array('js/tablerenderer.js', 'artefact/file/js/filebrowser.js'))
55
function &smarty($javascript = array(), $headers = array(), $pagestrings = array(), $extraconfig = array()) {
56
    global $USER, $SESSION, $CFG;
Martyn Smith's avatar
Martyn Smith committed
57
    $SIDEBLOCKS = array();
58
59

    require_once(get_config('libroot') . 'smarty/Smarty.class.php');
60
    $wwwroot = get_config('wwwroot');
Martyn Smith's avatar
Martyn Smith committed
61
62

    $theme_list = array();
63
64
65
66
    
    if (function_exists('pieform_get_headdata')) {
        $headers = array_merge($headers, pieform_get_headdata());
    }
67

68
    // Insert the appropriate javascript tags 
69
    $javascript_array = array();
70
    $jsroot = $wwwroot . 'js/';
71

Richard Mansfield's avatar
Richard Mansfield committed
72
    // TinyMCE must be included first for some reason we're not sure about
73
74
75
76
    $checkarray = array(&$javascript, &$headers);
    foreach ($checkarray as &$check) {
        if (($key = array_search('tinymce', $check)) !== false) {
            $javascript_array[] = $jsroot . 'tinymce/tiny_mce.js';
77
78
            if (isset($extraconfig['tinymceinit'])) {
                $headers[] = $extraconfig['tinymceinit'];
Nigel McNie's avatar
Gaah    
Nigel McNie committed
79
80
            }
            else {
Martyn Smith's avatar
Martyn Smith committed
81
                $content_css = json_encode(theme_get_url('style/tinymce.css'));
82
                $headers[] = <<<EOF
83
84
85
86
<script type="text/javascript">
tinyMCE.init({
    mode: "textareas",
    editor_selector: 'wysiwyg',
87
    button_tile_map: true,
88
    theme: "advanced",
89
90
    plugins: "table,emotions,iespell,inlinepopups,paste",
    theme_advanced_buttons1 : "bold,italic,underline,strikethrough,separator,forecolor,backcolor,separator,justifyleft,justifycenter,justifyright,justifyfull,separator,hr,emotions,iespell,cleanup,separator,link,unlink,separator,code",
91
    theme_advanced_buttons2 : "bullist,numlist,separator,tablecontrols,separator,cut,copy,paste,pasteword",
92
    theme_advanced_buttons3 : "fontselect,separator,fontsizeselect,separator,formatselect",
93
    theme_advanced_toolbar_location : "top",
94
    theme_advanced_toolbar_align : "center",
95
    width: '512',
Martyn Smith's avatar
Martyn Smith committed
96
    content_css : {$content_css}
97
98
99
100
});
</script>

EOF;
101
            }
102
103
            unset($check[$key]);
            break;
104
        }
105
106
    }

Martyn Smith's avatar
Martyn Smith committed
107
    $javascript_array[] = $jsroot . 'MochiKit/setup.js';
Martyn Smith's avatar
Martyn Smith committed
108
    $javascript_array[] = $jsroot . 'keyboardNavigation.js';
109

110
    $strings = array();
111
112
113
114
115
116
117
118
119
    foreach ($pagestrings as $k => $v) {
        if (is_array($v)) {
            foreach ($v as $tag) {
                $strings[$tag] = get_raw_string($tag, $k);
            }
        }
        else {
            $strings[$k] = get_raw_string($k, $v);
        }
120
121
    }

122
    $jsstrings = jsstrings();
Martyn Smith's avatar
Martyn Smith committed
123
    $themepaths = themepaths();
124

Richard Mansfield's avatar
Richard Mansfield committed
125
    foreach ($javascript as $jsfile) {
126
127
128
129
        // For now, if there's no path in the js file, assume it's in
        // $jsroot and append '.js' to the name.  Later we may want to
        // ensure all smarty() calls include the full path to the js
        // file, with the proper extension.
130
        if (strpos($jsfile, '/') === false) {
131
            $javascript_array[] = $jsroot . $jsfile . '.js';
132
            if (isset($jsstrings[$jsfile])) {
133
134
135
                foreach ($jsstrings[$jsfile] as $section => $tags) {
                    foreach ($tags as $tag) {
                        $strings[$tag] = get_raw_string($tag, $section);
136
137
138
                    }
                }
            }
Martyn Smith's avatar
Martyn Smith committed
139
140
141
142
143
            if (isset($themepaths[$jsfile])) {
                foreach ($themepaths[$jsfile] as $themepath) {
                    $theme_list[$themepath] = theme_get_url($themepath);
                }
            }
144
145
        }
        else {
146
            // A .js file with a fully specified path
147
            $javascript_array[] = $wwwroot . $jsfile;
148
149
150
151
152
153
            // If $jsfile is from a plugin (i.e. plugintype/pluginname/js/foo.js)
            // Then get js strings from static function jsstrings in plugintype/pluginname/lib.php 
            $bits = explode('/', $jsfile);
            if (count($bits) == 4) {
                safe_require($bits[0], $bits[1]);
                $pluginclass = generate_class_name($bits[0], $bits[1]);
154
                $name = substr($bits[3], 0, strpos($bits[3], '.js'));
155
156
                if (is_callable(array($pluginclass, 'jsstrings'))) {
                    $tempstrings = call_static_method($pluginclass, 'jsstrings', $name);
157
158
159
                    foreach ($tempstrings as $section => $tags) {
                        foreach ($tags as $tag) {
                            $strings[$tag] = get_raw_string($tag, $section);
160
161
                        }
                    }
Richard Mansfield's avatar
Richard Mansfield committed
162
                }
163
164
165
166
167
168
169
170
171
                if (is_callable(array($pluginclass, 'jshelp'))) {
                    $tempstrings = call_static_method($pluginclass, 'jshelp', $name);
                    foreach ($tempstrings as $section => $tags) {
                        foreach ($tags as $tag) {
                            $strings[$tag . '.help'] = get_help_icon($bits[0], $bits[1], null, null,
                                                                     null, $tag);
                        }
                    }
                }
Martyn Smith's avatar
Martyn Smith committed
172
173
174
175
176
177
                if (is_callable(array($pluginclass, 'themepaths'))) {
                    $tmpthemepaths = call_static_method($pluginclass, 'themepaths', $name);
                    foreach ($tmpthemepaths as $themepath) {
                        $theme_list[$themepath] = theme_get_url($themepath);
                    }
                }
Martyn Smith's avatar
Martyn Smith committed
178
            }
Martyn Smith's avatar
Martyn Smith committed
179
        }
180
    }
181
182
183
184

    $javascript_array[] = $jsroot . 'mahara.js';
    $javascript_array[] = $jsroot . 'debug.js';

185
186
187
    foreach ($jsstrings['mahara'] as $section => $tags) {
        foreach ($tags as $tag) {
            $strings[$tag] = get_raw_string($tag, $section);
188
189
        }
    }
Martyn Smith's avatar
Martyn Smith committed
190
191
192
    foreach ($themepaths['mahara'] as $themepath) {
        $theme_list[$themepath] = theme_get_url($themepath);
    }
193
194
195
196
197
    if (isset($extraconfig['themepaths']) && is_array($extraconfig['themepaths'])) {
        foreach ($extraconfig['themepaths'] as $themepath) {
            $theme_list[$themepath] = theme_get_url($themepath);
        }
    }
198

199
    $stringjs = '<script type="text/javascript">';
200
    $stringjs .= 'var strings = ' . json_encode($strings) . ';';
201
202
203
    $stringjs .= '</script>';
    $headers[] = $stringjs;

204
    $smarty =& new Smarty();
205
    
206
207
208
209
    $theme = theme_setup();

    $smarty->template_dir = $theme->template_dir;

210
211
212
    $smarty->compile_dir  = get_config('dataroot').'smarty/compile';
    $smarty->cache_dir    = get_config('dataroot').'smarty/cache';

213
    $smarty->assign('THEMEURL', get_config('themeurl'));
214
215
216
217
218
219
220
221
222

    // stylesheet set up - if we're in a plugin also get its stylesheet
    $stylesheets = array_reverse(theme_get_url('style/style.css', null, true));
    if (defined('SECTION_PLUGINTYPE') && defined('SECTION_PLUGINNAME') && SECTION_PLUGINTYPE != 'core') {
        if ($pluginsheets = theme_get_url('style/style.css', SECTION_PLUGINTYPE . '/' . SECTION_PLUGINNAME . '/', true)) {
            $stylesheets = array_merge($stylesheets, array_reverse($pluginsheets));
        }
    }
    $smarty->assign('STYLESHEETLIST', $stylesheets);
223
    $smarty->assign('WWWROOT', $wwwroot);
224
    $smarty->assign('SESSKEY', $USER->get('sesskey'));
Martyn Smith's avatar
Martyn Smith committed
225
    $smarty->assign('THEMELIST', json_encode($theme_list));
226

Martyn Smith's avatar
Martyn Smith committed
227
228
229
230
231
232
233
    if (defined('TITLE')) {
        $smarty->assign('PAGETITLE', TITLE . ' - ' . get_config('sitename'));
    }
    else {
        $smarty->assign('PAGETITLE', get_config('sitename'));
    }

234

235
236
237
    $sitename = get_config('sitename');
    $smarty->assign('title', $sitename);
    $smarty->assign('heading', $sitename);
238

239
240
241
    if (defined('PUBLIC')) {
        $smarty->assign('PUBLIC', true);
    }
242
243
244
    if (defined('ADMIN')) {
        $smarty->assign('ADMIN', true);
    }
245

246
247
    $smarty->assign('LOGGEDIN', $USER->is_logged_in());
    if ($USER->is_logged_in()) {
248
        $smarty->assign('MAINNAV', main_nav());
249
        $smarty->assign('LOGGEDINSTR', get_loggedin_string());
250
251
    }

252
    $smarty->assign_by_ref('USER', $USER);
253
    $smarty->assign_by_ref('JAVASCRIPT', $javascript_array);
254
255
    $smarty->assign_by_ref('HEADERS', $headers);

256
257
    $smarty->assign('searchform', searchform());

258
259
260
261
262
    if ($help = has_page_help()) {
        $smarty->assign('PAGEHELPNAME', $help[0]);
        $smarty->assign('PAGEHELPICON', $help[1]);
    }

Martyn Smith's avatar
Martyn Smith committed
263
264
265
266
267
268
269
270
271
272
    // ---------- sideblock stuff ----------
    if (get_config('installed')) {
        $smarty->assign('SITEMENU', site_menu());
        $SIDEBLOCKS[] = array(
            'name'   => 'mainmenu',
            'weight' => 10,
            'data'   => site_menu(),
        );
    }

273
274
275
276
277
278
279
280
    if ($USER->is_logged_in()) {
        $SIDEBLOCKS[] = array(
            'name'   => 'selfsearch',
            'weight' => 0,
            'data'   => array(),
        );
    }
    else {
Martyn Smith's avatar
Martyn Smith committed
281
282
283
284
285
286
287
288
289
290
        $SIDEBLOCKS[] = array(
            'name'   => 'login',
            'weight' => -10,
            'id'     => 'loginbox',
            'data'   => array(
                'loginform' => auth_generate_login_form(),
            ),
        );
    }

291
292
293
294
295
296
297
298
    require_once($CFG->docroot .'/auth/xmlrpc/lib.php');
    if ($ssopeers = get_service_providers($USER->authinstance)) {
        $SIDEBLOCKS[] = array(
            'name'   => 'ssopeers',
            'weight' => 1,
            'data'   => $ssopeers,
        );
    }
299

Martyn Smith's avatar
Martyn Smith committed
300
301
302
303
304
305
306
307
308
309
    if (isset($extraconfig['sideblocks']) && is_array($extraconfig['sideblocks'])) {
        foreach ($extraconfig['sideblocks'] as $sideblock) {
            $SIDEBLOCKS[] = $sideblock;
        }
    }

    usort($SIDEBLOCKS, create_function('$a,$b', 'if ($a["weight"] == $b["weight"]) return 0; return ($a["weight"] < $b["weight"]) ? -1 : 1;'));

    $smarty->assign('SIDEBLOCKS', $SIDEBLOCKS);

310
311
312
    return $smarty;
}

313
314
/** 
 * Returns the lists of strings used in the .js files
315
 * @return array                   
316
317
 */

318
function jsstrings() {
Martyn Smith's avatar
Martyn Smith committed
319
    return array(
320
321
322
       'mahara' => array(                        // js file
            'mahara' => array(                   // section
                'namedfieldempty',               // string name
323
                'processing',
324
325
326
                'requiredfieldempty',
                'unknownerror',
                'loading',
Martyn Smith's avatar
Martyn Smith committed
327
                'showtags',
328
329
                'unreadmessages',
                'unreadmessage',
330
                'couldnotgethelp',
331
            ),
332
333
        ),
        'tablerenderer' => array(
334
335
336
337
338
339
            'mahara' => array(
                'firstpage',
                'nextpage',
                'prevpage',
                'lastpage',
            )
340
341
342
343
344
345
        ),
        'collapsabletree' => array(
            'view' => array(
                'nochildren',
            ),
        ),
Martyn Smith's avatar
Martyn Smith committed
346
347
348
    );
}

Martyn Smith's avatar
Martyn Smith committed
349
350
351
352
function themepaths() {
    return array(
        'mahara' => array(
            'images/icon_close.gif',
353
            'images/failure.gif',
354
355
            'images/loading.gif',
            'images/success.gif',
356
            'images/icon_help.gif',
Martyn Smith's avatar
Martyn Smith committed
357
358
359
360
        ),
    );
}

361
362
363
364
365
366
/** 
 * Takes an array of string identifiers and returns an array of the
 * corresponding strings, quoted for use in inline javascript here
 * docs.
 */

367
368
369
370
371
372
function quotestrings($strings) {
    $qstrings = array();
    foreach ($strings as $section => $tags) {
        foreach ($tags as $tag) {
            $qstrings[$tag] = "'" . get_string($tag, $section) . "'";
        }
373
    }
374
    return $qstrings;
375
376
}

377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/** 
 * This function sets up and caches info about the current selected theme
 * contains inheritance path (used for locating images) and template dirs
 * and potentially more stuff later ( like mime header to send (html vs xhtml))
 * @return object
 */

function theme_setup() {
    
    static $theme;

    if (!empty($theme)) {
        return $theme;
    }
    
    $theme = new StdClass;
    $theme->theme = get_config('theme');
    $theme->path = get_config('docroot') . 'theme/' . $theme->theme . '/';
    $theme->template_dir = array($theme->path . 'templates/');
    $theme->inheritance = array($theme->theme);

    $parent = $theme->theme;

    while (true) {
        if (!$parent = theme_get_parent($parent)) {
            break;
        }
        if ($parent != 'default') {
            $theme->template_dir[] = get_config('docroot') . 'theme/' . $parent . '/templates/';
            $theme->inheritance[] = $parent;
        }
    }

410
    // always put the default theme at the top of the tree, unless we're already it
411
412
    if ($theme->theme != 'default') {
        $theme->template_dir[] = get_config('docroot')  . 'theme/default/templates/';
413
        $theme->inheritance[] = 'default';
414
    }
415

416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
    return $theme;
}

/** 
 * helper function to walk up the inheritance tree and find a parent
 * @param $currtheme the name of the theme to find the parent for
 * @return parent name or false
 */
function theme_get_parent($currtheme) {

    // look for a config file 
    if (is_readable(get_config('docroot') . 'theme/ ' . $currtheme. '/config.php')) {
        require_once(get_config('docroot') . 'theme/ ' . $currtheme. '/config.php');
        if (!empty($theme->parent) && is_dir(get_config('docroot') . 'theme/ ' . $theme->parent)) {
            return $theme->parent;
        }
    }
    return false;
}

/** 
 * This function returns the full url to an image
 * Always use it to get image urls
 * @param $imagelocation path to image relative to theme/$theme/static/
 * @param $pluginlocation path to plugin relative to docroot
 */
442
function theme_get_url($location, $pluginlocation='', $all = false) {
443
    $theme = theme_setup();
444
    $list = array();
445
446

    foreach ($theme->inheritance as $themedir) {
447
448
449
450
451
452
453
        if (is_readable(get_config('docroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location)) {
            if ($all) {
                $list[] = get_config('wwwroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location;
            }
            else {
                return get_config('wwwroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location;
            }
454
455
        }
    }
456
457
458
459
    if ($all) {
        return $list;
    }
    return;
460
461
}

462
463
464
465
466
467
/** 
 * This function returns the full path to an image
 * Always use it to get image paths
 * @param $imagelocation path to image relative to theme/$theme/static/
 * @param $pluginlocation path to plugin relative to docroot
 */
468
function theme_get_path($location, $pluginlocation='') {
469
470
471
    $theme = theme_setup();

    foreach ($theme->inheritance as $themedir) {
472
473
        if (is_readable(get_config('docroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location)) {
            return get_config('docroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location;
474
475
476
477
        }
    }
}

478
479
480
481
482
/**
 * This function sends headers suitable for all JSON returning scripts.
 *
 */
function json_headers() {
Martyn Smith's avatar
Martyn Smith committed
483
    // @todo martyn This should be changed, but for now it's useful for debugging
484
485
    // header('Content-type: text/x-json');
    header('Content-type: text/plain');
Martyn Smith's avatar
Martyn Smith committed
486
    header('Pragma: no-cache');
487
488
}

Richard Mansfield's avatar
Richard Mansfield committed
489
/**
490
 * This function sends a JSON message, and ends the script.
Richard Mansfield's avatar
Richard Mansfield committed
491
 *
492
493
494
495
496
497
498
499
 * Scripts receiving replies will recieve a JSON array with two fields:
 *
 *  - error: True or false depending on whether the request was successful
 *  - message: JSON data representing a message sent back from the script
 *
 * @param boolean $error   Whether the script ended in an error or not
 * @param string  $message A message to pass back to the user, can be an
 *                         array of JSON data
Richard Mansfield's avatar
Richard Mansfield committed
500
 */
501
function json_reply($error, $message) {
Richard Mansfield's avatar
Richard Mansfield committed
502
    json_headers();
503
    echo json_encode(array('error' => $error, 'message' => $message));
504
    perf_to_log();
Richard Mansfield's avatar
Richard Mansfield committed
505
506
507
    exit;
}

508
509
510
511
512
513
514
515
516
517
518
519
520
521
/**
 * This function checks the user's sesskey against one passed in. If the check
 * fails, a json reply is sent to that effect.
 */
function json_check_sesskey() {
    global $USER;

    $sesskey = param_variable('sesskey', null);

    if ($sesskey === null || $USER->get('sesskey') != $sesskey) {
        json_reply('invalidsesskey', get_string('invalidsesskey'));
    }
}

522
function _param_retrieve($name) {
523
524
525
526
527
528
529
    // prefer post
    if (isset($_POST[$name])) {
        $value = $_POST[$name];
    } 
    else if (isset($_GET[$name])) {
        $value = $_GET[$name];
    }
530
    else if (func_num_args() == 2) {
531
532
533
        $php_work_around = func_get_arg(1);
        return array($php_work_around, true);
    }
534
    else {
535
536
537
        throw new ParameterException("Missing parameter '$name' and no default supplied");
    }

538
    return array($value, false);
539
540
}

Martyn Smith's avatar
Martyn Smith committed
541
542
543
544
545
546
547
548
549
550
551
/**
 * This function returns a GET or POST parameter with optional default.  If the
 * default isn't specified and the parameter hasn't been sent, a
 * ParameterException exception is thrown
 *
 * @param string The GET or POST parameter you want returned
 * @param mixed [optional] the default value for this parameter
 *
 * @return string The value of the parameter
 *
 */
Martyn Smith's avatar
Martyn Smith committed
552
function param_variable($name) {
553
554
555
    $args = func_get_args();
    list ($value) = call_user_func_array('_param_retrieve', $args);
    return $value;
Martyn Smith's avatar
Martyn Smith committed
556
557
558
559
560
561
562
563
564
565
566
}

/**
 * This function returns a GET or POST parameter as an integer with optional
 * default.  If the default isn't specified and the parameter hasn't been sent,
 * a ParameterException exception is thrown. Likewise, if the parameter isn't a
 * valid integer, a ParameterException exception is thrown
 *
 * @param string The GET or POST parameter you want returned
 * @param mixed [optional] the default value for this parameter
 *
Nigel McNie's avatar
Nigel McNie committed
567
 * @return int The value of the parameter
Martyn Smith's avatar
Martyn Smith committed
568
569
 *
 */
Martyn Smith's avatar
Martyn Smith committed
570
function param_integer($name) {
571
572
573
574
575
576
    $args = func_get_args();

    list ($value, $defaultused) = call_user_func_array('_param_retrieve', $args);

    if ($defaultused) {
        return $value;
Martyn Smith's avatar
Martyn Smith committed
577
578
579
580
581
582
583
584
585
    }

    if (preg_match('/^\d+$/',$value)) {
        return (int)$value;
    }

    throw new ParameterException("Parameter '$name' = '$value' is not an integer");
}

Martyn Smith's avatar
Martyn Smith committed
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
/**
 * This function returns a GET or POST parameter as an alpha string with optional
 * default.  If the default isn't specified and the parameter hasn't been sent,
 * a ParameterException exception is thrown. Likewise, if the parameter isn't a
 * valid alpha string, a ParameterException exception is thrown
 *
 * Valid characters are a-z and A-Z
 *
 * @param string The GET or POST parameter you want returned
 * @param mixed [optional] the default value for this parameter
 *
 * @return string The value of the parameter
 *
 */
function param_alpha($name) {
601
602
603
604
605
606
    $args = func_get_args();

    list ($value, $defaultused) = call_user_func_array('_param_retrieve', $args);

    if ($defaultused) {
        return $value;
Martyn Smith's avatar
Martyn Smith committed
607
608
    }

Richard Mansfield's avatar
Richard Mansfield committed
609
    if (preg_match('/^[a-zA-Z]+$/',$value)) {
Martyn Smith's avatar
Martyn Smith committed
610
611
612
613
614
615
        return $value;
    }

    throw new ParameterException("Parameter '$name' = '$value' is not an alpha");
}

616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
/**
 * This function returns a GET or POST parameter as an alphanumeric string with optional
 * default.  If the default isn't specified and the parameter hasn't been sent,
 * a ParameterException exception is thrown. Likewise, if the parameter isn't a
 * valid alpha string, a ParameterException exception is thrown
 *
 * Valid characters are a-z and A-Z and 0-9
 *
 * @param string The GET or POST parameter you want returned
 * @param mixed [optional] the default value for this parameter
 *
 * @return string The value of the parameter
 *
 */
function param_alphanum($name) {
    $args = func_get_args();

    list ($value, $defaultused) = call_user_func_array('_param_retrieve', $args);

    if ($defaultused) {
        return $value;
    }

    if (preg_match('/^[a-zA-Z0-9]+$/',$value)) {
        return $value;
    }

    throw new ParameterException("Parameter '$name' = '$value' is not an alphanum");
}

646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
/**
 * This function returns a GET or POST parameter as an alphanumeric string with optional
 * default.  If the default isn't specified and the parameter hasn't been sent,
 * a ParameterException exception is thrown. Likewise, if the parameter isn't a
 * valid alpha string, a ParameterException exception is thrown
 *
 * Valid characters are a-z and A-Z and 0-9 and _ and - and .
 *
 * @param string The GET or POST parameter you want returned
 * @param mixed [optional] the default value for this parameter
 *
 * @return string The value of the parameter
 *
 */
function param_alphanumext($name) {
    $args = func_get_args();

    list ($value, $defaultused) = call_user_func_array('_param_retrieve', $args);

    if ($defaultused) {
        return $value;
    }

    if (preg_match('/^[a-zA-Z0-9_.-]+$/',$value)) {
        return $value;
    }

    throw new ParameterException("Parameter '$name' = '$value' is not an alphanumext");
}

Martyn Smith's avatar
Martyn Smith committed
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
/**
 * This function returns a GET or POST parameter as an array of integers with optional
 * default.  If the default isn't specified and the parameter hasn't been sent,
 * a ParameterException exception is thrown. Likewise, if the parameter isn't a
 * valid integer list , a ParameterException exception is thrown.
 *
 * An integer list is integers separated by commas (with optional whitespace),
 * or just whitespace which indicates an empty list
 *
 * @param string The GET or POST parameter you want returned
 * @param mixed [optional] the default value for this parameter
 *
 * @return array The value of the parameter
 *
 */
function param_integer_list($name) {
692
693
694
695
696
697
    $args = func_get_args();

    list ($value, $defaultused) = call_user_func_array('_param_retrieve', $args);

    if ($defaultused) {
        return $value;
Martyn Smith's avatar
Martyn Smith committed
698
699
700
701
702
703
704
705
706
707
708
709
710
    }

    if ($value == '') {
        return array();
    }

    if (preg_match('/^(\d+(,\d+)*)$/',$value)) {
        return array_map('intval', explode(',', $value));
    }

    throw new ParameterException("Parameter '$name' = '$value' is not an integer list");
}

Martyn Smith's avatar
Martyn Smith committed
711
712
713
714
715
/**
 * This function returns a GET or POST parameter as a boolean.
 *
 * @param string The GET or POST parameter you want returned
 *
Donal McMullan's avatar
Donal McMullan committed
716
 * @return bool The value of the parameter
Martyn Smith's avatar
Martyn Smith committed
717
718
 *
 */
Martyn Smith's avatar
Martyn Smith committed
719
function param_boolean($name) {
720
721
    
    list ($value) = _param_retrieve($name, false);
Martyn Smith's avatar
Martyn Smith committed
722

723
    if (empty($value) || $value == 'off' || $value == 'no' || $value == 'false') {
Martyn Smith's avatar
Martyn Smith committed
724
725
726
727
728
729
730
        return false;
    }
    else {
        return true;
    }
}

731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
/**
 * Gets a cookie, respecting the configured cookie prefix
 *
 * @param string $name The name of the cookie to get the value of
 * @return string      The value of the cookie, or null if the cookie does not
 *                     exist.
 */
function get_cookie($name) {
    $name = get_config('cookieprefix') . $name;
    return (isset($_COOKIE[$name])) ? $_COOKIE[$name] : null;
}

/**
 * Sets a cookie, respecting the configured cookie prefix
 *
 * @param string $name    The name of the cookie
 * @param string $value   The value for the cookie
 * @param int    $expires The unix timestamp of the time the cookie should expire
 * @todo path/domain/secure: should be set automatically by this function if possible (?)
 */
function set_cookie($name, $value='', $expires=0, $path='', $domain='', $secure=false) {
    $name = get_config('cookieprefix') . $name;
    setcookie($name, $value, $expires, $path, $domain, $secure);
}

Martyn Smith's avatar
Martyn Smith committed
756
757
758
759
760
761
762
763
764
/**
 * Returns an assoc array of countrys suitable for use with the "select" form
 * element
 *
 * @return array Associative array of countrycodes => countrynames
 */
function getoptions_country() {
    return array(
        'af' => 'Afghanistan',
765
        'ax' => 'Åland Islands',
Martyn Smith's avatar
Martyn Smith committed
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
        'al' => 'Albania',
        'dz' => 'Algeria',
        'as' => 'American Samoa',
        'ad' => 'Andorra',
        'ao' => 'Angola',
        'ai' => 'Anguilla',
        'aq' => 'Antarctica',
        'ag' => 'Antigua and Barbuda',
        'ar' => 'Argentina',
        'am' => 'Armenia',
        'aw' => 'Aruba',
        'au' => 'Australia',
        'at' => 'Austria',
        'az' => 'Azerbaijan',
        'bs' => 'Bahamas',
        'bh' => 'Bahrain',
        'bd' => 'Bangladesh',
        'bb' => 'Barbados',
        'by' => 'Belarus',
        'be' => 'Belgium',
        'bz' => 'Belize',
        'bj' => 'Benin',
        'bm' => 'Bermuda',
        'bt' => 'Bhutan',
        'bo' => 'Bolivia',
        'ba' => 'Bosnia and Herzegovina',
        'bw' => 'Botswana',
        'bv' => 'Bouvet Island',
        'br' => 'Brazil',
        'io' => 'British Indian Ocean Territory',
        'bn' => 'Brunei Darussalam',
        'bg' => 'Bulgaria',
        'bf' => 'Burkina Faso',
        'bi' => 'Burundi',
        'kh' => 'Cambodia',
        'cm' => 'Cameroon',
        'ca' => 'Canada',
        'cv' => 'Cape Verde',
        'ky' => 'Cayman Islands',
        'cf' => 'Central African Republic',
        'td' => 'Chad',
        'cl' => 'Chile',
        'cn' => 'China',
        'cx' => 'Christmas Island',
        'cc' => 'Cocos (Keeling) Islands',
        'co' => 'Colombia',
        'km' => 'Comoros',
        'cg' => 'Congo',
        'cd' => 'Congo, The Democratic Republic of The',
        'ck' => 'Cook Islands',
        'cr' => 'Costa Rica',
        'ci' => 'Cote D\'ivoire',
        'hr' => 'Croatia',
        'cu' => 'Cuba',
        'cy' => 'Cyprus',
        'cz' => 'Czech Republic',
        'dk' => 'Denmark',
        'dj' => 'Djibouti',
        'dm' => 'Dominica',
        'do' => 'Dominican Republic',
        'ec' => 'Ecuador',
        'eg' => 'Egypt',
        'sv' => 'El Salvador',
        'gq' => 'Equatorial Guinea',
        'er' => 'Eritrea',
        'ee' => 'Estonia',
        'et' => 'Ethiopia',
        'fk' => 'Falkland Islands (Malvinas)',
        'fo' => 'Faroe Islands',
        'fj' => 'Fiji',
        'fi' => 'Finland',
        'fr' => 'France',
        'gf' => 'French Guiana',
        'pf' => 'French Polynesia',
        'tf' => 'French Southern Territories',
        'ga' => 'Gabon',
        'gm' => 'Gambia',
        'ge' => 'Georgia',
        'de' => 'Germany',
        'gh' => 'Ghana',
        'gi' => 'Gibraltar',
        'gr' => 'Greece',
        'gl' => 'Greenland',
        'gd' => 'Grenada',
        'gp' => 'Guadeloupe',
        'gu' => 'Guam',
        'gt' => 'Guatemala',
        'gg' => 'Guernsey',
        'gn' => 'Guinea',
        'gw' => 'Guinea-bissau',
        'gy' => 'Guyana',
        'ht' => 'Haiti',
        'hm' => 'Heard Island and Mcdonald Islands',
        'va' => 'Holy See (Vatican City State)',
        'hn' => 'Honduras',
        'hk' => 'Hong Kong',
        'hu' => 'Hungary',
        'is' => 'Iceland',
        'in' => 'India',
        'id' => 'Indonesia',
        'ir' => 'Iran, Islamic Republic of',
        'iq' => 'Iraq',
        'ie' => 'Ireland',
        'im' => 'Isle of Man',
        'il' => 'Israel',
        'it' => 'Italy',
        'jm' => 'Jamaica',
        'jp' => 'Japan',
        'je' => 'Jersey',
        'jo' => 'Jordan',
        'kz' => 'Kazakhstan',
        'ke' => 'Kenya',
        'ki' => 'Kiribati',
        'kp' => 'Korea, Democratic People\'s Republic of',
        'kr' => 'Korea, Republic of',
        'kw' => 'Kuwait',
        'kg' => 'Kyrgyzstan',
        'la' => 'Lao People\'s Democratic Republic',
        'lv' => 'Latvia',
        'lb' => 'Lebanon',
        'ls' => 'Lesotho',
        'lr' => 'Liberia',
        'ly' => 'Libyan Arab Jamahiriya',
        'li' => 'Liechtenstein',
        'lt' => 'Lithuania',
        'lu' => 'Luxembourg',
        'mo' => 'Macao',
        'mk' => 'Macedonia, The Former Yugoslav Republic of',
        'mg' => 'Madagascar',
        'mw' => 'Malawi',
        'my' => 'Malaysia',
        'mv' => 'Maldives',
        'ml' => 'Mali',
        'mt' => 'Malta',
        'mh' => 'Marshall Islands',
        'mq' => 'Martinique',
        'mr' => 'Mauritania',
        'mu' => 'Mauritius',
        'yt' => 'Mayotte',
        'mx' => 'Mexico',
        'fm' => 'Micronesia, Federated States of',
        'md' => 'Moldova, Republic of',
        'mc' => 'Monaco',
        'mn' => 'Mongolia',
        'ms' => 'Montserrat',
        'ma' => 'Morocco',
        'mz' => 'Mozambique',
        'mm' => 'Myanmar',
        'na' => 'Namibia',
        'nr' => 'Nauru',
        'np' => 'Nepal',
        'nl' => 'Netherlands',
        'an' => 'Netherlands Antilles',
        'nc' => 'New Caledonia',
        'nz' => 'New Zealand',
        'ni' => 'Nicaragua',
        'ne' => 'Niger',
        'ng' => 'Nigeria',
        'nu' => 'Niue',
        'nf' => 'Norfolk Island',
        'mp' => 'Northern Mariana Islands',
        'no' => 'Norway',
        'om' => 'Oman',
        'pk' => 'Pakistan',
        'pw' => 'Palau',
        'ps' => 'Palestinian Territory, Occupied',
        'pa' => 'Panama',
        'pg' => 'Papua New Guinea',
        'py' => 'Paraguay',
        'pe' => 'Peru',
        'ph' => 'Philippines',
        'pn' => 'Pitcairn',
        'pl' => 'Poland',
        'pt' => 'Portugal',
        'pr' => 'Puerto Rico',
        'qa' => 'Qatar',
        're' => 'Reunion',
        'ro' => 'Romania',
        'ru' => 'Russian Federation',
        'rw' => 'Rwanda',
        'sh' => 'Saint Helena',
        'kn' => 'Saint Kitts and Nevis',
        'lc' => 'Saint Lucia',
        'pm' => 'Saint Pierre and Miquelon',
        'vc' => 'Saint Vincent and The Grenadines',
        'ws' => 'Samoa',
        'sm' => 'San Marino',
        'st' => 'Sao Tome and Principe',
        'sa' => 'Saudi Arabia',
        'sn' => 'Senegal',
        'cs' => 'Serbia and Montenegro',
        'sc' => 'Seychelles',
        'sl' => 'Sierra Leone',
        'sg' => 'Singapore',
        'sk' => 'Slovakia',
        'si' => 'Slovenia',
        'sb' => 'Solomon Islands',
        'so' => 'Somalia',
        'za' => 'South Africa',
        'gs' => 'South Georgia and The South Sandwich Islands',
        'es' => 'Spain',
        'lk' => 'Sri Lanka',
        'sd' => 'Sudan',
        'sr' => 'Suriname',
        'sj' => 'Svalbard and Jan Mayen',
        'sz' => 'Swaziland',
        'se' => 'Sweden',
        'ch' => 'Switzerland',
        'sy' => 'Syrian Arab Republic',
        'tw' => 'Taiwan, Province of China',
        'tj' => 'Tajikistan',
        'tz' => 'Tanzania, United Republic of',
        'th' => 'Thailand',
        'tl' => 'Timor-leste',
        'tg' => 'Togo',
        'tk' => 'Tokelau',
        'to' => 'Tonga',
        'tt' => 'Trinidad and Tobago',
        'tn' => 'Tunisia',
        'tr' => 'Turkey',
        'tm' => 'Turkmenistan',
        'tc' => 'Turks and Caicos Islands',
        'tv' => 'Tuvalu',
        'ug' => 'Uganda',
        'ua' => 'Ukraine',
        'ae' => 'United Arab Emirates',
        'gb' => 'United Kingdom',
        'us' => 'United States',
        'um' => 'United States Minor Outlying Islands',
        'uy' => 'Uruguay',
        'uz' => 'Uzbekistan',
        'vu' => 'Vanuatu',
        've' => 'Venezuela',
        'vn' => 'Viet Nam',
        'vg' => 'Virgin Islands, British',