<?php
/**
 * Sidebar frame
 *
 * This page is used as the leftmost frame, which is the menu bar
 * @package eFront
 * @version 1.0
 */

//---------------------------------------------Initialization-------------------------------------------------
//$debug_TimeStart = microtime(true);     //Debugging timer - initialization

//error_reporting(E_ERROR);
//if(!isset($_SESSION)) {
    session_cache_limiter('none');
    session_start();
//}

$path = "../libraries/";

/** Configuration file.*/
include_once $path."configuration.php";
include_once $path."menu.class.php";

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


if (isset($_SESSION['s_login'])) {
    $user_type_ret = eF_checkUser($_SESSION['s_login'], $_SESSION['s_password']);
    $currentUser = EfrontUserFactory :: factory($_SESSION['s_login']);

    if (MODULE_HCD_INTERFACE) {
        $currentUser -> aspects['hcd'] = EfrontEmployeeFactory :: factory($_SESSION['s_login']);
        $employee = $currentUser -> aspects['hcd'];
    }
}

if (!isset($_SESSION['s_login']) || ($user_type_ret != "student" && $user_type_ret != "professor" && $user_type_ret != "administrator") ) {  //Must be a user of any type to access this page
    header("location:index.php");
    exit;
}

$css = $configuration['css'];
if (strlen($css) > 0 && is_file(G_CUSTOMCSSPATH.$css)){
    $smarty->assign("T_CUSTOM_CSS",$css);
}


//---------------------------------------------End of Initialization-------------------------------------------------


///MODULE1
$modules = $currentUser -> getModules();
// Include module languages
foreach ($modules 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;
    }
}

/***** TOP MENU WITH AVATAR AND NAME *****/
//pr($currentUser);
try {
    $avatar = new EfrontFile($currentUser -> user['avatar']);
    $smarty -> assign ("T_AVATAR", $currentUser -> user['avatar']);
} catch (Exception $e) {
    $smarty -> assign ("T_AVATAR", G_AVATARSPATH."system_avatars/unknown_small.png");
}
//pr($currentUser -> user['avatar']);
//echo $avatar_file;
if ($currentUser -> user['name'] != '') {
    $realname = substr($currentUser -> user['name'],0,1) .".&nbsp;" . $currentUser -> user[0]['surname'] . "<br>"; //get the initial letter
    $smarty->assign("T_RESULT",$currentUser -> user);
}

$efront_type = "<b><i>" . $_SESSION['s_login'] . "</i></b><br>";
if ($_SESSION['s_type'] == 'administrator') {
    $efront_type .= "<b>" . _TYPEOFUSER . "</b>:<br>";
    $efront_type .= _ADMINISTRATOR;
} else if ($_SESSION['s_type'] == 'student') {
    $efront_type .= "<b>" . _EDUCATIONALROLE . "</b>:<br>";
    $efront_type .= _STUDENT;
} else {
    $efront_type .= "<b>" . _EDUCATIONALROLE . "</b>:<br>";
    $efront_type .= _PROFESSOR;
}
$efront_type .= "<br>";

if (MODULE_HCD_INTERFACE && $employee -> getType() == _SUPERVISOR) {
    $efront_type .= "<b>" . _ORGANIZATIONALROLE . "</b>:<br>" . _SUPERVISOR . "<br>";
}

if (MODULE_HCD_INTERFACE && $currentUser -> getType() != "administrator") {
    $efront_type .= "<b>" . _JOBDESCRIPTIONS. "</b>:<br>";
    $jobs = $employee -> getJobs();
    foreach ($jobs as $job) {
        $efront_type .= $job['description']. " ". _ATBRANCH . " \"" . $job['name']."\"<br>";
    }

}
/***** FOR SEARCHING *****/
eF_setRoleParameters();
/**Search module is used to display the search field and perform the searches*/
include "module_search.php";


/***** MENU *****/
$newMenu = new EfrontMenu();
$active_menu = 1; // initialized here, might change later
// SYSTEM MENU - ADMINISTRATOR ONLY
if ($_SESSION['s_type'] == 'administrator') {
    $systemMenu = array();
    $systemMenu[0] = array("id" => "control_panel_a", "image" => "home", "link" => "administrator.php?ctg=control_panel", "title" => _CONTROLCENTER);
    $systemMenu[1] = array("id" => "forum_a",         "image" => "messages", "link" => "forum/forum_index.php", "title" => _FORUM);
    $systemMenu[2] = array("id" => "cms_a", "image" => "document_text", "link" => "administrator.php?ctg=cms", "title" => _CMS);
    $systemMenu[3] = array("id" => "chat_a", "image" => "user1_message", "link" => "chat/chat_index.php", "title" => _CHAT);

    if ($_SESSION['s_role_options']['statistics'] == "1") {
        $systemMenu[4] = array("id" => "statistics_system_a", "image" => "chart", "link" => "administrator.php?ctg=statistics&option=system", "title" => _SYSTEMSTATISTICS);
    }

    // Get system menu modules
    $moduleMenus = eF_getModuleMenu($modules, "system");
    foreach ($moduleMenus as $moduleMenu) {
        $systemMenu[] = $moduleMenu;
    }
    $newMenu -> insertMenuOption($systemMenu, false, _SYSTEM);

}

//pr($_GET);

// LESSON MENU
if (isset($_GET['new_lesson_id'])) {

    $_SESSION['s_lessons_ID'] = $_GET['new_lesson_id'];
    eF_setLessonParameters();

    $lessonMenu = ef_getMenu();

    $lessons = eF_getTableData("users_to_lessons, lessons", "lessons.name","users_to_lessons.users_LOGIN='".$_SESSION['s_login']."' AND users_to_lessons.active=1 AND lessons.id=users_to_lessons.lessons_ID AND lessons.active=1 AND lessons.id = '".$_GET['new_lesson_id']."'");

    $lessonMenuId = $newMenu -> createMenu( array("title" => $lessons[0][name], "image" => "arrow_left_blue", "link" => "new_sidebar.php?sbctg=lessons"));          //onclick="top.mainframe.location='{$smarty.session.s_type}.php?ctg=lessons';"

    // Get current lesson menu modules

    $moduleMenus = eF_getModuleMenu($modules, "current_lesson");
    foreach ($moduleMenus as $moduleMenu) {
        $lessonMenu['lesson'][] = $moduleMenu;
    }
    $newMenu -> insertMenuOption($lessonMenu['lesson'], $lessonMenuId);


    // Insert blank option
    $newMenu -> insertMenuOptionAsRawHtml("<table height='8px'></table>", $lessonMenuId);
    $newMenu -> insertMenuOptionAsRawHtml("<a href=\"new_sidebar.php?sbctg=lessons\" onclick=\"top.mainframe.location='".$_SESSION['s_type'].".php?ctg=lessons';\"><img style=\"border:0; float: left;\" src=\"images/16x16/arrow_left_blue.png\" />"._CHANGELESSON."</a>", $lessonMenuId);

    $smarty -> assign("T_ACTIVE_ID","lesson_main");
} else {
    $_SESSION['s_lessons_ID'] = "";
    $lessonMenuId = $newMenu -> createMenu( array("title" => _LESSONS));
    if ($_SESSION['s_type'] == "administrator") {
        $newMenu -> insertMenuOption(array("id" => "lessons_a", "image" => "lessons", "link" => "administrator.php?ctg=lessons", "title" => _LESSONS), $lessonMenuId);
        $newMenu -> insertMenuOption(array("id" => "directions_a", "image" => "kdf",  "link" => "administrator.php?ctg=directions", "title" => _DIRECTIONS) , $lessonMenuId);
        $newMenu -> insertMenuOption(array("id" => "courses_a", "image" => "books", "link" => "administrator.php?ctg=courses", "title" => _COURSES), $lessonMenuId);
//        $newMenu -> insertMenuOption(array("id" => "search_courses_a", "image" => "book_open2", "link" => "administrator.php?ctg=search_courses", "title" => _SEARCHCOURSEUSERS), $lessonMenuId);
        $newMenu -> insertMenuOption(array("id" => "statistics_lesson_a", "image" => "chart", "link" => "administrator.php?ctg=statistics&option=lesson", "title" => _LESSONSTATISTICS),  $lessonMenuId);
        $newMenu -> insertMenuOption(array("id" => "statistics_test_a", "image" => "edit", "link" => "administrator.php?ctg=statistics&option=test", "title" => _TESTSTATISTICS),  $lessonMenuId);

        // Get lessons menu modules
        $moduleMenus = eF_getModuleMenu($modules, "lessons");
        foreach ($moduleMenus as $moduleMenu) {
            $newMenu -> insertMenuOption($moduleMenu,  $lessonMenuId);
        }

        $smarty -> assign("T_ACTIVE_ID","control_panel");
    } else {
        $newMenu -> insertMenuOption(array("id" => "lessons_a", "image" => "lessons", "link" => $_SESSION['s_type'].".php?ctg=lessons", "title" => _MYLESSONS), $lessonMenuId);

        // Get lessons menu modules
        $moduleMenus = eF_getModuleMenu($modules, "lessons");
        foreach ($moduleMenus as $moduleMenu) {
            $newMenu -> insertMenuOption($moduleMenu,  $lessonMenuId);
        }


        $userLessons = eF_getTableData("users_to_lessons, lessons", "lessons.name","users_to_lessons.users_LOGIN='".$_SESSION['s_login']."' AND users_to_lessons.active=1 AND lessons.id=users_to_lessons.lessons_ID AND lessons.languages_NAME='".$_SESSION['s_language']."' AND lessons.active=1");
        if (empty($userLessons)) {
            if (MODULE_HCD_INTERFACE == 1) {
                if ($employee -> isSupervisor()) {
                    $active_menu = 3;
                } else {
                    $active_menu = 2;
                }
            } else {
                $active_menu = 2;
            }

        }
        $smarty -> assign("T_ACTIVE_ID","personal");

    }
}

// In case of reload, select the correct menu
if (isset($_GET['sbctg'])) {
    $smarty -> assign("T_ACTIVE_ID",$_GET['sbctg']);
    if ($_GET['sbctg'] == "personal") {
        if (MODULE_HCD_INTERFACE == 1) {
            if ($_SESSION['s_type'] == "administrator") {
                $active_menu = 5;
            } else if ($employee -> isSupervisor()) {
                $active_menu = 3;
            } else {
                $active_menu = 2;
            }
        } else {
            ($_SESSION['s_type'] == "administrator") ? $active_menu = 4: $active_menu = 2;
        }
    }

}

$smarty -> assign ("T_ACTIVE_MENU", $active_menu);


// USERS MENU - ADMINISTRATOR ONLY
if ($_SESSION['s_type'] == 'administrator') {
    $usersMenu = array();
    $usersMenu[0] = array("id" => "users_a", "image" => "user1", "link" => "administrator.php?ctg=users", "title" => _USERS);
    //$usersMenu[1] = array("id" => "user_types_a",         "image" => "users_family", "link" => "administrator.php?ctg=user_types", "title" => _ROLES);
    $usersMenu[2] = array("id" => "user_groups_a", "image" => "users3", "link" => "administrator.php?ctg=user_groups", "title" => _GROUPS);
    $usersMenu[3] = array("id" => "statistics_user_a", "image" => "chart", "link" => "administrator.php?ctg=statistics&option=user", "title" => _USERSTATISTICS);

    // Get users menu modules
    $moduleMenus = eF_getModuleMenu($modules, "users");
    foreach ($moduleMenus as $moduleMenu) {
        $usersMenu[] = $moduleMenu;
    }

    $newMenu-> insertMenuOption($usersMenu, false, _USERS);
}

// ORGANIZATION MENU
if (MODULE_HCD_INTERFACE == 1) {
    include_once $path."module_hcd_tools.php";
    if ($employee -> getType() != _EMPLOYEE) {
        $menuHCD = ef_getHcdMenu();

        if ($currentUser -> getType() == 'administrator') {
            $menuHCD[] = array("id" => "search_employee_a", "image" => "book_red", "link" => "administrator.php?ctg=module_hcd&op=reports", "title" => _SEARCHEMPLOYEE);
        }

        // Get hcd menu modules
        $moduleMenus = eF_getModuleMenu($modules, "organization");
        foreach ($moduleMenus as $moduleMenu) {
            $usemenuHCD[] = $moduleMenu;
        }

        $newMenu -> insertMenuOption ($menuHCD, false, _ORGANIZATION);
    }
}

// TOOLS MENU
$toolsMenuId = $newMenu -> createMenu( array("title" => _PERSONALOPTIONS));
if ($_SESSION['s_type'] == 'administrator') {
    $newMenu -> insertMenuOption(array("id" => "personal_a", "image" => "index", "link" => "administrator.php?ctg=users&edit_user=".$_SESSION['s_login'], "title" => _PERSONALDATA), $toolsMenuId);
        $newMenu -> insertMenuOption(array("id" => "calendar_a",     "image" => "calendar", "link" => "administrator.php?ctg=calendar", "title" => _CALENDAR), $toolsMenuId);
    if (MODULE_HCD_INTERFACE == 1) {
        $newMenu -> insertMenuOption(array("id" => "file_manager_a", "image" => "folder_view", "link" => "administrator.php?ctg=users&edit_user=".$_SESSION['s_login']."&tab=file_record", "title" => _PERSONALFILES), $toolsMenuId);
    }
} else {
    $newMenu -> insertMenuOption(array("id" => "personal_a", "image" => "index", "link" => $_SESSION['s_type'].".php?ctg=personal", "title" => _PERSONALDATA), $toolsMenuId);
    $newMenu -> insertMenuOption(array("id" => "calendar_a", "image" => "calendar", "link" => $_SESSION['s_type'].".php?ctg=calendar", "title" => _CALENDAR), $toolsMenuId);

    if (MODULE_HCD_INTERFACE == 1) {
        $newMenu -> insertMenuOption(array("id" => "file_manager_a", "image" => "folder_view", "link" => $_SESSION['s_type'].".php?ctg=personal&tab=file_record", "title" => _PERSONALFILES), $toolsMenuId);
        if ($employee -> getType() == _EMPLOYEE) {
            $newMenu -> insertMenuOption(array("id" => "file_manager_a", "image" => "folder_view", "link" => $_SESSION['s_type'].".php?ctg=personal&tab=file_record", "title" => _PERSONALFILES), $toolsMenuId);
            $newMenu -> insertMenuOption(array('id' => 'chart_a',  'image' => "cubes", 'title' => _ORGANISATIONCHART,                       'target' => "mainframe",    'link' => $_SESSION['s_type'] . ".php?ctg=module_hcd&op=chart"), $toolsMenuId);

        }
    }
    $newMenu -> insertMenuOption(array("id" => "statistics_a", "image" => "chart", "link" => $_SESSION['s_type'].".php?ctg=statistics", "title" => _STATISTICS), $toolsMenuId);
}
$newMenu -> insertMenuOption(array("id" => "messages_a", "image" => "mail2", "link" => "forum/messages_index.php", "title" => _MESSAGES), $toolsMenuId);
// Get tools menu modules
$moduleMenus = eF_getModuleMenu($modules, "tools");
foreach ($moduleMenus as $moduleMenu) {
    $newMenu -> insertMenuOption($moduleMenu,  $toolsMenuId);
}

// Insert raw html for messages handling
$newMenu -> insertMenuOptionAsRawHtml("<table width = '100%'><tr><td align = 'center' id = 'new_chat_message'></td></tr></table><table width = '100%'><tr><td align = 'center' id = 'new_private_message'></td></tr></table>", $toolsMenuId);

// MODULES MENU
$other_menus = array();
foreach ($modules as $key => $module) {
    $sidebarLinks = $module -> getSidebarLinkInfo();

    $sidebarLinks = $sidebarLinks["other"];
    $menuTitle = $sidebarLinks["menuTitle"];
    // Get the title set for this other menu
    // If this menu does not exist create it
    if ($menuTitle && !isset($other_menus["'".$menuTitle."'"])) {
        $other_menus["'".$menuTitle."'"] = array();
    }

    foreach ($sidebarLinks["links"] as $mod_link) {
            $other_menus["'".$menuTitle."'"][] = array("id" => $module -> className . (($mod_link['id'])? "_".$mod_link['id']:""),
                                                       "image" => eF_getRelativeModuleImagePath($mod_link['image']),
                                                       "link" => $mod_link['link'],
                                                       "title" => $mod_link['title'],
                                                       "moduleLink" => "1",
                                                       "eFrontExtensions" => $mod_link['eFrontExtensions']);
    }

}

// If more than 8 new menus exist, then all will be put under the same menu called MODULES
if (sizeof($other_menus) > 8) {
    $massModulesMenuId = $newMenu -> createMenu( array("title" => _MODULES));
    foreach ($other_menus as $other_module_menu) {
        $newMenu -> insertMenuOption($other_module_menu, $massModulesMenu);
    }
} else {
// Otherwise a new menu will be put for each of them
    foreach ($other_menus as $title => $other_module_menu) {
        $newMenu -> insertMenuOption($other_module_menu, false, substr($title,1,strlen($title)-2));
    }
}


// ONLINE USERS MENU
if (isset($_SESSION['s_lessons_ID'])){
    try{
        $currentLesson = new EfrontLesson($_SESSION['s_lessons_ID']);
        $lesson_name = $currentLesson -> lesson['name'];
    }
    catch (Exception $e){
        $lesson_name = "";
    }
}
else{
    $lesson_name = "";
}


if ((($GLOBALS['currentLesson'] -> options['online']) && $GLOBALS['currentLesson'] -> options['online'] == 1) || $_SESSION['s_type']=='administrator' ){
    $currentUser = EfrontUserFactory :: factory($_SESSION['s_login']);
    $onlineUsers = $currentUser -> getUsersOnline(false);
    $size = sizeof($onlineUsers);
    if ($size) {
        $smarty -> assign("T_ONLINE_USERS_COUNT", $size);
    }
    $smarty -> assign("T_ONLINE_USERS_LIST", $onlineUsers);
}

//pr($newMenu);


$smarty -> assign("T_MENU",$newMenu -> menu);
$smarty -> assign("T_MENUCOUNT", $newMenu -> menuCount);

$smarty -> assign("T_UNREAD_MESSAGES", eF_getUnreadMessagesNumber());

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

$smarty -> assign("T_REALNAME", $realname);
$smarty -> assign("T_SB_CTG", $_GET['sbctg']);
$smarty -> assign("T_TYPE", $efront_type);
$smarty -> display('new_sidebar.tpl');


/*
$debug_timeAfterSmarty = microtime(true) - $debug_TimeStart;

$debug_TotalTime = microtime(true) - $debug_TimeStart;

    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>";

*/

?>