<?php

$default_template = get_config('W3CMobileAuthoringToolLibrary', 'default_theme');
$mobile_template = get_config('W3CMobileAuthoringToolLibrary', 'mobile_theme');

if($switch!='0' && !isset($need_switch)){
	
	if(!class_exists('Transcoder', false)){
		require_once(dirname(__FILE__) . '/common/transcoding/transcoder.php');
	}
	if(!class_exists('Servicefactory')){
		require_once(dirname(__FILE__) . '/common/ddrsimpleapi/interface/serviceFactory.php');
	}
	
	$implementation_name = get_config('W3CMobileAuthoringToolLibrary', 'ddrsimpleapi_implementation');
	$configuration = array();
	if($implementation_name == 'WURFL'){
		$path = get_config('W3CMobileAuthoringToolLibrary', 'wurfl_path');
		$lastChar = substr($path, strlen($path) -1);
		if($lastChar != '/' && $lastChar != '\\'){
			$path .= '/';
		}
		if(!file_exists($path)){
			throw new Exception("The given path of the wurfl files doesn't exists.");
			exit(1);
		}
		$configuration['wurfl_path'] = $path;
	}
	if(!isset($service)){
		$service = ServiceFactory::newService($implementation_name,
			'http://www.w3.org/2008/01/ddr-core-vocabulary',
			$configuration);
	}
	if(!isset($evidence)){
		$evidence = $service->newHTTPEvidenceM($_SERVER);
	}
	
	$transcoder = new Transcoder($service);
	$trans = $transcoder->newTranscodingAction('SwitchTemplate');
	$trans->setOption('default', $default_template);
	$trans->setOption('mobile', $mobile_template);
	$transcoder->addTranscodingAction($trans);
	$newTemplate = $transcoder->apply($default_template, $evidence);
	
	$mobile = ($newTemplate == $mobile_template);
	
	$need_switch = $newTemplate!='mobile_friendly';
}

/*
 * Functions
 */


if(!function_exists('my_setup_theme')){
function my_setup_theme($theme = '', $params=NULL){
	global $CFG;
	
	if (empty($theme)) {
        $theme = current_theme();
    }
//echo $CFG->themedir;
/// If the theme doesn't exist for some reason then revert to standardwhite
    if (!file_exists($CFG->themedir .'/'. $theme .'/config.php')) {
        $CFG->theme = $theme = 'standardwhite';
    }

/// Load up the theme config
    $THEME = NULL;   // Just to be sure
    include($CFG->themedir .'/'. $theme .'/config.php');  // Main config for current theme

/// Put together the parameters
    if (!$params) {
        $params = array();
    }

    if ($theme != $CFG->theme) {
        $params[] = 'forceconfig='.$theme;
    }

/// Force language too if required
    if (!empty($THEME->langsheets)) {
        $params[] = 'lang='.current_language();
    }


/// Convert params to string
    if ($params) {
        $paramstring = '?'.implode('&', $params);
    } else {
        $paramstring = '';
    }

/// Set up image paths
    if(isset($CFG->smartpix) && $CFG->smartpix==1) {
        if($CFG->slasharguments) {        // Use this method if possible for better caching
            $extra='';
        } else {
            $extra='?file=';
        }

        $CFG->pixpath = $CFG->wwwroot. '/pix/smartpix.php'.$extra.'/'.$theme;
        $CFG->modpixpath = $CFG->wwwroot .'/pix/smartpix.php'.$extra.'/'.$theme.'/mod';
    } else if (empty($THEME->custompix)) {    // Could be set in the above file
        $CFG->pixpath = $CFG->wwwroot .'/pix';
        $CFG->modpixpath = $CFG->wwwroot .'/mod';
    } else {
        $CFG->pixpath = $CFG->themewww .'/'. $theme .'/pix';
        $CFG->modpixpath = $CFG->themewww .'/'. $theme .'/pix/mod';
    }

/// Header and footer paths
	
    $CFG->header = $CFG->themedir .'/'. $theme .'/header.html';
    $CFG->footer = $CFG->themedir .'/'. $theme .'/footer.html';

/// Define stylesheet loading order
    $CFG->stylesheets = array();
    if ($theme != 'standard') {    /// The standard sheet is always loaded first
        $CFG->stylesheets[] = $CFG->themewww.'/standard/styles.php'.$paramstring;
    }
    if (!empty($THEME->parent)) {  /// Parent stylesheets are loaded next
        $CFG->stylesheets[] = $CFG->themewww.'/'.$THEME->parent.'/styles.php'.$paramstring;
    }
    $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/styles.php'.$paramstring;

/// We have to change some URLs in styles if we are in a $HTTPSPAGEREQUIRED page
    if (!empty($HTTPSPAGEREQUIRED)) {
        $CFG->themewww = str_replace('http:', 'https:', $CFG->themewww);
        $CFG->pixpath = str_replace('http:', 'https:', $CFG->pixpath);
        $CFG->modpixpath = str_replace('http:', 'https:', $CFG->modpixpath);
        foreach ($CFG->stylesheets as $key => $stylesheet) {
            $CFG->stylesheets[$key] = str_replace('http:', 'https:', $stylesheet);
        }
    }

// RTL support - only for RTL languages, add RTL CSS
    if (get_string('thisdirection') == 'rtl') {
        $CFG->stylesheets[] = $CFG->themewww.'/standard/rtl.css'.$paramstring;
        $CFG->stylesheets[] = $CFG->themewww.'/'.$theme.'/rtl.css'.$paramstring;
    }
}
}

if(!function_exists('my_print_header')){
function my_print_header ($title='', $heading='', $navigation='', $focus='',
                       $meta='', $cache=true, $button='&nbsp;', $menu='',
                       $usexml=false, $bodytags='', $return=false) {

    global $USER, $CFG, $THEME, $SESSION, $ME, $SITE, $COURSE;


    $heading = format_string($heading); // Fix for MDL-8582
   


/// Add the required stylesheets
    $stylesheetshtml = '';
    foreach ($CFG->stylesheets as $stylesheet) {
        $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
    }
    $meta = $stylesheetshtml.$meta;


/// Add the meta page from the themes if any were requested

    $metapage = '';

    if (!isset($THEME->standardmetainclude) || $THEME->standardmetainclude) {
        ob_start();
        include_once($CFG->dirroot.'/theme/standard/meta.php');
        $metapage .= ob_get_contents();
        ob_end_clean();
    }

    if ($THEME->parent && (!isset($THEME->parentmetainclude) || $THEME->parentmetainclude)) {
        if (file_exists($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php')) {
            ob_start();
            include_once($CFG->dirroot.'/theme/'.$THEME->parent.'/meta.php');
            $metapage .= ob_get_contents();
            ob_end_clean();
        }
    }

    if (!isset($THEME->metainclude) || $THEME->metainclude) {
        if (file_exists($CFG->dirroot.'/theme/'.current_theme().'/meta.php')) {
            ob_start();
            include_once($CFG->dirroot.'/theme/'.current_theme().'/meta.php');
            $metapage .= ob_get_contents();
            ob_end_clean();
        }
    }

    $meta = $meta."\n".$metapage;

    $meta .= "\n".require_js('',1);

/// Set up some navigation variables

    if (is_newnav($navigation)){
        $home = false;
    } else {
        if ($navigation == 'home') {
            $home = true;
            $navigation = '';
        } else {
            $home = false;
        }
    }
//var_dump($home);echo '<br />';var_dump($heading);echo '<br />';var_dump($navigation);
/// This is another ugly hack to make navigation elements available to print_footer later
    $THEME->title      = $title;
    $THEME->heading    = $heading;
    $THEME->navigation = $navigation;
    $THEME->button     = $button;
    $THEME->menu       = $menu;
    $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';

    if ($button == '') {
        $button = '&nbsp;';
    }

    if (file_exists($CFG->dataroot.'/'.SITEID.'/maintenance.html')) {
        $button = '<a href="'.$CFG->wwwroot.'/'.$CFG->admin.'/maintenance.php">'.get_string('maintenancemode', 'admin').'</a> '.$button;
        if(!empty($title)) {
            $title .= ' - ';
        }
        $title .= get_string('maintenancemode', 'admin');
    }

    if (!$menu and $navigation) {
        if (empty($CFG->loginhttps)) {
            $wwwroot = $CFG->wwwroot;
        } else {

            $wwwroot = str_replace('http:','https:',$CFG->wwwroot);
        }
        $menu = user_login_string($COURSE);
    }

    if (isset($SESSION->justloggedin)) {
        unset($SESSION->justloggedin);
        if (!empty($CFG->displayloginfailures)) {
            if (!empty($USER->username) and $USER->username != 'guest') {
                if ($count = count_login_failures($CFG->displayloginfailures, $USER->username, $USER->lastlogin)) {
                    $menu .= '&nbsp;<font size="1">';
                    if (empty($count->accounts)) {
                        $menu .= get_string('failedloginattempts', '', $count);
                    } else {
                        $menu .= get_string('failedloginattemptsall', '', $count);
                    }
                    if (has_capability('coursereport/log:view', get_context_instance(CONTEXT_SYSTEM))) {
                        $menu .= ' (<a href="'.$CFG->wwwroot.'/course/report/log/index.php'.
                                             '?chooselog=1&amp;id=1&amp;modid=site_errors">'.get_string('logs').'</a>)';
                    }
                    $menu .= '</font>';
                }
            }
        }
    }


    $meta = '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' .
            "\n" . $meta . "\n";
    if (!$usexml) {
        @header('Content-Type: text/html; charset=utf-8');
    }
    @header('Content-Script-Type: text/javascript');
    @header('Content-Style-Type: text/css');

    //Accessibility: added the 'lang' attribute to $direction, used in theme <html> tag.
    $direction = get_html_lang($dir=true);

    if ($cache) {  // Allow caching on "back" (but not on normal clicks)
        @header('Cache-Control: private, pre-check=0, post-check=0, max-age=0');
        @header('Pragma: no-cache');
        @header('Expires: ');
    } else {       // Do everything we can to always prevent clients and proxies caching
        @header('Cache-Control: no-store, no-cache, must-revalidate');
        @header('Cache-Control: post-check=0, pre-check=0', false);
        @header('Pragma: no-cache');
        @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
        @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');

        $meta .= "\n<meta http-equiv=\"pragma\" content=\"no-cache\" />";
        $meta .= "\n<meta http-equiv=\"expires\" content=\"0\" />";
    }
    @header('Accept-Ranges: none');

    $currentlanguage = current_language();

    if (empty($usexml)) {
        $direction =  ' xmlns="http://www.w3.org/1999/xhtml"'. $direction;  // See debug_header
    } else {
        $mathplayer = preg_match("/MathPlayer/i", $_SERVER['HTTP_USER_AGENT']);
        if(!$mathplayer) {
            header('Content-Type: application/xhtml+xml');
        }
        echo '<?xml version="1.0" ?>'."\n";
        if (!empty($CFG->xml_stylesheets)) {
            $stylesheets = explode(';', $CFG->xml_stylesheets);
            foreach ($stylesheets as $stylesheet) {
                echo '<?xml-stylesheet type="text/xsl" href="'. $CFG->wwwroot .'/'. $stylesheet .'" ?>' . "\n";
            }
        }
        echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1';
        if (!empty($CFG->xml_doctype_extra)) {
            echo ' plus '. $CFG->xml_doctype_extra;
        }
        echo '//' . strtoupper($currentlanguage) . '" "'. $CFG->xml_dtd .'">'."\n";
        $direction = " xmlns=\"http://www.w3.org/1999/xhtml\"
                       xmlns:math=\"http://www.w3.org/1998/Math/MathML\"
                       xmlns:xlink=\"http://www.w3.org/1999/xlink\"
                       $direction";
        if($mathplayer) {
            $meta .= '<object id="mathplayer" classid="clsid:32F66A20-7614-11D4-BD11-00104BD3F987">' . "\n";
            $meta .= '<!--comment required to prevent this becoming an empty tag-->'."\n";
            $meta .= '</object>'."\n";
            $meta .= '<?import namespace="math" implementation="#mathplayer" ?>' . "\n";
        }
    }

    // Clean up the title

    $title = format_string($title);    // fix for MDL-8582
    $title = str_replace('"', '&quot;', $title);

    // Create class and id for this page

    page_id_and_class($pageid, $pageclass);

    $pageclass .= ' course-'.$COURSE->id;

    if (!isloggedin()) {
        $pageclass .= ' notloggedin';
    }

    if (!empty($USER->editing)) {
        $pageclass .= ' editing';
    }

    if (!empty($CFG->blocksdrag)) {
        $pageclass .= ' drag';
    }

    $pageclass .= ' dir-'.get_string('thisdirection');

    $pageclass .= ' lang-'.$currentlanguage;

    $bodytags .= ' class="'.$pageclass.'" id="'.$pageid.'"';
//var_dump($CFG);
    ob_start();
    include($CFG->header);
    $output = ob_get_contents();
    ob_end_clean();
//echo 'here';
    // container debugging info
    $THEME->open_header_containers = open_containers();

    // Skip to main content, see skip_main_destination().
    if ($pageid=='course-view' or $pageid=='site-index' or $pageid=='course-index') {
        $skiplink = '<a class="skip" href="#maincontent">'.get_string('tocontent', 'access').'</a>';
        if (! preg_match('/(.*<div[^>]+id="page"[^>]*>)(.*)/s', $output, $matches)) {
            preg_match('/(.*<body.*?>)(.*)/s', $output, $matches);
        }
        $output = $matches[1]."\n". $skiplink .$matches[2];
    }

    $output = force_strict_header($output);

    if (!empty($CFG->messaging)) {
        $output .= message_popup_window();
    }

    // Add in any extra JavaScript libraries that occurred during the header
    $output .= require_js('', 2);

    if ($return) {
        return $output;
    } else {
        echo $output;
    }
}
}

if(!function_exists('my_print_footer')){
function my_print_footer($course=NULL, $usercourse=NULL, $return=false) {
    global $USER, $CFG, $THEME, $COURSE;

/// Course links or special footer
    if ($course) {
        if ($course === 'empty') {
            // special hack - sometimes we do not want even the docs link in footer
            $output = '';
            if (!empty($THEME->open_header_containers)) {
                for ($i=0; $i<$THEME->open_header_containers; $i++) {
                    $output .= print_container_end_all(); // containers opened from header
                }
            } else {
                //1.8 theme compatibility
                $output .= "\n</div>"; // content div
            }
            $output .= "\n</div>\n</body>\n</html>"; // close page div started in header
            if ($return) {
                return $output;
            } else {
                echo $output;
                return;
            }

        } else if ($course === 'none') {          // Don't print any links etc
            $homelink = '';
            $loggedinas = '';
            $home  = false;

        } else if ($course === 'home') {   // special case for site home page - please do not remove
            $course = get_site();
            $homelink  = '<div class="sitelink">'.
               '<a title="Moodle '. $CFG->release .'" href="http://moodle.org/">'.
               '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
            $home  = true;

        } else {
            $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.
                        '/course/view.php?id='.$course->id.'">'.format_string($course->shortname).'</a></div>';
            $home  = false;
        }

    } else {
        $course = get_site();  // Set course as site course by default
        $homelink = '<div class="homelink"><a '.$CFG->frametarget.' href="'.$CFG->wwwroot.'/">'.get_string('home').'</a></div>';
        $home  = false;
    }

/// Set up some other navigation links (passed from print_header by ugly hack)
    $menu        = isset($THEME->menu) ? str_replace('navmenu', 'navmenufooter', $THEME->menu) : '';
    $title       = isset($THEME->title) ? $THEME->title : '';
    $button      = isset($THEME->button) ? $THEME->button : '';
    $heading     = isset($THEME->heading) ? $THEME->heading : '';
    $navigation  = isset($THEME->navigation) ? $THEME->navigation : '';
    $navmenulist = isset($THEME->navmenulist) ? $THEME->navmenulist : '';


/// Set the user link if necessary
    if (!$usercourse and is_object($course)) {
        $usercourse = $course;
    }

    if (!isset($loggedinas)) {
        $loggedinas = user_login_string($usercourse, $USER);
    }

    if ($loggedinas == $menu) {
        $menu = '';
    }

/// there should be exactly the same number of open containers as after the header
    if ($THEME->open_header_containers != open_containers()) {
        debugging('Unexpected number of open containers: '.open_containers().', expecting '.$THEME->open_header_containers, DEBUG_DEVELOPER);
    }

/// Provide some performance info if required
    $performanceinfo = '';
    if (defined('MDL_PERF') || (!empty($CFG->perfdebug) and $CFG->perfdebug > 7)) {
        $perf = get_performance_info();
        if (defined('MDL_PERFTOLOG') && !function_exists('register_shutdown_function')) {
            error_log("PERF: " . $perf['txt']);
        }
        if (defined('MDL_PERFTOFOOT') || debugging() || $CFG->perfdebug > 7) {
            $performanceinfo = $perf['html'];
        }
    }

/// Include the actual footer file

    ob_start();
    include($CFG->footer);
    $output = ob_get_contents();
    ob_end_clean();

    if ($return) {
        return $output;
    } else {
        echo $output;
    }
}
}

?>