<?php
/**
* Student main page
*
* This page performs all student functions
* @package eFront
* @version 1.0
*/
$debug_TimeStart = microtime(true);     //Debugging timer - initialization

session_cache_limiter('none');          //Initialize session
session_start();

$path = "../libraries/";                //Define default path

/** The configuration file.*/
require_once $path."configuration.php";
$debug_InitTime = microtime(true) - $debug_TimeStart;       //Debugging timer - time spent on file inclusion
//error_reporting(E_ALL);
//Set headers in order to eliminate browser cache (especially IE's)

header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Date in the past

//If the page is shown as a popup, make sure it remains in such mode
if (isset($_GET['popup']) || isset($_POST['popup']) || strpos(strtolower($_SERVER['HTTP_REFERER']), 'popup') !== false) {
    output_add_rewrite_var('popup', 1);
    $smarty -> assign("T_POPUP_MODE", true);
    $popup = 1;
}
//pr($_SESSION);

$message = '';$message_type = '';                            //Initialize messages, because if register_globals is turned on, some messages will be displayed twice
$loadScripts = array('EfrontScripts', 'scriptaculous/prototype');
//pr($_SESSION);exit;
/*Check the user type. If the user is not valid or not an administrator, he cannot access this page, so exit*/
if (isset($_SESSION['s_login']) && $_SESSION['s_password']) {
    try {
        $currentUser = EfrontUserFactory :: factory($_SESSION['s_login'], false, 'student');
/*
        if ($currentUser -> user['user_type'] != 'student') {
            header("location:index.php?message=".urlencode(_YOUCANNOTACCESSTHISPAGE)."&message_type=failure");
            exit;
        }
*/
    } catch (EfrontException $e) {
        $message = $e -> getMessage().' ('.$e -> getCode().')';
        header("location:index.php?message=".urlencode($message)."&message_type=failure");
        exit;
    }
} else {
    header("location:index.php?message=".urlencode(_YOUCANNOTACCESSTHISPAGE)."&message_type=failure");
    exit;
}

/*This is the first time the professor enters this lesson, so register the lesson id to the session*/
if (isset($_GET['lessons_ID']) && eF_checkParameter($_GET['lessons_ID'], 'id') && (!isset($_SESSION['s_lessons_ID']) || $_GET['lessons_ID'] != $_SESSION['s_lessons_ID'])) {
    $userLessons = $currentUser -> getLessons();
    if (in_array($_GET['lessons_ID'], array_keys($userLessons))) {
        $_SESSION['s_lessons_ID'] = $_GET['lessons_ID'];
        $_SESSION['s_type']       = $userLessons[$_GET['lessons_ID']];

        $smarty -> assign("T_CHANGE_LESSON", "true");
        $smarty -> assign("T_REFRESH_SIDE", "true");
        //eF_setLessonParameters();    //@todo remove
        //eF_setRoleParameters();      //@todo remove
    } else {
        unset($_GET['lessons_ID']);
        $message      = _YOUCANNOTACCESSTHISLESSONORITDOESNOTEXIST;
        $message_type = 'failure';
        $ctg          = 'personal';
    }
}

if (isset($_SESSION['s_lessons_ID']) && $_SESSION['s_lessons_ID'] && in_array($_SESSION['s_lessons_ID'], array_keys($currentUser -> getLessons()))) {    //Check validity of current lesson
    try {
        $currentLesson  = new EfrontLesson($_SESSION['s_lessons_ID']);                //Initialize lesson
        $smarty -> assign("T_TITLE_BAR", $currentLesson -> lesson['name']);
    } catch (Exception $e) {
        unset($_SESSION['s_lessons_ID']);
        $message = $e -> getMessage().' ('.$e -> getCode().')';
        header("location:".$_SERVER['PHP_SELF']."?message=".urlencode($message)."&message_type=failure");    //redirect to user lessons page
    }
    try {
        $currentContent = new EfrontContentTree($_SESSION['s_lessons_ID']);           //Initialize content
        $currentContent -> markSeenNodes($currentUser);
        $currentUser    -> applyRoleOptions($_SESSION['s_lessons_ID']);                //Initialize user's role options for this lesson        
    } catch (Exception $e) {
        $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
        $message = _ERRORLOADINGCONTENT.": ".$_SESSION['s_lessons_ID'].": ".$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
    }
}

/*Check current unit*/
if (isset($_GET['view_unit']) && eF_checkParameter($_GET['view_unit'], 'id')) {
    try {
        $currentUnit  = $currentContent -> seekNode($_GET['view_unit']);              //Initialize current unit
        $log_comments = $_GET['view_unit'];                                           //Value to insert to logs
        $currentUnit['ctg_type'] == 'tests' ? $_GET['ctg'] = 'tests' : $_GET['ctg'] = 'content';
    } catch (Exception $e) {
        unset($_GET['view_unit']);
        $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
        $message = _ERRORLOADINGCONTENT.": ".$_SESSION['s_lessons_ID'].": ".$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
    }
}

// Share the hcd value with smarty
$module_hcd_interface = MODULE_HCD_INTERFACE;
$smarty -> assign("T_MODULE_HCD_INTERFACE", $module_hcd_interface);

///MODULE1: Import
$loadedModules = $currentUser -> getModules();

$module_css_array = array();
$module_js_array = array();

// Include module languages
foreach ($loadedModules as $module) {
    // The $setLanguage variable is defined in globals.php
    $mod_lang_file = $module -> getLanguageFile($setLanguage);
    if (is_file ($mod_lang_file)) {
        require_once $mod_lang_file;
    }

    // Get module css
    if($mod_css_file = $module -> getModuleCSS()) {
        if (is_file ($mod_css_file)) {

            // Get the relative path
            if ($position = strpos($mod_css_file, "modules")) {
                $mod_css_file = substr($mod_css_file, $position);
            }
            $module_css_array[] = $mod_css_file;
        }
    }

    // Get module js
    if($mod_js_file = $module -> getModuleJS()) {
        if (is_file($mod_js_file)) {
            // Get the relative path
            if ($position = strpos($mod_js_file, "modules")) {
                $mod_js_file = substr($mod_js_file, $position);
            }

            $module_js_array[] = $mod_js_file;
        }
    }
}

if (isset($_GET['ajax']) && isset($_GET['bookmarks'])) {
    if ($_GET['bookmarks'] == 'remove' && isset($_GET['id']) && eF_checkParameter($_GET['id'], 'id')) {
        eF_deleteTableData("bookmarks", "id=".$_GET['id']." and users_LOGIN='".$_SESSION['s_login']."'");
    } elseif ($_GET['bookmarks'] == 'add' && isset($_GET['url']) && eF_checkParameter($_GET['url'], 'text')) {
        $fields = array('users_LOGIN'     => $currentUser -> user['login'],
                        'users_USER_TYPE' => $currentUser -> user['user_type'],
                        'name'            => $_GET['name'],
                        'url'             => $_GET['url']);
        if (eF_insertTableData("bookmarks", $fields)) {
            echo _SUCCESSFULLYINSERTEDBOOKMARK;
        } else {
            echo _ERRORINSERTINGBOOKMARK;
        }
        exit;
    }
    $result = eF_getTableData("bookmarks" ,"name, url, id", "users_LOGIN='".$_SESSION['s_login']."' AND name!=''", "id ASC");
    if (sizeof($result) == 0) {
        $bookmarksCode .= '<tr><td class = "emptyCategory centerAlign">'._NOBOOKMARKSFOUND.'</td></tr>';
    }
    foreach ($result as $bookmark) {
        $bookmarksCode .= '
                    <tr><td style = "text-align:left"><a href = "'.$bookmark['url'].'">'.$bookmark['name'].'</a></td>
                        <td style = "text-align:right"><a href = "javascript:void(0)" onclick = ""><img src = "images/16x16/delete.png" alt = "'._DELETEBOOKMARK.'" title = "'._DELETEBOOKMARK.'" border = "0" onclick = "removeBookmark('.$bookmark['id'].')"/></td></tr>';
    }
    echo '<table style = "width:100%">'.$bookmarksCode.'</table>';
    exit;
}
/*Added Session variable for search results*/
$_SESSION['referer'] = $_SERVER['REQUEST_URI'];

/*These are the possible ctg we can have. - The three last added by HCD */
$possible_ctgs = array('control_panel', 'content', 'scheduling', 'tests', 'rules', 'calendar', 'module',
                       'statistics', 'survey', 'glossary', 'settings', 'lessons', 'personal',
                       'projects', 'module_hcd', 'users','emails','evaluations', 'newtests');
if (sizeof($module_ctgs) > 0) {
    $possible_ctgs = array_merge($possible_ctgs, array_keys($module_ctgs));
}
!isset($_GET['ctg']) || !in_array($_GET['ctg'], $possible_ctgs)  ? $ctg = "control_panel" : $ctg = $_GET['ctg'];    //The default ctg is 'control_panel'

if (!$_SESSION['s_lessons_ID'] && $ctg != 'personal' && $ctg != 'statistics' && ($ctg == 'control_panel' && $_GET['op'] != "search")) {       //If there is not a lesson in the session, then the user just logged into the system. Redirect him to lessons page, except for the case he is viewing his personal information 2007/07/27 added search control. It was a problem when user had not choose a lesson.
    $ctg = 'lessons';
}

$smarty -> assign("T_CTG", $ctg);       //As soon as we derive the current ctg, assign it to smarty.
$smarty -> assign("T_OP", $_GET['op']);
$smarty -> assign("T_FCT", $_GET['fct']);

/*
Control panel is the first page that the student sees, and contains links to most of the available functions
At the control panel main page, you will find 8 sections:
- The content tree
- Lesson announcements
- Recent forum messages
- Recent personal messages
- Recent comments
- The calendar
- The digital library
- Any new content that was added recently
*/
if ($ctg == 'control_panel') {
    $loadScripts[] = 'scriptaculous/scriptaculous';
    $loadScripts[] = 'scriptaculous/effects';
    $loadScripts[] = 'scriptaculous/dragdrop';
    $loadScripts[] = 'drag-drop-folder-tree';
    
    /*Insert a record into the logs table, if a lesson has been selected*/
    if (isset($_SESSION['s_lessons_ID'])) {
        $fields_log = array ('users_LOGIN' => $_SESSION['s_login'],                                 //This is the log entry array
                             'timestamp'   => time(),
                             'action'      => 'lesson',
                             'comments'    => 0,
                             'session_ip'  => eF_encodeIP($_SERVER['REMOTE_ADDR']),
                             'lessons_ID'  => $_SESSION['s_lessons_ID']);
        eF_deleteTableData("logs", "users_LOGIN='".$_SESSION['s_login']."' AND action='lastmove'"); //Only one lastmove action interests us, so delete any other
        eF_insertTableData("logs", $fields_log);
    }

    /*Include the module that is used to perform the searches*/
    if (isset($_GET['op']) && $_GET['op'] == 'search') {
        /**Functions to perform searches*/
        require_once "module_search.php";
    }

    /*Show the announcements (news) full page*/
    elseif (isset($_GET['op']) && $_GET['op'] == 'news') {
        $news = eF_getTableData("news", "*", "lessons_ID=0 or lessons_ID=".$currentLesson -> lesson['id']);
        $smarty -> assign("T_NEWS", $news);
    }
    /*
    This part is used to display the information that the professor
    has created for this lesson. It is also used to display the lesson
    objectives, that need to be met so that it can be considered done
    */
    elseif (isset($_GET['op']) && $_GET['op'] == 'lesson_information') {
        $lesson_info_categories = array('general_description' => _GENERALDESCRIPTION,
                                        'objectives'          => _OBJECTIVES,
                                        'assessment'          => _ASSESSMENT,
                                        'lesson_topics'       => _LESSONTOPICS,
                                        'resources'           => _RESOURCES,
                                        'other_info'          => _OTHERINFO);

        $lessonInformation = $currentLesson -> getInformation($currentUser -> user['login']);

        $smarty -> assign("T_LESSON_INFO", $lessonInformation);
        $smarty -> assign("T_LESSON_INFO_CATEGORIES", $lesson_info_categories);

        $userProgress = EfrontStats :: getStudentsLessonStatus($currentLesson, $currentUser -> user['login']);
        $smarty -> assign("T_USER_PROGRESS", $userProgress);
        $seenContent = EfrontStats :: getStudentsSeenContent($currentLesson -> lesson['id'], $currentUser -> user['login']);

        $conditions       = $currentLesson -> getConditions();
        foreach ($iterator = new EfrontVisitableFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST))) as $key => $value) {
            $visitableContentIds[$key] = $key;                                                    //Get the not-test unit ids for this content
        }
        foreach ($iterator = new EfrontTestsFilterIterator(new EfrontVisitableFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST)))) as $key => $value) {
            $testsIds[$key] = $key;                                                    //Get the not-test unit ids for this content
        }

        $conditionsStatus = EfrontStats :: checkConditions($seenContent[$currentLesson -> lesson['id']][$currentUser -> user['login']], $conditions, $visitableContentIds, $testsIds);
        $smarty -> assign("T_CONDITIONS", $conditions);
        $smarty -> assign("T_CONDITIONS_STATUS", $conditionsStatus);

        foreach ($iterator = new EfrontAttributeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree)), array('id', 'name')) as $key => $value) {
            $key == 'id' ? $ids[] = $value : $names[] = $value;
        }
        $smarty -> assign("T_TREE_NAMES", array_combine($ids, $names));
    }
    /*
    Module inclusion. If there are any modules that need to be displayed as ops in the control panel, they are included here
    */
    else if (isset($_GET['op']) && in_array($_GET['op'], array_keys($module_ctgs))) {
        $module_mandatory = eF_getTableData("modules", "mandatory", "name = '".$_GET['op']."'");
        if ($module_mandatory[0]['mandatory'] != 'false' || ($GLOBALS['currentLesson'] -> options[$_GET['op']])) {
            include(G_MODULESPATH.$_GET['op'].'/module.php');
            $smarty -> assign("T_OP_MODULE", $module_ctgs[$_GET['op']]);
        }
    }
    elseif (isset($_GET['op']) && $_GET['op'] == 'digital_library') {

        $loadScripts[] = 'drag-drop-folder-tree';
        $loadScripts[] = 'scriptaculous/effects';
        $basedir    = $currentLesson -> getDirectory();
        try {
            $filesystem = new FileSystemTree($basedir);
            $iterator   = new EfrontFileOnlyFilterIterator(new EfrontNodeFilterIterator(new EfrontDBOnlyFilterIterator(new EfrontFileOnlyFilterIterator(new RecursiveIteratorIterator($filesystem -> tree, RecursiveIteratorIterator :: SELF_FIRST))), array('shared' => $currentLesson -> lesson['id'])));
            $filesystem -> handleAjaxActions($currentUser);

            $url        = $_SERVER['PHP_SELF'].'?ctg=control_panel&op=digital_library';
            $options    = array('share' => false, 'zip' => false, 'folders' => false, 'delete' => false, 'edit' => false, 'create_folder' => false, 'upload' => false);

            if (isset($_GET['ajax'])) {
                isset($_GET['limit']) && eF_checkParameter($_GET['limit'], 'uint') ? $limit = $_GET['limit'] : $limit = G_DEFAULT_TABLE_SIZE;

                if (isset($_GET['sort']) && eF_checkParameter($_GET['sort'], 'text')) {
                    $sort = $_GET['sort'];
                    isset($_GET['order']) && $_GET['order'] == 'desc' ? $order = 'desc' : $order = 'asc';
                } else {
                    $sort = 'login';
                }

                if (isset($_GET['limit']) && eF_checkParameter($_GET['limit'], 'int')) {
                    isset($_GET['offset']) && eF_checkParameter($_GET['offset'], 'int') ? $offset = $_GET['offset'] : $offset = 0;
                }
                isset($_GET['filter']) ? $filter = $_GET['filter'] : $filter = false;
                isset($_GET['other'])  ? $other  = $_GET['other']  : $other  = '';
                $ajaxOptions = array('sort' => $sort, 'order' => $order, 'limit' => $limit, 'offset' => $offset, 'filter' => $filter);
                echo $filesystem -> toHTML($url, $other, $ajaxOptions, $options, false, false, false, $iterator);
                exit;
            }
            $smarty -> assign("T_FILE_MANAGER", $filesystem -> toHTML($url, false, false, $options, false, false, false, $iterator));
        } catch (Exception $e) {
            $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
            $message      = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            $message_type = 'failure';
        }

    }
    else {
        /*
        !isset($_GET['only_unseen']) ? $only_unseen = false : $only_unseen = $_SESSION['s_login'];

        $periods = eF_getTableData("periods", "count(*)", "lessons_ID=".$_SESSION['s_lessons_ID']); //Get the lesson periods
        if ($periods[0]['count(*)'] == 0) {                                                         //Get the content tree, based on whether there are periods defined
            $tree             = eF_getContentTree($nouse, $_SESSION['s_lessons_ID'], $content_ID, false, true, false, false, false, $only_unseen);
            $existing_periods = "";
            $new_content = eF_getNewContent($_SESSION['s_login'], $_SESSION['s_lessons_ID'], 'content');        //Get any new content
        } else {
            $tree             = eF_getContentTree($nouse, $_SESSION['s_lessons_ID'], $content_ID, false, true, true, true, true, $only_unseen);
            $existing_periods = 1;
            $new_content = eF_getNewContent($_SESSION['s_login'], $_SESSION['s_lessons_ID'], 'content', true);  //Get any new content
        }

        $smarty -> assign("T_PERIODS", $existing_periods);          //Let smarty know whether there are periods or not
        $smarty -> assign("T_NEW_CONTENT", $new_content);           //Assign new content to smarty
        */

        $smarty  -> assign("T_CONTENT_TREE", $currentContent -> toHTML(false, false, array('truncateNames' => 40)));

        if (!$currentLesson -> options['tracking']) {
            $lessonOptions[] = array('text' => _LESSONINFORMATION, 'image' => '32x32/about.png', 'href' => $_SERVER['PHP_SELF'].'?ctg=control_panel&op=lesson_information', 'onClick' => "eF_js_showDivPopup('"._LESSONINFORMATION."', 2)", 'target' => 'POPUP_FRAME');
        } else {
            try {
                $userProgress = EfrontStats :: getStudentsLessonStatus($currentLesson, $currentUser -> user['login']);
                $userProgress = $userProgress[$currentUser -> user['login']];

                if ($userProgress['current_unit']) {                                    //If there exists a value within the 'current_unit' attribute, it means that the student was in the lesson before. Seek the first unit that he hasn't seen yet
                    $firstUnseenUnit = $currentContent -> getFirstNode();

                    //Get to the first unseen unit
                    while ($firstUnseenUnit && (in_array($firstUnseenUnit['id'], $userProgress['done_content']) || ($firstUnseenUnit['data'] == '' && $firstUnseenUnit['ctg_type'] != 'tests'))) {
                        $firstUnseenUnit = $currentContent -> getNextNode($firstUnseenUnit);
                    }
                    if (!$firstUnseenUnit) {
                        $lessonOptions[] = array('text' => _YOUHAVESEENALLCONTENT, 'image' => '32x32/checks.png',     'href' => 'user_lesson.php?user='.$currentUser -> user['login']."&lesson=".$currentLesson -> lesson['id'], 'onClick' => "eF_js_showDivPopup('"._USERPROGRESS."', new Array('700px', '400px'))", 'target' => "POPUP_FRAME");
                    } else {
                        $lessonOptions[] = array('text' => _RESUMELESSON,          'image' => '32x32/media_play.png', 'href' => $_SERVER['PHP_SELF'].'?ctg='.($firstUnseenUnit['ctg_type'] == 'tests' ? 'tests' : 'content').'&view_unit='.$firstUnseenUnit['id']);
                    }
                    $smarty -> assign("T_CURRENT_UNIT", $firstUnseenUnit);
                } else {
                    $firstUnit = $currentContent -> getFirstNode();
                    while ($firstUnit && $firstUnit['active'] == 0) {
                        $firstUnit = $currentContent -> getNextNode($firstUnit);
                    } 
                    
                    if ($firstUnit) {
                        $lessonOptions[] = array('text' => _STARTLESSON, 'image' => '32x32/media_play_green.png', 'href' => $_SERVER['PHP_SELF'].'?ctg=content&view_unit='.$firstUnit['id']);
                    }
                }

                if ($userProgress['lesson_passed']) {
                    if (!$userProgress['completed']) {
                        $lessonOptions[] = array('text' => _LESSONCONDITIONSCOMPLETED, 'image' => '32x32/check2.png', 'href' => $_SERVER['PHP_SELF'].'?ctg=control_panel&op=lesson_information&popup=1', 'onClick' => "eF_js_showDivPopup('"._LESSONINFORMATION."', 2)", 'target' => 'POPUP_FRAME');
                    }
                    if (!$userProgress['completed'] && $currentLesson -> options['auto_complete']) {
                        $avgScore = 100;
                        if (sizeof($userProgress['done_tests']) > 0) {
                            foreach ($userProgress['done_tests'] as $id => $score) {
                                $scores[] = 100 * $score;
                            }
                            $avgScore = formatScore(array_sum($scores) / sizeof($userProgress['done_tests']));
                        }
                        $currentUser -> completeLesson($currentLesson, $avgScore, _AUTOCOMPLETEDAT.': '.date("Y/m/d, H:i:s"));
                        
                        $userProgress['completed'] = 1;
                        $userProgress['score']     = 100;
                        $userProgress['comments']  = _AUTOCOMPLETEDAT.': '.date("Y/m/d, H:i:s");
                    }
                } else {
                    $lessonOptions[] = array('text' => _LESSONINFORMATION, 'image' => '32x32/about.png', 'href' => $_SERVER['PHP_SELF'].'?ctg=control_panel&op=lesson_information&popup=1', 'onClick' => "eF_js_showDivPopup('"._LESSONINFORMATION."', 2)", 'target' => 'POPUP_FRAME');
                }

                if ($userProgress['completed']) {
                    $smarty -> assign("T_LESSON_COMPLETED", $userProgress['completed']);
                    $lessonOptions[] = array('text' => _LESSONCOMPLETE, 'image' => '32x32/graduation_hat2.png', 'href' => $_SERVER['PHP_SELF'].'?ctg=control_panel&op=lesson_information&popup=1', 'onClick' => "eF_js_showDivPopup('"._LESSONINFORMATION."', 2)", 'target' => 'POPUP_FRAME');
                }

            } catch (Exception $e) {
                $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                $message = _ERRORLOADINGCONTENT.": ".$_SESSION['s_lessons_ID'].": ".$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            }
        }

///MODULE2: Create lesson control panel sidelinks and innertable
        foreach ($loadedModules as $module) {
            if (isset($currentLesson -> options[$module -> className])) {

                if ($centerLinkInfo = $module -> getLessonCenterLinkInfo()) {
                    $lessonOptions[] = array('text' => $centerLinkInfo['title'],  'image' => eF_getRelativeModuleImagePath($centerLinkInfo['image']), 'href' => $centerLinkInfo['link']);
                }

                $lessonInnertableHTML = $module -> getLessonModule();   //**HERE**
                $innertable_modules = array();
                // If the module has a lesson innertable
                if ($lessonInnertableHTML) {

                    // Get module html - two ways: pure HTML or PHP+smarty
                    // If no smarty file is defined then false will be returned
                    if ($module_smarty_file = $module -> getLessonSmartyTpl()) {
                        // Execute the php code -> The code has already been executed by above (**HERE**)
                        // Let smarty know to include the module smarty file
                        $innertable_modules[$module->className] = array('smarty_file' => $module_smarty_file);
                    } else {
                        // Present the pure HTML cod
                        $innertable_modules[$module->className] = array('html_code' => $lessonInnertableHTML);
                    }
                }
            }
        }

/*
        foreach ($loadedModules as $module) {
            if ($module['mandatory'] != 'false' || ($GLOBALS['currentLesson'] -> options[$module['name']])) {
                if ($module['position'] != 'left') {
                    $lessonOptions[] = array('text' => $module['title'], 'image' => "32x32/component_green.png", 'href' => $_SERVER['PHP_SELF']."?ctg=control_panel&op=".$module['name']);
                }
                if ($module['menu'] == 'inner_table') {
                    //Include the inner table code
                    include(G_MODULESPATH.$module['name'].'/module_innerTable.php');
                    $innertable_modules[] = $module['name'];
                }
            }
        }
*/
        $smarty -> assign("T_INNERTABLE_MODULES", $innertable_modules);

        $smarty -> assign("T_LESSON_OPTIONS", $lessonOptions);
        $smarty -> assign("T_LESSON_OPTIONS_SIZE", sizeof($lessonOptions));
        $smarty -> assign("T_LESSON_LINK","student.php?ctg=lessons");

        $elementPositions = eF_getTableData("users_to_lessons","positions","lessons_ID=".$_SESSION['s_lessons_ID']." AND users_LOGIN='".$_SESSION['s_login']."'");
        if (sizeof($elementPositions) > 0) {
            $elementPositions = unserialize($elementPositions[0]['positions']);     //Get the inner tables positions, stored by the user.
            $smarty -> assign("T_POSITIONS_FIRST", $elementPositions['first']);     //Assign element positions to smarty
            $smarty -> assign("T_POSITIONS_SECOND", $elementPositions['second']);
            $smarty -> assign("T_POSITIONS", array_merge($elementPositions['first'], $elementPositions['second']));
        } else {
            $smarty -> assign("T_POSITIONS", array());
        }

        /*Projects list*/
        //$allProjects = eF_getTableData("projects,users_to_projects","title,id,deadline,creator_LOGIN","lessons_ID=".$_SESSION['s_lessons_ID']." AND id=projects_ID AND users_LOGIN='".$_SESSION['s_login']."'");
        if ($currentLesson -> options['projects']) {
            $allProjects = $currentLesson -> getProjects(false, $currentUser -> user['login']);
            $smarty -> assign("T_ALL_PROJECTS", $allProjects);
            $projects_options = array(
                        array('text' => _GOTOPROJECTS, 'image' => "16x16/redo.png", 'href' => $_SERVER['PHP_SELF']."?ctg=projects")
                            );
            $smarty -> assign("T_PROJECTS_OPTIONS",$projects_options);
            $smarty -> assign("T_PROJECTS_LINK","student.php?ctg=projects");
        }
        /*Forum messages list*/
        $forum_messages   = eF_getForumMessages($_SESSION['s_lessons_ID'], 3);                              //Get any forum messages related to this lesson
        $forum_lessons_ID = eF_getTableData("f_forums", "id", "lessons_ID=".$_SESSION['s_lessons_ID']); //Get the forum category related to this lesson
        $smarty -> assign("T_FORUM_MESSAGES", $forum_messages);                                             //Assign forum messages and categoru information to smarty
        $smarty -> assign("T_FORUM_LESSONS_ID", $forum_lessons_ID[0]['id']);

        if ($forum_lessons_ID[0]['id']) {                                                                   //If there is a forum category associated to this lesson (and the user is eligible to use it), display corresponding links
            if ($_SESSION['s_role_options']['forum'] == 1) {
                $forum_options = array(
                        array('text' => _GOTOFORUM, 'image' => "16x16/redo.png", 'href' => "forum/forum_index.php?category=".$forum_lessons_ID[0]['id']),
                        array('text' => _SENDMESSAGEATFORUM, 'image' => "16x16/add2.png", 'href' => "forum/forum_add.php?type=topic&category=".$forum_lessons_ID[0]['id'], 'onClick' => "eF_js_showDivPopup('"._NEWMESSAGE."', new Array('650px', '450px'));", 'target' => 'POPUP_FRAME')
                        );
            } else {
                $forum_options = array(
                        array('text' => _GOTOFORUM, 'image' => "16x16/redo.png", 'href' => "forum/forum_index.php?category=".$forum_lessons_ID[0]['id']),
                        array('text' => _UNPRIVILEGEDATTEMPT, 'image' => "16x16/add2_gray.png", 'href' => "#")
                        );
            }
        } else {                                                                                            //If there isn't a forum caegory associated to this lesson, only display a link to forum
            $forum_options = array(
                    array('text' => _GOTOFORUM, 'image' => "16x16/redo.png", 'href' => "forum/forum_index.php")
                    );
        }
        $smarty -> assign("T_FORUM_OPTIONS", $forum_options);                                               //Assign forum options to smarty
        $smarty -> assign("T_FORUM_LINK", "forum/forum_index.php");

        /*Personal messages list*/
        $personal_messages = eF_getPersonalMessages(false, $p_messages_limit);                              //Get user personal messages
        $smarty -> assign("T_PERSONAL_MESSAGES", $personal_messages);                                       //Assign personal messages to smarty
        if ($_SESSION['s_role_options']['personal_messages'] == 1) {                                        //If the user is eligible to use personal messages, assign handles to the personal messages inner table
            $personal_message_options = array(
                        array('text' => _GOTOINBOX, 'image' => "16x16/redo.png", 'href' => "forum/messages_index.php"),
                        array('text' => _SENDMESSAGE, 'image' => "16x16/add2.png", 'href' => "forum/new_message.php", 'onClick' => "eF_js_showDivPopup('"._NEWMESSAGE."', new Array('650px', '450px'));", 'target' => 'POPUP_FRAME')
            );
        } else {
            $personal_message_options = array(                                                              //If the user is not eligible to use personal messages, display inactive handles to the personal messages inner table
                        array('text' => _GOTOINBOX, 'image' => "16x16/redo.png", 'href' => "forum/messages_index.php"),
                        array('text' => _SENDMESSAGE, 'image' => "16x16/add2_gray.png", 'href' => "#")
            );
        }
        $smarty -> assign("T_PERSONAL_MESSAGES_OPTIONS",$personal_message_options);                         //Assign personal messages options to smarty. to display with the inner table
        $smarty -> assign("T_PERSONAL_MESSAGES_LINK", "forum/messages_index.php");

        /*Lesson announcements list*/
        $announcements         = eF_getNews();                                                                  //Get lesson announcements
        $announcements_options = array(
                array('text' => _ANNOUNCEMENTGO,  'image' => "16x16/redo.png", 'href' => $_SERVER['PHP_SELF']."?ctg=control_panel&op=news")
                );
        $new_announcements = eF_getNewContent($_SESSION['s_login'], $_SESSION['s_lessons_ID'], 'news');     //Get any new announcements

        $smarty -> assign("T_NEWS", $announcements);                                                        //Assign announcements to smarty
        $smarty -> assign("T_NEWS_OPTIONS",$announcements_options);
        $smarty -> assign("T_NEW_NEWS", array_values($new_announcements));                                  //eF_getNewContent does not reindex results, so it returns arrays with arbitrary keys, causing problems in the template
        $smarty -> assign("T_NEWS_LINK", "student.php?ctg=control_panel&op=news");
        /*Comments list*/
        if ($GLOBALS['currentLesson'] -> options['comments'] == 1) {                                               //If the comments in lesson are enabled
            $comments = eF_getComments(false, false, false, 3);                                             //Retrieve 3 first comments
            $smarty -> assign("T_COMMENTS", $comments);                                                     //Assign to smarty
        }

        /*Digital library files list*/
/*
        if ($GLOBALS['currentLesson'] -> options['digital_library'] == 1) {                                        //If the lesson digital library is enabled
            $dir    = G_LESSONSPATH.$_SESSION['s_lessons_ID'].'/Digital Library/';                          //This is the digital library directory
            $count  = 0;
            $handle = opendir($dir);                                                                        //Open the directory
            while (false !== ($file = readdir($handle)) && $count++ < 10) {                                 //Get the 10 first files
                if (!is_dir($dir.$file)) {
                    $files_list[] = $file;                                                                  //Append files (not directories) to files list
                }
            }
            $smarty -> assign("T_FILES_LIST", $files_list);                                                 //Assign the files list to smarty
            $files_list_options = array(                                                                    //Assign a 'view all' handle to digital library inner table
                array('text' => _VIEWALL, 'image' => "16x16/redo.png", 'href' => "/editor/view_digital_library.php", 'onClick' => "eF_js_showDivPopup('"._DIGITALLIBRARY."', new Array('450px', '500px'))", 'target' => 'POPUP_FRAME')
            );
            $smarty -> assign("T_FILES_LIST_OPTIONS", $files_list_options);                                 //Assign digital library inner table options to smarty
            $smarty -> assign("T_FILES_LIST_LINK", "/editor/view_digital_library.php");
        }
*/
        if ($currentLesson -> options['digital_library']) {                                        //If the lesson digital library is enabled
            $filesystem = new FileSystemTree($currentLesson -> getDirectory());
            $iterator   = new EfrontNodeFilterIterator(new EfrontDBOnlyFilterIterator(new EfrontFileOnlyFilterIterator(new RecursiveIteratorIterator($filesystem -> tree, RecursiveIteratorIterator :: SELF_FIRST))), array('shared' => $currentLesson -> lesson['id']));
            $iterator  -> rewind();
            $count      = 0;
            while ($iterator -> valid() && $count++ < 10) {
                $sharedFiles[] = $iterator -> current();
                $iterator -> next();
            }

            $files_list_options = array(                                                                    //Assign a 'view all' handle to digital library inner table
                        array('text' => _VIEWALL, 'image' => "16x16/redo.png", 'href' => $_SERVER['PHP_SELF']."?ctg=control_panel&op=digital_library")
            );
            $smarty -> assign("T_FILES_LIST", $sharedFiles);                                                //Assign the files list to smarty
            $smarty -> assign("T_FILES_LIST_OPTIONS", $files_list_options);                                 //Assign digital library inner table options to smarty
        }

        $calendar_options = array(                                                                          //Create calendar options and assign them to smarty, to be displayed at the calendar inner table
                    array('text' => _GOTOCALENDAR, 'image' => "16x16/redo.png", 'href' => "student.php?ctg=calendar")
        );
        $smarty -> assign("T_CALENDAR_OPTIONS", $calendar_options);
        $smarty -> assign("T_CALENDAR_LINK", "student.php?ctg=calendar");

        $today = getdate(time());                                                                           //Get current time in an array
        $today = mktime(0, 0, 0, $today['mon'], $today['mday'], $today['year']);                            //Create a timestamp that is today, 00:00. this will be used in calendar for displaying today
        (eF_checkParameter($_GET['view_calendar'], 'timestamp')) ? $view_calendar = $_GET['view_calendar']: $view_calendar = $today;    //If a specific calendar date is not defined in the GET, set as the current day to be today

        $result = eF_getTableData("calendar","*","");
        foreach ($result as $event) {
            $events[$event['timestamp']]['data'][] = $event['data'];
            $events[$event['timestamp']]['id'][]   = $event['id'];
            $events[$event['timestamp']]['lesson'][]   = $event['name'];
        }

        $smarty -> assign("T_CALENDAR_EVENTS", $events);                                                    //Assign events and specific day timestamp to smarty, to be used from calendar
        $smarty -> assign("T_VIEW_CALENDAR", $view_calendar);
    }
}
/*
Projects is the page where the student views the projects that have been assigned to him/her.
*/
elseif ($ctg == 'projects') {
    try {
        $projects = $currentLesson -> getProjects(false, $currentUser -> user['login']);
    } catch (Exception $e) {
        $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
        $message      = _SOMEPROBLEMOCCURED.': '.$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
        $message_type = 'failure';
    }

    if (isset($_GET['view_project']) && eF_checkParameter($_GET['view_project'], 'id') && in_array($_GET['view_project'], array_keys($projects))) {
        try {
            $currentProject = new EfrontProject($_GET['view_project']);
            $projectUser    = $currentProject -> getUsers();
            $projectUser    = $projectUser[$currentUser -> user['login']];
            $currentProject -> project['deadline'] < time() ? $currentProject -> expired = true : $currentProject -> expired = false;

            if ($projectUser['filename']) {
                try {
                    $projectFile = new EfrontFile($projectUser['filename']);
                    $smarty -> assign("T_PROJECT_FILE", $projectFile);
                    if (isset($_GET['delete_file']) && !$currentProject -> expired) {
                        $projectFile -> delete();
                        eF_updateTableData("users_to_projects", array('filename' => '', 'upload_timestamp' => ''), "users_LOGIN='".$currentUser -> user['login']."' AND projects_ID=".$_GET['view_project']);
                        header("location:".$_SERVER['PHP_SELF']."?ctg=projects&view_project=".$_GET['view_project']."&message=".urlencode(_FILEDELETEDSUCCESSFULLY)."&message_type=success");
                    }
                } catch (EfrontFileException $e) {
                    $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                    $message      = _SOMEPROBLEMOCCURED.': '.$e -> getMessage().' &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                    $message_type = 'failure';
                }
            }

            $form        =  new HTML_QuickForm("upload_project_form", "post", $_SERVER['PHP_SELF'].'?ctg=projects&view_project='.$_GET['view_project'], "", null, true);
            $file        =& $form -> addElement('file', 'filename', _FILE);
            $maxFileSize =  FileSystemTree :: getUploadMaxSize();
            //$form        -> addRule('filename', _NOTGIVEFILENAME, 'uploadedfile');
            $form        -> addRule('filename', _THEFIELD.' '._ISMANDATORY, 'required', null, 'client');
            $form        -> setMaxFileSize($maxFileSize * 1024);
            $form        -> addElement('submit', 'submit_upload_project', _SENDPROJECT);

            $smarty -> assign("T_MAX_FILE_SIZE", $maxFileSize);
            if ($form -> isSubmitted() && $form -> validate() && !$currentProject -> expired) {
                try {
                    $projectDirectory = G_UPLOADPATH.$currentUser -> user['login'].'/projects';
                    if (!is_dir($projectDirectory)) {
                        //EfrontFileSystem :: makeDirectory('projects', G_UPLOADPATH.$currentUser -> user['login'].'/');
                        EfrontDirectory :: createDirectory($projectDirectory);
                    }
                    //$directory    = new EfrontDirectory($projectDirectory);
                    $filesystem = new FileSystemTree($projectDirectory);
                    $uploadedFile = $filesystem -> uploadFile('filename', $projectDirectory);
                    //$uploadedFile = EfrontFileSystem :: uploadFile('filename', $directory -> getFullPath());
                    $fields_update = array("filename"         => $uploadedFile['id'],
                                           "upload_timestamp" => time());
                    eF_updateTableData("users_to_projects", $fields_update, "users_LOGIN='".$currentUser -> user['login']."' AND projects_ID=".$_GET['view_project']);
                    header("location:".$_SERVER['PHP_SELF']."?ctg=projects&view_project=".$_GET['view_project']."&message=".urlencode(_FILEUPLOADED)."&message_type=success");
                } catch (EfrontFileException $e) {
                    $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                    $message      = _SOMEPROBLEMOCCURED.': '.$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
                    $message_type = 'failure';
                }
            } elseif ($currentProject -> expired) {
                $message      = _PROJECTEXPIRED;
                $message_type = 'failure';
            }

            $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);

            $form -> setJsWarnings(_BEFOREJAVASCRIPTERROR, _AFTERJAVASCRIPTERROR);
            $form -> setRequiredNote(_REQUIREDNOTE);
            $form -> accept($renderer);

            $smarty -> assign('T_UPLOAD_PROJECT_FORM', $renderer -> toArray());
            $smarty -> assign("T_PROJECT", $currentProject);
            $smarty -> assign("T_PROJECT_USER_INFO", $projectUser);

        } catch (Exception $e) {
            $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
            $message      = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            $message_type = 'failure';
        }
    } else {
        $currentProjects = array();
        $passedProjects  = array();

        foreach ($projects as &$project) {
            $remainTime                = eF_convertIntervalToTimeFull($project['deadline'] - time());
            $project['time_remaining'] = $remainTime['string'];
            $project['deadline'] > time() ? $currentProjects[] = $project : $passedProjects[] = $project;
        }
        unset($project);

        $smarty -> assign("T_CURRENT_PROJECTS", $currentProjects);
        $smarty -> assign("T_ACTIVE_COUNT", sizeof($currentProjects));

        $smarty -> assign("T_EXPIRED_PROJECTS", $passedProjects);
        $smarty -> assign("T_INACTIVE_COUNT", sizeof($passedProjects));
    }
}

/*
Content is the page where the student views the lesson content.
*/
elseif ($ctg == 'content') {
    $loadScripts[] = 'drag-drop-folder-tree';
    $loadScripts[] = 'ASCIIMathML';
    $loadScripts[] = 'scriptaculous/scriptaculous';
    $loadScripts[] = 'scriptaculous/effects';
    $loadScripts[] = 'scriptaculous/sidebar_extra';

    $smarty -> assign("T_LESSON_NAME", $currentLesson -> lesson['name']);

    if (!$currentUnit) {
/*
        $iterator = new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST), array('active' => 1));
        $iterator  -> rewind();
        $current    = $iterator -> current();
        $depth      = $iterator -> getDepth();
        $treeString = '';

        while ($iterator -> valid()) {
            $iterator -> next();

            //Get only units that have children of the designated type, i.e. "examples"
            $it = new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> getNodeChildren($current['id'])), RecursiveIteratorIterator :: SELF_FIRST), array('active' => 1, 'ctg_type' => $_GET['type']));
            $it -> next();
            if ($current['ctg_type'] == $_GET['type']) {    //Print units of the designated type
                $treeString .= '
                    <li class = "'.$current['ctg_type'].'" id = "node'.$current['id'].'" noDrag = "true" noRename = "true" noDelete = "true">
                        <a class = "treeLink" href = "'.$_SERVER['PHP_SELF'].'?view_unit='.$current['id'].'" title = "'.$current['name'].'">'.$current['name']."</a>";
            } elseif ($it -> valid()) {                    //Print parents of units of the designated type
                $treeString .= '
                    <li class = "'.$current['ctg_type'].'" id = "node'.$current['id'].'" noDrag = "true" noRename = "true" noDelete = "true">
                        <a class = "inactiveLink" href = "javascript:void(0)" title = "'.$current['name'].'">'.$current['name']."</a>";
            }

            $iterator -> getDepth() > $depth ? $treeString .= '<ul>' : $treeString .= '</li>';
            for ($i = $depth; $i > $iterator -> getDepth(); $i--) {
                $treeString .= '</ul></li>';
            }
            $current = $iterator -> current();
            $depth   = $iterator -> getDepth();
        }

        $str = '
            <script>
                function updateExpandCollapseLink(status) {
                    status ? $("expand_collapse_link").update("'._COLLAPSEALL.'") : $("expand_collapse_link").update("'._EXPANDALL.'");
                }
            </script>
            <div id = "expand_collapse_div" expand = "1">
                <b><a id = "expand_collapse_link" href = "javascript:void(0)" onclick = "treeObj.setTreeId(\'dhtml_specific_tree\');if (treeObj.status) {treeObj.collapseAll();this.innerHTML = \''._EXPANDALL.'\';} else {treeObj.expandAll();this.innerHTML = \''._COLLAPSEALL.'\';}">'._COLLAPSEALL.'</a></b><br/>
            </div>
            <ul id = "dhtml_specific_tree" class = "dhtmlgoodies_tree">
            '.$treeString.'
            </ul>
            ';
*/
        if ($_GET['type'] == 'tests') {
            $iterator = new EfrontTestsFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST), array('active' => 1)));
        } else if ($_GET['type'] == 'theory') {
            $iterator = new EfrontTheoryFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST), array('active' => 1)));
        }
        $smarty  -> assign("T_THEORY_TREE", $currentContent -> toHTML($iterator, 'dhtmlContentTree', array('truncateNames' => 25)));


    } else {

        if (!$currentUser -> roleOptions['read_content']) {                            //Check if the student is eligible to see the content
            $message      = _HAVENOPRIVILEDGESTOSEECONTENT;
            $message_type = "failure";
        } else {
            try {
                !isset($currentUnit) ? $currentUnit = $currentContent -> getFirstNode() : null;                                               //If a unit is not specified, then consider the first content unit by default
                $iterator = new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST), array('active' => 1));
                $smarty  -> assign("T_CONTENT_TREE", $currentContent -> toHTML($iterator, 'dhtmlContentTree', array('truncateNames' => 25, 'selectedNode' => $currentUnit['id'])));
                if ($currentUnit['ctg_type'] == 'scorm' || $currentUnit['ctg_type'] == 'scorm_test') {
                    $scorm_unit = true;
                    $smarty -> assign("T_SCORM", $scorm_unit);
                }
                if ($currentLesson -> options['glossary']) {
                    $currentUnit['data'] = eF_applyGlossary($currentUnit['data']);        //If glossary is activated, transform content data accordingly
                }
                $currentUnit['data'] = str_replace("##EFRONTINNERLINK##", $_SESSION['s_type'], $currentUnit['data']);    //Replace inner links. Inner links are created when linking from one unit to another, so they must point either to professor.php or student.php, depending on the user viewing the content

                $visitableIterator = new EfrontVisitableFilterIterator(new EfrontNodeFilterIterator(new RecursiveIteratorIterator(new RecursiveArrayIterator($currentContent -> tree), RecursiveIteratorIterator :: SELF_FIRST)));
                $smarty -> assign("T_UNIT",          $currentUnit);
                $smarty -> assign("T_NEXT_UNIT",     $currentContent -> getNextNode($currentUnit, $visitableIterator));
                $smarty -> assign("T_PREVIOUS_UNIT", $currentContent -> getPreviousNode($currentUnit, $visitableIterator));        //Next and previous units are needed for navigation buttons
                $smarty -> assign("T_PARENT_LIST",   $currentContent -> getNodeAncestors($currentUnit));       //Parents are needed for printing the titles

                $smarty -> assign("T_COMMENTS",      eF_getComments($_SESSION['s_lessons_ID'], false, $currentUnit['id']));        //Retrieve any comments regarding this unit
                $smarty -> assign("T_SHOW_TOOLS",    true);                                                    //Tools is the right upper corner table box, that lists tools such as 'upload files', 'copy content' etc

                if ($currentLesson -> options['tracking']) {
                    $userProgress = EfrontStats :: getStudentsLessonStatus($currentLesson, $currentUser -> user['login']);
                    $userProgress = $userProgress[$currentUser -> user['login']];
                    $smarty -> assign("T_SEEN_UNIT", in_array($currentUnit['id'], $userProgress['done_content']));    //Notify smarty whether the student has seen the current unit
                    $ruleCheck = $currentContent -> checkRules($currentUnit['id'], $userProgress);
                    if ($ruleCheck !== true) {
                         $message      = $ruleCheck;
                         $message_type = false;
                         $smarty -> assign("T_RULE_CHECK_FAILED", true);
                    }

                    $smarty -> assign("T_USER_PROGRESS", $userProgress);

                    if (isset($_GET['ajax'])) {
                        $currentUser -> setSeenUnit($currentUnit, $currentLesson, $_GET['set_seen']);
                        exit;
                    }

                }
            } catch (Exception $e) {
                $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                $message = _ERRORLOADINGCONTENT.": ".$_SESSION['s_lessons_ID'].": ".$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            }
        }
    }
}
/*
Tests page is responsible for displaying and performing tests
Th student sees a list of tests and may choose to take one.
The code below is responsible for displaying tests and corresponding questions.
How the tests work:
1. Create a form with all the question types
2. At the same time, if the user has already done this test, then assign the stored question answers to form defaults and FREEZE the form
3. Correct the test, no matter if the student has just submited the test, or he sees an old test. The only difference is that in the latter case, there will be no inserts to the database
*/
elseif ($ctg == 'tests') {
    $loadScripts[] = 'drag-drop-folder-tree';
    $loadScripts[] = 'ASCIIMathML';
    $loadScripts[] = 'scriptaculous/scriptaculous';
    $loadScripts[] = 'scriptaculous/sidebar_extra';

    if (isset($_GET['view_unit']) && eF_checkParameter($_GET['view_unit'], 'id') && $_SESSION['s_role_options']['read_content'] == 1 && (!($GLOBALS['currentLesson'] -> options['rules']) || ($rules_message = eF_checkRules($_GET['view_unit'])) === true)) {
        try {
            //Assign information on the side content tree, the navigation buttons etc
            $smarty -> assign("T_CONTENT_TREE",  $currentContent -> toHTML(false, 'dhtmlContentTree', array('truncateNames' => 25, 'selectedNode' => $currentUnit['id'])));
            $smarty -> assign("T_UNIT",          $currentUnit);
            $smarty -> assign("T_NEXT_UNIT",     $currentContent -> getNextNode($currentUnit, $iterator));
            $smarty -> assign("T_PREVIOUS_UNIT", $currentContent -> getPreviousNode($currentUnit, $iterator));        //Next and previous units are needed for navigation buttons
            $smarty -> assign("T_PARENT_LIST",   $currentContent -> getNodeAncestors($currentUnit));       //Parents are needed for printing the titles

            $test      = new EfrontTest($currentUnit['id'], true);
            $questions = $test -> getQuestions();
            try {
                $doneInfo = $test -> setDone($currentUser -> user['login']);
            } catch (EfrontTestException $e) {}
        } catch (Exception $e) {
            $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
            $message = _ERRORLOADINGCONTENT.": ".$_SESSION['s_lessons_ID'].": ".$e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
        }

        $test -> test['duration_converted'] = eF_convertIntervalToTime($test -> test['duration']);
        $test -> test['questions_num']      = sizeof($questions);
        $test -> test['times_done']         = $doneInfo['times'];

        if (isset($_GET['redo_test'])) {                                                                                //The user asked to redo the test
            if ($test -> test['redoable'] > $test -> test['times_done'] || $test -> test['redoable'] == 0) {            //If the times that the user has done this test is less than the times it may be redone, allow him to do it again
                $test -> reset($currentUser);
                header("location:".$_SERVER['PHP_SELF']."?ctg=tests&view_unit=".$_GET['view_unit']);
            } else {
                $message      = _CANNOTREDOTEST;
                $message_type = 'failure';
            }
        }

        $test_begun = eF_getTableData("logs", "timestamp", "users_LOGIN='".$_SESSION['s_login']."' AND action='test_begin' AND comments='".$test -> test['id']."'");      //Check if the user has begun the test some other time
        if (!isset($_GET['confirm']) && !isset($doneInfo['id']) && sizeof($_POST) == 0 && sizeof($test_begun) == 0) {          //If the user hasn't confirmed he wants to do the test, display confirmation buttons
            $smarty -> assign("T_SHOW_CONFIRMATION", true);
        } else {                                                                                     //The user confirmed he wants to do the test, so display it
            if (!isset($doneInfo['id'])) {                                                           //The user sees an undone test
                if (sizeof($test_begun) > 0) {                                                       //The student is re-entering a test
                    $timeStart     = $test_begun[0]['timestamp'];                                    //When did the student started the test
                    $remainingTime = $test -> test['duration'] - time() + $timeStart;                //The time remaining for the test to complete

                    $smarty -> assign("T_REMAINING_TIME", $remainingTime > 0 ? eF_convertIntervalToTime($remainingTime) : 1);
                } else {                                                                             //The student has just begun the test
                    $timeStart = time();
                    $logFields = array ('users_LOGIN' => $_SESSION['s_login'],                      //Insert a log entry that indicates the time the test started
                                         'timestamp'   => $timeStart,
                                         'action'      => "test_begin",
                                         'comments'    => $test -> test['id']);
                    eF_insertTableData("logs", $logFields);                                         //Insert a log entry, indicating the time that the user begun this test
                    $smarty -> assign("T_REMAINING_TIME", $test -> test['duration_converted']);
                }
            }


            //Build the tests form
            try {
                $form       = new HTML_QuickForm("test_form", "post", $_SERVER['PHP_SELF'].'?ctg=tests&view_unit='.$_GET['view_unit'], "", null, true);
                $testString = $test -> toHTMLQuickForm($form);
                $smarty -> assign("T_TEST", $testString);
                $form   -> addElement('hidden', 'time_start', $timeStart);                                       //This element holds the time the test started, so we know the remaining time even if the user left the system
                $form   -> addElement('submit', 'submit_test', _SUBMITTEST, 'class = "flatButton" onclick = "if (typeof(checkedQuestions) != \'undefined\' && (unfinished = checkQuestions())) return confirm(\''._YOUHAVENOTCOMPLETEDTHEFOLLOWINGQUESTIONS.': \'+unfinished+\'. '._AREYOUSUREYOUWANTTOSUBMITTEST.'\');"');


                if (isset($doneInfo['id'])) {
                    $doneInfo['duration_converted'] = eF_convertIntervalToTime($doneInfo['duration']);
                    $smarty -> assign("T_TEST", $test -> toHTMLQuickForm($form, false, true));

                    $smarty -> assign("T_DONE_TEST_DATA", $doneInfo);
                } elseif ($form -> isSubmitted() && $form -> validate()) {
                    $values          = $form -> exportValues();
                    $uploadDirectory = G_UPLOADPATH.$currentUser -> user['login'].'/tests/';
                    $uploadedFiles   = array();
                    if (!is_dir($uploadDirectory) && !mkdir($uploadDirectory, 0755)) {
                        $message      = _COULDNOTCREATETESTSDIRECTORY;
                        $message_type = 'failure';
                    } else {
                        $filesystem = new FileSystemTree($uploadDirectory);
                        foreach ($_FILES as $key => $value) {
                            if ($value['name']) {
                                $uploadedFiles[str_replace('file_', '', $key)] = $filesystem -> uploadFile($key, $uploadDirectory);
                            }
                        }
                    }

                    $testData = array('login'    => $currentUser -> user['login'],
                                      'duration' => time() - $values['time_start'],
                                      'times'    => $test -> test['times_done'],
                                      'questions_order' => $_POST['questions_order'],
                                      'answers_order'   => $_POST['answers_order']);
                    $results  = $test -> correct($testData, $values['question'], $uploadedFiles);
                    $doneInfo = $test -> setDone($currentUser -> user['login']);

                    $doneInfo['duration_converted'] = eF_convertIntervalToTime($doneInfo['duration']);
                    $smarty -> assign("T_TEST", $test -> toHTMLQuickForm($form, false, true));

                    $smarty -> assign("T_DONE_TEST_DATA", $doneInfo);
                }

                $renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
                $form   -> accept($renderer);
                $smarty -> assign('T_TEST_FORM', $renderer -> toArray());
            } catch (Exception $e) {
                $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
                $message = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            }
        }
        $smarty -> assign("T_TEST_DATA", $test -> test);
        $test -> test['redoable'] > 0 ? $smarty -> assign("T_TIMES_REMAINING", $test -> test['redoable'] - $doneInfo['times']) : null;

    } else {                                                                            //The user sees the list of tests
        $smarty -> assign("T_CONTENT_TREE",  $currentContent -> toHTML($iterator, 'dhtmlContentTree', array('truncateNames' => 25, 'selectedNode' => $currentUnit['id'])));
        $smarty -> assign("T_UNIT",          $currentUnit);
        $smarty -> assign("T_NEXT_UNIT",     $currentContent -> getNextNode($currentUnit, $iterator));
        $smarty -> assign("T_PREVIOUS_UNIT", $currentContent -> getPreviousNode($currentUnit, $iterator));        //Next and previous units are needed for navigation buttons
        $smarty -> assign("T_PARENT_LIST",   $currentContent -> getNodeAncestors($currentUnit));       //Parents are needed for printing the titles
        $smarty -> assign("T_NO_TEST", true);
        if (isset($_GET['view_unit']) && !$_SESSION['s_role_options']['read_content']) {
            $message = _HAVENOPRIVILEDGESTOSEECONTENT;
            $message_type = "failure";
        } else if (isset($rules_message)) {
            $message      = _CANNOTACCESSTHISUNIT.' '.$rules_message;
            $message_type = 'failure';
        }
    }

}
/*
*/
elseif ($ctg == 'calendar') {
    include_once "calendar.php";
}
/*
The glossary page is responsible for viewing and manipulating glossary words
*/
elseif ($ctg == 'glossary') {
    if ($_SESSION['s_role_options']['read_content'] == 1) {
        $glossary_words = eF_getTableData("glossary_words", "name,info", "lessons_ID=".$_SESSION['s_lessons_ID']);

        $words = eF_getAllGlossaryWords($glossary_words);
        $smarty -> assign("T_GLOSSARY", $words);
    } else {
        $message = _HAVENOPRIVILEDGESTOSEECONTENT;
        $message_type = "failure";
    }

}

/*
This is the page that has to do with surveys
*/
elseif ($ctg == 'survey') {
     $load_editor=true;
     include_once "module_surveys.php";
}
/*
The student statistics depend entirely on module_statisics.php
*/
elseif ($ctg == 'statistics') {
    if (isset($_GET['show_solved_test']) && eF_checkParameter($_GET['show_solved_test'], 'id') && isset($_GET['lesson']) && eF_checkParameter($_GET['lesson'], 'id')) {
        try {
            //pr($_GET['lesson']);pr($currentUser -> getLessons());
            if (in_array($_GET['lesson'], array_keys($currentUser -> getLessons()))) {
                $result   = eF_getTableData("done_tests, tests, content", "done_tests.tests_ID, done_tests.users_LOGIN", "content.id=tests.content_ID and content.lessons_ID=".$_GET['lesson']." and tests.id = done_tests.tests_ID and done_tests.users_LOGIN = '".$currentUser -> user['login']."' and done_tests.id=".$_GET['show_solved_test']);
                if (sizeof($result) > 0) {
                    $showTest = new EfrontTest($result[0]['tests_ID']);
                    //Set "show answers" and "show given answers" to true, since if it is not the student that sees the test
                    if ($currentUser -> user['user_type'] != 'student') {
                        $showTest -> test['answers']       = 1;
                        $showTest -> test['given_answers'] = 1;
                    }
                    $showTest -> setDone($result[0]['users_LOGIN']);
                    $smarty   -> assign("T_CURRENT_TEST", $showTest -> test);
                    $smarty   -> assign("T_SOLVED_TEST_DATA", $showTest -> doneInfo);
                    $smarty   -> assign("T_TEST_SOLVED", $showTest -> toHTMLQuickForm(new HTML_Quickform(), false, true));
                } else {
                    $message      = _USERHASNOTDONETEST;
                    $message_type = 'failure';
                }
            } else {
                $message      = _USERHASNOTTHISLESSON;
                $message_type = 'failure';
            }
        } catch (Exception $e) {
            $smarty -> assign("T_EXCEPTION_TRACE", $e -> getTraceAsString());
            $message      = $e -> getMessage().' ('.$e -> getCode().') &nbsp;<a href = "javascript:void(0)" onclick = "eF_js_showDivPopup(\''._ERRORDETAILS.'\', 2, \'error_details\')">'._MOREINFO.'</a>';
            $message_type = 'failure';
        }
    } else {
        /**The statistics funtions*/
        include_once "module_statistics.php";
    }

}
/*
The lessons page is the page where the user chooses which lesson to view
*/
elseif ($ctg == 'lessons') {
//    $userLessons = $currentUser -> getLessons();                //Get user lessons
/*
    if (sizeof($userLessons) == 0) {                                //This user hasn't enrolled to any lessons
        header("location:".$_SERVER['PHP_SELF']."?ctg=personal&tab=attending");
    } elseif (sizeof($userLessons) == 1 && !$currentLesson) {                           //The user has enrolled to a single lesson
        header("location:".current($userLessons).".php?ctg=control_panel&lessons_ID=".key($userLessons)."&message=".$message."&message_type=".$message_type);    //Redirect to the lesson's first page
    }
*/
    $directionsTree = new EfrontDirectionsTree();
    $userLessons    = $currentUser -> getLessons(true);
    $userProgress   = EfrontStats :: getUsersLessonStatus($userLessons, $currentUser -> user['login']);
    foreach ($userLessons as $key => $lesson) {
        $userLessons[$key] -> userStatus = array_merge($userProgress[$key][$currentUser -> user['login']], $userLessons[$key] -> userStatus);
    }
    $userCourses = $currentUser -> getCourses(true);

    if (sizeof ($userLessons) > 0 || sizeof($userCourses) > 0) {
        $smarty -> assign("T_DIRECTIONS_TREE", $directionsTree -> toHTML(false, $userLessons, $userCourses));
    }
    
    if (isset($_GET['export']) && $_GET['export'] == 'pdf') {
        $result = eF_getTableData("users_to_courses", "*", "users_LOGIN = '".$_GET['user']."' and courses_ID = '".$_GET['course']."' limit 1");

        if (sizeof($result) == 1 || isset($_GET['preview'])) {
            $course = new EfrontCourse($_GET['course']);
            $border = $course -> getCertificateBorder();
            if (!isset($_GET['preview'])){
                $borderid = $course -> course['certificate_border'];
                $certificate = $result[0]['issued_certificate'];    
                $logo_position = $course -> course['logo_position'];
                $logo_id = $course -> course['logo_id'];
            }
            else{
                $logoFileSystemTree = new FileSystemTree(G_CERTIFICATELOGOPATH);
                $certificate = urldecode($_GET['cbody']);
                $borderid = $_GET['border'];
                if ($borderid == 1){
                    $border = "images/certificate.jpg";
                }
                else if ($borderid == 2){
                    $border =  "images/certificate2.jpg";
                }
                else if ($borderid == 3){
                    $border = "images/certificate3.jpg";
                }
                $logo_position = $_GET['logo_position'];
                $logoDirectory = G_CERTIFICATELOGOPATH;
                if (!is_dir($logoDirectory)) {
                    mkdir($logoDirectory);
                }
                $logo_id = 0;
                $selectedLogo = $_GET['logo_id'];
                if ($selectedLogo != "--"){
                    $selectedLogo = $logoFileSystemTree -> seekNode($logoDirectory.$selectedLogo);
                    $lfile = new EfrontFile($selectedLogo['path']);
                    $logo_id = $lfile -> offsetGet('id');    
                }
                else{
                    $logo_id = 0;
                }
            }

            $pdf = new TCPDF('L', PDF_UNIT, PDF_PAGE_FORMAT, true);
            $pdf->SetCreator(PDF_CREATOR);
            $pdf->SetAuthor(PDF_AUTHOR);
            $pdf->SetTitle($doc_title);
            $pdf->SetSubject($doc_subject);
            $pdf->SetKeywords($doc_keywords);

            //set margins
            $pdf->SetMargins(5, 2, 5);
            //set auto page breaks
            $pdf->SetAutoPageBreak(FALSE, PDF_MARGIN_BOTTOM);
            $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set image scale factor
            $pdf->setPrintHeader(false);
            $pdf->setPrintFooter(false);

            //initialize document
            $pdf -> AliasNbPages();
            $pdf -> AddPage();
            $pdf -> SetFont("FreeSerif","B", 18);
            $pdf -> SetTextColor(0, 0, 0);
            $pdf -> Image($border, '0', '0', '300', '210', '', '');
                
            if ($logo_id > 0){
                $logoFile = new EfrontFile($logo_id);
                $lpath = $logoFile -> offsetGet('path');
                switch ($logo_position){
                    case 0:{
                        if ($borderid == 1){
                            $pdf -> Image($lpath, '30', '35', '20', '20', '', '');
                        }
                        else{
                            $pdf -> Image($lpath, '50', '40', '20', '20', '', '');
                        }
                        break;
                    }
                    case 1:{
                        if ($borderid == 1){
                            $pdf -> Image($lpath, '250', '35', '20', '20', '', '');
                        }
                        else{
                            $pdf -> Image($lpath, '230', '40', '20', '20', '', '');
                        }
                        break;
                    }
                    case 2:{
                        if ($borderid == 1){
                            $pdf -> Image($lpath, '30', '160', '20', '20', '', '');
                        }
                        else{
                            $pdf -> Image($lpath, '50', '155', '20', '20', '', '');
                        }
                        break;
                    }
                    case 3:{
                        if ($borderid == 1){
                            $pdf -> Image($lpath, '240', '160', '20', '20', '', '');
                        }
                        else{
                            $pdf -> Image($lpath, '230', '152', '20', '20', '', '');
                        }
                        break;
                    }
                    case 4:{
                        if ($borderid == 1){
                            $pdf -> Image($lpath, '145', '35', '20', '20', '', '');
                        }
                        else{
                            $pdf -> Image($lpath, '140', '40', '20', '20', '', '');
                        }
                        $pdf->Cell(0, 0, "", 0, 1, C);
                        $pdf->Cell(0, 0, "", 0, 1, C);
                        $pdf->Cell(0, 0, "", 0, 1, C);
                        break;
                    }
                    case 5:{
                        if ($borderid == 1){
                            $pdf -> Image($lpath, '145', '160', '20', '20', '', '');
                        }
                        else{
                            $pdf -> Image($lpath, '140', '152', '20', '20', '', '');
                        }
                        break;
                    }
                    default:{

                        if ($borderid != 1){
                            $pdf -> Image($lpath, '30', '35', '20', '20', '', '');
                        }
                        else{
                            $pdf -> Image($lpath, '50', '40', '20', '20', '', '');
                        }
                        break;

                    }
                }
            }
            $pdf->Cell(0, 0, "", 0, 1, C);
            $pdf->Cell(0, 0, "", 0, 1, C);
            $pdf->Cell(0, 0, "", 0, 1, C);

            if ($borderid != 0){
                $pdf->Cell(0, 0, "", 0, 1, C);
                $pdf->Cell(0, 0, "", 0, 1, C);
            }

            $lines = explode("\n", $certificate);

            for ($i = 0; $i < sizeof($lines); $i++){
                $pdf->Cell(0, 0, $lines[$i], 0, 1, C);
            }
            $pdf->Output();
        }
        exit(0);
    }
}
/*
From this page the student may access and alter its personal information,
as well as join new lessons and courses
*/
elseif ($ctg == 'personal') {
    $login = $_SESSION['s_login'];

    /**This part is used to display the user's personal information*/
    include "module_personal.php";

    $log_comments = 1;                                              //The $log_comments variable is used at the log entry.
}
/**************/
/* MODULE HCD */
/**************/
elseif ($ctg == 'module_hcd' && MODULE_HCD_INTERFACE) {
   include "module_hcd.php";
}

/*
///MODULES3: Include the module code
 */
elseif ($ctg == 'module') {

//    $loadScripts = array_merge($loadScripts, array('scriptaculous/prototype', 'scriptaculous/scriptaculous'));
    $className = $_GET['op'];
    if (isset($loadedModules[$className])) {

        // Get top title navigational links
        $nav_links = $loadedModules[$className] -> getNavigationLinks();
        if ($nav_links) {
            $links_size = sizeof($nav_links);
            $count = 0;
            $module_nav_links = "";
            foreach ($nav_links as $link) {
                $module_nav_links .= '<a class="titleLink" href ="'.$link['link'].'">'.$link['title'].'</a>';
                $count++;
                if ($count < $links_size) {
                    $module_nav_links .= '&nbsp;&raquo;&nbsp;';
                }
            }
        } else {
            $module_nav_links = '<a class="titleLink" href ="'.$loadedModules[$className] -> moduleBaseUrl.'">'.$loadedModules[$className] -> getName().'</a>';
        }
        $smarty -> assign("T_MODULE_NAVIGATIONAL_LINKS", $module_nav_links);

        // Get link to highlight on the left sidebar
        $highlight = $loadedModules[$className] -> getLinkToHighlight();
        if ($highlight) {
            $highlight = $loadedModules[$className] -> className . "_" . $highlight;
        } else {
            $highlight = $loadedModules[$className] -> className;
        }
        $smarty -> assign("T_MODULE_HIGHLIGHT", $highlight);

        // Get module html - two ways: pure HTML or PHP+smarty
        // If no smarty file is defined then false will be returned
        if ($module_smarty_file = $loadedModules[$className] -> getSmartyTpl()) {
            // Execute the php code
            $loadedModules[$className] -> getModule();
            // Let smarty know to include the module smarty file
            $smarty -> assign("T_MODULE_SMARTY", $module_smarty_file);
        } else {
            // Present the pure HTML code
            $smarty -> assign("T_MODULE_PAGE", $loadedModules[$className] -> getModule());
        }
    } else {
        $message = _ERRORLOADINGMODULE;
        $message_type = "failure";
    }

}


/*
Emails is the page that is used to send email to system users.
*/
elseif ($ctg == "emails" && MODULE_HCD_INTERFACE) {
   include "emails.php";
}
/*
Users is the page that concerns EMPLOYEE administration for users with supervisor rights. It uses module_personal.php to perform most of the update functions,
since the same functions need to be performed from the professor and student as well (for themseleves)
There are 5 sub options in this page, denoted by an extra link part:
- &add_user=1                   When we are adding a new user
- &delete_user=<login>          When we want to delete user <login>
- &edit_user=<login>            When we want to edit user <login>
- &deactivate_user=<login>      When we deactivate user <login>
- &activate_user=<login>        When we activate user <login>
*/
elseif ($ctg == 'users' && MODULE_HCD_INTERFACE) {
    $currentUser -> aspects['hcd'] = EfrontEmployeeFactory :: factory($currentUser -> login);
    $currentEmployee = $currentUser -> aspects['hcd'];
    $unprivileged = false;                          //This variable is used to check whether the current user is elegible (based on his role) to access this area
    if ($currentUser -> getType() != "administrator" && $currentEmployee -> getType() != _SUPERVISOR) {
        $message      = _SORRYYOUDONOTHAVEPERMISSIONTOPERFORMTHISACTION;
        $message_type = "failure";
        header("location:".$_SERVER['HTTP_REFERER']."&message=".$message."&message_type=".$message_type);
        //header("location:".$_SESSION['s_type'].".php?ctg=module_hcd&op=chart&message=".$message."&message_type=".$message_type);
        exit;
    } else {

        if (isset($_GET['delete_user']) && eF_checkParameter($_GET['delete_user'], 'login') && !$unprivileged) {    //The administrator asked to delete a user
            if (eF_deleteUser($_GET['delete_user'])) {

                /** MODULE HCD: Delete the employee relevant information **/
                if ($module_hcd_interface) {
                    eF_deleteTableData("module_hcd_employees", "users_login='".$_GET['delete_user']."'");
                    eF_deleteTableData("module_hcd_employee_has_skill", "users_login='".$_GET['delete_user']."'");
                    eF_deleteTableData("module_hcd_employee_has_job_description", "users_login='".$_GET['delete_user']."'");
                    eF_deleteTableData("module_hcd_employee_works_at_branch", "users_login='".$_GET['delete_user']."'");

                    // Register user's firing into the event log
                    eF_insertTableData("module_hcd_events", array("event_code"    => $MODULE_HCD_EVENTS['FIRED'],
                                                                  "users_login"   => $_GET['delete_user'],
                                                                  "specification" => _FIRED,
                                                                  "timestamp"     => time()));
                    $message      = _EMPLOYEEDELETED;
                } else {
                    $message      = _USERDELETED;
                }
                $message_type = 'success';
            } else {
                $message      = _SOMEORALLOFTHEUSERELEMENTSCOULDNOTBEDELETED;
                $message_type = "failure";
            }
            header("location:".$_SERVER['PHP_SELF']."?ctg=users&message=".$message."&message_type=".$message_type);
        } elseif (isset($_GET['deactivate_user']) && eF_checkParameter($_GET['deactivate_user'], 'login') && !$unprivileged) {      //The administrator asked to deactivate a user
            if (eF_updateTableData("users", array('active' => 0), "login='".$_GET['deactivate_user']."'")) {
                $message      = _USERDEACTIVATED;
                $message_type = 'success';
            } else {
                $message      = _SOMEPROBLEMEMERGED;
                $message_type = "failure";
            }
            header("location:".$_SERVER['PHP_SELF']."?ctg=users&message=".$message."&message_type=".$message_type);
        } elseif (isset($_GET['activate_user']) && eF_checkParameter($_GET['activate_user'], 'login') && !$unprivileged) {          //The administrator asked to activate a user
            if (eF_updateTableData("users", array('active' => 1, 'pending' => 0), "login='".$_GET['activate_user']."'")) {
                $message      = _USERACTIVATED;
                $message_type = 'success';
            } else {
                $message      = _SOMEPROBLEMEMERGED;
                $message_type = "failure";
            }
            header("location:".$_SERVER['PHP_SELF']."?ctg=users&message=".$message."&message_type=".$message_type);
        } elseif (isset($_GET['add_user']) || (isset($_GET['edit_user']) && $login = eF_checkParameter($_GET['edit_user'], 'login')) && !$unprivileged) {   //The administrator asked to add a new user or to edit a user
            $smarty -> assign("T_PERSONAL", true);
            /**Include the personal settings file*/
            include "module_personal.php";                      //User addition and manipulation is done through module_personal.

        } else {                                                //The professor just asked to view the users
    //dddddddddddddddddd
            if (!$module_hcd_interface) {
                $result_with_lessons    = eF_getTableData("users_to_lessons, users","count( * ) AS lessons_num, users.*", "users_LOGIN = login AND users_LOGIN IN ( SELECT login FROM users) GROUP BY login");
                $result_without_lessons = eF_getTableData("users","*", "login NOT IN ( SELECT DISTINCT (users_LOGIN) FROM users_to_lessons)");
                $result = array_merge($result_with_lessons, $result_without_lessons);  //right is this: SELECT name, login, count( lessons_ID )FROM usersLEFT OUTER JOIN users_to_lessons ON users.login = users_to_lessons.users_LOGIN GROUP BY login
                for ($i = 0; $i < sizeof($result); $i++) {
                    foreach ($result[$i] as $key => $value) {
                        if ($key == 'user_type') {
                            $result[$i][$key] = $TRANSLATION[$value];
                        }
                    }
                }
                $smarty -> assign("T_USERS", $result);

            } else {

                $_GET['op'] = "employees";
                include "module_hcd.php";
            }
        }
   }
}
/*
At this point, we apply module functionality
*/
elseif (sizeof($modules) > 0 && in_array($ctg, array_keys($module_ctgs))) {
    $module_mandatory = eF_getTableData("modules", "mandatory", "name = '".$ctg."'");
    if ($module_mandatory[0]['mandatory'] != 'false' || ($GLOBALS['currentLesson'] -> options[$ctg])) {
        include(G_MODULESPATH.$ctg.'/module.php');
        $smarty -> assign("T_CTG_MODULE", $module_ctgs[$ctg]);
    }
}

$fields_log = array ('users_LOGIN' => $_SESSION['s_login'],         //This is the log entry array
                     'timestamp'   => time(),
                     'session_ip'  => eF_encodeIP($_SERVER['REMOTE_ADDR']));

if (isset($log_comments)) {                                         //If there is a $log_comments variable, it indicates the current action (i.e. the unit that the user saw)
    $fields_log['action']   = $ctg;
    $fields_log['comments'] = $log_comments;
    ($_SESSION['s_lessons_ID']) ? $fields_log['lessons_ID'] = $_SESSION['s_lessons_ID'] : $fields_log['lessons_ID'] = 0;
    eF_insertTableData("logs", $fields_log);
} else {                                                            //Any other move, that has not set the $log_comments variable, is considered a 'lastmove' action
    $fields_log['action']   = "lastmove";
    $fields_log['comments'] = "";
    ($_SESSION['s_lessons_ID']) ? $fields_log['lessons_ID'] = $_SESSION['s_lessons_ID'] : $fields_log['lessons_ID'] = 0;
    eF_deleteTableData("logs", "users_LOGIN='".$_SESSION['s_login']."' AND action='lastmove'"); //Only one lastmove action interests us, so delete any other
    eF_insertTableData("logs", $fields_log);
}

$smarty -> assign("T_HEADER_EDITOR", $load_editor);                 //Specify whether we need to load the editor

if (isset($_GET['refresh'])) {
    $smarty -> assign("T_REFRESH_SIDE","true");
}

///MODULES5
$smarty -> assign("T_MODULE_CSS", $module_css_array);
$smarty -> assign("T_MODULE_JS", $module_js_array);
foreach ($loadedModules as $module) {
    $loadScripts = array_merge($loadScripts, $module -> addScripts());
}

if ($message) {
    $loadScripts[] = 'scriptaculous/scriptaculous';
    $loadScripts[] = 'scriptaculous/effects';
}

$smarty -> assign("T_HEADER_LOAD_SCRIPTS", array_unique($loadScripts));

$smarty -> assign("T_CURRENT_CTG", $ctg);
$smarty -> assign("T_MENUCTG", $ctg);
$smarty -> assign("T_MENU", eF_getMenu());

$smarty -> assign("T_QUERIES", $numberOfQueries);

$smarty -> assign("T_MESSAGE", $message);
$smarty -> assign("T_MESSAGE_TYPE", $message_type);
$smarty -> assign("T_SEARCH_MESSAGE", $search_message);

$smarty -> assign("T_CONFIGURATION", $configuration);       //Assign global configuration values to smarty
$smarty -> assign("T_CURRENT_USER", $currentUser);
$smarty -> assign("T_CURRENT_LESSON", $currentLesson);

$smarty -> load_filter('output', 'eF_template_formatTimestamp');
$smarty -> load_filter('output', 'eF_template_formatLogins');

$debug_timeBeforeSmarty = microtime(true) - $debug_TimeStart;
$smarty -> display('student.tpl');
$debug_timeAfterSmarty = microtime(true) - $debug_TimeStart;

$debug_TotalTime = microtime(true) - $debug_TimeStart;

if (G_DEBUG) {
    echo "
    <div onclick = 'this.style.display=\"none\"' style = 'position:absolute;top:0px;right:0px;background-color:lightblue;border:1px solid black' >
    <table>
        <tr><th colspan = '100%'>Benchmarking info (click to remove)</th></tr>
        <tr><td>Initialization time: </td><td>".round($debug_InitTime, 5)." sec</td></tr>
        <tr><td>Time up to smarty: </td><td>".round($debug_timeBeforeSmarty, 5)." sec</td></tr>
        <tr><td>Database time: </td><td>".round($databaseTime, 5)." sec</td></tr>
        <tr><td>Smarty overhead: </td><td>".round($debug_timeAfterSmarty - $debug_timeBeforeSmarty, 5)." sec</td></tr>
        <tr><td colspan = \"2\" class = \"horizontalSeparator\"></td></tr>
        <tr><td>Total execution time: </td><td>".round($debug_TotalTime, 5)." sec</td></tr>
        <tr><td>Execution time for this script is: </td><td>".round($debug_TotalTime - $debug_InitTime - ($debug_timeAfterSmarty - $debug_timeBeforeSmarty), 5)." sec</td></tr>
    </table>
    </div>";
}





?>