<?php

/**
* Get status for lessons in course
*
* This function checks for the given course and the given student, which lessons
* he has the right to attend based on the course rules
* <br/>Example:<br/>
* <code>
* $status = eF_getCourseRulesPassed(5, array(2, 3, 4), 'student');
* //returns:
* Array
* (
*     [2] => 1
*     [3] => 0
*     [4] => 1
* )
* </code>
*
* @param int $course_id The course id
* @param mixed $lessons Either a single lesson id, or an array of lesson ids
* @param string $users_LOGIN The user to check access for
* @return array An array where keys are lesson ids and values are 0 or 1, depending on whether he may have access to this lesson
* @version 1.0
* @author Venakis Periklis
* @date 2007/26/09
* @deprecated
*/
function eF_getCourseRulesPassed($course_id, $lessons, $users_LOGIN) {
    if (!is_array($lessons)) {                                       //Convert to array, if a single value is given
        $lessons = array($lessons);
    }

    //$user_lessons = eF_getTableDataFlat("users_to_lessons", "lessons_ID, completed", "users_LOGIN='".$users_LOGIN."'");
    $user_lessons = eF_getTableDataFlat("users_to_lessons, lessons", "lessons_ID, completed, lessons.name", "lessons.id=users_to_lessons.lessons_ID and users_LOGIN='".$users_LOGIN."'");
    $lesson_names = array_combine($user_lessons['lessons_ID'], $user_lessons['name']);
    $user_lessons = array_combine($user_lessons['lessons_ID'], $user_lessons['completed']);
    $course       = eF_getTableData("courses", "rules, lessons", "id=$course_id");
    foreach ($lessons as $lesson_id) {
        $course_lessons = unserialize($course[0]['lessons']);
        $course_rules   = unserialize($course[0]['rules']);

        if (in_array($lesson_id, $course_lessons) && isset($course_rules[$lesson_id])) {
            $rule = $course_rules[$lesson_id];

            $rule_string = '';
            foreach ($rule['lesson'] as $key => $lesson) {
                $condition = '';
                $condition_string = '';
                if (isset($rule['condition'][$key + 1])) {
                    if ($rule['condition'][$key + 1] == 'and') {                                        //Construct the bit sequence, for example 1 & 0 & 0 | 1
                        $condition        = '&';
                        $condition_string = _AND;
                    } else if ($rule['condition'][$key + 1] == 'or') {
                        $condition        = '|';
                        $condition_string = _OR;
                    }
                }
                $rule_string .= $user_lessons[$lesson].$condition;
                $lesson_permitted[$lesson_id]['conditions'] .= $lesson_names[$lesson]." ".$condition_string." ";
            }

            eval("\$lesson_permitted[\$lesson_id]['selectable'] = $rule_string;");                                    //Evaluate bit sequence

        } else {
            $lesson_permitted[$lesson_id]['selectable'] = 1;
        }
    }

    return $lesson_permitted;
}


/**
* Converts a timestamp to human-readable date and time format
*
* This function takes a timestamp as an argument. It returns a string containing a textual representation
* of the date and time corresponding to this timestamp. If no input argument is given, it defaults to current timestamp.
* <br/>Example:
* <code>
* print eF_TimestampToTime(time()-3600);
* //prints: May 12 2005, 14:51
* </code>
*
* @param int $timestamp The timestamp to be converted
* @param bool $onlytime If set, then only the cirrent time is displayed
* @return string The date and time corresponding to the given timestamp
* @todo get rid of global
* @version 1.2
* @deprecated
* Changes from version 1.1 to 1.2:
* - Removed new conversion method and reverted to old one
* Changes from version 1.0 to 1.1:
* - Added $onlytime parameter
* - Changed conversion method to use date() function
*/
function eF_timestampToTime($timestamp = false, $onlytime = false)
{
    global $MONTH;

    if ($timestamp === false) {
        $timestamp = time();
    }

    $month_num = strftime("%m", $timestamp);
    if ($onlytime) {
        $date_str = date("H:i:s", $timestamp);
    } else {
        $date_str = date("d ".$MONTH[$month_num]." Y, H:i", $timestamp);
    }
    return strftime("%d ", $timestamp).$MONTH[$month_num].strftime(" %Y", $timestamp).",  ".strftime(" %H:%M", $timestamp); //This should change, as well as eF_timeStampToDate() above
    //return $date_str;
}



/**
* Presents a comma separated list of units related to a lesson
*
* This function accepts a results table, of the same structure as returned by the eF_getTableData() function and
* optionally a $key string. It searches through the table for $key, and appends results in the list.
* <br/>Example:
* <code>
* $content       = eF_getTableData("content", "*", "lessons_ID=3");
* $content_list  = eF_makeListIDs($content);
* echo $content_list;
* //prints: 2952,2956,2958,2960,2961,2962,2963,2979,2980,2981,2982,2985,3023,3022,3020
* </code>
*
* @param array $data The table to search for results
* @param string $key The key to search for
* @return string The comma-separated list of results
* @version 1.0
* @deprecated. Should use getTableDataFlat() with implode() instead
*/
function eF_makeListIDs($data, $key = "id")
{
    if ($data) {
        for ($i = 0; $i < sizeof($data); $i++) {
            $IDs[] = $data[$i][$key];
        }
        $list = implode(",", $IDs);
        return $list;
    } else {
        return false;
    }
}

/**
* Create content structure
*
* This function creates the content structure in its primitive form. This form consists
* of a multidimensional array, where each value represents a unit. If a unit has children,
* these children exist as sub-arrays of the unit. This way, the array created closely matches 
* the tree structure
* 
* @param int $content_ID The content id to build the tree for
* @param int $lessons_ID The lesson to build the tree for, defaults to session value
* @param bool $only_active Whether it should return only active values, defaults to true\
* 
* @deprecated 
*
*/
function eF_createContentStructure($content_ID = 0, $lessons_ID = '', $only_active = true) {

    if (!$lessons_ID || !eF_checkParameter($lessons_ID, 'id')) {
        $lessons_ID = $_SESSION['s_lessons_ID'];
    }

    if ($GLOBALS['configuration']['caching'] && $only_active) {                                                             //Cache this copy of the tree, but only if active units are requested (which is usualy the case)
        $result = eF_getTableData("cache", "*", "name='".$_SESSION['s_lessons_ID']."_contentTree'");                                 //Get cached copy
        if (sizeof($result) > 0 && $result[0]['expired'] == 0 && time() - $result[0]['timestamp'] < $GLOBALS['configuration']['cache_timeout']) {               //Check if cached copy is valid, and if so return it
            $tree = unserialize($result[0]['value']);
            return $tree;
        } else {
            eF_deleteTableData("cache", "name='".$_SESSION['s_lessons_ID']."_contentTree'");
        }
    }

    $units = eF_getTableData("content", "id, name, parent_content_ID, ctg_type, active, previous_content_ID, data", "lessons_ID=".$lessons_ID, "parent_content_ID, previous_content_ID");        //Get all the lesson units

    for ($i = 0; $i < sizeof($units); $i++) {                                                       //Initialize the nodes array
        $units[$i]['data'] == '' ? $units[$i]['data'] = false : $units[$i]['data'] = true;          //Set data bit, if the node has data.        
        
        $nodes[$units[$i]['id']]             = $units[$i];
        $nodes[$units[$i]['id']]['children'] = array();
    }

    $q = 0;
    while (sizeof($units) > 0 && $q++ < 1000 && !isset($wanted)) {                                   //$q is put here to prevent an infinite loop
        $leaves = eF_findLeaves($units);                                                            //Get the leaf nodes of the tree
        foreach ($leaves as $leaf) {
            $nodes[$leaf['parent_content_ID']]['children'][$nodes[$leaf['id']]['id']] = $nodes[$leaf['id']];

            if ($leaf['id'] == $content_ID) {                                                       //If the user asked for the tree below a specified content id, then put it in $wanted
                $wanted = $nodes[$leaf['id']];
            }
            unset($nodes[$leaf['id']]);
        }
    }
    isset($wanted) ? $nodes = array(0 => $wanted) : $nodes = $nodes[0]['children'];                 //$nodes now has either the whole tree (which was put in $nodes[0]['children'] from the loop above), or the branch under the specified content_ID (which was put in $wanted)

    $tree = array();
    $tree = eF_makeCompatibleTree($tree, $nodes, 0);                                                //Convert the tree from its multidimensional form to its flat form, which is used throughout eFront

    if (sizeof($tree) > 0) {
        $tree = eF_putInCorrectOrder($tree, $only_active);                                          //Reorder the units to match the content series
    }

    if ($GLOBALS['configuration']['caching'] && $only_active) {                                                           //If we reached here, it means that the tree was not cached, so cache it
        $cache_fields = array('name'      => $_SESSION['s_lessons_ID'].'_contentTree',
                              'value'     => serialize($tree),
                              'timestamp' => time(),
                              'expired'   => 0);
        eF_insertTableData("cache", $cache_fields);
    }
    
    return $tree;    
}


/**
* Convert primitive content tree to eFront-compatible tree
*
* This recursive function will convert the given (multidimensional) units array to the corresponding (flat) 
* efront content tree. It starts with an empty array as input.
*
* @param array $tree The efront-compatible content tree array (empty on initial call)
* @param array $nodes The primitive content array
* @param int $level The current tree level (depth) to consider
* @return array The new, efront-compatible content tree
* @deprecated
*/
function eF_makeCompatibleTree(&$tree, $nodes, $level = 0) {
    foreach($nodes as $node) {
        $new_node = array('id'        => $node['id'], 
                          'name'      => $node['name'],
                          'ctg_type'  => $node['ctg_type'],
                          'parent_id' => $node['parent_content_ID'],
                          'level'     => $level,
                          'active'    => $node['active'],
                          'data'      => $node['data']);

        if (!isset($tree[$node['previous_content_ID']])) {
            $tree[$node['previous_content_ID']] = $new_node;
        } 

        eF_makeCompatibleTree($tree, $node['children'], $level + 1);
    }
    
    return $tree;
}


/**
* Reorder tree according to content sequence
*
* This function is used to reorder the tree array, so that the array values succession 
* match the content sucession. The reordering is done based on array indexes, as returned
* by eF_makeCompatibleTree
*
* @param array $tree The content tree, as returned by eF_makeCompatibleTree
* @param bool $only_active Whether the tree should contain only active units
* @return array The correct content tree
* @version 1.1
* @deprecated 
* Changes from version 1.0 to 1.1 (2007/06/18 - venakis):
* - Added the check if the first unit is active
*/
function eF_putInCorrectOrder($tree, $only_active) {
    $current_unit    = $tree[0];
    if ($current_unit['active'] || !$only_active) {
        $correct_tree[0] = $tree[0];
    }
    unset($tree[0]);
    foreach ($tree as $node) {
        $current_unit = $tree[$current_unit['id']];
        if ($current_unit['active'] == 1 || !$only_active) {
            $correct_tree[] = $current_unit;
        }
    }
    return $correct_tree;
}



/**
* Get new content
* 
* @param string $student The student to calculate new stuff for
* @param int The lesson id
* @param bool current_period
* @version 1.0 (28/2/2005 - makriria)
* @deprecated 
*/
function eF_getNewContent($student, $lesson_ID, $type = 'content', $current_period = false)
{
    $login_limit     = 5;                                                                   //The limit of login times for the user, beyond which the content is not considered new anymore
    $timestamp_limit = 7 * 24 * 60 * 60;                                                    //The limit of time that passed since the last user login, set to a week later.
    $new_content     = array();                                                             
    
    if ($type == 'content') {

        if (!$current_period) {
            $res_content = eF_getTableData("content c, lessons l", "c.id, c.name, c.ctg_type, c.timestamp", "c.lessons_ID=l.id AND c.timestamp > ".(time() - $timestamp_limit)." AND l.id=".$lesson_ID, "c.timestamp asc");       //???? ??? ?? ??????????? ??? ?????????
        } else {
            $res_content = eF_getTableData("content c, lessons l, periods p, current_content cc", "c.id, c.name, c.ctg_type, c.timestamp", "c.lessons_ID=l.id AND c.timestamp > ".(time() - $timestamp_limit)." AND l.id=".$lesson_ID ." AND p.id=cc.periods_ID AND cc.content_ID=c.id AND p.lessons_ID=l.id AND p.lessons_ID=c.lessons_ID AND p.from_timestamp <" .time()." AND p.to_timestamp >" .time() , "c.timestamp asc");
            //$res_content = eF_getTableData("content,lessons", "content.id,timestamp", "content.lessons_ID=lessons.id AND lessons.id=". $lesson_ID,"timestamp asc");       
        }

        for ($i = 0; $i < sizeof($res_content); $i++) {                                                 
                $new_content[] = array('id'        => $res_content[$i]['id'],
                                       'timestamp' => $res_content[$i]['timestamp'],
                                       'name'      => $res_content[$i]['name'],
                                       'ctg_type'  => $res_content[$i]['ctg_type']);
                                                                                                       
        }
    }
    elseif ($type == 'news') {                                                                        
        $new_content = eF_getTableData("news","*", "(lessons_ID = 0 OR lessons_ID=".$lesson_ID .") AND timestamp > ".(time() - $timestamp_limit),"lessons_ID, timestamp asc");       

    }
    return $new_content;
}



/**
* Get the student seen content
*
* This function gets the units that the student has set as seen
* A unit is considered seen when the student clicks the corresponding icon
* below the unit content. The same way he may deignate a unit as unseen (except
* for test units).
*
* @param string $login The student login
* @param int $lessons_ID The current lesson id
* @return array An array holding the seen unit ids (including tests)
* @version 1.0
* @deprecated 
*/
function eF_getSeenContent($login, $lessons_ID)
{
    $done_content = eF_getTableDataFlat("users_to_lessons", "done_content", "users_LOGIN='".$login."' and lessons_ID=".$lessons_ID);
    $done_tests   = eF_getTableDataFlat("done_tests as dt,tests as t, content as c", "c.id", "dt.users_LOGIN='".$login."' AND t.content_ID = c.id AND c.lessons_ID = ".$lessons_ID." AND t.id=dt.tests_ID"); 
    (sizeof($done_content['done_content'][0]) > 0 && $done_content['done_content'][0]) ? $done_content = unserialize($done_content['done_content'][0])       : $done_content = array();
    sizeof($done_tests['id'][0])             > 0 ? $done_tests   = array_combine($done_tests['id'], $done_tests['id']) : $done_tests   = array();

    return ($done_content + $done_tests);
}



/**
* Calculates the lesson tree
*
* This function is used to create an array with all the lesson's units, sorted the right way, so that 
* parent-children and previous-next relationships are preserved. Each element of the array is another array,
* whose elements are holding unit information: Specifically, these elements are:
* - 'id'        : the unit id
* - 'name'      : the name of the unit
* - 'ctg_type'  : the unit type
* - 'parent_id' : the id of the unit's parent
* - 'level'     : The level of the unit
* - 'active'    : whether it is an active unit
* - 'data'      : Whether the unit has data.
* If a content id is specified, then only the tree under and including the specified unit is returned. content id
* defaults to 0, which means the entire lesson tree. We may also specify the content type, using the $ctg parameter. 
* This will result in returning a tree containing only units of the specified type. The $ctg_in_tree variable is 
* only used when $only_current or $only_done variables are set to true. It is an array that, after the function
* returns, will contain the unit types present in the list. So, if only theory and exercise units are present in
* the tree, then this variable will be equivalent to: array('theory'=>'theory', 'exercise'=>'exercise');
* <br/>Example:
* <code>
* // We name the first variable $nouse because we will not be using it
* // This call returns the full lesson tree, only active and done units.
* eF_getContentTree($nouse, $lessons_ID, 0, false, true, false, true, false);
* </code>
* 
* @param array $ctg_in_tree Lists the unit types present in the list.
* @param int $lessons_ID The lesson id
* @param int $content_ID The content id
* @param string $ctg The content type
* @param bool $only_active Shows only active units
* @param bool $only_current Shows only current units
* @param bool $only_done Shows only units done so far
* @param mixed $only_period If true, then it shows only units that belong to a currently active period. Otherwise, 
*                            if set to a number, then it shows only units assigned to the period with this id
* @param string $only_unseen Gets only units that the student with the specified login hasn't seen
* @deprecated 
* @return array The content tree
* @version 1.2.1
* Changes from version 1.2 to 1.2.1 (20/11/2005):
* - Replaced > with >= in the $only_period part, since, without it, it was displaying the first unit as clickable in the student tree, even if it wasn't eligible (i.e. out of period)
* Changes from version 1.1 to 1.2 (18/11/2005):
* - Moved the part that examines the $ctg at the end of the function body, in order to exclude units from the student theory / examples etc tree. 
*   Before that, parent units were appearing, of units not in the current period
* - Replaced > with >= in the $ctg check part
* Changes from version 1.0 to 1.1 (3/11/2005):
* - Replaced >= with > in many places
*
*/
function eF_getContentTree(&$ctg_in_tree, $lessons_ID = false, $content_ID = 0, $ctg = false, $only_active = true, $only_current = false, $only_done = false, $only_period = false, $only_unseen = false)
{
    if (!$lessons_ID) {
        return "";
    }
    if ($content_ID == "" OR $content_ID === false) {                                                   //defaults to 0
        $content_ID = 0;
    } 
    $counter = 0;
    $level   = 0;

    $tree = eF_createContentStructure($content_ID, $lessons_ID, $only_active);           //New way of getting the tree, at least 5 times faster (and many lines of code less)!

    $tree = eF_checkContentInTree($tree);                                                //Get done and current units (see function definition for more information on what "done" and "current" means)

    if ($_SESSION['s_type'] == 'student') {
        $seen_content = eF_getSeenContent($_SESSION['s_login'], $lessons_ID);
        //print_r($seen_content);
        foreach ($tree as $key => $value)
        {
            if (in_array($value['id'], $seen_content)) {
                $tree[$key]['seen']='yes';
            }
        }
    }    
/*
    foreach ($tree as $key => $value)
    {
        foreach ($seen_content as $key1 => $value1)
        {
            if ($value['id']==$value1['id'])
                $tree[$key]['seen']='yes';
        }
    }
*/
    $keep = array();

    if ($only_current) {
        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            //if (!eF_isCurrentContent($tree[$i]['id'])) {
            if (!$tree[$i]['isCurrentContent']) {
                $parent_keep = false;
                for ($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if ($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if (!$parent_keep) {
                    $tree = array_merge(array_slice($tree, 0, $i), array_slice($tree, $i + 1, sizeof($tree) - 1));
                }
            } else {
                $ctg_in_tree[$tree[$i]['ctg_type']] = $tree[$i]['ctg_type'];
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }
    }
//print_r($tree);    
    $keep = array();

    if ($only_done) {
        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            //if (!eF_isDoneContent($tree[$i]['id'])) {
            if (!($tree[$i]['isDoneContent'])) {
                $parent_keep = false;
                for($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if(!$parent_keep)
                    $tree = array_merge(array_slice($tree, 0, $i), array_slice($tree, $i + 1, sizeof($tree) - 1));
            } else {
                $ctg_in_tree[$tree[$i]['ctg_type']] = $tree[$i]['ctg_type'];
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }
    }
    
    $keep = array();
    
    if ($only_active) {
        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            //if (!eF_isDoneContent($tree[$i]['id'])) {
            if (!$tree[$i]['isDoneContent']) {
                $parent_keep = false;
                for ($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if ($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if (!$parent_keep) {
                    $tree[$i]['active'] = false;
                }
            } else {
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }
    }
    
    $keep = array();
    
    if ($only_period AND $only_period === true) {                                     
        $result = eF_getTableData("current_content", "content_ID");
        for ($i = 0; $i < sizeof($result); $i++) {
            $currentContent[$result[$i]['content_ID']] = $result[$i]['content_ID'];
        }

        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            //$res = eF_getTableData("current_content", "content_ID", "content_ID=".$tree[$i]['id']);
            //if (sizeof($res) == 0) {
            if (!isset($currentContent[$tree[$i]['id']])) {
                $parent_keep = false;
                for ($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if ($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if (!$parent_keep) {
                    $tree = array_merge(array_slice($tree, 0, $i), array_slice($tree, $i + 1, sizeof($tree) - 1));
                } else {
                    $tree[$i]['active'] = false;
                }
            } else {
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }
    } elseif ($only_period) {
        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            $res = eF_getTableData("current_content", "content_ID", "content_ID=".$tree[$i]['id']." AND periods_ID=$only_period");
            if (sizeof($res) == 0) {
                $parent_keep = false;
                $keep        = array();
                for ($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if ($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if (!$parent_keep) {
                    $tree = array_merge(array_slice($tree, 0, $i), array_slice($tree, $i + 1, sizeof($tree) - 1));
                } else {
                    $tree[$i]['active'] = false;
                }
            } else {
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }
    }
    
    $keep = array();
/*
    if ($only_unseen) {
        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            $res = eF_getTableData("logs","count(*) as times","(action='content' OR action='lessons' OR action = 'tests') AND users_LOGIN='".$only_unseen."' AND comments=".$tree[$i]['id']);
            if ($res[0]['times'] > 0 OR ($tree[$i]['data'] == false && $tree[$i]['ctg_type'] != 'tests')) {
                $parent_keep = false;
                for ($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if ($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if (!isset($tree[$i]['seen']) && $tree[$i]['ctg_type'] == 'tests') {            //This line checks against 'seen' attribute for tests, so that a test is considered 'unseen' not if it hasn't been visited, but if it hasn't been completed
                    //do nothing
                } else if (!$parent_keep) {
                    $tree = array_merge(array_slice($tree, 0, $i), array_slice($tree, $i + 1, sizeof($tree) - 1));
                } else {
                    $tree[$i]['active'] = false;
                }
            } else {
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }
    }

    $keep = array();
*/
    if ($only_unseen) {
        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            if ($tree[$i]['seen'] == 'yes') {
                $parent_keep = false;
                for ($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if ($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if (!isset($tree[$i]['seen']) && $tree[$i]['ctg_type'] == 'tests') {            //This line checks against 'seen' attribute for tests, so that a test is considered 'unseen' not if it hasn't been visited, but if it hasn't been completed
                    //do nothing
                } else if (!$parent_keep) {
                    $tree = array_merge(array_slice($tree, 0, $i), array_slice($tree, $i + 1, sizeof($tree) - 1));
                } else {
                    $tree[$i]['active'] = false;
                }
            } else {
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }
    }

    $keep = array();


    if ($ctg) {                                                                                         // ????? ???? ????????? ??????? ?? ???? ?? ctg
        $counter = 0;
        for ($i = sizeof($tree) - 1; $i >= 0; $i--) {
            if ($tree[$i]['ctg_type'] != $ctg) {
                $parent_keep = false;
                if (!isset($keep)) {
                    echo $keep = null;
                }
                for ($k = 0; $k < sizeof($keep) AND !$parent_keep; $k++) {
                    if ($tree[$i]['id'] == $keep[$k]) {
                        $parent_keep    = true;
                        $keep[$counter] = $tree[$i]['parent_id'];
                        $counter++;
                    }
                }
                if (!$parent_keep) {
                    $tree = array_merge(array_slice($tree, 0, $i), array_slice($tree, $i + 1, sizeof($tree) - 1));
                }
            } else {
                $keep[$counter] = $tree[$i]['parent_id'];
                $counter++;
            }
        }        
    }    
//    echo "<br>";print_r($tree);

    return $tree;
}


/**
* Parents of a unit
*
* This function returns an array containing the parents of a unit. 
* For example, for the unit 3.2.1, the array will hold the ids of the units 3.2.1,
* 3.2, 3 and the 0.
* <br/>Example:
* <code>
* $parents = eF_getParents(213);
* print_r($parents);
* //Returns:
* //Array
* //(
* //    [0] => 213
* //    [1] => 211
* //    [2] => 206
* //    [3] => 0
* //)
* </code>
* 
* @param int $content_ID The id of the unit
* @param array $tree The content tree
* @return array The unit's parents ids
* @version 2.0
* @deprecated 
* Changes from version 1.0 to version 2.0 (2007/05/15 - venakis):
* - Rewritten so that if $tree is specified, it doesn't perform any database queries
*/

function eF_getParents($content_ID, $tree = null, $tree_indexes = null) 
{
    if ($tree) {
        if (!$tree_indexes) {
            for ($i = 0; $i < sizeof($tree); $i++) {
                $tree_indexes[$tree[$i]['id']] = $i;
            }
        }

        $parents['id'][]   = $content_ID;
        $parents['name'][] = $tree[$tree_indexes[$content_ID]]['name'];
        
        while ($tree[$tree_indexes[$content_ID]]['parent_id'] != 0) {
            $content_ID = $tree[$tree_indexes[$content_ID]]['parent_id'];
            $parents['id'][]   = $content_ID;
            $parents['name'][] = $tree[$tree_indexes[$content_ID]]['name'];
        }
        
    } else {
        $now            = 0;
        $count          = 0;
        $parents['id'][0] = $content_ID;

        while ($now <= $count) {
            $child = $parents['id'][$now];
            $res   = eF_getTableData("content", "parent_content_ID, name", "id=$child");
            for ($i = 0; $i < sizeof($res) && $res[$i]['parent_content_ID'] != 0; $i++) {
                $parents['name'][$count] = $res[$i]['name'];
                $count++;
                $parents['id'][$count] = $res[$i]['parent_content_ID'];
            }
            $parents['name'][$count] = $res[$i]['name'];
            $now++;
        }
    }
    
    return $parents;
}

/**
* Checks if a user is eligible to access a unit, based on rules
*
* This function checks of the currently logged-in student is allowed to view a unit's content,
* based on access rules.
*
* @param int $content_ID the d of the current unit
* @return mixed true if the student is allowed to access the unit, or an explanatory message otherwise
* @version 2.0
* @deprecated
* @Changes from version 1.0 to 2.0 (2007/09/29 - venakis):
* - Rewritten so that it supports the new way of checking whether a unit is seen (through the explicit student action)
*/
function eF_checkRules($content_ID)
{
    $seen_content = eF_getSeenContent($_SESSION['s_login'], $_SESSION['s_lessons_ID']);

    $message = "";
    $parents = eF_getParents($content_ID);
    $list    = implode(",", $parents['id']);
    $rules   = eF_getTableData("rules", "rule_type, rule_content_ID, rule_option", "content_ID IN ($list) AND (users_LOGIN='*' OR users_LOGIN='".$_SESSION['s_login']."')");
    $allow   = true;

    for ($i = 0; $i < sizeof($rules); $i++) {
        if ($rules[$i]['rule_type'] == "always") {
            $allow    = false;
            $message .= _YOUHAVEBEENEXCLUDEDBYPROFESSOR.'<BR>';
        } elseif ($rules[$i]['rule_type'] == "hasnot_seen") {
            if (!in_array($rules[$i]['rule_content_ID'], $seen_content)) {
                $content  = eF_getTableData("content", "name", "id = ".$rules[$i]['rule_content_ID']);
                $allow    = false;
                $message .= _MUSTFIRSTREADUNIT.' <a href="student.php?ctg=content&view_unit='.$rules[$i]['rule_content_ID'].'">'.$content[0]['name'].'</a><br/>';
            }
        } elseif ($rules[$i]['rule_type'] == "hasnot_passed") {
            $res = eF_getTableData("tests, done_tests", "done_tests.id", "users_LOGIN='".$_SESSION['s_login']."' AND tests.content_ID=".$rules[$i]['rule_content_ID']." AND done_tests.tests_ID=tests.id AND score > ".$rules[$i]['rule_option']);
            if (!$res) {
                $content  = eF_getTableData("content", "name", "content.id=".$rules[$i]['rule_content_ID']);
                $allow    = false;
                $message .= _MUSTFIRSTTAKEATLEAST.' '.($rules[$i]['rule_option'] * 100).' % '._ATTEST.' <a href="student.php?ctg=tests&view_unit='.$rules[$i]['rule_content_ID'].'">'.$content[0]['name'].'</a><br/>';
            }
        }
    }

    if ($allow === true) {
        return ($allow);
    } else {
        return ($message);
    }
}



/**
* Checks if a user is logged in already
*
* This function checks the given login name and if that user is found logged in,
* returns true; otherwise it returns false.
*
* @param string $login The user login name
* @return bool If the user is logged in
* @version 1.1
* @deprecated
* Changes from version 1.0 to 1.1:
* - Got rid of forum
*/
function eF_userAlreadyIn($login)
{
    $result = eF_getTableData('logs', 'action', "users_LOGIN='$login' ", "timestamp desc limit 1");

    if (sizeof($result) != 0 && $result[0]['action'] != 'logout') {                                             //0 means that the user may have been just registered, so there are no ogs for him in the system
        $login_ip = eF_getTableData('logs', 'session_ip', "users_LOGIN='$login' and action = 'login'", "timestamp desc limit 1");

        if (eF_encodeIP($_SERVER['REMOTE_ADDR']) == $login_ip[0]['session_ip'] || $login_ip[0]['session_ip'] == '')  {      //If the IP of the user is the same with the one he logged in, or there is no ip recorded, log out the user.
            $user = EfrontUserFactory :: factory($login);
            $user -> logout();
            return false;
        } else {
            return true;
        }
    } else {
        return false;
    }
}





/**
* Returns the administrator's email address
*
* This function reads the configuration table in the database and returns the administrator's email
*
* @return string The administrator's email
* @version 1.0
* @deprecated. Use $GLOBALS['configuration']['system_email'] instead
*/
function eF_getAdminEmail()
{
    return $GLOBALS['configuration']['system_email'];
}


/**
* Returns whether the footer will be visible
*
* This function reads the configuration table in the database and returns true if the footer
* is to be visible
*
* @return bool Whether the footer will be visible
* @version 1.0
* @deprecated
*/
function eF_getShowFooter()
{
     return $GLOBALS['configuration']['show_footer'];
}




/**
* Convert backward slashes to forward slashes
*
* Thi function converts all the backslashes contained in a string to forward slashes.
* This is used to ensure cross-platform compatibility of the code (which, in general, uses
* forward slashes, '/').
*
* @param string $str The string to convert
* @return string The converted string
* @version 1.0
* @deprecated
*/
function eF_revertSlashes($str)
{
    $str = str_replace('\\', '/', $str);
    return $str;
}

/**
* Register a user with the system
*
* This function takes an array containing user information and stores it to the users
* database table. It also accepts two boolean parameters, corresponding to system configuration
* options. It returns a string with a success or failure message.
*
* @param array $values The user information array
* @param bool $is_automatic_activation Specifies whether new users are activated automatically.
* @param bool $is_ldap_user Specifies whether the user is ldap-based
* @return string An error or success message
* @version 1.2
* @todo Check for permissions in folder
* @todo return other than true
* @deprecated
* Changes from version 1.1 to 1.2:
* - Added if clauses and delete user on failure.
* Changes from version 1.0 to 1.1:
* - Got rid of forum
*/
function eF_registerUser($values, $is_automatic_activation, $is_ldap_user = false, $type="student")
{
    //$db -> debug = true;
    foreach ($values as $key => $value) {
        $fields_insert[$key] = $value;                                                                      //The values that will be inserted in the database
    }
    if ($type == ''){
        $fields_insert['user_type'] = "student";
    }else{
        $fields_insert['user_type'] = $type;
    }
    if($fields_insert['login'] == ''){
        $fields_insert['login'] = 'student';
    }

    if ($fields_insert['password'] == '') {
        $fields_insert['password']  = md5($fields_insert['login'].G_MD5KEY);
    } else {
        $fields_insert['password']  = md5($fields_insert['password'].G_MD5KEY);
    }

    if($fields_insert['languages_NAME'] == ''){
        $fields_insert['languages_NAME'] = $_SESSION['s_language'];
    }

    if ($is_ldap_user) {
        $fields_insert['password'] = 'ldap';                //For an LDAP user, the password always is 'ldap', so we can tell by looking at the password field that this is an LDAP user that authenticates to the LDAP server
    }

    $fields_insert['timestamp'] = time();
    if (!isset($fields_insert['active'])) {     //If the active field is not already set in the values, derive it
        if (!$is_automatic_activation) {      //Does the system permit automatic activation of new users?
            $fields_insert['pending'] = 1;
            $fields_insert['active']  = 0;
        } else {
            $fields_insert['pending'] = 0;
            $fields_insert['active']  = 1;
        }
    }
    //$fields_insert['valid_until_timestamp'] = time() + 365 * 86400;                                         //1 year

    //default avatar for new user
    $target_filename = time().'_prefix_unknown_small.png';
    copy (G_ROOTPATH.'www/images/avatars/system_avatars/unknown_small.png', G_ROOTPATH.'www/images/avatars/'.$target_filename);
    $fields_insert['avatar'] = $target_filename;

    if (eF_insertTableData("users", $fields_insert)) {                                                       //Create the new user by inserting a new entry in the users table
        if (is_dir(G_ROOTPATH.'upload/'.$values['login']) || mkdir(G_ROOTPATH.'upload/'.$values['login'])) {
            mkdir(G_ROOTPATH.'upload/'.$values['login'].'/message_attachments/');
            mkdir(G_ROOTPATH.'upload/'.$values['login'].'/message_attachments/Incoming');
            mkdir(G_ROOTPATH.'upload/'.$values['login'].'/message_attachments/Sent');
            mkdir(G_ROOTPATH.'upload/'.$values['login'].'/message_attachments/Drafts');
            mkdir(G_ROOTPATH.'upload/'.$values['login'].'/projects');
            $fields_insert = array('name'        => 'Incoming',
                                   'users_LOGIN' => $values['login'],
                                   'parent_id'   => 0);
            eF_insertTableData("f_folders", $fields_insert);


            $fields_insert = array('name'        => 'Sent',
                                   'users_LOGIN' => $values['login'],
                                   'parent_id'   => 0);
            eF_insertTableData("f_folders", $fields_insert);


            $fields_insert = array('name'        => 'Drafts',
                                   'users_LOGIN' => $values['login'],
                                   'parent_id'   => 0);
            eF_insertTableData("f_folders", $fields_insert);

            return true;
        } else {
            eF_deleteTableData("users", "login='".$values['login']."'");            //Delete inserted user in case of failure
            return false;
        }
    } else {
        return false;
    }

}

/**
* Delete user
*
* This function deletes the designated user
* @param string $login The user to delete
* @return bool true if the user was deleted
* @todo Ask if to delete forum data
* @version 1.0
*/
function eF_deleteUser($login) {
    if (eF_checkParameter($login, 'login')) {
        $user = eF_getTableData("users", "user_type, avatar", "login='".$login."'");

        eF_deleteTableData("users", "login='".$login."'");
        eF_deleteTableData("comments", "users_LOGIN='".$login."'");
        eF_deleteTableData("logs", "users_LOGIN='".$login."'");
        eF_deleteTableData("rules", "users_LOGIN='".$login."'");
        eF_deleteTableData("users_to_lessons", "users_LOGIN='".$login."'");
        eF_deleteTableData("scorm_data", "users_LOGIN='".$login."'");

        $result          = eF_getTableData("done_tests", "id", "users_LOGIN='".$login."'");
        $done_tests_list = eF_makeListIDs($result);
        if ($done_tests_list) {
            eF_deleteTableData("done_questions", "done_tests_ID IN ($done_tests_list)");
        }
        eF_deleteTableData("done_tests", "users_LOGIN='".$login."'");

        eF_deleteTableData("f_folders", "users_LOGIN='".$login."'");
        eF_deleteTableData("f_messages", "users_LOGIN='".$login."'");
        eF_deleteTableData("f_personal_messages", "users_LOGIN='".$login."'");
        eF_deleteTableData("chatmessages", "users_LOGIN='".$login."'");

        if ($user[0]['user_type'] != 'administrator') {                    //Delete chat and some other data, only if the users is not an administrator, otherwise you risk loosing much useful data
            eF_deleteTableData("groups", "users_LOGIN='".$login."'");
            eF_deleteTableData("chatrooms", "users_LOGIN='".$login."'");
        }

        if (is_dir(G_UPLOADPATH.$login)) {                            //Delete personal messages folder from system directory
            eF_deleteFolder(G_UPLOADPATH.$login);
        }

        if (is_file(G_AVATARSPATH.$user[0]['avatar'])) {                    //Delete user avatar
            unlink(G_AVATARSPATH.$user[0]['avatar']);
        }

        return true;
    } else {
        return false;
    }
}


/**
* Delete a personal message
*
* This function is used to delete a message, including any attachments it may have
*
* @param int $msg_id The message id
* @return bool True if the deletion was succesful
* @version 0.1
* @deprecated
*/
function eF_deletePersonalMessage($msg_id) {
    if (eF_checkParameter($msg_id, 'id')) {
        $res = eF_getTableData("f_personal_messages", "users_LOGIN, attachments, f_folders_ID", "id=".$msg_id);

        if ($_SESSION['s_login'] == $res[0]['users_LOGIN'] || $_SESSION['s_type'] == 'administrator') {
            eF_deleteTableData("f_personal_messages", "id=".$msg_id);

            if ($res[0]['attachments'] != '') {
                $attached_file = new eF_File($res[0]['attachments']);
                $attached_file -> delete();
            }

            return true;
        } else {
            $message = 'You cannot delete this message';
            return $message;
        }
    } else {
        $message = _INVALIDID;
        return $message;
    }
}

/**
* Move a personal message
*
* This function is used to move a message, including any attachments it may have
*
* @param int $msg_id The message id
* @param int $target_folder_id the target folder id
* @return bool True if the move was succesful
* @version 0.1
* @deprecated
*/
function eF_movePersonalMessage($msg_id, $target_folder_id) {
    if (eF_checkParameter($msg_id, 'id') && eF_checkParameter($target_folder_id, 'id')) {
        $res = eF_getTableData("f_personal_messages", "users_LOGIN, attachments, f_folders_ID", "id=".$msg_id);
        $folder_name = eF_getTableData("f_folders", "name", "users_LOGIN='".$_SESSION['s_login']."' and id=".$target_folder_id);

        if ($_SESSION['s_login'] == $res[0]['users_LOGIN'] || $_SESSION['s_type'] == 'administrator') {
            eF_updateTableData("f_personal_messages", array("f_folders_ID" => $target_folder_id), "id=".$msg_id);

            if ($res[0]['attachments'] && sizeof($folder_name) > 0) {
                $attachment = new eF_File($res[0]['attachments']);
                $attachment -> move(G_UPLOADPATH.$_SESSION['s_login'].'/message_attachments/'.$folder_name[0]['name'].'/');


/*
                $attachments = unserialize($res[0]['attachments']);
                foreach($attachments as $attach) {
                    rename($attach, G_UPLOADPATH.$_SESSION['s_login'].'/message_attachments/'.$folder_name[0]['name'].'/'.basename($attach));
                    $new_attachments[] = G_UPLOADPATH.$_SESSION['s_login'].'/message_attachments/'.$folder_name[0]['name'].'/'.basename($attach);
                }

                eF_updateTableData("f_personal_messages", array("attachments" => serialize($new_attachments)), "id=".$msg_id);
*/
            }
            return true;
        } else {
            $message = 'You cannot move this message';
            return $message;
        }
    } else {
        $message = _INVALIDID;
        return $message;
    }
}

/**
* Print a select box
*
* This function prints select options based on the $values array.
* If $labels is set, then it is used as the option label.
*
* @param array $values The option values
* @param array $labels The option labels
* @return string The html code of the select options
* @version 0.1
* @deprecated 
*/
function eF_printSelect($values, $labels = false) {
    $str = '';
    if ($labels === false || sizeof($labels) != sizeof($values)) {
        $labels = $values;
    }

    for($i = 0; $i < sizeof($values); $i++) {
        $str .= '
            <option value = "'.$values[$i].'">'.$labels[$i].'</option>';
    }
    return $str;
}

/**
* Get recent forum messages
*
* This function reads recent forum messages from the forum category with the same name as the current lesson.
* It returns an array with the forum title and information about the message, which can be used to access it.
* If a lesson is not specified, the current (session) is considered.
* <br/>Example:
* <code>
* $messages = eF_getForumMessages($lessons_ID);
* print_r($messages);
* //Returns:
*Array
*(
*    [0] => Array
*        (
*            [title] => Some message
*            [id] => 53
*            [topic_id] => 27
*            [users_LOGIN] => periklis
*            [timestamp] => 1125765345
*        )
*
*    [1] => Array
*        (
*            [title] => Another message
*            [id] => 54
*            [topic_id] => 27
*            [users_LOGIN] => periklis
*            [timestamp] => 1125752345
*        )
*
*    [2] => Array
*        (
*            [title] => This is a large mess...
*            [id] => 55
*            [topic_id] => 27
*            [users_LOGIN] => admin
*            [timestamp] => 1125751543
*        )
*
*)
* </code>
*
* @param int $lessons_ID The lesson id
* @param int $limit The results limit
* @return array The messages array
* @version 1.1
* Changes from 1.0 to 1.1 (15/11/2005):
* - Added $limit parameter
*/
function eF_getForumMessages($lessons_ID = false, $limit = false)
{
    if (!$lessons_ID) {
        $lessons_ID = $_SESSION['s_lessons_ID'];
    }

    if ($limit && eF_checkParameter($limit, 'uint')) {
        $limit_str = ' limit '.$limit;
    } else {
        $limit_str = '';
    }

    $messages_array = array();
    if ($lessons_ID) {
        $messages_array = eF_getTableData("f_messages m, f_topics t, f_forums c", "m.title, m.id, t.id as topic_id, m.users_LOGIN, m.timestamp", "c.lessons_ID=".$lessons_ID." AND t.f_forums_ID=c.id AND m.f_topics_ID=t.id", "m.timestamp desc".$limit_str);
    }
    return $messages_array;
}

/**
* Get unread personal messages
*
* This function gets the unread personal messages from the user's inbox. It returns an array with
* the message title and information about the message, which can be used to access it. If $login
* is not set, then messages for the current (session) user are returned.
* <br/>Example:
* <code>
* $messages = eF_getPrivateMessages();
* print_r($messages);
* //Returns:
*Array
*(
*    [0] => Array
*        (
*            [title] => Hello!
*            [id] => 26
*        )
*
*    [1] => Array
*        (
*            [title] => It's me again!
*            [id] => 24
*        )
*
*    [2] => Array
*        (
*            [title] => This is a large mess...
*            [id] => 23
*        )
*
*)
* </code>
*
* @param string $login The user login name
* @param int $limit The results limit
* @return array The messages array
* @version 1.1
* Changes from 1.0 to 1.1 (15/11/2005):
* - Added $limit parameter
*/
function eF_getPersonalMessages($login = false, $limit = false) {

    if (!$login) {
        $login = $_SESSION['s_login'];
    } elseif (sizeof(eF_getTableData("users", "login", "login=$login")) == 0) {                             //This user does not exist
        return array();
    }

    if ($limit && eF_checkParameter($limit, 'uint')) {
        $limit_str = ' limit '.$limit;
    } else {
        $limit_str = '';
    }

    $messages_array = eF_getTableData("f_personal_messages pm, f_folders", "pm.title, pm.id, pm.timestamp, pm.sender", "pm.users_LOGIN='".$login."' and f_folders_ID=f_folders.id and f_folders.name='Incoming' and viewed='no'", "pm.timestamp desc".$limit_str);         //Get unseen messages in Incoming folder

    return $messages_array;
}



/**
* Gets dates offset for a student
*
* This functions is used to add an offset to all dates concerning a student that has 
* enrolled late to the system. The amount of time he enrolled after the first period 
* started is added to the current time, in order to normalize the content flow per period
*
* @return int The date offset is an integer to be added to a timestamp
* @version 1.0.1
* Changes from version 1.0 to 1.0.1:
* - Fixed bug: it always reported offset.
* @deprecated 
*/
function eF_getOffset()
{
    if ($GLOBALS['currentLesson'] -> options['dynamic_periods']) {
        $res           = eF_getTableData("users_to_lessons", "from_timestamp", "lessons_ID=".$_SESSION['s_lessons_ID']." AND users_LOGIN='".$_SESSION['s_login']."'");
        $new_timestamp = $res[0]['from_timestamp'];
        if ($new_timestamp > 0) {
            $periods       = eF_getTableData("periods", "id, name, from_timestamp, to_timestamp", "lessons_ID=".$_SESSION['s_lessons_ID'], "from_timestamp ASC");
            if (sizeof ($periods) > 0) {
                $old_timestamp = $periods[0]['from_timestamp'];
                $temp          = $new_timestamp - $old_timestamp;
                if ($new_timestamp > $old_timestamp) {
                    $offset = $new_timestamp - $old_timestamp;
                }
            }
        }
    }
    if (!isset($offset)) {
        $offset = 0;
    }
    return $offset;
}

/**
* Checks if a unit is current and active
*
* This function will check if a unit is both active and current. This is how it works: If a lesson does not have any periods defined, then 
* all units are considered active and current, so this function returns true for every unit. If a lesson has periods defined, then the funtion 
* returns true if the specified unit is part of at least one of the *current* periods; otherwise, it returns false, meaning that this unit does 
* not belong to any current period (even if it belongs to a period that is not current)
* Note: as of eFront 3.0 this function is deprecated and you should use eF_checkCurrentContentInTree() instead
*
* @param int $id The unit id
* @return bool true if the unit is currently active 
* @version 1.0
* @see eF_checkCurrentContentInTree()
* @deprecated
*/
function eF_isDoneContent($id)
{

    $time   = time();
    $offset = eF_getOffset();
    $res    = eF_getTableData("current_content,periods,content", "content_ID", "content_ID=$id AND current_content.periods_ID=periods.id AND periods.from_timestamp+$offset<=$time AND content.id=current_content.content_ID AND content.active=1");
    if (isset($res[0]['content_ID'])) {
        return true;
    } else { 
        $res1 = eF_getTableData("periods,content", "count(*)", "periods.lessons_ID=content.lessons_ID AND content.id=$id"); 
        if ($res1[0]['count(*)'] == 0) {
            return true;
        } else {
            return false;
        }
    }
}

/**
* Return number of current units 
*
* This function calculates the number of units of the specified type that are current.
* <br/> Example:
* <code>
* echo eF_numCurrentContent('theory');      //returns 5
* </code>
*
* @param string $ctg_type The content type, can be 'theory', 'examples', 'projects', 'tests'
* @return int The number of units of this type
* @version 1.0
* 22/12/2005
* @deprecated 
*/
function eF_numCurrentContent($ctg_type, $lesson = false)      // makriria. add 2nd parameter
{
    if($lesson == false) {
        $lesson = $_SESSION['s_lessons_ID'];
    } 

    if($ctg_type == "projects"){ // new way of counting new type of exercises 2007/08/06
        $result = eF_getTableData("projects,users_to_projects", "id", "lessons_ID=".$lesson." AND projects_ID=id AND users_LOGIN='".$_SESSION['s_login']."'");
    }else{
        $time = time();
        $offset = eF_getOffset();
        $result = eF_getTableData("periods", "id", "lessons_ID=".$lesson);
        if (sizeof($result) > 0) {
            $result = eF_getTableData("current_content,periods,content", "distinct content.id", "ctg_type='$ctg_type' AND periods.lessons_ID = ".$lesson." AND current_content.periods_ID=periods.id AND periods.from_timestamp+$offset<=$time AND periods.to_timestamp+$offset>$time AND content.id=current_content.content_ID AND content.active=1");
        } else {
            $result = eF_getTableData("content", "distinct content.id", "ctg_type='$ctg_type' AND lessons_ID=".$lesson." AND active=1");
        }
    }
    return sizeof($result);
}


/**
* Children of a unit
*
* This function returns an array containing the children of a unit. If a lesson id is specified *and*
* the unit content id is 0, then all the units which are part of that lesson are returned.
* <br/>Example:
* <code>
* $unit_children = eF_getChildren(3);           //returns an array with the ids of all the children units of unit with id 3
* $lesson_units  = eF_getChildren(0, 1);        //returns an array with the ids of all the units contained in the lesson with id 1
* </code>
* 
* @param int $content_ID The id of the unit
* @param int $lessons_ID The id of the lesson. It is concidered only if $content_ID is 0
* @return array The unit's children ids
* @version 1.2
* Changes from 1.1 to 1.2 (2007/10/01 - venakis):
* - Fixed bug in children calculation (it returned fewer than normal)
* Changes from 1.0 to 1.1 (18/9/05):
* - Added the unset command before the return 
* @deprecated
*/
function eF_getChildren($content_ID, $lessons_ID = false, $tree = null, $tree_indexes = null) 
{

    if ($tree) {
        if (!$tree_indexes) {
            for ($i = 0; $i < sizeof($tree); $i++) {
                $tree_indexes[$tree[$i]['id']] = $i;
            }
        }

        if ($content_ID == 0) {
            $children = array_keys($tree_indexes);
        } else {        
            $children[] = $content_ID;
            $size       = sizeof($tree);
            $found      = true;
            $count      = 0;
            
            //for ($i = 0; $size > 0 && $found == true; $i++) {
            while($size > 0 && $found == true) {
                foreach ($tree as $key => $node) {
                    $i++;
                    if (in_array($node['parent_id'], $children)) {
                        $children[] = $node['id'];
                        unset($tree[$key]);
                        $found = true;
                        $i = 0;
                    } 
                    $size = sizeof($tree);
                    if ($i == $size) {
                        $found = false;
                    }
                }
            }
            
            unset($children[0]);                                                 //This is the unit itself.
        }
    } else {        
        $now            = 0;
        $count          = 0;
        $children[0] = $content_ID;

        while ($now <= $count) {
            if ($content_ID == 0 AND $lessons_ID) {
                $add_sql = "AND lessons_ID = $lessons_ID";
            } else {
                $add_sql = "";
            }
            $parent = $children[$now];
            $res    = eF_getTableData("content", "id", "parent_content_ID=$parent $add_sql", "previous_content_ID");

            for ($i = 0; $i < sizeof($res); $i++) {
                $count++;
                $children[$count] = $res[$i]['id'];
            }
            $now++;
        }

        unset($children[0]);                                                 //This is the unit itself.
    }
    
    return $children;
}

/**
* Returns unit levels
*
* This function accepts a content tree as an argument and returns unit levels in an array.
* Specifically, for a tree structure, similar to the one returned by eF_getContentTree(),
* creates an array entry where the key is the unit id and the value is the corresponding level
* This function is used from within eF_getContentTree()
*
* @param $tree The content tree
* @return array An array where each key is a unit and each value is its level inside the tree
* @see eF_getContentTree()
* @version 1.0
* @deprecated 
*/
function eF_getLevels($tree)
{
    for ($i = 0; $i < sizeof($tree); $i++) {
        $levels[$tree[$i]['id']] = $tree[$i]['level'];
    }
    return $levels;
}

/**
* Check if a unit is linked form another lesson
*
* When we copy units from one lesson to another, then a special strin is appended to the data, '<:link:>' plus the content_ID.
* This function checks the data to see if it is linked to another unit.
*
* @param string $data the unit content
* @return bool True if the unit is linked to another.
* @version 1.0
* @deprecated 
*/
function eF_isLinked($data)
{
    if(mb_substr($data, 0, 8) == "<:link:>") {
        return true;
    } else {
        return false;
    }
}


/**
* Converts a timestamp interval to time interval
*
* This function is used to convert the interval specified into a human - readable format.
* <br/> Example:
* <code>
* $timestamp_from = mktime(10, 34, 27, 10, 7, 2005);
* $timestamp_to = mktime(11, 47, 4, 10, 7, 2005);
* $interval = $timestamp_to - $timestamp_from;
* print_r(eF_convertIntervalToTimeFull($interval));
* </code>
* Returns:
* <code>
*Array
*(
*    [weeks] => 0
*    [days] => 0
*    [hours] => 1
*    [minutes] => 12
*    [seconds] => 37
*)
* </code>
* @deprecated 
*/
function eF_convertIntervalToTimeFull($interval)
{
    $seconds = $interval % 60;
    $minutes = (($interval - $seconds) / 60) % 60;
    $hours   = ($interval - $seconds - ($minutes * 60)) / 3600 % 24;
    $days    = floor(($interval - $seconds - ($minutes * 60) - ($hours*24))/ 86400 % 7);
    $weeks   = floor(($interval - $seconds - ($minutes * 60) - 7*($hours*24)) / 604800);
    //return "$interval $string:$weeks:$days:$hours:$minutes:$seconds";
    $string = null;
    if($weeks == 1)         $string .= ' '.$weeks.' '._WEEKs.',';
    elseif($weeks > 1)      $string .= ' '.$weeks.' '._WEEKS.',';
    if($days == 1)          $string .= ' '.$days.' '._DAY.',';
    elseif($days > 1)       $string .= ' '.$days.' '._DAYS.',';
    if($hours == 1)         $string .= ' '.$hours.' '._HOUR.',';
    elseif($hours > 1)      $string .= ' '.$hours.' '._HOURS.',';
    if($minutes == 1)       $string .= ' '.$minutes.' '._MINUTE.',';
    elseif($minutes > 1)    $string .= ' '.$minutes.' '._MINUTES.',';
    if($seconds > 0)        $string .= ' '.$seconds.' '._SECONDS;

    return array('string' => $string,'weeks' => $weeks, 'days' => $days, 'hours' => $hours, 'minutes' => $minutes, 'seconds' => $seconds);
}

/**
* Processes a message string
*
* This function gets a string as an argument, that comes from either a message editor (forum or personal), or the chat text box.
* It then formats its according to some modifiers that maybe present: [b][/b] for bold, [i][/i] for italics, [u][/u] for underlined
* and [link=<target>][/link] for a link reference. It also converts text smilies to their corresponding gif icons.
*
* @param string $msg The message to process
* @return string The processed message
* @version 1.0 (20/11/2005)
* @deprecated 
*/
function eF_messageProcess($msg)
{
    $search  = array("/(.*)\n(.*)/U",
                     "/\[b\](.*)\[\/b\]/U",
                     "/\[i\](.*)\[\/i\]/U",
                     "/\[u\](.*)\[\/u\]/U",
                     "/\040/U",
                     "/\[link=(.*)\](.*)\[\/link\]/U",
                     "/\[quote\](.*)\[\/quote\]/");
    $replace = array("\$1<br>\$2",
                     "<b>\$1</b>",
                     "<i>\$1</i>",
                     "<u>\$1</u>",
                     "&nbsp;",
                     "<a href = \"javascript:void(0)\" onclick = \"popUp(\'\$1\', 600, 400, 1)\">\$2</a>",
                     "<table><tr><td style = \"background-color:lightblue\">\$1</td></tr></table>");

    $new_msg = preg_replace($search, $replace, $msg);
    $new_msg = eF_convertTextToSmilies($new_msg);

    return $new_msg;
}


/**
* 18_1_2007 add case for periods...makriria.. now, in lessons_list op, it appears only current content numbers
* @deprecated 
*/
function getLessonContentUnits($lessons_ID = false, $nonempty = false) {
    if (!$lessons_ID) {
        $lessons_ID = $_SESSION['s_lessons_ID'];
    }
    ($nonempty) ? $nonempty = " AND content.data != '' " : $nonempty = "";

    $time = time();
    $offset = eF_getOffset();
    $result = eF_getTableData("periods", "id", "lessons_ID=".$lessons_ID);
    if (sizeof($result) > 0) {
        $units = eF_getTableData("current_content,periods,content", "count(*)", "ctg_type != 'tests' AND periods.lessons_ID = ".$lessons_ID." AND current_content.periods_ID=periods.id AND periods.from_timestamp+$offset<=$time AND periods.to_timestamp+$offset>$time AND content.id=current_content.content_ID AND content.active=1".$nonempty);

        $tests = eF_getTableData("current_content,periods,content", "count(*)", "ctg_type = 'tests' AND periods.lessons_ID = ".$lessons_ID." AND current_content.periods_ID=periods.id AND periods.from_timestamp+$offset<=$time AND periods.to_timestamp+$offset>$time AND content.id=current_content.content_ID AND content.active=1");

    } else {
        $units = eF_getTableData("content", "count(*)", "ctg_type != 'tests' and lessons_ID = $lessons_ID and active = 1".$nonempty);
        $tests = eF_getTableData("content", "count(*)", "ctg_type = 'tests' and lessons_ID = $lessons_ID and active = 1");
    }


    return array('units' => $units[0]['count(*)'], 'tests' => $tests[0]['count(*)']);
}



/**
* Get number of unread messages
*
* This function returns the number of a user's unread messages.
* If $login is not set, the current user is assumed.
*
* @param string $login The user to check messages for
* @return int The number of unread messages
* @version 1.0 (9/12/2005)
* @deprecated 
*/
function eF_getUnreadMessagesNumber($login = false) {
    if (!$login) {
        $login = $_SESSION['s_login'];
    }

    $messages = eF_getTableData("f_personal_messages pm, f_folders", "count(*)", "pm.users_LOGIN='".$login."' and viewed='no' and f_folders_ID=f_folders.id and f_folders.name='Incoming'");

    return $messages[0]['count(*)'];
}


/**
* Returns questions of a test (for unsolved test)in correct order
*
* This function returns the questions of a test in correct order
* @param id $tests_ID The test id
* @return array with the questions of test
* in new format there is previous_question_ID field. If there is one row with previous_question_ID=0, then there is defined order of questions. Otherwise there is no order defined and the array returned in the old way.
* @version 1.0
* @Date 2007/03/16
* @deprecated 
*/
function eF_getTestQuestions($tests_ID, $shuffle = false){

  if ($shuffle == true){
     $questions_order = eF_getTableData("questions, tests_to_questions", "questions.*,tests_to_questions.weight AS weight", "tests_to_questions.tests_ID=$tests_ID AND tests_to_questions.questions_ID=questions.id","questions.content_ID, questions.id ASC");
     shuffle($questions_order);
 } else {

    $res = eF_getTableData("questions,tests_to_questions","questions.*,tests_to_questions.weight AS weight,questions_ID","tests_to_questions.tests_ID=$tests_ID AND tests_to_questions.questions_ID=questions.id AND previous_question_ID=0");
    if (sizeof($res) == 1) {  //new format of tests_to_questions
        $previous_ques_ID = $res[0]['questions_ID'];
        $questions_order[] = $res[0];
        while (sizeof($res)!=0) {
            $res = eF_getTableData("questions,tests_to_questions","questions.*,tests_to_questions.weight AS weight,questions_ID","tests_to_questions.tests_ID=$tests_ID AND tests_to_questions.questions_ID=questions.id AND previous_question_ID=".$previous_ques_ID);
            if (sizeof($res)!=0 ){
                $previous_ques_ID = $res[0]['questions_ID'];
                $questions_order[] = $res[0];

            }
        }
    } else { //old format of tests_to_questions
        $questions_order = eF_getTableData("questions, tests_to_questions", "questions.*,tests_to_questions.weight AS weight", "tests_to_questions.tests_ID=$tests_ID AND tests_to_questions.questions_ID=questions.id","questions.content_ID, questions.id ASC");
    }
  }
    return $questions_order;
}


/**
 * 
 * @deprecated 
 * @param unknown_type $password
 * @return unknown
 */
function eF_passwdCheck($password){
    if( mb_strlen($password) < 6){
        return false;
    }
    return true;
}

/**
* Return the custom css
*
* This function checks whether there is a custom css file set and returns its name.
*
* @return string The custom CSS name
* @version 0.1
* @deprecated
*/
function eF_getCustomCss() {
    $css = eF_getTableData("configuration", "value", "name='css'");
    if ($css && eF_checkParameter($css[0]['value'], 'filename') && is_file(G_ROOTPATH.'www/css/custom_css/'.$css[0]['value'])) {
        return $css[0]['value'];
    } else {
        return 'normal.css';
    }
}


/**
* Get student Progress
*
* This function can be used to get the progress information for every student lesson
* Example:<br>
* <code>
* $progress = eF_getStudentProgress('jdoe');        //$progress now holds an array of the form 'lessons_ID' => 'progress' for every student lesson
* $progress = eF_getStudentProgress('jdoe', 13);    //$progress now holds a 1 element array of the form 'lessons_ID' => 'progress', for the lesson with id 13
* $progress = eF_getStudentProgress('jdoe', array(13,15,17));    //$progress now holds a 3-elements array of the form 'lessons_ID' => 'progress', for the lessons specified
* </code>
*
* @param string $login The student login
* @param string $lessons The array of lessons id (may be a single value for just 1 lesson)
* @return array The progress array
* @version 1.0
* @deprecated 
*/
function eF_getStudentProgress($login, $lessons = false) {
    if (!$lessons) {                                                                                    //If $lessons is not specified, all lessons are assumed
        $lessons = eF_getTableDataFlat("users_to_lessons", "lessons_ID", "users_LOGIN='".$login."'");   //Get all user lessons
    } elseif (!is_array($lessons)) {                                                                    //If $lessons is a single value, convert it to 1-element array
        $lessons = array('lessons_ID' => array($lessons));
    }

    $progress = array();                                                                                //Initialize variable, so it never returns undefined value
    foreach ($lessons['lessons_ID'] as $lessons_ID) {                                                   //Get the progress for each lesson id
        $content      = getLessonContentUnits($lessons_ID, true);                                             //Get the content units
        $seen_content = eF_getSeenContent($login, $lessons_ID);                                         //Get the seen content
        array_sum($content) > 0 ? $progress[$lessons_ID] = round(100 - 100 * (array_sum($content) - sizeof($seen_content)) / array_sum($content)) : $progress[$lessons_ID] = '0';   //Calculate the progress percentage
    }

    return $progress;
}


/**
* Get basic type of user  ...which is enum(student,professor,administrator)
*
* This function returns the basic user type  for the given lesson
*
* @param login $login, defaults to corresponding session variable
* @param int $lesson_id the current lesson id, defaults to corresponding session variable
* @return basic user_type of login
* @version 2.6
* @from now on, basic user_type is lesson specific.if value in users_to_lesson is NULL (because of an import), we take default basic user type from table users
* @deprecated 
*/

function eF_getUserBasicType($login = false, $lessons_ID = false){

    if($login == false){
        $login = $_SESSION['s_login'];
    }
    if($lessons_ID == false){
        if (isset($_SESSION['s_lessons_ID']))
            $lessons_ID = $_SESSION['s_lessons_ID'];
    }
    $user = EfrontUserFactory :: factory($login);
    try{
        $lesson = new EfrontLesson($lessons_ID);
        $role = $user -> getRole($lesson -> lesson['id']);
    }
    catch (Exception $e){
        $role = $user -> user['user_type'];
    }

    if ($role != "student" && $role != "professor" && $role != "administrator" ){
        $res2 = eF_getTableData("user_types","basic_user_type","user_type='".$role."'");
        $user_type = $res2[0]['basic_user_type'];
    }else{
        $user_type = $role;
    }

    return $user_type;
}

/**
* Create new lesson
*
* This function is used to create a new lesson
*
* @param array $fields_insert the lesson database fields
* @return array An array with the first element holding the id, the second the message and the third the message type
* @deprecated 
*/

function eF_createLesson($fields_insert) {

    $id = eF_insertTableData("lessons", $fields_insert);

    if ($id) {
        $message      = _SUCCESFULLYCREATEDLESSON;
        $message_type = 'success';

        EfrontSearch :: insertText($fields_insert['name'], $id, "lessons", "data");
        EfrontSearch :: insertText($fields_insert['name'], $id, "lessons", "title");

        $fields_forum = array('title'       => $fields_insert['name'],
                              'lessons_ID'  => $id,
                              'parent_id'   => 0,
                              'status'      => 'public',
                              'users_LOGIN' => isset($_SESSION['s_login']) ? $_SESSION['s_login'] : 'admin',
                              'comments'    => '');

        eF_insertTableData("f_forums", $fields_forum);

        $fields_chat = array('name'             => $fields_insert['name'],
                             'create_timestamp' => time(),
                             'users_LOGIN'      => $_SESSION['s_login'],
                             'type'             => 'public',
                             'active'           => 1,
                             'lessons_ID'       => $id);

        eF_insertTableData("chatrooms", $fields_chat);

        $folder  = G_LESSONSPATH.$id;
        if (!(is_dir($folder))) {
            if (!(mkdir($folder, 0700))) {
                $message      = _THELESSONFOLDERCOULDNOTBECREATED;
                $message_type = 'failure';
                EfrontLessson::deleteLesson($id);
                $id = false;
            }
        } else {
            $message      = _THELESSONNOTCREATEDFOLDERSAMENAME.': '.$id.'. '._PLEASEDELETEFOLDERSORCONTACTADMIN;
            $message_type = 'failure';
            EfrontLessson::deleteLesson($id);
            $id = false;
        }
    } else {
            $message      = _SOMEPROBLEMOCCURED;
            $message_type = 'failure';
            $id = false;
    }

    return array($id, $message, $message_type);

}


/**
* Set the lesson parameters
*
* This function is used to read any specific lesson parameters stored in the database and
* assign them to the session.
*
* @return bool True if succes
* @version 1.0
* @deprecated
*/
function eF_setLessonParameters() {

    $result = eF_getTableData("lessons", "options", "id=".$_SESSION['s_lessons_ID']);                                      // Get the lesson options (eg if the chat and forum are activated)
    if ($result[0]['options'] != "") {                                                                                     //If there are no specific options for this lesson, get default options
        $GLOBALS['currentLesson'] -> options = unserialize($result[0]['options']);
    } else {
        $GLOBALS['currentLesson'] -> options = $GLOBALS['DEF_OPTIONS'];
    }

    return true;
}

/**
* Set the role parameters
*
* This function sets the session user parameters that define user privileges
* based on its user type (role)
*
* @return bool true if success
* @version 1.0
* @deprecated
*/
function eF_setRoleParameters() {

    $user = EfrontUserFactory :: factory($_SESSION['s_login']);
    try{
        $lesson = new EfrontLesson($_SESSION['s_lessons_ID']);
        $role = $user -> getRole($lesson);
    }
    catch (Exception $e){
        $role = $user -> user['user_type'];
    }
    $_SESSION['s_role'] = $role;
    $basic_type = eF_getUserBasicType();

    $result = eF_getTableData("user_types", "characteristics", "user_type='".$role."'");

    if (sizeof($result) > 0 && $result[0]['characteristics'] != "" && $role != $basic_type) {
        $_SESSION['s_role_options'] = unserialize($result[0]['characteristics']);
    } else {
        $_SESSION['s_role_options'] = $GLOBALS['DEF_ROLE_OPTIONS'];
    }

    return true;
}


/**
 * 
 * @deprecated 
 * @param unknown_type $tests_content_ID
 * @return unknown
 */
function eF_testExport($tests_content_ID){
    $res = eF_getTableData("tests", "id", "content_ID=".$tests_content_ID);
    $tests_ID = $res[0]['id'];
    $test_users = eF_getTableData("users_to_done_tests utdt","utdt.users_LOGIN","utdt.tests_ID=".$tests_ID);
    for($i = 0 ; $i < sizeof($test_users) ; $i ++){
        $data[$i] = array('login' => $test_users[$i]['users_LOGIN'],
                     'info'  => eF_getTableData("done_tests dt,done_questions dq,tests_to_questions tq,questions q,users u","q.text,q.options,dq.answer,dt.score,tq.weight,u.name,u.surname,u.login","dt.tests_ID=".$tests_ID." AND dt.users_LOGIN=\"".$test_users[$i]['users_LOGIN']."\" AND dt.tests_ID = tq.tests_ID AND dq.questions_ID = tq.questions_ID AND q.id = dq.questions_ID AND q.id = tq.questions_ID AND u.login = dt.users_LOGIN"));
    }
    return $data;
}



/**
* prints header - why this is not a smarty template?
*
* @version 1.0
* @DEPRECATED!!!
*/

function eF_printHeader($editor = false)
{
    global $path, $COLOR, $ctg;

    //$marginstr = isset($_POST['standalone'])? "" : " style = 'margin-left: -5px;'"; 
    //$marginstr = "style = 'margin-left: -5px;'";
    $marginstr = "style = 'margin-left:0px; margin-right:2px; margin-top:4px; margin-bottom:0px'";
    print ' 
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 transitional//EN">
      <HTML><HEAD>
      <meta http-equiv="Content-Language" content="'._HEADERLANGUAGETAG.'" />
      <TITLE>eFront - '._THENEWFORMOFADDITIVELEARNING.'</TITLE>
      <link rel="shortcut icon" href="images/favicon.ico" >
      <link rel="icon" href="images/favicon.gif" type="image/gif" >
      <META http-equiv="keywords" content="education" />
      <META http-equiv="description" content="Collaborative Elearning Platform" />
      <META http-equiv="Content-Type" content="text/html; charset=utf-8"/>
      <META http-equiv="Cache-Control" content="no-cache" />
      <META http-equiv="Pragma" content="no-cache" />
      <META http-equiv="Expires" content="0" />
    <LINK rel="stylesheet" type="text/css" href="css/css_global.css" />   
    <LINK rel="stylesheet" type="text/css" href="css/css_global_temp.css" />   
    ';
    $css = eF_getTableData("configuration", "value", "name='css'");
    $css = $css[0]['value'];
    if ($css && eF_checkParameter($css, 'filename') && is_file(G_ROOTPATH.'www/css/custom_css/'.$css)) {
        print '<LINK rel="stylesheet" type="text/css" href="css/custom_css/'.$css.'" />';
    } else {
        print '<LINK rel="stylesheet" type="text/css" href="css/custom_css/normal.css" />';
    }    

    print '<LINK rel="stylesheet" type="text/css" href="slashfiles/menu.css" />
    <LINK rel="stylesheet" type="text/css" href="css/drag-drop-folder-tree.css" />
    <LINK rel="stylesheet" type="text/css" href="css/context-menu.css" />
    <LINK rel="stylesheet" type="text/css" href="css/tabber.css" />';
    
    if($editor == true) {
     
        print '
        <script language="javascript" type="text/javascript" src="editor/tiny_mce/tiny_mce.js"></script>
        <script language="javascript" type="text/javascript">
    
        tinyMCE.init({
        mode : "specific_textareas",
        editor_selector : "simpleEditor",
        theme : "simple",
        ';
    
        switch ($_SESSION['s_language']) {
            case "greek":
                print 'language : \'el\',';
                break;
            case "english":
                print 'language : \'en\',';
                break;
        }
    
        print '
        entity_encoding : "raw",
        force_p_newlines : false,
        force_br_newlines : true,
        convert_newlines_to_brs : true
            });

        tinyMCE.init({
        //mode : "exact",
        mode : "specific_textareas",
        ';
    
    
        switch ($_SESSION['s_language']) {
            case "greek":
                print 'language : \'el\',';
                break;
            case "english":
                print 'language : \'en\',';
                break;
        }
    
        print ' 
        editor_selector : "mceEditor",
        theme : "advanced",
        //height : "550",
        theme_advanced_resizing : true,
        theme_advanced_resizing_use_cookie : false,
        entity_encoding : "raw",
        force_p_newlines : false,
        force_br_newlines : true,
        convert_newlines_to_brs : false,
        apply_source_formatting : true, 
        plugins : "table,save,advhr,advimage,advlink,emotions,iespell,insertdatetime,preview,zoom,java,searchreplace,print,contextmenu,media,mathtype,paste,fullscreen",
        theme_advanced_buttons1_add_before : "save,separator",
        theme_advanced_buttons1_add : "fontselect,fontsizeselect",
        theme_advanced_buttons2_add : "separator,insertdate,inserttime,zoom,separator,forecolor,backcolor",
        theme_advanced_buttons2_add_before: "cut,copy,paste,separator,search,replace,separator",
        theme_advanced_buttons3_add_before : "tablecontrols,separator",
        theme_advanced_buttons3_add : "emotions,iespell,advhr,separator,print,java,media,separator,mathtype,pastetext,pasteword,selectall,preview,fullscreen",
        plugin_preview_width : "700",
        plugin_preview_height : "700",
        paste_create_paragraphs : false,
        paste_create_linebreaks : false,
        paste_use_dialog : true,
        paste_auto_cleanup_on_paste : true,
        paste_convert_middot_lists : false,
        paste_unindented_list_class : "unindentedList",
        paste_convert_headers_to_strong : true,
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_path_location : "bottom",
        plugin_insertdate_dateFormat : "%Y-%m-%d",
        plugin_insertdate_timeFormat : "%H:%M:%S",
        extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],applet[code|codebase|width|height],embed[src|autostart|type]",';
        
        //file_browser_callback : "myCustomFileBrowser",
        print '
        external_link_list_url : "example_data/example_link_list.js",
        external_image_list_url : "myexternallist.js",
        flash_external_list_url : "example_data/example_flash_list.js"
        
        });
        

    function myCustomFileBrowser(field_name, url, type, win) {

        var fileBrowserWindow = new Array();

        fileBrowserWindow["file"] = "editor/popups/insert_image.php" + "?type=" + type + "&lessons_ID='.$_SESSION['s_lessons_ID'].'"; 
        fileBrowserWindow["title"] = "File Browser";
        fileBrowserWindow["width"] = "800";
        fileBrowserWindow["height"] = "600";
        fileBrowserWindow["close_previous"] = "no";
    
        tinyMCE.openWindow(fileBrowserWindow, {
          window : win,
          input : field_name,
          resizable : "yes",
          inline : "yes"
        });


        win.tinyMCE.setWindowArg(\'editor_id\',\'mce_editor_0\');
        

    }       
        
    
        tinyMCE.init({
        mode : "specific_textareas",
        ';
    
    
        switch ($_SESSION['s_language']) {
            case "greek":
                print 'language : \'el\',';
                break;
            case "english":
                print 'language : \'en\',';
                break;
        }
    
        print ' 
        editor_selector : "intermediateEditor",
        theme : "advanced",
        theme_advanced_resizing : true,
        theme_advanced_resizing_use_cookie : false,
        entity_encoding : "raw",
        force_p_newlines : false,
        force_br_newlines : true,
        convert_newlines_to_brs : false,
        apply_source_formatting : true, 
        plugins : "table,advhr,advimage,advlink,emotions,iespell,java,contextmenu,media,mathtype",
        theme_advanced_buttons1_add : "fontselect,fontsizeselect,removeformat",
        theme_advanced_buttons2_add_before : "forecolor,backcolor,separator,table",
        theme_advanced_buttons2_add : "emotions,iespell,separator,advimage,java,media,separator,mathtype,sub,sup",
        theme_advanced_buttons3 : "",
        theme_advanced_disable : "formatselect,styleselect,strikethrough,cut,copy,paste,indent,outdent,help,cleanup,hr,anchor",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_path_location : "bottom",
        extended_valid_elements : "a[name|href|target|title|onclick],img[class|src|border=0|alt|title|hspace|vspace|width|height|align|onmouseover|onmouseout|name],hr[class|width|size|noshade],font[face|size|color|style],span[class|align|style],applet[code|codebase|width|height],embed[src|autostart|type]"
        });
        </script>';
    }    
    print '<script type="text/javascript" src="js/mathml.js"> </script>
        <script type="text/javascript" src="js/ASCIIMathML.js"></script>
    <script type="text/javascript" src="js/ajax.js"></script>
    <script type="text/javascript" src="js/context-menu.js"></script>
    <script type="text/javascript" src="js/drag-drop-folder-tree.js"></script>
    <script type="text/javascript" src="js/statists_tabber.js"></script>
    <script type="text/javascript" src="js/calendar3.js"></script>
    <script type="text/javascript">
    //--------------------------------
    // Save functions
    //--------------------------------
    var ajaxObjects = new Array();
    
    // Use something like this if you want to save data by Ajax.
    function saveMyTree()
    {
            saveString = treeObj.getNodeOrders();
            var ajaxIndex = ajaxObjects.length;
            ajaxObjects[ajaxIndex] = new sack();
            var url = "saveNodes.php?saveString=" + saveString;
            ajaxObjects[ajaxIndex].requestFile = url;   // Specifying which file to get
            ajaxObjects[ajaxIndex].onCompletion = function() { saveComplete(ajaxIndex); };// Specify function that will be executed after file has been found
            ajaxObjects[ajaxIndex].runAJAX();       // Execute AJAX function            
        
    }
    function saveComplete(index)
    {
        alert(ajaxObjects[index].response);         
    }

    
    // Call this function if you want to save it by a form.
    function saveMyTree_byForm()
    {
        document.myForm.elements["saveString"].value = treeObj.getNodeOrders();
        document.myForm.submit();       
    }
    

        </script>';
//echo $ctg." ".$COLOR[$ctg];
    //include_once $path."css.php";

    if (!$ctg) {
        $ctg = "lessons";
    }
    
    if (!$COLOR[$ctg] OR $COLOR[$ctg] == "") {
        //$DEF_COLOR   = eF_getDefaultColors();
        $COLOR[$ctg] = $DEF_COLOR["lessons"];
    }
    $COLOR['messages'] = $COLOR['forum'];  
    print '<style type="text/css">
            TH {
                BACKGROUND-COLOR: '.$COLOR[$ctg].';
            }

            .top_title {
                BACKGROUND-COLOR: '.$COLOR[$ctg].';
            }
            </style>';           


print'        </HEAD>
            <BODY id = "body_'.$ctg.'" onload = "jeF_initialize()" '.$marginstr.'>
        <script type="text/javascript" src="js/PieNG.js"></script>
        <script type="text/javascript" src="js/tabber.js"></script>
        <script type="text/javascript" LANGUAGE="JavaScript">


            if(window.location==top.location)
            {
            //if(document.body.style && document.body.style.marginLeft)
                    //  document.body.style.marginLeft = "10px";
            }
        </script>
        <script type="text/javascript">
            top.document.title = "eFront - '._THENEWFORMOFADDITIVELEARNING.'";
        </script>
        <SCRIPT type="text/javascript" LANGUAGE="JavaScript" src="js/print-script.js"></SCRIPT>
            ';
        
 
        //echo $ctg." ".$COLOR[$ctg];
        
    print " <SCRIPT LANGUAGE=\"JavaScript\">
      
            function jeF_initialize() 
            {
                if (el = document.getElementById('main_table'))
                    el.style.display = '';
                if (el = document.getElementById('loading_table')) 
                    el.style.display = 'none';
                if (window._editor_url) initEditor();
                
                setCorrectIframeSize();

                if(changeImages)
                        changeImages();
            }
            
            function popUp(URL, width, height, resize) 
            {
                var left = (screen.width - width) / 2
                var top  = (screen.height-height) / 2
                var resizeable = 0;
                if (resize == 1) {
                    resizeable = 1;
                }
                popup = window.open(URL, '', 'toolbar = 0, scrollbars = 1, location = 0, statusbar = 1, menubar = 0, resizable = '+resizeable+', width = '+width+', height = '+height+', left = '+left+', top = '+top);
                return popup;
            }           

            //Áõôü ôï êïììÜôé javascript öÝñíåé ôï iframe ôïõ scorm óôï óùóôü ìÝãåèïò, þóôå íá ðéÜíåé üëç ôçí åéêüíá
            function setCorrectIframeSize()
            {
                if (frame = window.document.getElementById('scormFrameID'))
                {
                    innerDoc    = (frame.contentDocument) ? frame.contentDocument : frame.contentWindow.document;
                    objToResize = (frame.style) ? frame.style : frame;
                    if (frame.document) {
                        //alert(frame.contentWindow.document.body.clientHeight);
                        objToResize.height = Math.max(innerDoc.body.scrollHeight, frame.document.body.scrollHeight) + 50;
                        //alert(frame.contentWindow.document.body.clientHeight);
                        
                    } else {
                        objToResize.height = innerDoc.body.scrollHeight + 50;
                    }
                }
            }

            </SCRIPT>";
}



/**
* Prints a warning or error message
*
* This function prints a message in a yellow box with an exclamation mark. It is used when
* an important message must be displayed, such as a confirmation or a warning. If the $print
* variable is set, then the message is printed, otherwise it is returned in a string
*
* @param string $str The message to be printed
* @param bool $print If the message will be directly displayed, or returned in a string
* @return string The string with the message
* @version 1.0
*/
function eF_printMessage($str, $print = true, $message_type = '')
{
    if ($str) {
        if ($message_type == 'success') {
            $message = '
                <table border = "1" width = "100%" align = "center" bgcolor = "gray" rules = "none" style = "border-color:black">
                    <tr><td class = "message_success">
                            <img src = "images/32x32/check2.png" title="'.$str.'" alt="'.$str.'">
                        </td><td width = "99%" class = "message_success" align = "center">
                            '.$str.'
                    </td></tr>
                </table><br/>';            
        } else {
            $message = '
                <table border = "1" width = "100%" align = "center" bgcolor = "gray" rules = "none" style = "border-color:black">
                    <tr><td class="message">
                            <img src = "images/32x32/warning.png" title="'.$str.'" alt="'.$str.'">
                        </td><td width = "99%" class="message" align="center">
                            '.$str.'
                    </td></tr>
                </table><br/>';
        }
        
        if ($print) {
            print $message;
        } else {
            return $message;
        }
    }
}

/**
* Prints a unit path 
*
* This function prints family tree of a unit, starting from the older parent and diving until it reaches 
* the unit
* <br/>Example:
* <code>
* print eF_printContentPathFlat(26);    //If unit with id 26 is the Unit 1.3.2, then this will output something like: Unit 1 >> Unit 1.3 >> Unit 1.3.2
* </code>
*
* @param int $content_ID The unit id
* @return string The HTML code of the flat content path
* @version 1.0 
* @deprecated 
*/
function eF_printContentPathFlat($content_ID = 0)
{
    $parent = $content_ID;
    while ($parent != 0) {
        $res    = eF_getTableData("content", "id, name, parent_content_ID, ctg_type", "id=$parent");
        $id     = $res[0]['id'];
        $name   = $res[0]['name'];
        $parent = $res[0]['parent_content_ID'];
        if ($id == $content_ID) {
            $path = $name;
        } else {
            $path = $name." &raquo; ".$path;
        }
    }
    return $path;
}


/**
* Check if it is a child unit and print a mark
*
* If a unit is child to another unit, then this function prints a small mark, ':--' right
* before the unit title. If the unit has no parents, then only ':' is printed before its title.
* The check is done by examining the 'level' field of the argument array, which normally 
* is part of a content tree. This function is used when printing the content tree, by the 
* eF_printContentTree() function.
*
* @param array $content_array A Tree element, as returned by eF_getContentTree()
* @return string The string containing the prestring
* @see eF_printContentTree()
* @version 1.0
* @deprecated 
*/
function eF_printContentPrestring($content_array)
{
    $str = '';
    for ($k = 0; $k < $content_array['level']; $k++) {
        if($k == $content_array['level'] - 1) {
            $str .= "&nbsp; &raquo; ";
        } else {
            $str .= "&nbsp;  ";
        }
    }
   
    return $str;

}



/**
* Prints the unit content
*
* This function reads the content of the specified unit from the database and displays it, but only
* if the user is elegible to see it based on existing access rules. Otherwise, it returns false.
*
* @param int $content_ID The unit id
* @return string The unit content or false otherwise
* @version 1.1
* Changes from version 1.0 to 1.1 (2007/5/30):
* - Added return for all cases
* @deprecated;
*/
function eF_printContentData($content_ID = false)
{
    if ($content_ID) {
        if (!($GLOBALS['currentLesson'] -> options['rules']) OR $_SESSION['s_type'] != "student" OR ($_SESSION['s_type'] == "student" AND eF_checkRules($content_ID) === true)) {
            $res = eF_getTableData("content", "data", "id=$content_ID");
            if (eF_isLinked($res[0]['data'])) {
                $res = eF_getTableData("content", "data", "id=".mb_substr($res[0]['data'], 8));
            }

            //manos lines : regular expression replace gia na mpei to eikonidio tou pdf dipla sta links.
            $types   = "doc|pdf|png|jpg|gif|pps|bmp|swf|txt|zip|xls|avi|mp3|mpeg|wav|mpg";
            $pattern = '/<a[^>]+href=([\'"]?)[^>]*\.('.$types.')\1[^>]*>[^<]*<\/a>/';
            $replace = '\0<img src = "editor/icons/\2.png" style="margin-left:3px;"/>';
            //$text = preg_replace($pattern,$replace,$res[0]['data']);
            $text    = $res[0]['data'];
            $text = str_replace("##EFRONTINNERLINK##", $_SESSION['s_type'], $text);
            return "<br/>".$text."<br/><br/>";
        } else {
            return false;
        }
    } else {
        return false;
    }
}


function eF_checkContentInTree($tree)
{
    $time   = time();
    $offset = eF_getOffset();       //Get the user offset, if such exists
//pr($tree);    
    if (sizeof($tree) == 0) {
        $ids[] = 0;
    } else {
        foreach ($tree as $branch) {
            if ($branch['id']) {
                $ids[] = $branch['id'];     //Make a list of ids, that will be used in the query
            }
        }
    }
    
//pr($ids);
    $result_done    = eF_getTableDataFlat("current_content,periods,content", "current_content.content_ID", "current_content.content_ID in (".implode(",",$ids).") AND current_content.periods_ID=periods.id AND periods.from_timestamp+$offset<=$time AND content.id=current_content.content_ID AND content.active=1");
    $result_current = eF_getTableDataFlat("current_content,periods,content", "current_content.content_ID", "current_content.content_ID in (".implode(",",$ids).") AND current_content.periods_ID=periods.id AND periods.from_timestamp+$offset<=$time AND periods.to_timestamp+$offset>$time AND content.id=current_content.content_ID AND content.active=1");

    $done_ids       = array_combine($result_done['content_ID'], $result_done['content_ID']);                //Copy the array values to keys
    $current_ids    = array_combine($result_current['content_ID'], $result_current['content_ID']);          //Copy the array values to keys

    if (sizeof($tree) > 0) {
        $lesson_periods = eF_getTableData("periods,content", "count(*)", "periods.lessons_ID=content.lessons_ID AND content.id=".$tree[0]['id']);       //check if this lesson has periods
    }
    $lesson_periods[0]['count(*)'] == 0 ? $lesson_periods = false : $lesson_periods = true;           //Make $lesson_periods a boolean value, based on whether this lesson has periods or not
    
    for ($i = 0; $i < sizeof($tree); $i++) {
        if (isset($done_ids[$tree[$i]['id']])) {                    //If the unit is in a current or past period, set the isDoneContent field in the $tree array to true
            $tree[$i]['isDoneContent'] = true;
        } else {
            if ($lesson_periods) {
                $tree[$i]['isDoneContent'] = false;                 //If the lesson has periods and the unit is not part of a current or past one, set isDoneContent to false
            } else {
                $tree[$i]['isDoneContent'] = true;                  //If the lesson does not have any periods, set isDoneContent to true
            }
        }

        if (isset($current_ids[$tree[$i]['id']])) {                 //If the unit is in a current period, set the isCurrentContent field in the $tree array to true
            $tree[$i]['isCurrentContent'] = true;
        } else {
            if ($lesson_periods) {
                $tree[$i]['isCurrentContent'] = false;              //If the lesson has periods and the unit is not part of a current one of them, set isCurrentContent to false
            } else {
                $tree[$i]['isCurrentContent'] = true;               //If the lesson does not have any periods, set isCurrentContent to true
            }
        }
    }
//pr($tree);
    return $tree;
}

/**
* Get the leaf nodes of the tree
*
* Ths function is used to traverse through the primitive content tree array,
* to find all units that do not have children (leaf units). It also removes
* these leaves from the array.
*
* @param array $units The array of units
* @return array The tree leaves
*/
function eF_findLeaves(&$units) {
    
    for ($i = 0; $i < sizeof($units); $i++) {
        $ok = true;
        for ($j = 0; $j < sizeof($units); $j++) {
            if ($units[$j]['parent_content_ID'] == $units[$i]['id']) {
                $ok = false;
            }
        }
        if ($ok) {
            $leaves[]      = $units[$i];
            $unset_array[] = $i;
        }
    }
    
    for ($i = 0; $i < sizeof($unset_array); $i++) {
        unset($units[$unset_array[$i]]);
    }
    
    $units = array_values($units);
    return $leaves;
}

?>