<?php
//including needed files
include("../../inc/claro_init_global.inc.php"); 
include_once (api_get_library_path()."/course.lib.php");
include_once (api_get_library_path()."/groupmanager.lib.php");
include_once (api_get_library_path()."/text.lib.php");
//error_reporting(E_ALL);

$tool_name = "Wiki"; // title of the page (should come from the language file) 

if ($_SESSION['_gid'] OR $_GET['group_id'])
{
	if (isset($_SESSION['_gid']))
	{
		$_clean['group_id']=(int)$_SESSION['_gid'];
	}
	if (isset($_GET['group_id']))
	{
		$_clean['group_id']=(int)$_GET['group_id'];
	}
	$current_group = GroupManager :: get_group_properties($_clean['group_id']);
	$interbredcrump[] = array ("url" => "../group/group_space.php?gidReq=".$_clean['group_id'], "name" => $current_group['name']);
	$groupfilter='group_id="'.$_clean['group_id'].'"';
}
else
{
	$groupfilter='group_id IS NULL';
}

Display::display_header($tool_name);
	
api_display_tool_title($tool_name);

$not_allowed_titles=array("Index", "RecentChanges","AllPages", "Categories");

/**
Some language variables
*/
if ($GLOBALS["HTTP_SESSION_VARS"]['_course']['language'] == 'greek') {
	include_once('greek.inc.php');
} else {
$StartPage="Start Page";
$EditThisPage="Edit this page";
$ShowPageHistory="Page History";
$RecentChanges='Recent Changes';
$AllPages='All Pages';
$AddNew='Add a new page';
$ChangesStored='Your changes have been stored.';
$ExplainRecentchanges='On this page you see all the latest changes. The first column displays the date of the change. Clicking this column brings you to that specific (older) version. The second column displays the title that has been changed. Clicking that column takes you to the latest (most recent) version of that title. The third column displays who has changed it. Clicking that link brings you to the profile of the user.';
$NewWikiSaved='The new wiki entry has been saved. You can view it by clicking: ';
$DefaultContent='This is the default text for the start page. You can write some text here by clicking the "edit this page" link';
$DefaultTitle='Start Page';
$Submit = 'Submit';
}

/**
Some CSS styles
*/
?>
<style type="text/css">
<!--
#wikititle {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 100%;
	font-weight: bold;
	background-color: #EFEFEF;
	border-bottom-width: 2px;
	border-bottom-style: solid;
	border-bottom-color: #333333;
	padding: 3px;
}
#menuwiki {
	background-color: #FFFFFF;
}

#menuwiki li{
	display: inline; 
}
-->
</style>
<?php
//the page we are dealing with
if (!isset($_GET['title']))
{
	$page='index';
}
else
{
	$page=$_GET['title'];
}


echo "<div id='wikiwrapper'>";

/**
This is the small menu on the left
*/
echo "<div id='menuwiki'>";
echo '<ul>';
echo '<li><a href="index.php?action=show&title=index">'.$StartPage.'</a> | </li>';
echo '<li><a href="index.php?action=edit&title='.$page.'">'.$EditThisPage.'</a> | </li>';
echo '<li><a href="index.php?action=history&title='.$page.'">'.$ShowPageHistory.'</a> | </li>';
echo '<li><a href="index.php?action=addnew">'.$AddNew.'</a> | </li>';
echo '<li><a href="index.php?action=recentchanges">'.$RecentChanges.'</a> | </li>';
echo '<li><a href="index.php?action=allpages">'.$AllPages.'</a></li>';
echo "</ul>";
echo "</div>";


echo "<div id='mainwiki'>";

// Database definition
$tbl_wiki = "`".$_course['dbNameGlu']."wiki`";

// Database creation if not created yet
if (mysql_query("SELECT * FROM $tbl_wiki") == FALSE)
{
		// create the table that contains the messages
		$sql="CREATE TABLE ".$tbl_wiki." (
			  `id` int(11) NOT NULL auto_increment,
			  `reflink` varchar(250) NOT NULL default 'index',
			  `title` text NOT NULL,
			  `content` text NOT NULL,
			  `user_id` int(11) NOT NULL default '0',
			  `group_id` int(11) default NULL,
			  `timestamp` timestamp(14) NOT NULL,
			  PRIMARY KEY  (`id`)
			) TYPE=MyISAM";
		$result=mysql_query($sql) or die(mysql_error());
}

// saving a change
if ($_POST['SaveWikiChange'] AND $_POST['reflink']<>'')
{
	$_clean['reflink']=mysql_real_escape_string($_POST['reflink']);
	$_clean['title']=mysql_real_escape_string($_POST['title']);
	$_clean['content']=mysql_real_escape_string($_POST['content']);
	$_clean['content']=$_POST['content'];
	$_clean['user_id']=(int)$_uid;
	$_clean['group_id']=(int)$_SESSION['_gid'];
	
	$sql="INSERT INTO ".$tbl_wiki." (reflink, title,content,user_id) VALUES ('".$_clean['reflink']."','".$_clean['title']."','".$_clean['content']."','".$_clean['user_id']."')";
	if ($_SESSION['_gid'])
	{
		$sql="INSERT INTO ".$tbl_wiki." (reflink, title,content,user_id, group_id) VALUES ('".$_clean['reflink']."','".$_clean['title']."','".$_clean['content']."','".$_clean['user_id']."','".$_clean['group_id']."')";
	}
	$result=api_sql_query($sql);
	Display::display_normal_message($ChangesStored);
}

// saving a new wiki entry
if ($_POST['SaveWikiNew'])
{
	
	// cleaning the variables
	$_clean['reflink']=mysql_real_escape_string(str_replace(' ','',$_POST['title']));
	$_clean['title']=mysql_real_escape_string($_POST['title']);
	$_clean['content']=mysql_real_escape_string($_POST['content']);
	$_clean['user_id']=(int)$_uid;
	$_clean['group_id']=(int)$_SESSION['_gid'];

	// checking if the current default reflink is not in use yet
	$var=$_clean['reflink'];
	$_clean['reflink']=createreflink($var);

	$sql="INSERT INTO ".$tbl_wiki." (reflink, title,content,user_id) VALUES ('".$_clean['reflink']."','".$_clean['title']."','".$_clean['content']."','".$_clean['user_id']."')";
	if ($_SESSION['_gid'])
	{
		$sql="INSERT INTO ".$tbl_wiki." (reflink, title,content,user_id, group_id) VALUES ('".$_clean['reflink']."','".$_clean['title']."','".$_clean['content']."','".$_clean['user_id']."','".$_clean['group_id']."')";
	}	

	$result=api_sql_query($sql,__LINE__,__FILE__);

	Display::display_normal_message($NewWikiSaved.'<a href="index.php?action=show&title='.$_clean['reflink'].'">'.$_POST['title'].'</a>');

}

// Add a new wiki entry
if ($_GET['action']=='addnew')
{
	echo '<form name="form1" method="post" action="'.$_SERVER['PHP_SELF'].'?action=show&title='.$page.'">';
	echo '<input type="text" name="title" value="'.$row['title'].'">';
	api_disp_html_area('content','','300px'); 
	echo '<input type="submit" name="SaveWikiNew" value="'.$Submit.'">';
	echo '</form>';
}

// Displaying the wiki text
if (!$_GET['action'] OR $_GET['action']=='show' AND !$_POST['SaveWikiNew'])
{
	//$_clean['group_id']=(int)$_SESSION['_gid'];
	if ($_GET['view'])
	{
		$_clean['view']=(int)$_GET['view'];
		$filter=" AND id='".$_clean['view']."'";
	}
	
	$sql="SELECT * FROM ".$tbl_wiki."WHERE reflink='".$page."' AND $groupfilter $filter ORDER BY id DESC";
	$result=api_sql_query($sql,__LINE__,__FILE__);
	$row=mysql_fetch_array($result); // we do not need a while loop since we are always displaying the last version
	
	// if both are empty and we are displaying the index page then we display the default text
	if ($row['content']=='' AND $row['title']=='' AND $page='index')
	{
		$content=$DefaultContent;
		$title=$DefaultTitle;
	}
	else
	{
		$content=$row['content'];
		$title=$row['title'];	
	}
	
	echo '<div id="wikititle">'.$title.'</div>';
	echo $content;
}

// Editing the wiki text
if ($_GET['action']=='edit')
{
	$_clean['group_id']=(int)$_SESSION['_gid'];

	$sql='SELECT * FROM '.$tbl_wiki.'WHERE reflink="'.$page.'" AND '.$groupfilter.' ORDER BY id DESC';
	$result=api_sql_query($sql,__LINE__,__FILE__);
	$row=mysql_fetch_array($result); // we do not need a while loop since we are always displaying the last version
	
	if ($row['content']=='' AND $row['title']=='' AND $page='index')
	{
		$content=$DefaultContent;
		$title=$DefaultTitle;
	}
	else
	{
		$content=$row['content'];
		$title=$row['title'];	
	}
	
	echo '<form name="form1" method="post" action="'.$_SERVER['PHP_SELF'].'?action=show&title='.$page.'">';
	echo 'Title: <input type="hidden" name="reflink" value="'.$page.'">';
	echo '<input type="text" name="title" value="'.$title.'" size="50"><br><br>';
	api_disp_html_area('content',$content,'300px', '200px'); 
	echo '<input type="submit" name="SaveWikiChange" value="'.$Submit.'">';
	echo '</form>';
}

// Page history
if ($_GET['action']=='history')
{
	$_clean['group_id']=(int)$_SESSION['_gid'];
	
	$sql='SELECT * FROM '.$tbl_wiki.'WHERE reflink="'.$page.'" AND '.$groupfilter.' ORDER BY id DESC';
	$result=api_sql_query($sql,__LINE__,__FILE__);
	echo '<ul>';
	while ($row=mysql_fetch_array($result))
	{
		$userinfo=Database::get_user_info_from_id($row['user_id']);
		echo '<li><a href="'.$_SERVER['PHP_SELF'].'?action=show&title='.$page.'&view='.$row['id'].'">';
		echo ucfirst(format_locale_date($dateFormatLong,strtotime($row['timestamp'])));
		echo '</a> - <a href="../../user/userInfo.php?uInfo='.$userinfo['user_id'].'">'.$userinfo['lastname'].' '.$userinfo['firstname'].'</a></li>';
		//print_r($userinfo);
	}
	echo '</ul>';	
}

// Recent Changes
if ($_GET['action']=='recentchanges')
{
	$_clean['group_id']=(int)$_SESSION['_gid'];
	
	$sql='SELECT * FROM '.$tbl_wiki.' WHERE '.$groupfilter.' ORDER BY timestamp DESC LIMIT 0,10';
	$result=api_sql_query($sql,__LINE__,__FILE__);
	echo $ExplainRecentchanges;
	echo '<ul>';
	while ($row=mysql_fetch_array($result))
	{
		$userinfo=Database::get_user_info_from_id($row['user_id']);
		echo '<li><a href="'.$_SERVER['PHP_SELF'].'?action=show&title='.$row['reflink'].'&view='.$row['id'].'">';
		echo ucfirst(format_locale_date($dateFormatLong,strtotime($row['timestamp'])));
		echo '</a> - <a href="'.$_SERVER['PHP_SELF'].'?action=show&title='.$row['reflink'].'">'.$row['title'].'</a> - <a href="../../user/userInfo.php?uInfo='.$userinfo['user_id'].'">'.$userinfo['lastname'].' '.$userinfo['firstname'].'</a></li>';
		//print_r($userinfo);
	}
	echo '</ul>';	
}


// All Pages
if ($_GET['action']=='allpages')
{
	$_clean['group_id']=(int)$_SESSION['_gid'];
	
	$sql='SELECT * FROM '.$tbl_wiki.' WHERE '.$groupfilter.' GROUP BY reflink ORDER BY reflink ASC';
	$result=api_sql_query($sql,__LINE__,__FILE__);
	echo '<ul>';
	while ($row=mysql_fetch_array($result))
	{
		$userinfo=Database::get_user_info_from_id($row['user_id']);
		echo '<li>';
		echo ucfirst(format_locale_date($dateFormatLong,strtotime($row['timestamp'])));
		echo ' - <a href="'.$_SERVER['PHP_SELF'].'?action=show&title='.$row['reflink'].'">'.$row['title'].'</a></li>';
		//print_r($userinfo);
	}
	echo '</ul>';	
}

echo "</div>"; // echo "<div id='mainwiki'>";

echo "</div>"; // echo "<div id='wikiwrapper'>";
 
 
 
/*
==============================================================================
		FOOTER 
==============================================================================
*/ 
//$_SESSION['_gid'];
Display::display_footer();

/**
* @auth Patrick Cool <patrick.cool@ugent.be>, Ghent University
* @desc This function checks weither the proposed reflink is not in use yet. It is a recursive function because every newly created reflink suggestion
		has to be checked also
*/
function createreflink($testvalue)
{
	global $groupfilter;
	
	$counter='';
	
	while (!checkreflink($testvalue.$counter))
	{
		$counter++;
		echo $counter."-".$testvalue.$counter."<br>";
	}
			// the reflink has not been found yet, so it is OK
	return $testvalue.$counter;
}
function checkreflink($param)
{
	global $tbl_wiki;
	global $groupfilter; 
	
	$sql='SELECT * FROM '.$tbl_wiki.' WHERE reflink="'.$param.'" AND '.$groupfilter.'';
	$result=api_sql_query($sql,__FILE__,__LINE__);
	$numberofresults=mysql_num_rows($result);
	
	if ($numberofresults==0) // the f
	{
		return true;
	}
	else // the value has been found 
	{
		return false; 
	}
}
?>
