<?php // $Id: course_home.php,v 1.103 2005/06/28 23:56:31 olivierb78 Exp $
/*
==============================================================================
	Dokeos - elearning and course management software

	Copyright (c) 2004 Dokeos S.A.
	Copyright (c) 2003 University of Ghent (UGent)
	Copyright (c) 2001 Universite catholique de Louvain (UCL)
	Copyright (c) various contributors

	For a full list of contributors, see "credits.txt".
	The full license can be read in "license.txt".

	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 the GNU General Public License for more details.

	Contact: Dokeos, 181 rue Royale, B-1000 Brussels, Belgium, info@dokeos.com
==============================================================================
*/
/**
==============================================================================
*                  HOME PAGE FOR EACH COURSE
*
*	This page, included in every course's index.php is the home
*	page. To make administration simple, the teacher edits his
*	course from the home page. Only the login detects that the
*	visitor is allowed to activate, deactivate home page links,
*	access to the teachers tools (statistics, edit forums...).
*
* Edit visibility of tools
*
*     visibility = 1 - everybody
*     visibility = 0 - course admin (teacher) and platform admin
*     visibility = 2 - platform admin
*
* Who can change visibility ?
*
*     admin = 0 - course admin (teacher) and platform admin
*     admin = 1 - platform admin
*
* Show message to confirm that a tools must be hide from aivailable tools
*
*     visibility 0,1->2 - $remove
*
* Deleting tools or hiding them from the list of available tools.
*
*     visibility = 2 are only displayed to platform admin
*     visibility 0,1->2 - $destroy
*
*     visibility 1 -> 0 - $hide / $restore
*
*	@package dokeos.course_home
==============================================================================
*/

/*
==============================================================================
		INIT SECTION
==============================================================================
*/

if (!isset($cidReq))
{
	$cidReq = $dbname;  // to provide compatibility. with previous  system

	GLOBAL $error_msg,$error_no;

	$classError = "init";	$error_no[$classError][] = "2";
	$error_level[$classError][] = "info";
	$error_msg[$classError][] = "[".__FILE__."][".__LINE__."] cidReq was Missing $cidReq take $dbname;";

}

$langFile = "course_home";

include('../../claroline/inc/claro_init_global.inc.php');

/*
-----------------------------------------------------------
	Libraries
-----------------------------------------------------------
*/
include_once(api_get_library_path()."/course.lib.php");
include_once(api_get_library_path()."/debug.lib.inc.php");
include_once(api_get_library_path()."/text.lib.php");

/*
-----------------------------------------------------------
	Constants
-----------------------------------------------------------
*/
define ("TOOL_PUBLIC", "Public");
define ("TOOL_PUBLIC_BUT_HIDDEN", "PublicButHide");
define ("TOOL_COURSE_ADMIN", "courseAdmin");
define ("TOOL_PLATFORM_ADMIN", "platformAdmin");

/*
-----------------------------------------------------------
	Virtual course support code
-----------------------------------------------------------
*/
$user_id = api_get_user_id();
$course_code = $_course["sysCode"];
$course_info = Database::get_course_info_from_code($course_code);

$return_result = CourseManager::determine_course_title_from_course_info($_uid, $course_info);
$course_title = $return_result["title"];
$course_code = $return_result["code"];

$_course["name"] = $course_title;
$_course['official_code'] = $course_code;

/*
-----------------------------------------------------------
	Header
-----------------------------------------------------------
*/

$nameTools = $course_title;
Display::display_header($nameTools,"Home");

$is_allowed_to_edit = api_is_allowed_to_edit();

if ($is_allowed_in_course == false) api_not_allowed();


// Stats :
// Count only one time by course and by session
if ( !isset($coursesAlreadyVisited[$_cid]) )
{
	include(api_get_library_path()."/events.lib.inc.php");
	event_access_course();
	$coursesAlreadyVisited[$_cid] = 1;
	api_session_register('coursesAlreadyVisited');
}

$tool_table = Database::get_course_tool_list_table();

$temps=time();
$reqdate="&reqdate=$temps";

/*
==============================================================================
		FUNCTIONS
==============================================================================
*/

/**
 * Displays the tools of a certain category.
 *
 * @return void
 * @param string $cat	contains the category of tools to display:
 * "Public", "PublicButHide", "courseAdmin", "claroAdmin"
 */

function showtools($cat)
{
	$is_allowed_to_edit = api_is_allowed_to_edit();
	$clarolineRepositoryWeb = api_get_path(WEB_CODE_PATH);
	$course_tool_table = Database::get_course_tool_list_table();

	switch ($cat)
	{
		case TOOL_PUBLIC:

				$result = api_sql_query("SELECT * FROM $course_tool_table WHERE visibility=1 ORDER BY id",__FILE__,__LINE__);
				$colLink ="##003399";
				break;

		case TOOL_PUBLIC_BUT_HIDDEN:

				$result = api_sql_query("SELECT * FROM $course_tool_table WHERE visibility=0 AND admin=0 ORDER BY id",__FILE__,__LINE__);
				$colLink ="##808080";
				break;

		case TOOL_COURSE_ADMIN:

				$result = api_sql_query("SELECT * FROM $course_tool_table WHERE admin=1 AND visibility != 2 ORDER BY id",__FILE__,__LINE__);
				$colLink ="##003399";
				break;

		case TOOL_PLATFORM_ADMIN:

				$result = api_sql_query("SELECT * FROM $course_tool_table WHERE visibility = 2 ORDER BY id",__FILE__,__LINE__);
				$colLink ="##003399";
	}

	$i=0;

	// grabbing all the tools from $course_tool_table
	while ($tempRow = mysql_fetch_array($result))
	{
		if($cat == TOOL_PUBLIC_BUT_HIDDEN && $tempRow['image'] != 'scormbuilder.gif')
		{
			$tempRow['image']=str_replace('.gif','_na.gif',$tempRow['image']);
		}

		$toolsRow_all[]=$tempRow;
	}

	// grabbing all the links that have the property on_homepage set to 1
	$tbl_link = Database::get_course_link_table();
	$tbl_item_property = Database::get_course_table(ITEM_PROPERTY_TABLE);
	switch ($cat)
	{
		case TOOL_PUBLIC:
			$sql_links="SELECT tl.*, tip.visibility
					FROM $tbl_link tl
					LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
					WHERE tl.on_homepage='1' AND tip.visibility = 1";
			break;
		case TOOL_PUBLIC_BUT_HIDDEN:
			$sql_links="SELECT tl.*, tip.visibility
				FROM $tbl_link tl
				LEFT JOIN $tbl_item_property tip ON tip.tool='link' AND tip.ref=tl.id
				WHERE tl.on_homepage='1' AND tip.visibility = 0";
			break;
		default:
			$sql_links = null;
			break;
	}
	if( $sql_links != null )
	{
		$result_links=api_sql_query($sql_links,__FILE__,__LINE__);
		while ($links_row=mysql_fetch_array($result_links))
		{
			unset($properties);
			$properties['name']=$links_row['title'];
			$properties['link']=$links_row['url'];
			$properties['visibility']=$links_row['visibility'];
			$properties['image']=($cat == TOOL_PUBLIC_BUT_HIDDEN)?"external_na.gif":"external.gif";
			$properties['adminlink']=api_get_code_web_path()."link/link.php?action=editlink&id=".$links_row['id'];
			$toolsRow_all[]=$properties;
		}
	}
		//echo "<pre>";
		//print_r($toolsRow_all);
		//echo "</pre>";

	if (isset($toolsRow_all))
	{
		foreach ($toolsRow_all as $toolsRow)
		{

			if (!($i%2))
			{
				echo	"<tr valign=\"top\">\n";
			}

			// NOTICE : table tool no longer contains "../claroline/img/" but only the image file name

			if(!stristr($toolsRow['link'],'http://') && !stristr($toolsRow['link'],'https://') && !stristr($toolsRow['link'],'ftp://'))
			{
				$toolsRow['link']=$clarolineRepositoryWeb.$toolsRow['link'];
			}
			if ($cat==TOOL_PUBLIC_BUT_HIDDEN)
			{
			    $class="class=\"invisible\"";
			}
			$qm_or_amp = ((strpos($toolsRow['link'],'?')===FALSE)?'?':'&amp;');
			echo	'<td width="50%" height="30">', "\n",

					'<a href="', htmlspecialchars($toolsRow['link'])
						.(($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif") ? '' : $qm_or_amp.api_get_cidreq()),
						'" target="' , $toolsRow['target'], '" '.$class.'>',
					'<img src="', $clarolineRepositoryWeb, 'img/',
						$toolsRow['image'], '" align="absmiddle" border="0" alt="', $toolsRow['image'],'" />',
					'&nbsp;', ($toolsRow['image']=="external.gif" || $toolsRow['image']=="external_na.gif" || $toolsRow['image']=="scormbuilder.gif") ? htmlspecialchars( $toolsRow['name']) : get_lang($toolsRow['name']),
					"</a>\n ";

			// This part displays the links to hide or remove a tool.
			// These links are only visible by the course manager.
			unset($lnk);
			if ($is_allowed_to_edit)
			{
				if ($toolsRow["visibility"] == '1' && !strpos($toolsRow['link'],'learnpath_handler.php?learnpath_id'))
				{
					$link['name'] = '<img src="'.api_get_path(WEB_CODE_PATH).'img/visible.gif" align="absmiddle" alt="'.get_lang("Deactivate").'"/>';
					$link['cmd'] = "hide=yes";
					$lnk[] = $link;
				}

				if ($cat==TOOL_PUBLIC_BUT_HIDDEN)
				{
					$link['name'] = '<img src="'.api_get_path(WEB_CODE_PATH).'img/invisible.gif" align="absmiddle" alt="'.get_lang("Activate").'"/>';
					$link['cmd']  = "restore=yes";
					$lnk[] = $link;

					if($toolsRow["added_tool"] == 1)
					{
						$link['name'] = '<img src="'.api_get_path(WEB_CODE_PATH).'img/delete.gif" align="absmiddle" alt="'.get_lang("Remove").'"/>';
						$link['cmd']  = "remove=yes";
						$lnk[] = $link;
					}
				}
				if ($toolsRow['adminlink'])
				{
					echo	'<a href="'.$toolsRow['adminlink'].'"><img src="'.api_get_path(WEB_CODE_PATH).'img/edit.gif" align="absmiddle" alt="'.get_lang("Edit").'"/></a>';
					//echo "edit link:".$properties['adminlink'];
				}

			}
			if ( api_is_platform_admin() )
			{
				if ($toolsRow["visibility"]==2)
				{
					$link['name'] = '<img src="'.api_get_path(WEB_CODE_PATH).'img/undelete.gif" align="absmiddle" alt="'.get_lang("Activate").'"/>';

					$link['cmd']  = "hide=yes";
					$lnk[] = $link;

					if($toolsRow["added_tool"] == 1)
					{
						$link['name'] = get_lang("Delete");
						$link['cmd'] = "askDelete=yes";
						$lnk[] = $link;
					}
				}

				if ($toolsRow["visibility"] == 0 && $toolsRow["added_tool"] == 0)
				{
					$link['name'] = '<img src="'.api_get_path(WEB_CODE_PATH).'img/delete.gif" align="absmiddle" alt="'.get_lang("Remove").'"/>';
					$link['cmd'] = "remove=yes";
					$lnk[] = $link;
				}
			}
			if (is_array($lnk))
			{
				foreach($lnk as $this_link)
				{
					if (!$toolsRow['adminlink'])
						{
							echo "<a href=\"" . $_SERVER['PHP_SELF'] . "?".api_get_cidreq()."&amp;id=" . $toolsRow["id"] . "&amp;" . $this_link['cmd'] . "\">" .	$this_link['name'] . "</a>";
						}
				}
			}

			// Allow editing of invisible homepage links (modified external_module)
			if ($toolsRow["added_tool"] == 1 &&
					$is_allowed_to_edit && !$toolsRow["visibility"])
				echo	"<a class=\"nobold\" href=\"" . api_get_path(WEB_PATH) .
						'claroline/external_module/external_module.php' .
						"?".api_get_cidreq()."&amp;id=".$toolsRow["id"]."\">". get_lang("Edit"). "</a>";

			echo "</td>\n";

			if($i%2)
			{
				echo "</tr>\n";
			}

			$i++;
		}
	}

	if($i%2)
	{
		echo	"<td width=\"50%\">&nbsp;</td>\n",
				"</tr>\n";
	}
}


/*
==============================================================================
		MAIN CODE
==============================================================================
*/

/*
-----------------------------------------------------------
	SWITCH TO A DIFFERENT HOMEPAGE VIEW
	the setting $homepage_view is located in claro_main.conf.php
-----------------------------------------------------------
*/
if (get_setting('homepage_view') != "default")
{
	include(get_setting('homepage_view').'.php');
	exit;
}

/*
-----------------------------------------------------------
	Introduction section
	(editable by course admins)
-----------------------------------------------------------
*/
$moduleId = TOOL_COURSE_HOMEPAGE;
include(api_get_include_path()."/introductionSection.inc.php");
/*
-----------------------------------------------------------
	Work with data post askable by admin of course (franglais, clean this)
-----------------------------------------------------------
*/
if ($is_allowed_to_edit)
{
	/*  Work request */

	/*
	-----------------------------------------------------------
		Modify home page
	-----------------------------------------------------------
	*/

	/*
	 * display message to confirm that a tool must be hidden from the list of available tools
	 * (visibility 0,1->2)
	 */

	if($_GET["remove"])
	{
		$msgDestroy=get_lang('DelLk').'<br />';
		$msgDestroy.='<a href="'.$_SERVER['PHP_SELF'].'">'.get_lang('No').'</a>&nbsp;|&nbsp;';
		$msgDestroy.='<a href="'.$_SERVER['PHP_SELF'].'?destroy=yes&amp;id='.$_GET["id"].'">'.get_lang('Yes').'</a>';

		Display :: display_normal_message($msgDestroy);
	}

	/*
	 * Process hiding a tools from aivailable tools.
	 * visibility=2 are only view  by clarolineAdministrator
	 * (visibility 0,1->2)
	 */

	elseif ($_GET["destroy"])
	{
		api_sql_query("UPDATE $tool_table SET visibility='2' WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
	}

  	/*
	-----------------------------------------------------------
		HIDE
	-----------------------------------------------------------
	*/
	elseif ($_GET["hide"]) // visibility 1 -> 0
	{
		api_sql_query("UPDATE $tool_table SET visibility=0 WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
		Display::display_normal_message(get_lang('ToolIsNowHidden'));
	}

    /*
	-----------------------------------------------------------
		REACTIVATE
	-----------------------------------------------------------
	*/
	elseif ($_GET["restore"]) // visibility 0,2 -> 1
	{
		api_sql_query("UPDATE $tool_table SET visibility=1  WHERE id='".$_GET["id"]."'",__FILE__,__LINE__);
		Display::display_normal_message(get_lang('ToolIsNowVisible'));
	}

	/*
	-----------------------------------------------------------
		editing "apparance" of tools on the course Home Page.

		--- This section has been removed ---

		This code section was built by the Claroline team to allow users to edit their homepage icons. It was never completed. This could be completeley removed in the future. Or completed.
	-----------------------------------------------------------
	*/
}

// work with data post askable by admin of course

if ($is_platformAdmin)
{
	// Show message to confirm that a tools must be hide from aivailable tools
	// visibility 0,1->2
	if($_GET["askDelete"])
	{
		?>
			<div id="toolhide">
			<?php echo get_lang("DelLk"); ?>
			<br />&nbsp;&nbsp;&nbsp;
			<a href="<?php echo $_SERVER['PHP_SELF']; ?>"><?php echo get_lang("No"); ?></a>&nbsp;|&nbsp;
			<a href="<?php echo $_SERVER['PHP_SELF']; ?>?delete=yes&id=<?php echo $_GET["id"]; ?>"><?php echo get_lang("Yes"); ?></a>
			</div>
		<?php
	}

	/*
	 * Process hiding a tools from aivailable tools.
	 * visibility=2 are only view  by clarolineAdministrator
	 * visibility 0,1->2
	 */

	elseif (isset($_GET["delete"]) && $_GET["delete"])
	{
		api_sql_query("DELETE FROM $tool_table WHERE id='$id' AND added_tool=1",__FILE__,__LINE__);
	}
}

/*
==============================================================================
		TOOLS VISIBLE FOR EVERYBODY
==============================================================================
*/

echo "<div class=\"everybodyview\">";
echo "<table width=\"100%\">";

showtools(TOOL_PUBLIC);

echo "</table>";
echo "</div>";


/*
==============================================================================
		COURSE ADMIN ONLY VIEW
==============================================================================
*/

// start of tools for CourseAdmins (teachers/tutors)
if ($is_allowed_to_edit)
{
	echo	"<div class=\"courseadminview\">";
	echo	"<span class=\"viewcaption\">";
	echo	get_lang("CourseAdminOnly");
	echo	"</span>";
	echo	"<table width=\"100%\">";

	showtools(TOOL_COURSE_ADMIN);

	/*
	-----------------------------------------------------------
		INACTIVE TOOLS - HIDDEN (GREY) LINKS
	-----------------------------------------------------------
	*/

	echo	"<tr><td colspan=\"4\"><hr style='color:\"#4171B5\"' noshade=\"noshade\" size=\"1\" /></td></tr>\n",

			"<tr>\n",
			"<td colspan=\"4\">\n",
			"<div style=\"margin-bottom: 10px;\"><font color=\"#808080\">\n",get_lang("InLnk"),"</font></div>",
			"</td>\n",
			"</tr>\n";

	showTools(TOOL_PUBLIC_BUT_HIDDEN);

	echo	"</table>";
	echo	"</div> ";

}

/*
-----------------------------------------------------------
	Tools for platform admin only
-----------------------------------------------------------
*/

if ($is_platformAdmin && $is_allowed_to_edit)
{
	?>
		<div class="platformadminview">
		<span class="viewcaption"><?php echo get_lang("PlatformAdminOnly"); ?></span>
		<table width="100%">
		<?php
			showtools(TOOL_PLATFORM_ADMIN);
		?>
		</table>
		</div>
	<?php
}


/*
==============================================================================
		FOOTER
==============================================================================
*/

Display::display_footer();
?>
