web.php 164 KB
Newer Older
1 2 3 4 5
<?php
/**
 *
 * @package    mahara
 * @subpackage core
6
 * @author     Catalyst IT Ltd
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9 10 11 12 13 14
 * @copyright  (C) portions from Moodle, (C) Martin Dougiamas http://dougiamas.com
 */

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


15 16 17
function smarty_core() {
    require_once 'dwoo/dwoo/dwooAutoload.php';
    require_once 'dwoo/mahara/Dwoo_Mahara.php';
18

19
    return new Dwoo_Mahara();
20 21 22
}


23 24 25 26 27 28 29 30 31

/**
 * Function to set an optional page icon. Mahara uses fontawesome for icons by default,
 * (http://fortawesome.github.io/Font-Awesome/icons/) but this can be overridden at the theme
 * level by supplying a different icon font + css.
 *
 * @param Smarty | an initialized smarty object
 * @param String | the name of the icon to include (eg "icon-university")
 */
Pat Kira's avatar
Pat Kira committed
32
function setpageicon($smarty, $icon) {
33 34 35 36 37 38
    $smarty->assign('pageicon', 'icon ' . $icon);
}



/**
39 40
 * Helper function (called by smarty()) to determine what stylesheets to include
 * on the page (based on constants, global variables, and $extraconfig)
41
 *
42 43
 * @param $stylesheets Stylesheets we already know we're going to need
 * @param $extraconfig Extra configuration passed to smarty()
44 45 46
 * @return array
 */

Pat Kira's avatar
Pat Kira committed
47
function get_stylesheets_for_current_page($stylesheets, $extraconfig) {
48 49 50 51 52 53 54

    global $USER, $SESSION, $THEME, $HEADDATA, $langselectform;

    // stylesheet set up - if we're in a plugin also get its stylesheet
    $allstylesheets = $THEME->get_url('style/style.css', true);

    // determine if we want to include the parent css
Pat Kira's avatar
Pat Kira committed
55
    if (isset($THEME->overrideparentcss) && $THEME->overrideparentcss && $THEME->parent) {
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
        unset($allstylesheets[$THEME->parent]);
    }

    $stylesheets = array_merge($stylesheets, array_reverse(array_values($allstylesheets)));

    if (defined('SECTION_PLUGINTYPE') && defined('SECTION_PLUGINNAME') && SECTION_PLUGINTYPE != 'core') {
        if ($pluginsheets = $THEME->get_url('style/style.css', true, SECTION_PLUGINTYPE . '/' . SECTION_PLUGINNAME)) {
            $stylesheets = array_merge($stylesheets, array_reverse($pluginsheets));
        }
    }

    if ($adminsection = in_admin_section()) {
        if ($adminsheets = $THEME->get_url('style/admin.css', true)) {
            $stylesheets = array_merge($stylesheets, array_reverse($adminsheets));
        }
    }

    if (get_config('developermode') & DEVMODE_DEBUGCSS) {
        $stylesheets[] = get_config('wwwroot') . 'theme/debug.css';
    }

    // look for extra stylesheets
    if (isset($extraconfig['stylesheets']) && is_array($extraconfig['stylesheets'])) {
        foreach ($extraconfig['stylesheets'] as $extrasheet) {
            if ($sheets = $THEME->get_url($extrasheet, true)) {
                $stylesheets = array_merge($stylesheets, array_reverse(array_values($sheets)));
            }
        }
    }
85 86 87 88

    // Only add additional stylesheets when configurable theme is set.
    if ($THEME->basename == 'custom') {
        $sheets = $THEME->additional_stylesheets();
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
        $stylesheets = array_merge($stylesheets, $sheets);
    }

    // Give the skin a chance to affect the page
    if (!empty($extraconfig['skin'])) {
        require_once(get_config('docroot').'/lib/skin.php');
        $skinobj = new Skin($extraconfig['skin']['skinid']);
        $viewid = isset($extraconfig['skin']['viewid']) ? $extraconfig['skin']['viewid'] : null;
        $stylesheets = array_merge($stylesheets, $skinobj->get_stylesheets($viewid));
    }

    $langdirection = get_string('thisdirection', 'langconfig');

    // Include rtl.css for right-to-left langs
    if ($langdirection == 'rtl') {
        $smarty->assign('LANGDIRECTION', 'rtl');
        if ($rtlsheets = $THEME->get_url('style/rtl.css', true)) {
            $stylesheets = array_merge($stylesheets, array_reverse($rtlsheets));
        }
    }

    $stylesheets = append_version_number($stylesheets);

    return $stylesheets;
}

Pat Kira's avatar
Pat Kira committed
115

116 117 118 119
/**
 * This function creates a Smarty object and sets it up for use within our
 * podclass app, setting up some variables.
 *
120 121
 * WARNING: If you are using pieforms, set them up BEFORE calling this function.
 *
122 123
 * The variables that it sets up are:
 *
124
 * - WWWROOT: The base url for the Mahara system
125 126 127 128 129
 * - 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).
130 131
 * - PUBLIC: Set true if this page is a public page
 * - MAINNAV: Array defining the main navigation
132
 *
133
 * @param $javascript A list of javascript includes.  Each include should be just
134
 *                    the name of a file, and reside in js/{filename}
135 136 137
 * @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.
138
 * @return Dwoo_Mahara
139
 */
140

141 142


143
function smarty($javascript = array(), $headers = array(), $pagestrings = array(), $extraconfig = array()) {
Aaron Wells's avatar
Aaron Wells committed
144
    global $USER, $SESSION, $THEME, $HEADDATA, $langselectform, $CFG;
145 146 147 148 149 150 151 152 153 154 155

    if (!is_array($headers)) {
        $headers = array();
    }
    if (!is_array($pagestrings)) {
        $pagestrings = array();
    }
    if (!is_array($extraconfig)) {
        $extraconfig = array();
    }

156
    $sideblocks = array();
157 158 159 160 161
    // Some things like die_info() will try and create a smarty() call when we are already in one, which causes
    // language_select_form() to throw headdata error as it is called twice.
    if (!isset($langselectform)) {
        $langselectform = language_select_form();
    }
162 163
    $smarty = smarty_core();

164
    $wwwroot = get_config('wwwroot');
Aaron Wells's avatar
Aaron Wells committed
165
    // NOTE: not using jswwwroot - it seems to wreck image paths if you
166
    // drag them around the wysiwyg editor
167
    $jswwwroot = json_encode($wwwroot);
Martyn Smith's avatar
Martyn Smith committed
168

169 170 171 172 173 174 175 176 177 178
    // Workaround for $cfg->cleanurlusersubdomains.
    // When cleanurlusersubdomains is on, ajax requests might come from somewhere other than
    // the wwwroot.  To avoid cross-domain requests, set a js variable when this page is on a
    // different subdomain, and let the ajax wrapper function sendjsonrequest rewrite its url
    // if necessary.
    if (get_config('cleanurls') && get_config('cleanurlusersubdomains')) {
        if ($requesthost = get_requested_host_name()) {
            $wwwrootparts = parse_url($wwwroot);
            if ($wwwrootparts['host'] != $requesthost) {
                $fakewwwroot = $wwwrootparts['scheme'] . '://' . $requesthost . '/';
179
                $headers[] = '<script type="application/javascript">var fakewwwroot = ' . json_encode($fakewwwroot) . ';</script>';
180 181 182 183
            }
        }
    }

Martyn Smith's avatar
Martyn Smith committed
184
    $theme_list = array();
185
    $adminsection = in_admin_section();
Aaron Wells's avatar
Aaron Wells committed
186

187 188
    if (function_exists('pieform_get_headdata')) {
        $headers = array_merge($headers, pieform_get_headdata());
189 190 191
        if (!defined('PIEFORM_GOT_HEADDATA')) {
          define('PIEFORM_GOT_HEADDATA', 1);
        }
192
    }
193

194 195 196
    // Define the stylesheets array early so that javascript modules can add extras
    $stylesheets = array();

Aaron Wells's avatar
Aaron Wells committed
197
    // Insert the appropriate javascript tags
198
    $javascript_array = array();
199
    $jsroot = $wwwroot . 'js/';
200

201 202
    $langdirection = get_string('thisdirection', 'langconfig');

203 204
    // Make jQuery accessible with $j (Mochikit has $)
    $javascript_array[] = $jsroot . 'jquery/jquery.js';
205
    $headers[] = '<script type="application/javascript">$j=jQuery;</script>';
206

207 208 209 210 211
    // If necessary, load MathJax configuration
    if (get_config('mathjax')) {
        $headers[] = '<script type="application/javascript">'.get_config('mathjaxconfig').'</script>';
    }

Richard Mansfield's avatar
Richard Mansfield committed
212
    // TinyMCE must be included first for some reason we're not sure about
213 214 215 216
    //
    // Note: we do not display tinyMCE for mobile devices
    // as it doesn't work on some of them and can
    // disable the editing of a textarea field
217
    if (is_html_editor_enabled()) {
218 219 220 221 222 223
        $checkarray = array(&$javascript, &$headers);
        $found_tinymce = false;
        foreach ($checkarray as &$check) {
            if (($key = array_search('tinymce', $check)) !== false || ($key = array_search('tinytinymce', $check)) !== false) {
                if (!$found_tinymce) {
                    $found_tinymce = $check[$key];
224
                    $javascript_array[] = $wwwroot . 'artefact/file/js/filebrowser.js';
225
                    $javascript_array[] = $jsroot . 'switchbox.js';
226 227
                    $javascript_array[] = $jsroot . 'tinymce/tinymce.js';
                    $stylesheets = array_merge($stylesheets, array_reverse(array_values($THEME->get_url('style/tinymceskin.css', true))));
228
                    $content_css = json_encode($THEME->get_url('style/tinymce.css'));
229 230
                    $language = current_language();
                    $language = substr($language, 0, ((substr_count($language, '_') > 0) ? 5 : 2));
231
                    if ($language != 'en' && !file_exists(get_config('docroot') . 'js/tinymce/langs/' . $language . '.js')) {
232 233 234 235 236 237 238 239
                        // In case the language file exists as a string with both lower and upper case, eg fr_FR we test for this
                        $language = substr($language, 0, 2) . '_' . strtoupper(substr($language, 0, 2));
                        if (!file_exists(get_config('docroot') . 'js/tinymce/langs/' . $language . '.js')) {
                            // In case we fail to find a language of 5 chars, eg pt_BR (Portugese, Brazil) we try the 'parent' pt (Portugese)
                            $language = substr($language, 0, 2);
                            if ($language != 'en' && !file_exists(get_config('docroot') . 'js/tinymce/langs/' . $language . '.js')) {
                                $language = 'en';
                            }
240
                        }
241 242
                    }
                    $extrasetup = isset($extraconfig['tinymcesetup']) ? $extraconfig['tinymcesetup'] : '';
243
                    $extramceconfig = isset($extraconfig['tinymceconfig']) ? $extraconfig['tinymceconfig'] : '';
244

245
                    // Check whether to make the spellchecker available
246
                    if (get_config('tinymcespellcheckerengine')) {
247
                        $spellchecker = ',spellchecker';
248
                        $spellchecker_toolbar = '| spellchecker';
249
                        $spellchecker_config = "gecko_spellcheck : false, spellchecker_rpc_url : \"{$jsroot}tinymce/plugins/spellchecker/spellchecker.php\",";
250 251
                    }
                    else {
252
                        $spellchecker = $spellchecker_toolbar = '';
253 254
                        $spellchecker_config = 'gecko_spellcheck : true,';
                    }
255 256
                    $mathslate = (get_config('mathjax')) ? 'mathslate' : '';
                    $mathslateplugin = !empty($mathslate) ? ',' . $mathslate : '';
257
                    $toolbar = array(
258
                        null,
259
                        '"toolbar_toggle | formatselect | bold italic | bullist numlist | link unlink | imagebrowser | undo redo"',
260
                        '"underline strikethrough subscript superscript | alignleft aligncenter alignright alignjustify | outdent indent | forecolor backcolor | ltr rtl | fullscreen"',
261
                        '"fontselect | fontsizeselect | emoticons nonbreaking charmap ' . $mathslate . ' ' . $spellchecker_toolbar . ' | table | removeformat pastetext | code"',
262 263 264 265 266 267
                    );

                    // For right-to-left langs, reverse button order & align controls right.
                    $tinymce_langdir = $langdirection == 'rtl' ? 'rtl' : 'ltr';
                    $toolbar_align = 'left';

268 269 270 271
                    // Language strings required for TinyMCE
                    $pagestrings['mahara'] = isset($pagestrings['mahara']) ? $pagestrings['mahara'] : array();
                    $pagestrings['mahara'][] = 'attachedimage';

272 273 274 275 276 277 278 279 280 281 282
                    $tinymceinitbehatsetup = '';
                    $tinymcebehatsetup = '';
                    if (defined('BEHAT_TEST')) {
                        $tinymceinitbehatsetup = 'window.isEditorInitializing = false;';
                        $tinymcebehatsetup = <<<EOF
        ed.on('PreInit', function(ed) {
            window.isEditorInitializing = true;
        });
EOF;
                    }

283
                    if ($check[$key] == 'tinymce') {
284 285
                        $tinymceconfig = <<<EOF
    theme: "modern",
286
    plugins: "tooltoggle,textcolor,visualblocks,wordcount,link,lists,imagebrowser,table,emoticons{$spellchecker},paste,code,fullscreen,directionality,searchreplace,nonbreaking,charmap{$mathslateplugin}",
287
    skin: 'light',
288 289
    toolbar1: {$toolbar[1]},
    toolbar2: {$toolbar[2]},
290
    toolbar3: {$toolbar[3]},
291
    menubar: false,
292
    fix_list_elements: true,
293
    image_advtab: true,
294
    table_style_by_css: true,
295
    {$spellchecker_config}
296
EOF;
297 298
                    }
                    else {
299 300 301
                        $tinymceconfig = <<<EOF
    selector: "textarea.tinywysiwyg",
    theme: "modern",
302
    skin: 'light',
303 304
    plugins: "fullscreen,autoresize",
    toolbar: {$toolbar[0]},
305
EOF;
306
                    }
307

308
                    $headers[] = <<<EOF
309
<script type="application/javascript">
310
tinyMCE.init({
311 312
    {$tinymceconfig}
    schema: 'html4',
313 314 315 316 317 318 319 320 321
    extended_valid_elements:
        "object[width|height|classid|codebase]"
        + ",param[name|value]"
        + ",embed[src|type|width|height|flashvars|wmode]"
        + ",script[src,type,language]"
        + ",ul[id|type|compact]"
        + ",iframe[src|width|height|name|scrolling|frameborder|allowfullscreen|webkitallowfullscreen|mozallowfullscreen|longdesc|marginheight|marginwidth|align|title|class|type]"
        + ",a[id|class|title|href|name]"
    ,urlconverter_callback : "custom_urlconvert",
322
    language: '{$language}',
323
    directionality: "{$tinymce_langdir}",
324
    content_css : {$content_css},
325
    font_formats: 'Andale Mono=andale mono,times;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;Comic Sans MS=comic sans ms,sans-serif;Courier New=courier new,courier;Georgia=georgia,palatino;Helvetica=helvetica;Impact=impact,chicago;Open Sans=Open Sans;Symbol=symbol;Tahoma=tahoma,arial,helvetica,sans-serif;Terminal=terminal,monaco;Times New Roman=times new roman,times;Trebuchet MS=trebuchet ms,geneva;Verdana=verdana,geneva;Webdings=webdings;Wingdings=wingdings,zapf dingbats;',
326
    remove_script_host: false,
327
    relative_urls: false,
328
    target_list: false,
Aaron Wells's avatar
Aaron Wells committed
329
    cache_suffix: '?v={$CFG->cacheversion}',
330
    {$extramceconfig}
331
    setup: function(ed) {
332
        {$tinymcebehatsetup}
333
        ed.on('init', function(ed) {
334
        {$tinymceinitbehatsetup}
335
            if (typeof(editor_to_focus) == 'string' && ed.editorId == editor_to_focus) {
336 337 338
                ed.focus();
            }
        });
339 340 341
        ed.on('keyup change', function (e) {
            checkTextareaMaxLength(ed.settings.id);
        });
342 343
        ed.on('LoadContent', function(e) {
            // Hide all the 2nd/3rd row menu buttons
344
            jQuery('.mce-toolbar.mce-first').siblings().addClass('hidden');
345 346 347 348 349 350 351 352 353 354 355
            // The tinymce fullscreen mode does not work properly in a transformed container div
            // such as div.vertcentre
            // and IE doesn't like a preset z-index
            // This work-around will remove/add classes: .vertcenter .configure .blockinstane
            // of the configure block div
            // when toggling fullscreen
            jQuery('div[aria-label="Fullscreen"]').on('click', function(e) {
                jQuery('div#configureblock').toggleClass('vertcentre');
                jQuery('div#configureblock').toggleClass('blockinstance');
                jQuery('div#configureblock').toggleClass('configure');
            });
356
        });
357
        {$extrasetup}
358
    }
359
});
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376

function imageBrowserConfigSuccess(form, data) {
    // handle updates to file browser
    // final form submission handled by tinymce plugin
    if (data.formelementsuccess) {
        eval(data.formelementsuccess + '(form, data)');
        return;
    }
}

function imageBrowserConfigError(form, data) {
    if (data.formelementerror) {
        eval(data.formelementerror + '(form, data)');
        return;
    }
}

377
function custom_urlconvert (u, n, e) {
378 379
    // Don't convert the url on the skype status buttons.
    if (u.indexOf('skype:') == 0) {
380
      return u;
381 382
    }
    var t = tinyMCE.activeEditor, s = t.settings;
383

384 385
    // Don't convert link href since thats the CSS files that gets loaded into the editor also skip local file URLs
    if (!s.convert_urls || (e && e.nodeName == 'LINK') || u.indexOf('file:') === 0)
386 387
      return u;

388 389
    // Convert to relative
    if (s.relative_urls)
390 391
      return t.documentBaseURI.toRelative(u);

392 393
    // Convert to absolute
    u = t.documentBaseURI.toAbsolute(u, s.remove_script_host);
394

395
    return u;
396
}
397 398 399
</script>

EOF;
400 401 402 403 404 405 406
                    unset($check[$key]);
                }
                else {
                    if ($check[$key] != $found_tinymce) {
                        log_warn('Two differently configured tinyMCE instances have been asked for on this page! This is not possible');
                    }
                    unset($check[$key]);
407
                }
408
            }
409

410 411 412 413
            // If any page adds jquery explicitly, remove it from the list
            if (($key = array_search('jquery', $check)) !== false) {
                unset($check[$key]);
            }
414
        }
415
    }
416 417 418 419 420 421 422 423
    else {
        if (($key = array_search('tinymce', $javascript)) !== false || ($key = array_search('tinytinymce', $javascript)) !== false) {
            unset($javascript[$key]);
        }
        if (($key = array_search('tinymce', $headers)) !== false || ($key = array_search('tinytinymce', $headers)) !== false) {
            unset($headers[$key]);
        }
    }
Martyn Smith's avatar
Martyn Smith committed
424
    $javascript_array[] = $jsroot . 'keyboardNavigation.js';
425

426 427 428 429 430
    //If necessary, load MathJax path
    if (get_config('mathjax')) {
        $javascript_array[] = get_config('mathjaxpath');
    }

431
    $strings = array();
432 433 434 435 436 437 438 439 440
    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);
        }
441 442
    }

443
    $jsstrings = jsstrings();
Martyn Smith's avatar
Martyn Smith committed
444
    $themepaths = themepaths();
445

Richard Mansfield's avatar
Richard Mansfield committed
446
    foreach ($javascript as $jsfile) {
447 448 449 450
        // 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.
451
        if (strpos($jsfile, '/') === false) {
452
            $javascript_array[] = $jsroot . $jsfile . '.js';
453
            if (isset($jsstrings[$jsfile])) {
454 455 456
                foreach ($jsstrings[$jsfile] as $section => $tags) {
                    foreach ($tags as $tag) {
                        $strings[$tag] = get_raw_string($tag, $section);
457 458 459
                    }
                }
            }
Martyn Smith's avatar
Martyn Smith committed
460 461
            if (isset($themepaths[$jsfile])) {
                foreach ($themepaths[$jsfile] as $themepath) {
Nigel McNie's avatar
Nigel McNie committed
462
                    $theme_list[$themepath] = $THEME->get_url($themepath);
Martyn Smith's avatar
Martyn Smith committed
463 464
                }
            }
465
        }
466
        else if (stripos($jsfile, 'http://') === false && stripos($jsfile, 'https://') === false) {
467
            // A local .js file with a fully specified path
468
            $javascript_array[] = $wwwroot . $jsfile;
469 470 471 472 473 474
            // If $jsfile is from a plugin or plugin's block, i.e.:
            // - plugintype/pluginname/js/foo.js
            // - plugintype/pluginname/blocktype/pluginname/js/foo.js
            // Then get js strings from static function jsstrings in:
            // - plugintype/pluginname/lib.php, or
            // - plugintype/pluginname/blocktype/pluginname/lib.php
475
            $bits = explode('/', $jsfile);
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492
            $pluginname = false;
            $plugintype = false;
            $jsfilename = false;
            if (count($bits) == 4 && $bits[2] == 'js' && in_array($bits[0], plugin_types())) {
                $plugintype = $bits[0];
                $pluginname = $bits[1];
                $jsfilename = $bits[3];
            }
            if (count($bits) == 6 && $bits[0] == 'artefact' && $bits[2] == 'blocktype' && $bits[4] == 'js') {
                $plugintype = 'blocktype';
                $pluginname = $bits[3];
                $jsfilename = $bits[5];
            }
            if ($pluginname) {
                safe_require($plugintype, $pluginname);
                $pluginclass = generate_class_name($plugintype, $pluginname);
                $name = substr($jsfilename, 0, strpos($jsfilename, '.js'));
493 494
                if (is_callable(array($pluginclass, 'jsstrings'))) {
                    $tempstrings = call_static_method($pluginclass, 'jsstrings', $name);
495 496 497
                    foreach ($tempstrings as $section => $tags) {
                        foreach ($tags as $tag) {
                            $strings[$tag] = get_raw_string($tag, $section);
498 499
                        }
                    }
Richard Mansfield's avatar
Richard Mansfield committed
500
                }
501 502 503 504
                if (is_callable(array($pluginclass, 'jshelp'))) {
                    $tempstrings = call_static_method($pluginclass, 'jshelp', $name);
                    foreach ($tempstrings as $section => $tags) {
                        foreach ($tags as $tag) {
505
                            $strings[$tag . '.help'] = get_help_icon($plugintype, $pluginname, null, null,
506 507 508 509
                                                                     null, $tag);
                        }
                    }
                }
Martyn Smith's avatar
Martyn Smith committed
510 511 512
                if (is_callable(array($pluginclass, 'themepaths'))) {
                    $tmpthemepaths = call_static_method($pluginclass, 'themepaths', $name);
                    foreach ($tmpthemepaths as $themepath) {
Nigel McNie's avatar
Nigel McNie committed
513
                        $theme_list[$themepath] = $THEME->get_url($themepath);
Martyn Smith's avatar
Martyn Smith committed
514 515
                    }
                }
Martyn Smith's avatar
Martyn Smith committed
516
            }
Martyn Smith's avatar
Martyn Smith committed
517
        }
518 519 520 521
        else {
            // A remote .js file
            $javascript_array[] = $jsfile;
        }
522
    }
523 524

    $javascript_array[] = $jsroot . 'mahara.js';
525
    $javascript_array[] = $jsroot . 'formchangechecker.js';
526
    $javascript_array[] = $jsroot . 'textareamaxlengthchecker.js';
527

528 529 530 531 532 533
    // Load some event handler functions for checking if all AJAX requests have completed
    // when running behat tests
    if (defined('BEHAT_TEST')) {
        $javascript_array[] = get_config('wwwroot') . 'testing/frameworks/behat/page_status.js';
    }

534 535 536
    foreach ($jsstrings['mahara'] as $section => $tags) {
        foreach ($tags as $tag) {
            $strings[$tag] = get_raw_string($tag, $section);
537 538
        }
    }
539 540
    if (isset($extraconfig['themepaths']) && is_array($extraconfig['themepaths'])) {
        foreach ($extraconfig['themepaths'] as $themepath) {
Nigel McNie's avatar
Nigel McNie committed
541
            $theme_list[$themepath] = $THEME->get_url($themepath);
542 543
        }
    }
544

545
    $stringjs = '<script type="application/javascript">';
546
    $stringjs .= 'var strings = ' . json_encode($strings) . ';';
547
    $stringjs .= "\nfunction plural(n) { return " . get_raw_string('pluralrule', 'langconfig') . "; }\n";
548 549
    $stringjs .= '</script>';

550

551 552 553
    // Allow us to set the HTML lang attribute
    $smarty->assign('LANGUAGE', substr(current_language(), 0, 2));

554
    $smarty->assign('STRINGJS', $stringjs);
555

556
    $stylesheets = get_stylesheets_for_current_page($stylesheets, $extraconfig);
557

Son Nguyen's avatar
Son Nguyen committed
558 559 560 561
    // Disable CSS transforms, transitions, and animations when running behat tests
    if (defined('BEHAT_TEST')) {
        $stylesheets[] = get_config('wwwroot') . 'testing/frameworks/behat/no_transitions.css';
    }
562
    $smarty->assign('STYLESHEETLIST', $stylesheets);
563 564
    if (!empty($theme_list)) {
        // this gets assigned in smarty_core, but do it again here if it's changed locally
Aaron Wells's avatar
Aaron Wells committed
565
        $smarty->assign('THEMELIST', json_encode(array_merge((array)json_decode($smarty->get_template_vars('THEMELIST')),  $theme_list)));
566
    }
567

568 569 570 571 572
    $dropdownmenu = get_config('dropdownmenu');
    // disable drop-downs if overridden at institution level
    $sitethemeprefs = get_config('sitethemeprefs');
    $institutions = $USER->institutions;
    if (!empty($institutions)) {
573 574 575 576
        if (count($institutions) == 1) {
            $i = reset($institutions);
            if ($i->theme == $THEME->basename && $USER->institutiontheme->institutionname == $i->institution) {
                $dropdownmenu = $i->dropdownmenu;
577
            }
578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
        }
        else {
            foreach ($institutions as $i) {
                if (!empty($sitethemeprefs)) {
                    if (!empty($USER->accountprefs['theme']) && $USER->accountprefs['theme'] == $THEME->basename . '/' . $i->institution) {
                        $dropdownmenu = $i->dropdownmenu;
                        break;
                    }
                }
                else {
                    if ((!empty($USER->accountprefs['theme']) && $USER->accountprefs['theme'] == $THEME->basename . '/' . $i->institution)
                        || (empty($USER->accountprefs) && $i->theme == $THEME->basename && $USER->institutiontheme->institutionname == $i->institution)) {
                        $dropdownmenu = $i->dropdownmenu;
                        break;
                    }
593 594 595 596 597 598
                }
            }
        }
    }

    // and/or disable drop-downs if a handheld device detected
599
    $dropdownmenu = $SESSION->get('handheld_device') ? false : $dropdownmenu && get_config('dropdownmenuenabled');
600

601 602
    if ($dropdownmenu) {
        $smarty->assign('DROPDOWNMENU', $dropdownmenu);
603
        $javascript_array[] = $jsroot . 'dropdown-nav.js';
604
    }
605

606
    $smarty->assign('MOBILE', $SESSION->get('mobile'));
607
    $smarty->assign('HANDHELD_DEVICE', $SESSION->get('handheld_device'));
608 609 610 611 612 613 614 615 616
    if (defined('FILEBROWSERS') ||
        (defined('SECTION_PAGE') && SECTION_PAGE == 'blocks')) {
        // Need to add the headers for select2 here so filebrowser has correct language
        require_once(get_config('libroot') . 'form/elements/autocomplete.php');
        $select2lang = pieform_element_autocomplete_language();
        $select2headdata = pieform_element_autocomplete_get_headdata();
        $headers = array_merge($headers, $select2headdata);
        $smarty->assign('select2_language', $select2lang);
    }
617

618 619 620 621
    $sitename = get_config('sitename');
    if (!$sitename) {
       $sitename = 'Mahara';
    }
622
    $smarty->assign('sitename', $sitename);
623

624 625 626 627
    $sitelogocustom = false;
    if (get_config('installed')) {
        $sitelogocustom = (int) (get_field('institution', 'logo', 'name', 'mahara') || $THEME->headerlogo);
    }
628
    $smarty->assign('sitelogocustom', $sitelogocustom);
629
    $sitelogo = $THEME->header_logo();
630
    $sitelogo = append_version_number($sitelogo);
631
    $smarty->assign('sitelogo', $sitelogo);
632 633
    $smarty->assign('sitelogo4facebook', $THEME->facebook_logo());
    $smarty->assign('sitedescription4facebook', get_string('facebookdescription', 'mahara'));
634

Martyn Smith's avatar
Martyn Smith committed
635
    if (defined('TITLE')) {
636
        $smarty->assign('PAGETITLE', TITLE . ' - ' . $sitename);
Martyn Smith's avatar
Martyn Smith committed
637 638
    }
    else {
639
        $smarty->assign('PAGETITLE', $sitename);
Martyn Smith's avatar
Martyn Smith committed
640
    }
641 642 643 644 645 646 647 648 649
    if (defined('PAGEHEADING')) {
        $smarty->assign('PAGEHEADING', PAGEHEADING);
    }
    else {
        if (defined('TITLE')) {
            $smarty->assign('PAGEHEADING', TITLE);
        }
    }

650 651 652
    if (defined('SUBSECTIONHEADING')) {
        $smarty->assign('SUBSECTIONHEADING', SUBSECTIONHEADING);
    }
Martyn Smith's avatar
Martyn Smith committed
653

654
    $smarty->assign('PRODUCTIONMODE', get_config('productionmode'));
655
    if (function_exists('local_header_top_content')) {
656
        $sitetop = (isset($sitetop) ? $sitetop : '') . local_header_top_content();
657 658 659
    }
    if (isset($sitetop)) {
        $smarty->assign('SITETOP', $sitetop);
660
    }
661 662 663
    if (defined('PUBLIC')) {
        $smarty->assign('PUBLIC', true);
    }
664 665 666
    if (defined('ADMIN')) {
        $smarty->assign('ADMIN', true);
    }
667 668 669
    if (defined('INSTITUTIONALADMIN')) {
        $smarty->assign('INSTITUTIONALADMIN', true);
    }
670 671 672 673 674 675
    if (defined('STAFF')) {
        $smarty->assign('STAFF', true);
    }
    if (defined('INSTITUTIONALSTAFF')) {
        $smarty->assign('INSTITUTIONALSTAFF', true);
    }
676

677
    $smarty->assign('LOGGEDIN', $USER->is_logged_in());
678 679 680 681 682 683 684
    $publicsearchallowed = false;
    $searchplugin = get_config('searchplugin');
    if ($searchplugin) {
        safe_require('search', $searchplugin);
        $publicsearchallowed = (call_static_method(generate_class_name('search', $searchplugin), 'publicform_allowed') && get_config('publicsearchallowed'));
    }
    $smarty->assign('publicsearchallowed', $publicsearchallowed);
685
    if ($USER->is_logged_in()) {
686
        global $SELECTEDSUBNAV; // It's evil, but rightnav & mainnav stuff are now in different templates.
687 688 689 690 691 692 693 694 695 696 697
        if (in_array('raw_old', $THEME->inheritance)) {
            $menutype = (in_admin_section() ? 'adminnav' : null);
            $smarty->assign('MAINNAV', main_nav($menutype));
        }
        else {
            $smarty->assign('MAINNAV', main_nav());
            $is_admin = $USER->get('admin') || $USER->is_institutional_admin() || $USER->get('staff') || $USER->is_institutional_staff();
            if ($is_admin) {
                $smarty->assign('MAINNAVADMIN', main_nav('adminnav'));
            }
        }
698
        $mainnavsubnav = $SELECTEDSUBNAV;
699
        $smarty->assign('RIGHTNAV', right_nav());
700 701 702 703 704 705 706 707 708
        if (!$mainnavsubnav && $dropdownmenu) {
            // In drop-down navigation, the submenu is only usable if its parent is one of the top-level menu
            // items.  But if the submenu comes from something in right_nav (settings), it's unreachable.
            // Turning the submenu into SUBPAGENAV group-style tabs makes it usable.
            $smarty->assign('SUBPAGENAV', $SELECTEDSUBNAV);
        }
        else {
            $smarty->assign('SELECTEDSUBNAV', $SELECTEDSUBNAV);
        }
709
    }
710
    else {
711
        $smarty->assign('languageform', $langselectform);
712
    }
713
    $smarty->assign('FOOTERMENU', footer_menu());
714

715
    $smarty->assign('USER', $USER);
716
    $smarty->assign('SESSKEY', $USER->get('sesskey'));
717
    $smarty->assign('CC_ENABLED', get_config('cookieconsent_enabled'));
718
    $javascript_array = append_version_number($javascript_array);
719
    $smarty->assign('JAVASCRIPT', $javascript_array);
720
    $smarty->assign('RELEASE', get_config('release'));
721
    $smarty->assign('SERIES', get_config('series'));
722
    $smarty->assign('CACHEVERSION', get_config('cacheversion', 0));
723
    if (get_config('siteclosedforupgrade')) {
724
        $smarty->assign('SITECLOSED', 'logindisabled');
725
    }
726
    else if (get_config('siteclosedbyadmin')) {
727
        $smarty->assign('SITECLOSED', 'loginallowed');
728
    }
729

730 731
    if ((!isset($extraconfig['pagehelp']) || $extraconfig['pagehelp'] !== false)
        and $help = has_page_help()) {
732 733 734
        $smarty->assign('PAGEHELPNAME', $help[0]);
        $smarty->assign('PAGEHELPICON', $help[1]);
    }
735
    if (defined('GROUP')) {
736
        require_once('group.php');
737 738 739 740 741 742
        if ($group = group_current_group()) {
            $smarty->assign('GROUP', $group);
            if (!defined('NOGROUPMENU')) {
                $smarty->assign('SUBPAGENAV', group_get_menu_tabs());
                $smarty->assign('PAGEHEADING', $group->name);
            }
743
        }
744
    }
745

Martyn Smith's avatar
Martyn Smith committed
746
    // ---------- sideblock stuff ----------
747 748
    $sidebars = !isset($extraconfig['sidebars']) || $extraconfig['sidebars'] !== false;
    if ($sidebars && !defined('INSTALLER') && (!defined('MENUITEM') || substr(MENUITEM, 0, 5) != 'admin')) {
749
        if (get_config('installed') && !$adminsection) {
750 751 752
            $data = site_menu();
            if (!empty($data)) {
                $smarty->assign('SITEMENU', site_menu());
753
                $sideblocks[] = array(
754
                    'name'   => 'linksandresources',
755 756 757 758 759 760
                    'weight' => 10,
                    'data'   => $data,
                );
            }
        }

761 762
        if ($USER->is_logged_in() && defined('MENUITEM') &&
            (substr(MENUITEM, 0, 11) == 'myportfolio' || substr(MENUITEM, 0, 7) == 'content')) {
763
            if (get_config('showselfsearchsideblock')) {
764
                $sideblocks[] = array(
765 766 767 768 769 770
                    'name'   => 'selfsearch',
                    'weight' => 0,
                    'data'   => array(),
                );
            }
            if (get_config('showtagssideblock')) {
771
                $sideblocks[] = array(
772 773 774 775 776 777
                    'name'   => 'tags',
                    'id'     => 'sb-tags',
                    'weight' => 0,
                    'data'   => tags_sideblock(),
                );
            }
Clare Lenihan's avatar
Clare Lenihan committed
778
        }
Clare Lenihan's avatar
Clare Lenihan committed
779

780
        if ($USER->is_logged_in() && !$adminsection) {
781
            $sideblocks[] = array(
782
                'name'   => 'profile',
783
                'id'     => 'sb-profile',
784
                'class' => 'user-panel',
785 786 787
                'weight' => -20,
                'data'   => profile_sideblock()
            );
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
            $showusers = 2;
            $institutions = $USER->institutions;
            if (!empty($institutions)) {
                $showusers = 0;
                foreach ($institutions as $i) {
                    if ($i->showonlineusers == 2) {
                        $showusers = 2;
                        break;
                    }
                    if ($i->showonlineusers == 1) {
                        $showusers = 1;
                    }
                }
            }
            if (get_config('showonlineuserssideblock') && $showusers > 0) {
803
                $sideblocks[] = array(
804
                    'name'   => 'onlineusers',
805
                    'id'     => 'sb-onlineusers',
806 807 808 809
                    'weight' => -10,
                    'data'   => onlineusers_sideblock(),
                );
            }
810
            if (get_config('showprogressbar') && $USER->get_account_preference('showprogressbar')) {
811
                $sideblocks[] = array(
812 813
                    'name'   => 'progressbar',
                    'id'     => 'sb-progressbar',
814
                    'class'  => 'progressbar',
815
                    'weight' => -8,
816 817 818 819 820 821
                    'data'   => progressbar_sideblock(),
                );
            }
        }

        if ($USER->is_logged_in() && $adminsection && defined('SECTION_PAGE') && SECTION_PAGE == 'progressbar') {
822
            $sideblocks[] = array(
823 824
                'name'   => 'progressbar',
                'id'     => 'sb-progressbar',
825
                'class'  => 'progressbar',
826
                'weight' => -8,
827 828
                'data'   => progressbar_sideblock(true),
            );
829
        }
Martyn Smith's avatar
Martyn Smith committed
830

831
        $isloginblockvisible = !$USER->is_logged_in() && !get_config('siteclosedforupgrade')
832 833
                && get_config('showloginsideblock');
        if ($isloginblockvisible) {
834
            $sideblocks[] = array(
835 836
                'name'   => 'login',
                'weight' => -10,
837
                'id'     => 'sb-loginbox',
838 839 840
                'data'   => array(
                    'loginform' => auth_generate_login_form(),
                ),
841 842
            );
        }
843
        $smarty->assign('SHOWLOGINBLOCK', $isloginblockvisible);
844

845 846 847
        if (get_config('enablenetworking')) {
            require_once(get_config('docroot') .'api/xmlrpc/lib.php');
            if ($USER->is_logged_in() && $ssopeers = get_service_providers($USER->authinstance)) {
848
                $sideblocks[] = array(
849 850 851 852 853
                    'name'   => 'ssopeers',
                    'weight' => 1,
                    'data'   => $ssopeers,
                );
            }
Martyn Smith's avatar
Martyn Smith committed
854 855
        }

856 857
        if (isset($extraconfig['sideblocks']) && is_array($extraconfig['sideblocks'])) {
            foreach ($extraconfig['sideblocks'] as $sideblock) {
858
                $sideblocks[] = $sideblock;
859 860
            }
        }
Martyn Smith's avatar
Martyn Smith committed
861