<?php
/**

* @package eFront
*/



/**
* Calculates a lesson's traffic through a sepecific time period
*
* This function calculates, for a specific lesson, how many times the lesson's pages have been accessed.
* Additionally, it returns the access number for every user.
*
* @param int $lesson The lesson id
* @param int $from_time Time from
* @return int $to_time Time to
* @version 1.0
*/
function eF_getLessonTraffic($lesson, $from_time, $to_time)
{
    $sql = "SELECT users_LOGIN, count(id) as cnt FROM logs WHERE lessons_id='$lesson' and timestamp between $from_time and  $to_time group by users_LOGIN order by users_LOGIN";
    $res = eF_execute($sql);
    $traffic = array();
    $traffic['users'] = array();
    $traffic['user_cnt'] = array();
    $cnt_access = 0;
    $cnt_time = 0;
    while ($k=mysql_fetch_row($res)){
        $cnt_access += $k[1];
        $traffic['users'][]=$k[0]; 
        $traffic['users_cnt'][]=$k[1];
        $tm =  ef_getUserLessonTime($lesson, $k[0], $from_time, $to_time); 
        $traffic['users_time'][]= $tm;  
        $cnt_time = $cnt_time + $tm['minutes']*60+$tm['seconds'];
    }
    $traffic['total_access'] = $cnt_access;
    $traffic['total_time']['minutes'] = floor($cnt_time/60);
    $traffic['total_time']['seconds'] = $cnt_time%60;
    return $traffic;
}

/**
* Prints the number of posts for a user
*
* This function prints the number of messages the specified user has posted so far in the forum. If the $lessons_ID
* parameter is set, then only messages posted in the correspoding lesson category are counted.
* <br/>Example:
* <code>
* eF_numberOfPosts('professor');        //Returns a number, i.e. 16
* </code>
*
* @param string $login The login name of the user
* @param int $lessons_ID The lesson id
* @return int The forum messages number
* @version 2.0
* Changes from version 1.1 to 2.0 (24/10/05):
* - Added $lessons_ID parameter and functionality
* - Changed return type, from string to int
* Changes from version 1.0 to 1.1:
* - Got rid of forum
*/
function eF_numberOfPosts($login, $lessons_ID = false)
{
    if ($lessons_ID && eF_checkParameter($lessons_ID, 'id')) {
        $result = eF_getTableData("f_messages, f_topics, f_forums", "count(*)", "f_topics.id = f_messages.f_topics_ID and f_forums.id = f_topics.f_forums_ID and f_forums.lessons_ID = ".$lessons_ID." and f_messages.users_LOGIN='".$login."'");
    } else {
        $result = eF_getTableData("f_messages", "count(*)", "users_LOGIN='".$login."'");
    }
    
    return $result[0]['count(*)'];
}



/**
* Prints the number of comments for a user
*
* This function prints the number of comments the user $login has added so far in 
* the lesson content. If no lesson is specified, it returns all his comments
* <br/>Example:
* <code>
* echo eF_numberOfComments('john', 1);
* //prints i.e. 5
* </code>
*
* @param int $start_month The timestamp corresponding to the start time of the statistic period
* @param int $end_month The timestamp corresponding to the end time of the statistic period
* @param string $login The login name of the user
* @param int $lessons_ID The lesson id
* @return int The comments number.
* @version 2.1
* Changes from 2.0 to 2.1 (24/10/05):
* - Made lessons_ID parameter optional
* Changes from 1.0 to 2.0 (17/10/05):
* - Returns int instead of string
* - Changed handling of $start_month, $end_month
* - Added functionality
*/
function eF_numberOfComments($login, $lessons_ID = false, $start_month = false, $end_month = false)
{
    ($lessons_ID && eF_checkParameter($lessons_ID, 'id')) ? $lessons_str = " and content.lessons_ID=".$lessons_ID : $lessons_str = '';
    
    if (!$start_month && !$end_month) {
        $result = eF_getTableData("content, comments", "count(*)", "users_LOGIN = '".$login."' and comments.content_ID = content.id".$lessons_str);
    } else {
        !$start_month ? $start_month = time() : null;
        !$end_month   ? $end_month   = time() : null;

        $result = eF_getTableData("logs l, content", "count(*)", "l.users_LOGIN='$login' and l.action='comment' and l.timestamp>$start_month and l.timestamp<$end_month and l.comments=content.id".$lessons_str);
    }
    
    $comments_num = $result[0]['count(*)'];

    return $comments_num;
}







function ef_getUserContentTime($log_id, $content_id, $login, $time_start){
    $sql = "SELECT action, comments, timestamp FROM logs where id > $log_id and users_LOGIN='$login' order by id";
    $res = ef_execute($sql);
    while ($k = mysql_fetch_row($res)){
        $action = $k[0];
        $comments = $k[1];
        $timestamp = $k[2];
        if ($action != "content"){
            $interval = ef_convertIntervalToTime($timestamp - $time_start);
            return $interval;
        }
        else{
            if ($comments != $content_id){
                $interval = ef_convertIntervalToTime($timestamp - $time_start);
                return $interval;
            }                
        }        
    }    
}


function ef_getUserLessonTime($lesson, $login, $from_time, $to_time){
    
    $sql = "SELECT id, timestamp, lessons_id FROM logs WHERE users_LOGIN='$login' and timestamp between $from_time and $to_time order by timestamp";
    $res = eF_execute($sql);
    $total_time = array();
    $total_time['minutes'] = 0;
    $total_time['seconds'] = 0;
    $total_time['hours'] = 0;
    $total_time['total_seconds'] = 0;
    $l_start = 0;
    $inlesson = 0;
    while ($k=mysql_fetch_row($res)){       
        $c_id = $k[0];
        $c_time = $k[1];
        $c_lesson = $k[2];
        if ($inlesson){
            if ($c_lesson != $lesson){
                $inlesson = 0;
                $interval = ef_convertIntervalToTime($c_time - $l_start);
                if ($interval['hours'] == 0 && $interval['minutes'] <= 60){
                    $total_time['minutes'] += $interval['minutes'];
                    $total_time['seconds'] += $interval['seconds'];
                }               
            }
            else{
                $interval = ef_convertIntervalToTime($c_time - $l_start);
                if ($interval['hours']==0 && $interval['minutes']<=30){
                    $total_time['minutes'] += $interval['minutes'];
                    $total_time['seconds'] += $interval['seconds'];
                }
                $l_start = $c_time;
            }
        }
        else{
            if ($c_lesson == $lesson){
                $inlesson = 1;
                $l_start = $c_time;
            }
            
        }
    }        
    
    $sec = $total_time['seconds'];
    if ($sec >=60){
        $nm = floor($sec / 60);
        $ns = $sec %60;
        $total_time['seconds'] = $ns;
        $total_time['minutes'] += $nm;
    }
    if ($total_time['minutes'] >=60){
        $nh = floor($total_time['minutes']/60);
        $nm = $total_time['minutes'] % 60;
        $total_time['hours'] = $nh;
        $total_time['minutes'] = $nm;
    }
    $total_time['total_seconds'] = 3600 * $total_time['hours'] + 60 * $total_time['minutes'] + $total_time['seconds'];
    return $total_time;
}





/**
* Get user online times
*
* This function calculates the time a user spent online. If the optional interval parameter is set, then 
* statistics are calculated only for this time period.
* <br/>Example:
* <code>
* $interval = array('from' => time()-86400, 'to' => time());        //Calculate statistics for the last 24 hours
* $times = eF_getUserTimes('john', $interval);
* print_r($times);
* //Returns:
*Array
*(
*    [duration] => Array
*        (
*            [0] => 19
*            [1] => 120
*            [2] => 63
*        )
*
*    [times] => Array
*        (
*           [0] => 1118770769
*           [1] => 1118824615
*           [2] => 1118824760
*        )
*)        
* </code>
*
* @param string $login The user login name
* @param array $interval The time interval to calculate statistics for
* @return array The login times and durations (in seconds)
* @version 1.0 27/10/2005
*/
function eF_getUserTimes($login, $interval = false) {
    $times = array('duration' => array(), 'time' => array(), 'session_ip' => array());

    if (isset($interval['from']) && eF_checkParameter($interval['from'], 'timestamp') && isset($interval['to']) && eF_checkParameter($interval['to'], 'timestamp')) {
        $result = eF_getTableDataFlat("logs", "timestamp, action, session_ip", "timestamp > ".$interval['from']." and timestamp < ".$interval['to']." and users_LOGIN='".$login."' and (action='login' or action = 'logout')", "timestamp");
    } else {
        $result = eF_getTableDataFlat("logs", "timestamp, action, session_ip", "users_LOGIN='".$login."' and (action='login' or action = 'logout')", "timestamp");
    }
    
    if (sizeof($result) > 0) {
        for ($i = 0; $i < sizeof($result['action']) - 1; $i++) {                                            //The algorithm goes like this: We search for the 'login' actions in the log. When one is found, then we search either for the next 'login' or 'logout' action, if there are no other actions, or the last non-login or logout action. This way, we calculate the true time spent inside the system. If we calculated only the logout-login times, then when a user had closed a window without logging out first, the online time would be reported falsely
            if ($result['action'][$i] == 'login') {
                $count      = $i + 1;
                $end_action = $result['timestamp'][$count];
                while ($result['action'][$count] != 'logout' && $result['action'][$count] != 'login' && $count < sizeof($result['action'])) {
                    $end_action = $result['timestamp'][$count];
                    $count++;
                }
                if ($end_action - $result['timestamp'][$i] <= 3600){    //only take into account intervals less than one hour
                    $times['duration'][]   = $end_action - $result['timestamp'][$i];
                    $times['time'][]       = $result['timestamp'][$i];
                    $times['session_ip'][] = eF_decodeIP($result['session_ip'][$i]);
                }
            }
        }
    }

    return $times;
}
/**
 * @deprecated 
 *
 * @param unknown_type $login
 * @return unknown
 */
function ef_getProfessorStudents($login){
    $sql = "select distinct(ul.users_LOGIN) from users_to_lessons ul, users u where ul.users_LOGIN = u.login and u.user_type = 'student' and exists (select l.lessons_ID from users_to_lessons l where ul.lessons_ID=l.lessons_ID and l.users_LOGIN='$login') order by ul.users_LOGIN";
    $res = ef_execute($sql);   
    $users = array();
    while ($k = mysql_fetch_row($res)){
        $user = array();
        $user['login']= $k[0];
        $users[] = $user;
    }    
    return $users;
}


/**
 * @deprecated 
 *
 * @param unknown_type $login
 * @param unknown_type $interval
 * @return unknown
 */
function ef_getUserStatistics($login, $interval){
    $traffic = array();
    $traffic['lessons_name'] = array();
    $traffic['lessons_id'] = array();
    $traffic['lessons_access'] = array();
    $traffic['lessons_time'] = array();
    
    $sql = "select count(id) from logs where users_LOGIN='$login' and timestamp between ".$interval['from']." and ".$interval['to']." and action='login'";
    $result = ef_execute($sql);
    $k = mysql_fetch_row($result);
    $traffic['logins']=$k[0];
    
    $sql = "select s.name, l.lessons_ID, count(l.id) as cnt from logs l, lessons s where l.users_LOGIN='$login' and l.timestamp between ".$interval['from']." and ".$interval['to']." and l.lessons_ID=s.id  group by s.name, l.lessons_ID";
    $result = ef_execute($sql);
    $cnt = 0;
    while ($k = mysql_fetch_row($result)){
        $cnt += $k[2];
        $traffic['lessons_name'][]=$k[0];
        $traffic['lessons_id'][]=$k[1];
        $traffic['lessons_access'][] = $k[2];
        $traffic['lessons_time'][] = ef_getUserLessonTime($k[1], $login, $interval['from'],$interval['to']);
    }
    $traffic['total_access'] = $cnt;
    return $traffic;
}

/**
 * @deprecated
 *
 * @param unknown_type $login
 * @param unknown_type $interval
 * @return unknown
 */
function ef_getUserLoginTime($login, $interval){
    $from = $interval['from'];
    $to = $interval['to'];
    $sql = "select id, timestamp, action from logs where users_LOGIN='$login' and timestamp between $from and $to order by timestamp";
    $res = ef_execute($sql);
    $total_time = 0;
    $l_start = 0;
    $inlogin = 0;
    while ($k = mysql_fetch_row($res)){
        $c_time = $k[1];
        $c_action = $k[2];
        
        if ($inlogin){
            if ($c_action != 'logout' && $c_action != 'login'){
                $total_time += ($c_time - $l_start);
                $l_start = $c_time;
            }    
            else if ($c_action == 'logout'){
                if ($c_time < ($l_start + 3600))//if it is logged in more than an hour, we don't consider it
                    $total_time += ($c_time - $l_start);
                $inlogin = 0; 
            }
            else if ($c_action == 'login'){
                $inlogin = 1;
                $l_start = $c_time;
            }
        }
        else{
            if ($c_action == 'login'){
                $inlogin = 1;
                $l_start = $c_time;
            }
        }
    }       
    return ef_convertIntervalToTime($total_time);
}

function ef_getSystemStatistics($interval){
    $from = $interval['from'];
    $to = $interval['to'];
    $statistics = array();
    $sql = "select count(id) from logs where action='login' and timestamp between $from and $to ";
    $res = ef_execute($sql);
    $k = mysql_fetch_row($res);
    $statistics['total_logins']=$k[0];
    return $statistics;
}

function ef_getLessonAccessStatistics($interval, $lesson, $login)
{
    $from = $interval['from'];
    $to = $interval['to'];
    $statistics = array();
    $sql = "select count(id) from logs where lessons_ID=$lesson and timestamp between $from and $to and users_LOGIN='$login'";
    $res = ef_execute($sql);
    $k = mysql_fetch_row($res);
    $statistics['total_access']=$k[0];
    return $statistics;
}

function ef_getUserLogins($interval, $login)
{
    $from = $interval['from'];
    $to = $interval['to'];
    $statistics = array();
    $sql = "select count(id) from logs where action='login' and timestamp between $from and $to and users_LOGIN='$login'";
    $res = ef_execute($sql);
    $k = mysql_fetch_row($res);
    $statistics['total_logins']=$k[0];
    return $statistics;
}

function ef_getActiveUsers($interval){
    $from = $interval['from'];
    $to = $interval['to'];
    $sql = "select users_LOGIN as login, count(id) as cnt from logs where timestamp between $from and $to and action='login' group by users_LOGIN order by count(id) desc";
    $res = ef_execute($sql);
    $activeusers = array();
    $n = 0;
    $totalseconds = 0;
    while ( ($k = mysql_fetch_row($res)) && $n<20 ){
        $activeusers['login'][]=$k[0];
        $activeusers['access'][]=$k[1];
        $time = ef_getUserLoginTime($k[0],$interval);
        $secs = $time['hours']*3600+$time['minutes']*60+$time['seconds'];
        $totalseconds+=$secs;
        $activeusers['secs'][] = $secs;
        $activeusers['time'][]=$time;
        $n++;
    }   
    array_multisort($activeusers['secs'],SORT_DESC,SORT_NUMERIC,$activeusers['access'],SORT_DESC,SORT_NUMERIC,$activeusers['login'],SORT_DESC,SORT_STRING,$activeusers['time'] );
    $totalhours = floor($totalseconds/3600);
    $totmins = floor(($totalseconds-3600*$totalhours)/60);
    $totsecs = ($totalseconds-3600*$totalhours-60%$totmins) % 60;
    $activeusers['totaltime'] = array();
    $activeusers['totaltime']['hours']=$totalhours;
    $activeusers['totaltime']['minutes']=$totmins;
    $activeusers['totaltime']['seconds']=$totsecs;
    
    return $activeusers;    
}


function ef_getActiveLessons($interval){
    $from = $interval['from'];
    $to = $interval['to'];
    $sql = "select g.lessons_ID, l.name,  count(g.id) from logs g, lessons l where timestamp between $from and $to and g.lessons_ID=l.ID group by g.lessons_ID, l.name order by count(g.id) desc";
    $res = ef_execute($sql);
    $activelessons = array();
    while ( ($k = mysql_fetch_row($res))){
        $activelessons['id'][]=$k[0];
        $activelessons['name'][]=$k[1];
        $activelessons['access'][]=$k[2];
        $tr = ef_getLessonTraffic($k[0],$interval['from'],$interval['to']);
        $activelessons['time'][] = $tr['total_time'];   
    }   
    return $activelessons;  
}


function ef_getSystemLog($interval){
    $from = $interval['from'];
    $to = $interval['to'];
    $log = array();
    $sql = "select id, users_LOGIN, action, timestamp from logs where timestamp between $from and $to order by timestamp";
    $res = ef_execute($sql);
    while ($k=mysql_fetch_row($res)){
        $log['id'][] = $k[0];
        $log['login'][] = $k[1];
        $log['action'][] = $k[2];
        $log['time'][] = date("d/m/Y h:i:s",$k[3]);
    }
    return $log;
}
/**
 * @deprecated 
 *
 * @param unknown_type $lesson
 * @param unknown_type $interval
 * @return unknown
 */
function ef_getLessonLog($lesson, $interval){
    $from = $interval['from'];
    $to = $interval['to'];
    $log = array();
    $sql = "select id, users_LOGIN, action, timestamp from logs where timestamp between $from and $to and lessons_id='$lesson' order by timestamp";
    $res = ef_execute($sql);
    while ($k=mysql_fetch_row($res)){
        $log['id'][] = $k[0];
        $log['login'][] = $k[1];
        $log['action'][] = $k[2];
        $log['time'][] = date("d/m/Y h:i:s",$k[3]);
    }
    return $log;
}

function ef_getUserLog($login, $interval){
    $from = $interval['from'];
    $to = $interval['to'];
    $log = array();
    $sql = "select id, users_LOGIN, action, timestamp from logs where timestamp between $from and $to and users_LOGIN='$login' order by timestamp";
    $res = ef_execute($sql);
    while ($k=mysql_fetch_row($res)){
        $log['id'][] = $k[0];
        $log['login'][] = $k[1];
        $log['action'][] = $k[2];
        $log['time'][] = date("d/m/Y h:i:s",$k[3]);
    }
    return $log;
}







/**
* Calculates a list with the content that a user has seen
* 
* This function returns an array containing the total units of a lesson, and 
* the units that the user has seen until now. This information is grouped by 
* unit type, in 4 categories: Theory, Exercises, Examples and Tests.
* <br/>Example:
* <code>
* $content_done = eF_usersContentDone('student', 1);
* </code>
* Outputs:
* <code>
* Array
* (
*     [theory] => 25
*     [theory_seen] => 5
*     [exercises] => 2
*     [exercises_seen] => 0
*     [examples] => 6
*     [examples_seen] => 0
*     [tests] => 9
*     [tests_done] => 3
* )
* </code>
*
* @param string $usrname The login name of the user
* @param id $lesson The lesson id
* @return array The results array.
* @version 1.0
*/
/*

*/
function eF_usersContentDone($usrname, $lesson) 
{
    $tmp = eF_getStudentProgress($usrname, $lesson);
    $theory_perc = $tmp[$lesson];
    $res = eF_execute("select count(*) from content where lessons_ID=$lesson and ctg_type='exercises' and active=1");
    list($exercises)      = mysql_fetch_row($res);
    $res = eF_execute("select count(distinct l.comments) from logs l,content c where l.users_LOGIN='$usrname' and l.action='exercises' and l.comments=c.id and c.lessons_ID=$lesson and c.active=1 ");
    list($exercises_seen) = mysql_fetch_row($res);
    if ($exercises > 0){
        $exercises_perc = round(($exercises_seen/$exercises)*100,2);
    }
    else
        $exercices_perc = 0;    
    $res = eF_execute("select count(*) from content where lessons_ID=$lesson and ctg_type='examples' and active=1");
    list($examples)       = mysql_fetch_row($res);
    $res = eF_execute("select count(distinct l.comments) from logs l,content c where l.users_LOGIN='$usrname' and l.action='examples' and l.comments=c.id and c.lessons_ID=$lesson and c.active=1 ");
    list($examples_seen)  = mysql_fetch_row($res);
    if ($examples > 0){
        $examples_perc = round(($examples_seen/$examples)*100,2);
    }
    else
        $examples_perc = 0;    
    $res = eF_execute("select count(*) from content where lessons_ID=$lesson and ctg_type='tests' and active=1");
    list($tests)          = mysql_fetch_row($res);
    $res = eF_execute("select count(*) from done_tests d,content c,tests t where d.users_LOGIN='$usrname' and d.tests_ID=t.id and t.content_ID=c.id and c.lessons_ID=$lesson and c.active=1 ");
    list($tests_done)     = mysql_fetch_row($res);
    if ($tests > 0){
        $tests_perc = round(($tests_done/$tests)*100,2);
    }
    else
        $tests_perc = 0;
    
    $res = eF_execute("select count(*) from users_to_projects u, projects p where u.users_LOGIN='$usrname' and u.projects_ID=p.id and p.lessons_ID=$lesson");
    list($projects) = mysql_fetch_row($res);
    $res = eF_execute("select count(*) from users_to_projects u, projects p where u.users_LOGIN='$usrname' and u.projects_ID=p.id and p.lessons_ID=$lesson and u.grade!=''");
    list($projects_done)     = mysql_fetch_row($res);
    if ($projects > 0){
        $projects_perc = round(($projects_done/$projects)*100,2);
    }
    else
        $projects_perc = 0;
    
    $content_stats = array('theory'         => $theory, 
                           'theory_seen'    => $theory_seen,
                           'theory_perc'    => $theory_perc,
                           'exercises'      => $exercises,
                           'exercises_seen' => $exercises_seen,
                           'exercises_perc' => $exercises_perc,
                           'examples'       => $examples,
                           'examples_seen'  => $examples_seen,
                           'examples_perc'  => $examples_perc,
                           'tests'          => $tests,
                           'tests_done'     => $tests_done,
                           'tests_perc'     => $tests_perc,
                           'projects'          => $projects,
                           'projects_done'     => $projects_done,
                           'projects_perc'     => $projects_perc
        );

    return $content_stats;
}

/**
* Calculates folder statistics.
*
* This function is used to calculate how many files and folders are contained inside a lesson folder. It 
* also calculates the total size of these files. The parameter given corresponds to the lesson id, which
* coincides with the lesson folder name inside the content/ directory. The function returns a 3-values array, 
* whith the first element being the total files number, the second the total folders and the third the total size.
* <br/>Example<br/>:
* <code>
* $files_array = EfrontLessonFiles(3);                                         //3 is the lesson id
* print_r($files_array);
* //Outputs:
*Array
*(
*    [0] => 10
*    [1] => 2
*    [2] => 1791160
*)
* </code>
* @param string $lesson_id The lesson id
* @return array An array with 3 elements: number of files, number of directories and total file size, in bytes. if the lesson does not exist it returns false.
* @version 1.0
*/
function EfrontLessonFiles($lesson_id) 
{
    $dir = G_LESSONSPATH.$lesson_id;

    if ($handle = @opendir($dir)) {                                         //Check if lesson directory exists
        $stats = eF_diveIntoDir($dir);                                        //Calculate statistics
    } else {
        $stats = false;
    }
    
    return $stats;
}


/**
* Calculates statistics for the designated folder.
*
* This function is used to recursively calculate statistics for the designated folder.
* Statistics include number of files and folders as well as total file size.
* It returns a 3-valued array containing these values.
*
* @param string $dir The directory name
* @param int $files Total files to continue counting from
* @param int $directories Total directories to continue counting from
* @param int $file_size Total file size to continue counting from
* @return array An array with 3 elements, total files, directories and file size
* @version 1.2.1
* @see EfrontLessonFiles
* changes from 1.2 to 1.2.1:
* - Fixed bug in file size reporting
* changes from version 1.0 (renamed to eF_diveIntoDirOld) to 1.2:
* - Rewritten because it was buggy (it displayed only the root folder statistics)
*/
function eF_diveIntoDir($dir, $files = 0, $directories = 0, $file_size = 0)
{    
    if ($handle = @opendir($dir)) {
        $in_directories = 0;
        while (false !== ($file = readdir($handle)))  {
            if (is_dir($dir.'/'.$file)) {
                if ($file != "." && $file != "..") {
                    $new_dir = $dir.'/'.$file;
                    $directories++;
                    list($files, $directories, $file_size) = eF_diveIntoDir($new_dir, $files, $directories, $file_size);
                }
            } else {
                $files++;
                $file_stat = stat($dir.'/'.$file);
                $file_size += $file_stat[7];
            }
        }
    }

    return array($files, $directories, $file_size);
}




/**
*
*/
function eF_getUsersActivityInfo($user_type, $lessons_ID = false, $group_id = false) {

    switch ($user_type) {
        case 'administrator':    
            $admins = eF_getTableDataFlat("users", "login", "user_type = 'administrator'");
            $admins = $admins['login'];
        
            $users_info = array('logins' => $admins);
        break;
        
        case 'professor':
            if ($lessons_ID && eF_checkParameter($lessons_ID, 'id')) {
                if ($group_id && eF_checkParameter($group_id, 'id'))
                    $professors = eF_getTableDataFlat("users u, users_to_lessons ul, users_to_groups g", "u.login,u.name,u.surname", "g.users_LOGIN = u.login and g.groups_id=$group_id and  u.login=ul.users_LOGIN and ul.lessons_ID = $lessons_ID and u.user_type = 'professor'");
                else
                    $professors = eF_getTableDataFlat("users u, users_to_lessons ul", "u.login,u.name,u.surname", "u.login=ul.users_LOGIN and ul.lessons_ID = $lessons_ID and u.user_type = 'professor'");
            } else {
                $professors = eF_getTableDataFlat("users", "login", "user_type = 'professor'");
            }
        $names = $professors['name'];
        $surnames = $professors['surname'];
            $professors = $professors['login'];

            for ($i = 0; $i < sizeof($professors); $i++) {
                if ($lessons_ID && eF_checkParameter($lessons_ID, 'id')) {
                    $temp_user_lessons = eF_getTableDataFlat("users_to_lessons, lessons", "lessons.id, lessons.name", "lessons.id = users_to_lessons.lessons_ID and users_LOGIN='".$professors[$i]."' and lessons.id=$lessons_ID");
                } else {
                    $temp_user_lessons = eF_getTableDataFlat("users_to_lessons, lessons", "lessons.id, lessons.name", "lessons.id = users_to_lessons.lessons_ID and users_LOGIN='".$professors[$i]."'");
                }

                $temp_num_comments = array();
                $temp_num_posts    = array();
                if (sizeof($temp_user_lessons) > 0) {
                    $professors_user_lessons[$i] = $temp_user_lessons['name'];
                    foreach ($temp_user_lessons['id'] as $id) {
                        $temp_num_comments[] = eF_numberOfComments($professors[$i], $id);
                        $temp_num_posts[]    = eF_numberOfPosts($professors[$i], $id);
                        $temp_time            = eF_getUserLessonTime($id, $professors[$i],"0000000", time());          
                    }
                } else {
                    $professors_user_lessons[$i] = array();
                }

                $professors_num_comments[$i] = $temp_num_comments;
                $professors_num_posts[$i]    = $temp_num_posts;
                $professors_lesson_time[$i]   = $temp_time;
            }
            $users_info = array('logins'       => $professors,
                                'name'         => $names,
                                'surname'      => $surnames,
                                'lessons'      => $professors_user_lessons, 
                                'time'         => $professors_lesson_time,
                                'num_comments' => $professors_num_comments, 
                                'num_posts'    => $professors_num_posts);
        break;
        
        case 'student':
            if ($lessons_ID && eF_checkParameter($lessons_ID, 'id')) {
                if ($group_id && ef_checkParameter($group_id, 'id')){
                    $students = eF_getTableDataFlat("users u, users_to_lessons ul, users_to_groups g", "u.login,u.name,u.surname", "g.users_LOGIN = u.login and g.groups_ID = $group_id and u.login=ul.users_LOGIN and ul.lessons_ID = $lessons_ID and u.user_type = 'student'");
                }
                else{
                    $students = eF_getTableDataFlat("users u, users_to_lessons ul", "u.login,u.name,u.surname", "u.login=ul.users_LOGIN and ul.lessons_ID = $lessons_ID and u.user_type = 'student'");
                }
            } else {
                $students = eF_getTableDataFlat("users", "login", "user_type = 'student'");
            }
            $names = $students['name'];
            $surnames = $students['surname'];
            $students = $students['login'];

            for ($i = 0; $i < sizeof($students); $i++) {
                if ($lessons_ID && eF_checkParameter($lessons_ID, 'id')) {
                    $temp_user_lessons = eF_getTableDataFlat("users_to_lessons, lessons", "lessons.id, lessons.name", "lessons.id = users_to_lessons.lessons_ID and users_LOGIN='".$students[$i]."' and lessons.id=$lessons_ID");                    
                } else {
                    $temp_user_lessons = eF_getTableDataFlat("users_to_lessons, lessons", "lessons.id, lessons.name", "lessons.id = users_to_lessons.lessons_ID and users_LOGIN='".$students[$i]."'");                    
                    
                }
                $temp_num_comments  = array();
                $temp_content_done  = array();
                $temp_average_score = array();
                $temp_project_score = array();
                $temp_num_posts     = array();
                if (sizeof($temp_user_lessons) > 0) {
                    $students_user_lessons[$i] = $temp_user_lessons['name'];
                    foreach ($temp_user_lessons['id'] as $id) {
                        $temp_num_comments[]  = eF_numberOfComments($students[$i], $id);
                        $temp_content_done[]  = eF_usersContentDone($students[$i], $id);
                        $temp_num_posts[]     = eF_numberOfPosts($students[$i], $id);
                        $temp_time            = eF_getUserLessonTime($id, $students[$i],"0000000", time());          
                        $score                = eF_getTableData("done_tests, tests, content", "avg(score)", "done_tests.tests_ID = tests.id and tests.content_ID = content.id and content.lessons_ID = ".$id." and users_LOGIN='".$students[$i]."'");
                        $temp_average_score[] = round($score[0]['avg(score)'] * 100, 2);
                        $grades               = ef_getTableData("users_to_projects, projects", "avg(grade)", "users_to_projects.projects_ID = projects.id and projects.lessons_ID =".$id." and users_LOGIN='".$students[$i]."'");                        
                        $temp_project_score[] = sprintf("%01.2f", round($grades[0]['avg(grade)'], 2));
                       
                    }
                } else {
                    $students_user_lessons[$i] = array();
                }

                $students_num_comments[$i]  = $temp_num_comments;
                $students_content_done[$i]  = $temp_content_done;
                $students_average_score[$i] = $temp_average_score;
                $students_project_score[$i] = $temp_project_score;
                $students_num_posts[$i]     = $temp_num_posts;
                $students_lesson_time[$i]   = $temp_time;
            }
            $users_info = array('logins'       => $students,
                                'name'         => $names,
                                'surname'      => $surnames,
                                'time'         => $students_lesson_time,
                                'lessons'      => $students_user_lessons, 
                                'content_done' => $students_content_done, 
                                'avg_score'    => $students_average_score, 
                                'project_score'=> $students_project_score, 
                                'num_comments' => $students_num_comments, 
                                'num_posts'    => $students_num_posts);       
                                  
        break;
    }
    
    return $users_info;
}




function eF_getUserTypesInfo($lesson_ID = false){
    if ($lesson_ID){
        $user_types = eF_getTableData("users","user_type, count(login) as cnt_total","","","user_type");
        for ($i=0;$i<sizeof($user_types);$i++){
            $user_current_type = $user_types[$i]['user_type'];
            $user_lesson = eF_getTableData("users u, users_to_lessons ul","count(u.login) as cnt_lesson","ul.users_LOGIN=u.login and u.user_type='$user_current_type' and ul.lessons_ID='$lesson_ID'");
            if (sizeof($user_lesson) > 0)
                $user_types[$i]['cnt_lesson'] = $user_lesson[0]['cnt_lesson'];
            else
                $user_types[$i]['cnt_lesson'] = 0;
        }
    }else
        $user_types = eF_getTableData("users","user_type, count(login) as cnt_total, count(login) as cnt_lesson","","","user_type");

    return $user_types;
    
}





/**
*
*/
function eF_getUserInfo($login, $lessons_ID = false) 
{
    $general_info = eF_getTableData("users", "*", "login='".$login."'");
    $lesson_num = ef_getTableData("users_to_lessons","count(*)", "users_LOGIN='$login'");
    $interval = array(  'from'  => "000000",
                        'to'    => time());
    $user_info['user_type'] = $general_info[0]['user_type'];    
    $user_info['general_info'] = array(_LANGUAGE   => $general_info[0]['languages_NAME'],                                       
                                       _ACTIVE     => $general_info[0]['active'],                                       
                                       _JOINED     => '#filter:timestamp-'.$general_info[0]['timestamp'].'#');
    $user_info['common_info'] = array (_USERNAME   => $login." (".$general_info[0]['surname']." ".$general_info[0]['name'].")",                                                                                                                                                           
                                       _NAME       => $general_info[0]['name'],
                                       _SURNAME    => $general_info[0]['surname'],
                                       _USERTYPE   => $general_info[0]['user_type'],
                                       _LESSONS    => $lesson_num[0]['count(*)'],
                                       _TOTALLOGINTIME => ef_getUserLoginTime($login,$interval));        
    if (strlen($general_info[0]['avatar']) > 0)
        $user_info['avatar'] = $general_info[0]['avatar'];
    
    $res_profile = eF_getTableData("user_profile", "*", "active=1 AND languages_NAME='".$_SESSION['s_language']."'");
    
    for($l=0; $l<sizeof($res_profile); $l++) {      
        $user_info['general_info'][$res_profile[$l]['description']] = $general_info[0][$res_profile[$l]['name']];
      
    }   // afto einai gia na pairnei aytomata ta pedia meta tin prosthiki toy user profile


    $forum_info['messages_num'] = eF_numberOfPosts($login, $lessons_ID);
    if ($lessons_ID && eF_checkParameter($lessons_ID, 'id')) {
        $temp = eF_getTableData("f_messages fm, f_topics ft, f_forums fc", "fm.id, fm.f_topics_ID, fm.timestamp", "fm.users_LOGIN='$login' and fm.f_topics_ID = ft.id and ft.f_forums_ID = fc.id and fc.lessons_ID = $lessons_ID", "fm.timestamp desc limit 1");
    } else {
        $temp = eF_getTableData("f_messages", "id, f_topics_ID, timestamp", "users_LOGIN='$login'", "timestamp desc limit 1");
    }
    sizeof($temp) > 0 ? $forum_info['last_message'] = '#filter:timestamp_time-'.$temp[0]['timestamp'].'# <a href = "forum/forum_index.php?topic='.$temp[0]['f_topics_ID'].'&view_message='.$temp[0]['id'].'">&raquo</a>' : $forum_info['last_message'] = '';

    $p_messages_info['messages_num'] = eF_getTableData("f_personal_messages", "count(*)", "users_LOGIN='$login'");
    $p_messages_info['folders_num']  = eF_getTableData("f_folders", "count(*)", "users_LOGIN='$login'");
    $p_messages_info['volume']       = eF_diveIntoDir(G_UPLOADPATH.$login.'/message_attachments/');
    
    $temp = eF_getTableData("chatmessages", "count(*)", "users_LOGIN='$login'");
    sizeof($temp) > 0 ? $chat_info['messages_num'] = $temp[0]['count(*)'] : $chat_info['messages_num'] = '';
    $temp = eF_getTableData("chatmessages", "timestamp", "users_LOGIN='$login'", "timestamp desc limit 1");
    sizeof($temp) > 0 ? $chat_info['last_message'] = '#filter:timestamp_time-'.$temp[0]['timestamp'].'#' : $chat_info['last_message'] = '';

    $num_comments = eF_numberOfComments($login, $lessons_ID);

    $user_info['communication'] = array(_FORUMPOSTS       => $forum_info['messages_num'],
                                        _FORUMLASTMESSAGE => $forum_info['last_message'],
                                        _PERSONALMESSAGES => $p_messages_info['messages_num'][0]['count(*)'],
                                        _MESSAGESFOLDERS  => $p_messages_info['folders_num'][0]['count(*)'],
                                        _FILES            => $p_messages_info['volume'][0],
                                        _FOLDERS          => $p_messages_info['volume'][1],
                                        _TOTALSIZE        => ceil($p_messages_info['volume'][2] / 1000).' KB',
                                        _CHATMESSAGES     => $chat_info['messages_num'],
                                        _CHATLASTMESSAGE  => $chat_info['last_message'],
                                        _COMMENTS         => $num_comments);

    $last_login = eF_getTableData("logs", "timestamp", "action='login' and users_LOGIN='".$login."'", "timestamp desc");
    sizeof($last_login) > 0 ? $last_login = '#filter:timestamp_time-'.$last_login[0]['timestamp'].'#' : $last_login = '';

    $total_logins = eF_getTableData("logs", "count(*)", "action='login' and users_LOGIN='".$login."'");
    $total_logins = $total_logins[0]['count(*)'];

    $month_logins = eF_getTableData("logs", "count(*)", "timestamp > ".(time() - 2592000)." and action='login' and users_LOGIN='".$login."'");
    $month_logins = $month_logins[0]['count(*)'];

    $week_logins = eF_getTableData("logs", "count(*)", "timestamp > ".(time() - 604800)." and action='login' and users_LOGIN='".$login."'");
    $week_logins = $week_logins[0]['count(*)'];

    $temp = eF_getUserTimes($login);
    sizeof($temp['duration']) > 0 ? $mean_duration = ceil((array_sum($temp['duration']) / sizeof($temp['duration'])) / 60) : $mean_duration = 0;

    $temp = eF_getUserTimes($login, array('from' => time() - 2592000, 'to' => time()));
    sizeof($temp['duration']) > 0 ? $month_mean_duration = ceil((array_sum($temp['duration']) / sizeof($temp['duration']) / 60)) : $month_mean_duration = 0;

    $temp = eF_getUserTimes($login, array('from' => time() - 604800, 'to' => time()));
    sizeof($temp['duration']) > 0 ? $week_mean_duration = ceil((array_sum($temp['duration']) / sizeof($temp['duration']) / 60)) : $week_mean_duration = 0;

    
    $user_info['usage'] = array(_LASTLOGIN         => $last_login,
                                _TOTALLOGINS       => $total_logins,
                                _MONTHLOGINS       => $month_logins,
                                _WEEKLOGINS        => $week_logins,
                                _MEANDURATION      => $mean_duration."'",
                                _MONTHMEANDURATION => $month_mean_duration."'",
                                _WEEKMEANDURATION  => $week_mean_duration."'");
                                
    $user_info['tmp'] = array('last_login' => $last_login);
    
    
    switch($general_info[0]['user_type']) {
        case 'administrator':
            break;
        case 'professor':
            $lessons_info = array();
            
            if ($_SESSION['s_type'] == 'professor') {
                if ($lessons_ID)
                    $lessons = eF_getTableData("users_to_lessons ul, lessons l", "l.id, l.name", "ul.users_LOGIN = '".$login."' and ul.lessons_ID = l.id and ul.users_LOGIN='".$_SESSION['s_login']."' and l.id=$lessons_ID");
                else
                    $lessons = eF_getTableData("users_to_lessons ul, lessons l", "l.id, l.name", "ul.users_LOGIN = '".$login."' and ul.lessons_ID = l.id and ul.users_LOGIN='".$_SESSION['s_login']."'");
            } else {
                if ($lessons_ID)
                    $lessons = eF_getTableData("users_to_lessons ul, lessons l", "l.id, l.name", "ul.users_LOGIN = '".$login."' and ul.lessons_ID = l.id and l.id=$lessons_ID");
                else
                    $lessons = eF_getTableData("users_to_lessons ul, lessons l", "l.id, l.name", "ul.users_LOGIN = '".$login."' and ul.lessons_ID = l.id");
            }
            
            foreach ($lessons as $lesson) {
                $lessons_info['name'][] = $lesson['name'];
                $lessons_info['id'][]   = $lesson['id'];
                $lessons_info['time'][] = ef_getUserLessonTime($lesson['id'], $login,0,time());
            }
            $user_info['lessons_info'] = $lessons_info;
            break;
        case 'student':
            if ($_SESSION['s_type'] == 'professor') {
                if ($lessons_ID)
                    $lessons = eF_getTableData("users_to_lessons ul1, users_to_lessons ul2, lessons l", "l.id, l.name", "ul1.users_LOGIN = '".$login."' and ul2.users_LOGIN='".$_SESSION['s_login']."' and ul1.lessons_ID = l.id and ul1.lessons_ID = ul2.lessons_ID and l.id=$lessons_ID");
                else
                    $lessons = eF_getTableData("users_to_lessons ul1, users_to_lessons ul2, lessons l", "l.id, l.name", "ul1.users_LOGIN = '".$login."' and ul2.users_LOGIN='".$_SESSION['s_login']."' and ul1.lessons_ID = l.id and ul1.lessons_ID = ul2.lessons_ID");
                    
            } else {
                if ($lessons_ID)
                    $lessons = eF_getTableData("users_to_lessons ul, lessons l", "l.id, l.name", "ul.users_LOGIN = '".$login."' and ul.lessons_ID = l.id AND l.active=1 and l.id=$lessons_ID"); //makriria. ebala to active=1 oste na emfanizei mono ta energopoimena mathimata. etsi ki allios sta deactivated ta ebgaze ola 0.
                else
                    $lessons = eF_getTableData("users_to_lessons ul, lessons l", "l.id, l.name", "ul.users_LOGIN = '".$login."' and ul.lessons_ID = l.id AND l.active=1"); //makriria. ebala to active=1 oste na emfanizei mono ta energopoimena mathimata. etsi ki allios sta deactivated ta ebgaze ola 0.
            }
            foreach ($lessons as $lesson) {
                $lessons_info['id'][]           = $lesson['id'];
                $lessons_info['name'][]         = $lesson['name'];
                $lessons_info['content_done'][] = eF_usersContentDone($login, $lesson['id']);
                $lessons_info['done_tests'][]   = eF_getTableDataFlat("done_tests, tests, content", "content.name, done_tests.score, done_tests.timestamp, content.id as test_content_ID", "done_tests.tests_ID=tests.id and tests.content_ID=content.id and content.lessons_ID=".$lesson['id']." and done_tests.users_login='$login'");
                $lessons_info['done_projects'][] = eF_getTableDataFlat("users_to_projects, projects", "projects.title, users_to_projects.grade, users_to_projects.upload_timestamp", "users_to_projects.projects_ID=projects.id and users_to_projects.users_LOGIN='$login' and projects.lessons_ID=".$lesson['id']);
                $lessons_info['time'][] = ef_getUserLessonTime($lesson['id'], $login,0,time());
            }
            $user_info['lessons_info'] = $lessons_info;
            break;
        default: break;
    }       
    return $user_info;    
}







/**
 * Returns all the done tests for a specified test
 * 
 * This function returns an array which holds the information for the done tests of a specific test
 * @param int $test_id The id of the specified test
 * @return array An array with the information for the done tests
 * @version 1.0 (10/6/2007)  
*/
function ef_getDoneTests($test_id){
    $done_tests = ef_getTableData("done_tests","*",'tests_ID="'.$test_id.'"');
    return $done_tests;
}

function ef_getTestInfo($test_id){
    $info = array();
    
    $common = ef_getTableData("tests t, content c, lessons l", "c.name as test_name, t.duration, l.name as lesson_name, l.id as lesson_id", "l.id = c.lessons_ID and t.content_id = c.id and t.id=$test_id");
    $questions = ef_getTableData("tests_to_questions t, questions q", "q.id, q.text, q.type, q.options", "t.tests_ID=$test_id AND t.questions_ID = q.id");
    $info['common_info'] = array();
    $info['common_info']['name'] = $common[0]['test_name'];
    $info['common_info']['lesson_name'] = $common[0]['lesson_name'];    
    $info['common_info']['duration'] = $common[0]['duration'];
    $info['common_info']['questions_number'] = sizeof($questions);
    
    
    $info['questions'] = array();
    for ($i=0; $i<sizeof($questions); $i++){
        $info['questions'][$i]['id'] = $questions[$i]['id'];
        mb_strlen(strip_tags($questions[$i]['text'])) > 50 ? $info['questions'][$i]['text'] = mb_substr(strip_tags($questions[$i]['text']), 0, 50).'...' : $info['questions'][$i]['text'] = strip_tags($questions[$i]['text']);
        $info['questions'][$i]['full_text'] = $questions[$i]['text'];
       
        switch ($questions[$i]['type']){
            case 'raw_text': $info['questions'][$i]['type'] = _RAWTEXT; break;
            case 'multiple_one': $info['questions'][$i]['type'] = _MULTIPLEONE; break;
            case 'multiple_many': $info['questions'][$i]['type'] = _MULTIPLEMANY; break;
            case 'true_false': $info['questions'][$i]['type'] = _TRUEFALSE; break;
            case 'empty_spaces': $info['questions'][$i]['type'] = _EMPTYSPACES; break;
            case 'match': $info['questions'][$i]['type'] = _MATCH; break;
        }
        $correct = ef_getTableData("done_questions q, done_tests t","*", "q.done_tests_id = t.id and t.tests_ID = $test_id and questions_ID='".$questions[$i]['id']."' and q.score = 1");
        $false = ef_getTableData("done_questions q, done_tests t","*", "q.done_tests_id = t.id and t.tests_ID = $test_id and q.questions_ID='".$questions[$i]['id']."' and q.score = 0");
        $info['questions'][$i]['correct'] = sizeof($correct);
        $info['questions'][$i]['false'] = sizeof($false);
    }
    
    return $info;
}
?>
