web.php 55 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;
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
                $language = substr(current_language(), 0, 2);
83
                $headers[] = <<<EOF
84
85
86
87
<script type="text/javascript">
tinyMCE.init({
    mode: "textareas",
    editor_selector: 'wysiwyg',
88
    button_tile_map: true,
89
    language: '{$language}',
90
    theme: "advanced",
91
92
    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",
93
    theme_advanced_buttons2 : "bullist,numlist,separator,tablecontrols,separator,cut,copy,paste,pasteword",
94
    theme_advanced_buttons3 : "fontselect,separator,fontsizeselect,separator,formatselect",
95
    theme_advanced_toolbar_location : "top",
96
    theme_advanced_toolbar_align : "center",
97
    width: '512',
Martyn Smith's avatar
Martyn Smith committed
98
    content_css : {$content_css}
99
100
101
102
});
</script>

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

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

112
    $strings = array();
113
114
115
116
117
118
119
120
121
    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);
        }
122
123
    }

124
    $jsstrings = jsstrings();
Martyn Smith's avatar
Martyn Smith committed
125
    $themepaths = themepaths();
126

Richard Mansfield's avatar
Richard Mansfield committed
127
    foreach ($javascript as $jsfile) {
128
129
130
131
        // 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.
132
        if (strpos($jsfile, '/') === false) {
133
            $javascript_array[] = $jsroot . $jsfile . '.js';
134
            if (isset($jsstrings[$jsfile])) {
135
136
137
                foreach ($jsstrings[$jsfile] as $section => $tags) {
                    foreach ($tags as $tag) {
                        $strings[$tag] = get_raw_string($tag, $section);
138
139
140
                    }
                }
            }
Martyn Smith's avatar
Martyn Smith committed
141
142
143
144
145
            if (isset($themepaths[$jsfile])) {
                foreach ($themepaths[$jsfile] as $themepath) {
                    $theme_list[$themepath] = theme_get_url($themepath);
                }
            }
146
147
        }
        else {
148
            // A .js file with a fully specified path
149
            $javascript_array[] = $wwwroot . $jsfile;
150
151
152
153
154
155
            // 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]);
156
                $name = substr($bits[3], 0, strpos($bits[3], '.js'));
157
158
                if (is_callable(array($pluginclass, 'jsstrings'))) {
                    $tempstrings = call_static_method($pluginclass, 'jsstrings', $name);
159
160
161
                    foreach ($tempstrings as $section => $tags) {
                        foreach ($tags as $tag) {
                            $strings[$tag] = get_raw_string($tag, $section);
162
163
                        }
                    }
Richard Mansfield's avatar
Richard Mansfield committed
164
                }
165
166
167
168
169
170
171
172
173
                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
174
175
176
177
178
179
                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
180
            }
Martyn Smith's avatar
Martyn Smith committed
181
        }
182
    }
183
184
185
186

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

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

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

206
    $smarty =& new Smarty();
207
    
208
209
210
211
    $theme = theme_setup();

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

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

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

    // 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);
225
    $smarty->assign('WWWROOT', $wwwroot);
226
    $smarty->assign('SESSKEY', $USER->get('sesskey'));
Martyn Smith's avatar
Martyn Smith committed
227
    $smarty->assign('THEMELIST', json_encode($theme_list));
228

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

236

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

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

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

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

258
259
    $smarty->assign('searchform', searchform());

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

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

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

293
294
    if (get_config('enablenetworking')) {
        require_once(get_config('docroot') .'api/xmlrpc/lib.php');
Donal McMullan's avatar
Donal McMullan committed
295
        if ($USER->is_logged_in() && $ssopeers = get_service_providers($USER->authinstance)) {
296
297
298
299
300
301
            $SIDEBLOCKS[] = array(
                'name'   => 'ssopeers',
                'weight' => 1,
                'data'   => $ssopeers,
            );
        }
302
    }
303

Martyn Smith's avatar
Martyn Smith committed
304
305
306
307
308
309
310
311
    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;'));

312
    $smarty->assign('userauthinstance', $USER->lastauthinstance);
Martyn Smith's avatar
Martyn Smith committed
313
314
    $smarty->assign('SIDEBLOCKS', $SIDEBLOCKS);

315
316
317
    return $smarty;
}

318
319
/** 
 * Returns the lists of strings used in the .js files
320
 * @return array                   
321
322
 */

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

Martyn Smith's avatar
Martyn Smith committed
354
355
356
357
function themepaths() {
    return array(
        'mahara' => array(
            'images/icon_close.gif',
358
            'images/failure.gif',
359
360
            'images/loading.gif',
            'images/success.gif',
361
            'images/icon_help.gif',
Martyn Smith's avatar
Martyn Smith committed
362
363
364
365
        ),
    );
}

366
367
368
369
370
371
/** 
 * Takes an array of string identifiers and returns an array of the
 * corresponding strings, quoted for use in inline javascript here
 * docs.
 */

372
373
374
375
function quotestrings($strings) {
    $qstrings = array();
    foreach ($strings as $section => $tags) {
        foreach ($tags as $tag) {
376
            $qstrings[$tag] = json_encode(get_string($tag, $section));
377
        }
378
    }
379
    return $qstrings;
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
410
411
412
413
414
/** 
 * 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;
        }
    }

415
    // always put the default theme at the top of the tree, unless we're already it
416
417
    if ($theme->theme != 'default') {
        $theme->template_dir[] = get_config('docroot')  . 'theme/default/templates/';
418
        $theme->inheritance[] = 'default';
419
    }
420

421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
    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
 */
447
function theme_get_url($location, $pluginlocation='', $all = false) {
448
    $theme = theme_setup();
449
    $list = array();
450
451

    foreach ($theme->inheritance as $themedir) {
452
453
454
455
456
457
458
        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;
            }
459
460
        }
    }
461
462
463
464
    if ($all) {
        return $list;
    }
    return;
465
466
}

467
468
469
470
471
472
/** 
 * 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
 */
473
function theme_get_path($location, $pluginlocation='') {
474
475
476
    $theme = theme_setup();

    foreach ($theme->inheritance as $themedir) {
477
478
        if (is_readable(get_config('docroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location)) {
            return get_config('docroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location;
479
480
481
482
        }
    }
}

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

Richard Mansfield's avatar
Richard Mansfield committed
494
/**
495
 * This function sends a JSON message, and ends the script.
Richard Mansfield's avatar
Richard Mansfield committed
496
 *
497
498
499
500
501
502
503
504
 * 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
505
 */
506
function json_reply($error, $message) {
Richard Mansfield's avatar
Richard Mansfield committed
507
    json_headers();
508
    echo json_encode(array('error' => $error, 'message' => $message));
509
    perf_to_log();
Richard Mansfield's avatar
Richard Mansfield committed
510
511
512
    exit;
}

513
514
515
516
517
518
519
520
521
522
523
524
525
526
/**
 * 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'));
    }
}

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

543
    return array($value, false);
544
545
}

Martyn Smith's avatar
Martyn Smith committed
546
547
548
549
550
551
552
553
554
555
556
/**
 * 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
557
function param_variable($name) {
558
559
560
    $args = func_get_args();
    list ($value) = call_user_func_array('_param_retrieve', $args);
    return $value;
Martyn Smith's avatar
Martyn Smith committed
561
562
563
564
565
566
567
568
569
570
571
}

/**
 * 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
572
 * @return int The value of the parameter
Martyn Smith's avatar
Martyn Smith committed
573
574
 *
 */
Martyn Smith's avatar
Martyn Smith committed
575
function param_integer($name) {
576
577
578
579
580
581
    $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
582
583
584
585
586
587
    }

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

588
    throw new ParameterException("The '$name' parameter is not an integer");
Martyn Smith's avatar
Martyn Smith committed
589
590
}

Martyn Smith's avatar
Martyn Smith committed
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
/**
 * 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) {
606
607
608
609
610
611
    $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
612
613
    }

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

618
    throw new ParameterException("The '$name' parameter is not alphabetical only");
Martyn Smith's avatar
Martyn Smith committed
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
646
647
/**
 * 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;
    }

648
    throw new ParameterException("The '$name' parameter is not alphanumeric only");
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
676
677
/**
 * 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;
    }

678
    throw new ParameterException("The '$name' parameter contains invalid characters");
679
680
}

Martyn Smith's avatar
Martyn Smith committed
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
/**
 * 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) {
697
698
699
700
701
702
    $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
703
704
705
706
707
708
709
710
711
712
    }

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

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

713
    throw new ParameterException("The '$name' parameter is not an integer list");
Martyn Smith's avatar
Martyn Smith committed
714
715
}

Martyn Smith's avatar
Martyn Smith committed
716
717
718
719
720
/**
 * 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
721
 * @return bool The value of the parameter
Martyn Smith's avatar
Martyn Smith committed
722
723
 *
 */
Martyn Smith's avatar
Martyn Smith committed
724
function param_boolean($name) {
725
726
    
    list ($value) = _param_retrieve($name, false);
Martyn Smith's avatar
Martyn Smith committed
727

728
    if (empty($value) || $value == 'off' || $value == 'no' || $value == 'false') {
Martyn Smith's avatar
Martyn Smith committed
729
730
731
732
733
734
735
        return false;
    }
    else {
        return true;
    }
}

736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
/**
 * 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
761
762
763
764
765
766
767
768
769
/**
 * 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',
770
        'ax' => 'Åland Islands',
Martyn Smith's avatar
Martyn Smith committed
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
        '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',
        'vi' => 'Virgin Islands, U.S.',
        'wf' => 'Wallis and Futuna',
        'eh' => 'Western Sahara',
        'ye' => 'Yemen',
        'zm' => 'Zambia',
        'zw' => 'Zimbabwe',
    );
}

Penny Leach's avatar
Penny Leach committed
1015
1016
1017
1018
/**
 * 
 */

1019
function get_help_icon($plugintype, $pluginname, $form, $element, $page='', $section='') {
Nigel McNie's avatar
Nigel McNie committed
1020
1021
    // I see no reason why IE has to drag the quality of the interwebs down with it
    $imageext = (isset($_SERVER['HTTP_USER_AGENT'])) && false !== stripos($_SERVER['HTTP_USER_AGENT'], 'msie') ? 'gif' : 'png';
1022
    return ' <span class="help"><a href="" onclick="'. 
1023
1024
1025
        hsc(
            'contextualHelp(' . json_encode($form) . ',' . 
            json_encode($element) . ',' . json_encode($plugintype) . ',' . 
1026
1027
1028
            json_encode($pluginname) . ',' . json_encode($page) . ',' . 
            json_encode($section)
            . ',this); return false;'
Nigel McNie's avatar
Nigel McNie committed
1029
        ) . '"><img src="' . theme_get_url('images/icon_help.' . $imageext) . '" alt="?"></a></span>';
Penny Leach's avatar
Penny Leach committed
1030
1031
}

1032
1033
1034
1035
1036
1037
function pieform_get_help(Pieform $form, $element) {
    return get_help_icon($form->get_property('plugintype'),
        $form->get_property('pluginname'),
        $form->get_name(), $element['name']);
}

1038
1039
1040
1041
function make_link($url) {
    return '<a href="' . $url . '">' . $url . '</a>';
}

1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057

/**
 * Builds the admin navigation menu and returns it as a data structure
 *
 * @return $adminnav a data structure containing the admin navigation
 */
function admin_nav() {
    $wwwroot = get_config('wwwroot');

    $menu = array(
        array(
            'name'     => 'adminhome',
            'section'  => 'admin',
            'link'     => $wwwroot . 'admin/',
        ),
        array(
1058
            'name'     => 'configsite',
1059
            'section'  => 'admin',
1060
1061
1062
1063
1064
1065
1066
1067
            'link'     => $wwwroot . 'admin/site/options.php',
            'submenu'  => array(
                array(
                    'name' => 'siteoptions',
                    'section' => 'admin',
                    'link' => $wwwroot . 'admin/site/options.php'
                ),
                array(
1068
                    'name'    => 'sitepages',
1069
1070
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/site/pages.php',
1071
1072
                ),
                array(
1073
                    'name'    => 'sitemenu',
1074
1075
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/site/menu.php',
1076
1077
                ),
                array(
1078
                    'name'    => 'adminfiles',
1079
1080
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/site/files.php'
1081
1082
1083
1084
1085
                ),
                array(
                    'name'    => 'networking',
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/site/networking.php'
1086
1087
                )
            )
1088
1089
        ),
        array(
1090
            'name'     => 'configusers',
1091
            'section'  => 'admin',
1092
            'link'     => $wwwroot . 'admin/users/suspended.php',
1093
1094
            'submenu' => array(
                array(
1095
1096
1097
                    'name'    => 'suspendedusers',
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/users/suspended.php'
1098
                ),
1099
                array(
1100
                    'name'    => 'staffusers',
1101
                    'section' => 'admin',
1102
                    'link'    => $wwwroot . 'admin/users/staff.php'
1103
1104
                ),
                array(
1105
                    'name'    => 'adminusers',
1106
                    'section' => 'admin',
1107
                    'link'    => $wwwroot . 'admin/users/admins.php'
1108
1109
                ),
                array(
1110
                    'name'    => 'adminnotifications',
1111
                    'section' => 'admin',
1112
                    'link'    => $wwwroot . 'admin/users/notifications.php'
1113
1114
                ),
                array(
1115
                    'name'    => 'institutions',
1116
                    'section' => 'admin',
1117
                    'link'    => $wwwroot . 'admin/users/institutions.php'
1118
1119
                ),
                array(
1120
                    'name'    => 'uploadcsv',
1121
                    'section' => 'admin',
1122
                    'link'    => $wwwroot . 'admin/users/uploadcsv.php'
1123
1124
1125
1126
1127
1128
                ),
                array(
                    'name'    => 'usersearch',
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/users/search.php'
                ),
1129
1130
            )
        ),
1131
        array(
1132
            'name'     => 'configextensions',
1133
            'section'  => 'admin',
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
            'link'     => $wwwroot . 'admin/extensions/plugins.php',
            'submenu' => array(
                array(
                    'name' => 'pluginadmin',
                    'section' => 'admin',
                    'link' => $wwwroot . 'admin/extensions/plugins.php'
                ),
                array(
                    'name' => 'templatesadmin',
                    'section' => 'admin',
                    'link' => $wwwroot . 'admin/extensions/templates.php'
                )
            )
1147
        ),
1148
1149
1150
1151
1152
1153
    );

    if (defined('MENUITEM')) {
        foreach ( $menu as &$item ) {
            if ($item['name'] == MENUITEM) {
                $item['selected'] = true;
Nigel McNie's avatar
Nigel McNie committed
1154
                if (defined('SUBMENUITEM') && is_array($item['submenu'])) {
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
                    foreach ( $item['submenu'] as &$subitem ) {
                        if ($subitem['name'] == SUBMENUITEM) {
                            $subitem['selected'] = true;
                        }
                    }
                }
            }
        }
    }

    return $menu;
}

/**
 * Builds the main navigation menu and returns it as a data structure
 *
 * @return $mainnav a data structure containing the main navigation
 * @todo martyn this is probably quite expenvise, perhaps it needs teh caching
 */
function main_nav() {
    $wwwroot = get_config('wwwroot');

    if (defined('ADMIN')) {
        return admin_nav();
    }

    $menu = array(
        array(
            'name'     => 'home',
            'section'  => 'mahara',
            'link'     => $wwwroot,
        ),
    );

    if ($plugins = get_records_array('artefact_installed')) {
        foreach ($plugins as &$plugin) {
1191
            safe_require('artefact', $plugin->name);
1192
1193
1194
1195
1196
            $plugin_menu = call_static_method(generate_class_name('artefact',$plugin->name), 'menu_items');

            foreach ($plugin_menu as &$menu_item) {
                $menu_item['link'] = $wwwroot . 'artefact/' . $plugin->name . '/' . $menu_item['link'];
                $menu_item['section'] = 'artefact.' . $plugin->name;
1197
1198
1199
1200
1201
1202
1203
                if (array_key_exists('submenu', $menu_item)) {
                    foreach ($menu_item['submenu'] as &$submenuitem) {
                        if (!array_key_exists('section', $submenuitem)) {
                            $submenuitem['section'] = 'artefact.' . $plugin->name;
                        }
                    }
                }
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
            }

            $menu = array_merge($menu, $plugin_menu);
        }
    }

    $menu[] = array(
        'name'    => 'mycontacts',
        'link'    => $wwwroot . 'contacts/',
        'section' => 'mahara',
        'submenu' => array(
            array(
                'name'    => 'myfriends',
                'link'    => $wwwroot . 'contacts/',
                'section' => 'mahara',
            ),
1220
            /*
1221
1222
1223
1224
1225
            array(
                'name'    => 'myaddressbook',
                'link'    => $wwwroot . 'contacts/addressbook/',
                'section' => 'mahara',
            ),
1226
            */
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
            array(
                'name'    => 'mycommunities',
                'link'    => $wwwroot . 'contacts/communities/',
                'section' => 'mahara',
            ),
            array(
                'name'    => 'myownedcommunities',
                'link'    => $wwwroot . 'contacts/communities/owned.php',
                'section' => 'mahara',
            ),
            array(
                'name'    => 'mygroups',
                'link'    => $wwwroot . 'contacts/groups/',
                'section' => 'mahara',
            ),
        ),
    );
    $menu[] = array(
        'name'    => 'myviews',
        'link'    => $wwwroot . 'view/',
        'section' => 'mahara',
    );
    $menu[] = array(
        'name'    => 'account',
        'link'    => $wwwroot . 'account/',
        'section' => 'mahara',
        'submenu' => array(
            array(
                'name'    => 'accountprefs',
                'link'    => $wwwroot . 'account/',
                'section' => 'mahara',
            ),
            array(
                'name'    => 'activity',
                'link'    => $wwwroot . 'account/activity/',
                'section' => 'mahara',
            ),
            array(
                'name'    => 'activityprefs',
                'link'    => $wwwroot . 'account/activity/preferences/',
                'section' => 'mahara',
            ),
            array(
                'name'    => 'watchlist',
                'link'    => $wwwroot . 'account/watchlist/',
                'section' => 'mahara',
            ),
        ),
    );


    if (defined('MENUITEM')) {
        foreach ( $menu as &$item ) {
            if ($item['name'] == MENUITEM) {
                $item['selected'] = true;
                if (defined('SUBMENUITEM') and is_array($item['submenu'])) {
                    foreach ( $item['submenu'] as &$subitem ) {
                        if ($subitem['name'] == SUBMENUITEM) {
                            $subitem['selected'] = true;
                        }
                    }
                }
            }
        }
    }
    else {
        $menu[0]['selected'] = true;
    }

    return $menu;
}

/**
 * Site-level sidebar menu (list of links)
 * There is no admin files table yet so just get the urls.
 * @return $menu a data structure containing the site menu
 */
function site_menu() {
    global $USER;
    $menu = array();
    if ($menuitems = get_records_array('site_menu','public',(int) !$USER->is_logged_in(),'displayorder')) {
        foreach ($menuitems as $i) {
            if ($i->url) {
                $menu[] = array('name' => $i->title,
                                'link' => $i->url);
            }
1313
1314
1315
1316
            else if ($i->file) {
                $menu[] = array('name' => $i->title,
                                'link' => get_config('wwwroot') . 'artefact/file/download.php?file=' . $i->file);
            }
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
        }
    }
    return $menu;
}

/**
 * Returns the list of site content pages
 * @return array of names
 */
function site_content_pages() {
    return array('about', 'home', 'loggedouthome', 'privacy', 'termsandconditions', 'uploadcopyright');
}

function get_site_page_content($pagename) {
    if ($pagedata = @get_record('site_content', 'name', $pagename)) {
        return $pagedata->content;
    }
    return get_string('sitecontentnotfound', 'mahara', get_string($pagename));
}


1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351

/** 
 * Redirects the browser to a new location. The path to redirect to can take
 * two forms:
 *  
 * - http[something]: will redirect the user to that exact URL
 * - /[something]: will redirect to WWWROOT/[something]
 *       
 * Any other form is illegal and will cause an error.
 *      
 * @param string $location The location to redirect the user to. Defaults to
 *                         the application home page.
 */     
function redirect($location='/') {
1352
1353
1354
    if (headers_sent()) {
        throw new Exception('Headers already sent when redirect() was called');
    }
1355

1356
1357
1358
1359
1360
    if (substr($location, 0, 4) != 'http') {
        if (substr($location, 0, 1) != '/') {
            throw new SystemException('redirect() should be called with either'
                . ' /[something] for local redirects or http[something] for'
                . ' absolute redirects');
1361
        }
1362
1363

        $location = get_config('wwwroot') . substr($location, 1);
1364
1365
    }

1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
    header('HTTP/1.1 303 See Other');
    header('Location:' . $location);
    exit;
}

/**
 * Returns a string, HTML escaped
 *
 * @param string $text The text to escape
 * @return string      The text, HTML escaped
 */
function hsc ($text) {
    return htmlspecialchars($text, ENT_COMPAT, 'UTF-8');
}

function searchform() {
    require_once('pieforms/pieform.php');
    return pieform(array(
        'name'                => 'searchform',
1385
        'action'              => get_config('wwwroot') . 'search.php',
1386
        'renderer'            => 'oneline',
1387
        'autofocus'           => false,
1388
        'validate'            => false,
1389
1390
1391
        'elements'            => array(
            'query' => array(
                'type'           => 'text',
1392
1393
                'defaultvalue'   => 'Search',
                'class'          => 'emptyonfocus'
1394
1395
1396
            ),
            'submit' => array(
                'type' => 'image',
1397
                'src'  => theme_get_url('images/btn_search_off.gif')
1398
            )
1399
1400
1401
1402
        )
    ));
}

1403
1404
function get_loggedin_string() {
    global $USER;
1405
1406
1407

    $str = get_string('youareloggedinas', 'mahara', display_name($USER));

1408
1409
1410
1411
1412
1413
1414
1415
    safe_require('notification', 'internal');
    $count = call_static_method(generate_class_name('notification', 'internal'), 'unread_count', $USER->get('id'));
    if ($count == 1) {
        $key = 'unreadmessage';
    }
    else {
        $key = 'unreadmessages';
    }
1416
1417
1418
1419
1420
1421
1422
1423

    if ($count > 0) {
        // these spans are here so that on the ajax page that marks messages as read, the contents can be updated.
        $str .=
            ' (<a href="' . get_config('wwwroot') . 'account/activity/">'  . 
            '<span id="headerunreadmessagecount">' . $count . '</span> ' . 
            '<span id="headerunreadmessages">' . get_string($key) . '</span></a>)';
    }
1424
1425
1426
1427

    return $str;
}

1428

1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489