<?php
/**
* Chat functionality page
*
* This page implements the chat functionality. It is the iframe's target. 
*
* @package eFront
* @version 0.1
* @todo Limited users per room
* @todo Limited rooms
*/

session_cache_limiter('none');
session_start();

$path = "../libraries/";

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

if (!eF_checkUser($_SESSION['s_login'],  $_SESSION['s_password'])) {                   //Only a valid user may access this page
    header("location: index.php");
    exit;
}

$chatrooms_ID = $_GET['chatrooms_ID'];

$messages_limit = 400;                                                                 //The messages list limit
$data = '';

    if (isset($_POST['submit']) || isset($_POST['chat_message']) ) {                                         //The user posted a message. IF the user just pressed enter, in IE POST['submit'] is not set!!!!!, so we include the || clause...
        if ($_POST['chat_message']!='') {
            $fields_insert = array('users_LOGIN'     => $_SESSION['s_login'],
                                   'users_USER_TYPE' => $_SESSION['s_type'],
                                   'content'         => htmlspecialchars($_POST['chat_message'], ENT_QUOTES),
                                   'timestamp'       => time(),
                                   'chatrooms_ID'    => $chatrooms_ID);        
            eF_insertTableData("chatmessages", $fields_insert);                             //Insert the message into the database
        }
    }

    isset($_GET['standalone']) ? $standalone_str = '&standalone=1' : $standalone_str = '';      //Is it the stand-alone version of the window?

    $rooms_str = '
    	<table cellpadding = "1" >';                                          //Display public and private rooms list

    $public_rooms  = eF_getTableData("chatrooms, users_to_chatrooms", "distinct chatrooms.id, chatrooms.name, count(*)", "chatrooms.active=1 AND chatrooms.type = 'public' and users_to_chatrooms.chatrooms_ID = chatrooms.id group by id");
    $private_rooms = eF_getTableData("chatrooms, users_to_chatrooms", "distinct chatrooms.id, chatrooms.name, chatrooms.users_LOGIN, count(*)", "chatrooms.active=1 AND chatrooms.type = 'private' and users_to_chatrooms.chatrooms_ID = chatrooms.id group by id");

    for ($i = 0; $i < sizeof($public_rooms); $i++) {                                    //The public rooms string part
        if (mb_strlen($public_rooms[$i]['name']) > 20) {
			$room_name = mb_substr($public_rooms[$i]['name'],0,17)."...";	
		}else{
			$room_name = $public_rooms[$i]['name'];
		}
		
		if ($public_rooms[$i]['id'] != $chatrooms_ID) {	
            $rooms_str .= '<tr><td>'.($i+1).'. <a href = "chat/chat_index.php?chatrooms_ID='.$public_rooms[$i]['id'].$standalone_str.'" >'.$room_name.'</a> (<a href = "/chat/chat_room_options.php?show_users='.$public_rooms[$i]['id'].'" target = "POPUP_FRAME" onclick = "eF_js_showDivPopup(&quot;'._PARTICIPANTS.'&quot;, new Array(&quot;200px&quot;, &quot;200px&quot;))">'.$public_rooms[$i]['count(*)'].'</a>)</td></tr>';
        } else {
            $notice = '<tr><td>'._NOTEPUBLICROOMSARESTOREDANDACCESSED.'.</td></tr>';
            $rooms_str .= '<tr><td>'.($i+1).'. '.$room_name.' (<a href = "chat/chat_room_options.php?show_users='.$public_rooms[$i]['id'].'" target = "POPUP_FRAME" onclick = "eF_js_showDivPopup(&quot;'._PARTICIPANTS.'&quot;, new Array(&quot;200px&quot;, &quot;200px&quot;))">'.$public_rooms[$i]['count(*)'].'</a>)</td></tr>';
        }
    }
    for ($j = 0; $j < sizeof($private_rooms); $j++) {                                   //The private rooms string part
        if (mb_strlen($private_rooms[$j]['name']) > 20){
			$room_name = mb_substr($private_rooms[$j]['name'], 0, 17)."...";	
		} else {
			$room_name = $private_rooms[$j]['name'];
		}
		
		if ($private_rooms[$j]['id'] != $chatrooms_ID) {
            $rooms_str .= '<tr><td>'.($j+1+$i).'. <a href = "chat/chat_index.php?chatrooms_ID='.$private_rooms[$j]['id'].$standalone_str.'">'.$room_name.'</a> (<a href = "chat/chat_room_options.php?show_users='.$public_rooms[$i]['id'].'" target = "POPUP_FRAME" onclick = "eF_js_showDivPopup(&quot;'._PARTICIPANTS.'&quot;, new Array(&quot;200px&quot;, &quot;200px&quot;))">'.$private_rooms[$j]['count(*)'].'</a>) *</td></tr>';
        } else {
            //$room_name = $private_rooms[$j]['name'];
            $rooms_str .= '<tr><td>'.($i+1).'. '.$room_name.' (<a href = "chat/chat_room_options.php?show_users='.$public_rooms[$i]['id'].'" target = "POPUP_FRAME" onclick = "eF_js_showDivPopup(&quot;'._PARTICIPANTS.'&quot;, new Array(&quot;200px&quot;, &quot;200px&quot;))">'.$private_rooms[$j]['count(*)'].'</a>) * </td></tr>';
        }
    }    

    if (sizeof($private_rooms) > 0) {
        $rooms_str .= '<table><tr><td>*: '._PRIVATEROOM.'</td></tr></table>';                                                                              //Display footnote
    } 
    
    $rooms_str .= '</table>';

    $users_str = array();                                                               //Build the users list. Professors are displayed in blue, and administrators in red
    $users = eF_getTableDataFlat("users_to_chatrooms", "users_LOGIN, users_USER_TYPE, timestamp", "chatrooms_ID=".$chatrooms_ID);

    for ($i = 0; isset($users['users_LOGIN']) && $i < sizeof($users['users_LOGIN']); $i++) {                            //Check each user type, to display in different color
        switch ($users['users_USER_TYPE'][$i]) {
            case 'professor':                                                           //Professor: blue bold
                $style_str = 'font-weight:bold;color:blue';
                break;
            case 'administrator':
                $style_str = 'font-weight:bold;color:red';                              //Administrator: red bold
                break;
            default:
                $style_str = '';                                                        //Everybody else: default
                break;
        }

        if ($users['users_LOGIN'][$i] != $_SESSION['s_login']) {
            $users_str[] = '<a href = "chat/chat_index.php?chatrooms_ID='.$chatrooms_ID.'&invite='.$users['users_LOGIN'][$i].'&standalone=1" target = "POPUP_FRAME" onclick = "eF_js_showDivPopup(&quot;'._INVITE.'&quot;, new Array(&quot;600px&quot;, &quot;400px&quot;))">'.$users['users_LOGIN'][$i].'</a>';                                   //Make the strings an array, so we may then implode() it with commas
        } else {                                                                        //Check if we are logged in the chat
            $offset = $i;
            $enter_time = $users['timestamp'][$i];                                      //Keep the entrance time so we display only messages after this time
        }
    }

    if (sizeof($users_str) > 0) {
        $users_str = '<table cellpadding = "1"><tr><td>'.implode(", ", $users_str).'</td></tr></table>';                 //The users list string
    } else {
        $users_str = '<table><tr><td class = "emptyCategory"><span title="'._THEREARENOOTHERUSERSRIGHTNOWINTHISROOM.'">'.mb_substr(_THEREARENOOTHERUSERSRIGHTNOWINTHISROOM,0 ,30).'...</span></td></tr></table>';    //The users list string
    }

    $all_messages = 0;
    $last_id = isset($_SESSION['last_id'])?$_SESSION['last_id']:0;

    if (!isset($_POST['chat_message'])) {
        $messages = eF_getTableData("chatmessages", "users_LOGIN, users_USER_TYPE, timestamp, content, id", "timestamp > $enter_time AND chatrooms_ID = $chatrooms_ID AND id > $last_id", "timestamp DESC,id DESC LIMIT $messages_limit");     //Retrieve the recent messages

        if (sizeof($messages)>0) {
            $new_id = $messages[0]['id'];
        } else {
            $new_id = $last_id;
        }
        $_SESSION['last_id'] = $new_id;
    } else {
        $messages = eF_getTableData("chatmessages", "users_LOGIN, users_USER_TYPE, timestamp, content, id", "timestamp > $enter_time AND chatrooms_ID = $chatrooms_ID AND id > $last_id", "timestamp DESC, id DESC LIMIT 1");     //Retrieve the most recent message 
        if (sizeof($messages) > 0) {
            $new_id = $messages[0]['id'];
        } else {
            $new_id = $sent;
        }
        $_SESSION['last_id'] = $new_id;
    }

    $new_msg = false;
    if ($_SESSION['last_message'][$chatrooms_ID] != $messages[0]['timestamp']) {
        $_SESSION['last_message'][$chatrooms_ID] = $messages[0]['timestamp'];
        $new_msg = array('user' => $messages[0]['users_LOGIN'], 'message' => $messages[0]['content']);
        if (mb_strlen($new_msg['message']) > 15) {
            $new_msg['message'] = mb_substr($new_msg['message'], 0, 25).'...';
        }
    }


    //isset($_GET['standalone']) ? $font_size = 'font-size:10px;' : $font_size = 'font-size:14px;';
    $font_size = 'font-size:11px;';
    
    foreach ($messages as $value) {                                                     //Loop through messages, so that they are displayed in different format, depending on the message poster
        if ($value['users_LOGIN'] == $_SESSION['s_login']) {                        
            $span_style = 'color:darkorange;';                                           //Own messages are displayed in darkorange
        } elseif ($value['users_USER_TYPE'] == 'professor') {
            $span_style = 'color:blue;';                                                 //Professor messages are displayed in blue
        } elseif ($value['users_USER_TYPE'] == 'administrator') {
            $span_style = 'color:red;';                                                  //Administrator messages are displayed in red
        } else {
            $span_style = '';                                                            //Other messages are displayed in default format
        }
        

        date("ymd", time()) == date("ymd", $value['timestamp']) ? $time_str = date("H:i:s", $value['timestamp']) : $time_str = eF_timestampToTime($value['timestamp'], true);       //for today's messages don't display date, only time.
        if ($value['content'][0] != '#' || !preg_match("/^#for_user-(\S*):(\d+)#/", $value['content'], $matches) || ($matches[1] == $_SESSION['s_login'] && $value['content'] = mb_substr($value['content'], mb_strlen($matches[0])))) {     //Explanation for this line: The first part, $value['content'][0] != '#' , is a fast check for the special character #. if it does not exist, proceed and display message. Otherwise, check if the character is followed by a specific sequence, of the form: #for_user-<login>#. If so, then display only the message to the current user (where $_SESSION['s_login'] == <login>) and finally delete the special sequence from the beginning of the message (the mb_substr part). otherwise (if it starts with # but is not a special message), display the message.
            $data .= '<span style="'.$span_style.$font_size.'">'.$time_str.' '.$value['users_LOGIN'].': '.$value['content'].'</span><br/>';     //Display the message, along with any notification message
        }
    }

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
//header("Content-type: text/html;charset="._CHARSET);

$data = eF_convertTextToSmilies($data);
//$data = iconv("UTF-8",_CHARSET,$data);
//echo $data."special_splitter"."new_limit: ".$new_limit."<br>all messages: ".$all_messages."<br>sent: ".$sent."<br>new_limit_flag: ".$new_limit_flag."-|*special_splitter*|-".$rooms_str."-|*special_splitter*|-".$new_limit."-|*special_splitter*|-".$sent; 
echo $data."special_splitter".$users_str."special_splitter".$rooms_str."special_splitter".$new_id; 

?>
