<?php
/**
* This plugin can be used in two places: 
* - In the right menu when not logged in (=> searching in all courses)
* - In the ricght menu when logged in (=> choice to search in all courses or only the courses of the user)
* This is a really very basic search and could be improved quite a lot. 
* what this tool cannot do is search inside documents because it only searches inside the databases. It does look inside the path, filenames 
* and comments of the documents, but not inside the documents itself

* @todo search with booleans (at least and)
* @todo if the course is open the title of the course should be clickable
* @todo foresee that the search results can go in the main content area (= where the platform introduction text is located [not logged in], or the my courses area [logged in])
* 		this is needs some hacking of the normal dokeos and this file has to be split up into two separate files: one for the form and one for the results (=output). 
* @todo search inside tests, studentpublications
* @todo foresee a config setting that determines who is allowed to search: platform admin, teachers, students
* @todo performance testing on a campus with a lot of courses. 
* @todo investigate if the found search term can be highlighted (best way would be using a javascript for this so that we can do the highlighting after the 
* 		page has loaded so that we do not have to change a lot. 
* @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
*/

// Language variables
if ($_SESSION['user_language_choice']=='english') {
	include_once('english.lang.php');
} else {
	include_once('greek.lang.php');
}

?>

<div class="note" style="background: none">	
  <form name="form1" method="post" action="">
    <input type="text" name="SearchTerm" value="<?php echo htmlspecialchars(trim($_POST['SearchTerm']))?>"><br />
<?php if ($_uid) // we are logged in => you have the choice to search in 'my courses' or in all courses.
{
?>
	<input name="search_scope" type="radio" value="my_courses" checked><?=$MyCourses?><br />
    <input name="search_scope" type="radio" value="all_courses"><?=$AllCourses?><br />
<?php 
}
?>
    <input type="submit" name="SubmitSearch" value="<?=$Search?>">
  </form>
<?php 
if ($_POST['SubmitSearch']) {
	if (strlen(trim($_POST['SearchTerm']))) {
		$results=do_search($_POST['SearchTerm']);
		if (!is_array($results) || !count($results)) {
			echo $NoLessonsFound;
		} else {
			echo $SearchResultsFor.' '.$_POST['SearchTerm']."<br><br>";
			display_results($results);
		}
	}
}
?>
</div>


<?php 
function do_search($search_term)
{
global $_course; 
$tbl_courses=Database::get_main_table(MAIN_COURSE_TABLE); 
$tbl_course_user_table = Database :: get_main_table(MAIN_COURSE_USER_TABLE);
global $_uid; 

// we create an array containing all the courses of the user
// this will be needed later on when we search for content 
// matching the search criterium later on and also
// for the construction of the url to go to the found result
if ($_POST['search_scope']=='my_courses')
{
	$courses=get_courses_of_user($_uid);
}
if ($_POST['search_scope']=='all_courses'  OR !$_POST['search_scope'])
{
	$courses=get_all_courses();
}

// searching for COURSES based on title, course code or teacher
$search_term_safe=$search_term;
$sql_find="SELECT * FROM $tbl_courses WHERE code LIKE '%".$search_term_safe."%' OR title LIKE '%".$search_term_safe."%' OR tutor_name LIKE '%".$search_term_safe."%'";
//echo $sql_find;
$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
while ($row=mysql_fetch_array($result_find))
	{
	//echo "<li>course: <a href\"#\">".$row['title']."</a>";
	$result[$row['code']]['course'][]=array($row['code'], $row['title']);
	}
return $result; 
}

/**
 * @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
 * @param string the search term = what we are looking for
*/
function do_search_old($search_term)
{
global $_course; 
$tbl_courses=Database::get_main_table(MAIN_COURSE_TABLE); 
$tbl_course_user_table = Database :: get_main_table(MAIN_COURSE_USER_TABLE);
global $_uid; 

// we create an array containing all the courses of the user
// this will be needed later on when we search for content 
// matching the search criterium later on and also
// for the construction of the url to go to the found result
if ($_POST['search_scope']=='my_courses')
{
	$courses=get_courses_of_user($_uid);
}
if ($_POST['search_scope']=='all_courses'  OR !$_POST['search_scope'])
{
	$courses=get_all_courses();
}

// searching for COURSES based on title, course code or teacher
$search_term_safe=$search_term;
$sql_find="SELECT * FROM $tbl_courses WHERE code LIKE '%".$search_term_safe."%' OR title LIKE '%".$search_term_safe."%' OR tutor_name LIKE '%".$search_term_safe."%'";
//echo $sql_find;
$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
while ($row=mysql_fetch_array($result_find))
	{
	//echo "<li>course: <a href\"#\">".$row['title']."</a>";
	$result[$row['code']]['course'][]=array($row['code'], $row['title']);
	}
echo "</ul>";

// searching for content inside each course
// the result array will look like this
// $result[course][TOOL_ANNOUNCEMENT][]=array(course_id,tool_item_id)
// we store everything in a $result array. This array is a multidimensional associative array
// where the first index is the course_code and inside it we have the tool constants as index.
foreach ($courses as $key=>$course)
{
	//print_r($course);
	// searching the ANNOUNCEMENTS
	$tbl_announcements=Database::get_course_table(TOOL_ANNOUNCEMENT,$course['db']); 
	$sql_find="SELECT * FROM ".$tbl_announcements." WHERE content LIKE '%".$search_term_safe."%'";
	$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']][TOOL_ANNOUNCEMENT][]=array($course['code'], $row['id'],$row['title']);
		}
	// searching the CALENDAR / Agenda
	$tbl_calendar=Database::get_course_table(TOOL_CALENDAR_EVENT,$course['db']); 
	$sql_find="SELECT * FROM ".$tbl_calendar." WHERE title LIKE '%".$search_term_safe."%' OR content LIKE '%".$search_term_safe."%'";
	$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']][TOOL_CALENDAR_EVENT][]=array($course['code'], $row['id'],$row['title']);
		}
	
	// searching the FORUM
/*	$tbl_posts            = $course['db'].'`.`bb_posts';
	$tbl_posts_text       = $course['db'].'`.`bb_posts_text';
	$sql_find="SELECT * FROM `$tbl_posts` posts, `$tbl_posts_text` poststext WHERE poststext.post_title LIKE '%".$search_term_safe."%' OR poststext.post_text LIKE '%".$search_term_safe."%' AND poststext.post_id=posts.post_id";
	$result_find=api_sql_query($sql_find) or die(mysql_error($sql_find));
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']][TOOL_BB_FORUM][]=array($course['code'], $row['topic_id'], $row['forum_id'], $row['post_title']);
		}
*/
	// searching the COURSE DESCRIPTION
	//$tbl_coursedescription = $course['db'].'`.`course_description';
	$tbl_coursedescription = Database::get_course_table(TOOL_COURSE_DESCRIPTION, $course['db']);
	$sql_find="SELECT * FROM ".$tbl_coursedescription." WHERE title LIKE '%".$search_term_safe."%' OR content LIKE '%".$search_term_safe."%'";
	//echo $sql_find;
	$result_find=api_sql_query($sql_find) or die(mysql_error());
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']]["course_description"][]=array($course['code'], $row['id']);
		}
	// searching the DOCUMENTS (comments, filename and folder)
	$tbl_document=Database::get_course_table(TOOL_DOCUMENT,$course['db']); 
	$sql_find="SELECT * FROM ".$tbl_document." WHERE path LIKE '%".$search_term_safe."%' OR comment LIKE '%".$search_term_safe."%' OR title LIKE '%".$search_term_safe."%'";
	$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']][TOOL_DOCUMENT][]=array($course['code'], $row['id'], $row['path'], $row['title']);
		}
	// searching the LINKS (url, title, comment)
	$tbl_link=Database::get_course_table(TOOL_LINK,$course['db']); 
	$sql_find="SELECT * FROM ".$tbl_link." WHERE url LIKE '%".$search_term_safe."%' OR title LIKE '%".$search_term_safe."%' OR description LIKE '%".$search_term_safe."%'";
	$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']][TOOL_LINK][]=array($course['code'], $row['id'], $row['url'], $row['title']);
		}
	// searching the LINK CATEGORIES (category title, category description)
	/*$tbl_link_category="`".$course['db']."`.`link_category`"; 
	$sql_find="SELECT * FROM ".$tbl_link_category." WHERE category_title LIKE '%".$search_term_safe."%' OR description LIKE '%".$search_term_safe."%'";
	//echo $sql_find; 
	$result_find=mysql_query($sql_find) or die(mysql_error());
	while ($row=mysql_fetch_array($result_find))
		{
		//creating the expandcode
		$sql=mysql_query("SELECT * FROM $tbl_link_category ORDER BY  display_order DESC");
		while ($myrow=mysql_fetch_array($sql))
		{
			if ($myrow['id']<>$row['id'])
				{$expandcode.="0";}
			else
				{$expandcode.="1";}
		}
		
		$result[$course['code']][link_category][]=array($course['code'], $row['id'], $row['category_title'], $expandcode);
		}
	*/
	
	// searching the introduction texts
	/*$tbl_introtext="`".$course['db']."`.`tool_intro`"; 
	$sql_find="SELECT * FROM ".$tbl_introtext." WHERE intro_text LIKE '%".$search_term_safe."%'";
	$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']]['introductiontext'][]=array($course['code'], $row['id']);
		}
	*/
	
			
	// SEARCHING THE TESTS
	
	//SEARCHING THE GROUPS
	//$tbl_group=get_course_table(GROUP_TABLE); 
	/*$tbl_group="`".$course['db']."`.`group_info`"; 
	$sql_find="SELECT * FROM $tbl_group WHERE name LIKE '%".$search_term_safe."%' OR description LIKE '%".$search_term_safe."%'";
	$result_find=mysql_query($sql_find) or die(mysql_error());
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']][TOOL_GROUP][]=array($course['code'], $row['name'], $row['id']);
		}
	*/
	// SEARCHING THE USERS
	$tbl_course_user = Database :: get_main_table(MAIN_COURSE_USER_TABLE);
	$tbl_user = Database :: get_main_table(MAIN_USER_TABLE);
	$sql_find="SELECT * FROM $tbl_course_user course_user, $tbl_user user WHERE course_user.course_code='".$course['code']."' AND course_user.user_id=user.user_id AND (firstname LIKE '%".$search_term_safe."%' OR lastname LIKE '%".$search_term_safe."%')";
	$result_find=mysql_query($sql_find) or die(mysql_error($sql_find));
	while ($row=mysql_fetch_array($result_find))
		{
		$result[$course['code']]['user'][]=array($course['code'], $row['user_id'], $row['firstname'], $row['lastname']);
		}
	
	// SEARCHING THE STUDENT PUBLICATIONS
	
}
//echo "<pre>";
//print_r($result);
//echo "</pre>";

return $result; 
}

function display_results($result)
{
	// the first array dimension is the course
	foreach ($result as $coursecode=>$courseresult)
	{
		echo $coursecode;
		echo "<ul>\n";
		// the second array dimension are the search results within the course with as first key the tool 
		// (following the constants that were defined in main_api.lib.php
		foreach ($courseresult as $key=>$value)
		{
			switch($key)
			{
				case "course":
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_COURSE_PATH).$subvalue[0]."/\">".limitoutput($subvalue[1])."</a></li>\n";
					}
					break;
				case TOOL_ANNOUNCEMENT:
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."announcements/announcements.php?cidReq=".$subvalue[0]."\"><img src=\"claroline/img/valves.gif\">".limitoutput($subvalue[1])."</a></li>\n";
					}
					break;
				case TOOL_CALENDAR_EVENT:
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."calendar/agenda.php?cidReq=".$subvalue[0]."\"><img src=\"claroline/img/agenda.gif\">".limitoutput($subvalue[2])."</a></li>\n";
					}
					break;
				case TOOL_BB_FORUM:
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."phpbb/viewtopic.php?cidReq=".$subvalue[0]."&topic=".$subvalue[1]."&forum=".$subvalue[2]."\"><img src=\"claroline/img/forum.gif\">".limitoutput($subvalue[3])."</a></li>\n";
					}
					break;
				case TOOL_DOCUMENT:
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."document/document.php?cidReq=".$subvalue[0]."\"><img src=\"claroline/img/documents.gif\">".limitoutput($subvalue[3])."</a></li>\n";
					}
					break;
				case "course_description":
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."course_description/?cidReq=".$subvalue[0]."\"><img src=\"claroline/img/info.gif\">".limitoutput($subvalue[1])."</a></li>\n";
					}
					break;
				case TOOL_LINK:
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."link/link_goto.php?link_id=".$subvalue[1]."&link_url=".htmlspecialchars($subvalue[2])."\"><img src=\"claroline/img/liens.gif\">".limitoutput($subvalue[3])."</a></li>\n";
					}
					break;
				case "link_category":
					foreach ($value as $subkey=>$subvalue)
					{
						echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."link/link.php?cidReq=".$subvalue[0]."&urlview=".$subvalue[3]."\"><img src=\"claroline/img/liens.gif\">".limitoutput($subvalue[2])."</a></li>\n";
					}
					break;
				case "introductiontext":
					foreach ($value as $subkey=>$subvalue)
					{
						// the url depends on the $subvalue[1]
						switch ($subvalue[1])
						{
							// this should be extended wherever there can be tool introductions
							case "course_homepage";
								$url=api_get_path(WEB_COURSE_PATH).$subvalue[0];
								break; 
							case TOOL_ANNOUNCEMENT;
								$url=api_get_path(WEB_CODE_PATH)."announcements/announcements.php?cidReq=".$subvalue[0];
								break; 
							case TOOL_CALENDAR_EVENT;
								$url=api_get_path(WEB_CODE_PATH)."calendar/agenda.php?cidReq=".$subvalue[0];
								break; 
							case TOOL_BB_FORUM;
								$url=api_get_path(WEB_CODE_PATH)."phpbb/index.php?cidReq=".$subvalue[0];
								break; 
							case TOOL_DOCUMENT;
								$url=api_get_path(WEB_CODE_PATH)."document/document.php?cidReq=".$subvalue[0];
								break; 
							case TOOL_LINK;
								$url=api_get_path(WEB_CODE_PATH)."link/link.php?cidReq=".$subvalue[0];
								break; 
						}
						echo "<li><a href=\"".$url."\"><img src=\"claroline/img/txt.gif\">".limitoutput("introduction text")."</a></li>\n";
					}
					break;
			case TOOL_USER:
				foreach ($value as $subkey=>$subvalue)
				{
					echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."user/userInfo.php?cidReq=".$subvalue[0]."&uInfo=".$subvalue[1]."\"><img src=\"claroline/img/membres.gif\">".$subvalue[2].' '.$subvalue[3]."</a></li>";
					//echo "<li><a href=\"http://localhost/dokeos_cvs/claroline/phpbb/viewtopic.php?cidReq=".$subvalue[0]."&topic=".$subvalue[1]."&forum=".$subvalue[2]."\"><img src=\"claroline/img/forum.gif\">".limitoutput($subvalue[3])."</a></li>\n";
				}
				break;
			case TOOL_GROUP:
				foreach ($value as $subkey=>$subvalue)
				{
					echo "<li><a href=\"".api_get_path(WEB_CODE_PATH)."group/group_space.php?gidReq=".$subvalue[2]."&cidReq=".$subvalue[0]."\"><img src=\"claroline/img/group.gif\">".$subvalue[1]."</a></li>";
					//echo "<li><a href=\"http://localhost/dokeos_cvs/claroline/phpbb/viewtopic.php?cidReq=".$subvalue[0]."&topic=".$subvalue[1]."&forum=".$subvalue[2]."\"><img src=\"claroline/img/forum.gif\">".limitoutput($subvalue[3])."</a></li>\n";
					
				}
				break;
				
			}  // switch
		} //search results within the course 
		echo "</ul>";
	} //
	echo "<hr>";
//	echo "<pre>";
//	print_r($result);
//	echo "</pre>";
}




/** 
 * retrieves all the courses that the user has already subscribed to
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @param int $user_id: the id of the user
 * @return array an array containing all the information of the courses of the given user
*/
function get_courses_of_user($user_id)
{
$TABLECOURS=Database::get_main_table(MAIN_COURSE_TABLE); 
$TABLECOURSUSER=Database::get_main_table(MAIN_COURSE_USER_TABLE);

$sql_select_courses="SELECT course.code k, course.visual_code  vc, course.subscribe subscr, course.unsubscribe unsubscr, 
							course.title i, course.tutor_name t, course.db_name db, course.directory dir, course_rel_user.status status,
							course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
	                        FROM    $TABLECOURS       course,
									$TABLECOURSUSER  course_rel_user
	                        WHERE course.code = course_rel_user.course_code
	                        AND   course_rel_user.user_id = '".$user_id."' ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
$result = api_sql_query($sql_select_courses) or die(mysql_error());
while ($row=mysql_fetch_array($result))
	{
	// we only need the database name of the course
	$courses[]=array("db"=> $row['db'], "code" => $row['k'], "visual_code" => $row['vc'], "title" => $row['i'], "directory" => $row['dir'], "status" => $row['status'], "tutor" => $row['t'], "subscribe" => $row['subscr'], "unsubscribe" => $row['unsubscr'], "sort" => $row['sort'], "user_course_category" => $row['user_course_cat']); 
	}
return $courses; 
}

/** 
 * retrieves all the courses on the platform
 * @author Patrick Cool <patrick.cool@UGent.be>, Ghent University
 * @return array an array containing all the information of the courses of the given user
*/
function get_all_courses()
{
$TABLECOURS=Database::get_main_table(MAIN_COURSE_TABLE); 
$TABLECOURSUSER=Database::get_main_table(MAIN_COURSE_USER_TABLE);

$sql_select_courses="SELECT course.code k, course.visual_code  vc, course.subscribe subscr, course.unsubscribe unsubscr, 
							course.title i, course.tutor_name t, course.db_name db, course.directory dir, course_rel_user.status status,
							course_rel_user.sort sort, course_rel_user.user_course_cat user_course_cat
	                        FROM    $TABLECOURS       course,
									$TABLECOURSUSER  course_rel_user
	                        WHERE course.code = course_rel_user.course_code
	                        ORDER BY course_rel_user.user_course_cat, course_rel_user.sort ASC";
$result = api_sql_query($sql_select_courses) or die(mysql_error());
while ($row=mysql_fetch_array($result))
	{
	// we only need the database name of the course
	$courses[]=array("db"=> $row['db'], "code" => $row['k'], "visual_code" => $row['vc'], "title" => $row['i'], "directory" => $row['dir'], "status" => $row['status'], "tutor" => $row['t'], "subscribe" => $row['subscr'], "unsubscribe" => $row['unsubscr'], "sort" => $row['sort'], "user_course_category" => $row['user_course_cat']); 
	}
return $courses; 
}

function utf8_substr($str,$from,$len){
  return preg_replace('#^(?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$from.'}'.
                       '((?:[\x00-\x7F]|[\xC0-\xFF][\x80-\xBF]+){0,'.$len.'}).*#s',
                       '$1',$str);
}
/**
* This function shortens the input to x characters. 
* @author Patrick Cool <patrick.cool@ugent.be>, Ghent University
*/
function limitoutput($input, $length=17)
{
	if (strlen($input) <= $length)
	{
		return $input;
	}
	else
	{
		return utf8_substr($input, 0, $length)."...";
	}
}
?>
