web.php 44 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;
57
58

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

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

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

Richard Mansfield's avatar
Richard Mansfield committed
71
    // TinyMCE must be included first for some reason we're not sure about
72
73
74
75
    $checkarray = array(&$javascript, &$headers);
    foreach ($checkarray as &$check) {
        if (($key = array_search('tinymce', $check)) !== false) {
            $javascript_array[] = $jsroot . 'tinymce/tiny_mce.js';
76
77
78
            if (isset($extraconfig['tinymceinit'])) {
                $headers[] = $extraconfig['tinymceinit'];
            } else {
Martyn Smith's avatar
Martyn Smith committed
79
                $content_css = json_encode(theme_get_url('style/tinymce.css'));
80
                $headers[] = <<<EOF
81
82
83
84
<script type="text/javascript">
tinyMCE.init({
    mode: "textareas",
    editor_selector: 'wysiwyg',
85
    button_tile_map: true,
86
    theme: "advanced",
87
88
89
    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",
    theme_advanced_buttons2 : "tablecontrols,separator,cut,copy,paste,pasteword",
90
    theme_advanced_buttons3 : "fontselect,separator,fontsizeselect,separator,formatselect",
91
    theme_advanced_toolbar_location : "top",
92
    theme_advanced_toolbar_align : "center",
Martyn Smith's avatar
Martyn Smith committed
93
    content_css : {$content_css}
94
95
96
97
});
</script>

EOF;
98
            }
99
100
            unset($check[$key]);
            break;
101
        }
102
103
    }

Martyn Smith's avatar
Martyn Smith committed
104
    $javascript_array[] = $jsroot . 'MochiKit/setup.js';
105

106
    $strings = array();
107
108
109
110
111
112
113
114
115
    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);
        }
116
117
    }

118
    $jsstrings = jsstrings();
Martyn Smith's avatar
Martyn Smith committed
119
    $themepaths = themepaths();
120

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

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

173
174
175
    foreach ($jsstrings['mahara'] as $section => $tags) {
        foreach ($tags as $tag) {
            $strings[$tag] = get_raw_string($tag, $section);
176
177
        }
    }
Martyn Smith's avatar
Martyn Smith committed
178
179
180
    foreach ($themepaths['mahara'] as $themepath) {
        $theme_list[$themepath] = theme_get_url($themepath);
    }
181
182
183
184
185
    if (isset($extraconfig['themepaths']) && is_array($extraconfig['themepaths'])) {
        foreach ($extraconfig['themepaths'] as $themepath) {
            $theme_list[$themepath] = theme_get_url($themepath);
        }
    }
186

187
    $stringjs = '<script type="text/javascript">';
188
    $stringjs .= 'var strings = ' . json_encode($strings) . ';';
189
190
191
    $stringjs .= '</script>';
    $headers[] = $stringjs;

192
    $smarty =& new Smarty();
193
    
194
195
196
197
    $theme = theme_setup();

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

198
199
200
    $smarty->compile_dir  = get_config('dataroot').'smarty/compile';
    $smarty->cache_dir    = get_config('dataroot').'smarty/cache';

201
202
203
    if (get_config('installed')) {
        $smarty->assign('SITEMENU', site_menu());
    }
204
    $smarty->assign('THEMEURL', get_config('themeurl'));
205
    $smarty->assign('STYLESHEETLIST', array_reverse(theme_get_url('style/style.css', null, true)));
206
    $smarty->assign('WWWROOT', $wwwroot);
Martyn Smith's avatar
Martyn Smith committed
207
    $smarty->assign('THEMELIST', json_encode($theme_list));
208

Martyn Smith's avatar
Martyn Smith committed
209
210
211
212
213
214
215
    if (defined('TITLE')) {
        $smarty->assign('PAGETITLE', TITLE . ' - ' . get_config('sitename'));
    }
    else {
        $smarty->assign('PAGETITLE', get_config('sitename'));
    }

216

217
218
219
    $sitename = get_config('sitename');
    $smarty->assign('title', $sitename);
    $smarty->assign('heading', $sitename);
220

221
222
223
    if (defined('PUBLIC')) {
        $smarty->assign('PUBLIC', true);
    }
224
225
226
    if (defined('ADMIN')) {
        $smarty->assign('ADMIN', true);
    }
227

228
229
    $smarty->assign('LOGGEDIN', $USER->is_logged_in());
    if ($USER->is_logged_in()) {
230
        $smarty->assign('MAINNAV', main_nav());
231
        $smarty->assign('LOGGEDINSTR', get_loggedin_string());
232
233
    }

234
    $smarty->assign_by_ref('USER', $USER);
235
    $smarty->assign_by_ref('JAVASCRIPT', $javascript_array);
236
237
    $smarty->assign_by_ref('HEADERS', $headers);

238
239
    $smarty->assign('searchform', searchform());

240
241
242
243
244
    if ($help = has_page_help()) {
        $smarty->assign('PAGEHELPNAME', $help[0]);
        $smarty->assign('PAGEHELPICON', $help[1]);
    }

245
246
247
    return $smarty;
}

248
249
/** 
 * Returns the lists of strings used in the .js files
250
 * @return array                   
251
252
 */

253
function jsstrings() {
Martyn Smith's avatar
Martyn Smith committed
254
    return array(
255
256
257
       'mahara' => array(                        // js file
            'mahara' => array(                   // section
                'namedfieldempty',               // string name
258
                'processing',
259
260
261
                'requiredfieldempty',
                'unknownerror',
                'loading',
262
263
                'unreadmessages',
                'unreadmessage',
264
            ),
265
266
        ),
        'tablerenderer' => array(
267
268
269
270
271
272
            'mahara' => array(
                'firstpage',
                'nextpage',
                'prevpage',
                'lastpage',
            )
273
274
275
276
277
278
        ),
        'collapsabletree' => array(
            'view' => array(
                'nochildren',
            ),
        ),
Martyn Smith's avatar
Martyn Smith committed
279
280
281
    );
}

Martyn Smith's avatar
Martyn Smith committed
282
283
284
285
function themepaths() {
    return array(
        'mahara' => array(
            'images/icon_close.gif',
286
            'images/failure.gif',
287
288
            'images/loading.gif',
            'images/success.gif',
Martyn Smith's avatar
Martyn Smith committed
289
290
291
292
        ),
    );
}

293
294
295
296
297
298
/** 
 * Takes an array of string identifiers and returns an array of the
 * corresponding strings, quoted for use in inline javascript here
 * docs.
 */

299
300
301
302
303
304
function quotestrings($strings) {
    $qstrings = array();
    foreach ($strings as $section => $tags) {
        foreach ($tags as $tag) {
            $qstrings[$tag] = "'" . get_string($tag, $section) . "'";
        }
305
    }
306
    return $qstrings;
307
308
}

309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/** 
 * 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;
        }
    }

342
    // always put the default theme at the top of the tree, unless we're already it
343
344
    if ($theme->theme != 'default') {
        $theme->template_dir[] = get_config('docroot')  . 'theme/default/templates/';
345
        $theme->inheritance[] = 'default';
346
    }
347

348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
    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
 */
374
function theme_get_url($location, $pluginlocation='', $all = false) {
375
    $theme = theme_setup();
376
    $list = array();
377
378

    foreach ($theme->inheritance as $themedir) {
379
380
381
382
383
384
385
        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;
            }
386
387
        }
    }
388
389
390
391
    if ($all) {
        return $list;
    }
    return;
392
393
}

394
395
396
397
398
399
/** 
 * 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
 */
400
function theme_get_path($location, $pluginlocation='') {
401
402
403
    $theme = theme_setup();

    foreach ($theme->inheritance as $themedir) {
404
405
        if (is_readable(get_config('docroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location)) {
            return get_config('docroot') . $pluginlocation . 'theme/' . $themedir . '/static/' . $location;
406
407
408
409
        }
    }
}

410
411
412
413
414
/**
 * This function sends headers suitable for all JSON returning scripts.
 *
 */
function json_headers() {
Martyn Smith's avatar
Martyn Smith committed
415
    // @todo martyn This should be changed, but for now it's useful for debugging
416
417
    // header('Content-type: text/x-json');
    header('Content-type: text/plain');
Martyn Smith's avatar
Martyn Smith committed
418
    header('Pragma: no-cache');
419
420
}

Richard Mansfield's avatar
Richard Mansfield committed
421
/**
422
 * This function sends a JSON message, and ends the script.
Richard Mansfield's avatar
Richard Mansfield committed
423
 *
424
425
426
427
428
429
430
431
 * 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
432
 */
433
function json_reply($error, $message) {
Richard Mansfield's avatar
Richard Mansfield committed
434
    json_headers();
435
    echo json_encode(array('error' => $error, 'message' => $message));
Richard Mansfield's avatar
Richard Mansfield committed
436
437
438
    exit;
}

439
440
441
442
443
444
445
446
447
448
449
450
451
452
/**
 * 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'));
    }
}

453
454
455
456
457
458
459
460
461
462
463
464
465
466
function _param_retrieve($name) {
    // if it's not set and we have a default
    if (!isset($_REQUEST[$name]) && func_num_args() == 2) {
        $php_work_around = func_get_arg(1);
        return array($php_work_around, true);
    }

    if (!isset($_REQUEST[$name])) {
        throw new ParameterException("Missing parameter '$name' and no default supplied");
    }

    return array($_REQUEST[$name], false);
}

Martyn Smith's avatar
Martyn Smith committed
467
468
469
470
471
472
473
474
475
476
477
/**
 * 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
478
function param_variable($name) {
479
480
481
    $args = func_get_args();
    list ($value) = call_user_func_array('_param_retrieve', $args);
    return $value;
Martyn Smith's avatar
Martyn Smith committed
482
483
484
485
486
487
488
489
490
491
492
493
494
495
}

/**
 * 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
 *
 * @return string The value of the parameter
 *
 */
Martyn Smith's avatar
Martyn Smith committed
496
function param_integer($name) {
497
498
499
500
501
502
    $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
503
504
505
506
507
508
509
510
511
    }

    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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/**
 * 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) {
527
528
529
530
531
532
    $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
533
534
    }

Richard Mansfield's avatar
Richard Mansfield committed
535
    if (preg_match('/^[a-zA-Z]+$/',$value)) {
Martyn Smith's avatar
Martyn Smith committed
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
        return $value;
    }

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

/**
 * 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) {
558
559
560
561
562
563
    $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
564
565
566
567
568
569
570
571
572
573
574
575
576
    }

    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
577
578
579
580
581
582
583
584
/**
 * This function returns a GET or POST parameter as a boolean.
 *
 * @param string The GET or POST parameter you want returned
 *
 * @return string The value of the parameter
 *
 */
Martyn Smith's avatar
Martyn Smith committed
585
function param_boolean($name) {
586
587
    
    list ($value) = _param_retrieve($name, false);
Martyn Smith's avatar
Martyn Smith committed
588

589
    if (empty($value) || $value == 'off' || $value == 'no' || $value == 'false') {
Martyn Smith's avatar
Martyn Smith committed
590
591
592
593
594
595
596
        return false;
    }
    else {
        return true;
    }
}

597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
/**
 * 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
622
623
624
625
626
627
628
629
630
/**
 * 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',
631
        'ax' => 'Åland Islands',
Martyn Smith's avatar
Martyn Smith committed
632
633
634
635
636
637
638
639
640
641
642
643
644
645
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
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
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
756
757
758
759
760
761
762
763
764
765
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
        '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
876
877
878
879
880
/**
 * 
 */

function get_help_icon($plugintype, $pluginname, $form, $element, $page='') {
881
882
883
884
    return ' <span class="help"><a href="" onclick="' . 
        hsc(
            'contextualHelp(' . json_encode($form) . ',' . 
            json_encode($element) . ',' . json_encode($plugintype) . ',' . 
Martyn Smith's avatar
Martyn Smith committed
885
            json_encode($pluginname) . ',' . json_encode($page) . ',this); return false;'
886
        ) . '">?</a></span>';
Penny Leach's avatar
Penny Leach committed
887
888
}

889
890
891
892
function make_link($url) {
    return '<a href="' . $url . '">' . $url . '</a>';
}

893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908

/**
 * 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(
909
            'name'     => 'configsite',
910
            'section'  => 'admin',
911
912
913
914
915
916
917
918
            'link'     => $wwwroot . 'admin/site/options.php',
            'submenu'  => array(
                array(
                    'name' => 'siteoptions',
                    'section' => 'admin',
                    'link' => $wwwroot . 'admin/site/options.php'
                ),
                array(
919
                    'name'    => 'sitepages',
920
921
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/site/pages.php',
922
923
                ),
                array(
924
                    'name'    => 'sitemenu',
925
926
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/site/menu.php',
927
928
                ),
                array(
929
                    'name'    => 'adminfiles',
930
931
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/site/files.php'
932
933
                )
            )
934
935
        ),
        array(
936
            'name'     => 'configusers',
937
            'section'  => 'admin',
938
            'link'     => $wwwroot . 'admin/users/suspended.php',
939
940
            'submenu' => array(
                array(
941
942
943
                    'name'    => 'suspendedusers',
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/users/suspended.php'
944
                ),
945
                array(
946
                    'name'    => 'staffusers',
947
                    'section' => 'admin',
948
                    'link'    => $wwwroot . 'admin/users/staff.php'
949
950
                ),
                array(
951
                    'name'    => 'adminusers',
952
                    'section' => 'admin',
953
                    'link'    => $wwwroot . 'admin/users/admins.php'
954
955
                ),
                array(
956
                    'name'    => 'adminnotifications',
957
                    'section' => 'admin',
958
                    'link'    => $wwwroot . 'admin/users/notifications.php'
959
960
                ),
                array(
961
                    'name'    => 'institutions',
962
                    'section' => 'admin',
963
                    'link'    => $wwwroot . 'admin/users/institutions.php'
964
965
                ),
                array(
966
                    'name'    => 'uploadcsv',
967
                    'section' => 'admin',
968
                    'link'    => $wwwroot . 'admin/users/uploadcsv.php'
969
970
971
972
973
974
                ),
                array(
                    'name'    => 'usersearch',
                    'section' => 'admin',
                    'link'    => $wwwroot . 'admin/users/search.php'
                ),
975
976
            )
        ),
977
        array(
978
            'name'     => 'configextensions',
979
            'section'  => 'admin',
980
981
982
983
984
985
986
987
988
989
990
991
992
            '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'
                )
            )
993
        ),
994
995
996
997
998
999
    );

    if (defined('MENUITEM')) {
        foreach ( $menu as &$item ) {
            if ($item['name'] == MENUITEM) {
                $item['selected'] = true;
Nigel McNie's avatar
Nigel McNie committed
1000
                if (defined('SUBMENUITEM') && is_array($item['submenu'])) {
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
                    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) {
1037
            safe_require('artefact', $plugin->name);
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
            $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;
            }

            $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',
            ),
            array(
                'name'    => 'myaddressbook',
                'link'    => $wwwroot . 'contacts/addressbook/',
                'section' => 'mahara',
            ),
            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);
            }
1150
1151
1152
1153
            else if ($i->file) {
                $menu[] = array('name' => $i->title,
                                'link' => get_config('wwwroot') . 'artefact/file/download.php?file=' . $i->file);
            }
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
        }
    }
    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));
}


1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188

/** 
 * 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='/') {
1189
1190
1191
    if (headers_sent()) {
        throw new Exception('Headers already sent when redirect() was called');
    }
1192

1193
1194
1195
1196
1197
    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');
1198
        }
1199
1200

        $location = get_config('wwwroot') . substr($location, 1);
1201
1202
    }

1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
    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',
1222
        'action'              => get_config('wwwroot') . 'search.php',
1223
        'renderer'            => 'oneline',
1224
        'autofocus'           => false,
1225
        'validate'            => false,
1226
1227
1228
        'elements'            => array(
            'query' => array(
                'type'           => 'text',
1229
1230
                'defaultvalue'   => 'Search',
                'class'          => 'emptyonfocus'
1231
1232
1233
            ),
            'submit' => array(
                'type' => 'image',
1234
                'src'  => theme_get_url('images/btn_search_off.gif')
1235
            )
1236
1237
1238
1239
        )
    ));
}

1240
1241
function get_loggedin_string() {
    global $USER;
1242
1243
1244

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

1245
1246
1247
1248
1249
1250
1251
1252
    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';
    }
1253
1254
1255
1256
1257
1258
1259
1260

    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>)';
    }
1261
1262
1263
1264

    return $str;
}

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
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
/**
 * Returns the name of the current script, WITH the querystring portion.
 * this function is necessary because PHP_SELF and REQUEST_URI and SCRIPT_NAME
 * return different things depending on a lot of things like your OS, Web
 * server, and the way PHP is compiled (ie. as a CGI, module, ISAPI, etc.)
 * <b>NOTE:</b> This function returns false if the global variables needed are not set.
 *
 * @return string
 */
function get_script_path() {

    if (!empty($_SERVER['REQUEST_URI'])) {
        return $_SERVER['REQUEST_URI'];

    } else if (!empty($_SERVER['PHP_SELF'])) {
        if (!empty($_SERVER['QUERY_STRING'])) {
            return $_SERVER['PHP_SELF'] .'?'. $_SERVER['QUERY_STRING'];
        }
        return $_SERVER['PHP_SELF'];

    } else if (!empty($_SERVER['SCRIPT_NAME'])) {
        if (!empty($_SERVER['QUERY_STRING'])) {
            return $_SERVER['SCRIPT_NAME'] .'?'. $_SERVER['QUERY_STRING'];
        }
        return $_SERVER['SCRIPT_NAME'];

    } else if (!empty($_SERVER['URL'])) {     // May help IIS (not well tested)
        if (!empty($_SERVER['QUERY_STRING'])) {
            return $_SERVER['URL'] .'?'. $_SERVER['QUERY_STRING'];
        }
        return $_SERVER['URL'];

    } else {
        log_warn('Warning: Could not find any of these web server variables: $REQUEST_URI, $PHP_SELF, $SCRIPT_NAME or $URL');
        return false;
    }
}

/**
 * Like {@link me()} but returns a full URL
 * @see me()
 * @return string
 */
function get_full_script_path() {

    global $CFG;

    if (!empty($CFG->wwwroot)) {
        $url = parse_url($CFG->wwwroot);
    }

    if (!empty($url['host'])) {
        $hostname = $url['host'];
    } else if (!empty($_SERVER['SERVER_NAME'])) {
        $hostname = $_SERVER['SERVER_NAME'];
    } else if (!empty($_ENV['SERVER_NAME'])) {
        $hostname = $_ENV['SERVER_NAME'];
    } else if (!empty($_SERVER['HTTP_HOST'])) {
        $hostname = $_SERVER['HTTP_HOST'];
    } else if (!empty($_ENV['HTTP_HOST'])) {
        $hostname = $_ENV['HTTP_HOST'];
    } else {
        log_warn('Warning: could not find the name of this server!');
        return false;
    }

    if (!empty($url['port'])) {
        $hostname .= ':'.$url['port'];
    } else if (!empty($_SERVER['SERVER_PORT'])) {
        if ($_SERVER['SERVER_PORT'] != 80 && $_SERVER['SERVER_PORT'] != 443) {
            $hostname .= ':'.$_SERVER['SERVER_PORT'];
        }
    }

    if (isset($_SERVER['HTTPS'])) {
        $protocol = ($_SERVER['HTTPS'] == 'on') ? 'https://' : 'http://';
    } else if (isset($_SERVER['SERVER_PORT'])) { # Apache2 does not export $_SERVER['HTTPS']
        $protocol = ($_SERVER['SERVER_PORT'] == '443') ? 'https://' : 'http://';
    } else {
        $protocol = 'http://';
    }

    $url_prefix = $protocol.$hostname;
    return $url_prefix . get_script_path();
}

function has_page_help() {
    // the path of the current script (used for page help)
    $scriptname = substr(get_full_script_path(), strlen(get_config('wwwroot')));
    if (strpos($scriptname, '.php') != (strlen($scriptname) - 4)) {
        $scriptname .= 'index.php';
    }
    $scriptname = substr($scriptname, 0, -4);
    
    $firstdir = $scriptname;
    if (false !== ($slashpos = strpos($scriptname, '/'))) {
        $firstdir = substr($scriptname, 0, $slashpos);
    }

    if (in_array($firstdir, plugin_types())) {
        $bits = explode('/', $scriptname);
        if (count($bits) > 2) {
            $plugintype = $bits[0];
            $pluginname = $bits[1];
            $pagehelp = get_config('docroot') . $plugintype . '/' . $pluginname . '/lang/en.utf8/help/pages/' . 
                substr($scriptname, strlen($plugintype . '/' . $pluginname . '/')) . '.html';
        }
    }
    if (empty($plugintype)) {
        $plugintype = 'core';
        $pluginname = 'pages';
        $pagehelp = get_config('docroot') . 'lang/en.utf8/help/pages/' . $scriptname . '.html';
    }

    if (is_readable($pagehelp)) {
        $scriptname = str_replace('/', '-', $scriptname);
        return array($scriptname, get_help_icon($plugintype, $pluginname, '', '', $scriptname));
    }
    return false;
}

Nigel McNie's avatar
Nigel McNie committed
1387
?>