<?php
/*
    DOKEOS - elearning and course management software

    For a full list of contributors, see documentation/credits.html

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.
    See "documentation/licence.html" more details.

    Contact: Zhong	poopsoft@163.com
*/

/**
*	@package iilearn.main
* 	@author Patrick Cool <patrick.cool@UGent.be>, Ghent University, Refactoring
* 	@version $Id: index.php 11924 2007-04-08 16:30:56Z pcool $
*   @todo check the different @todos in this page and really do them
* 	@todo check if the news management works as expected
*/

// only this script should have this constant defined. This is used to activate the javascript that
// gives the login name automatic focus in header.inc.html.
/** @todo  Couldn't this be done using the $HtmlHeadXtra array? */
define('DOKEOS_HOMEPAGE', true);

// the language file
$language_file = array ('courses', 'index');

/* Flag forcing the 'current course' reset, as we're not inside a course anymore  */
// maybe we should change this into an api function? an example: Coursemanager::unset();
$cidReset = true;



/*
-----------------------------------------------------------
	Included libraries
-----------------------------------------------------------
*/
/** @todo make all the library files consistent use filename.lib.php and not filename.lib.inc.php */
require_once ('./main/inc/global.inc.php');
include_once (api_get_path(LIBRARY_PATH).'course.lib.php');
include_once (api_get_path(LIBRARY_PATH).'debug.lib.inc.php');
include_once (api_get_path(LIBRARY_PATH).'events.lib.inc.php');
include_once (api_get_path(LIBRARY_PATH).'system_announcements.lib.php');
include_once (api_get_path(LIBRARY_PATH).'groupmanager.lib.php');
include_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');

include_once('./main/course/course.inc.php');

$loginFailed = isset($_GET['loginFailed']) ? true : isset($loginFailed);

// the section (for the tabs)
$this_section = SECTION_CAMPUS;

/*
-----------------------------------------------------------
	Action Handling
-----------------------------------------------------------
*/
/** @todo 	wouldn't it make more sense if this would be done in local.inc.php so that local.inc.php become the only place where authentication is done?
 * 			by doing this you could logout from any page instead of only from index.php. From the moment there is a logout=true in the url you will be logged out
 * 			this can be usefull when you are on an open course and you need to log in to edit something and you immediately want to check how anonymous users
 * 			will see it.
 */
if ($_GET['logout'])
{
	logout();
}

/*
-----------------------------------------------------------
	Table definitions
-----------------------------------------------------------
*/
$main_course_table 		= Database :: get_main_table(TABLE_MAIN_COURSE);
$main_category_table 	= Database :: get_main_table(TABLE_MAIN_CATEGORY);
$track_login_table 		= Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);

/*
-----------------------------------------------------------
	Constants and CONFIGURATION parameters
-----------------------------------------------------------
*/
/** @todo these configuration settings should move to the dokeos config settings */
/** defines wether or not anonymous visitors can see a list of the courses on the Dokeos homepage that are open to the world */
$_setting['display_courses_to_anonymous_users'] = 'true';
/** defines weither empty course categories should appear in the list with the course categories */
$_setting['show_empty_course_categories'] = 'true';
/** defines weither the number of open courses has to appear after the course category (faculty) */
/** remark: actually count are only for direct children */
$_setting['show_number_of_courses'] = 'false';
/** Show the back link on top of the tree */
$_setting['show_back_link_on_top_of_tree'] = 'false';
/** Show the course language if it is not the same as the platform lanugage */
$_setting['show_different_course_language'] = 'true';


/** @todo remove this piece of code because this is not used */
if (isset ($_user['user_id']))
{
	$nameTools = api_get_setting('siteName');
}

/*
==============================================================================
		LOGIN
==============================================================================
*/
/**
 * @todo This piece of code should probably move to local.inc.php where the actual login / logout procedure is handled.
 * @todo consider removing this piece of code because does nothing.
 */
if ($_GET["submitAuth"] == 1)
{
	// nice lie!!!
	echo "Attempted breakin - sysadmins notified.";
	session_destroy();
	die();
}

/**
 * @todo This piece of code should probably move to local.inc.php where the actual login procedure is handled.
 * @todo check if this code is used. I think this code is never executed because after clicking the submit button
 * 		 the code does the stuff in local.inc.php and then redirects to index.php or user_portal.php depending
 * 		 on api_get_setting('page_after_login')
 */
if ($_POST["submitAuth"])
{
	// the user is already authenticated, we now find the last login of the user.
	if (isset ($_user['user_id']))
	{
		$sql_last_login = "SELECT UNIX_TIMESTAMP(login_date)
								FROM $track_login_table
								WHERE login_user_id = '".$_user['user_id']."'
								ORDER BY login_date DESC LIMIT 1";
		$result_last_login = api_sql_query($sql_last_login, __FILE__, __LINE__);
		if (!$result_last_login)
			if (mysql_num_rows($result_last_login) > 0)
			{
				$user_last_login_datetime = mysql_fetch_array($result_last_login);
				$user_last_login_datetime = $user_last_login_datetime[0];
				api_session_register('user_last_login_datetime');
			}
		mysql_free_result($result_last_login);

		//event_login();
		if (api_is_platform_admin())
		{
			// decode all open event informations and fill the track_c_* tables
			include (api_get_path(LIBRARY_PATH)."stats.lib.inc.php");
			decodeOpenInfos();
		}
	}
} // end login -- if($_POST["submitAuth"])
else
{
	// only if login form was not sent because if the form is sent the user was already on the page.
	event_open();
}

$htmlHeadXtra[] = get_table_style_ie6();

// the header
Display :: display_header('', 'dokeos');

/*
==============================================================================
		MAIN CODE
==============================================================================
*/
echo '<div class="maincontent" id="content">';

// Plugins for loginpage_main AND campushomepage_main
if (!api_get_user_id())
{
	api_plugin('loginpage_main');
}
else
{
	api_plugin('campushomepage_main');
}

display_courses_subscribing();

echo '</div>';

echo '<div class="menu" id="menu">';

// display login form
if (!isset($_user['user_id']))
{
    echo '<h3>' . get_lang('UserLogin') . '</h3>';
    echo '<div class="menusection">';
    display_anonymous_right_menu(); 
    echo '</div>';
}

// display system announcement
display_system_announcement(); 

echo '</div>';

/*
==============================================================================
		FOOTER
==============================================================================
*/
Display :: display_footer();


/**
 * allows you to browse or search through the course categories (faculties) and subscribe to the courses of
 * this category (faculty)
 * @author Zhong <poopsoft@163.com>
*/
function display_courses_subscribing()
{
	$categoryName = get_category_name(Database::escape_string($_GET['category']));
	$html = "<div class='homeCategory'>\n";
	$html .= "<table border=0 class='contentData' cellspacing='0'>\n";
	$html .= "<tr>\n";
	$html .= "<th align='left'>" . Display::return_icon("star.gif") . "&nbsp;" . get_lang("CourseCategories") . (!empty($categoryName) ? " - " . $categoryName : "") . "</th>\n";
	$html .= "</tr>\n";
	$html .= "<tr>\n";	
	$html .= "<td width='40%' align='left' valign='top'>\n";
	$html .= display_course_categories(Database::escape_string($_GET['category']), $_GET['up']);
	$html .= "</td>\n";
	$html .= "</tr>\n";
	$html .= "</table>\n";
	$html .= "</div>\n";

	$html .= display_courses_in_category(Database::escape_string($_GET['category']), Database::escape_string($_GET['start']), Database::escape_string($_REQUEST['search_term']));
	
	echo  $html;
}

/**
 * This function handles the logout and is called whenever there is a $_GET['logout']
 *
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 */
function logout()
{
	// variable initialisation
	$query_string='';

	if(!empty($_SESSION['user_language_choice']))
	{
		$query_string='?language='.$_SESSION['user_language_choice'];
	}

	// Database table definition
	$tbl_track_login = Database :: get_statistic_table(TABLE_STATISTIC_TRACK_E_LOGIN);

	// selecting the last login of the user
	$uid = intval($_GET['uid']);
	$sql_last_connection="SELECT login_id, login_date FROM $tbl_track_login WHERE login_user_id='$uid' ORDER BY login_date DESC LIMIT 0,1";
	$q_last_connection = api_sql_query($sql_last_connection, __FILE__, __LINE__);
	
	$i_id_last_connection=mysql_result($q_last_connection,0,"login_id");

	$s_sql_update_logout_date="UPDATE $tbl_track_login SET logout_date=NOW() WHERE login_id='$i_id_last_connection'";
	api_sql_query($s_sql_update_logout_date,__FILE__,__LINE__);

	LoginDelete($uid, $_configuration['statistics_database']);

	api_session_destroy();

	header("Location: index.php$query_string");
	exit();
}

/**
 * This function checks if there are courses that are open to the world in the platform course categories (=faculties)
 *
 * @param unknown_type $category
 * @return boolean
 */
function category_has_open_courses($category)
{
	$main_course_table = Database :: get_main_table(TABLE_MAIN_COURSE);
	$sql_query = "SELECT * FROM $main_course_table WHERE category_code='$category'";
	$sql_result = api_sql_query($sql_query, __FILE__, __LINE__);
	while ($course = mysql_fetch_array($sql_result))
	{
		if ($course['visibility'] == COURSE_VISIBILITY_OPEN_WORLD)
		{
			return true; //at least one open course
		}
	}
	return false;
}

/**
 * Displays the right-hand menu for anonymous users:
 * login form, useful links, help section
 * Warning: function defines globals
 * @version 1.0.1
 * @todo does $_plugins need to be global?
 */
function display_anonymous_right_menu()
{
	global $loginFailed, $_plugins, $_user;

	$platformLanguage = api_get_setting('platformLanguage');

	if ( !($_user['user_id']) ) // only display if the user isn't logged in
	{
		api_display_language_form();
		//hgz 20070420
		//echo '<br />';
		display_login_form();
		
		/* hgz 20070709 it is only used by demo
		echo '&nbsp;&nbsp teacher &nbsp;&nbsp; 123456' . '<br>';
		echo '&nbsp;&nbsp student &nbsp;&nbsp; 123456' . '<br>';
		*/
		
		if ($loginFailed)
		{
			handle_login_failed();
		}

		if (api_get_setting('allow_lostpassword') == 'true' || api_get_setting('allow_registration') == 'true')
		{
			if (get_setting('allow_registration') <> 'false') {
				$strUrl = '<a href="main/auth/inscription.php">' . get_lang('Reg') . '</a>&nbsp;&nbsp;&nbsp;&nbsp;';
			}
			if (get_setting('allow_lostpassword') == 'true') {
				$strUrl .= '<a href="main/auth/lostPassword.php">' . get_lang('LostPassword') . '</a>';
			}
			if (isset($strUrl)) {
				echo '<ul class="menulist">';
				echo $strUrl;
				echo '</ul>';
			}
		}

		if(api_number_of_plugins('loginpage_menu') > 0)
		{
			echo '<div class="note" style="background: none">';
			api_plugin('loginpage_menu');
			echo '</div>';
		}
	}

	if ($_user['user_id'] && api_number_of_plugins('campushomepage_menu') > 0)
	{
		echo '<div class="note" style="background: none">';
		api_plugin('campushomepage_menu');
		echo '</div>';
	}

/**** use this comment to hide notice file section from right menu ****

	echo '<div class="note">';
	// includes for any files to be displayed below anonymous right menu
	if(!file_exists('home/home_notice_'.$user_selected_language.'.html'))
	{
		include ('home/home_notice.html');
	}
	else
	{
		include('home/home_notice_'.$user_selected_language.'.html');
	}
	echo '</div>';

**** end of hide various right menu items on anonymous right menu ****/
}

/**
*	Reacts on a failed login:
*	displays an explanation with
*	a link to the registration form.
*
*	@version 1.0.1
*/
function handle_login_failed()
{
	switch ($_GET['error'])
	{
		case '':
			$message = get_lang("InvalidId");
			if (api_is_self_registration_allowed())
			{
				$message = get_lang("InvalidForSelfRegistration");
			}
			break;
		case 'account_expired':
			$message=get_lang('AccountExpired');
			break;
		case 'account_inactive':
			$message=get_lang('AccountInactive');
			break;
		case 'user_password_incorrect':
			$message=get_lang('InvalidId');
			break;
	}
	echo "<div id=\"login_fail\">".$message."</div>";
}

/**
*	Adds a form to let users login
*	@version 1.1
*/
function display_login_form()
{
	$form = new FormValidator('formLogin');
	$form->addElement('text','login',get_lang('UserName'),array('size'=>15));
	$form->addElement('password','password',get_lang('Pass')."&nbsp;",array('size'=>15));
	$form->addElement('submit','submitAuth',get_lang('Ok'),'class="inputSubmit"');
	$renderer =$form->defaultRenderer();
	//hgz
	$renderer->setFormTemplate('<form{attributes}><div class="formLogin">{content}</div></form>');
	$renderer->setElementTemplate('<div><label>{label}</label></div><div>{element}</div>');
	
	$form->display();
}
/**
 * Displays a link to the lost password section
 */
function display_lost_password_info()
{
	echo "<li><a href=\"main/auth/lostPassword.php\">".get_lang("LostPassword")."</a></li>";
}

function display_system_announcement()
{
    global $_user;
    if (isset($_user['user_id']))
    {
        $visibility = api_is_allowed_to_create_course() ? VISIBLE_TEACHER : VISIBLE_STUDENT;
    } else {
        $visibility = VISIBLE_GUEST;    
    }
    $announcement = $_GET['announcement'] ? $_GET['announcement'] : -1;
    $announcement = intval($announcement);
    SystemAnnouncementManager :: display_announcements($visibility, $announcement);
}
?>