Browse Source

[svn r16915] New version of the new gradebook tool (integrated into courses) - integration from usil project by Isaac Flores. Needs revision (see FS#3173)

Yannick Warnier 16 years ago
parent
commit
a1d57c6066
57 changed files with 5282 additions and 3214 deletions
  1. 36 22
      main/gradebook/exercise_jump.php
  2. 170 219
      main/gradebook/gradebook.php
  3. 32 21
      main/gradebook/gradebook_add_cat.php
  4. 17 20
      main/gradebook/gradebook_add_eval.php
  5. 57 44
      main/gradebook/gradebook_add_link.php
  6. 14 13
      main/gradebook/gradebook_add_link_select_course.php
  7. 16 18
      main/gradebook/gradebook_add_result.php
  8. 33 45
      main/gradebook/gradebook_add_user.php
  9. 165 0
      main/gradebook/gradebook_edit_all.php
  10. 19 24
      main/gradebook/gradebook_edit_cat.php
  11. 17 21
      main/gradebook/gradebook_edit_eval.php
  12. 16 13
      main/gradebook/gradebook_edit_link.php
  13. 19 18
      main/gradebook/gradebook_edit_result.php
  14. 95 67
      main/gradebook/gradebook_flatview.php
  15. 291 0
      main/gradebook/gradebook_result.class.php
  16. 44 45
      main/gradebook/gradebook_scoring_system.php
  17. 71 0
      main/gradebook/gradebook_showlog_eval.php
  18. 73 0
      main/gradebook/gradebook_showlog_link.php
  19. 34 47
      main/gradebook/gradebook_statistics.php
  20. 324 341
      main/gradebook/gradebook_view_result.php
  21. 658 0
      main/gradebook/index.php
  22. 28 9
      main/gradebook/lib/be.inc.php
  23. 143 157
      main/gradebook/lib/be/abstractlink.class.php
  24. 299 275
      main/gradebook/lib/be/category.class.php
  25. 34 24
      main/gradebook/lib/be/dropboxlink.class.php
  26. 73 81
      main/gradebook/lib/be/evallink.class.php
  27. 180 183
      main/gradebook/lib/be/evaluation.class.php
  28. 75 81
      main/gradebook/lib/be/exerciselink.class.php
  29. 255 0
      main/gradebook/lib/be/forumthreadlink.class.php
  30. 23 4
      main/gradebook/lib/be/gradebookitem.class.php
  31. 25 6
      main/gradebook/lib/be/learnpathlink.class.php
  32. 58 36
      main/gradebook/lib/be/linkfactory.class.php
  33. 93 59
      main/gradebook/lib/be/result.class.php
  34. 202 26
      main/gradebook/lib/be/studentpublicationlink.class.php
  35. 50 50
      main/gradebook/lib/fe/catform.class.php
  36. 28 6
      main/gradebook/lib/fe/dataform.class.php
  37. 239 127
      main/gradebook/lib/fe/displaygradebook.php
  38. 76 96
      main/gradebook/lib/fe/evalform.class.php
  39. 31 17
      main/gradebook/lib/fe/exportgradebook.php
  40. 51 43
      main/gradebook/lib/fe/flatviewtable.class.php
  41. 60 87
      main/gradebook/lib/fe/gradebooktable.class.php
  42. 60 52
      main/gradebook/lib/fe/linkaddeditform.class.php
  43. 51 39
      main/gradebook/lib/fe/linkform.class.php
  44. 54 43
      main/gradebook/lib/fe/resulttable.class.php
  45. 36 20
      main/gradebook/lib/fe/scoredisplayform.class.php
  46. 38 26
      main/gradebook/lib/fe/userform.class.php
  47. 40 35
      main/gradebook/lib/fe/usertable.class.php
  48. 82 66
      main/gradebook/lib/flatview_data_generator.class.php
  49. 109 104
      main/gradebook/lib/gradebook_data_generator.class.php
  50. 181 33
      main/gradebook/lib/gradebook_functions.inc.php
  51. 51 53
      main/gradebook/lib/gradebook_functions_users.inc.php
  52. 70 60
      main/gradebook/lib/results_data_generator.class.php
  53. 116 146
      main/gradebook/lib/scoredisplay.class.php
  54. 95 126
      main/gradebook/lib/user_data_generator.class.php
  55. 22 5
      main/gradebook/open_document.php
  56. 18 22
      main/gradebook/user_info.php
  57. 35 39
      main/gradebook/user_stats.php

+ 36 - 22
main/gradebook/exercise_jump.php

@@ -1,29 +1,45 @@
-<?php
-
+<?php //$id $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Sets needed course variables and then jumps to the exercises result page.
  * This intermediate page is needed because the user is not inside a course
  * when visiting the gradebook, and several course scripts rely on these
  * variables.
  * Most code here is ripped from /main/course_home/course_home.php
- * @author Bert Stepp�
+ * @author Bert Steppé
  */
 
-
-$cidReq = mysql_real_escape_string($_GET['cid']);
-
-include ('../inc/global.inc.php');
-
+require_once ('../inc/global.inc.php');
 api_block_anonymous_users();
-
 $this_section=SECTION_COURSES;
 
-include_once (api_get_path(LIBRARY_PATH).'course.lib.php');
+require_once (api_get_path(LIBRARY_PATH).'course.lib.php');
 
-$course_code = $_course['sysCode'];
+$course_code = api_get_course_id();
 $course_info = Database::get_course_info($course_code);
-$return_result = CourseManager::determine_course_title_from_course_info($_user['user_id'], $course_info);
-$course_title = $return_result['title'];
+$course_title = $course_info['title'];
 $course_code = $return_result['code'];
 
 $dbname = $course_info['db_name'];
@@ -31,15 +47,13 @@ $dbname = $course_info['db_name'];
 $_course['name'] = $course_title;
 $_course['official_code'] = $course_code;
 
-if (isset($_GET['doexercise']))
-{
+if (isset($_GET['doexercise'])) {
 	header('Location: ../exercice/exercice_submit.php?cidReq='.$cidReq.'&origin=&learnpath_id=&learnpath_item_id=&exerciseId='.Security::remove_XSS($_GET['doexercise']));
 	exit;
-}
-else
-{
-	header('Location: ../exercice/exercice.php?show=result');
+} else {
+	if (isset($_GET['gradebook'])) {
+		$add_url = '&gradebook=view&exerciseId='.(int)$_GET['exerciseId'];
+	}
+	header('Location: ../exercice/exercice.php?cidReq='.Security::remove_XSS($cidReq).'&show=result'.Security::remove_XSS($add_url));
 	exit;
-}
-
-?>
+}

+ 170 - 219
main/gradebook/gradebook.php

@@ -1,8 +1,9 @@
-<?php // $Id: gradebook.php 15047 2008-04-23 22:41:04Z juliomontoya $
+<?php // $Id: gradebook.php 16915 2008-11-25 20:15:42Z yannoo $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
 	Copyright (c) 2006-2008 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
@@ -22,20 +23,25 @@
 ==============================================================================
 */
 $language_file= 'gradebook';
+// $cidReset : This is the main difference with gradebook.php, here we say,
+// basically, that we are inside a course, and many things depend from that
 $cidReset= true;
-include_once ('../inc/global.inc.php');
+$_in_course = false;
+//make sure the destination for scripts is index.php instead of gradebook.php
+require_once ('../inc/global.inc.php');
+$_SESSION['gradebook_dest'] = 'gradebook.php';
 $this_section = SECTION_MYGRADEBOOK;
-include_once ('lib/be.inc.php');
-include_once ('lib/scoredisplay.class.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/catform.class.php');
-include_once ('lib/fe/evalform.class.php');
-include_once ('lib/fe/linkform.class.php');
-include_once ('lib/gradebook_data_generator.class.php');
-include_once ('lib/fe/gradebooktable.class.php');
-include_once ('lib/fe/displaygradebook.php');
-include_once ('lib/fe/userform.class.php');
-include_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/scoredisplay.class.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/catform.class.php');
+require_once ('lib/fe/evalform.class.php');
+require_once ('lib/fe/linkform.class.php');
+require_once ('lib/gradebook_data_generator.class.php');
+require_once ('lib/fe/gradebooktable.class.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/fe/userform.class.php');
+require_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
 api_block_anonymous_users();
 
 $htmlHeadXtra[]= '<script type="text/javascript">
@@ -47,7 +53,6 @@ function confirmation ()
 		{return false;}
 }
 </script>';
-
 $filter_confirm_msg = true;
 $filter_warning_msg = true;
 // --------------------------------------------------------------------------------
@@ -55,14 +60,11 @@ $filter_warning_msg = true;
 // --------------------------------------------------------------------------------
 
 //this is called when there is no data for the course admin
-if (isset ($_GET['createallcategories']))
-{
+if (isset ($_GET['createallcategories'])) {
 	block_students();
 	$coursecat= Category :: get_not_created_course_categories(api_get_user_id());
-	if (!count($coursecat) == 0)
-	{
-		foreach ($coursecat as $row)
-		{
+	if (!count($coursecat) == 0) {
+		foreach ($coursecat as $row) {
 			$cat= new Category();
 			$cat->set_name($row[1]);
 			$cat->set_course_code($row[0]);
@@ -75,39 +77,31 @@ if (isset ($_GET['createallcategories']))
 			unset ($cat);
 		}
 	}
-	header('Location: gradebook.php?addallcat=&selectcat=0');
+	header('Location: '.$_SESSION['gradebook_dest'].'?addallcat=&selectcat=0');
 	exit;
 }
-
 //move a category
-if (isset ($_GET['movecat']))
-{
+if (isset ($_GET['movecat'])) {
 	block_students();
 	$cats= Category :: load($_GET['movecat']);
-	if (!isset ($_GET['targetcat']))
-	{
+	if (!isset ($_GET['targetcat'])) {
 		$move_form= new CatForm(CatForm :: TYPE_MOVE,
 								$cats[0],
 								'move_cat_form',
 								null,
 								api_get_self() . '?movecat=' . Security::remove_XSS($_GET['movecat'])
 													 . '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
-		if ($move_form->validate())
-		{
+		if ($move_form->validate()) {
 			header('Location: ' . api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
 													   . '&movecat=' . Security::remove_XSS($_GET['movecat'])
 													   . '&targetcat=' . $move_form->exportValue('move_cat'));
 			exit;
 		}
-	}
-
-	else
-	{
+	} else {
 		$targetcat= Category :: load($_GET['targetcat']);
 		$course_to_crsind = ($cats[0]->get_course_code() != null && $targetcat[0]->get_course_code() == null);
 
-		if (!($course_to_crsind && !isset($_GET['confirm'])))
-		{
+		if (!($course_to_crsind && !isset($_GET['confirm']))) {
 			$cats[0]->move_to_cat($targetcat[0]);
 			header('Location: ' . api_get_self() . '?categorymoved=&selectcat=' . Security::remove_XSS($_GET['selectcat']));
 			exit;
@@ -118,12 +112,10 @@ if (isset ($_GET['movecat']))
 }
 
 //move an evaluation
-if (isset ($_GET['moveeval']))
-{
+if (isset ($_GET['moveeval'])) {
 	block_students();
 	$evals= Evaluation :: load($_GET['moveeval']);
-	if (!isset ($_GET['targetcat']))
-	{
+	if (!isset ($_GET['targetcat'])) {
 
 		$move_form= new EvalForm(EvalForm :: TYPE_MOVE,
 								 $evals[0],
@@ -133,22 +125,17 @@ if (isset ($_GET['moveeval']))
 								 api_get_self() . '?moveeval=' . Security::remove_XSS($_GET['moveeval'])
 								 					  . '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
 
-		if ($move_form->validate())
-		{
+		if ($move_form->validate()) {
 			header('Location: ' .api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
 													   . '&moveeval=' . Security::remove_XSS($_GET['moveeval'])
 													   . '&targetcat=' . $move_form->exportValue('move_cat'));
 			exit;
 		}
-	}
-
-	else
-	{
+	} else {
 		$targetcat= Category :: load($_GET['targetcat']);
 		$course_to_crsind = ($evals[0]->get_course_code() != null && $targetcat[0]->get_course_code() == null);
 
-		if (!($course_to_crsind && !isset($_GET['confirm'])))
-		{
+		if (!($course_to_crsind && !isset($_GET['confirm']))) {
 			$evals[0]->move_to_cat($targetcat[0]);
 			header('Location: ' . api_get_self() . '?evaluationmoved=&selectcat=' . Security::remove_XSS($_GET['selectcat']));
 			exit;
@@ -159,13 +146,11 @@ if (isset ($_GET['moveeval']))
 }
 
 //move a link
-if (isset ($_GET['movelink']))
-{
+if (isset ($_GET['movelink'])) {
 	block_students();
 	$link= LinkFactory :: load($_GET['movelink']);
 	$move_form= new LinkForm(LinkForm :: TYPE_MOVE, null, $link[0], 'move_link_form', null, api_get_self() . '?movelink=' . $_GET['movelink'] . '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
-	if ($move_form->validate())
-	{
+	if ($move_form->validate()) {
 		$targetcat= Category :: load($move_form->exportValue('move_cat'));
 		$link[0]->move_to_cat($targetcat[0]);
 		unset ($link);
@@ -174,116 +159,106 @@ if (isset ($_GET['movelink']))
 	}
 }
 
-
 //parameters for categories
-if (isset ($_GET['visiblecat']))
-{
+if (isset ($_GET['visiblecat'])) {
 	block_students();
-	if (isset ($_GET['set_visible']))
-		$visibility_command= 1;
-	else
-		$visibility_command= 0;
+	if (isset ($_GET['set_visible'])) {
+		$visibility_command= 1;		
+	} else {
+		$visibility_command= 0;		
+	}
 	$cats= Category :: load($_GET['visiblecat']);
 	$cats[0]->set_visible($visibility_command);
 	$cats[0]->save();
 	$cats[0]->apply_visibility_to_children();
 	unset ($cats);
-	if ($visibility_command)
-	{
+	if ($visibility_command) {
 		$confirmation_message = get_lang('ViMod');
 		$filter_confirm_msg = false;
-	}
-	else
-	{
+	} else {
 		$confirmation_message = get_lang('InViMod');
 		$filter_confirm_msg = false;
 	}
 }
-if (isset ($_GET['deletecat']))
-{
+if (isset ($_GET['deletecat'])) {
 	block_students();
 	$cats= Category :: load($_GET['deletecat']);
 	//delete all categories,subcategories and results
-	if ($cats[0] != null)
-	{
-		if ($cats[0]->get_id() != 0) // better don't try to delete the root...
-			$cats[0]->delete_all();
+	if ($cats[0] != null) {
+		if ($cats[0]->get_id() != 0) {
+			// better don't try to delete the root...
+			$cats[0]->delete_all();		
+		} 
 	}
 	$confirmation_message = get_lang('CategoryDeleted');
 	$filter_confirm_msg = false;
 }
 //parameters for evaluations
-if (isset ($_GET['visibleeval']))
-{
+if (isset ($_GET['visibleeval'])) {
 	block_students();
-	if (isset ($_GET['set_visible']))
-		$visibility_command= 1;
-	else
-		$visibility_command= 0;
+	if (isset ($_GET['set_visible'])) {
+		$visibility_command= 1;		
+	} else {
+		$visibility_command= 0;		
+	}
+
 	$eval= Evaluation :: load($_GET['visibleeval']);
 	$eval[0]->set_visible($visibility_command);
 	$eval[0]->save();
 	unset ($eval);
-	if ($visibility_command)
-	{
+	if ($visibility_command) {
 		$confirmation_message = get_lang('ViMod');
 		$filter_confirm_msg = false;
-	}
-	else
-	{
+	} else {
 		$confirmation_message = get_lang('InViMod');
 		$filter_confirm_msg = false;
 	}
 }
-if (isset ($_GET['deleteeval']))
-{
+if (isset ($_GET['deleteeval'])) {
 	block_students();
 	$eval= Evaluation :: load($_GET['deleteeval']);
-	if ($eval[0] != null)
-		$eval[0]->delete_with_results();
-	$confirmation_message = get_lang('EvaluationDeleted');
+	if ($eval[0] != null) {
+		$eval[0]->delete_with_results();		
+	}
+	$confirmation_message = get_lang('GradebookEvaluationDeleted');
 	$filter_confirm_msg = false;
 }
 //parameters for links
-if (isset ($_GET['visiblelink']))
-{
+if (isset ($_GET['visiblelink'])) {
 	block_students();
-	if (isset ($_GET['set_visible']))
-		$visibility_command= 1;
-	else
-		$visibility_command= 0;
+	if (isset ($_GET['set_visible'])) {
+		$visibility_command= 1;		
+	}else {
+		$visibility_command= 0;		
+	}
 	$link= LinkFactory :: load($_GET['visiblelink']);
 	$link[0]->set_visible($visibility_command);
 	$link[0]->save();
 	unset ($link);
-	if ($visibility_command)
-	{
+	if ($visibility_command) {
 		$confirmation_message = get_lang('ViMod');
 		$filter_confirm_msg = false;
-	}
-	else
-	{
+	} else {
 		$confirmation_message = get_lang('InViMod');
 		$filter_confirm_msg = false;
 	}
 }
-if (isset ($_GET['deletelink']))
-{
+if (isset ($_GET['deletelink'])) {
 	block_students();
 	$link= LinkFactory :: load($_GET['deletelink']);
-	if ($link[0] != null)
-		$link[0]->delete();
+	if ($link[0] != null) {
+		$link[0]->delete();		
+	}
 	unset ($link);
 	$confirmation_message = get_lang('LinkDeleted');
 	$filter_confirm_msg = false;
 }
 
-if ($course_to_crsind && !isset($_GET['confirm']))
-{
+if ($course_to_crsind && !isset($_GET['confirm'])) {
 	block_students();
-	if (!isset($_GET['movecat']) && !isset($_GET['moveeval']))
-		die ('Error: movecat or moveeval not defined');
-
+	if (!isset($_GET['movecat']) && !isset($_GET['moveeval'])) {
+		die ('Error: movecat or moveeval not defined');		
+	}
 	$button = '<form name="confirm"
 					 method="post"
 					 action="'.api_get_self() .'?confirm='
@@ -297,47 +272,40 @@ if ($course_to_crsind && !isset($_GET['confirm']))
 	$warning_message = get_lang('MoveWarning').'<br><br>'.$button;
 	$filter_warning_msg = false;
 }
-
-
 //actions on the sortabletable
-if (isset ($_POST['action']))
-{
+if (isset ($_POST['action'])) {
 	block_students();
 	$number_of_selected_items= count($_POST['id']);
-	if ($number_of_selected_items == '0')
-	{
+	if ($number_of_selected_items == '0') {
 		$warning_message = get_lang('NoItemsSelected');
 		$filter_warning_msg = false;
 	}
-	else
-	{
-		switch ($_POST['action'])
-		{
+	else {
+		switch ($_POST['action']) {
 			case 'delete' :
 				$number_of_deleted_categories= 0;
 				$number_of_deleted_evaluations= 0;
 				$number_of_deleted_links= 0;
-				foreach ($_POST['id'] as $indexstr)
-				{
-					if (substr($indexstr, 0, 4) == 'CATE')
-					{
+				foreach ($_POST['id'] as $indexstr) {
+					if (substr($indexstr, 0, 4) == 'CATE') {
 						$cats= Category :: load(substr($indexstr, 4));
-						if ($cats[0] != null)
+						if ($cats[0] != null) {
 							$cats[0]->delete_all();
+						}
 						$number_of_deleted_categories++;
 					}
-					if (substr($indexstr, 0, 4) == 'EVAL')
-					{
+					if (substr($indexstr, 0, 4) == 'EVAL') {
 						$eval= Evaluation :: load(substr($indexstr, 4));
-						if ($eval[0] != null)
-							$eval[0]->delete_with_results();
+						if ($eval[0] != null) {
+						$eval[0]->delete_with_results();						
+						}
 						$number_of_deleted_evaluations++;
 					}
-					if (substr($indexstr, 0, 4) == 'LINK')
-					{
+					if (substr($indexstr, 0, 4) == 'LINK') {
 						$link= LinkFactory :: load(substr($indexstr, 4));
-						if ($link[0] != null)
-							$link[0]->delete();
+						if ($link[0] != null) {
+							$link[0]->delete();							
+						}
 						$number_of_deleted_links++;
 					}
 				}
@@ -400,121 +368,116 @@ if (isset ($_POST['action']))
 	}
 }
 
-if (isset ($_POST['submit']) && isset ($_POST['keyword']))
-{
+if (isset ($_POST['submit']) && isset ($_POST['keyword'])) {
 	header('Location: ' . api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
 											   . '&search='.Security::remove_XSS($_POST['keyword']));
 	exit;
 }
-
-
 // --------------------------------------------------------------------------------
 // -                       DISPLAY HEADERS AND MESSAGES                           -
 // --------------------------------------------------------------------------------
 
-if (!isset($_GET['exportpdf']) and !isset($_GET['export_certificate']))
-{
-	if (isset ($_GET['studentoverview']))
-	{
+if (!isset($_GET['exportpdf']) and !isset($_GET['export_certificate'])) {
+	if (isset ($_GET['studentoverview'])) {
 		$interbreadcrumb[]= array (
-			'url' => 'gradebook.php?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+			'url' => $_SESSION['gradebook_dest'].'?selectcat=' . Security::remove_XSS($_GET['selectcat']),
 			'name' => get_lang('Gradebook')
 		);
 		Display :: display_header(get_lang('FlatView'));
 	}
-	elseif (isset ($_GET['search']))
-	{
+	elseif (isset ($_GET['search'])) {
 		$interbreadcrumb[]= array (
-			'url' => 'gradebook.php?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+			'url' => $_SESSION['gradebook_dest'].'?selectcat=' . Security::remove_XSS($_GET['selectcat']),
 			'name' => get_lang('Gradebook')
 		);
 		Display :: display_header(get_lang('SearchResults'));
-	} else
-	{
+	} else{
 		Display :: display_header(get_lang('Gradebook'));
 	}
 }
 
-if (isset ($_GET['categorymoved']))
-	Display :: display_confirmation_message(get_lang('CategoryMoved'),false);
-if (isset ($_GET['evaluationmoved']))
+if (isset ($_GET['categorymoved'])) {
+	Display :: display_confirmation_message(get_lang('CategoryMoved'),false);	
+} 
+if (isset ($_GET['evaluationmoved'])) {
 	Display :: display_confirmation_message(get_lang('EvaluationMoved'),false);
-if (isset ($_GET['linkmoved']))
-	Display :: display_confirmation_message(get_lang('LinkMoved'),false);
-if (isset ($_GET['addcat']))
-	Display :: display_confirmation_message(get_lang('CategoryAdded'),false);
-if (isset ($_GET['linkadded']))
-	Display :: display_confirmation_message(get_lang('LinkAdded'),false);
-if (isset ($_GET['addresult']))
+}
+if (isset ($_GET['linkmoved'])) {
+	Display :: display_confirmation_message(get_lang('LinkMoved'),false);	
+}
+if (isset ($_GET['addcat'])) {
+	Display :: display_confirmation_message(get_lang('CategoryAdded'),false);	
+}
+if (isset ($_GET['linkadded'])) {
+	Display :: display_confirmation_message(get_lang('LinkAdded'),false);	
+}
+if (isset ($_GET['addresult'])) {
 	Display :: display_confirmation_message(get_lang('ResultAdded'),false);
-if (isset ($_GET['editcat']))
-	Display :: display_confirmation_message(get_lang('CategoryEdited'),false);
-if (isset ($_GET['editeval']))
-	Display :: display_confirmation_message(get_lang('EvaluationEdited'),false);
-if (isset ($_GET['linkedited']))
-	Display :: display_confirmation_message(get_lang('LinkEdited'),false);
-if (isset ($_GET['nolinkitems']))
-	Display :: display_warning_message(get_lang('NoLinkItems'),false);
-if (isset ($_GET['addallcat']))
-	Display :: display_normal_message(get_lang('AddAllCat'),false);
-
-if (isset ($confirmation_message))
+}
+if (isset ($_GET['editcat'])) {
+	Display :: display_confirmation_message(get_lang('CategoryEdited'),false);	
+}
+if (isset ($_GET['editeval'])) {
+	Display :: display_confirmation_message(get_lang('EvaluationEdited'),false);	
+}
+if (isset ($_GET['linkedited'])) {
+	Display :: display_confirmation_message(get_lang('LinkEdited'),false);	
+}
+if (isset ($_GET['nolinkitems'])) {
+	Display :: display_warning_message(get_lang('NoLinkItems'),false);	
+}
+if (isset ($_GET['addallcat'])) {
+	Display :: display_normal_message(get_lang('AddAllCat'),false);	
+}
+if (isset ($confirmation_message)) {
 	Display :: display_confirmation_message($confirmation_message,$filter_confirm_msg);
-if (isset ($warning_message))
-	Display :: display_warning_message($warning_message,$filter_warning_msg);
-
-if (isset ($move_form))
-	Display :: display_normal_message($move_form->toHtml(),false);
-
-
+}
+if (isset ($warning_message)) {
+	Display :: display_warning_message($warning_message,$filter_warning_msg);	
+}
+if (isset ($move_form)) {
+	Display :: display_normal_message($move_form->toHtml(),false);	
+}
 // --------------------------------------------------------------------------------
 // -                        LOAD DATA & DISPLAY TABLE                             -
 // --------------------------------------------------------------------------------
-
-
 $is_platform_admin= api_is_platform_admin();
 $is_course_admin= api_is_allowed_to_create_course();
-
-
 //load data for category, evaluation and links
-if (!isset ($_GET['selectcat']) || empty ($_GET['selectcat']))
+if (!isset ($_GET['selectcat']) || empty ($_GET['selectcat'])) {
 	$category= 0;
-else
-	$category= $_GET['selectcat'];
-
+	} else {
+	$category= $_GET['selectcat'];		
+	}
 // search form
 $simple_search_form= new UserForm(UserForm :: TYPE_SIMPLE_SEARCH, null, 'simple_search_form', null, api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']));
 $values= $simple_search_form->exportValues();
 $keyword = '';
-if (isset($_GET['search']) && !empty($_GET['search']))
-	$keyword = Security::remove_XSS($_GET['search']);
-if ($simple_search_form->validate() && (empty($keyword)))
+if (isset($_GET['search']) && !empty($_GET['search'])) {
+	$keyword = Security::remove_XSS($_GET['search']);	
+}
+if ($simple_search_form->validate() && (empty($keyword))) {
 	$keyword = $values['keyword'];
-
-
-if (!empty($keyword))
-{
+}
+if (!empty($keyword)) {
 	$cats= Category :: load($category);
 	$allcat= array ();
 	$alleval= Evaluation :: find_evaluations($keyword, $cats[0]->get_id());
 	$alllink= LinkFactory :: find_links($keyword, $cats[0]->get_id());
-}
-elseif (isset ($_GET['studentoverview']))
-{
+} elseif (isset ($_GET['studentoverview'])) {
 	$cats= Category :: load($category);
 	$stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
 	$allcat= array ();
 	$alleval= $cats[0]->get_evaluations($stud_id, true);
 	$alllink= $cats[0]->get_links($stud_id, true);
-	if (isset ($_GET['exportpdf']))
-	{
+	if (isset ($_GET['exportpdf'])) {
 		$datagen = new GradebookDataGenerator ($allcat,$alleval, $alllink);
 		$header_names = array(get_lang('Name'),get_lang('Description'),get_lang('Weight'),get_lang('Date'),get_lang('Results'));
 		$data_array = $datagen->get_data(GradebookDataGenerator :: GDG_SORT_NAME,0,null,true);	
 		$newarray = array();
-		foreach ($data_array as $data)
-			$newarray[] = array_slice($data, 1);		
-		
+		foreach ($data_array as $data) {
+			$newarray[] = array_slice($data, 1);				
+		}
 		$pdf= new Cezpdf();
 		$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
 		$pdf->ezSetMargins(30, 30, 50, 30);
@@ -527,17 +490,13 @@ elseif (isset ($_GET['studentoverview']))
 		$pdf->ezStream();
 		exit;
 	}
-}
-elseif(!empty($_GET['export_certificate']))
-{
+} elseif (!empty($_GET['export_certificate'])){
 	$user_id = strval(intval($_GET['user']));
-	if(!api_is_allowed_to_edit(true,true))
-	{
+	if (!api_is_allowed_to_edit(true,true)) {
 		$user_id = api_get_user_id();
 	}
 	$category = Category :: load ($_GET['cat']);
-	if($category[0]->is_certificate_available($user_id))
-	{
+	if ($category[0]->is_certificate_available($user_id)) {
 		$user= get_user_info_from_id($user_id);
 		$scoredisplay = ScoreDisplay :: instance();
 		$scorecourse = $category[0]->calc_score($user_id);
@@ -576,38 +535,30 @@ elseif(!empty($_GET['export_certificate']))
 		$pdf->ezStream();
 	}
 	exit;	
-}
-else
-{
+} else {
 	$cats= Category :: load($category);
 	$stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
 	$allcat= $cats[0]->get_subcategories($stud_id);
 	$alleval= $cats[0]->get_evaluations($stud_id);
 	$alllink= $cats[0]->get_links($stud_id);
 }
-
 $addparams = array ('selectcat' => $cats[0]->get_id());
-if (isset($_GET['search']))
-	$addparams['search'] = $keyword;
-if (isset ($_GET['studentoverview']))
+if (isset($_GET['search'])) {
+	$addparams['search'] = $keyword;	
+}
+if (isset ($_GET['studentoverview'])) {
 	$addparams['studentoverview'] = '';
-
-
+}
 $gradebooktable= new GradebookTable($cats[0], $allcat, $alleval, $alllink, $addparams);
-if ((empty ($allcat)) && (empty ($alleval)) && (empty ($alllink)) && (!$is_platform_admin) && ($is_course_admin) && (!isset ($_GET['selectcat'])))
-{
+if ((empty ($allcat)) && (empty ($alleval)) && (empty ($alllink)) && (!$is_platform_admin) && ($is_course_admin) && (!isset ($_GET['selectcat']))) {
 	Display :: display_normal_message(get_lang('GradebookWelcomeMessage') . '<br /><br /><form name="createcat" method="post" action="' . api_get_self() . '?createallcategories=1"><input type="submit" value="' . get_lang('CreateAllCat') . '"></form>',false);
 }
 //here we are in a sub category
-if ($category != '0')
-{
+if ($category != '0') {
 	DisplayGradebook :: display_header_gradebook($cats[0], 1, $_GET['selectcat'], $is_course_admin, $is_platform_admin, $simple_search_form);
-}
-//this is the root category
-else
-{
+} else {
+	//this is the root category
 	DisplayGradebook :: display_header_gradebook($cats[0], (((count($allcat) == '0') && (!isset ($_GET['search']))) ? 0 : 1), 0, $is_course_admin, $is_platform_admin, $simple_search_form);
 }
 $gradebooktable->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 32 - 21
main/gradebook/gradebook_add_cat.php

@@ -1,11 +1,10 @@
-<?php
-
-// $Id: gradebook_add_cat.php 880 2007-05-07 09:32:52Z bert $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+    Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -19,25 +18,34 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, 108 rue du Corbeau, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
-
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/catform.class.php');
+require_once '../inc/global.inc.php';
+$_in_course = true;
+$course_code = api_get_course_id();
+if ( empty ($course_code ) ) {
+	$_in_course = false;
+}
+
+require_once 'lib/be.inc.php';
+require_once 'lib/gradebook_functions.inc.php';
+require_once 'lib/fe/catform.class.php';
 api_block_anonymous_users();
 block_students();
 
 $catadd = new Category();
-$catadd->set_user_id($_user['user_id']);
+$my_user_id = api_get_user_id();
+$catadd->set_user_id($my_user_id);
 $catadd->set_parent_id(Database::escape_string($_GET['selectcat']));
 $catcourse = Category :: load ($_GET['selectcat']);
-$catadd->set_course_code($catcourse[0]->get_course_code());
+if ($_in_course) {
+	$catadd->set_course_code($course_code);
+} else {
+	$catadd->set_course_code($catcourse[0]->get_course_code());
+}
 $form = new CatForm(CatForm :: TYPE_ADD, $catadd, 'add_cat_form', null, api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']));
 if ($form->validate()) {
 	$values = $form->exportValues();
@@ -58,20 +66,23 @@ if ($form->validate()) {
 	$cat->set_user_id($values['hid_user_id']);
 	$cat->set_parent_id($values['hid_parent_id']);
 	$cat->set_weight($values['weight']);
-	if (empty ($values['visible']))
+	if (empty ($values['visible'])) {
 		$visible = 0;
-	else
+	} else {
 		$visible = 1;
+	}
 	$cat->set_visible($visible);
 	$cat->add();
-	header('Location: gradebook.php?addcat=&selectcat=' . $cat->get_parent_id());
+	header('Location: '.$_SESSION['gradebook_dest'].'?addcat=&selectcat=' . $cat->get_parent_id());
 	exit;
 }
+
+if ( !$_in_course ) {
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php?selectcat='.Security::remove_XSS($_GET['selectcat']),
-	'name' => get_lang('Gradebook'
-));
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']),
+	'name' => get_lang('Gradebook')
+	);
+}
 Display :: display_header(get_lang('NewCategory'));
 $form->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 17 - 20
main/gradebook/gradebook_add_eval.php

@@ -1,12 +1,10 @@
-<?php
-
-
-// $Id: gradebook_add_eval.php 880 2007-05-07 09:32:52Z bert $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -20,16 +18,15 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/evalform.class.php');
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/evalform.class.php');
 api_block_anonymous_users();
 block_students();
 
@@ -51,17 +48,19 @@ if ($form->validate()) {
 	$eval->set_name($values['name']);
 	$eval->set_description($values['description']);
 	$eval->set_user_id($values['hid_user_id']);
-	if (!empty ($values['hid_course_code']))
+	if (!empty ($values['hid_course_code'])) {
 		$eval->set_course_code($values['hid_course_code']);
+	}
 	$eval->set_category_id($values['hid_category_id']);
 	$eval->set_weight($values['weight']);
 	//converts the date back to unix timestamp format
 	$eval->set_date(strtotime($values['date']));
 	$eval->set_max($values['max']);
-	if (empty ($values['visible']))
+	if (empty ($values['visible'])) {
 		$visible = 0;
-	else
+	} else {
 		$visible = 1;
+	}
 	$eval->set_visible($visible);
 	$eval->add();
 	if ($eval->get_course_code() == null) {
@@ -69,7 +68,7 @@ if ($form->validate()) {
 			header('Location: gradebook_add_user.php?selecteval=' . $eval->get_id());
 			exit;
 		} else {
-			header('Location: gradebook.php?selectcat=' . $eval->get_category_id());
+			header('Location: '.$_SESSION['gradebook_dest'].'?selectcat=' . $eval->get_category_id());
 			exit;
 		}
 	} else {
@@ -77,15 +76,14 @@ if ($form->validate()) {
 			header('Location: gradebook_add_result.php?selecteval=' . $eval->get_id());
 			exit;
 		} else {
-			header('Location: gradebook.php?selectcat=' . $eval->get_category_id());
+			header('Location: '.$_SESSION['gradebook_dest'].'?selectcat=' . $eval->get_category_id());
 			exit;
 		}
 	}
-
 }
 
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php?selectcat='.Security::remove_XSS($_GET['selectcat']),
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']),
 	'name' => get_lang('Gradebook'
 ));
 Display :: display_header(get_lang('NewEvaluation'));
@@ -93,5 +91,4 @@ if ($evaladd->get_course_code() == null) {
 	Display :: display_normal_message(get_lang('CourseIndependentEvaluation'),false);
 }
 $form->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 57 - 44
main/gradebook/gradebook_add_link.php

@@ -1,11 +1,11 @@
-<?php
-// $Id: gradebook_add_link.php 338 2007-04-06 14:02:05Z stijn $
+<?php // $Id:  $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
-	Copyright (c) 2007 Stijn Konings, Bert Stepp� (Hogeschool Gent)
+	Copyright (c) 2006-2008 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	Copyright (c) various contributors
 
 	For a full list of contributors, see "credits.txt".
 	The full license can be read in "license.txt".
@@ -17,20 +17,22 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/linkform.class.php');
-include_once ('lib/fe/linkaddeditform.class.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/linkform.class.php');
+require_once ('lib/fe/linkaddeditform.class.php');
+require_once ('../forum/forumfunction.inc.php');
 api_block_anonymous_users();
 block_students();
-
+$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD);
+$tbl_link=Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 $category = Category :: load($_GET['selectcat']);
 
 $typeform = new LinkForm(LinkForm :: TYPE_CREATE,
@@ -44,8 +46,7 @@ $typeform = new LinkForm(LinkForm :: TYPE_CREATE,
 						;
 
 // if user selected a link type
-if ($typeform->validate() && isset($_GET['newtypeselected']))
-{
+if ($typeform->validate() && isset($_GET['newtypeselected'])) {
 	// reload page, this time with a parameter indicating the selected type
 	header('Location: '.api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
 											 . '&typeselected='.$typeform->exportValue('select_link')
@@ -54,8 +55,7 @@ if ($typeform->validate() && isset($_GET['newtypeselected']))
 }
 
 // link type selected, show 2nd form to retrieve the link data
-if (isset($_GET['typeselected']) && $_GET['typeselected'] != '0')
-{
+if (isset($_GET['typeselected']) && $_GET['typeselected'] != '0') {
 	$addform = new LinkAddEditForm(LinkAddEditForm :: TYPE_ADD,
 								   $category[0],
 								   intval($_GET['typeselected']),
@@ -63,50 +63,62 @@ if (isset($_GET['typeselected']) && $_GET['typeselected'] != '0')
 								   'add_link',
 								   api_get_self() . '?selectcat=' . $_GET['selectcat']
 														. '&typeselected=' . $_GET['typeselected'] . '&course_code=' . $_GET['course_code']);
-	if ($addform->validate())
-	{
+	if ($addform->validate()) {
 		$addvalues = $addform->exportValues();
-
 		$link= LinkFactory :: create($_GET['typeselected']);
 		$link->set_user_id(api_get_user_id());
-		if($category[0]->get_course_code() == '' && !empty($_GET['course_code']))
-		{
+		if($category[0]->get_course_code() == '' && !empty($_GET['course_code'])) {
 			$link->set_course_code(Database::escape_string($_GET['course_code']));
-		}
-		else
-		{
+			
+		} else {
 			$link->set_course_code($category[0]->get_course_code());
 		}
 		$link->set_category_id($category[0]->get_id());
 		
-		if ($link->needs_name_and_description())
+		if ($link->needs_name_and_description()) {
 			$link->set_name($addvalues['name']);
-		else
+		} else {
 			$link->set_ref_id($addvalues['select_link']);
-
+		}
 		$link->set_weight($addvalues['weight']);
 		
-		if ($link->needs_max())
+		if ($link->needs_max()) {
 			$link->set_max($addvalues['max']);
-		
+		}
 		$link->set_date(strtotime($addvalues['date']));
 		
-		if ($link->needs_name_and_description())
+		if ($link->needs_name_and_description()) {
 			$link->set_description($addvalues['description']);
-		
+		}
 		$link->set_visible(empty ($addvalues['visible']) ? 0 : 1);
 		
-		$link->add();
-
+		//update view_properties
+		$work_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION);	
+		
+		if ( isset($_GET['typeselected']) && 5==$_GET['typeselected'] && (isset($addvalues['select_link']) && $addvalues['select_link']!="")) {
+			$sql1='SELECT thread_title from '.$tbl_forum_thread.' where thread_id='.$addvalues['select_link'].';';
+			$res1=api_sql_query($sql1);
+			$rowtit=Database::fetch_row($res1);
+			$res_l=api_sql_query('SELECT count(*) FROM '.$tbl_link.' WHERE ref_id='.$addvalues['select_link'].' and course_code="'.Security::remove_XSS($_GET['course_code']).'" and type=5;');
+			$row=Database::fetch_row($res_l);
+			
+			if ( $row[0]==0 ) {
+				$link->add();
+				$sql='UPDATE '.$tbl_forum_thread.' set thread_qualify_max='.$addvalues['weight'].',thread_weight='.$addvalues['weight'].',thread_title_qualify="'.$rowtit[0].'" WHERE thread_id='.$addvalues['select_link'].';';
+				$sql_l='UPDATE '.$tbl_link.' SET weight='.$addvalues['weight'].' WHERE ref_id='.$addvalues['select_link'].';';
+				api_sql_query($sql);
+				api_sql_query($sql_l);
+			}
+			
+		} else {
+			$link->add();
+		}
 
-		if ($addvalues['addresult'] == 1)
-		{
+		if ($addvalues['addresult'] == 1) {
 			header('Location: gradebook_add_result.php?selecteval=' . $link->get_ref_id());
 			exit;
-		}
-		else
-		{
-			header('Location: gradebook.php?linkadded=&selectcat=' . $_GET['selectcat']);
+		} else {
+			header('Location: '.$_SESSION['gradebook_dest'].'?linkadded=&selectcat=' . $_GET['selectcat']);
 			exit;
 		}
 
@@ -116,14 +128,15 @@ if (isset($_GET['typeselected']) && $_GET['typeselected'] != '0')
 
 
 $interbreadcrumb[]= array (
-	'url' => 'gradebook.php?selectcat=' . $_GET['selectcat'],
+	'url' => $_SESSION['gradebook_dest'].'?selectcat=' . $_GET['selectcat'],
 	'name' => get_lang('Gradebook'
 ));
 
 Display :: display_header(get_lang('MakeLink'));
-if (isset ($typeform))
+if (isset ($typeform)) {
 	$typeform->display();
-if (isset ($addform))
+}
+if (isset ($addform)) {
 	$addform->display();
-Display :: display_footer();
-?>
+}
+Display :: display_footer();

+ 14 - 13
main/gradebook/gradebook_add_link_select_course.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2007 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2007 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,17 +18,17 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/catform.class.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/catform.class.php');
 api_block_anonymous_users();
 block_students();
 
@@ -37,7 +37,8 @@ $catadd->set_user_id($_user['user_id']);
 $catadd->set_parent_id($_GET['selectcat']);
 $catcourse = Category :: load ($_GET['selectcat']);
 //$catadd->set_course_code($catcourse[0]->get_course_code());
-$form = new CatForm(CatForm :: TYPE_SELECT_COURSE, $catadd, 'add_cat_form', null, api_get_self().'?selectcat=' . $_GET['selectcat']);
+$form = new CatForm(CatForm :: TYPE_SELECT_COURSE, $catadd, 'add_cat_form', null, api_get_self().'?selectcat=' . Security::remove_XSS($_GET['selectcat']));
+
 if ($form->validate()) {
 	$values = $form->exportValues();
 	$cat = new Category();
@@ -46,11 +47,11 @@ if ($form->validate()) {
 	header('location: gradebook_add_link.php?selectcat=' .Security::remove_XSS($_GET['selectcat']).'&course_code='.Security::remove_XSS($values['select_course']));
 	exit;
 }
+
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php?selectcat='.$_GET['selectcat'],
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']),
 	'name' => get_lang('Gradebook'
 ));
 Display :: display_header(get_lang('NewCategory'));
 $form->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 16 - 18
main/gradebook/gradebook_add_result.php

@@ -1,11 +1,10 @@
-<?php
-
-// $Id: gradebook_add_result.php 905 2007-05-07 14:00:29Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -19,30 +18,30 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/evalform.class.php');
-include_once ('lib/fe/displaygradebook.php');
-include_once ('lib/scoredisplay.class.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/evalform.class.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/scoredisplay.class.php');
 api_block_anonymous_users();
 block_students();
 
 $resultadd = new Result();
 $resultadd->set_evaluation_id($_GET['selecteval']);
 $evaluation = Evaluation :: load($_GET['selecteval']);
-$add_result_form = new EvalForm(EvalForm :: TYPE_RESULT_ADD, $evaluation[0], $resultadd, 'add_result_form', null, api_get_self() . '?selectcat=' . $_GET['selectcat'] . '&selecteval=' . $_GET['selecteval']);
+$add_result_form = new EvalForm(EvalForm :: TYPE_RESULT_ADD, $evaluation[0], $resultadd, 'add_result_form', null, api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']) . '&selecteval=' . Security::remove_XSS($_GET['selecteval']));
 if ($add_result_form->validate()) {
 	$values = $add_result_form->exportValues();
 	$nr_users = $values['nr_users'];
 	if ($nr_users == '0') {
-		header('Location: gradebook_view_result.php?addresultnostudents=&selecteval=' . $_GET['selecteval']);
+		header('Location: gradebook_view_result.php?addresultnostudents=&selecteval=' . Security::remove_XSS($_GET['selecteval']));
 		exit;
 	}
 	$scores = ($values['score']);
@@ -55,11 +54,11 @@ if ($add_result_form->validate()) {
 		$res->add();
 		next($scores);
 	}
-	header('Location: gradebook_view_result.php?addresult=&selecteval=' . $_GET['selecteval']);
+	header('Location: gradebook_view_result.php?addresult=&selecteval=' . Security::remove_XSS($_GET['selecteval']));
 	exit;
 }
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 Display :: display_header(get_lang('AddResult'));
@@ -67,5 +66,4 @@ DisplayGradebook :: display_header_result ($evaluation[0], null, 0,0);
 echo '<div class="main">';
 echo $add_result_form->toHtml();
 echo '</div>';
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 33 - 45
main/gradebook/gradebook_add_user.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: gradebook_add_result.php 328 2007-04-04 14:02:48Z stijn $
+<?php// $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,27 +18,27 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
+//$cidReset = true;
+require_once '../inc/global.inc.php';
 $this_section = SECTION_MYGRADEBOOK;
-include_once ('lib/be.inc.php');
-include_once ('lib/fe/displaygradebook.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/evalform.class.php');
-include_once ('lib/scoredisplay.class.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/evalform.class.php');
+require_once ('lib/scoredisplay.class.php');
 api_block_anonymous_users();
 block_students();
 
 $evaluation= Evaluation :: load($_GET['selecteval']);
 $newstudents = $evaluation[0]->get_not_subscribed_students();
-if (count($newstudents) == '0')
-{
-	header('Location: gradebook_view_result.php?nouser=&selecteval=' . $_GET['selecteval']);
+
+if (count($newstudents) == '0') {
+	header('Location: gradebook_view_result.php?nouser=&selecteval=' . Security::remove_XSS($_GET['selecteval']));
 	exit;
 }
 $add_user_form= new EvalForm(EvalForm :: TYPE_ADD_USERS_TO_EVAL,
@@ -50,60 +50,48 @@ $add_user_form= new EvalForm(EvalForm :: TYPE_ADD_USERS_TO_EVAL,
 							 $_GET['firstletter'],
 							 $newstudents);
 
-if ($_POST['submit_button'])
-{
+if ( isset($_POST['submit_button']) ) {
 	$users= is_array($_POST['add_users']) ? $_POST['add_users'] : array ();
-	foreach ($users as $key => $value)
+	foreach ($users as $key => $value){
 		$users[$key]= intval($value);
+	}
 
-	if (count($users) == 0)
-	{
-		header('Location: ' . api_get_self() . '?erroroneuser=&selecteval=' . $_GET['selecteval']);
+	if (count($users) == 0) {
+		header('Location: ' . api_get_self() . '?erroroneuser=&selecteval=' .Security::remove_XSS($_GET['selecteval']));
 		exit;
-	}
-	else
-	{
-		foreach ($users as $user_id)
-		{
+	} else {
+		foreach ($users as $user_id) {
 			$result= new Result();
 			$result->set_user_id($user_id);
 			$result->set_evaluation_id($_GET['selecteval']);
 			$result->set_date(time());
 			$result->add();
+			}
 		}
-	}
-	header('Location: gradebook_view_result.php?adduser=&selecteval=' . $_GET['selecteval']);
+	header('Location: gradebook_view_result.php?adduser=&selecteval=' .Security::remove_XSS($_GET['selecteval']));
 	exit;
-
-}
-elseif ($_POST['firstLetterUser'])
-{
-	$firstletter= $_POST['firstLetterUser'];
-	if (!empty ($firstletter))
-	{
-		header('Location: ' . api_get_self() . '?firstletter=' . $firstletter . '&selecteval=' . $_GET['selecteval']);
-		exit;
-	}
+	} elseif ($_POST['firstLetterUser']) {
+		$firstletter= $_POST['firstLetterUser'];
+		if (!empty ($firstletter)) {
+			header('Location: ' . api_get_self() . '?firstletter=' . Security::remove_XSS($firstletter) . '&selecteval=' . Security::remove_XSS($_GET['selecteval']));
+			exit;
+		}
 }
 
-
-
 $interbreadcrumb[]= array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 $interbreadcrumb[]= array (
-	'url' => 'gradebook_view_result.php?selecteval=' . $_GET['selecteval'],
+	'url' => 'gradebook_view_result.php?selecteval=' .Security::remove_XSS($_GET['selecteval']),
 	'name' => get_lang('ViewResult'
 ));
 Display :: display_header(get_lang('AddUserToEval'));
-if (isset ($_GET['erroroneuser']))
-{
+if (isset ($_GET['erroroneuser'])){
 	Display :: display_warning_message(get_lang('AtLeastOneUser'),false);
 }
 DisplayGradebook :: display_header_result($evaluation[0], null, 0,0);
 echo '<div class="main">';
 echo $add_user_form->toHtml();
 echo '</div>';
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 165 - 0
main/gradebook/gradebook_edit_all.php

@@ -0,0 +1,165 @@
+<?php // $Id: $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2006-2008 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+$language_file= 'gradebook';
+$cidReset= true;
+require_once ('../inc/global.inc.php');
+$this_section = SECTION_MYGRADEBOOK;
+require_once ('lib/be.inc.php');
+require_once ('lib/scoredisplay.class.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/catform.class.php');
+require_once ('lib/fe/evalform.class.php');
+require_once ('lib/fe/linkform.class.php');
+require_once ('lib/gradebook_data_generator.class.php');
+require_once ('lib/fe/gradebooktable.class.php');
+require_once ('lib/fe/displaygradebook.php');
+
+api_block_anonymous_users();
+
+if (!api_is_allowed_to_edit()) {
+	header('Location: /index.php');
+}
+// --------------------------------------------------------------------------------
+// -                       DISPLAY HEADERS AND MESSAGES                           -
+// --------------------------------------------------------------------------------
+
+if (!isset($_GET['exportpdf']) and !isset($_GET['export_certificate'])) {
+	if (isset ($_GET['studentoverview'])) {
+		$interbreadcrumb[]= array (
+			'url' => 'gradebook.php?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+			'name' => get_lang('Gradebook')
+		);
+		Display :: display_header(get_lang('FlatView'));
+	} elseif (isset ($_GET['search'])) {
+		$interbreadcrumb[]= array (
+			'url' => 'gradebook.php?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+			'name' => get_lang('Gradebook')
+		);
+		Display :: display_header(get_lang('SearchResults'));
+	} else {
+		$interbreadcrumb[]= array (
+			'url' => 'index.php?',
+			'name' => get_lang('Gradebook'));
+
+		Display :: display_header('');
+		//api_get_cidreq()
+	}
+}
+
+
+$table_link = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+$table_evaluation = Database::get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
+$table_forum_thread=Database::get_course_table(TABLE_FORUM_THREAD);
+/*
+if($_SERVER['REQUEST_METHOD']=='POST'):
+	foreach($_POST['link'] as $key => $value){
+		api_sql_query('UPDATE '.$table_link.' SET weight = '."'".$value."'".' WHERE id = '.$key);
+	}
+	foreach($_POST['evaluation'] as $key => $value){
+		api_sql_query('UPDATE '.$table_evaluation.' SET weight = '."'".$value."'".' WHERE id = '.$key);
+	}
+	Display :: display_normal_message(get_lang('GradebookWeightUpdated')) . '<br /><br />';
+endif;*/
+/*
+define('LINK_EXERCISE',1);
+define('LINK_DROPBOX',2);
+define('LINK_STUDENTPUBLICATION',3);
+define('LINK_LEARNPATH',4);
+define('LINK_FORUM_THREAD',5);
+*/
+$table_evaluated[1] = array(TABLE_QUIZ_TEST, 'title', 'id', get_lang('Exercise'));
+$table_evaluated[2] = array(TABLE_DROPBOX_FILE, 'name','id', get_lang('Dropbox'));
+$table_evaluated[3] = array(TABLE_STUDENT_PUBLICATION, 'url','id', get_lang('Student_publication'));
+$table_evaluated[4] = array(TABLE_LP_MAIN, 'name','id', get_lang('Learnpath'));
+$table_evaluated[5] = array(TABLE_FORUM_THREAD, 'thread_title_qualify', 'thread_id', get_lang('Forum'));
+
+
+function get_table_type_course($type,$course) {
+	global $_configuration;
+	global $table_evaluated;
+	return Database::get_course_table($table_evaluated[$type][0],$_configuration['db_prefix'].$course);
+}
+
+if($_POST['submitted']==1) {
+	Display :: display_normal_message(get_lang('GradebookWeightUpdated')) . '<br /><br />';
+	if (isset($_POST['evaluation'])) {
+		require_once 'lib/be/evaluation.class.php';
+		$eval_log = new Evaluation();
+	}
+	
+	if(isset($_POST['link'])){
+		require_once 'lib/be/abstractlink.class.php';
+		//$eval_link_log = new AbstractLink();
+	}
+	
+}
+
+$category_id = (int)$_GET['selectcat'];
+$sql='SELECT * FROM '.$table_link.' WHERE category_id = '.$category_id;
+$result = api_sql_query($sql,__FILE__,__LINE__);
+	while($row = Database ::fetch_array($result)){
+	
+		//update only if value changed
+		if(isset($_POST['link'][$row['id']]) && $_POST['link'][$row['id']] != $row['weight']) {
+			api_sql_query('UPDATE '.$table_link.' SET weight = '."'".trim($_POST['link'][$row['id']])."'".' WHERE id = '.$row['id'],__FILE__,__LINE__);
+			api_sql_query('UPDATE '.$table_forum_thread.' SET thread_weight='.$_POST['link'][$row['id']].' WHERE thread_id='.$row['ref_id']);
+			AbstractLink::add_link_log($row['id']);
+			$row['weight'] = trim($_POST['link'][$row['id']]);
+		}
+
+		$tempsql = api_sql_query('SELECT * FROM '.get_table_type_course($row['type'],$row['course_code']).' WHERE '.$table_evaluated[$row['type']][2].' = '.$row['ref_id']);
+		$resource_name = Database ::fetch_array($tempsql);	
+	
+		$output.= '<tr><td> [ '.$table_evaluated[$row['type']][3].' ] '.$resource_name[$table_evaluated[$row['type']][1]].'</td><td><input size="10" type="text" name="link['.$row['id'].']" value="'.$row['weight'].'"/></td></tr>';	
+	}
+
+	$sql = api_sql_query('SELECT * FROM '.$table_evaluation.' WHERE category_id = '.$category_id,__FILE__,__LINE__);
+	while($row = Database ::fetch_array($sql)) {
+	
+		//update only if value changed
+		if(isset($_POST['evaluation'][$row['id']]) && $_POST['evaluation'][$row['id']] != $row['weight']) {
+			api_sql_query('UPDATE '.$table_evaluation.' SET weight = '."'".trim($_POST['evaluation'][$row['id']])."'".' WHERE id = '.$row['id'],__FILE__,__LINE__);
+			AbstractLink::add_link_log($row['id']);
+			$row['weight'] = trim($_POST['evaluation'][$row['id']]);
+		}
+
+	$output.= '<tr><td> [ '.get_lang('Evaluation').$table_evaluated[$row['type']][3].' ] '.$row['name'].'</td><td><input type="text" size="10" name="evaluation['.$row['id'].']" value="'.$row['weight'].'"/></td></tr>';	
+}
+?>
+<a href="/main/gradebook/index.php?<?php echo api_get_cidreq() ?>&selectcat=<?php echo $category_id ?>"><< <?php echo get_lang('Back') ?>
+<!--<a href="/main/gradebook/index.php?<?php echo api_get_cidreq() ?>&selectcat=<?php echo $category_id ?>"><< <?php echo get_lang('Back') ?></a>-->
+<form method="post" action="gradebook_edit_all.php?<?php echo api_get_cidreq() ?>&selectcat=<?php echo $category_id?>">
+<table class="data_table">
+		 <tr class="row_odd">
+		  <th><?php echo get_lang('Resource'); ?></th>
+		  <th><?php echo get_lang('Weight'); ?></th>
+		 </tr>
+		 <?php echo $output ?>
+ </table>
+ <input type="hidden" name="submitted" value="1" />
+  <input type="submit" name="name" value="<?php echo get_lang('Save') ?>"/>
+</form>
+<?php
+Display :: display_footer();
+?>

+ 19 - 24
main/gradebook/gradebook_edit_cat.php

@@ -1,11 +1,10 @@
-<?php
-
-// $Id: gradebook_edit_cat.php 880 2007-05-07 09:32:52Z bert $
+<?php // $Id:$
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -19,19 +18,18 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/catform.class.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/catform.class.php');
 api_block_anonymous_users();
 block_students();
-
 $catedit = Category :: load($_GET['editcat']);
 $form = new CatForm(CatForm :: TYPE_EDIT, $catedit[0], 'edit_cat_form');
 if ($form->validate()) {
@@ -39,12 +37,9 @@ if ($form->validate()) {
 	$cat = new Category();
 	$cat->set_id($values['hid_id']);
 	$cat->set_name($values['name']);
-	if (empty ($values['course_code']))
-	{
+	if (empty ($values['course_code'])) {
 		$cat->set_course_code(null);
-	}
-	else
-	{	
+	}else {	
 		$cat->set_course_code($values['course_code']);
 	}
 	$cat->set_description($values['description']);
@@ -52,20 +47,20 @@ if ($form->validate()) {
 	$cat->set_parent_id($values['hid_parent_id']);
 	$cat->set_weight($values['weight']);
 	$cat->set_certificate_min_score($values['certif_min_score']);
-	if (empty ($values['visible']))
-		$visible = 0;
-	else
-		$visible = 1;
+	if (empty ($values['visible'])) {
+		$visible = 0;		
+	} else {
+		$visible = 1;	
+	}
 	$cat->set_visible($visible);
 	$cat->save();
-	header('Location: gradebook.php?editcat=&selectcat=' . $cat->get_parent_id());
+	header('Location: '.$_SESSION['gradebook_dest'].'?editcat=&selectcat=' . $cat->get_parent_id());
 	exit;
 }
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php?selectcat='.$_GET['selectcat'],
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']),
 	'name' => get_lang('Gradebook'
 ));
 Display :: display_header(get_lang('EditCategory'));
 $form->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 17 - 21
main/gradebook/gradebook_edit_eval.php

@@ -1,12 +1,10 @@
-<?php
-
-
-// $Id: gradebook_edit_eval.php 880 2007-05-07 09:32:52Z bert $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -20,16 +18,16 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/evalform.class.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/evalform.class.php');
 api_block_anonymous_users();
 block_students();
 
@@ -47,22 +45,20 @@ if ($form->validate()) {
 	$eval->set_weight($values['weight']);
 	$eval->set_date(strtotime($values['date']));
 	$eval->set_max($values['max']);
-	if (empty ($values['visible']))
-		$visible = 0;
-	else
-		$visible = 1;
+	if (empty ($values['visible'])) {
+		$visible = 0;	
+	} else {
+		$visible = 1;		
+	}
 	$eval->set_visible($visible);
 	$eval->save();
-	//var_dump($values);
-	//echo 'visible :' . $visible;
-	header('Location: gradebook.php?editeval=&selectcat=' . $eval->get_category_id());
+	header('Location: '.$_SESSION['gradebook_dest'].'?editeval=&selectcat=' . $eval->get_category_id());
 	exit;
 }
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php?selectcat='.$_GET['selectcat'],
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']),
 	'name' => get_lang('Gradebook'
 ));
 Display :: display_header(get_lang('EditEvaluation'));
 $form->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 16 - 13
main/gradebook/gradebook_edit_link.php

@@ -1,5 +1,5 @@
 <?php
-// $Id: gradebook_edit_link.php 400 2007-04-10 13:58:55Z stijn $
+// $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
@@ -22,15 +22,18 @@
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/linkform.class.php');
-include_once ('lib/fe/linkaddeditform.class.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/linkform.class.php');
+require_once ('lib/fe/linkaddeditform.class.php');
 api_block_anonymous_users();
 block_students();
 
+$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD);
+$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+
 $linkarray = LinkFactory :: load($_GET['editlink']);
 $link = $linkarray[0];
 
@@ -42,23 +45,23 @@ $form = new LinkAddEditForm(LinkAddEditForm :: TYPE_EDIT,
 							api_get_self() . '?selectcat=' . $_GET['selectcat']
 												 . '&editlink=' . $_GET['editlink']);
 
-if ($form->validate())
-{
+if ($form->validate()) {
 	$values = $form->exportValues();
 	$link->set_weight($values['weight']);
 	$link->set_date(strtotime($values['date']));
 	$link->set_visible(empty ($values['visible']) ? 0 : 1);
 	$link->save();
-	header('Location: gradebook.php?linkedited=&selectcat=' . $link->get_category_id());
+	$sql_t='UPDATE '.$tbl_forum_thread.' SET thread_weight='.$values['weight'].' WHERE thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' where id='.$_GET['editlink'].' and type=5);';
+	api_sql_query($sql_t);
+	header('Location: '.$_SESSION['gradebook_dest'].'?linkedited=&selectcat=' . $link->get_category_id());
 	exit;
 }
 
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php?selectcat='.$_GET['selectcat'],
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.$_GET['selectcat'],
 	'name' => get_lang('Gradebook'
 ));
 
 Display :: display_header(get_lang('EditLink'));
 $form->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 19 - 18
main/gradebook/gradebook_edit_result.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: gradebook_add_result.php 252 2007-03-29 13:46:31Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,18 +18,18 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/fe/displaygradebook.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/evalform.class.php');
-include_once ('lib/scoredisplay.class.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/evalform.class.php');
+require_once ('lib/scoredisplay.class.php');
 api_block_anonymous_users();
 block_students();
 
@@ -39,21 +39,23 @@ $edit_result_form = new EvalForm(EvalForm :: TYPE_ALL_RESULTS_EDIT, $evaluation[
 if ($edit_result_form->validate()) {
 	$values = $edit_result_form->exportValues();
 	$scores = ($values['score']);
-	foreach ($scores as $row){
+	foreach ($scores as $row) {
 		$resultedit = Result :: load (key($scores));
-		if ((!empty ($row)) || ($row == '0')) $resultedit[0]->set_score($row);
+		if ((!empty ($row)) || ($row == '0')) {
+			$resultedit[0]->set_score($row);
+		}
 		$resultedit[0]->save();
 		next($scores);
 	}
-	header('Location: gradebook_view_result.php?selecteval='.$_GET['selecteval'].'&editallresults=');
+	header('Location: gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'&editallresults=');
 	exit;
 }
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 $interbreadcrumb[]= array (
-	'url' => 'gradebook_view_result.php?selecteval='.$_GET['selecteval'],
+	'url' => 'gradebook_view_result.php?selecteval='.Security::remove_XSS($_GET['selecteval']),
 	'name' => get_lang('ViewResult'
 ));
 Display :: display_header(get_lang('EditResult'));
@@ -61,5 +63,4 @@ DisplayGradebook :: display_header_result ($evaluation[0],null,0,0);
 echo '<div class="main">';
 echo $edit_result_form->toHtml();
 echo '</div>';
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 95 - 67
main/gradebook/gradebook_flatview.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: gradebook_view_result.php 479 2007-04-12 11:50:58Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,79 +18,83 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file= 'gradebook';
-$cidReset= true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/dataform.class.php');
-include_once ('lib/fe/userform.class.php');
-include_once ('lib/flatview_data_generator.class.php');
-include_once ('lib/fe/flatviewtable.class.php');
-include_once ('lib/fe/displaygradebook.php');
-include_once ('lib/fe/exportgradebook.php');
-include_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
-include_once ('lib/scoredisplay.class.php');
+//$cidReset= true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/dataform.class.php');
+require_once ('lib/fe/userform.class.php');
+require_once ('lib/flatview_data_generator.class.php');
+require_once ('lib/fe/flatviewtable.class.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/fe/exportgradebook.php');
+require_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
+require_once ('lib/scoredisplay.class.php');
 api_block_anonymous_users();
 block_students();
 
-
-if (isset ($_POST['submit']) && isset ($_POST['keyword']))
-{
+if (isset ($_POST['submit']) && isset ($_POST['keyword'])) {
 	header('Location: ' . api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
-											   . '&search='.Security::remove_XSS($_POST['keyword']));
+										   . '&search='.Security::remove_XSS($_POST['keyword']));
 	exit;
 }
 
-
 $interbreadcrumb[]= array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 $showeval= (isset ($_POST['showeval']) ? '1' : '0');
 $showlink= (isset ($_POST['showlink']) ? '1' : '0');
-if (($showlink == '0') && ($showeval == '0'))
-{
+if (($showlink == '0') && ($showeval == '0')) {
 	$showlink= '1';
 	$showeval= '1';
 }
-$cat= Category :: load($_GET['selectcat']);
-if ($showeval)
+$cat= Category :: load($_REQUEST['selectcat']);
+
+if ($showeval) {
 	$alleval= $cat[0]->get_evaluations($_GET['userid'], true);
-if ($showlink)
+}
+
+if ($showlink) {
 	$alllinks= $cat[0]->get_links($_GET['userid'], true);
-if (isset ($export_flatview_form) && (!$file_type == 'pdf'))
+}
+
+if (isset ($export_flatview_form) && (!$file_type == 'pdf')) {
 	Display :: display_normal_message($export_flatview_form->toHtml(),false);
+}
+
 $simple_search_form= new UserForm(UserForm :: TYPE_SIMPLE_SEARCH, null, 'simple_search_form', null, api_get_self() . '?selectcat=' . $_GET['selectcat']);
 $values= $simple_search_form->exportValues();
 $keyword = '';
-if (isset($_GET['search']) && !empty($_GET['search']))
+if (isset($_GET['search']) && !empty($_GET['search'])) {
 	$keyword = $_GET['search'];
-if ($simple_search_form->validate() && (empty($keyword)))
+}
+if ($simple_search_form->validate() && (empty($keyword))) {
 	$keyword = $values['keyword'];
+}
+
 
-if (!empty($keyword))
+if (!empty($keyword)) {
 	$users= find_students($keyword);
-else
+} else {
 	$users= get_all_users($alleval, $alllinks);
-
-if (isset ($_GET['exportpdf']))
-{
+}
+if (isset ($_GET['exportpdf']))	{
 	$interbreadcrumb[]= array (
-		'url' => api_get_self().'?selectcat=' . $_GET['selectcat'],
-		'name' => get_lang('FlatView')
-		);
+	'url' => api_get_self().'?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+	'name' => get_lang('FlatView')
+	);
 	$export_pdf_form= new DataForm(DataForm :: TYPE_EXPORT_PDF, 'export_pdf_form', null, api_get_self() . '?exportpdf=&offset='.$_GET['offset'].'&selectcat=' . $_GET['selectcat'],'_blank');
-	if (!$export_pdf_form->validate())
+	if (!$export_pdf_form->validate()) {
 		Display :: display_header(get_lang('ExportPDF'));
-	if ($export_pdf_form->validate())	
-	{
+	}
+	if ($export_pdf_form->validate()) {
 		$printable_data = get_printable_data ($users,$alleval, $alllinks);
-
 		$export= $export_pdf_form->exportValues();
 		$format = $export['orientation'];
 		$pdf =& new Cezpdf('a4',$format); //format is 'portrait' or 'landscape'
@@ -101,53 +105,77 @@ if (isset ($_GET['exportpdf']))
 }
 
 
-if (isset ($_GET['print']))
-{
-	$printable_data = get_printable_data ($users,$alleval, $alllinks);
+if (isset ($_GET['print']))	{
+	$printable_data = get_printable_data ($users,$alleval, $alllinks);	
 	echo print_table($printable_data[1],$printable_data[0], get_lang('FlatView'), $cat[0]->get_name());
 	exit;
 }
 
+if(!empty($_POST['export_report']) && $_POST['export_report'] == 'export_report'){
+	if(api_is_platform_admin() || api_is_course_admin() || api_is_course_coach())	{
+		$user_id = null;
+		
+		if(empty($_SESSION['export_user_fields'])) { 
+			$_SESSION['export_user_fields'] = false;
+		}
+		if(!$is_allowedToEdit and !$is_tutor) {
+			$user_id = api_get_user_id();
+		}
+	
+		require_once('gradebook_result.class.php');	
+		$printable_data = get_printable_data ($users,$alleval, $alllinks);
+		
+		switch($_POST['export_format']) {
+			case 'xls':
+				$export = new GradeBookResult();				
+				$export->exportCompleteReportXLS($printable_data );
+				exit;
+				break;
+			case 'csv':
+			default:
+				$export = new GradeBookResult();
+				$export->exportCompleteReportCSV($printable_data);
+				exit;
+				break;
+		}
+	} else {
+		api_not_allowed(true);
+	}
+}
 
 $addparams= array ('selectcat' => $cat[0]->get_id());
-if (isset($_GET['search']))
+if (isset($_GET['search'])) {
 	$addparams['search'] = $keyword;
-
-
+}
 $offset = (isset($_GET['offset'])?$_GET['offset']:'0');
+
 $flatviewtable= new FlatViewTable($cat[0], $users, $alleval, $alllinks, true, $offset, $addparams);
-	
-if (isset($_GET['exportpdf']))
-{
+
+if (isset($_GET['exportpdf'])) {
 	echo '<div class="normal-message">';
 	$export_pdf_form->display();
 	echo '</div>';
-}
-else
+} else {
 	Display :: display_header(get_lang('FlatView'));
-
-DisplayGradebook :: display_header_flatview($cat[0], $showeval, $showlink, $simple_search_form);
+}
+DisplayGradebook :: display_header_reduce_flatview($cat[0], $showeval, $showlink, $simple_search_form);
 $flatviewtable->display();
 Display :: display_footer();
 
-
-function get_printable_data ($users,$alleval, $alllinks)
-{
+function get_printable_data($users,$alleval, $alllinks) {
 	$datagen = new FlatViewDataGenerator ($users,$alleval, $alllinks);
 
 	$offset = (isset($_GET['offset'])?$_GET['offset']:'0');
 
-   	$count = (($offset+10) > $datagen->get_total_items_count()) ?
-      		 ($datagen->get_total_items_count()-$offset) : 10;
+	$count = (($offset+10) > $datagen->get_total_items_count()) ?
+  		 	 ($datagen->get_total_items_count()-$offset) : 10;
 
 	$header_names = $datagen->get_header_names($offset,$count);
 	$data_array = $datagen->get_data(FlatViewDataGenerator :: FVDG_SORT_LASTNAME,0,null,$offset,$count,true);	
-	
+
 	$newarray = array();
-	foreach ($data_array as $data)
-		$newarray[] = array_slice($data, 1);
-	
+	foreach ($data_array as $data) {
+		$newarray[] = array_slice($data, 1);		
+	}
 	return array ($header_names, $newarray);
-}
-
-?>
+}

+ 291 - 0
main/gradebook/gradebook_result.class.php

@@ -0,0 +1,291 @@
+<?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:
+		Dokeos
+		Rue du Corbeau, 108
+		B-1030 Brussels - Belgium
+		info@dokeos.com
+*/
+/**
+*	ExerciseResult class: This class allows to instantiate an object of type ExerciseResult
+*	which allows you to export exercises results in multiple presentation forms
+*	@package dokeos.exercise
+* 	@author Yannick Warnier
+* 	@version $Id: $
+*/
+
+
+if(!class_exists('GradeBookResult')):
+
+class GradeBookResult
+{
+	private $gradebook_list = array(); //stores the list of exercises
+	private $results = array(); //stores the results
+	
+	/**
+	 * constructor of the class
+	 */
+	public function GradeBookResult($get_questions=false,$get_answers=false) {
+		//nothing to do
+		/*
+		$this->exercise_list = array();
+		$this->readExercisesList();
+		if($get_questions)
+		{
+			foreach($this->exercises_list as $exe)
+			{
+				$this->exercises_list['questions'] = $this->getExerciseQuestionList($exe['id']);
+			}
+		}
+		*/
+	}
+
+	/**
+	 * Reads exercises information (minimal) from the data base
+	 * @param	boolean		Whether to get only visible exercises (true) or all of them (false). Defaults to false.
+	 * @return	array		A list of exercises available
+	 */
+	private function _readGradebookList($only_visible = false) {
+		$return = array();
+    	$TBL_EXERCISES          = Database::get_course_table(TABLE_QUIZ_TEST);
+
+		$sql="SELECT id,title,type,random,active FROM $TBL_EXERCISES";
+		if($only_visible) {
+			$sql.= ' WHERE active=1';
+		}
+		$sql .= ' ORDER BY title';
+		$result=api_sql_query($sql,__FILE__,__LINE__);
+
+		// if the exercise has been found
+		while($row=Database::fetch_array($result,'ASSOC')) {
+			$return[] = $row;
+		}
+		// exercise not found
+		return $return;
+	}
+
+	/**
+	 * Gets the questions related to one exercise
+	 * @param	integer		Exercise ID
+	 */
+	private function _readGradeBookQuestionsList($e_id) {
+		$return = array();
+    	$TBL_EXERCISE_QUESTION  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
+    	$TBL_QUESTIONS = Database::get_course_table(TABLE_QUIZ_QUESTION);
+		$sql="SELECT q.id, q.question, q.ponderation, q.position, q.type, q.picture " .
+			" FROM $TBL_EXERCISE_QUESTION eq, $TBL_QUESTIONS q " .
+			" WHERE eq.question_id=q.id AND eq.exercice_id='$e_id' " .
+			" ORDER BY q.position";
+		$result=api_sql_query($sql,__FILE__,__LINE__);
+
+		// fills the array with the question ID for this exercise
+		// the key of the array is the question position
+		while($row=Database::fetch_array($result,'ASSOC')) {
+			$return[] = $row;
+		}
+		return true;		
+	}
+	/**
+	 * Gets the results of all students (or just one student if access is limited)
+	 * @param	string		The document path (for HotPotatoes retrieval)
+	 * @param	integer		User ID. Optional. If no user ID is provided, we take all the results. Defauts to null
+	 */
+	function _getGradeBookReporting($document_path,$user_id=null) {
+		$return = array();
+    	$TBL_EXERCISES          = Database::get_course_table(TABLE_QUIZ_TEST);
+    	$TBL_EXERCISE_QUESTION  = Database::get_course_table(TABLE_QUIZ_TEST_QUESTION);
+    	$TBL_QUESTIONS 			= Database::get_course_table(TABLE_QUIZ_QUESTION);
+		$TBL_USER          	    = Database::get_main_table(TABLE_MAIN_USER);
+		$TBL_DOCUMENT          	= Database::get_course_table(TABLE_DOCUMENT);
+		$TBL_ITEM_PROPERTY      = Database::get_course_table(TABLE_ITEM_PROPERTY);
+		$TBL_TRACK_EXERCISES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
+		$TBL_TRACK_HOTPOTATOES	= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_HOTPOTATOES);
+		$TBL_TRACK_ATTEMPT		= Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_ATTEMPT);
+
+    	$cid = api_get_course_id();
+		if (empty($user_id)) {
+			//get all results (ourself and the others) as an admin should see them
+			//AND exe_user_id <> $_user['user_id']  clause has been removed
+			$sql="SELECT CONCAT(lastname,' ',firstname),ce.title, te.exe_result ,
+						te.exe_weighting, UNIX_TIMESTAMP(te.exe_date),te.exe_id, user.email, user.user_id
+				  FROM $TBL_EXERCISES ce , $TBL_TRACK_EXERCISES te, $TBL_USER user
+				  WHERE te.exe_exo_id = ce.id AND user_id=te.exe_user_id AND te.exe_cours_id='$cid'
+				  ORDER BY te.exe_cours_id ASC, ce.title ASC, te.exe_date ASC";
+
+			$hpsql="SELECT CONCAT(tu.lastname,' ',tu.firstname), tth.exe_name,
+						tth.exe_result , tth.exe_weighting, UNIX_TIMESTAMP(tth.exe_date), tu.email, tu.user_id
+					FROM $TBL_TRACK_HOTPOTATOES tth, $TBL_USER tu
+					WHERE  tu.user_id=tth.exe_user_id AND tth.exe_cours_id = '".$cid."'
+					ORDER BY tth.exe_cours_id ASC, tth.exe_date ASC";
+
+		} else { // get only this user's results
+			  $sql="SELECT '',ce.title, te.exe_result , te.exe_weighting, " .
+			  		"UNIX_TIMESTAMP(te.exe_date),te.exe_id
+				  FROM $TBL_EXERCISES ce , $TBL_TRACK_EXERCISES te
+				  WHERE te.exe_exo_id = ce.id AND te.exe_user_id='".$user_id."' AND te.exe_cours_id='$cid'
+				  ORDER BY te.exe_cours_id ASC, ce.title ASC, te.exe_date ASC";
+
+			$hpsql="SELECT '',exe_name, exe_result , exe_weighting, UNIX_TIMESTAMP(exe_date)
+					FROM $TBL_TRACK_HOTPOTATOES
+					WHERE exe_user_id = '".$user_id."' AND exe_cours_id = '".$cid."'
+					ORDER BY exe_cours_id ASC, exe_date ASC";
+
+		}
+
+		$results=getManyResultsXCol($sql,8);
+		$hpresults=getManyResultsXCol($hpsql,7);
+
+		$NoTestRes = 0;
+		$NoHPTestRes = 0;
+		$j=0;
+		//Print the results of tests
+		if (is_array($results)) {
+			for ($i = 0; $i < sizeof($results); $i++) {
+				$return[$i] = array();
+				$id = $results[$i][5];
+				$mailid = $results[$i][6];
+				$user = $results[$i][0];
+				$test = $results[$i][1];
+				$dt = strftime(get_lang('dateTimeFormatLong'),$results[$i][4]);
+				$res = $results[$i][2];
+				if(empty($user_id)) {
+					$user = $results[$i][0];
+					$return[$i]['user'] = $user;
+					$return[$i]['user_id'] = $results[$i][7];
+				}
+				$return[$i]['title'] = $test;
+				$return[$i]['time'] = format_locale_date(get_lang('dateTimeFormatLong'),$results[$i][4]);
+				$return[$i]['result'] = $res;
+				$return[$i]['max'] = $results[$i][3];
+				$j=$i;
+			}
+		}
+		$j++;
+		// Print the Result of Hotpotatoes Tests
+		if (is_array($hpresults)) {
+			for ($i = 0; $i < sizeof($hpresults); $i++) {
+				$return[$j+$i] = array();
+				$title = GetQuizName($hpresults[$i][1],$document_path);
+				if ($title =='') {
+					$title = GetFileName($hpresults[$i][1]);
+				}
+				if (empty($user_id)) {
+					$return[$j+$i]['user'] = $hpresults[$i][0];
+					$return[$j+$i]['user_id'] = $results[$i][6];
+					
+				}
+				$return[$j+$i]['title'] = $title;
+				$return[$j+$i]['time'] = strftime(get_lang('dateTimeFormatLong'),$hpresults[$i][4]);
+				$return[$j+$i]['result'] = $hpresults[$i][2];
+				$return[$j+$i]['max'] = $hpresults[$i][3];
+			}
+		}
+		$this->results = $return;
+		return true;
+	}
+	/**
+	 * Exports the complete report as a CSV file
+	 * @param	string		Document path inside the document tool
+	 * @param	integer		Optional user ID
+	 * @param	boolean		Whether to include user fields or not
+	 * @return	boolean		False on error
+	 */
+	public function exportCompleteReportCSV($dato) {
+		//$this->_getGradeBookReporting($document_path,$user_id);
+		$filename = 'gradebook_results_'.date('YmdGis').'.csv';
+		if (!empty($user_id)) {
+			$filename = 'gradebook_results_user_'.$user_id.'_'.date('YmdGis').'.csv';
+		}
+		$data = '';
+		//build the results
+		//titles
+	
+		foreach ($dato[0] as $header_col) {
+			if(!empty($header_col)) {
+				$data .= str_replace("\r\n",'  ',html_entity_decode(strip_tags($header_col))).';';
+			}			
+		}
+		
+		$data .="\r\n";
+		$cant_students = count($dato[1]);
+		//print_r($data);		exit();
+		
+		for($i=0;$i<$cant_students;$i++) {
+			$column = 0;
+			foreach($dato[1][$i] as $col_name) {	
+				$data .= str_replace("\r\n",'  ',html_entity_decode(strip_tags($col_name))).';';					
+			}
+			$data .="\r\n";
+		}
+		
+		//output the results
+		$len = strlen($data);
+		header('Content-type: application/octet-stream');
+		header('Content-Type: application/force-download');
+		header('Content-length: '.$len);
+		if (preg_match("/MSIE 5.5/", $_SERVER['HTTP_USER_AGENT'])) {
+			header('Content-Disposition: filename= '.$filename);
+		} else {
+			header('Content-Disposition: attachment; filename= '.$filename);
+		} if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE')) {
+			header('Pragma: ');
+			header('Cache-Control: ');
+			header('Cache-Control: public'); // IE cannot download from sessions without a cache
+		}
+		header('Content-Description: '.$filename);
+		header('Content-transfer-encoding: binary');
+		echo $data;
+		return true;
+	}
+	/**
+	 * Exports the complete report as an XLS file
+	 * @return	boolean		False on error
+	 */
+	public function exportCompleteReportXLS($data) {
+	   	$filename = 'gradebook_results_user_'.date('YmdGis').'.xls';
+		//build the results
+		require_once(api_get_path(LIBRARY_PATH).'pear/Spreadsheet_Excel_Writer/Writer.php');
+		$workbook = new Spreadsheet_Excel_Writer();
+		$workbook->send($filename);
+		$worksheet =& $workbook->addWorksheet('Report '.date('YmdGis'));
+		$line = 0;
+		$column = 0; //skip the first column (row titles)
+		//headers			
+		foreach ($data[0] as $header_col) {
+			$worksheet->write($line,$column,$header_col);
+			$column++;
+		}
+		//$worksheet->write($line,$column,get_lang('Total'));
+		//$column++;		
+		$line++;	
+		
+		$cant_students = count($data[1]);
+		//print_r($data);		exit();
+		
+		for ($i=0;$i<$cant_students;$i++) {
+			$column = 0;
+			foreach ($data[1][$i] as $col_name) {		
+				$worksheet->write($line,$column,$col_name);
+				$column++;
+				
+			}
+			$line++;
+		}
+		//output the results
+		$workbook->close();
+		return true;
+	}
+}
+
+endif;
+?>

+ 44 - 45
main/gradebook/gradebook_scoring_system.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: gradebook_view_result.php 725 2007-04-24 07:27:11Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,17 +18,17 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file= 'gradebook';
-$cidReset= true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/scoredisplayform.class.php');
-include_once ('lib/scoredisplay.class.php');
+//$cidReset= true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/scoredisplayform.class.php');
+require_once ('lib/scoredisplay.class.php');
 api_block_anonymous_users();
 api_protect_admin_script();
 
@@ -65,73 +65,72 @@ $htmlHeadXtra[]= '
  </script>';
 
 $interbreadcrumb[]= array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 $displayscore= ScoreDisplay :: instance();
 $customdisplays = $displayscore->get_custom_score_display_settings();
 $nr_items =(count($customdisplays)!='0')?count($customdisplays):'1';
-	
+
 $scoreform= new ScoreDisplayForm('scoring_system_form',
-								 api_get_self() . '?selectcat=' . $_GET['selectcat']
-								 );
-if ($scoreform->validate())
-{
+							 api_get_self() . '?selectcat=' . $_GET['selectcat']
+							 );
+if ($scoreform->validate()) {
 	$values= $scoreform->exportValues();
 
 
-	// create new array of custom display settings
-	// this loop also checks if all score ranges are unique
-	
+// create new array of custom display settings
+// this loop also checks if all score ranges are unique
+
 	$scoringdisplay= array ();
 	$ranges_ok = true;
 	$endscore= $values['endscore'];
 	$displaytext= $values['displaytext'];
-	for ($counter= 1; $ranges_ok && $counter <= 20; $counter++)
-	{
-		$setting= array ();
-		$setting['score']= $endscore[$counter];
-		$setting['display']= $displaytext[$counter];
-		if (!empty($setting['score']))
-		{
-			foreach ($scoringdisplay as $passed_entry)
-			{
-				if ($passed_entry['score'] == $setting['score'])
-					$ranges_ok = false;
-			}
+	for ($counter= 1; $ranges_ok && $counter <= 20; $counter++) {
+			$setting= array ();
+			$setting['score']= $endscore[$counter];
+			$setting['display']= $displaytext[$counter];
+			if (!empty($setting['score'])) {
+				foreach ($scoringdisplay as $passed_entry) {
+					if ($passed_entry['score'] == $setting['score']) {
+						$ranges_ok = false;	
+					}
+				}
 			$scoringdisplay[]= $setting;
+			}
 		}
-	}
 
-	if (!$ranges_ok)
-	{
-		header('Location: ' . api_get_self() . '?nouniqueranges=&selectcat=' . $_GET['selectcat']);
+	if (!$ranges_ok) {
+		header('Location: ' . api_get_self() . '?nouniqueranges=&selectcat=' . Security::remove_XSS($_GET['selectcat']));
 		exit;
 	}
 
 
 	// update color settings
 	$displayscore->set_coloring_enabled(($values['enablescorecolor'] == '1') ? true : false);
-	if ($displayscore->is_coloring_enabled())
-		$displayscore->set_color_split_value($values['scorecolpercent']);
-
+	if ($displayscore->is_coloring_enabled()) {
+		$displayscore->set_color_split_value($values['scorecolpercent']);	
+	}
 	// update custom display settings
 	$displayscore->set_custom(($values['enablescore'] == '1') ? true : false);
 	$displayscore->set_upperlimit_included(($values['includeupperlimit'] == '1') ? true : false);
-	if ($displayscore->is_custom() && !empty($scoringdisplay))
+	if ($displayscore->is_custom() && !empty($scoringdisplay)) {
 		$displayscore->update_custom_score_display_settings($scoringdisplay);
-
-	header('Location: ' . api_get_self() . '?scoringupdated=&selectcat=' . $_GET['selectcat']);
+	}
+	header('Location: ' . api_get_self() . '?scoringupdated=&selectcat=' . Security::remove_XSS($_GET['selectcat']));
 	exit;
 }
 
 Display :: display_header(get_lang('ScoreEdit'));
-if (isset ($_GET['scoringupdated']))
+if (isset ($_GET['scoringupdated'])) {
 	Display :: display_confirmation_message(get_lang('ScoringUpdated'),false);
-if (isset ($_GET['nouniqueranges']))
+}
+
+if (isset ($_GET['nouniqueranges'])) {
 	Display :: display_error_message(get_lang('NoUniqueScoreRanges'),false);
+}
+
 echo '<div class="maincontent">';
 $scoreform->display();
 echo '</div>';
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 71 - 0
main/gradebook/gradebook_showlog_eval.php

@@ -0,0 +1,71 @@
+<?php // $Id: $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+$language_file = 'gradebook';
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/evalform.class.php');
+api_block_anonymous_users();
+block_students();
+
+$interbreadcrumb[] = array (
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']),
+	'name' => get_lang('Gradebook'
+));
+Display :: display_header();
+$t_linkeval_log = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);
+$t_user=	 Database :: get_main_table(TABLE_MAIN_USER);
+$evaledit = Evaluation :: load($_GET['visiblelog']);
+$sql="SELECT le.name,le.description,le.date_log,le.weight,le.visible,le.type,us.username from ".$t_linkeval_log." le inner join ".$t_user." us on le.user_id_log=us.user_id where id_linkeval_log=".$evaledit[0]->get_id()." and type='evaluation';";
+$result=api_sql_query($sql);
+	echo '<table width="100%" border="0" >';
+		echo '<tr>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('GradebookNameLog').'</strong></td>';
+		echo '<td align="center" class="Gradebook-table-header"><strong>'.get_lang('GradebookDescriptionLog').'</strong></td>';
+		echo '<td align="center" class="Gradebook-table-header"><strong>'.get_lang('Date').'</strong></td>';
+		echo '<td align="center" class="Gradebook-table-header"><strong>'.get_lang('Weight').'</strong></td>';
+		echo '<td align="center" class="Gradebook-table-header"><strong>'.get_lang('GradebookVisibilityLog').'</strong></td>';
+		echo '<td align="center" class="Gradebook-table-header"><strong>'.get_lang('ResourceType').'</strong></td>';
+		echo '<td align="center" class="Gradebook-table-header"><strong>'.get_lang('GradebookWhoChangedItLog').'</strong></td>';
+		echo '</tr>';
+	while($row=Database::fetch_array($result)) {
+	echo '<tr>';
+		echo '<td align="center" Class="Gradebook-table-body">'.$row[0].'</td>';
+		echo '<td align="center" class="Gradebook-table-body">'.$row[1].'</td>';
+		echo '<td align="center" class="Gradebook-table-body">'.date('d-m-Y H:i:s',$row[2]).'</td>';
+		echo '<td align="center" class="Gradebook-table-body">'.$row[3].'</td>';
+		if (1 == $row[4]) {
+			$visib=get_lang('GradebookVisible');
+		} else {
+			$visib=get_lang('GradebookInvisible');
+		}
+		echo '<td align="center" Class="Gradebook-table-body">'.$visib.'</td>';
+		echo '<td align="center" class="Gradebook-table-body">'.$row[5].'</td>';
+		echo '<td align="center" class="Gradebook-table-body">'.$row[6].'</td>';
+	echo '</tr>';
+}
+echo '</table>';
+Display :: display_footer();

+ 73 - 0
main/gradebook/gradebook_showlog_link.php

@@ -0,0 +1,73 @@
+<?php // $Id: $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+$language_file = 'gradebook';
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/evalform.class.php');
+api_block_anonymous_users();
+block_students();
+
+$interbreadcrumb[] = array (
+	'url' => $_SESSION['gradebook_dest'].'?selectcat='.Security::remove_XSS($_GET['selectcat']),
+	'name' => get_lang('Gradebook'
+));
+
+Display :: display_header();
+$t_user=	 Database :: get_main_table(TABLE_MAIN_USER);
+$t_link_log = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);	
+$evaledit = EvalLink :: load($_GET['visiblelink']);
+
+$sql="SELECT lk.name,lk.description,lk.date_log,lk.weight,lk.visible,lk.type,us.username from ".$t_link_log." lk inner join ".$t_user." us on lk.user_id_log=us.user_id where lk.id_linkeval_log=".$evaledit[0]->get_id()." and lk.type='link';";
+$result=api_sql_query($sql);
+echo '<table width="100%" border="0" >';
+	echo '<tr>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('GradebookNameLog').'</strong></td>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('GradebookDescriptionLog').'</strong></td>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('Date').'</strong></td>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('Weight').'</strong></td>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('GradebookVisibilityLog').'</strong></td>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('ResourceType').'</strong></td>';
+		echo '<td align="center" style="Gradebook-table-header"><strong>'.get_lang('GradebookWhoChangedItLog').'</strong></td>';
+echo '</tr>';
+while($row=Database::fetch_array($result)){
+echo '<tr>';
+		echo '<td align="center" Class="Gradebook-table-body">'.$row[0].'</td>';
+		echo '<td align="center" Class="Gradebook-table-body">'.$row[1].'</td>';
+		echo '<td align="center" Class="Gradebook-table-body">'.date('d-m-Y H:i:s',$row[2]).'</td>';
+		echo '<td align="center" Class="Gradebook-table-body">'.$row[3].'</td>';
+		if (1 == $row[4]) {
+			$visib=get_lang('GradebookVisible');
+		} else {
+			$visib=get_lang('GradebookInvisible');
+		}
+		echo '<td align="center" Class="Gradebook-table-body">'.$visib.'</td>';
+		echo '<td align="center" Class="Gradebook-table-body">'.$row[5].'</td>';
+		echo '<td align="center" Class="Gradebook-table-body">'.$row[6].'</td>';
+		echo '</tr>';
+}
+echo '</table>';
+Display :: display_footer();

+ 34 - 47
main/gradebook/gradebook_statistics.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: gradebook_view_result.php 725 2007-04-24 07:27:11Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,36 +18,36 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file= 'gradebook';
-$cidReset= true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/dataform.class.php');
-include_once ('lib/scoredisplay.class.php');
-include_once ('lib/fe/displaygradebook.php');
+//$cidReset= true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/dataform.class.php');
+require_once ('lib/scoredisplay.class.php');
+require_once ('lib/fe/displaygradebook.php');
 api_block_anonymous_users();
 $eval= Evaluation :: load($_GET['selecteval']);
-if ($eval[0]->get_category_id() < 0)
-{
+if ($eval[0]->get_category_id() < 0) {
 	// if category id is negative, then the evaluation's origin is a link
 	$link= LinkFactory :: get_evaluation_link($eval[0]->get_id());
 	$currentcat= Category :: load($link->get_category_id());
-} else
+} else {
 	$currentcat= Category :: load($eval[0]->get_category_id());
-	
+}
+
+
 $interbreadcrumb[]= array (
-'url' => 'gradebook.php?selectcat=' . $currentcat[0]->get_id(), 'name' => get_lang('Gradebook'));
+	'url' => $_SESSION['gradebook_dest'].'?selectcat=' . $currentcat[0]->get_id(), 'name' => get_lang('Gradebook'));
 
-if (api_is_allowed_to_create_course())
-{
+if (api_is_allowed_to_create_course()){
 	$interbreadcrumb[]= array (
-		'url' => 'gradebook_view_result.php?selecteval=' . $_GET['selecteval'],
-		'name' => get_lang('ViewResult'
+	'url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']),
+	'name' => get_lang('ViewResult'
 	));
 }
 $displayscore= ScoreDisplay :: instance();
@@ -57,42 +57,34 @@ DisplayGradebook :: display_header_result($eval[0], $currentcat[0]->get_id(), 0,
 
 
 
-if (!$displayscore->is_custom())
+if (!$displayscore->is_custom()) {
 	Display :: display_error_message(get_lang('PleaseEnableScoringSystem'),false);
-else
-{
-	// generate data
-	
+} else {
 	$displays= $displayscore->get_custom_score_display_settings();
 	$allresults = Result :: load(null,null,$eval[0]->get_id());
 	$nr_items = array();
-	foreach ($displays as $itemsdisplay)
-		$nr_items[$itemsdisplay['display']] = 0;
-	
+	foreach ($displays as $itemsdisplay) {
+		$nr_items[$itemsdisplay['display']] = 0;		
+	}
 	$resultcount = 0;
-	foreach ($allresults as $result)
-	{	
+	foreach ($allresults as $result) {	
 		$score = $result->get_score();
-		if (isset($score))
-		{
+		if (isset($score)) {
 			$display = $displayscore->display_score(array($score, $eval[0]->get_max()),SCORE_DIV | SCORE_IGNORE_SPLIT, SCORE_ONLY_CUSTOM);
 			$nr_items[$display] ++;
 			$resultcount ++;
 		}
 	}
-	
-	
-	
+
 	$keys = array_keys($nr_items);
 
-	
 	// find the region with the most scores, this is 100% of the bar
 
 	$highest_ratio = 0;
-	foreach ($keys as $key)
-	{
-		if ($nr_items[$key] > $highest_ratio)
-			$highest_ratio = $nr_items[$key];
+	foreach ($keys as $key) {
+		if ($nr_items[$key] > $highest_ratio){
+		$highest_ratio = $nr_items[$key];		
+		}
 	}
 
 
@@ -102,14 +94,10 @@ else
 	$stattable .= '<tr><th colspan="4">' . get_lang('Statistics') . '</th></tr>';
 
 	$counter=0;
-	foreach ($keys as $key)
-	{
-		//var_dump ($key);
+	foreach ($keys as $key) {
 		$bar = ($nr_items[$key] / $highest_ratio) * 100;
-
 		$stattable .= '<tr class="row_' . ($counter % 2 == 0 ? 'odd' : 'even') . '">';
 		$stattable .= '<td width="150">' . $key . '</td>';
-		
 		$stattable .= '<td width="550"><img src="../img/bar_1u.gif" width="' . $bar . '%" height="10"/></td>';
 		$stattable .= '<td align="right">' . $nr_items[$key] . '</td>';
 		$stattable .= '<td align="right"> ' . round( ($nr_items[$key] / $resultcount) * 100 ) . '%</td>';
@@ -118,5 +106,4 @@ else
 	$stattable .= '</tr></table>';
 	echo $stattable;
 }
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 324 - 341
main/gradebook/gradebook_view_result.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: gradebook_view_result.php 1020 2007-05-11 08:20:27Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,114 +18,104 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file[] = 'gradebook';
-$cidReset= true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/displaygradebook.php');
-include_once ('lib/fe/evalform.class.php');
-include_once ('lib/fe/dataform.class.php');
-include_once (api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
-include_once (api_get_path(LIBRARY_PATH) . 'export.lib.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'import.lib.php');
-include_once ('lib/results_data_generator.class.php');
-include_once ('lib/fe/resulttable.class.php');
-include_once ('lib/fe/exportgradebook.php');
-include_once ('lib/scoredisplay.class.php');
-include_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
+//$cidReset= true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/fe/evalform.class.php');
+require_once ('lib/fe/dataform.class.php');
+require_once (api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
+require_once (api_get_path(LIBRARY_PATH) . 'export.lib.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'import.lib.php');
+require_once ('lib/results_data_generator.class.php');
+require_once ('lib/fe/resulttable.class.php');
+require_once ('lib/fe/exportgradebook.php');
+require_once ('lib/scoredisplay.class.php');
+require_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
 api_block_anonymous_users();
 block_students();
 $interbreadcrumb[]= array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 //load the evaluation & category
 $displayscore = Scoredisplay :: instance();
 $eval= Evaluation :: load($_GET['selecteval']);
 $overwritescore= 0;
-if ($eval[0]->get_category_id() < 0)
-{
+if ($eval[0]->get_category_id() < 0) {
 	// if category id is negative, then the evaluation's origin is a link
 	$link= LinkFactory :: get_evaluation_link($eval[0]->get_id());
 	$currentcat= Category :: load($link->get_category_id());
 } else
 	$currentcat= Category :: load($eval[0]->get_category_id());
-//load the result with the evaluation id
-function overwritescore($resid, $importscore, $eval_max)
-{
+	//load the result with the evaluation id
+function overwritescore($resid, $importscore, $eval_max) {
 	$result= Result :: load($resid);
-	if ($importscore > $eval_max)
-	{
-		header('Location: gradebook_view_result.php?selecteval=' . $_GET['selecteval'] . '&overwritemax=');
+	if ($importscore > $eval_max) {
+		header('Location: gradebook_view_result.php?selecteval=' .Security::remove_XSS($_GET['selecteval']) . '&overwritemax=');
 		exit;
 	}
 	$result[0]->set_score($importscore);
 	$result[0]->save();
 	unset ($result);
 }
-if (isset ($_GET['selecteval']))
-{
+if (isset ($_GET['selecteval'])) {
 	$allresults= Result :: load(null, null, $_GET['selecteval']);
 	$iscourse= $currentcat[0]->get_course_code() == null ? 1 : 0;
 }
 /**
  * XML-parser: handle start of element
  */
-function element_start($parser, $data)
-{
-	global $user;
-	global $current_tag;
-	switch ($data)
-	{
-		case 'Result' :
-			$user= array ();
-			break;
-		default :
-			$current_tag= $data;
+function element_start($parser, $data) {
+global $user;
+global $current_tag;
+	switch ($data) {
+	case 'Result' :
+		$user= array ();
+		break;
+	default :
+		$current_tag= $data;
 	}
 }
 /**
  * XML-parser: handle end of element
  */
-function element_end($parser, $data)
-{
-	global $user;
-	global $users;
-	global $current_value;
-	switch ($data)
-	{
-		case 'Result' :
-			$users[]= $user;
-			break;
-		default :
-			$user[$data]= $current_value;
-			break;
+function element_end($parser, $data) {
+global $user;
+global $users;
+global $current_value;
+	switch ($data) {
+	case 'Result' :
+		$users[]= $user;
+		break;
+	default :
+		$user[$data]= $current_value;
+		break;
 	}
 }
 /**
  * XML-parser: handle character data
  */
-function character_data($parser, $data)
-{
-	global $current_value;
-	$current_value= $data;
+function character_data($parser, $data) {
+global $current_value;
+$current_value= $data;
 }
 /**
  * Read the XML-file
  * @param string $file Path to the XML-file
  * @return array All userinformation read from the file
  */
-function parse_xml_data($file)
-{
-	global $current_tag;
-	global $current_value;
-	global $user;
-	global $users;
+function parse_xml_data($file) {
+global $current_tag;
+global $current_value;
+global $user;
+global $users;
 	$users= array ();
 	$parser= xml_parser_create();
 	xml_set_element_handler($parser, 'element_start', 'element_end');
@@ -135,373 +125,366 @@ function parse_xml_data($file)
 	xml_parser_free($parser);
 	return $users;
 }
-if (isset ($_GET['editres']))
-{
+if (isset ($_GET['editres'])) {
 	$resultedit= Result :: load($_GET['editres']);
 	$edit_res_form= new EvalForm(EvalForm :: TYPE_RESULT_EDIT, $eval[0], $resultedit[0], 'edit_result_form', null, api_get_self() . '?editres=' . $resultedit[0]->get_id() . '&selecteval=' . $_GET['selecteval']);
-	if ($edit_res_form->validate())
-	{
+	if ($edit_res_form->validate()) {
+	
 		$values= $edit_res_form->exportValues();
 		$result= new Result();
+		$resultlog=new Result();
+		$resultlog->add_result__log($values['hid_user_id'],$_GET['selecteval']);
 		$result->set_id($_GET['editres']);
 		$result->set_user_id($values['hid_user_id']);
 		$result->set_evaluation_id($_GET['selecteval']);
-		if ((!empty ($values['score'])) || ($values['score'] == '0'))
-			$result->set_score($values['score']);
+	if ((!empty ($values['score'])) || ($values['score'] == '0')) {
+		$result->set_score($values['score']);		
+	}
 		$result->save();
 		unset ($result);
-		header('Location: gradebook_view_result.php?selecteval=' . $_GET['selecteval'] . '&editresmessage=');
+		header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&editresmessage=');
 		exit;
 	}
 }
-if (isset ($_GET['import']))
-{
-	$interbreadcrumb[]= array (
-		'url' => 'gradebook_view_result.php?selecteval=' . $_GET['selecteval'],
-		'name' => get_lang('ViewResult'
-	));
-	$import_result_form = new DataForm(DataForm :: TYPE_IMPORT, 'import_result_form', null, api_get_self() . '?import=&selecteval=' . $_GET['selecteval']);
-	if (!$import_result_form->validate())
-		Display :: display_header(get_lang('Import'));
-	if ($_POST['formSent'])
-	{
-		if (!empty ($_FILES['import_file']['name']))
-		{
-			$values= $import_result_form->exportValues();
-			$file_type= $_POST['file_type'];
-			$file_name= $_FILES['import_file']['tmp_name'];
-			if ($file_type == 'csv')
-			{
-				$results= Import :: csv_to_array($file_name);
-			} else
-			{
-				$results= parse_xml_data($file_name);
-			}
-			//var_dump($results);
-			$nr_results_added= 0;
-			foreach ($results as $index => $importedresult)
-			{
-				//check username & score
-				$added= '0';
-				foreach ($allresults as $allresult)
-				{
-					if (($importedresult['user_id'] == $allresult->get_user_id()))
-					{
-						if ($importedresult['score'] != $allresult->get_score())
-						{
-							if (!isset ($values['overwrite']))
-							{
-								header('Location: gradebook_view_result.php?selecteval=' . $_GET['selecteval'] . '&import_score_error=' . $importedresult['user_id']);
-								exit;
-								break;
-							} else
-							{
-								overwritescore($allresult->get_id(), $importedresult['score'], $eval[0]->get_max());
-								$overwritescore++;
-								$added= '1';
-							}
-						} else
+if (isset ($_GET['import'])) {
+$interbreadcrumb[]= array (
+	'url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']),
+	'name' => get_lang('ViewResult'
+));
+$import_result_form = new DataForm(DataForm :: TYPE_IMPORT, 'import_result_form', null, api_get_self() . '?import=&selecteval=' . $_GET['selecteval']);
+if (!$import_result_form->validate()) {
+	Display :: display_header(get_lang('Import'));	
+}
+
+if ($_POST['formSent'] ) {
+	if (!empty ($_FILES['import_file']['name'])) {
+		$values= $import_result_form->exportValues();
+		$file_type= $_POST['file_type'];
+		$file_name= $_FILES['import_file']['tmp_name'];
+		if ($file_type == 'csv') {
+			$results= Import :: csv_to_array($file_name);
+		} else {
+			$results= parse_xml_data($file_name);
+		}
+		$nr_results_added= 0;
+		foreach ($results as $index => $importedresult) {
+			//check username & score
+			$added= '0';
+			foreach ($allresults as $allresult) {
+				if (($importedresult['user_id'] == $allresult->get_user_id())) {
+					if ($importedresult['score'] != $allresult->get_score()) {
+						if (!isset ($values['overwrite'])) {
+							header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&import_score_error=' . $importedresult['user_id']);
+							exit;
+							break;
+						} else {
+							overwritescore($allresult->get_id(), $importedresult['score'], $eval[0]->get_max());
+							$overwritescore++;
 							$added= '1';
+						}
+					} else {
+						$added= '1';
 					}
+						
 				}
-				if ($importedresult['user_id'] == null)
-				{
-					header('Location: gradebook_view_result.php?selecteval=' . $_GET['selecteval'] . '&incorrectdata=');
+			}
+			if ($importedresult['user_id'] == null) {
+				header('Location: gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&incorrectdata=');
+				exit;
+			}
+			$userinfo= get_user_info_from_id($importedresult['user_id']);
+			if ($userinfo['lastname'] != $importedresult['lastname'] || $userinfo['firstname'] != $importedresult['firstname'] || $userinfo['official_code'] != $importedresult['official_code']) {
+				if (!isset ($values['ignoreerrors'])) {
+					header('Location: gradebook_view_result.php?selecteval=' .Security::remove_XSS($_GET['selecteval']) . '&import_user_error=' . $importedresult['user_id']);
 					exit;
 				}
-				$userinfo= get_user_info_from_id($importedresult['user_id']);
-				if ($userinfo['lastname'] != $importedresult['lastname'] || $userinfo['firstname'] != $importedresult['firstname'] || $userinfo['official_code'] != $importedresult['official_code'])
-				{
-					if (!isset ($values['ignoreerrors']))
-					{
-						header('Location: gradebook_view_result.php?selecteval=' . $_GET['selecteval'] . '&import_user_error=' . $importedresult['user_id']);
-						exit;
-					}
+			}
+			if ($added != '1') {
+				if ($importedresult['score'] > $eval[0]->get_max()) {
+					header('Location: gradebook_view_result.php?selecteval=' .Security::remove_XSS($_GET['selecteval']) . '&overwritemax=');
+					exit;
 				}
-				if ($added != '1')
-				{
-					if ($importedresult['score'] > $eval[0]->get_max())
-					{
-						header('Location: gradebook_view_result.php?selecteval=' . $_GET['selecteval'] . '&overwritemax=');
-						exit;
-					}
-					$result= new Result();
-					$result->set_user_id($importedresult['user_id']);
-					if (!empty ($importedresult['score']))
-					{
-						$result->set_score($importedresult['score']);
-					}
-					if (!empty ($importedresult['date']))
-					{
-						$result->set_date(strtotime($importedresult['date']));
-					} else
-					{
-						$result->set_date(time());
-					}
-					$result->set_evaluation_id($_GET['selecteval']); //var_dump($result);
-					$result->add();
-					$nr_results_added++;
+				$result= new Result();
+				$result->set_user_id($importedresult['user_id']);
+				if (!empty ($importedresult['score'])) {
+					$result->set_score($importedresult['score']);
 				}
+				if (!empty ($importedresult['date'])) {
+					$result->set_date(strtotime($importedresult['date']));
+				} else {
+					$result->set_date(time());
+				}
+				$result->set_evaluation_id($_GET['selecteval']);
+				$result->add();
+				$nr_results_added++;
 			}
-		} else
-		{
-			header('Location: ' . api_get_self() . '?import=&selecteval=' . $_GET['selecteval'] . '&importnofile=');
-			exit;
 		}
-		if ($overwritescore != 0)
-		{
-			header('Location: ' . api_get_self() . '?selecteval=' . $_GET['selecteval'] . '&importoverwritescore=' . $overwritescore);
-			exit;
-		}
-		if ($nr_results_added == 0)
-		{
-			header('Location: ' . api_get_self() . '?selecteval=' . $_GET['selecteval'] . '&nothingadded=');
-			exit;
-		}
-		header('Location: ' . api_get_self() . '?selecteval=' . $_GET['selecteval'] . '&importok=');
+	} else {
+		header('Location: ' . api_get_self() . '?import=&selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&importnofile=');
+		exit;
+	}
+	if ($overwritescore != 0) {
+		header('Location: ' . api_get_self() . '?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&importoverwritescore=' . $overwritescore);
 		exit;
 	}
+	if ($nr_results_added == 0) {
+		header('Location: ' . api_get_self() . '?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&nothingadded=');
+		exit;
+	}
+	header('Location: ' . api_get_self() . '?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '&importok=');
+	exit;
+	}
 }
-if (isset ($_GET['export']))
-{
-	$interbreadcrumb[]= array (
-		'url' => 'gradebook_view_result.php?selecteval=' . $_GET['selecteval'],
-		'name' => get_lang('ViewResult'
-	));
-	$export_result_form= new DataForm(DataForm :: TYPE_EXPORT, 'export_result_form', null, api_get_self() . '?export=&selecteval=' . $_GET['selecteval'], '_blank');
-	if (!$export_result_form->validate())
-		Display :: display_header(get_lang('Export'));
-	if ($export_result_form->validate())
-	{
-		$export= $export_result_form->exportValues();
-		$file_type= $export['file_type'];
-		$filename= 'export_results_' . date('Y-m-d_H-i-s');
-		$results= Result :: load(null, null, $_GET['selecteval']);
-		$data= array (); //when file type is csv, add a header to the output file
-		if ($file_type == 'csv')
-		{
-			$alldata[]= array (
-				'user_id',
-				'official_code',
-				'lastname',
-				'firstname',
-				'score',
-				'date'
-			);
-		}
-		if ($file_type == 'pdf')
-		{
-			if (($eval[0]->has_results()))
-			{
-				$score= $eval[0]->calc_score();
-				if ($score != null)
-					$average= get_lang('Average') . ' : ' . round(100 * ($score[0] / $score[1])) . ' %';
-			}
-			if ($eval[0]->get_course_code() == null)
-				$course= get_lang('CourseIndependent');
-			else
-				$course= get_course_name_from_code($eval[0]->get_course_code());
-			$pdf= new Cezpdf();
-			$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
-			$pdf->ezSetMargins(30, 30, 50, 30);
-			$pdf->ezSetY(800);
-			$pdf->ezText(get_lang('EvaluationName') . ' : ' . $eval[0]->get_name() . ' (' . date('j/n/Y g:i', $eval[0]->get_date()) . ')', 12, array (
-				'justification' => 'left'
-			));
-			$pdf->ezText(get_lang('Description') . ' : ' . $eval[0]->get_description());
-			$pdf->ezText(get_lang('Course') . ' : ' . $course, 12, array (
-				'justification' => 'left'
-			));
-			$pdf->ezText(get_lang('Weight') . ' : ' . $eval[0]->get_weight(), 12, array (
-				'justification' => 'left'
-			));
-			$pdf->ezText(get_lang('Max') . ' : ' . $eval[0]->get_max(), 12, array (
-				'justification' => 'left'
-			));
-			$pdf->ezText($average, 12, array (
-				'justification' => 'left'
-			));
-			
-			$datagen = new ResultsDataGenerator ($eval[0],$allresults);
-			$data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_LASTNAME,0,null,true);	
-			$newarray = array();
-			foreach ($data_array as $data)
-			{
-				$newitem = array();
-				$newitem[] = $data['lastname'];
-				$newitem[] = $data['firstname'];
-				$newitem[] = $data['score'];
-				if ($displayscore->is_custom())
-					$newitem[] = $data['display'];
-				$newarray[] = $newitem;
+if (isset ($_GET['export'])) {
+$interbreadcrumb[]= array (
+	'url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']),
+	'name' => get_lang('ViewResult'
+));
+$export_result_form= new DataForm(DataForm :: TYPE_EXPORT, 'export_result_form', null, api_get_self() . '?export=&selecteval=' . $_GET['selecteval'], '_blank');
+if (!$export_result_form->validate()) {
+	Display :: display_header(get_lang('Export'));	
+}
+
+if ($export_result_form->validate()) {
+	$export= $export_result_form->exportValues();
+	$file_type= $export['file_type'];
+	$filename= 'export_results_' . date('Y-m-d_H-i-s');
+	$results= Result :: load(null, null, Security::remove_XSS($_GET['selecteval']));
+	$data= array (); //when file type is csv, add a header to the output file
+	if ($file_type == 'csv') {
+		$alldata[]= array (
+			'user_id',
+			'official_code',
+			'lastname',
+			'firstname',
+			'score',
+			'date'
+		);
+	}
+	if ($file_type == 'pdf') {
+		if (($eval[0]->has_results())) {
+			$score= $eval[0]->calc_score();
+			if ($score != null) {
+				$average= get_lang('Average') . ' : ' . round(100 * ($score[0] / $score[1])) . ' %';				
 			}
-			$pdf->ezSetY(650);
-			if ($displayscore->is_custom())
-				$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'),get_lang('Display'));
-			else
-				$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'));
+		}
+		if ($eval[0]->get_course_code() == null) {
+			$course= get_lang('CourseIndependent');
+		} else {
+			$course= get_course_name_from_code($eval[0]->get_course_code());			
+		}
+
+		$pdf= new Cezpdf();
+		$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
+		$pdf->ezSetMargins(30, 30, 50, 30);
+		$pdf->ezSetY(800);
+		$pdf->ezText(get_lang('EvaluationName') . ' : ' . $eval[0]->get_name() . ' (' . date('j/n/Y g:i', $eval[0]->get_date()) . ')', 12, array (
+			'justification' => 'left'
+		));
+		$pdf->ezText(get_lang('Description') . ' : ' . $eval[0]->get_description());
+		$pdf->ezText(get_lang('Course') . ' : ' . $course, 12, array (
+			'justification' => 'left'
+		));
+		$pdf->ezText(get_lang('Weight') . ' : ' . $eval[0]->get_weight(), 12, array (
+			'justification' => 'left'
+		));
+		$pdf->ezText(get_lang('Max') . ' : ' . $eval[0]->get_max(), 12, array (
+			'justification' => 'left'
+		));
+		$pdf->ezText($average, 12, array (
+			'justification' => 'left'
+		));
 		
-			$pdf->ezTable($newarray,$header_names,'',array('showHeadings'=>1,'shaded'=>1,'showLines'=>1,'rowGap'=>3,'width'=> 500));
-			$pdf->ezStream();
-			exit;
+		$datagen = new ResultsDataGenerator ($eval[0],$allresults);
+		$data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_LASTNAME,0,null,true);	
+		$newarray = array();
+		foreach ($data_array as $data) {
+			$newitem = array();
+			$newitem[] = $data['lastname'];
+			$newitem[] = $data['firstname'];
+			$newitem[] = $data['score'];
+			if ($displayscore->is_custom())
+				$newitem[] = $data['display'];
+			$newarray[] = $newitem;
 		}
-		foreach ($results as $result)
-		{
-			$userinfo= get_user_info_from_id($result->get_user_id());
-			$data['user_id']= $result->get_user_id();
-			$data['official_code']= $userinfo['official_code'];
-			$data['lastname']= $userinfo['lastname'];
-			$data['firstname']= $userinfo['firstname'];
-			$data['score']= $result->get_score();
-			$data['date']= date('Y-n-j g:i', $result->get_date());
-			$alldata[]= $data;
+		$pdf->ezSetY(650);
+		if ($displayscore->is_custom()) {
+			$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'),get_lang('Display'));			
+		}else {
+			$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'));
 		}
-		switch ($file_type)
-		{
-			case 'xml' :
-				Export :: export_table_xml($alldata, $filename, 'Result', 'XMLResults');
-				break;
-			case 'csv' :
-				Export :: export_table_csv($alldata, $filename);
-				break;
+			
+		$pdf->ezTable($newarray,$header_names,'',array('showHeadings'=>1,'shaded'=>1,'showLines'=>1,'rowGap'=>3,'width'=> 500));
+		$pdf->ezStream();
+		exit;
+	}
+	foreach ($results as $result) {
+		$userinfo= get_user_info_from_id($result->get_user_id());
+		$data['user_id']= $result->get_user_id();
+		$data['official_code']= $userinfo['official_code'];
+		$data['lastname']= $userinfo['lastname'];
+		$data['firstname']= $userinfo['firstname'];
+		$data['score']= $result->get_score();
+		$data['date']= date('Y-n-j g:i', $result->get_date());
+		$alldata[]= $data;
+	}
+	switch ($file_type) {
+		case 'xml' :
+			Export :: export_table_xml($alldata, $filename, 'Result', 'XMLResults');
+			break;
+		case 'csv' :
+			Export :: export_table_csv($alldata, $filename);
+			break;
 		}
 	}
 }
-if (isset ($_GET['resultdelete']))
-{
+if (isset ($_GET['resultdelete'])) {
 	$result= Result :: load($_GET['resultdelete']);
 	$result[0]->delete();
-	header('Location: gradebook_view_result.php?deleteresult=&selecteval=' . $_GET['selecteval']);
+	header('Location: gradebook_view_result.php?deleteresult=&selecteval=' .Security::remove_XSS($_GET['selecteval']));
 	exit;
 }
-if (isset ($_POST['action']))
-{
+if (isset ($_POST['action'])) {
 	$number_of_selected_items= count($_POST['id']);
-	if ($number_of_selected_items == '0')
-		Display :: display_warning_message(get_lang('NoItemsSelected'),false);
-	else
-	{
-		switch ($_POST['action'])
-		{
-			case 'delete' :
-				$number_of_deleted_results= 0;
-				foreach ($_POST['id'] as $indexstr)
-				{
-					$result= Result :: load($indexstr);
-					$result[0]->delete();
-					$number_of_deleted_results++;
-				}
-				header('Location: gradebook_view_result.php?massdelete=&selecteval=' . $_GET['selecteval']);
-				exit;
-				break;
+	if ($number_of_selected_items == '0') {
+		Display :: display_warning_message(get_lang('NoItemsSelected'),false);		
+	} else {
+	switch ($_POST['action']) {
+		case 'delete' :
+			$number_of_deleted_results= 0;
+			foreach ($_POST['id'] as $indexstr) {
+				$result= Result :: load($indexstr);
+				$result[0]->delete();
+				$number_of_deleted_results++;
+			}
+			header('Location: gradebook_view_result.php?massdelete=&selecteval=' .Security::remove_XSS($_GET['selecteval']));
+			exit;
+			break;
 		}
 	}
 } // TODO - what if selecteval not set ?
 $addparams= array (
 'selecteval' => $eval[0]->get_id());
-if (isset ($_GET['print']))
-{
+if (isset ($_GET['print'])) {
 	$datagen = new ResultsDataGenerator ($eval[0],$allresults);
 	$data_array = $datagen->get_data(ResultsDataGenerator :: RDG_SORT_LASTNAME,0,null,true);	
-			if ($displayscore->is_custom())
-				$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'),get_lang('Display'));
-			else
-				$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'));
+		if ($displayscore->is_custom()) {
+			$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'),get_lang('Display'));			
+		}else {
+			$header_names = array(get_lang('LastName'),get_lang('FirstName'),get_lang('Score'));			
+		}
 	$newarray = array();
-	foreach ($data_array as $data)
-		$newarray[] = array_slice($data, 2);		
-
+	foreach ($data_array as $data) {
+		$newarray[] = array_slice($data, 2);			
+	}
 	echo print_table($newarray, $header_names,get_lang('ViewResult'), $eval[0]->get_name());
 	exit;
 } else
 	$resulttable= new ResultTable($eval[0], $allresults, $iscourse, $addparams);
-$htmlHeadXtra[]= '<script type="text/javascript">
+	$htmlHeadXtra[]= '<script type="text/javascript">
 function confirmationuser ()
 {
-	if (confirm("' . get_lang('DeleteUser') . '?"))
-		{return true;}
-	else
-		{return false;}
+if (confirm("' . get_lang('DeleteUser') . '?"))
+	{return true;}
+else
+	{return false;}
 }
 function confirmationall ()
 {
-	if (confirm("' . get_lang('DeleteAll') . '?"))
-		{return true;}
-	else
-		{return false;}
+if (confirm("' . get_lang('DeleteAll') . '?"))
+	{return true;}
+else
+	{return false;}
 }
 </script>';
-if (isset ($_GET['deleteall']))
-{
+if (isset ($_GET['deleteall'])) {
 	$eval[0]->delete_results();
-	header('Location: gradebook_view_result.php?allresdeleted=&selecteval=' . $_GET['selecteval']);
+	header('Location: gradebook_view_result.php?allresdeleted=&selecteval=' . Security::remove_XSS($_GET['selecteval']));
 	exit;
 }
-if ((!isset ($_GET['export'])) && (!isset ($_GET['import'])))
-	Display :: display_header(get_lang('ViewResult'));
-if (isset ($_GET['addresultnostudents']))
+if ((!isset ($_GET['export'])) && (!isset ($_GET['import']))) {
+	Display :: display_header(get_lang('ViewResult'));	
+}
+if (isset ($_GET['addresultnostudents'])) {
 	Display :: display_warning_message(get_lang('AddResultNoStudents'),false);
-if (isset ($_GET['editresmessage']))
+}
+
+if (isset ($_GET['editresmessage'])) {
 	Display :: display_confirmation_message(get_lang('ResultEdited'),false);
-if (isset ($_GET['addresult']))
+}
+
+if (isset ($_GET['addresult'])) {
 	Display :: display_confirmation_message(get_lang('ResultAdded'),false);
-if (isset ($_GET['adduser']))
+}
+
+if (isset ($_GET['adduser'])) {
 	Display :: display_confirmation_message(get_lang('UserAdded'),false);
-if (isset ($_GET['deleteresult']))
+}
+
+if (isset ($_GET['deleteresult'])) {
 	Display :: display_confirmation_message(get_lang('ResultDeleted'),false);
-if (isset ($_GET['editallresults']))
+}
+
+if (isset ($_GET['editallresults'])) {
 	Display :: display_confirmation_message(get_lang('AllResultsEdited'),false);
-if (isset ($_GET['importok']))
+}
+
+if (isset ($_GET['importok'])) {
 	Display :: display_confirmation_message(get_lang('ImportOk'),false);
-if (isset ($_GET['importnofile']))
+}
+
+if (isset ($_GET['importnofile'])) {
 	Display :: display_warning_message(get_lang('ImportNoFile'),false);
-if (isset ($_GET['incorrectdata']))
+}
+
+if (isset ($_GET['incorrectdata'])) {
 	Display :: display_warning_message(get_lang('IncorrectData'),false);
-if (isset ($_GET['nothingadded']))
+}
+if (isset ($_GET['nothingadded'])) {
 	Display :: display_warning_message(get_lang('NothingAdded'),false);
-if (isset ($_GET['massdelete']))
+}
+if (isset ($_GET['massdelete'])) {
 	Display :: display_confirmation_message(get_lang('ResultsDeleted'),false);
-if (isset ($_GET['nouser']))
+}
+if (isset ($_GET['nouser'])) {
 	Display :: display_warning_message(get_lang('NoUser'),false);
-if (isset ($_GET['overwritemax']))
+}
+if (isset ($_GET['overwritemax'])) {
 	Display :: display_warning_message(get_lang('OverWriteMax'),false);
-if (isset ($_GET['importoverwritescore']))
+}
+if (isset ($_GET['importoverwritescore'])) {
 	Display :: display_confirmation_message(get_lang('ImportOverwriteScore') . ' ' . $_GET['importoverwritescore']);
-if (isset ($_GET['import_user_error']))
-{
+}
+
+if (isset ($_GET['import_user_error'])) {
 	$userinfo= get_user_info_from_id($_GET['import_user_error']);
 	Display :: display_warning_message(get_lang('UserInfoDoesNotMatch') . '<br /><br /><b>' . $userinfo['lastname'] . ' ' . $userinfo['firstname'] . '</b>');
 }
-if (isset ($_GET['allresdeleted']))
+if (isset ($_GET['allresdeleted'])) {
 	Display :: display_confirmation_message(get_lang('AllResultDeleted'));
-if (isset ($_GET['import_score_error']))
-{
+}
+
+if (isset ($_GET['import_score_error'])) {
 	$userinfo= get_user_info_from_id($_GET['import_score_error']);
 	Display :: display_warning_message(get_lang('ScoreDoesNotMatch') . '<br /><br /><b>' . $userinfo['lastname'] . ' ' . $userinfo['firstname'] . '</b>');
 }
-if ($file_type == null)
-{ //show the result header
-	if (isset ($export_result_form) && !(isset ($edit_res_form)))
-	{
+if ($file_type == null) { //show the result header
+		if (isset ($export_result_form) && !(isset ($edit_res_form))) {
 		echo '<div class ="normal-message">';
 		echo $export_result_form->display();
 		echo '</div>';
 		DisplayGradebook :: display_header_result($eval[0], $currentcat[0]->get_id(), 1);
-	} else
-	{
-		if (isset ($import_result_form))
-		{
+} else {
+		if (isset ($import_result_form)){
 			echo '<div class ="normal-message">';
 			echo $import_result_form->display();
 			echo '</div>';
 		}
-		if (isset ($edit_res_form))
-		{
+		if (isset ($edit_res_form)) {
 			Display :: display_normal_message($edit_res_form->toHtml(),false);
 		}
 		DisplayGradebook :: display_header_result($eval[0], $currentcat[0]->get_id(), 1);
 	}
 	$resulttable->display();
 	Display :: display_footer();
-}
-?>
+}

+ 658 - 0
main/gradebook/index.php

@@ -0,0 +1,658 @@
+<?php // $Id: $
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+    Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006-2008 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+$language_file= 'gradebook';
+// $cidReset : This is the main difference with gradebook.php, here we say,
+// basically, that we are inside a course, and many things depend from that
+$cidReset= false;
+$_in_course = true;
+require_once ('../inc/global.inc.php');
+$course_code = api_get_course_id();
+//make sure the destination for scripts is index.php instead of gradebook.php
+$_SESSION['gradebook_dest'] = 'index.php';
+$this_section = SECTION_MYGRADEBOOK;
+require_once ('lib/be.inc.php');
+require_once ('lib/scoredisplay.class.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/catform.class.php');
+require_once ('lib/fe/evalform.class.php');
+require_once ('lib/fe/linkform.class.php');
+require_once ('lib/gradebook_data_generator.class.php');
+require_once ('lib/fe/gradebooktable.class.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/fe/userform.class.php');
+require_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
+api_block_anonymous_users();
+$htmlHeadXtra[]= '<script type="text/javascript">
+function confirmation ()
+{
+	if (confirm("' . get_lang('DeleteAll') . '?"))
+		{return true;}
+	else
+		{return false;}
+}
+</script>';
+
+$tbl_forum_thread = Database :: get_course_table(TABLE_FORUM_THREAD);
+$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+
+$filter_confirm_msg = true;
+$filter_warning_msg = true;
+// --------------------------------------------------------------------------------
+// -                                  ACTIONS                                     -
+// --------------------------------------------------------------------------------
+//this is called when there is no data for the course admin
+if (isset ($_GET['createallcategories'])) {
+	block_students();
+	$coursecat= Category :: get_not_created_course_categories(api_get_user_id());
+	if (!count($coursecat) == 0) {
+		
+		foreach ($coursecat as $row) {
+			$cat= new Category();
+			$cat->set_name($row[1]);
+			$cat->set_course_code($row[0]);
+			$cat->set_description(null);
+			$cat->set_user_id(api_get_user_id());
+			$cat->set_parent_id(0);
+			$cat->set_weight(0);
+			$cat->set_visible(0);
+			$cat->add();
+			unset ($cat);
+		}
+	}
+	header('Location: '.$_SESSION['gradebook_dest'].'?addallcat=&selectcat=0');
+	exit;
+}
+//show logs evaluations
+if (isset ($_GET['visiblelog'])) {
+	header('Location: ' . api_get_self().'/gradebook_showlog_eval.php');
+	exit;
+}
+//move a category
+if (isset ($_GET['movecat'])) {
+	block_students();
+	$cats= Category :: load($_GET['movecat']);
+	if (!isset ($_GET['targetcat'])) {
+		$move_form= new CatForm(CatForm :: TYPE_MOVE,
+		$cats[0],
+		'move_cat_form',
+		null,
+		api_get_self() . '?movecat=' . Security::remove_XSS($_GET['movecat'])
+		. '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
+			if ($move_form->validate()) {
+				header('Location: ' . api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
+				 . '&movecat=' . Security::remove_XSS($_GET['movecat'])
+				 . '&targetcat=' . $move_form->exportValue('move_cat'));
+				 exit;
+			}
+		} else {
+			$targetcat= Category :: load($_GET['targetcat']);
+			$course_to_crsind = ($cats[0]->get_course_code() != null && $targetcat[0]->get_course_code() == null);
+
+			if (!($course_to_crsind && !isset($_GET['confirm']))) {
+				$cats[0]->move_to_cat($targetcat[0]);
+				header('Location: ' . api_get_self() . '?categorymoved=&selectcat=' . Security::remove_XSS($_GET['selectcat']));
+				exit;
+				}
+				unset ($targetcat);
+		}
+	unset ($cats);
+}
+//move an evaluation
+if (isset ($_GET['moveeval'])) {
+	block_students();
+	$evals= Evaluation :: load($_GET['moveeval']);
+	if (!isset ($_GET['targetcat'])) {
+
+		$move_form= new EvalForm(EvalForm :: TYPE_MOVE,
+		$evals[0],
+		null,
+		'move_eval_form',
+		null,
+		api_get_self() . '?moveeval=' . Security::remove_XSS($_GET['moveeval'])
+		. '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
+
+		if ($move_form->validate()) {
+			header('Location: ' .api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
+			. '&moveeval=' . Security::remove_XSS($_GET['moveeval'])
+			. '&targetcat=' . $move_form->exportValue('move_cat'));
+			exit;
+			}
+		} else {
+		$targetcat= Category :: load($_GET['targetcat']);
+		$course_to_crsind = ($evals[0]->get_course_code() != null && $targetcat[0]->get_course_code() == null);
+
+		if (!($course_to_crsind && !isset($_GET['confirm']))) {
+			$evals[0]->move_to_cat($targetcat[0]);
+			header('Location: ' . api_get_self() . '?evaluationmoved=&selectcat=' . Security::remove_XSS($_GET['selectcat']));
+			exit;
+		}
+		unset ($targetcat);
+	}
+	unset ($evals);
+}
+//move a link
+if (isset ($_GET['movelink'])) {
+	block_students();
+	$link= LinkFactory :: load($_GET['movelink']);
+	$move_form= new LinkForm(LinkForm :: TYPE_MOVE, null, $link[0], 'move_link_form', null, api_get_self() . '?movelink=' . $_GET['movelink'] . '&selectcat=' . Security::remove_XSS($_GET['selectcat']));
+	
+	if ($move_form->validate()) {
+		$targetcat= Category :: load($move_form->exportValue('move_cat'));
+		$link[0]->move_to_cat($targetcat[0]);
+		unset ($link);
+		header('Location: ' . api_get_self(). '?linkmoved=&selectcat=' . Security::remove_XSS($_GET['selectcat']));
+		exit;
+	}
+}
+//parameters for categories
+if (isset ($_GET['visiblecat'])) {
+	block_students();
+	
+	if (isset ($_GET['set_visible'])) {
+		$visibility_command= 1;		
+	} else {
+		$visibility_command= 0;		
+	}
+	$cats= Category :: load($_GET['visiblecat']);
+	$cats[0]->set_visible($visibility_command);
+	$cats[0]->save();
+	$cats[0]->apply_visibility_to_children();
+	unset ($cats);
+	if ($visibility_command) {
+		$confirmation_message = get_lang('ViMod');
+		$filter_confirm_msg = false;
+	} else {
+		$confirmation_message = get_lang('InViMod');
+		$filter_confirm_msg = false;
+	}
+}
+if (isset ($_GET['deletecat'])) {
+	block_students();
+	$cats= Category :: load($_GET['deletecat']);
+	//delete all categories,subcategories and results
+	if ($cats[0] != null) {
+		if ($cats[0]->get_id() != 0) {
+			 // better don't try to delete the root...
+			 $cats[0]->delete_all();
+		}	
+	}
+	$confirmation_message = get_lang('CategoryDeleted');
+	$filter_confirm_msg = false;
+}
+//parameters for evaluations
+if (isset ($_GET['visibleeval'])) {
+	block_students();
+	if (isset ($_GET['set_visible'])) {
+		$visibility_command= 1;		
+	} else {
+		$visibility_command= 0;		
+	}
+	$eval= Evaluation :: load($_GET['visibleeval']);
+	$eval[0]->set_visible($visibility_command);
+	$eval[0]->save();
+	unset ($eval);
+	if ($visibility_command) {
+		$confirmation_message = get_lang('ViMod');
+		$filter_confirm_msg = false;
+	} else {
+		$confirmation_message = get_lang('InViMod');
+		$filter_confirm_msg = false;
+	}
+}
+if (isset ($_GET['deleteeval'])) {
+	block_students();
+	$eval= Evaluation :: load($_GET['deleteeval']);
+	if ($eval[0] != null) {
+		$eval[0]->delete_with_results();		
+	}
+	$confirmation_message = get_lang('GradebookEvaluationDeleted');
+	$filter_confirm_msg = false;
+}
+//parameters for links
+if (isset ($_GET['visiblelink'])) {
+	block_students();
+	if (isset ($_GET['set_visible'])) {
+		$visibility_command= 1;	
+	} else {
+		$visibility_command= 0;		
+	}
+	$link= LinkFactory :: load($_GET['visiblelink']);
+	$link[0]->set_visible($visibility_command);
+	$link[0]->save();
+	unset ($link);
+	if ($visibility_command) {
+		$confirmation_message = get_lang('ViMod');
+		$filter_confirm_msg = false;
+	} else {
+		$confirmation_message = get_lang('InViMod');
+		$filter_confirm_msg = false;
+	}
+}
+
+if (isset ($_GET['deletelink'])) {
+	block_students();
+	$link= LinkFactory :: load($_GET['deletelink']);
+	if ($link[0] != null) {
+		$sql='UPDATE '.$tbl_forum_thread.' SET thread_qualify_max=0,thread_weight=0,thread_title_qualify="" WHERE thread_id=(SELECT ref_id FROM '.$tbl_grade_links.' where id='.$_GET['deletelink'].');';
+		api_sql_query($sql);
+		$link[0]->delete();
+	}
+	unset ($link);
+	$confirmation_message = get_lang('LinkDeleted');
+	$filter_confirm_msg = false;
+}
+
+if ($course_to_crsind && !isset($_GET['confirm'])) {
+	block_students();
+	
+	if (!isset($_GET['movecat']) && !isset($_GET['moveeval'])) {
+		die ('Error: movecat or moveeval not defined');		
+	}
+	$button = '<form name="confirm"
+					 method="post"
+					 action="'.api_get_self() .'?confirm='
+					.(isset($_GET['movecat']) ? '&movecat=' . Security::remove_XSS($_GET['movecat'])
+					: '&moveeval=' . Security::remove_XSS($_GET['moveeval']) )
+					.'&selectcat=' . Security::remove_XSS($_GET['selectcat'])
+					.'&targetcat=' . Security::remove_XSS($_GET['targetcat']).'">
+			   <input type="submit" value="'.get_lang('Ok').'">
+			   </form>';
+	$warning_message = get_lang('MoveWarning').'<br><br>'.$button;
+	$filter_warning_msg = false;
+}
+//actions on the sortabletable
+if (isset ($_POST['action'])) {
+	block_students();
+	$number_of_selected_items= count($_POST['id']);
+	
+	if ($number_of_selected_items == '0') {
+		$warning_message = get_lang('NoItemsSelected');
+		$filter_warning_msg = false;
+	} else {
+		switch ($_POST['action']) {
+			case 'deleted' :
+				$number_of_deleted_categories= 0;
+				$number_of_deleted_evaluations= 0;
+				$number_of_deleted_links= 0;
+				foreach ($_POST['id'] as $indexstr) {
+					if (substr($indexstr, 0, 4) == 'CATE') {
+						$cats= Category :: load(substr($indexstr, 4));
+						if ($cats[0] != null) {
+							$cats[0]->delete_all();							
+						}
+						$number_of_deleted_categories++;
+					}
+					if (substr($indexstr, 0, 4) == 'EVAL') {
+						$eval= Evaluation :: load(substr($indexstr, 4));
+						if ($eval[0] != null) {
+							$eval[0]->delete_with_results();							
+						}
+
+						$number_of_deleted_evaluations++;
+					}
+					if (substr($indexstr, 0, 4) == 'LINK') {
+						$link= LinkFactory :: load(substr($indexstr, 4));
+						if ($link[0] != null) {
+							$link[0]->delete();							
+						}
+
+						$number_of_deleted_links++;
+					}
+				}
+				$confirmation_message = get_lang('DeletedCategories') . ' : <b>' . $number_of_deleted_categories . '</b><br />' . get_lang('DeletedEvaluations') . ' : <b>' . $number_of_deleted_evaluations . '</b><br />' . get_lang('DeletedLinks') . ' : <b>' . $number_of_deleted_links . '</b><br /><br />' . get_lang('TotalItems') . ' : <b>' . $number_of_selected_items . '</b>';
+				$filter_confirm_msg = false;
+				break;
+			case 'setvisible' :
+				foreach ($_POST['id'] as $indexstr) {
+					if (substr($indexstr, 0, 4) == 'CATE') {
+						$cats= Category :: load(substr($indexstr, 4));
+						$cats[0]->set_visible(1);
+						$cats[0]->save();
+						$cats[0]->apply_visibility_to_children();
+					}
+					if (substr($indexstr, 0, 4) == 'EVAL') {
+						$eval= Evaluation :: load(substr($indexstr, 4));
+						$eval[0]->set_visible(1);
+						$eval[0]->save();
+					}
+					if (substr($indexstr, 0, 4) == 'LINK') {
+						$link= LinkFactory :: load(substr($indexstr, 4));
+						$link[0]->set_visible(1);
+						$link[0]->save();
+					}
+				}
+				$confirmation_message = get_lang('ItemsVisible');
+				$filter_confirm_msg = false;
+				break;
+			case 'setinvisible' :
+				foreach ($_POST['id'] as $indexstr) {
+					if (substr($indexstr, 0, 4) == 'CATE') {
+						$cats= Category :: load(substr($indexstr, 4));
+						$cats[0]->set_visible(0);
+						$cats[0]->save();
+						$cats[0]->apply_visibility_to_children();
+					}
+					if (substr($indexstr, 0, 4) == 'EVAL') {
+						$eval= Evaluation :: load(substr($indexstr, 4));
+						$eval[0]->set_visible(0);
+						$eval[0]->save();
+					}
+					if (substr($indexstr, 0, 4) == 'LINK') {
+						$link= LinkFactory :: load(substr($indexstr, 4));
+						$link[0]->set_visible(0);
+						$link[0]->save();
+					}
+				}
+				$confirmation_message = get_lang('ItemsInVisible');
+				$filter_confirm_msg = false;
+				break;
+		}
+	}
+}
+
+if (isset ($_POST['submit']) && isset ($_POST['keyword'])) {
+	header('Location: ' . api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat'])
+	. '&search='.Security::remove_XSS($_POST['keyword']));
+	exit;
+}
+
+
+// --------------------------------------------------------------------------------
+// -                       DISPLAY HEADERS AND MESSAGES                           -
+// --------------------------------------------------------------------------------
+
+if (!isset($_GET['exportpdf']) and !isset($_GET['export_certificate'])) {
+	if (isset ($_GET['studentoverview'])) {
+		$interbreadcrumb[]= array (
+			'url' => $_SESSION['gradebook_dest'].'?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+			'name' => get_lang('Gradebook')
+		);
+		Display :: display_header(get_lang('FlatView'));
+	} elseif (isset ($_GET['search'])) {
+		$interbreadcrumb[]= array (
+			'url' => $_SESSION['gradebook_dest'].'?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+			'name' => get_lang('Gradebook')
+		);
+		Display :: display_header(get_lang('SearchResults'));
+	} elseif(isset ($_GET['selectcat'])) {
+		$interbreadcrumb[]= array (
+			'url' => $_SESSION['gradebook_dest'],
+			'name' => get_lang('Gradebook')
+		);
+		
+		$interbreadcrumb[]= array (
+			'url' => $_SESSION['gradebook_dest'].'?selectcat=' . Security::remove_XSS($_GET['selectcat']),
+			'name' => get_lang('Details')
+		);
+		Display :: display_header();
+	} else {
+		Display :: display_header(get_lang('Gradebook'));
+	}
+}
+
+if (isset ($_GET['categorymoved'])) {
+	Display :: display_confirmation_message(get_lang('CategoryMoved'),false);
+}
+if (isset ($_GET['evaluationmoved'])) {
+	Display :: display_confirmation_message(get_lang('EvaluationMoved'),false);	
+}
+if (isset ($_GET['linkmoved'])) {
+	Display :: display_confirmation_message(get_lang('LinkMoved'),false);	
+}
+if (isset ($_GET['addcat'])) {
+	Display :: display_confirmation_message(get_lang('CategoryAdded'),false);
+}
+if (isset ($_GET['linkadded'])) {
+	Display :: display_confirmation_message(get_lang('LinkAdded'),false);
+}
+if (isset ($_GET['addresult'])) {
+	Display :: display_confirmation_message(get_lang('ResultAdded'),false);
+}
+if (isset ($_GET['editcat'])) {
+	Display :: display_confirmation_message(get_lang('CategoryEdited'),false);	
+}
+if (isset ($_GET['editeval'])) {
+	Display :: display_confirmation_message(get_lang('EvaluationEdited'),false);	
+}
+if (isset ($_GET['linkedited'])) {
+	Display :: display_confirmation_message(get_lang('LinkEdited'),false);	
+}
+if (isset ($_GET['nolinkitems'])){
+	Display :: display_warning_message(get_lang('NoLinkItems'),false);	
+}
+if (isset ($_GET['addallcat'])){
+	Display :: display_normal_message(get_lang('AddAllCat'),false);	
+}
+if (isset ($confirmation_message)){
+	Display :: display_confirmation_message($confirmation_message,$filter_confirm_msg);	
+}
+if (isset ($warning_message)){
+	Display :: display_warning_message($warning_message,$filter_warning_msg);	
+}
+if (isset ($move_form)){
+	Display :: display_normal_message($move_form->toHtml(),false);	
+}
+
+// --------------------------------------------------------------------------------
+// -                        LOAD DATA & DISPLAY TABLE                             -
+// --------------------------------------------------------------------------------
+
+$is_platform_admin= api_is_platform_admin();
+$is_course_admin= api_is_allowed_to_create_course();
+
+//load data for category, evaluation and links
+if (empty ($_GET['selectcat'])) {
+	$category= 0;
+} else {
+	$category= $_GET['selectcat'];
+}
+// search disabled in course context
+/*
+$simple_search_form= new UserForm(UserForm :: TYPE_SIMPLE_SEARCH, null, 'simple_search_form', null, api_get_self() . '?selectcat=' . Security::remove_XSS($_GET['selectcat']));
+$values= $simple_search_form->exportValues();
+$keyword = '';
+if (isset($_GET['search']) && !empty($_GET['search']))
+	$keyword = Security::remove_XSS($_GET['search']);
+if ($simple_search_form->validate() && (empty($keyword)))
+	$keyword = $values['keyword'];
+*/
+
+/* search disabled in course context
+if (!empty($keyword))
+{
+	$cats= Category :: load($category);
+	$allcat= array ();
+	$alleval= Evaluation :: find_evaluations($keyword, $cats[0]->get_id());
+	$alllink= LinkFactory :: find_links($keyword, $cats[0]->get_id());
+}
+else
+*/
+if (isset ($_GET['studentoverview'])) {
+	$cats= Category :: load($category);
+	$stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
+	$allcat= array ();
+	$alleval= $cats[0]->get_evaluations($stud_id, true);
+	$alllink= $cats[0]->get_links($stud_id, true);
+	if (isset ($_GET['exportpdf'])) {
+		$datagen = new GradebookDataGenerator ($allcat,$alleval, $alllink);
+		$header_names = array(get_lang('Name'),get_lang('Description'),get_lang('Weight'),get_lang('Date'),get_lang('Results'));
+		$data_array = $datagen->get_data(GradebookDataGenerator :: GDG_SORT_NAME,0,null,true);	
+		$newarray = array();
+		
+		foreach ($data_array as $data) {
+			$newarray[] = array_slice($data, 1);				
+		}
+		$pdf= new Cezpdf();
+		$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
+		$pdf->ezSetMargins(30, 30, 50, 30);
+		$pdf->ezSetY(810);
+		$pdf->ezText(get_lang('FlatView').' ('. date('j/n/Y g:i') .')',12,array('justification'=>'center'));
+		$pdf->line(50,790,550,790);
+		$pdf->line(50,40,550,40);
+		$pdf->ezSetY(750);
+		$pdf->ezTable($newarray,$header_names,'',array('showHeadings'=>1,'shaded'=>1,'showLines'=>1,'rowGap'=>3,'width'=> 500));
+		$pdf->ezStream();
+		exit;
+		}
+	} elseif (!empty($_GET['export_certificate'])) {
+	$user_id = strval(intval($_GET['user']));
+	if (!api_is_allowed_to_edit(true,true)) {
+		$user_id = api_get_user_id();
+	}
+	$category = Category :: load ($_GET['cat']);
+	if ($category[0]->is_certificate_available($user_id)) {
+		$user= get_user_info_from_id($user_id);
+		$scoredisplay = ScoreDisplay :: instance();
+		$scorecourse = $category[0]->calc_score($user_id);
+		$scorecourse_display = (isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable'));
+
+		$cattotal = Category :: load(0);
+		$scoretotal= $cattotal[0]->calc_score($user_id);
+		$scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal,SCORE_PERCENT) : get_lang('NoResultsAvailable'));
+		
+		//prepare all necessary variables:
+		$organization_name = api_get_setting('Institution');
+		$portal_name = api_get_setting('siteName');
+		$stud_fn = $user['firstname'];
+		$stud_ln = $user['lastname'];
+		$certif_text = sprintf(get_lang('CertificateWCertifiesStudentXFinishedCourseYWithGradeZ'),$organization_name,$stud_fn.' '.$stud_ln,$category[0]->get_name(),$scorecourse_display);
+		$certif_text = str_replace("\\n","\n",$certif_text);
+		$date = date('d/m/Y',time());
+		
+		$pdf= new Cezpdf('a4','landscape');
+		$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
+		$pdf->ezSetMargins(30, 30, 50, 50);
+		//line Y coordinates in landscape mode are upside down (500 is on top, 10 is on the bottom)
+		$pdf->line(50,50,790,50);
+		$pdf->line(50,550,790,550);
+		$pdf->ezSetY(450);
+		$pdf->ezImage(api_get_path(SYS_CODE_PATH).'img/dokeos_logo_certif.png',1,400,'','center','');
+		$pdf->ezSetY(480);
+		$pdf->ezText($certif_text,28,array('justification'=>'center'));
+		//$pdf->ezSetY(750);
+		$pdf->ezSetY(50);
+		$pdf->ezText($date,18,array('justification'=>'center'));
+		$pdf->ezSetY(580);
+		$pdf->ezText($organization_name,22,array('justification'=>'left'));
+		$pdf->ezSetY(580);
+		$pdf->ezText($portal_name,22,array('justification'=>'right'));
+		$pdf->ezStream();
+	}
+	exit;	
+} else { //in any other case (no search, no pdf), print the available gradebooks
+    // Important note: loading a category will actually load the *contents* of
+    // this category. This means that, to show the categories of a course,
+    // we have to show the root category and show its subcategories that
+    // are inside this course. This is done at the time of calling
+    // $cats[0]->get_subcategories(), not at the time of doing Category::load() 
+    
+    // $category comes from GET['selectcat']
+    $course_code = api_get_course_id();
+    $session_id = api_get_session_id();
+
+    //if $category = 0 (which happens when GET['selectcat'] is undefined)
+    // then Category::load() will create a new 'root' category with empty
+    // course and session fields in memory (Category::create_root_category())
+    if ($_in_course === true) {
+        // When *inside* a course, we want to make sure there is one (and only
+        // one) category for this course or for this session.
+	    $cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
+
+        if (empty($cats)) {
+            // There is no category for this course+session, so create one
+            $cat= new Category();
+            $course_code = api_get_course_id();
+            $session_id = api_get_session_id();
+            if (!empty($session_id)) {
+                $s_name = api_get_session_name();
+            	$cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
+                $cat->set_session_id($session_id);
+            } else {
+                $cat->set_name($course_code);
+            }
+            $cat->set_course_code($course_code);
+            $cat->set_description(null);
+            $cat->set_user_id(api_get_user_id());
+            $cat->set_parent_id(0);
+            $cat->set_weight(100);
+            $cat->set_visible(0);
+            $can_edit = api_is_allowed_to_edit(true, true);
+            if ($can_edit) {
+                $cat->add();
+            }        	
+            unset ($cat);
+        }
+        unset($cats);
+    }
+    $cats = Category :: load ($category, null, null, null, null, null, false);
+    
+    //with this fix the teacher only can view 1 gradebook
+	//$stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
+    if (api_is_platform_admin()) {
+            $stud_id= (api_is_allowed_to_create_course() ? null : api_get_user_id());
+    } else {
+    	$stud_id= api_get_user_id();
+    }
+	$allcat= $cats[0]->get_subcategories($stud_id, $course_code, $session_id);
+	$alleval= $cats[0]->get_evaluations($stud_id);
+	$alllink= $cats[0]->get_links($stud_id);
+    //whether we found a category or not, we now have a category object with
+    // empty or full subcats
+}
+
+// add params to the future links (in the table shown)
+$addparams = array ('selectcat' => $cats[0]->get_id());
+/*
+if (isset($_GET['search'])) {
+	$addparams['search'] = $keyword;
+}
+*/
+if (isset ($_GET['studentoverview'])) {
+	$addparams['studentoverview'] = '';
+}
+$gradebooktable= new GradebookTable($cats[0], $allcat, $alleval,$alllink, $addparams);
+$no_qualification = false;
+if (( count($allcat) == 0) && ( count($alleval) == 0 ) && ( count($alllink) == 0 )) {
+    $no_qualification = true;
+    if (($is_course_admin) && (!isset ($_GET['selectcat']))) {
+	   Display :: display_normal_message(get_lang('GradebookWelcomeMessage') . '<br /><br /><form name="createcat" method="post" action="' . api_get_self() . '?createallcategories=1"><input type="submit" value="' . get_lang('CreateAllCat') . '"></form>',false);
+    }
+} 
+//here we are in a sub category
+if ($category != '0') {
+	DisplayGradebook :: display_header_gradebook($cats[0], 0, $_GET['selectcat'], $is_course_admin, $is_platform_admin, $simple_search_form, false, true);
+} else {
+//this is the root category
+	//DisplayGradebook :: display_header_gradebook($cats[0], 0, 0, $is_course_admin, $is_platform_admin, $simple_search_form, false, false);
+}
+
+if (api_is_platform_admin() || api_is_allowed_to_create_course()) {
+	if (!isset ($_GET['selectcat'])) {
+		$cats = Category :: load(null, null, $course_code, null, null, $session_id, false);
+		DisplayGradebook :: display_reduce_header_gradebook($cats[0],$is_course_admin, $is_platform_admin, $simple_search_form, false, false);
+	}
+}
+$gradebooktable->display();
+Display :: display_footer();

+ 28 - 9
main/gradebook/lib/be.inc.php

@@ -1,13 +1,32 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
-// include this file to have access to all backend classes
-// @author Bert Steppé
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	Copyright (c) various contributors
+
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
 
-include_once ('be/gradebookitem.class.php');
-include_once ('be/category.class.php');
-include_once ('be/evaluation.class.php');
-include_once ('be/result.class.php');
-include_once ('be/linkfactory.class.php');	// this contains the include declarations
-											// to all link classes
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+// include this file to have access to all backend classes
+// @author Bert Steppé
+require_once ('be/gradebookitem.class.php');
+require_once ('be/category.class.php');
+require_once ('be/evaluation.class.php');
+require_once ('be/result.class.php');
+require_once ('be/linkfactory.class.php');	// this contains the include declarations
+											// to all link classes

+ 143 - 157
main/gradebook/lib/be/abstractlink.class.php

@@ -1,12 +1,33 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Defines a gradebook AbstractLink object.
  * To implement specific links,
  * extend this class and define a type in LinkFactory.
  * Use the methods in LinkFactory to create link objects.
- * @author Bert Stepp�
+ * @author Bert Steppé
  * @package dokeos.gradebook
  */
 abstract class AbstractLink implements GradebookItem
@@ -23,177 +44,158 @@ abstract class AbstractLink implements GradebookItem
 	protected $link_date;
 	protected $weight;
 	protected $visible;
-
+	protected $session_id;
+	
 // CONSTRUCTORS
 
-    function AbstractLink()
-    {
+    function AbstractLink() {
     }
 
 // GETTERS AND SETTERS
 
-   	public function get_id()
-	{
+   	public function get_id() {
 		return $this->id;
 	}
 
-	public function get_type()
-	{
+	public function get_type() {
 		return $this->type;
 	}
 
-	public function get_ref_id()
-	{
+	public function get_ref_id() {
 		return $this->ref_id;
 	}
 
-	public function get_user_id()
-	{
+	public function get_user_id() {
 		return $this->user_id;
 	}
 
-	public function get_course_code()
-	{
+	public function get_course_code() {
 		return $this->course_code;
 	}
 
-	public function get_category_id()
-	{
+	public function get_category_id() {
 		return $this->category;
 	}
 
-	public function get_date()
-	{
+	public function get_date() {
 		return $this->link_date;
 	}
 
-	public function get_weight()
-	{
+	public function get_weight() {
 		return $this->weight;
 	}
 
-	public function is_visible()
-	{
+	public function is_visible() {
 		return $this->visible;
 	}
 
-
-
-	public function set_id ($id)
-	{
+	public function set_id ($id) {
 		$this->id = $id;
 	}
 	
-	public function set_type ($type)
-	{
+	public function set_type ($type) {
 		$this->type = $type;
 	}
 	
-	public function set_ref_id ($ref_id)
-	{
+	public function set_ref_id ($ref_id) {
 		$this->ref_id = $ref_id;
 	}
 	
-	public function set_user_id ($user_id)
-	{
+	public function set_user_id ($user_id) {
 		$this->user_id = $user_id;
 	}
 	
-	public function set_course_code ($course_code)
-	{
+	public function set_course_code ($course_code) {
 		$this->course_code = $course_code;
 	}
 	
-	public function set_category_id ($category_id)
-	{
+	public function set_category_id ($category_id) {
 		$this->category = $category_id;
 	}
 	
-	public function set_date ($date)
-	{
+	public function set_date ($date) {
 		$this->link_date = $date;
 	}
 	
-	public function set_weight ($weight)
-	{
+	public function set_weight ($weight) {
 		$this->weight = $weight;
 	}
 	
-	public function set_visible ($visible)
-	{
+	public function set_visible ($visible) {
 		$this->visible = $visible;
 	}
-	
-    
+	    
 // CRUD FUNCTIONS
 
 	/**
 	 * Retrieve links and return them as an array of extensions of AbstractLink.
 	 * To keep consistency, do not call this method but LinkFactory::load instead.
 	 */
-	public function load ($id = null, $type = null, $ref_id = null, $user_id = null, $course_code = null, $category_id = null, $visible = null)
-	{
+	public function load ($id = null, $type = null, $ref_id = null, $user_id = null, $course_code = null, $category_id = null, $visible = null) {
     	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 		$sql='SELECT id,type,ref_id,user_id,course_code,category_id,date,weight,visible FROM '.$tbl_grade_links;
 		$paramcount = 0;
-		if (isset ($id))
-		{
+		if (isset ($id)) {
 			$sql.= ' WHERE id = '.$id;
 			$paramcount ++;
 		}
-		if (isset ($type))
-		{
+		if (isset ($type)) {
 			if ($paramcount != 0) $sql .= ' AND';
 			else $sql .= ' WHERE';
 			$sql .= ' type = '.$type;
 			$paramcount ++;
 		}
-		if (isset ($ref_id))
-		{
+		if (isset ($ref_id)) {
 			if ($paramcount != 0) $sql .= ' AND';
 			else $sql .= ' WHERE';
 			$sql .= ' ref_id = '.$ref_id;
 			$paramcount ++;
 		}
-		if (isset ($user_id))
-		{
-			if ($paramcount != 0) $sql .= ' AND';
-			else $sql .= ' WHERE';
+		if (isset ($user_id)) {
+			if ($paramcount != 0) {
+			$sql .= ' AND';	
+			}else {
+			 $sql .= ' WHERE';	
+			}
 			$sql .= ' user_id = '.$user_id;
 			$paramcount ++;
 		}
-		if (isset ($course_code))
-		{
-			if ($paramcount != 0) $sql .= ' AND';
-			else $sql .= ' WHERE';
+		if (isset ($course_code)) {
+			if ($paramcount != 0) {
+			 $sql .= ' AND';	
+			} else {
+			 $sql .= ' WHERE';	
+			}
 			$sql .= " course_code = '".$course_code."'";
 			$paramcount ++;
 		}
-		if (isset ($category_id))
-		{
-			if ($paramcount != 0) $sql .= ' AND';
-			else $sql .= ' WHERE';
+		if (isset ($category_id)) {
+			if ($paramcount != 0) {
+				$sql .= ' AND';
+			}else {
+			 	$sql .= ' WHERE';	
+			}
 			$sql .= ' category_id = '.$category_id;
 			$paramcount ++;
 		}
-		if (isset ($visible))
-		{
-			if ($paramcount != 0) $sql .= ' AND';
-			else $sql .= ' WHERE';
+		if (isset ($visible)) {
+			if ($paramcount != 0) {
+				$sql .= ' AND';
+			} else {
+				 $sql .= ' WHERE';
+			}
 			$sql .= ' visible = '.$visible;
 			$paramcount ++;
 		}
 
 		$result = api_sql_query($sql, __FILE__, __LINE__);
-		$links = AbstractLink::create_objects_from_mysql_result($result);
+		$links = AbstractLink::create_objects_from_sql_result($result);
 		return $links;
 	}
     
-    private function create_objects_from_mysql_result($result)
-    {
+    private function create_objects_from_sql_result($result) {
     	$links=array();
-		while ($data=mysql_fetch_array($result))
-		{
+		while ($data=Database::fetch_array($result)) {
 			$link = LinkFactory::create(intval($data['type']));
 			$link->set_id($data['id']);
 			$link->set_type($data['type']);
@@ -209,44 +211,47 @@ abstract class AbstractLink implements GradebookItem
 		return $links;
     }
     
+    public function set_session_id($id) {
+    	$this->session_id = $id;
+    }
+    
     /**
      * Insert this link into the database
      */
-    public function add()
-	{
+    public function add() {
 		$this->add_linked_data();
-
-		if (isset($this->type) && isset($this->ref_id) && isset($this->user_id) && isset($this->course_code)
-		 && isset($this->category) && isset($this->weight) && isset($this->visible))
-		{
+		
+		if (isset($this->type) && isset($this->ref_id) && isset($this->user_id) && isset($this->course_code) && isset($this->category) && isset($this->weight) && isset($this->visible)) {
 			$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+			$sql_testing="select count(*) from ".$tbl_grade_links." where ref_id=".$this->get_ref_id()." AND category_id =  ".$this->category." AND type =  ".$this->type." ;";
+			$result_testing=api_sql_query($sql_testing,__FILE__,__LINE__);
+			$row_testing=Database::fetch_array($result_testing);
 			
-			$sql = 'INSERT INTO '.$tbl_grade_links
-					.' (type,ref_id,user_id,course_code,category_id,weight,visible';
-			if (isset($this->link_date)) $sql .= ',date';
-			$sql .= ') VALUES ('
-					.$this->get_type()
-					.','.$this->get_ref_id()
-					.','.$this->get_user_id()
-					.",'".$this->get_course_code()."'"
-					.','.$this->get_category_id()
-					.','.$this->get_weight()
-					.','.$this->is_visible();
-			if (isset($this->link_date)) $sql .= ','.$this->get_date();
+			if ($row_testing[0]==0) {
+				$sql = 'INSERT INTO '.$tbl_grade_links.' (type,ref_id,user_id,course_code,category_id,weight,visible';
+				if (isset($this->link_date)) { $sql .= ',date';} 
+					$sql .= ') VALUES ('
+						.$this->get_type()
+						.','.$this->get_ref_id()
+						.','.$this->get_user_id()
+						.",'".$this->get_course_code()."'"
+						.','.$this->get_category_id()
+						.','.$this->get_weight()
+						.','.$this->is_visible();
+				if (isset($this->link_date)) {$sql .= ','.$this->get_date();} 
 			$sql .= ")";
-
 			api_sql_query($sql, __FILE__, __LINE__);
-			$this->set_id(mysql_insert_id());
-		}
-		else
+			$this->set_id(Database::insert_id());
+		 	}
+		} else {
 			die('Error in AbstractLink add: required field empty');
+		}
 	}
 	
 	/**
 	 * Update the properties of this link in the database
 	 */
-	public function save()
-	{
+	public function save() {
 		$this->save_linked_data();
 
 		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
@@ -257,24 +262,33 @@ abstract class AbstractLink implements GradebookItem
 				.", course_code = '".$this->get_course_code()."'"
 				.', category_id = '.$this->get_category_id()
 				.', date = ';
-		if (isset($this->link_date))
-			$sql .= $this->get_date();
-		else
-			$sql .= 'null';
-
+		if (isset($this->link_date)) {
+			$sql .= $this->get_date();		
+		} else {
+			$sql .= 'null';			
+		}
 		$sql .= ', weight = '.$this->get_weight()
 				.', visible = '.$this->is_visible()
 				.' WHERE id = '.$this->id;
+		AbstractLink::add_link_log($this->id);
 		api_sql_query($sql, __FILE__, __LINE__);
 	}
 	
+	public function add_link_log($idevaluation) {
+		$tbl_grade_linkeval_log = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);
+		$dateobject=AbstractLink::load ($idevaluation,null,null,null,null);
+		$arreval=get_object_vars($dateobject[0]);
+		$sql="INSERT INTO ".$tbl_grade_linkeval_log."(id_linkeval_log,name,description,date_log,weight,visible,type,user_id_log)VALUES('".$arreval['id']."','".$arreval['course_code']."','".$arreval['description']."','".$arreval['link_date']."','".$arreval['weight']."','".$arreval['visible']."','Link',".api_get_user_id().")";
+		api_sql_query($sql,__FILE__,__LINE__);
+	
+	}	
 	/**
 	 * Delete this link from the database
 	 */
-	public function delete()
-	{
+	public function delete() {
+		
 		$this->delete_linked_data();
-
+		
 		$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 		$sql = 'DELETE FROM '.$tbl_grade_links.' WHERE id = '.$this->id;
 		api_sql_query($sql, __FILE__, __LINE__);
@@ -289,16 +303,14 @@ abstract class AbstractLink implements GradebookItem
 	 * to disable this element.
 	 * @return array 2-dimensional array - every element contains 3 subelements (id, name, level)
 	 */
-    public function get_target_categories()
-    {
+    public function get_target_categories() {
     	// links can only be moved to categories inside this course
 
 		$targets = array();
 		$level = 0;
 
 		$crscats = Category::load(null,null,$this->get_course_code(),0);
-		foreach ($crscats as $cat)
-		{
+		foreach ($crscats as $cat) {
 			$targets[] = array ($cat->get_id(), $cat->get_name(), $level+1);
 			$targets = $this->add_target_subcategories($targets, $level+1, $cat->get_id());
 		}
@@ -309,11 +321,9 @@ abstract class AbstractLink implements GradebookItem
     /**
 	 * Internal function used by get_target_categories()
 	 */
-	private function add_target_subcategories($targets, $level, $catid)
-	{
+	private function add_target_subcategories($targets, $level, $catid) {
 		$subcats = Category::load(null,null,null,$catid);
-		foreach ($subcats as $cat)
-		{
+		foreach ($subcats as $cat) {
 			$targets[] = array ($cat->get_id(), $cat->get_name(), $level+1);
 			$targets = $this->add_target_subcategories($targets, $level+1, $cat->get_id());
 		}
@@ -324,14 +334,10 @@ abstract class AbstractLink implements GradebookItem
 	 * Move this link to the given category.
 	 * If this link moves to outside a course, delete it.
 	 */
-    public function move_to_cat($cat)
-    {
-		if ($this->get_course_code() != $cat->get_course_code())
-		{
+    public function move_to_cat($cat) {
+		if ($this->get_course_code() != $cat->get_course_code()) {
 			$this->delete();
-		}
-		else
-		{
+		} else {
 			$this->set_category_id($cat->get_id());
 			$this->save();
 		}
@@ -343,15 +349,14 @@ abstract class AbstractLink implements GradebookItem
 	 * To keep consistency, do not call this method but LinkFactory::find_links instead.
      * @todo can be written more efficiently using a new (but very complex) sql query
      */
-    public function find_links ($name_mask,$selectcat)
-    {
+    public function find_links ($name_mask,$selectcat) {
     	$rootcat = Category::load($selectcat); 
 		$links = $rootcat[0]->get_links((api_is_allowed_to_create_course() ? null : api_get_user_id()), true);
 		$foundlinks = array();
-		foreach ($links as $link)
-		{
-			if (!(strpos(strtolower($link->get_name()), strtolower($name_mask)) === false))
-				$foundlinks[] = $link;
+		foreach ($links as $link) {
+			if (!(strpos(strtolower($link->get_name()), strtolower($name_mask)) === false)) {
+				$foundlinks[] = $link;				
+			}
 		}
 		return $foundlinks;
     }
@@ -359,17 +364,13 @@ abstract class AbstractLink implements GradebookItem
 
 // Other methods implementing GradebookItem
 
-	public function get_item_type()
-	{
+	public function get_item_type() {
 		return 'L';
 	}
 
-	public function get_icon_name()
-	{
+	public function get_icon_name() {
 		return 'link';
 	}
-
-
 // ABSTRACT FUNCTIONS - to be implemented by subclass
     
     abstract function has_results();
@@ -388,47 +389,32 @@ abstract class AbstractLink implements GradebookItem
 	abstract function needs_results();
 	abstract function is_allowed_to_change_name();
 
-
 // TRIVIAL FUNCTIONS - to be overwritten by subclass if needed
-
-	public function get_not_created_links()
-	{
+	public function get_not_created_links() {
 		return null;
 	}
-	public function get_all_links()
-	{
+	public function get_all_links() {
 		return null;
 	}
 
-	public function add_linked_data()
-	{
+	public function add_linked_data() {
 	}
 	
-	public function save_linked_data()
-	{
+	public function save_linked_data() {
 	}
 	
-	public function delete_linked_data()
-	{
+	public function delete_linked_data() {
 	}
 
-
-	public function set_name ($name)
-	{
+	public function set_name ($name) {
 	}
 	
-	public function set_description ($description)
-	{
+	public function set_description ($description) {
 	}
 	
-	public function set_max ($max)
-	{
+	public function set_max ($max) {
 	}
-	
-	public function get_view_url ($stud_id)
-	{
+	public function get_view_url ($stud_id) {
 		return null;
 	}
-
-}
-?>
+}

File diff suppressed because it is too large
+ 299 - 275
main/gradebook/lib/be/category.class.php


+ 34 - 24
main/gradebook/lib/be/dropboxlink.class.php

@@ -1,8 +1,30 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Gradebook link to dropbox item
- * @author Bert Steppé
+ * @author Bert Steppé
  * @package dokeos.gradebook
  */
 class DropboxLink extends EvalLink
@@ -14,16 +36,14 @@ class DropboxLink extends EvalLink
 
 // CONSTRUCTORS
 
-    function DropboxLink()
-    {
+    function DropboxLink() {
     	$this->set_type(LINK_DROPBOX);
     }
 
 
 // FUNCTIONS IMPLEMENTING ABSTRACTLINK
 
-	public function get_view_url ($stud_id)
-	{
+	public function get_view_url ($stud_id) {
 		// find a file uploaded by the given student,
 		// with the same title as the evaluation name
 
@@ -32,11 +52,10 @@ class DropboxLink extends EvalLink
 		$sql = 'SELECT filename'
 				.' FROM '.$this->get_dropbox_table()
 				.' WHERE uploader_id = '.$stud_id
-				." AND title = '".mysql_real_escape_string($eval->get_name())."'";
+				." AND title = '".Database::escape_string($eval->get_name())."'";
 
 		$result = api_sql_query($sql, __FILE__, __LINE__);
-		if ($fileurl = mysql_fetch_row($result))
-		{
+		if ($fileurl = Database::fetch_row($result)) {
 	    	$course_info = Database :: get_course_info($this->get_course_code());
 
 			$url = api_get_path(WEB_PATH)
@@ -46,19 +65,16 @@ class DropboxLink extends EvalLink
 					.$fileurl[0];
 
 			return $url;
+		} else {
+			return null;			
 		}
-		else
-			return null;
-		
 	}
 
-    public function get_type_name()
-    {
+    public function get_type_name() {
     	return get_lang('DokeosDropbox');
     }
     
-	public function is_allowed_to_change_name()
-	{
+	public function is_allowed_to_change_name() {
 		return false;
 	}
 
@@ -68,18 +84,12 @@ class DropboxLink extends EvalLink
     /**
      * Lazy load function to get the dropbox database table
      */
-    private function get_dropbox_table ()
-    {
-    	if (!isset($this->dropbox_table))
-    	{
+    private function get_dropbox_table () {
+    	if (!isset($this->dropbox_table)) {
 	    	$course_info = Database :: get_course_info($this->get_course_code());
 			$database_name = $course_info['db_name'];
 			$this->dropbox_table = Database :: get_course_table(TABLE_DROPBOX_FILE, $database_name);
     	}
    		return $this->dropbox_table;
     }
-
-
-	
-}
-?>
+}

+ 73 - 81
main/gradebook/lib/be/evallink.class.php

@@ -1,8 +1,30 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Class to be used as basis for links referring to Evaluation objects.
- * @author Bert Steppé
+ * @author Bert Steppé
  * @package dokeos.gradebook
  */
 abstract class EvalLink extends AbstractLink
@@ -13,30 +35,23 @@ abstract class EvalLink extends AbstractLink
 	/**
 	 * Constructor
 	 */
-    function EvalLink()
-    {
+    function EvalLink() {
 
     }
-
-
 // Functions implementing AbstractLink
 
-    public function has_results()
-    {
+    public function has_results() {
     	$eval = $this->get_evaluation();
 		return $eval->has_results();
     }
     
-    public function calc_score($stud_id = null)
-    {
+    public function calc_score($stud_id = null) {
     	$eval = $this->get_evaluation();
 		return $eval->calc_score($stud_id);
     }
 
-	public function get_link()
-	{
+	public function get_link() {
     	$eval = $this->get_evaluation();
-
 		// course/platform admin can go to the view_results page
 		if (api_is_allowed_to_create_course())
 			return 'gradebook_view_result.php?selecteval=' . $eval->get_id();
@@ -47,110 +62,95 @@ abstract class EvalLink extends AbstractLink
 			return null;
 	}
 	
-
-    public function get_name()
-    {
+    public function get_name() {
     	$eval = $this->get_evaluation();
     	return $eval->get_name();
     }
     
-    public function get_description()
-    {
+    public function get_description() {
     	$eval = $this->get_evaluation();
     	return $eval->get_description();
     }
     
-    public function get_max()
-    {
+    public function get_max() {
     	$eval = $this->get_evaluation();
     	return $eval->get_max();
     }
 
-    public function is_valid_link()
-    {
+    public function is_valid_link() {
     	$eval = $this->get_evaluation();
     	return (isset($eval));
     }
-
-
-	public function needs_name_and_description()
-	{
+	public function needs_name_and_description() {
 		return true;
 	}
 	
-	public function needs_max()
-	{
+	public function needs_max() {
 		return true;
 	}
 
-	public function needs_results()
-	{
+	public function needs_results() {
 		return true;
 	}
 
 
-	public function add_linked_data()
-	{
-		if ($this->is_valid_link())
-		{
+	public function add_linked_data() {
+		if ($this->is_valid_link()) {
 			$this->evaluation->add();
 			$this->set_ref_id($this->evaluation->get_id());
 		}
 	}
 	
-	public function save_linked_data()
-	{
-		if ($this->is_valid_link())
-			$this->evaluation->save();
+	public function save_linked_data() {
+		if ($this->is_valid_link()) {
+			$this->evaluation->save();			
+		}
 	}
 	
-	public function delete_linked_data()
-	{
-		if ($this->is_valid_link())
-			$this->evaluation->delete_with_results();
+	public function delete_linked_data() {
+		if ($this->is_valid_link()) {
+			$this->evaluation->delete_with_results();			
+		}
 	}
 
 
-	public function set_name ($name)
-	{
-		if ($this->is_valid_link())
-			$this->evaluation->set_name($name);
+	public function set_name ($name) {
+		if ($this->is_valid_link()) {
+			$this->evaluation->set_name($name);			
+		}
 	}
 	
-	public function set_description ($description)
-	{
-		if ($this->is_valid_link())
-			$this->evaluation->set_description($description);
+	public function set_description ($description) {
+		if ($this->is_valid_link()) {
+			$this->evaluation->set_description($description);			
+		}
 	}
 	
-	public function set_max ($max)
-	{
-		if ($this->is_valid_link())
-			$this->evaluation->set_max($max);
+	public function set_max ($max) {
+		if ($this->is_valid_link()) {
+			$this->evaluation->set_max($max);		
+		}
 	}
-
-
 // Functions overriding non-trivial implementations from AbstractLink
-
-	public function set_date ($date)
-	{
+	public function set_date ($date) {
 		$this->link_date = $date;
-		if ($this->is_valid_link())
-			$this->evaluation->set_date($date);
+		if ($this->is_valid_link()) {
+			$this->evaluation->set_date($date);			
+		}
 	}
 	
-	public function set_weight ($weight)
-	{
+	public function set_weight ($weight) {
 		$this->weight = $weight;
-		if ($this->is_valid_link())
-			$this->evaluation->set_weight($weight);
+		if ($this->is_valid_link()) {
+			$this->evaluation->set_weight($weight);			
+		}
 	}
 	
-	public function set_visible ($visible)
-	{
+	public function set_visible ($visible) {
 		$this->visible = $visible;
-		if ($this->is_valid_link())
-			$this->evaluation->set_visible($visible);
+		if ($this->is_valid_link()) {
+			$this->evaluation->set_visible($visible);			
+		}
 	}
 
 
@@ -160,17 +160,12 @@ abstract class EvalLink extends AbstractLink
 	/**
 	 * Lazy load function to get the linked evaluation
 	 */
-	protected function get_evaluation ()
-	{
-		if (!isset($this->evaluation))
-		{
-			if (isset($this->ref_id))
-			{
+	protected function get_evaluation () {
+		if (!isset($this->evaluation)) {
+			if (isset($this->ref_id)) {
 		    	$evalarray = Evaluation::load($this->get_ref_id());
 				$this->evaluation = $evalarray[0];
-			}
-			else
-			{
+			} else {
 				$eval = new Evaluation();
 				$eval->set_category_id(-1);
 				$eval->set_date(time()); // these values will be changed
@@ -186,7 +181,4 @@ abstract class EvalLink extends AbstractLink
 		}
 		return $this->evaluation;
 	}
-	
-
-}
-?>
+}

+ 180 - 183
main/gradebook/lib/be/evaluation.class.php

@@ -1,9 +1,30 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Defines a gradebook Evaluation object
- * @author Bert Stepp�, Stijn Konings
+ * @author Bert Steppé, Stijn Konings
  * @package dokeos.gradebook
  */
 class Evaluation implements GradebookItem
@@ -21,112 +42,91 @@ class Evaluation implements GradebookItem
 	private $weight;
 	private $eval_max;
 	private $visible;
-
+	
 // CONSTRUCTORS
 
-    function Evaluation()
-    {
+    function Evaluation() {
     }
 
 // GETTERS AND SETTERS
 
-   	public function get_id()
-	{
+   	public function get_id() {
 		return $this->id;
 	}
 
-	public function get_name()
-	{
+	public function get_name() {
 		return $this->name;
 	}
 
-	public function get_description()
-	{
+	public function get_description() {
 		return $this->description;
 	}
 
-	public function get_user_id()
-	{
+	public function get_user_id() {
 		return $this->user_id;
 	}
 
-	public function get_course_code()
-	{
+	public function get_course_code() {
 		return $this->course_code;
 	}
 
-	public function get_category_id()
-	{
+	public function get_category_id() {
 		return $this->category;
 	}
 
-	public function get_date()
-	{
+	public function get_date() {
 		return $this->eval_date;
 	}
 
-	public function get_weight()
-	{
+	public function get_weight() {
 		return $this->weight;
 	}
 
-	public function get_max()
-	{
+	public function get_max() {
 		return $this->eval_max;
 	}
 
-	public function is_visible()
-	{
+	public function is_visible() {
 		return $this->visible;
 	}
 
-	public function set_id ($id)
-	{
+	public function set_id ($id) {
 		$this->id = $id;
 	}
 	
-	public function set_name ($name)
-	{
+	public function set_name ($name) {
 		$this->name = $name;
 	}
 	
-	public function set_description ($description)
-	{
+	public function set_description ($description) {
 		$this->description = $description;
 	}
 	
-	public function set_user_id ($user_id)
-	{
+	public function set_user_id ($user_id) {
 		$this->user_id = $user_id;
 	}
 	
-	public function set_course_code ($course_code)
-	{
+	public function set_course_code ($course_code) {
 		$this->course_code = $course_code;
 	}
 	
-	public function set_category_id ($category_id)
-	{
+	public function set_category_id ($category_id) {
 		$this->category = $category_id;
 	}
 	
-	public function set_date ($date)
-	{
+	public function set_date ($date) {
 		$this->eval_date = $date;
 	}
 	
-	public function set_weight ($weight)
-	{
+	public function set_weight ($weight) {
 		$this->weight = $weight;
 	}
 	
-	public function set_max ($max)
-	{
+	public function set_max ($max) {
 		$this->eval_max = $max;
 	}
 	
-	public function set_visible ($visible)
-	{
+	public function set_visible ($visible) {
 		$this->visible = $visible;
 	}
     
@@ -146,34 +146,29 @@ class Evaluation implements GradebookItem
     	$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 		$sql='SELECT id,name,description,user_id,course_code,category_id,date,weight,max,visible FROM '.$tbl_grade_evaluations;
 		$paramcount = 0;
-		if (isset ($id))
-		{
+		if (isset ($id)) {
 			$sql.= ' WHERE id = '.$id;
 			$paramcount ++;
 		}
-		if (isset ($user_id))
-		{
+		if (isset ($user_id)) {
 			if ($paramcount != 0) $sql .= ' AND';
 			else $sql .= ' WHERE';
 			$sql .= ' user_id = '.$user_id;
 			$paramcount ++;
 		}
-		if (isset ($course_code))
-		{
+		if (isset ($course_code)) {
 			if ($paramcount != 0) $sql .= ' AND';
 			else $sql .= ' WHERE';
 			$sql .= " course_code = '".$course_code."'";
 			$paramcount ++;
 		}
-		if (isset ($category_id))
-		{
+		if (isset ($category_id)) {
 			if ($paramcount != 0) $sql .= ' AND';
 			else $sql .= ' WHERE';
 			$sql .= ' category_id = '.$category_id;
 			$paramcount ++;
 		}
-		if (isset ($visible))
-		{
+		if (isset ($visible)) {
 			if ($paramcount != 0) $sql .= ' AND';
 			else $sql .= ' WHERE';
 			$sql .= ' visible = '.$visible;
@@ -181,15 +176,14 @@ class Evaluation implements GradebookItem
 		}
 
 		$result = api_sql_query($sql, __FILE__, __LINE__);
-		$alleval = Evaluation::create_evaluation_objects_from_mysql_result($result);
+		$alleval = Evaluation::create_evaluation_objects_from_sql_result($result);
 		return $alleval;
 	}
-    
-    private function create_evaluation_objects_from_mysql_result($result)
+   
+    private function create_evaluation_objects_from_sql_result($result)
     {
     	$alleval=array();
-		while ($data=mysql_fetch_array($result))
-		{	
+		while ($data=Database::fetch_array($result)) {	
 			$eval= new Evaluation();
 			$eval->set_id($data['id']);
 			$eval->set_name($data['name']);
@@ -211,79 +205,106 @@ class Evaluation implements GradebookItem
      */
     public function add()
 	{
-		if (isset($this->name) && isset($this->user_id) && isset($this->weight) && isset ($this->eval_max) && isset($this->visible))
-		{
+		if (isset($this->name) && isset($this->user_id) && isset($this->weight) && isset ($this->eval_max) && isset($this->visible)) {
 			$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 			
 			$sql = 'INSERT INTO '.$tbl_grade_evaluations
 					.' (name,user_id,weight,max,visible';
-			if (isset($this->description)) $sql .= ',description';
-			if (isset($this->course_code)) $sql .= ',course_code';
-			if (isset($this->category)) $sql .= ',category_id';
-			if (isset($this->eval_date)) $sql .= ',date';
-			$sql .= ") VALUES ('".mysql_real_escape_string($this->get_name())."'"
+			if (isset($this->description)) {
+			 $sql .= ',description';	
+			}
+			if (isset($this->course_code)) {
+			 $sql .= ',course_code';
+			}
+			if (isset($this->category)) {
+			 $sql .= ',category_id';
+			}
+			if (isset($this->eval_date)) {
+			  $sql .= ',date';
+			}
+			$sql .= ") VALUES ('".Database::escape_string($this->get_name())."'"
 					.','.$this->get_user_id()
 					.','.$this->get_weight()
 					.','.$this->get_max()
 					.','.$this->is_visible();
-			if (isset($this->description)) $sql .= ",'".mysql_real_escape_string($this->get_description())."'";
-			if (isset($this->course_code)) $sql .= ",'".$this->get_course_code()."'";
-			if (isset($this->category)) $sql .= ','.$this->get_category_id();
-			if (isset($this->eval_date)) $sql .= ','.$this->get_date();
+			if (isset($this->description)) {
+				 $sql .= ",'".Database::escape_string($this->get_description())."'";
+			}
+			if (isset($this->course_code)) {
+				 $sql .= ",'".$this->get_course_code()."'";
+			}
+			if (isset($this->category)) {
+				 $sql .= ','.$this->get_category_id();
+			}
+			if (isset($this->eval_date)) {
+				 $sql .= ','.$this->get_date();
+			}
 			$sql .= ")";
 
 			api_sql_query($sql, __FILE__, __LINE__);
-			$this->set_id(mysql_insert_id());
+			$this->set_id(Database::insert_id());
+		}
+		else {
+			die('Error in Evaluation add: required field empty');			
 		}
-		else
-			die('Error in Evaluation add: required field empty');
 	}
+
+	public function add_evaluation_log($idevaluation){
 	
+		$tbl_grade_linkeval_log = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINKEVAL_LOG);
+		$eval=new Evaluation();
+		$dateobject=$eval->load ($idevaluation,null,null,null,null);
+		$arreval=get_object_vars($dateobject[0]);
+		$sql="INSERT INTO ".$tbl_grade_linkeval_log."(id_linkeval_log,name,description,date_log,weight,visible,type,user_id_log)VALUES('".$arreval['id']."','".$arreval['name']."','".$arreval['description']."','".$arreval['eval_date']."','".$arreval['weight']."','".$arreval['visible']."','evaluation',".api_get_user_id().")";
+		api_sql_query($sql,__FILE__,__LINE__);
+	}
 	/**
 	 * Update the properties of this evaluation in the database
 	 */
-	public function save()
-	{
+	public function save() {
 		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 		$sql = 'UPDATE '.$tbl_grade_evaluations
-			." SET name = '".mysql_real_escape_string($this->get_name())."'"
+			." SET name = '".Database::escape_string($this->get_name())."'"
 			.', description = ';
-		if (isset($this->description))
-			$sql .= "'".mysql_real_escape_string($this->get_description())."'";
-		else
-			$sql .= 'null';
-
+		if (isset($this->description)) {
+			$sql .= "'".Database::escape_string($this->get_description())."'";			
+		}else {
+			$sql .= 'null';		
+		}
 		$sql .= ', user_id = '.$this->get_user_id()
 				.', course_code = ';
-		if (isset($this->course_code))
-			$sql .= "'".$this->get_course_code()."'";
-		else
-			$sql .= 'null';
-		
+		if (isset($this->course_code)) {
+			$sql .= "'".$this->get_course_code()."'";			
+		} else {
+			$sql .= 'null';			
+		}
 		$sql .= ', category_id = ';
-		if (isset($this->category))
-			$sql .= $this->get_category_id();
-		else
-			$sql .= 'null';
-
+		if (isset($this->category)) {
+			$sql .= $this->get_category_id();			
+		} else {
+			$sql .= 'null';			
+		}
 		$sql .= ', date = ';
-		if (isset($this->eval_date))
-			$sql .= $this->get_date();
-		else
-			$sql .= 'null';
-
+		if (isset($this->eval_date)) {
+			$sql .= $this->get_date();		
+		} else {
+			$sql .= 'null';		
+		}
 		$sql .= ', weight = '.$this->get_weight()
 				.', max = '.$this->get_max()
 				.', visible = '.$this->is_visible()
 				.' WHERE id = '.$this->id;
+		//recorded history
+		$eval_log=new Evaluation();
+		$eval_log->add_evaluation_log($this->id);
 		api_sql_query($sql, __FILE__, __LINE__);
+	
 	}
 	
 	/**
 	 * Delete this evaluation from the database
 	 */
-	public function delete()
-	{
+	public function delete() {
 		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
 		$sql = 'DELETE FROM '.$tbl_grade_evaluations.' WHERE id = '.$this->id;
 		api_sql_query($sql, __FILE__, __LINE__);
@@ -296,10 +317,8 @@ class Evaluation implements GradebookItem
 	 * @param $name name to check (if not given, the name property of this object will be checked)
 	 * @param $parent parent category
 	 */
-	public function does_name_exist($name, $parent)
-	{
-		if (!isset ($name))
-		{
+	public function does_name_exist($name, $parent) {
+		if (!isset ($name)) {
 			$name = $this->name;
 			$parent = $this->category;
 		}
@@ -308,32 +327,31 @@ class Evaluation implements GradebookItem
 			 .' FROM '.$tbl_grade_evaluations
 			 ." WHERE name = '".$name."'";
 			 
-		if (api_is_allowed_to_create_course()) // && !api_is_platform_admin())
-		{
+		if (api_is_allowed_to_create_course()) {
 			$parent = Category::load($parent);
 			$code = $parent[0]->get_course_code();
-			if (isset($code) && $code != '0')
-			{
+			if (isset($code) && $code != '0') {
 				$main_course_user_table = Database :: get_main_table(TABLE_MAIN_COURSE_USER);			
 				$sql .= ' AND user_id IN ('
 						.' SELECT user_id FROM '.$main_course_user_table
 						." WHERE course_code = '".$code."'"
 						.' AND status = '.COURSEMANAGER
 						.')';
+			} else {
+				$sql .= ' AND user_id = '.api_get_user_id();				
 			}
-			else
-				$sql .= ' AND user_id = '.api_get_user_id();
+
+		}else {
+			$sql .= ' AND user_id = '.api_get_user_id();			
 		}
-		else
-			$sql .= ' AND user_id = '.api_get_user_id();
 			 
-		if (!isset ($parent))
-			$sql.= ' AND category_id is null';
-		else
-			$sql.= ' AND category_id = '.$parent;
-
+		if (!isset ($parent)) {
+			$sql.= ' AND category_id is null';			
+		} else {
+			$sql.= ' AND category_id = '.$parent;			
+		}
     	$result = api_sql_query($sql, __FILE__, __LINE__);
-		$number=mysql_fetch_row($result);
+		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
 	}
 
@@ -341,13 +359,12 @@ class Evaluation implements GradebookItem
 	 * Are there any results for this evaluation yet ?
 	 * The 'max' property should not be changed then.
 	 */
-    public function has_results()
-    {
+    public function has_results() {
     	$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 		$sql='SELECT count(id) AS number FROM '.$tbl_grade_results
 			.' WHERE evaluation_id = '.$this->id;
     	$result = api_sql_query($sql, __FILE__, __LINE__);
-		$number=mysql_fetch_row($result);
+		$number=Database::fetch_row($result);
 
 		return ($number[0] != 0);
     }
@@ -363,7 +380,7 @@ class Evaluation implements GradebookItem
 		$sql="SELECT count(id) AS number FROM ".$tbl_grade_results
 			." WHERE evaluation_id = ".$this->id." AND user_id = ".$stud_id;
     	$result = api_sql_query($sql, __FILE__, __LINE__);
-		$number=mysql_fetch_row($result);
+		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
     }
     */
@@ -372,8 +389,7 @@ class Evaluation implements GradebookItem
     /**
      * Delete all results for this evaluation
      */
-    public function delete_results()
-    {
+    public function delete_results() {
 		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 		$sql = 'DELETE FROM '.$tbl_grade_results.' WHERE evaluation_id = '.$this->id;
 		api_sql_query($sql, __FILE__, __LINE__);
@@ -383,8 +399,7 @@ class Evaluation implements GradebookItem
     /**
      * Delete this evaluation and all underlying results.
      */
-    public function delete_with_results()
-    {
+    public function delete_with_results(){
     	$this->delete_results();
     	$this->delete();
     }
@@ -393,8 +408,7 @@ class Evaluation implements GradebookItem
     /**
      * Check if the given score is possible for this evaluation
      */
-    public function is_valid_score ($score)
-    {
+    public function is_valid_score ($score) {
     	return (is_numeric($score) && $score >= 0 && $score <= $this->eval_max);
     }
     
@@ -406,45 +420,41 @@ class Evaluation implements GradebookItem
 	 * 			array (sum of scores, number of scores) otherwise
 	 * 			or null if no scores available
 	 */
-    public function calc_score ($stud_id = null)
-    {
+    public function calc_score ($stud_id = null) {
 		$results = Result::load(null,$stud_id,$this->id);
 		
 		$rescount = 0;
 		$sum = 0;
-		foreach ($results as $res)
-		{
+		foreach ($results as $res) {
 			$score = $res->get_score();
-			if ((!empty ($score)) || ($score == '0'))
-			{
+			if ((!empty ($score)) || ($score == '0')) {
 				$rescount++;
 				$sum += ($score / $this->get_max());
 			}
 		}
 		
-		if ($rescount == 0)
-			return null;
-		else if (isset($stud_id))
-			return array ($score, $this->get_max());
-		else
-			return array ($sum, $rescount);
+		if ($rescount == 0) {
+			return null;			
+		}
+		else if (isset($stud_id)) {
+			return array ($score, $this->get_max());			
+		} else {
+			return array ($sum, $rescount);			
+		}
+
     }
-    
-    
-    
+        
     /**
 	 * Generate an array of possible categories where this evaluation can be moved to.
 	 * Notice: its own parent will be included in the list: it's up to the frontend
 	 * to disable this element.
 	 * @return array 2-dimensional array - every element contains 3 subelements (id, name, level)
 	 */
-	public function get_target_categories()
-	{
+	public function get_target_categories() {
 		// - course independent evaluation
 		//   -> movable to root or other course independent categories
 		// - evaluation inside a course
 		//   -> movable to root, independent categories or categories inside the course
-
 		$user = (api_is_platform_admin() ? null : api_get_user_id());
 		$targets = array();
 		$level = 0;
@@ -452,19 +462,16 @@ class Evaluation implements GradebookItem
 		$root = array(0, get_lang('RootCat'), $level);
 		$targets[] = $root;
 
-		if (isset($this->course_code) && !empty($this->course_code))
-		{
+		if (isset($this->course_code) && !empty($this->course_code)) {
 			$crscats = Category::load(null,null,$this->course_code,0);
-			foreach ($crscats as $cat)
-			{
+			foreach ($crscats as $cat) {
 				$targets[] = array ($cat->get_id(), $cat->get_name(), $level+1);
 				$targets = $this->add_target_subcategories($targets, $level+1, $cat->get_id());
 			}
 		}
 
 		$indcats = Category::load(null,$user,0,0);
-		foreach ($indcats as $cat)
-		{
+		foreach ($indcats as $cat) {
 			$targets[] = array ($cat->get_id(), $cat->get_name(), $level+1);
 			$targets = $this->add_target_subcategories($targets, $level+1, $cat->get_id());
 		}
@@ -475,11 +482,9 @@ class Evaluation implements GradebookItem
 	/**
 	 * Internal function used by get_target_categories()
 	 */
-	private function add_target_subcategories($targets, $level, $catid)
-	{
+	private function add_target_subcategories($targets, $level, $catid) {
 		$subcats = Category::load(null,null,null,$catid);
-		foreach ($subcats as $cat)
-		{
+		foreach ($subcats as $cat) {
 			$targets[] = array ($cat->get_id(), $cat->get_name(), $level+1);
 			$targets = $this->add_target_subcategories($targets, $level+1, $cat->get_id());
 		}
@@ -492,11 +497,9 @@ class Evaluation implements GradebookItem
 	 * If this evaluation moves from inside a course to outside,
 	 * its course code is also changed.
 	 */
-	public function move_to_cat ($cat)
-	{
+	public function move_to_cat ($cat) {
 		$this->set_category_id($cat->get_id());
-		if ($this->get_course_code() != $cat->get_course_code())
-		{
+		if ($this->get_course_code() != $cat->get_course_code()) {
 			$this->set_course_code($cat->get_course_code());
 		}
 		$this->save();
@@ -510,8 +513,7 @@ class Evaluation implements GradebookItem
 	 * @param $cat_id parent category (use 'null' to retrieve them in all categories)
 	 * @param $stud_id student id
 	 */
-    public function get_evaluations_with_result_for_student ($cat_id = null, $stud_id)
-    {
+    public function get_evaluations_with_result_for_student ($cat_id = null, $stud_id) {
 		$tbl_grade_evaluations = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_EVALUATION);
     	$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 
@@ -519,17 +521,17 @@ class Evaluation implements GradebookItem
 				.' WHERE id IN'
 				.'(SELECT evaluation_id FROM '.$tbl_grade_results
 				.' WHERE user_id = '.$stud_id.' AND score IS NOT NULL)';
-		if (!api_is_allowed_to_create_course())
-			$sql .= ' AND visible = 1';
-		if (isset($cat_id))
-			$sql .= ' AND category_id = '.$cat_id;
-		else
-			$sql .= ' AND category_id >= 0';
-
+		if (!api_is_allowed_to_create_course()) {
+			$sql .= ' AND visible = 1';			
+		}
+		if (isset($cat_id)) {
+			$sql .= ' AND category_id = '.$cat_id;			
+		} else {
+			$sql .= ' AND category_id >= 0';			
+		}
 
 		$result = api_sql_query($sql, __FILE__, __LINE__);
-		$alleval = Evaluation::create_evaluation_objects_from_mysql_result($result);
-		
+		$alleval = Evaluation::create_evaluation_objects_from_sql_result($result);
 		return $alleval;
     }
     
@@ -538,8 +540,7 @@ class Evaluation implements GradebookItem
     /**
      * Get a list of students that do not have a result record for this evaluation
      */
-    public function get_not_subscribed_students ($first_letter_user = '')
-    {
+    public function get_not_subscribed_students ($first_letter_user = '') {
 		$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
     	$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 
@@ -564,15 +565,14 @@ class Evaluation implements GradebookItem
      * @return array evaluation objects matching the search criterium
      * @todo can be written more efficiently using a new (but very complex) sql query
      */
-    public function find_evaluations ($name_mask,$selectcat)
-    {
+    public function find_evaluations ($name_mask,$selectcat) {
     	$rootcat = Category::load($selectcat); 
 		$evals = $rootcat[0]->get_evaluations((api_is_allowed_to_create_course() ? null : api_get_user_id()), true);
 		$foundevals = array();
-		foreach ($evals as $eval)
-		{
-			if (!(strpos(strtolower($eval->get_name()), strtolower($name_mask)) === false))
-				$foundevals[] = $eval;
+		foreach ($evals as $eval) {
+			if (!(strpos(strtolower($eval->get_name()), strtolower($name_mask)) === false)) {
+				$foundevals[] = $eval;				
+			}
 		}
 		return $foundevals;
     }
@@ -581,15 +581,12 @@ class Evaluation implements GradebookItem
     
 // Other methods implementing GradebookItem
 
-    public function get_item_type()
-	{
+    public function get_item_type() {
 		return 'E';
 	}
     
-	public function get_icon_name()
-	{
+	public function get_icon_name() {
 		return $this->has_results() ? 'evalnotempty' : 'evalempty';
 	}
     
-}
-?>
+}

+ 75 - 81
main/gradebook/lib/be/exerciselink.class.php

@@ -1,9 +1,30 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Defines a gradebook ExerciseLink object.
- * @author Bert Stepp�
+ * @author Bert Steppé
  * @package dokeos.gradebook
  */
 class ExerciseLink extends AbstractLink
@@ -19,8 +40,7 @@ class ExerciseLink extends AbstractLink
 
 // CONSTRUCTORS
 
-    function ExerciseLink()
-    {
+    function ExerciseLink() {
     	$this->set_type(LINK_EXERCISE);
     }
 
@@ -31,11 +51,10 @@ class ExerciseLink extends AbstractLink
 	 * Generate an array of exercises that a teacher hasn't created a link for.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_not_created_links()
-    {
-    	if (empty($this->course_code))
-    		die('Error in get_not_created_links() : course code not set');
-    	
+    public function get_not_created_links() {
+    	if (empty($this->course_code)) {
+     	die('Error in get_not_created_links() : course code not set');  		
+    	}
     	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
 
 		$sql = 'SELECT id,title from '.$this->get_exercise_table()
@@ -46,10 +65,8 @@ class ExerciseLink extends AbstractLink
 				.')';
 
 		$result = api_sql_query($sql, __FILE__, __LINE__);
-
 		$cats=array();
-		while ($data=mysql_fetch_array($result))
-		{
+		while ($data=Database::fetch_array($result)) {
 			$cats[] = array ($data['id'], $data['title']);
 		}
 		return $cats;
@@ -58,20 +75,17 @@ class ExerciseLink extends AbstractLink
 	 * Generate an array of all exercises available.
 	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
 	 */
-    public function get_all_links()
-    {
-    	if (empty($this->course_code))
-    		die('Error in get_not_created_links() : course code not set');
-    	
+    public function get_all_links() {
+    	if (empty($this->course_code)) {
+    		die('Error in get_not_created_links() : course code not set');  		
+    	}
     	$course_info = api_get_course_info($this->course_code);
     	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK,$course_info['dbName']);
-
-		$sql = 'SELECT id,title from '.$this->get_exercise_table();
+		$sql = 'SELECT id,title from '.$this->get_exercise_table().' where active=1';
 		$result = api_sql_query($sql, __FILE__, __LINE__);
 
 		$cats=array();
-		while ($data=mysql_fetch_array($result))
-		{
+		while ($data=Database::fetch_array($result)) {
 			$cats[] = array ($data['id'], $data['title']);
 		}
 		return $cats;
@@ -80,14 +94,13 @@ class ExerciseLink extends AbstractLink
     /**
      * Has anyone done this exercise yet ?
      */
-    public function has_results()
-    {
+    public function has_results() {
     	$tbl_stats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
 		$sql = 'SELECT count(exe_id) AS number FROM '.$tbl_stats
 				." WHERE exe_cours_id = '".$this->get_course_code()."'"
 				.' AND exe_exo_id = '.$this->get_ref_id();
     	$result = api_sql_query($sql, __FILE__, __LINE__);
-		$number=mysql_fetch_row($result);
+		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
     }
     
@@ -98,44 +111,37 @@ class ExerciseLink extends AbstractLink
 	 * 			array (sum of scores, number of scores) otherwise
 	 * 			or null if no scores available
 	 */
-    public function calc_score($stud_id = null)
-    {
+    public function calc_score($stud_id = null) {
     	$tbl_stats = Database::get_statistic_table(TABLE_STATISTIC_TRACK_E_EXERCICES);
     	$sql = 'SELECT * FROM '.$tbl_stats
     			." WHERE exe_cours_id = '".$this->get_course_code()."'"
     			.' AND exe_exo_id = '.$this->get_ref_id();
     	
-    	if (isset($stud_id))
-    		$sql .= ' AND exe_user_id = '.$stud_id;
-    		
+    	if (isset($stud_id)) {
+     	$sql .= ' AND exe_user_id = '.$stud_id;  		
+    	}
     	// order by id, that way the student's first attempt is accessed first
 		$sql .= ' ORDER BY exe_id';
 
     	$scores = api_sql_query($sql, __FILE__, __LINE__);
 
 		// for 1 student
-    	if (isset($stud_id))
-    	{
-    		if ($data=mysql_fetch_array($scores))
-    			return array ($data['exe_result'], $data['exe_weighting']);
-    		else
-    			return null;
-    	}
-    	
-    	// all students -> get average
-    	else
-    	{
+    	if (isset($stud_id)) {
+    		if ($data=Database::fetch_array($scores)) {
+    			return array ($data['exe_result'], $data['exe_weighting']);    			
+    		} else {
+     			return null;   			
+    		}
+
+    	} else {// all students -> get average
     		$students=array();  // user list, needed to make sure we only
     							// take first attempts into account
 			$rescount = 0;
 			$sum = 0;
 
-			while ($data=mysql_fetch_array($scores))
-			{
-				if (!(array_key_exists($data['exe_user_id'],$students)))
-				{
-					if ($data['exe_weighting'] != 0)
-					{
+			while ($data=Database::fetch_array($scores)) {
+				if (!(array_key_exists($data['exe_user_id'],$students))) {
+					if ($data['exe_weighting'] != 0) {
 						$students[$data['exe_user_id']] = $data['exe_result'];
 						$rescount++;
 						$sum += ($data['exe_result'] / $data['exe_weighting']);
@@ -143,10 +149,12 @@ class ExerciseLink extends AbstractLink
 				}
 			}
 
-			if ($rescount == 0)
-				return null;
-			else
-				return array ($sum , $rescount);
+			if ($rescount == 0) {
+				return null;				
+			} else {
+				return array ($sum , $rescount);				
+			}
+
     	}
     }
     
@@ -155,22 +163,20 @@ class ExerciseLink extends AbstractLink
      * First we go to exercise_jump.php and then to the result page.
      * Check this php file for more info.
      */
-	public function get_link()
-	{
+	public function get_link() {
 		$url = api_get_path(WEB_PATH)
-			.'main/gradebook/exercise_jump.php?cid='.$this->get_course_code();
+			.'main/gradebook/exercise_jump.php?cidReq='.$this->get_course_code().'&gradebook=view&exerciseId='.$this->get_ref_id();
 		if (!api_is_allowed_to_create_course()
-			&& $this->calc_score(api_get_user_id()) == null)
-		$url .= '&amp;doexercise='.$this->get_ref_id();
-		
+			&& $this->calc_score(api_get_user_id()) == null) {
+		  $url .= '&amp;doexercise='.$this->get_ref_id();
+        }
 		return $url;
 	}
     
     /**
      * Get name to display: same as exercise title
      */
-    public function get_name()
-    {
+    public function get_name() {
     	$data = $this->get_exercise_data();
     	return $data['title'];
     }
@@ -178,8 +184,7 @@ class ExerciseLink extends AbstractLink
     /**
      * Get description to display: same as exercise description
      */
-    public function get_description()
-    {
+    public function get_description() {
     	$data = $this->get_exercise_data();
     	return $data['description'];
     }
@@ -187,37 +192,31 @@ class ExerciseLink extends AbstractLink
     /**
      * Check if this still links to an exercise
      */
-    public function is_valid_link()
-    {
+    public function is_valid_link() {
     	$sql = 'SELECT count(id) from '.$this->get_exercise_table()
 				.' WHERE id = '.$this->get_ref_id();
 		$result = api_sql_query($sql, __FILE__, __LINE__);
-		$number=mysql_fetch_row($result);
+		$number=Database::fetch_row($result);
 		return ($number[0] != 0);
     }
     
-    public function get_type_name()
-    {
+    public function get_type_name() {
     	return get_lang('DokeosExercises');
     }
     
-	public function needs_name_and_description()
-	{
+	public function needs_name_and_description() {
 		return false;
 	}
 	
-	public function needs_max()
-	{
+	public function needs_max() {
 		return false;
 	}
 
-	public function needs_results()
-	{
+	public function needs_results() {
 		return false;
 	}
 
-	public function is_allowed_to_change_name()
-	{
+	public function is_allowed_to_change_name() {
 		return false;
 	}
 
@@ -227,8 +226,7 @@ class ExerciseLink extends AbstractLink
     /**
      * Lazy load function to get the database table of the exercise
      */
-    private function get_exercise_table ()
-    {
+    private function get_exercise_table () {
     	if (!isset($this->exercise_table))
     	{
 	    	$course_info = Database :: get_course_info($this->get_course_code());
@@ -241,18 +239,14 @@ class ExerciseLink extends AbstractLink
     /**
      * Lazy load function to get the database contents of this exercise
      */
-    private function get_exercise_data()
-    {
+    private function get_exercise_data () {
     	if (!isset($this->exercise_data))
     	{
 			$sql = 'SELECT * from '.$this->get_exercise_table()
 					.' WHERE id = '.$this->get_ref_id();
 			$result = api_sql_query($sql, __FILE__, __LINE__);
-			$this->exercise_data=mysql_fetch_array($result);
+			$this->exercise_data=Database::fetch_array($result);
     	}
     	return $this->exercise_data;
     }
-    
-    
-}
-?>
+}

+ 255 - 0
main/gradebook/lib/be/forumthreadlink.class.php

@@ -0,0 +1,255 @@
+<?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+ * Gradebook link to student publication item
+ * @author Bert Steppé
+ * @package dokeos.gradebook
+ */
+class ForumThreadLink extends AbstractLink
+{
+
+// INTERNAL VARIABLES
+
+    private $forum_thread_table = null;
+    private $itemprop_table = null;
+
+
+// CONSTRUCTORS
+
+    function ForumThreadLink() {
+    	$this->set_type(LINK_FORUM_THREAD);
+    }
+
+    public function get_type_name() {
+    	return get_lang('ForumThreads');
+    }
+    
+
+	public function is_allowed_to_change_name() {
+		return false;
+	}
+
+
+// FUNCTIONS IMPLEMENTING ABSTRACTLINK
+
+	/**
+	 * Generate an array of exercises that a teacher hasn't created a link for.
+	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
+	 */
+    public function get_not_created_links() {
+    	if (empty($this->course_code)) {
+    		die('Error in get_not_created_links() : course code not set');    		
+    	}
+    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+
+		$sql = 'SELECT thread_id,thread_title,thread_title_qualify from '.$this->get_forum_thread_table()
+				.' WHERE thread_id NOT IN'
+				.' (SELECT ref_id FROM '.$tbl_grade_links
+				.' WHERE type = '.LINK_FORUM_THREAD
+				." AND course_code = '".$this->get_course_code()."'"
+				.')';
+
+		$result = api_sql_query($sql, __FILE__, __LINE__);
+
+		$cats=array();
+		while ($data=Database::fetch_array($result)) {
+			if ( isset($data['thread_title_qualify']) and $data['thread_title_qualify']!=""){
+				$cats[] = array ($data['thread_id'], $data['thread_title_qualify']);
+			} else {
+				$cats[] = array ($data['thread_id'], $data['thread_title']);
+			}
+		}
+		return $cats;
+    }
+	/**
+	 * Generate an array of all exercises available.
+	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
+	 */
+    public function get_all_links() {
+    	if (empty($this->course_code)) {
+    		die('Error in get_not_created_links() : course code not set');    		
+    	}
+    	$course_info = api_get_course_info($this->course_code);
+    	$tbl_grade_links = Database :: get_course_table(TABLE_FORUM_THREAD,$course_info['dbName']);
+    	$tbl_item_property=Database :: get_course_table(TABLE_ITEM_PROPERTY,$course_info['dbName']);
+		$sql = 'SELECT tl.thread_id,tl.thread_title,tl.thread_title_qualify FROM '.$tbl_grade_links.' tl ,'.$tbl_item_property.' ip where tl.thread_id=ip.ref and ip.tool="forum_thread" and ip.visibility<>2 group by ip.ref';
+		$result = api_sql_query($sql, __FILE__, __LINE__);
+		
+		while ($data=Database::fetch_array($result)) {
+			if ( isset($data['thread_title_qualify']) and $data['thread_title_qualify']!=""){
+				$cats[] = array ($data['thread_id'], $data['thread_title_qualify']);
+			} else {
+				$cats[] = array ($data['thread_id'], $data['thread_title']);
+			}
+		}
+		return $cats;
+    }
+      
+
+    /**
+     * Has anyone done this exercise yet ?
+     */
+    public function has_results() {
+    	$course_info = api_get_course_info($this->course_code);
+    	$tbl_grade_links = Database :: get_course_table(TABLE_FORUM_POST,$course_info['dbName']);
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." WHERE thread_id = '".$this->get_ref_id()."'";
+    	$result = api_sql_query($sql, __FILE__, __LINE__);
+		$number=Database::fetch_row($result);
+		return ($number[0] != 0);
+    }
+
+  public function calc_score($stud_id = null) {
+    	$course_info = Database :: get_course_info($this->get_course_code());
+		$database_name = (empty($course_info['db_name']))?$course_info['dbName']:$course_info['db_name'];
+		$thread_qualify = Database :: get_course_table('forum_thread_qualify', $database_name);
+
+  		$sql = 'SELECT thread_qualify_max FROM '.Database :: get_course_table(TABLE_FORUM_THREAD, $database_name)." WHERE thread_id = '".$this->get_ref_id()."'";
+		$query = api_sql_query($sql,__FILE__,__LINE__);
+		$assignment = Database::fetch_array($query);
+  	
+  	    $sql = 'SELECT * FROM '.$thread_qualify.' WHERE thread_id = '.$this->get_ref_id();
+    	
+    	if (isset($stud_id)){
+    		$sql .= ' AND user_id = '."'".$stud_id."'";
+    	}
+    		
+    	// order by id, that way the student's first attempt is accessed first
+		$sql .= ' ORDER BY qualify_time DESC';
+		 
+    	$scores = api_sql_query($sql, __FILE__, __LINE__);
+
+		// for 1 student
+    	if (isset($stud_id))
+    	{
+    		if ($data=Database::fetch_array($scores)) {
+    			return array ($data['qualify'], $assignment['thread_qualify_max']);    			
+    		} else {
+      			return null;  			
+    		}
+    	} else {// all students -> get average
+    		$students=array();  // user list, needed to make sure we only
+    							// take first attempts into account
+			$rescount = 0;
+			$sum = 0;
+
+			while ($data=Database::fetch_array($scores)) {
+				if (!(array_key_exists($data['user_id'],$students))) {
+					if ($assignment['thread_qualify_max'] != 0) {
+						$students[$data['user_id']] = $data['qualify'];
+						$rescount++;
+						$sum += ($data['qualify'] / $assignment['thread_qualify_max']);
+					}
+				 }
+			 }
+
+			if ($rescount == 0) {
+				return null;				
+			  } else {
+				return array ($sum , $rescount);				
+			 }
+
+    	}
+    }
+      
+// INTERNAL FUNCTIONS
+    
+    /**
+     * Lazy load function to get the database table of the student publications
+     */
+    private function get_forum_thread_table () {
+    	if (!isset($this->forum_thread_table)) {
+	    	$course_info = Database :: get_course_info($this->get_course_code());
+			$database_name = $course_info['db_name'];
+			$this->forum_thread_table = Database :: get_course_table(TABLE_FORUM_THREAD, $database_name);
+    	}
+   		return $this->forum_thread_table;
+    }
+
+    /**
+     * Lazy load function to get the database table of the item properties
+     */
+    private function get_itemprop_table () {
+    	if (!isset($this->itemprop_table)) {
+	    	$course_info = Database :: get_course_info($this->get_course_code());
+			$database_name = $course_info['db_name'];
+			$this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY, $database_name);
+    	}
+   		return $this->itemprop_table;
+    }
+   
+   	public function needs_name_and_description() {
+		return false;
+	}
+    public function needs_max() {
+        return false;
+    }
+
+    public function needs_results() {
+        return false;
+    }
+    	 
+    public function get_name() {
+    	$this->get_exercise_data();
+    	
+    	if ( isset($this->exercise_data['thread_title_qualify']) and $this->exercise_data['thread_title_qualify']!="") {
+    		return $this->exercise_data['thread_title_qualify'];
+    	} else {
+    		return $this->exercise_data['thread_title'];
+    	}
+    }    
+	
+    public function get_description() {
+    	return '';//$this->exercise_data['description'];
+    } 
+    /**
+     * Check if this still links to an exercise
+     */
+    public function is_valid_link() {
+        $sql = 'SELECT count(id) from '.$this->get_forum_thread_table()
+                .' WHERE thread_id = '.$this->get_ref_id();
+        $result = api_sql_query($sql, __FILE__, __LINE__);
+        $number=Database::fetch_row($result);
+        return ($number[0] != 0);
+    }
+        
+    public function get_test_id() {
+    	return 'DEBUG:ID';
+    } 
+    
+    public function get_link() {
+		$url = api_get_path(WEB_PATH)
+			.'main/forum/viewthread.php?cidReq='.$this->get_course_code().'&thread='.$this->get_ref_id().'&gradebook=view';
+		
+		return $url;
+	}
+	private function get_exercise_data() {
+    	if (!isset($this->exercise_data)) {
+    	$sql = 'SELECT * FROM '.$this->get_forum_thread_table()." WHERE thread_id = '".$this->get_ref_id()."'";
+		$query = api_sql_query($sql,__FILE__,__LINE__);
+		$this->exercise_data = Database::fetch_array($query);
+    	}
+    	return $this->exercise_data;
+    }
+}

+ 23 - 4
main/gradebook/lib/be/gradebookitem.class.php

@@ -1,13 +1,33 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Interface for all displayable items in the gradebook.
- * @author Bert Steppé
+ * @author Bert Steppé
  */
 interface GradebookItem
 {
-
 	public function get_item_type();
 
 	public function get_id();
@@ -22,5 +42,4 @@ interface GradebookItem
 
 	public function calc_score($stud_id = null);
 
-}
-?>
+}

+ 25 - 6
main/gradebook/lib/be/learnpathlink.class.php

@@ -1,4 +1,27 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Defines a gradebook LearnpathLink object.
  * @author Yannick Warnier <yannick.warnier@dokeos.com>
@@ -220,7 +243,6 @@ class LearnpathLink extends AbstractLink
 		return false;
 	}
 
-    
 // INTERNAL FUNCTIONS
     
     /**
@@ -250,8 +272,5 @@ class LearnpathLink extends AbstractLink
 			$this->learnpath_data=Database::fetch_array($result);
     	}
     	return $this->learnpath_data;
-    }
-    
-    
-}
-?>
+    }  
+}

+ 58 - 36
main/gradebook/lib/be/linkfactory.class.php

@@ -1,27 +1,46 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 // To add your new link type here:
 // - define a unique type id
 // - add include
 // - change create() and get_all_types()
-
-
 // Please do not change existing values, they are used in the database !
 define('LINK_EXERCISE',1);
 define('LINK_DROPBOX',2);
 define('LINK_STUDENTPUBLICATION',3);
 define('LINK_LEARNPATH',4);
-
-
-
-include_once('abstractlink.class.php');
-include_once('exerciselink.class.php');
-include_once('evallink.class.php');
-include_once('dropboxlink.class.php');
-include_once('studentpublicationlink.class.php');
-include_once('learnpathlink.class.php');
-
-
+define('LINK_FORUM_THREAD',5);
+//define('LINK_WORK',6);
+require_once('gradebookitem.class.php');
+require_once('abstractlink.class.php');
+require_once('exerciselink.class.php');
+require_once('evallink.class.php');
+require_once('dropboxlink.class.php');
+require_once('studentpublicationlink.class.php');
+require_once('learnpathlink.class.php');
+require_once('forumthreadlink.class.php');
 /**
  * Factory for link objects
  * @author Bert Steppé
@@ -40,8 +59,7 @@ class LinkFactory
 	 * @param $category_id parent category
 	 * @param $visible visible
 	 */
-	public function load ($id = null, $type = null, $ref_id = null, $user_id = null, $course_code = null, $category_id = null, $visible = null)
-	{
+	public function load ($id = null, $type = null, $ref_id = null, $user_id = null, $course_code = null, $category_id = null, $visible = null) {
 		return AbstractLink::load($id, $type, $ref_id, $user_id, $course_code, $category_id, $visible);
 	}
 
@@ -49,25 +67,22 @@ class LinkFactory
 	/**
 	 * Get the link object referring to an evaluation
 	 */
-	public function get_evaluation_link ($eval_id)
-	{
+	public function get_evaluation_link ($eval_id) {
 		$links = AbstractLink :: load(null, null, $eval_id);
-		foreach ($links as $link)
-		{
-			if (is_a($link, 'EvalLink'))
-				return $link;
+		foreach ($links as $link) {
+			if (is_a($link, 'EvalLink')) {
+				return $link;				
+			}
 		}
 		return null;
 	}
 
-
     /**
      * Find links by name
      * @param string $name_mask search string
      * @return array link objects matching the search criterium
      */
-    public function find_links ($name_mask,$selectcat)
-    {
+    public function find_links ($name_mask,$selectcat) {
     	return AbstractLink::find_links($name_mask,$selectcat);
     }
 
@@ -75,26 +90,33 @@ class LinkFactory
 	 * Static method to create specific link objects
 	 * @param $type link type
 	 */
-	public function create ($type)
-	{
-		if ($type == LINK_EXERCISE ) return new ExerciseLink();
-		elseif ($type == LINK_DROPBOX ) return new DropboxLink();
-		elseif ($type == LINK_STUDENTPUBLICATION ) return new StudentPublicationLink();
-		elseif ($type == LINK_LEARNPATH ) return new LearnpathLink();
-		else return null;
+	public function create ($type) {
+		if ($type == LINK_EXERCISE ) { 
+			return new ExerciseLink();
+		} elseif ($type == LINK_DROPBOX ) { 
+			return new DropboxLink();
+		} elseif ($type == LINK_STUDENTPUBLICATION ) {
+			return new StudentPublicationLink();
+		} elseif ($type == LINK_LEARNPATH ) {
+			 return new LearnpathLink();
+		} elseif ($type == LINK_FORUM_THREAD ) {
+			 return new ForumThreadLink();
+		} else {
+			 return null;
+		}
 	}
 
 	/**
 	 * Return an array of all known link types
 	 */
-	public function get_all_types ()
-	{
+	public function get_all_types () {
+		//LINK_DROPBOX,
 		return array (LINK_EXERCISE,
-					  LINK_DROPBOX,
+					  //LINK_DROPBOX,
 					  LINK_STUDENTPUBLICATION,
 					  LINK_LEARNPATH,
+                      LINK_FORUM_THREAD
 					  );
 	}
 
-}
-?>
+}

+ 93 - 59
main/gradebook/lib/be/result.class.php

@@ -1,9 +1,30 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Defines a gradebook Result object
- * @author Bert Stepp�, Stijn Konings
+ * @author Bert Steppé, Stijn Konings
  * @package dokeos.gradebook
  */
 class Result
@@ -19,60 +40,49 @@ class Result
 
 // CONSTRUCTORS
 
-    function Result()
-    {
+    function Result() {
     	$this->creation_date = time();
     }
     
 // GETTERS AND SETTERS
 
-   	public function get_id()
-	{
+   	public function get_id() {
 		return $this->id;
 	}
 
-   	public function get_user_id()
-	{
+   	public function get_user_id() {
 		return $this->user_id;
 	}
 
-   	public function get_evaluation_id()
-	{
+   	public function get_evaluation_id() {
 		return $this->evaluation;
 	}
 
-    public function get_date()
-	{
+    public function get_date() {
 		return $this->creation_date;
 	}
 
-   	public function get_score()
-	{
+   	public function get_score() {
 		return $this->score;
 	}
     
-    public function set_id ($id)
-	{
+    public function set_id ($id) {
 		$this->id = $id;
 	}
 
-   	public function set_user_id ($user_id)
-	{
+   	public function set_user_id ($user_id) {
 		$this->user_id = $user_id;
 	}
 
-   	public function set_evaluation_id ($evaluation_id)
-	{
+   	public function set_evaluation_id ($evaluation_id) {
 		$this->evaluation = $evaluation_id;
 	}
 
-    public function set_date ($creation_date)
-	{
+    public function set_date ($creation_date) {
 		$this->creation_date = $creation_date;
 	}
 
-   	public function set_score ($score)
-	{
+   	public function set_score ($score) {
 		$this->score = $score;
 	}
 
@@ -84,35 +94,32 @@ class Result
 	 * @param $user_id user id (student)
 	 * @param $evaluation_id evaluation where this is a result for
 	 */
-	public function load ($id = null, $user_id = null, $evaluation_id = null)
-	{
+	public function load ($id = null, $user_id = null, $evaluation_id = null) {
 		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 		$sql='SELECT id,user_id,evaluation_id,date,score FROM '.$tbl_grade_results;
 		$paramcount = 0;
-		if (!empty ($id))
-		{
+		if (!empty ($id)) {
 			$sql.= ' WHERE id = '.$id;
 			$paramcount ++;
 		}
-		if (!empty ($user_id))
-		{
+		if (!empty ($user_id)) {
 			if ($paramcount != 0) $sql .= ' AND';
 			else $sql .= ' WHERE';
 			$sql .= ' user_id = '.$user_id;
 			$paramcount ++;
 		}
-		if (!empty ($evaluation_id))
-		{
-			if ($paramcount != 0) $sql .= ' AND';
-			else $sql .= ' WHERE';
+		if (!empty ($evaluation_id)) {
+			if ($paramcount != 0) {
+				$sql .= ' AND';
+			} else {
+			 $sql .= ' WHERE';	
+			}
 			$sql .= ' evaluation_id = '.$evaluation_id;
 			$paramcount ++;
 		}
-		
 		$result = api_sql_query($sql, __FILE__, __LINE__);
 		$allres=array();
-		while ($data=mysql_fetch_array($result))
-		{
+		while ($data=Database::fetch_array($result)) {
 			$res= new Result();
 			$res->set_id($data['id']);
 			$res->set_user_id($data['user_id']);
@@ -127,44 +134,75 @@ class Result
     /**
      * Insert this result into the database
      */
-    public function add()
-	{
-		if (isset($this->user_id) && isset($this->evaluation) && isset($this->creation_date) )
-		{
+    public function add() {
+		if (isset($this->user_id) && isset($this->evaluation) && isset($this->creation_date) ) {
 			$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 			$sql = 'INSERT INTO '.$tbl_grade_results
 					.' (user_id, evaluation_id,
 					date';
-			if (isset($this->score)) $sql .= ',score';
-
+			if (isset($this->score)) {
+			 $sql .= ',score';	
+			}
 			$sql .= ') VALUES
 					('.$this->get_user_id().', '.$this->get_evaluation_id()
 					.', '.$this->get_date();
-			if (isset($this->score)) $sql .= ', '.$this->get_score();
+			if (isset($this->score)) {
+			 $sql .= ', '.$this->get_score();
+			}
 			$sql .= ')';
 
 			api_sql_query($sql, __FILE__, __LINE__);
+		} else {
+			die('Error in Result add: required field empty');			
 		}
-		else
-			die('Error in Result add: required field empty');
+
 	}
-	
+	/**
+	 * insert log result
+	 */
+	 public function add_result__log($userid,$evaluationid){
+
+	 	if (isset($userid) && isset($evaluationid) ) {
+			$tbl_grade_results_log = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT_LOG);
+			$result=new Result();
+
+			$arr_result=$result->load (null, $userid, $evaluationid);
+			$arr=get_object_vars($arr_result[0]);
+			
+			$sql = 'INSERT INTO '.$tbl_grade_results_log
+					.' (id_result,user_id, evaluation_id,
+					date';
+			if (isset($arr['score'])) {
+			 	$sql .= ',score';	
+			}
+				$sql .= ') VALUES
+					('.$arr['id'].','.$arr['user_id'].', '.$arr['evaluation']
+					.', '.$arr['creation_date'];
+			if (isset($arr['score'])) {
+				 $sql .= ', '.$arr['score'];
+			}
+			$sql .= ')';
+
+			api_sql_query($sql, __FILE__, __LINE__);
+		} else {
+			die('Error in Result add: required field empty');			
+		}
+	 }
 	/**
 	 * Update the properties of this result in the database
 	 */
-	public function save()
-	{
+	public function save() {
 		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 		$sql = 'UPDATE '.$tbl_grade_results
 				.' SET user_id = '.$this->get_user_id()
 				.', evaluation_id = '.$this->get_evaluation_id()
 				.', score = ';
 
-		if (isset($this->score))
-			$sql .= $this->get_score();
-		else
-			$sql .= 'null';
-
+		if (isset($this->score)) {
+			$sql .= $this->get_score();			
+		} else {
+			$sql .= 'null';			
+		}
 		$sql .= ' WHERE id = '.$this->id;
 		// no need to update creation date
 		api_sql_query($sql, __FILE__, __LINE__);
@@ -173,13 +211,9 @@ class Result
 	/**
 	 * Delete this result from the database
 	 */
-	public function delete()
-	{
+	public function delete() {
 		$tbl_grade_results = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 		$sql = 'DELETE FROM '.$tbl_grade_results.' WHERE id = '.$this->id;
 		api_sql_query($sql, __FILE__, __LINE__);
 	}
-
-    
-}
-?>
+}

+ 202 - 26
main/gradebook/lib/be/studentpublicationlink.class.php

@@ -1,11 +1,33 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Gradebook link to student publication item
  * @author Bert Steppé
  * @package dokeos.gradebook
  */
-class StudentPublicationLink extends EvalLink
+class StudentPublicationLink extends AbstractLink
 {
 
 // INTERNAL VARIABLES
@@ -16,16 +38,14 @@ class StudentPublicationLink extends EvalLink
 
 // CONSTRUCTORS
 
-    function StudentPublicationLink()
-    {
+    function StudentPublicationLink() {
     	$this->set_type(LINK_STUDENTPUBLICATION);
     }
 
 
 // FUNCTIONS IMPLEMENTING ABSTRACTLINK
 
-	public function get_view_url ($stud_id)
-	{
+	public function get_view_url ($stud_id) {
 		// find a file uploaded by the given student,
 		// with the same title as the evaluation name
 
@@ -37,11 +57,10 @@ class StudentPublicationLink extends EvalLink
 				." WHERE prop.tool = 'work'"
 				.' AND prop.insert_user_id = '.$stud_id
 				.' AND prop.ref = pub.id'
-				." AND pub.title = '".mysql_real_escape_string($eval->get_name())."'";
+				." AND pub.title = '".Database::escape_string($eval->get_name())."'";
 
 		$result = api_sql_query($sql, __FILE__, __LINE__);
-		if ($fileurl = mysql_fetch_row($result))
-		{
+		if ($fileurl = Database::fetch_row($result)) {
 	    	$course_info = Database :: get_course_info($this->get_course_code());
 
 			$url = api_get_path(WEB_PATH)
@@ -51,35 +70,144 @@ class StudentPublicationLink extends EvalLink
 					.$fileurl[0];
 
 			return $url;
+		 } else {
+			return null;		
 		}
-		else
-			return null;
-		
 	}
 	
     
-    public function get_type_name()
-    {
+    public function get_type_name() {
     	return get_lang('DokeosStudentPublications');
     }
     
 
-	public function is_allowed_to_change_name()
-	{
+	public function is_allowed_to_change_name() {
 		return false;
 	}
 
+// FUNCTIONS IMPLEMENTING ABSTRACTLINK
 
-    
+	/**
+	 * Generate an array of exercises that a teacher hasn't created a link for.
+	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
+	 */
+    public function get_not_created_links() {
+    	if (empty($this->course_code)) {
+    		die('Error in get_not_created_links() : course code not set');    		
+    	}
+    	$tbl_grade_links = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+
+		$sql = 'SELECT id,url from '.$this->get_studpub_table()
+				.' WHERE has_properties != '."''".' AND id NOT IN'
+				.' (SELECT ref_id FROM '.$tbl_grade_links
+				.' WHERE type = '.LINK_STUDENTPUBLICATION
+				." AND course_code = '".$this->get_course_code()."'"
+				.')';
+
+		$result = api_sql_query($sql, __FILE__, __LINE__);
+
+		$cats=array();
+		while ($data=Database::fetch_array($result)) {
+			$cats[] = array ($data['id'], $data['url']);
+		}
+		return $cats;
+    }
+	/**
+	 * Generate an array of all exercises available.
+	 * @return array 2-dimensional array - every element contains 2 subelements (id, name)
+	 */
+    public function get_all_links() {
+    	if (empty($this->course_code)) {
+     		die('Error in get_not_created_links() : course code not set');   		
+    	}
+    	$course_info = api_get_course_info($this->course_code);
+    	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION,$course_info['dbName']);
+
+		$sql = 'SELECT id,url FROM '.$tbl_grade_links.' WHERE has_properties != '."'' AND filetype='folder'";
+		$result = api_sql_query($sql, __FILE__, __LINE__);
+		
+		while ($data=Database::fetch_array($result)) {
+			$cats[] = array ($data['id'], $data['url']);
+		}
+		return $cats;
+    }
+
+    /**
+     * Has anyone done this exercise yet ?
+     */
+    public function has_results() {
+    	$course_info = api_get_course_info($this->course_code);
+    	$tbl_grade_links = Database :: get_course_table(TABLE_STUDENT_PUBLICATION,$course_info['dbName']);
+		$sql = 'SELECT count(*) AS number FROM '.$tbl_grade_links." WHERE parent_id = '".$this->get_ref_id()."'";
+    	$result = api_sql_query($sql, __FILE__, __LINE__);
+		$number=Database::fetch_row($result);
+		return ($number[0] != 0);
+    }
+
+
+  public function calc_score($stud_id = null) {
+    	$course_info = Database :: get_course_info($this->get_course_code());
+		$database_name = (empty($course_info['db_name']))?$course_info['dbName']:$course_info['db_name'];
+		$tbl_stats = Database :: get_course_table(TABLE_STUDENT_PUBLICATION, $database_name);
+
+    	$sql = 'SELECT * FROM '.$tbl_stats." WHERE id = '".$this->get_ref_id()."'";
+		$query = api_sql_query($sql,__FILE__,__LINE__);
+		$assignment = Database::fetch_array($query);
+
+    	if(Database::num_rows($assignment)==0) {
+    		 $v_assigment_id ='0';
+    	} else { 
+    		 $v_assigment_id = $assignment['id'];
+    	}
+    	$sql = 'SELECT * FROM '.$tbl_stats.' WHERE parent_id = '.$v_assigment_id;
+    	if (isset($stud_id)){
+    		$sql1='SELECT firstname, lastname FROM '.Database::get_main_table(TABLE_MAIN_USER)." WHERE user_id = '".$stud_id."'";
+     		$query = api_sql_query($sql1,__FILE__,__LINE__);
+			$student = Database::fetch_array($query);
+    		$sql .= ' AND author = '."'".$student['firstname'].' '.$student['lastname']."'";
+    	}
+    	// order by id, that way the student's first attempt is accessed first
+		$sql .= ' ORDER BY id';
+    	$scores = api_sql_query($sql, __FILE__, __LINE__);
+
+		// for 1 student
+    	if (isset($stud_id)) {
+    		if ($data=Database::fetch_array($scores)) {
+     			return array ($data['qualification'], $assignment['qualification']);   			
+    		} else {
+     			return null;   			
+    		}
+    	} else {
+    		$students=array();  // user list, needed to make sure we only
+    							// take first attempts into account
+			$rescount = 0;
+			$sum = 0;
+
+			while ($data=Database::fetch_array($scores)) {
+				if (!(array_key_exists($data['author'],$students))) {
+					if ($assignment['qualification'] != 0) {
+						$students[$data['author']] = $data['qualification'];
+						$rescount++;
+						$sum += ($data['qualification'] / $assignment['qualification']);
+					}
+				}
+			}
+
+			if ($rescount == 0) {
+				return null;				
+			} else {
+				return array ($sum , $rescount);				
+			}
+    	}
+    }
+      
 // INTERNAL FUNCTIONS
     
     /**
      * Lazy load function to get the database table of the student publications
      */
-    private function get_studpub_table ()
-    {
-    	if (!isset($this->studpub_table))
-    	{
+    private function get_studpub_table () {
+    	if (!isset($this->studpub_table)) {
 	    	$course_info = Database :: get_course_info($this->get_course_code());
 			$database_name = $course_info['db_name'];
 			$this->studpub_table = Database :: get_course_table(TABLE_STUDENT_PUBLICATION, $database_name);
@@ -90,17 +218,65 @@ class StudentPublicationLink extends EvalLink
     /**
      * Lazy load function to get the database table of the item properties
      */
-    private function get_itemprop_table ()
-    {
-    	if (!isset($this->itemprop_table))
-    	{
+    private function get_itemprop_table () {
+    	if (!isset($this->itemprop_table)) {
 	    	$course_info = Database :: get_course_info($this->get_course_code());
 			$database_name = $course_info['db_name'];
 			$this->itemprop_table = Database :: get_course_table(TABLE_ITEM_PROPERTY, $database_name);
     	}
    		return $this->itemprop_table;
     }
+   
+   	public function needs_name_and_description() {
+		return false;
+	}
+	 
+    public function get_name() {
+    	$this->get_exercise_data();
+    	return $this->exercise_data['url'];
+    }    
 	
+    public function get_description() {
+    	$this->get_exercise_data();
+    	return $this->exercise_data['description'];
+    } 
+    
+    public function get_test_id() {
+    	return 'DEBUG:ID';
+    } 
+    
+    public function get_link() {
+	$url = api_get_path(WEB_PATH)
+			.'main/work/work.php?cidReq='.$this->get_course_code();
+		if (!api_is_allowed_to_create_course()
+			&& $this->calc_score(api_get_user_id()) == null) {
+		$url .= '&curdirpath=/'.$this->get_ref_id();				
+			}
+		return $url;
+	}
+	
+	private function get_exercise_data() {
+    	if (!isset($this->exercise_data)) {
+    	$sql = 'SELECT * FROM '.$this->get_studpub_table()." WHERE id = '".$this->get_ref_id()."'";
+		$query = api_sql_query($sql,__FILE__,__LINE__);
+		$this->exercise_data = Database::fetch_array($query);
+    	}
+    	return $this->exercise_data;
+    }
+    
+    public function needs_max() {
+		return false;
+	}
+
+	public function needs_results() {
+		return false;
+	}
 
-}
-?>
+    public function is_valid_link() {
+    	$sql = 'SELECT count(id) from '.$this->get_studpub_table()
+				.' WHERE id = '.$this->get_ref_id();
+		$result = api_sql_query($sql, __FILE__, __LINE__);
+		$number=Database::fetch_row($result);
+		return ($number[0] != 0);
+    }
+}

+ 50 - 50
main/gradebook/lib/fe/catform.class.php

@@ -1,7 +1,29 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
 require_once (api_get_path(LIBRARY_PATH).'formvalidator/FormValidator.class.php');
 
 /**
@@ -25,28 +47,19 @@ class CatForm extends FormValidator {
 	 * @param string form name
 	 * @param method method
 	 */
-    function CatForm($form_type, $category_object,$form_name,$method = 'post',$action=null)
-    {
+    function CatForm($form_type, $category_object,$form_name,$method = 'post',$action=null) {
 		parent :: __construct($form_name, $method, $action);
     	$this->form_type = $form_type;
-    	if (isset ($category_object))
-    	{	
+    	if (isset ($category_object)) {	
     		$this->category_object = $category_object;
     	}
-    	if ($this->form_type == self :: TYPE_EDIT)
-    	{
+    	if ($this->form_type == self :: TYPE_EDIT) {
     		$this->build_editing_form();
-    	}
-    	elseif ($this->form_type == self :: TYPE_ADD)
-    	{
+    	} elseif ($this->form_type == self :: TYPE_ADD) {
     		$this->build_add_form();
-    	}
-    	elseif ($this->form_type == self :: TYPE_MOVE)
-    	{
+    	} elseif ($this->form_type == self :: TYPE_MOVE) {
     		$this->build_move_form();
-    	}
-    	elseif ($this->form_type == self :: TYPE_SELECT_COURSE)
-    	{
+    	} elseif ($this->form_type == self :: TYPE_SELECT_COURSE) {
     		$this->build_select_course_form();
     	}
     	$this->setDefaults();
@@ -56,23 +69,21 @@ class CatForm extends FormValidator {
 	 * This function will build a move form that will allow the user to move a category to
 	 * a another
 	 */
-   	protected function build_move_form()
-   	{
+   	protected function build_move_form() {
 		$renderer =& $this->defaultRenderer();
 		$renderer->setElementTemplate('<span>{element}</span> ');
 		$this->addElement('static',null,null,'"'.$this->category_object->get_name().'" ');
 		$this->addElement('static',null,null,get_lang('MoveTo'). ' : ');
 		$select = $this->addElement('select','move_cat',null,null);
-		foreach ($this->category_object->get_target_categories() as $cat)
-		{
-			for ($i=0;$i<$cat[2];$i++)
-			{
+		foreach ($this->category_object->get_target_categories() as $cat) {
+			for ($i=0;$i<$cat[2];$i++) {
 				$line .= '--';
 			}
-			if ($cat[0] != $this->category_object->get_parent_id())
+			if ($cat[0] != $this->category_object->get_parent_id()) {
 				$select->addoption($line.' '.$cat[1],$cat[0]);
-			else
+			} else {
 				$select->addoption($line.' '.$cat[1],$cat[0],'disabled');
+			}	
 			$line = '';
 		}
    		$this->addElement('submit', null, get_lang('Ok'));
@@ -81,31 +92,27 @@ class CatForm extends FormValidator {
 	 * This function builds an 'add category form, if parent id is 0, it will only
 	 * show courses
 	 */
-   	protected function build_add_form()
-   	{
+   	protected function build_add_form() {
 		//check if we are a root category
 		//if so, you can only choose between courses
-		if ($this->category_object->get_parent_id() == '0')
-		{
+		if ($this->category_object->get_parent_id() == '0') {
 			$select = $this->addElement('select','select_course',array(get_lang('PickACourse'),'test'), null);
 			$coursecat = Category :: get_not_created_course_categories(api_get_user_id());
-			if (count($coursecat)==0)
+			if (count($coursecat)==0) {
 				$select->addoption(get_lang('CourseIndependent'),'COURSEINDEPENDENT','disabled');
-				else
+			} else {
 				$select->addoption(get_lang('CourseIndependent'),'COURSEINDEPENDENT');
+			}
 			//only return courses that are not yet created by the teacher
 
-			foreach($coursecat as $row) 
-			{
+			foreach($coursecat as $row) {
 				$select->addoption($row[1],$row[0]);
 			}
    			$this->setDefaults(array(
    			   'hid_user_id' => $this->category_object->get_user_id(),
    			   'hid_parent_id' => $this->category_object->get_parent_id()
    			));		
-		}
-		else
-		{			
+		} else {			
    			$this->setDefaults(array(
    		    'hid_user_id' => $this->category_object->get_user_id(),
    		    'hid_parent_id' => $this->category_object->get_parent_id()
@@ -118,8 +125,7 @@ class CatForm extends FormValidator {
 	/**
 	 * Builds an form to edit a category
 	 */
-   	protected function build_editing_form()
-   	{
+   	protected function build_editing_form() {
    		$this->setDefaults(array(
 			'name' => $this->category_object->get_name(),
     		'description' => $this->category_object->get_description(),
@@ -134,8 +140,7 @@ class CatForm extends FormValidator {
 		$this->build_basic_form();
    	}
    	
-   	private function build_basic_form()
-   	{
+   	private function build_basic_form() {
 		$this->addElement('hidden', 'zero', 0);
 		$this->add_textfield('name', get_lang('CategoryName'),true,array('size'=>'54','maxlength'=>'50'));
 		$this->add_textfield('weight', get_lang('Weight'),true,array('size'=>'4','maxlength'=>'4'));			
@@ -156,14 +161,12 @@ class CatForm extends FormValidator {
 	 * This function builds an 'select course' form in the add category process, 
 	 * if parent id is 0, it will only show courses
 	 */
-   	protected function build_select_course_form()
-   	{
+   	protected function build_select_course_form() {
 		$select = $this->addElement('select','select_course',array(get_lang('PickACourse'),'test'), null);
 		$coursecat = Category :: get_all_courses(api_get_user_id());
 		//only return courses that are not yet created by the teacher
 
-		foreach($coursecat as $row) 
-		{
+		foreach($coursecat as $row) {
 			$select->addoption($row[1],$row[0]);
 		}
 		$this->setDefaults(array(
@@ -175,14 +178,11 @@ class CatForm extends FormValidator {
 		$this->addElement('submit', null, get_lang('Ok'));
    	}
      	
-   	function display()
-   	{
+   	function display() {
    		parent :: display();
    	}
    	
-   	function setDefaults($defaults = array ())
-  	{
+   	function setDefaults($defaults = array ()) {
    		parent :: setDefaults($defaults);
    	}
-}
-?>
+}

+ 28 - 6
main/gradebook/lib/fe/dataform.class.php

@@ -1,8 +1,31 @@
 <?php
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
-include_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
+require_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
 require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php');
 
 /**
@@ -93,5 +116,4 @@ class DataForm extends FormValidator {
 	function setDefaults($defaults = array ()) {
 		parent :: setDefaults($defaults);
 	}
-}
-?>
+}

+ 239 - 127
main/gradebook/lib/fe/displaygradebook.php

@@ -1,10 +1,27 @@
 <?php
 /*
- * Created on 25-apr-07
- *
- * @author Stijn Konings
- * 
- */
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 class DisplayGradebook
 {
 	/**
@@ -14,61 +31,54 @@ class DisplayGradebook
 	* @param $shownavbar 1=show navigation bar
 	* @param $forpdf only output for pdf file
 	*/
-	function display_header_result($evalobj, $selectcat, $shownavbar)
-	{
-		if ($shownavbar == '1')
-		{
-			$header= '<table border=0 cellpadding=5><tr><td>';
-			$header .= '<a href=gradebook.php?selectcat=' . $selectcat . '><img src=../img/lp_leftarrow.gif alt=' . get_lang('BackToOverview') . ' align=absmiddle/> ' . get_lang('BackToOverview') . '</a></td>';
-			if ($evalobj->get_course_code() == null)
-			{
-				$header .= '<td><a href=gradebook_add_user.php?selecteval=' . $evalobj->get_id() . '><img src=../img/add_user_big.gif alt=' . get_lang('AddStudent') . ' align=absmiddle/> ' . get_lang('AddStudent') . '</a></td>';
+	function display_header_result($evalobj, $selectcat, $shownavbar) {
+		if ($shownavbar == '1') {
+			$header= '<table border="0" cellpadding="5"><tr><td>';
+			$header .= '<a href="'.$_SESSION['gradebook_dest'].'?selectcat=' . $selectcat . '"><img src="../img/lp_leftarrow.gif" alt="' . get_lang('BackToOverview') . '" align="absmiddle"/> ' . get_lang('BackToOverview') . '</a></td>';
+			if ($evalobj->get_course_code() == null) {
+				$header .= '<td><a href="gradebook_add_user.php?selecteval=' . $evalobj->get_id() . '"><img src="../img/add_user_big.gif" alt="' . get_lang('AddStudent') . '" align="absmiddle" /> ' . get_lang('AddStudent') . '</a></td>';
 			}
-			elseif (!$evalobj->has_results())
-			{
-				$header .= '<td><a href=gradebook_add_result.php?selectcat=' . $selectcat . '&selecteval=' . $evalobj->get_id() . '><img src=../img/filenew.gif alt=' . get_lang('AddResult') . ' align=absmiddle/> ' . get_lang('AddResult') . '</a></td>';
+			elseif (!$evalobj->has_results()) {
+				$header .= '<td><a href="gradebook_add_result.php?selectcat=' . $selectcat . '&selecteval=' . $evalobj->get_id() . '"><img src="../img/filenew.gif" alt="' . get_lang('AddResult') . '" align="absmiddle"/> ' . get_lang('AddResult') . '</a></td>';
 			}
-			$header .= '<td><a href=' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&import=><img src="../img/calendar_down.gif" border="0" alt="" />' . ' ' . get_lang('ImportResult') . '</a></td>';
-			if ($evalobj->has_results())
-			{
-				$header .= '<td><a href=' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&export=><img src="../img/calendar_up.gif" border="0" alt="" />' . ' ' . get_lang('ExportResult') . '</a></td>';
-				$header .= '<td><a href=gradebook_edit_result.php?selecteval=' . $evalobj->get_id() .'><img src=../img/works.gif alt=' . get_lang('EditResult') . ' align=absmiddle/> ' . get_lang('EditResult') . '</a></td>';
-				$header .= '<td><a href=' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&deleteall= onclick="return confirmationall();"><img src="../img/delete.gif" border="0" alt="" />' . ' ' . get_lang('DeleteResult') . '</a></td>';
+			$header .= '<td><a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&import="><img src="../img/calendar_down.gif" border="0" alt="" />' . ' ' . get_lang('ImportResult') . '</a></td>';
+			if ($evalobj->has_results()) {
+				$header .= '<td><a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&export="><img src="../img/calendar_up.gif" border="0" alt="" />' . ' ' . get_lang('ExportResult') . '</a></td>';
+				$header .= '<td><a href="gradebook_edit_result.php?selecteval=' . $evalobj->get_id() .'"><img src="../img/works.gif" alt="' . get_lang('EditResult') . '" align="absmiddle" /> ' . get_lang('EditResult') . '</a></td>';
+				$header .= '<td><a href="' . api_get_self() . '?&selecteval=' . $evalobj->get_id() . '&deleteall=" onclick="return confirmationall();"><img src="../img/delete.gif" border="0" alt="" />' . ' ' . get_lang('DeleteResult') . '</a></td>';
 			}
-			$header .= '<td><a href=' . api_get_self() . '?print=&selecteval=' . $evalobj->get_id() . ' target="_blank"><img src=../img/printmgr.gif alt=' . get_lang('Print') . '/> ' . get_lang('Print') . '</a>';
+			$header .= '<td><a href="' . api_get_self() . '?print=&selecteval=' . $evalobj->get_id() . '" target="_blank"><img src="../img/printmgr.gif" alt="' . get_lang('Print') . '" /> ' . get_lang('Print') . '</a>';
 			$header .= '</td></tr></table>';
 		}
-		if ($evalobj->is_visible() == '1')
-		{
+		if ($evalobj->is_visible() == '1') {
 			$visible= get_lang('Yes');
-		} else
-		{
+		} else {
 			$visible= get_lang('No');
 		}
 		
 		$scoredisplay = ScoreDisplay :: instance(); 
-		if (($evalobj->has_results())) // TODO this check needed ?
-		{
+		if (($evalobj->has_results())){ // TODO this check needed ?
 			
 			$score= $evalobj->calc_score();
 			if ($score != null)
 				$average= get_lang('Average') . ' :<b> ' .$scoredisplay->display_score($score,SCORE_AVERAGE) . '</b>';
 		}
-		if (!$evalobj->get_description() == '')
-		{
+		if (!$evalobj->get_description() == '') {
 			$description= get_lang('Description') . ' :<b> ' . $evalobj->get_description() . '</b><br>';
 		}
-		if ($evalobj->get_course_code() == null)
+		if ($evalobj->get_course_code() == null) {
 			$course= get_lang('CourseIndependent');
-		else
+		} else {
 			$course= get_course_name_from_code($evalobj->get_course_code());
-		$evalinfo= '<table width=100% border=0><tr><td>';
+		}
+
+		$evalinfo= '<table width="100%" border="0"><tr><td>';
 		$evalinfo .= get_lang('EvaluationName') . ' :<b> ' . $evalobj->get_name() . ' </b>(' . date('j/n/Y g:i', $evalobj->get_date()) . ')<br>' . get_lang('Course') . ' :<b> ' . $course . '</b><br>' . get_lang('Weight') . ' :<b> ' . $evalobj->get_weight() . '</b><br>' . get_lang('Max') . ' :<b> ' . $evalobj->get_max() . '</b><br>' . $description . get_lang('Visible') . ' :<b> ' . $visible . '</b><br>' . $average;
 		if (!$evalobj->has_results())
-			$evalinfo .= '<br><i>' . get_lang('NoResultsInEvaluation') . '</i>';
+			$evalinfo .= '<br /><i>' . get_lang('NoResultsInEvaluation') . '</i>';
 		elseif ($scoredisplay->is_custom() && api_get_self() != '/dokeos/main/gradebook/gradebook_statistics.php')
-			$evalinfo .= '<br><br><a href="gradebook_statistics.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'"> '. get_lang('ViewStatistics') . '</a>';
-		$evalinfo .= '</td><td align=right><img src="../img/tutorial.gif"></img></td></table>';
+			$evalinfo .= '<br /><br /><a href="gradebook_statistics.php?selecteval='.Security::remove_XSS($_GET['selecteval']).'"> '. get_lang('ViewStatistics') . '</a>';
+		$evalinfo .= '</td><td align="right"><img src="../img/tutorial.gif"></img></td></table>';
 		Display :: display_normal_message($evalinfo,false);
 		echo $header;
 
@@ -79,160 +89,263 @@ class DisplayGradebook
 	* @param $showeval
 	* @param $showlink
 	*/
-	function display_header_flatview($catobj, $showeval, $showlink,$simple_search_form)
-	{
-		$header= '<table border=0 cellpadding=5>';
-		$header .= '<td style="vertical-align: top;"><a href=gradebook.php?selectcat=' . Security::remove_XSS($_GET['selectcat']) . '><< ' . get_lang('BackToOverview') . '</a></td>';
-		$header .= '<td style="vertical-align: top;">' . get_lang('FilterCategory') . '</td><td style="vertical-align: top;"><form name=selector><select name=selectcat onchange="document.selector.submit()">';
+	function display_header_flatview($catobj, $showeval, $showlink,$simple_search_form) {
+		$header= '<table border="0" cellpadding="5">';
+		$header .= '<td style="vertical-align: top;"><a href="'.$_SESSION['gradebook_dest'].'?selectcat=' . Security::remove_XSS($_GET['selectcat']) . '"><< ' . get_lang('BackToOverview') . '</a></td>';
+		$header .= '<td style="vertical-align: top;">' . get_lang('FilterCategory') . '</td><td style="vertical-align: top;"><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
 		$cats= Category :: load();
 		$tree= $cats[0]->get_tree();
 		unset ($cats);
-		foreach ($tree as $cat)
-		{
-			for ($i= 0; $i < $cat[2]; $i++)
-			{
+		foreach ($tree as $cat) {
+			for ($i= 0; $i < $cat[2]; $i++) {
 				$line .= '&mdash;';
 			}
-			if ($_GET['selectcat'] == $cat[0])
-			{
-				$header .= '<option selected value=' . $cat[0] . '>' . $line . ' ' . $cat[1] . '</option>';
-			} else
-			{
+			if ($_GET['selectcat'] == $cat[0]) {
+				$header .= '<option selected="selected" value=' . $cat[0] . '>' . $line . ' ' . $cat[1] . '</option>';
+			} else {
 				$header .= '<option value=' . $cat[0] . '>' . $line . ' ' . $cat[1] . '</option>';
 			}
 			$line= '';
 		}
 		$header .= '</td></select></form>';
-		if (!$catobj->get_id() == '0')
-			$header .= '<td style="vertical-align: top;"><a href=' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '><img src="../img/folder_up.gif" border="0" alt="'.get_lang('Up').'" /></a></td>';
+		if (!$catobj->get_id() == '0') {
+			$header .= '<td style="vertical-align: top;"><a href="' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '"><img src="../img/folder_up.gif" border="0" alt="'.get_lang('Up').'" /></a></td>';
+		}
 		$header .= '<td style="vertical-align: top;">'.$simple_search_form->toHtml().'</td>';
 		$header .= '<td style="vertical-align: top;"><a href="' . api_get_self() . '?exportpdf=&offset='.Security::remove_XSS($_GET['offset']).'&search=' . Security::remove_XSS($_GET['search']).'&selectcat=' . $catobj->get_id() . '"><img src=../img/calendar_up.gif alt=' . get_lang('ExportPDF') . '/> ' . get_lang('ExportPDF') . '</a>';
 		$header .= '<td style="vertical-align: top;"><a href="' . api_get_self() . '?print=&selectcat=' . $catobj->get_id() . '" target="_blank"><img src="../img/printmgr.gif" alt=' . get_lang('Print') . '/> ' . get_lang('Print') . '</a>';
 		$header .= '</td></tr></table>';
-		if (!$catobj->get_id() == '0')
-		{
-			$header .= '<table border=0 cellpadding=5><tr><td><form name=itemfilter method=post action=' . api_get_self() . '?selectcat=' . $catobj->get_id() . '><input type="checkbox" name=showeval onclick="document.itemfilter.submit()" ' . (($showeval == '1') ? 'checked' : '') . '>Show Evaluations &nbsp;';
-			$header .= '<input type="checkbox" name=showlink onclick="document.itemfilter.submit()" ' . (($showlink == '1') ? 'checked' : '') . '>Show Links</form></td></tr></table>';
+		if (!$catobj->get_id() == '0') {
+			$header .= '<table border="0" cellpadding="5"><tr><td><form name="itemfilter" method="post" action="' . api_get_self() . '?selectcat=' . $catobj->get_id() . '"><input type="checkbox" name="showeval" onclick="document.itemfilter.submit()" ' . (($showeval == '1') ? 'checked' : '') . '>Show Evaluations &nbsp;';
+			$header .= '<input type="checkbox" name="showlink" onclick="document.itemfilter.submit()" ' . (($showlink == '1') ? 'checked' : '') . '>'.get_lang('ShowLinks').'</form></td></tr></table>';
 		}
-		if (isset ($_GET['search']))
+		if (isset ($_GET['search'])) {
 			$header .= '<b>'.get_lang('SearchResults').' :</b>';
+		}
 		echo $header;
 	}
+	
+		/**
+	* Displays the header for the flatview page containing filters
+	* @param $catobj
+	* @param $showeval
+	* @param $showlink
+	*/
+	function display_header_reduce_flatview($catobj, $showeval, $showlink,$simple_search_form) {
+		$header= '<table border="0" cellpadding="5">';
+		$header .= '<td style="vertical-align: top;"><a href="index.php' . '"><< ' . get_lang('BackToOverview') . '</a></td>';
+		
+
+//		$header .= '<td style="vertical-align: top;"><a href="' . api_get_self() . '?exportpdf=&offset='.Security::remove_XSS($_GET['offset']).'&search=' . Security::remove_XSS($_GET['search']).'&selectcat=' . $catobj->get_id() . '"><img src=../img/calendar_up.gif alt=' . get_lang('ExportPDF') . '/> ' . get_lang('ExportPDF') . '</a>';
+
+		// this MUST be a GET variable not a POST
+		echo '<form id="form1a" name="form1a" method="post" action="'.api_get_self().'?show='.Security::remove_XSS($_GET['show']).'">';
+		echo '<input type="hidden" name="export_report" value="export_report">';
+		echo '<input type="hidden" name="selectcat" value="'.$catobj->get_id() .'">';
+		
+		echo '<input type="hidden" name="export_format" value="csv">';
+		echo '</form>';
+		
+		echo '<form id="form1b" name="form1b" method="post" action="'.api_get_self().'?show='.Security::remove_XSS($_GET['show']).'">';
+		echo '<input type="hidden" name="export_report" value="export_report">';
+		echo '<input type="hidden" name="selectcat" value="'.$catobj->get_id() .'">';
+		echo '<input type="hidden" name="export_format" value="xls">';
+		echo '</form>';
+			
+		$header .= '<td style="vertical-align: top;"><a class="quiz_export_link" href="#" onclick="document.form1a.submit();"><img align="absbottom" src="'.api_get_path(WEB_IMG_PATH).'excel.gif" alt="'.get_lang('ExportAsCSV').'">&nbsp;'.get_lang('ExportAsCSV').'</a></td>';
+		$header .= '<td style="vertical-align: top;"><a class="quiz_export_link" href="#" onclick="document.form1b.submit();"><img align="absbottom" src="'.api_get_path(WEB_IMG_PATH).'excel.gif" alt="'.get_lang('ExportAsXLS').'">&nbsp;'.get_lang('ExportAsXLS').'</a></td>';
+	
+		$header .= '<td style="vertical-align: top;"><a href="' . api_get_self() . '?print=&selectcat=' . $catobj->get_id() . '" target="_blank"><img src="../img/printmgr.gif" alt=' . get_lang('Print') . '/> ' . get_lang('Print') . '</a>';
+		$header .= '</td></tr></table>';
+		
+		if (!$catobj->get_id() == '0') {
+			//this is necessary?
+			//$header .= '<table border="0" cellpadding="5"><tr><td><form name="itemfilter" method="post" action="' . api_get_self() . '?selectcat=' . $catobj->get_id() . '"><input type="checkbox" name="showeval" onclick="document.itemfilter.submit()" ' . (($showeval == '1') ? 'checked' : '') . '>Show Evaluations &nbsp;';
+			//$header .= '<input type="checkbox" name="showlink" onclick="document.itemfilter.submit()" ' . (($showlink == '1') ? 'checked' : '') . '>'.get_lang('ShowLinks').'</form></td></tr></table>';
+		}
+		if (isset ($_GET['search'])) {
+			$header .= '<b>'.get_lang('SearchResults').' :</b>';
+		}
+		echo $header;
+	}
+	
 	/**
 	 * Displays the header for the gradebook containing the navigation tree and links
 	 * @param category_object $currentcat
 	 * @param int $showtree '1' will show the browse tree and naviation buttons
 	 * @param boolean $is_course_admin
 	 * @param boolean $is_platform_admin
+     * @param boolean Whether to show or not the link to add a new qualification (we hide it in case of the course-embedded tool where we have only one calification per course or session)
+     * @param boolean Whether to show or not the link to add a new item inside the qualification (we hide it in case of the course-embedded tool where we have only one calification per course or session)
+     * @return void Everything is printed on screen upon closing
 	 */
-	function display_header_gradebook($catobj, $showtree, $selectcat, $is_course_admin, $is_platform_admin,$simple_search_form)
-	{
+	function display_header_gradebook($catobj, $showtree, $selectcat, $is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true) {
 		//student
-		if (!$is_course_admin)
-		{
-			$user= get_user_info_from_id(api_get_user_id());
+		if (!$is_course_admin) {
+			$user_id = api_get_user_id();
+			$user= get_user_info_from_id($user_id);		
+			
 			$catcourse= Category :: load($catobj->get_id());
 			$scoredisplay = ScoreDisplay :: instance();
-			$scorecourse = $catcourse[0]->calc_score(api_get_user_id());
-			$scorecourse_display = (isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable'));
+			$scorecourse = $catcourse[0]->calc_score($user_id);
+			
+			// generating the total score for a course
+			$allevals= $catcourse[0]->get_evaluations($user_id,true);
+			$alllinks= $catcourse[0]->get_links($user_id,true);
+			$evals_links = array_merge($allevals, $alllinks);			
+			$item_value=0;
+			$item_total=0;				
+			for ($count=0; $count < count($evals_links); $count++) {
+				$item = $evals_links[$count];
+				$score = $item->calc_score($user_id);					
+				$item_value+=$score[0]/$score[1]*$item->get_weight();			
+				$item_total+=$item->get_weight();				
+				//$row[] = $scoredisplay->display_score($score,SCORE_DIV_PERCENT);								
+			}			
+			$item_value = number_format($item_value, 2, '.', ' ');			
+			$total_score=array($item_value,$item_total);
+			$scorecourse_display = $scoredisplay->display_score($total_score,SCORE_DIV_PERCENT);
+			//----------------------
+			
+			
+			//$scorecourse_display = (isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable'));			
 			$cattotal = Category :: load(0);
 			$scoretotal= $cattotal[0]->calc_score(api_get_user_id());
 			$scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal,SCORE_PERCENT) : get_lang('NoResultsAvailable'));
 			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.$user['lastname'].' '.$user['firstname'].'</b><br />';
-			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search'])))
-				$scoreinfo.= '<br />'.get_lang('TotalForThisCategory') . ' : <b>' . $scorecourse_display . '</b>';
-			$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';
+			
+			
+			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search']))) {
+				$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scorecourse_display . '</b>';
+			}
+			//$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';
 			Display :: display_normal_message($scoreinfo,false);
 		}
 		// show navigation tree and buttons?
 		$header .= '<table border=0 cellpadding=5>';
-		if (($showtree == '1') || (isset ($_GET['studentoverview'])))
-		{
+		if (($showtree == '1') || (isset ($_GET['studentoverview']))) {
 			
-			$header .= '<tr><td style="vertical-align: top;">' . get_lang('CurrentCategory') . '</td><td style="vertical-align: top;"><form name=selector><select name=selectcat onchange="document.selector.submit()">';
+			$header .= '<tr><td style="vertical-align: top;">' . get_lang('CurrentCategory') . '</td><td style="vertical-align: top;"><form name="selector"><select name="selectcat" onchange="document.selector.submit()">';
 			$cats= Category :: load();
+			
 			$tree= $cats[0]->get_tree();
 			unset ($cats);
-			foreach ($tree as $cat)
-			{
-				for ($i= 0; $i < $cat[2]; $i++)
-				{
+			foreach ($tree as $cat) {
+				for ($i= 0; $i < $cat[2]; $i++) {
 					$line .= '&mdash;';
 				}
-				if ($_GET['selectcat'] == $cat[0])
-				{
+				if ($_GET['selectcat'] == $cat[0]) {
 					$header .= '<option selected value=' . $cat[0] . '>' . $line . ' ' . $cat[1] . '</option>';
-				} else
-				{
+				} else {
 					$header .= '<option value=' . $cat[0] . '>' . $line . ' ' . $cat[1] . '</option>';
 				}
 				$line= '';
 			}
 			$header .= '</select></form></td>';
-			if (!$selectcat == '0')
-			{
-				$header .= '<td style="vertical-align: top;"><a href=' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '><img src="../img/folder_up.gif" border="0" alt="" /></a></td>';
+			if (!$selectcat == '0') {
+				$header .= '<td style="vertical-align: top;"><a href="' . api_get_self() . '?selectcat=' . $catobj->get_parent_id() . '"><img src="../img/folder_up.gif" border="0" alt="" /></a></td>';
 			}
-			$header .= '<td style="vertical-align: top;">'.$simple_search_form->toHtml().'</td>';
-			if ($is_course_admin)
-			{
-				$header .= '<td style="vertical-align: top;"><a href=gradebook_flatview.php?selectcat=' . $catobj->get_id() . '><img src=../img/stats_access.gif alt=' . get_lang('FlatView') . '/> ' . get_lang('FlatView') . '</a>';
-				if ($is_platform_admin)
-					$header .= '<td style="vertical-align: top;"><a href="gradebook_scoring_system.php?selectcat=' . $catobj->get_id() .'"><img src=../img/acces_tool.gif alt=' . get_lang('ScoreEdit') . '/> ' . get_lang('ScoreEdit') . '</a>';
-			}
-			elseif (!(isset ($_GET['studentoverview'])))
-			{
-				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?studentoverview=&selectcat=' . $catobj->get_id() . '"><img src=../img/stats_access.gif alt=' . get_lang('FlatView') . '/> ' . get_lang('FlatView') . '</a>';
-			}
-			else
-			{
-				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?studentoverview=&exportpdf=&selectcat=' . $catobj->get_id() . '" target="_blank"><img src=../img/calendar_up.gif alt=' . get_lang('ExportPDF') . '/> ' . get_lang('ExportPDF') . '</a>';
+            if (!empty($simple_search_form)) {
+			    $header .= '<td style="vertical-align: top;">'.$simple_search_form->toHtml().'</td>';
+            } else {
+            	$header .= '<td></td>';
+            }
+			if ($is_course_admin) {
+				$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/stats_access.gif" alt="' . get_lang('FlatView') . '" /> ' . get_lang('FlatView') . '</a>';
+				if ($is_platform_admin) {
+					$header .= '<td style="vertical-align: top;"><a href="gradebook_scoring_system.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() .'"><img src="../img/acces_tool.gif" alt="' . get_lang('ScoreEdit') . '" /> ' . get_lang('ScoreEdit') . '</a>';
+				}	
+			} elseif (!(isset ($_GET['studentoverview']))) {
+				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&selectcat=' . $catobj->get_id() . '"><img src="../img/stats_access.gif" alt="' . get_lang('FlatView') . '" /> ' . get_lang('FlatView') . '</a>';
+			} else {
+				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&exportpdf=&selectcat=' . $catobj->get_id() . '" target="_blank"><img src="../img/calendar_up.gif" alt="' . get_lang('ExportPDF') . '" /> ' . get_lang('ExportPDF') . '</a>';
 			}
 			$header .= '</td></tr>';
 		}
 		$header.='</table>';
 		
 		// for course admin & platform admin add item buttons are added to the header
-		$header .= '<table border=0 cellpadding=0><tr><td>';
-		if (($is_course_admin) && (!isset ($_GET['search'])))
-		{
-			if ($selectcat == '0')
-			{
-				$header .= '<a href=gradebook_add_cat.php?selectcat=0><img src=../img/folder_new.gif alt=' . get_lang('NewCategory') . '/> ' . get_lang('NewCategory') . '</a></td>';
-				$header .= '<td><a href=gradebook_add_eval.php><img src=../img/filenew.gif alt=' . get_lang('NewEvaluation') . '/> ' . get_lang('NewEvaluation') . '</a>';
-			} else
-			{
-				$header .= '<a href=gradebook_add_cat.php?selectcat=' . $catobj->get_id() . '><img src=../img/folder_new.gif alt=' . get_lang('NewSubCategory') . ' align=absmiddle/> ' . get_lang('NewSubCategory') . '</a></td>';
-				$header .= '<td><a href=gradebook_add_eval.php?selectcat=' . $catobj->get_id() . '><img src=../img/filenew.gif alt=' . get_lang('NewEvaluation') . ' align=absmiddle/> ' . get_lang('NewEvaluation') . '</a>';
-				$cats= Category :: load($selectcat);
-				if ($cats[0]->get_course_code() != null)
-				{
-					$header .= '<td><a href=gradebook_add_link.php?&selectcat=' . $catobj->get_id() . '><img src=../img/link.gif alt=' . get_lang('MakeLink') . ' align=absmiddle/> ' . get_lang('MakeLink') . '</a>';
-				}
-				else
-				{
-					$header .= '<td><a href=gradebook_add_link_select_course.php?&selectcat=' . $catobj->get_id() . '><img src=../img/link.gif alt=' . get_lang('MakeLink') . ' align=absmiddle/> ' . get_lang('MakeLink') . '</a>';
-				}
+		$header .= '<table border="0" cellpadding="0"><tr><td>';
+		if (($is_course_admin) && (!isset ($_GET['search']))) {
+			if ($selectcat == '0') {
+                if ($show_add_qualification === true) {
+				    $header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=0"><img src="../img/folder_new.gif" alt="' . get_lang('NewCategory') . '" /> ' . get_lang('NewCategory') . '</a></td>';
+                }
+                if ($show_add_link === true) {
+				    $header .= '<td><a href="gradebook_add_eval.php'.api_get_cidreq().'&"><img src="../img/filenew.gif" alt="' . get_lang('NewEvaluation') . '" /> ' . get_lang('NewEvaluation') . '</a>';
+                }
+
+			} else {
+                if ($show_add_qualification === true) {
+    				$header .= '<a href="gradebook_add_cat.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '" ><img src="../img/folder_new.gif" alt="' . get_lang('NewSubCategory') . '" align="absmiddle" /> ' . get_lang('NewSubCategory') . '</a></td>';
+                }
+                if ($show_add_link === true) {
+    				$header .= '<td><a href="gradebook_add_eval.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '" ><img src="../img/filenew.gif" alt="' . get_lang('NewEvaluation') . '" align="absmiddle" /> ' . get_lang('NewEvaluation') . '</a>';
+                    $cats= Category :: load($selectcat);
+                    if ($cats[0]->get_course_code() != null) {
+                        //$header .= '<td><a href="gradebook_add_link.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/link.gif" alt="' . get_lang('MakeLink') . '" align="absmiddle" /> ' . get_lang('MakeLink') . '</a>';
+                        $header .= '<td><a href="gradebook_add_link.php?course_code='.api_get_course_id().'&selectcat=' . $catobj->get_id() . '"><img src="../img/link.gif" alt="' . get_lang('MakeLink') . '" align="absmiddle" /> ' . get_lang('MakeLink') . '</a>';
+                        
+                    } else {
+                        $header .= '<td><a href="gradebook_add_link_select_course.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/link.gif" alt="' . get_lang('MakeLink') . '" align="absmiddle" /> ' . get_lang('MakeLink') . '</a>';
+                    }
+                }
+                 $header .= '<td><a href="gradebook_edit_all.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/quiz.gif" alt="' . get_lang('EditAllWeights') . '" /> ' . get_lang('EditAllWeights') . '</a>';
 			}
-		}
-		elseif (isset ($_GET['search']))
-		{
+		} elseif (isset ($_GET['search'])) {
 			$header .= '<b>'.get_lang('SearchResults').' :</b>';
 		}
-
 		$header .= '</td></tr></table>';
 		echo $header;
 	}
 	
-	function display_header_user($userid)
-	{
+	
+	function display_reduce_header_gradebook($catobj,$is_course_admin, $is_platform_admin, $simple_search_form, $show_add_qualification = true, $show_add_link = true) {
+		//student
+		if (!$is_course_admin) {
+			/*$user= get_user_info_from_id(api_get_user_id());
+			$catcourse= Category :: load($catobj->get_id());
+			$scoredisplay = ScoreDisplay :: instance();
+			$scorecourse = $catcourse[0]->calc_score(api_get_user_id());
+			$scorecourse_display = (isset($scorecourse) ? $scoredisplay->display_score($scorecourse,SCORE_AVERAGE) : get_lang('NoResultsAvailable'));
+			$cattotal = Category :: load(0);
+			$scoretotal= $cattotal[0]->calc_score(api_get_user_id());
+			$scoretotal_display = (isset($scoretotal) ? $scoredisplay->display_score($scoretotal,SCORE_PERCENT) : get_lang('NoResultsAvailable'));
+			$scoreinfo = get_lang('StatsStudent') . ' :<b> '.$user['lastname'].' '.$user['firstname'].'</b><br />';
+			if ((!$catobj->get_id() == '0') && (!isset ($_GET['studentoverview'])) && (!isset ($_GET['search'])))
+				$scoreinfo.= '<br />'.get_lang('TotalForThisCategory') . ' : <b>' . $scorecourse_display . '</b>';
+			$scoreinfo.= '<br />'.get_lang('Total') . ' : <b>' . $scoretotal_display . '</b>';
+			Display :: display_normal_message($scoreinfo,false);
+			*/
+		}
+			// show navigation tree and buttons?
+			$header .= '<table border=0 cellpadding=5 >';
+			
+			if ($is_course_admin) {
+				$header .= '<td style="vertical-align: top;"><a href="gradebook_flatview.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() . '"><img src="../img/stats_access.gif" alt="' . get_lang('FlatView') . '" /> ' . get_lang('FlatView') . '</a>';
+				if ($is_platform_admin)
+					$header .= '<td style="vertical-align: top;"><a href="gradebook_scoring_system.php?'.api_get_cidreq().'&selectcat=' . $catobj->get_id() .'"><img src="../img/acces_tool.gif" alt="' . get_lang('ScoreEdit') . '" /> ' . get_lang('ScoreEdit') . '</a>';
+			} elseif (!(isset ($_GET['studentoverview']))) {
+				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&selectcat=' . $catobj->get_id() . '"><img src="../img/stats_access.gif" alt="' . get_lang('FlatView') . '" /> ' . get_lang('FlatView') . '</a>';
+			} else {
+				$header .= '<td style="vertical-align: top;"><a href="'.api_get_self().'?'.api_get_cidreq().'&studentoverview=&exportpdf=&selectcat=' . $catobj->get_id() . '" target="_blank"><img src="../img/calendar_up.gif" alt="' . get_lang('ExportPDF') . '" /> ' . get_lang('ExportPDF') . '</a>';
+			}
+			$header .= '</td></tr>';
+		$header.='</table>';
+		echo $header;
+	}
+	
+	
+	function display_header_user($userid) {
 		$user= get_user_info_from_id($userid);
 		$image= $user['picture_uri'];
 		$image_file= ($image != '' ? api_get_path(WEB_CODE_PATH) . "upload/users/$image" : api_get_path(WEB_CODE_PATH) . 'img/unknown.jpg');
 		$image_size= @ getimagesize($image_file);
 		$img_attributes= 'src="' . $image_file . '?rand=' . time() . '" ' . 'alt="' . $user['lastname'] . ' ' . $user['firstname'] . '" ';
-		if ($image_size[0] > 200) //limit display width to 200px
-			$img_attributes .= 'width="200" ';
+		if ($image_size[0] > 200) {
+		 //limit display width to 200px
+			$img_attributes .= 'width="200" ';	
+		}
 		$cattotal= Category :: load(0);
 		$info = '<table width="100%" border=0 cellpadding=5><tr><td width="80%">';
 		$info.= get_lang('Name') . ' : <b>' . $user['lastname'] . ' ' . $user['firstname'] . '</b> ( <a href="user_info.php?userid=' . $userid . '&selecteval=' . Security::remove_XSS($_GET['selecteval']) . '">' . get_lang('MoreInfo') . '...</a> )<br>';
@@ -248,5 +361,4 @@ class DisplayGradebook
 		$info.= '<img ' . $img_attributes . '/></td></tr></table>';
 		echo Display :: display_normal_message($info,false);
 	}
-}
-?>
+}

+ 76 - 96
main/gradebook/lib/fe/evalform.class.php

@@ -1,8 +1,31 @@
 <?php
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
-include_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
+require_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
 require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php');
 /**
  * Extends formvalidator with add&edit forms for evaluations
@@ -36,40 +59,28 @@ class EvalForm extends FormValidator
 	{
 		parent :: __construct($form_name, $method, $action);
 
-		if (isset ($evaluation_object))
+		if (isset ($evaluation_object)) {
 			$this->evaluation_object= $evaluation_object;
-		if (isset ($result_object))
+		}
+		if (isset ($result_object)) {
 			$this->result_object= $result_object;
-		if (isset ($extra1))
+		}
+		if (isset ($extra1)) {
 			$this->extra = $extra1;
-		
-		
-		if ($form_type == self :: TYPE_EDIT)
-		{
-			$this->build_editing_form();
 		}
-		elseif ($form_type == self :: TYPE_ADD)
-		{
+		if ($form_type == self :: TYPE_EDIT) {
+			$this->build_editing_form();
+		} elseif ($form_type == self :: TYPE_ADD) {
 			$this->build_add_form();
-		}
-		elseif ($form_type == self :: TYPE_MOVE)
-		{
+		} elseif ($form_type == self :: TYPE_MOVE) {
 			$this->build_move_form();
-		}
-		elseif ($form_type == self :: TYPE_RESULT_ADD)
-		{
+		} elseif ($form_type == self :: TYPE_RESULT_ADD) {
 			$this->build_result_add_form();
-		}
-		elseif ($form_type == self :: TYPE_RESULT_EDIT)
-		{
+		} elseif ($form_type == self :: TYPE_RESULT_EDIT) {
 			$this->build_result_edit_form();
-		}
-		elseif ($form_type == self :: TYPE_ALL_RESULTS_EDIT)
-		{
+		} elseif ($form_type == self :: TYPE_ALL_RESULTS_EDIT) {
 			$this->build_all_results_edit_form();
-		}
-		elseif ($form_type == self :: TYPE_ADD_USERS_TO_EVAL)
-		{
+		} elseif ($form_type == self :: TYPE_ADD_USERS_TO_EVAL) {
 			$this->build_add_user_to_eval();
 		}
 		$this->setDefaults();
@@ -77,8 +88,7 @@ class EvalForm extends FormValidator
 	/**
 	 * This form will build a form to add users to an evaluation
 	 */
-	protected function build_add_user_to_eval()
-	{
+	protected function build_add_user_to_eval() {
 		//$this->addElement('hidden', 'formSent');
 		$this->addElement('header','label',get_lang('ChooseUser'));
 		$select= $this->addElement('select', 'firstLetterUser', get_lang('FirstLetter'), null, array(
@@ -87,24 +97,23 @@ class EvalForm extends FormValidator
 
 		$result = '';
 		$select->addOption('','');
-		for ($i = 65; $i <= 90; $i ++)
-		{
+		for ($i = 65; $i <= 90; $i ++) {
 			$letter = chr($i);
-			if (isset($this->extra) && $this->extra == $letter)
+			if (isset($this->extra) && $this->extra == $letter) {
 				$select->addOption($letter,$letter,'selected');
-			else
+			} else {
 				$select->addOption($letter,$letter);
+			}	
 		}
-
 		$select= $this->addElement('select', 'add_users', null, null, array (
 			'multiple' => 'multiple',
 			'size' => '15',
 			'style' => 'width:250px'
 		));
-		foreach ($this->evaluation_object->get_not_subscribed_students() as $user)
-		{
-			if ( (!isset($this->extra)) || empty($this->extra) || strtoupper(substr($user[1],0,1)) == $this->extra )
+		foreach ($this->evaluation_object->get_not_subscribed_students() as $user) {
+			if ( (!isset($this->extra)) || empty($this->extra) || strtoupper(substr($user[1],0,1)) == $this->extra ) {
 				$select->addoption($user[1] . ' ' . $user[2] . ' (' . $user[3] . ')', $user[0]);
+			}	
 		}
 		$this->addElement('submit', 'submit_button', get_lang('AddUserToEval'));
 //		$this->setDefaults(array (
@@ -115,8 +124,7 @@ class EvalForm extends FormValidator
 	/**
 	 * This function builds a form to edit all results in an evaluation
 	 */
-	protected function build_all_results_edit_form()
-	{
+	protected function build_all_results_edit_form() {
 		//extra field for check on maxvalue
 		$this->addElement('hidden', 'maxvalue', $this->evaluation_object->get_max());
 		$this->addElement('hidden', 'minvalue', 0);
@@ -132,8 +140,7 @@ class EvalForm extends FormValidator
 			</div>';		
 
 		$results_and_users = array();
-		foreach ($this->result_object as $result)
-		{
+		foreach ($this->result_object as $result) {
 			$user= get_user_info_from_id($result->get_user_id());
 			$results_and_users[] = array ('result' => $result, 'user' => $user);
 		}
@@ -142,8 +149,7 @@ class EvalForm extends FormValidator
 
 
 		$defaults= array ();
-		foreach ($results_and_users as $result_and_user)
-		{
+		foreach ($results_and_users as $result_and_user) {
 			$user = $result_and_user['user'];
 			$result = $result_and_user['result'];
 			
@@ -169,17 +175,14 @@ class EvalForm extends FormValidator
 	 * This function builds a form to move an item to another category
 	 *
 	 */
-	protected function build_move_form()
-	{
+	protected function build_move_form() {
 		$renderer =& $this->defaultRenderer();
 		$renderer->setElementTemplate('<span>{element}</span> ');
 		$this->addElement('static', null, null, '"'.$this->evaluation_object->get_name().'" ');
 		$this->addElement('static', null, null, get_lang('MoveTo').' : ');
 		$select= $this->addElement('select', 'move_cat', null, null);
-		foreach ($this->evaluation_object->get_target_categories() as $cat)
-		{
-			for ($i= 0; $i < $cat[2]; $i++)
-			{
+		foreach ($this->evaluation_object->get_target_categories() as $cat) {
+			for ($i= 0; $i < $cat[2]; $i++) {
 				$line .= '&mdash;';
 			}
 			$select->addoption($line . ' ' . $cat[1], $cat[0]);
@@ -190,8 +193,7 @@ class EvalForm extends FormValidator
 	/**
 	 * Builds a result form containing inputs for all students with a given course_code
 	 */
-	protected function build_result_add_form()
-	{
+	protected function build_result_add_form() {
 		$tblusers= get_users_in_course($this->evaluation_object->get_course_code());
 		$nr_users= 0;
 		//extra field for check on maxvalue
@@ -208,8 +210,7 @@ class EvalForm extends FormValidator
 			<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	{element} / '.$this->evaluation_object->get_max().'
 			</div>
 			</div>';
-		foreach ($tblusers as $user)
-		{
+		foreach ($tblusers as $user) {
 			$this->add_textfield('score[' . $user[0] . ']',
 								 $this->build_stud_label($user[0], $user[1], $user[2]),
 								 false,
@@ -236,8 +237,7 @@ class EvalForm extends FormValidator
 	/**
 	 * Builds a form to edit a result
 	 */
-	protected function build_result_edit_form()
-	{
+	protected function build_result_edit_form() {
 		$this->setDefaults(array (
 		'score' => $this->result_object->get_score(),
 		'maximum' => $this->evaluation_object->get_max()
@@ -274,16 +274,13 @@ class EvalForm extends FormValidator
 	/**
 	 * Builds a form to add an evaluation
 	 */
-	protected function build_add_form()
-	{
+	protected function build_add_form() {
 		$this->setDefaults(array (
 		'hid_user_id' => $this->evaluation_object->get_user_id(), 'hid_category_id' => $this->evaluation_object->get_category_id(), 'hid_course_code' => $this->evaluation_object->get_course_code(), 'date' => time()));
 		$this->build_basic_form(0);
-		if ($this->evaluation_object->get_course_code() == null)
-		{
+		if ($this->evaluation_object->get_course_code() == null) {
 			$this->addElement('checkbox', 'adduser', get_lang('AddUserToEval'));
-		} else
-		{
+		} else {
 			$this->addElement('checkbox', 'addresult', get_lang('AddResult'));
 		}
 		$this->addElement('submit', null, get_lang('Add'));
@@ -291,8 +288,7 @@ class EvalForm extends FormValidator
 	/**
 	 * Builds a form to edit an evaluation
 	 */
-	protected function build_editing_form()
-	{
+	protected function build_editing_form() {
 		$this->setDefaults(array (
 		'hid_id' => $this->evaluation_object->get_id(), 'name' => $this->evaluation_object->get_name(), 'description' => $this->evaluation_object->get_description(), 'hid_user_id' => $this->evaluation_object->get_user_id(), 'hid_course_code' => $this->evaluation_object->get_course_code(), 'hid_category_id' => $this->evaluation_object->get_category_id(), 'date' => $this->evaluation_object->get_date(), 'weight' => $this->evaluation_object->get_weight(), 'max' => $this->evaluation_object->get_max(), 'visible' => $this->evaluation_object->is_visible()));
 		$this->addElement('hidden', 'hid_id', $this->id);
@@ -302,8 +298,7 @@ class EvalForm extends FormValidator
 	/**
 	 * Builds a basic form that is used in add and edit
 	 */
-	private function build_basic_form($edit= 0)
-	{
+	private function build_basic_form($edit= 0) {
 		$this->addElement('hidden', 'zero', 0);
 		$this->addElement('hidden', 'hid_user_id');
 		$this->addElement('hidden', 'hid_category_id');
@@ -316,17 +311,13 @@ class EvalForm extends FormValidator
 			'size' => '4',
 			'maxlength' => '4'
 		));
-		if ($edit)
-		{
-			if (!$this->evaluation_object->has_results())
-			{
+		if ($edit) {
+			if (!$this->evaluation_object->has_results()) {
 				$this->add_textfield('max', get_lang('Max'), true, array (
 					'size' => '4',
 					'maxlength' => '4'
 				));
-			}
-			else
-			{
+			} else {
 				$this->add_textfield('max', get_lang('Max'), false, array (
 					'size' => '4',
 					'maxlength' => '4',
@@ -334,8 +325,7 @@ class EvalForm extends FormValidator
 				));
 				$this->addElement('static','label','','<small>'.get_lang('NoMaxChange').'</small>');
 			}
-		} else
-		{
+		} else {
 			$this->add_textfield('max', get_lang('Max'), true, array (
 				'size' => '4',
 				'maxlength' => '4'
@@ -352,31 +342,24 @@ class EvalForm extends FormValidator
 		$this->addRule('max', get_lang('OnlyNumbers'), 'numeric');
 		$this->addRule(array ('max', 'zero'), get_lang('NegativeValue'), 'compare', '>=');
 	}
-	function display()
-	{
+	function display() {
 		parent :: display();
 	}
-	function setDefaults($defaults= array ())
-	{
+	function setDefaults($defaults= array ()) {
 		parent :: setDefaults($defaults);
 	}
 
 
-	private function build_stud_label ($id, $lastname, $firstname)
-	{
+	private function build_stud_label ($id, $lastname, $firstname) {
 		$opendocurl_start = '';
 		$opendocurl_end = '';
 
 		// evaluation's origin is a link
-		if ($this->evaluation_object->get_category_id() < 0)
-		{
+		if ($this->evaluation_object->get_category_id() < 0) {
 			$link = LinkFactory :: get_evaluation_link ($this->evaluation_object->get_id());
 
-			//var_dump($stud);
-
 			$doc_url = $link->get_view_url($id);
-			if ($doc_url != null)
-			{
+			if ($doc_url != null) {
 				$opendocurl_start .= '<a href="'. $doc_url . '" target="_blank">';
 				$opendocurl_end = '</a>';
 			}
@@ -385,16 +368,13 @@ class EvalForm extends FormValidator
 		return $opendocurl_start . $lastname . ' ' . $firstname . $opendocurl_end;
 	}
 
-	function sort_by_user ($item1, $item2)
-	{
+	function sort_by_user ($item1, $item2) {
 		$user1 = $item1['user'];
 		$user2 = $item2['user'];
-		if ($user1['lastname'] == $user2['lastname'])
+		if ($user1['lastname'] == $user2['lastname']) {
 			return 0;
-		else
+		} else {
 			return ($user1['lastname'] < $user2['lastname'] ? -1 : 1);
+		}	
 	}
-
-
-}
-?>
+}

+ 31 - 17
main/gradebook/lib/fe/exportgradebook.php

@@ -1,4 +1,27 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Prints an HTML page with a table containing the gradebook data
  * @param	array 	Array containing the data to be printed in the table	
@@ -6,8 +29,7 @@
  * @param	string	View to print as a title for the table
  * @param	string	Course name to print as title for the table
  */
-function print_table($data_array,$header_names,$view,$coursename)
-{
+function print_table ($data_array,$header_names,$view,$coursename) {
 	$printdata= '<!DOCTYPE html
      PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
@@ -61,16 +83,13 @@ a:active {text-decoration: none; font-weight : bold;  color : black;}
 	$printdata .= '<h2>'.$view.' : '.$coursename.'</h2>';
 	$printdata .= '<h3>'.get_lang('Date').' : '.date('j/n/Y g:i').'</h3>';
 	$printdata .= '<table border="1" width="90%" cellspacing="1" cellpadding="1">';
-	foreach ($header_names as $header)
-	{
+	foreach ($header_names as $header) {
 		$printdata .= '<th>'.$header.'</th>';		
 		
 	}
-	foreach ($data_array as $data)
-	{
+	foreach ($data_array as $data) {
 		$printdata .= '<tr>';
-		foreach ($data as $rowdata)
-		{
+		foreach ($data as $rowdata) {
 			$printdata .= '<td>'.$rowdata.'</td>';	
 		}
 		$printdata .= '</tr>';
@@ -86,20 +105,16 @@ a:active {text-decoration: none; font-weight : bold;  color : black;}
  * @param	array		Table headers
  * @param	string		Format (portrait or landscape) 
  */
-function export_pdf($pdf,$newarray,$header_names,$format)
-{
+function export_pdf($pdf,$newarray,$header_names,$format) {
 	$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
 	$pdf->ezSetCmMargins(0,0,0,0);
 	$pdf->ezSetY(($format=='portrait')?'820':'570');
 	$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
 	$pdf->ezText(get_lang('FlatView').' ('. date('j/n/Y g:i') .')',12,array('justification'=>'center'));
-	if ($format=='portrait')
-	{
+	if ($format=='portrait') {
 		$pdf->line(40,790,540,790);
 		$pdf->line(40,40,540,40);
-	}
-	else
-	{
+	} else {
 		$pdf->line(40,540,790,540);
 		$pdf->line(40,40,790,40);		
 	}
@@ -107,5 +122,4 @@ function export_pdf($pdf,$newarray,$header_names,$format)
 	$pdf->ezTable($newarray,$header_names,'',array('showHeadings'=>1,'shaded'=>1,'showLines'=>1,'rowGap'=>3,'width'=>(($format=='portrait')?'500':'750')));
 	$pdf->ezStream();	
 	
-}
-?>
+}

+ 51 - 43
main/gradebook/lib/fe/flatviewtable.class.php

@@ -1,7 +1,29 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
 
 define ('LIMIT',10);
 
@@ -22,8 +44,7 @@ class FlatViewTable extends SortableTable
 	/**
 	 * Constructor
 	 */
-	function FlatViewTable ($selectcat, $users= array (), $evals= array (), $links= array (), $limit_enabled = false, $offset = 0, $addparams = null)
-	{
+	function FlatViewTable ($selectcat, $users= array (), $evals= array (), $links= array (), $limit_enabled = false, $offset = 0, $addparams = null) {
 		parent :: SortableTable ('flatviewlist', null, null, 0);
 
 		$this->datagen = new FlatViewDataGenerator($users, $evals, $links);
@@ -32,34 +53,33 @@ class FlatViewTable extends SortableTable
 		$this->limit_enabled = $limit_enabled;
 		$this->offset = $offset;
 		
-		if (isset ($addparams))
+		if (isset ($addparams)) {
 			$this->set_additional_parameters($addparams);
+		}
+			
 	}
 
 	/**
 	 * Function used by SortableTable to get total number of items in the table
 	 */
-	function get_total_number_of_items()
-	{
+	function get_total_number_of_items () {
 		return $this->datagen->get_total_users_count();
 	}
 
 	/** 
 	 * Function used by SortableTable to generate the data to display
 	 */
-	function get_table_data($from = 1)
-	{
+	function get_table_data ($from = 1) {
 
 		// create page navigation if needed
 
 		$totalitems = $this->datagen->get_total_items_count();
-		if ($this->limit_enabled && $totalitems > LIMIT)
+		if ($this->limit_enabled && $totalitems > LIMIT) {
 			$selectlimit = LIMIT;
-		else
+		} else {
 			$selectlimit = $totalitems;
-		
-		if ($this->limit_enabled && $totalitems > LIMIT)
-		{
+		}
+		if ($this->limit_enabled && $totalitems > LIMIT) {
 	      	$calcprevious = LIMIT;
 			$header .= '<div class="normal-message">'
 						.'<table style="width: 100%; text-align: left; margin-left: auto; margin-right: auto;" border="0" cellpadding="2">'
@@ -68,8 +88,7 @@ class FlatViewTable extends SortableTable
 
 			// previous X
 	      	$header .= '<td style="width:40%;">';
-	      	if ($this->offset >= LIMIT)
-	      	{
+	      	if ($this->offset >= LIMIT) {
 	      		$header .= '<a href="'.api_get_self()
 	      							.'?selectcat='.Security::remove_XSS($_GET['selectcat'])
 	      							.'&offset='.(($this->offset)-LIMIT)
@@ -77,20 +96,17 @@ class FlatViewTable extends SortableTable
 	      					.'<img src="../img/lp_leftarrow.gif" alt="'.get_lang('Previous').'/" />'
 	      					.get_lang('Previous').' '.$calcprevious . ' ' . get_lang('Evaluations')
 	      					.'</a>';
-	      	}
-	      	else
+	      	} else {
 	      		$header .= '<img src="../img/lp_leftarrow.gif" alt="'.get_lang('Previous').' ' . get_lang('Evaluations').'/" />'.get_lang('Previous').' ' . get_lang('Evaluations');
+	      	}	
 	      	$header .= '</td>';
-
 	      	// 'glue'
 	      	$header .= '<td style="width:20%;"></td>';
-
 			// next X
 	      	$calcnext = (($this->offset+(2*LIMIT)) > $totalitems) ?
 	      					($totalitems-(LIMIT+$this->offset)) : LIMIT;
       		$header .= '<td style="text-align: right; width: 40%;">';
-      		if ($calcnext > 0)
-      		{
+      		if ($calcnext > 0) {
 	      		$header .= '<a href="'.api_get_self()
 	      							.'?selectcat='.Security::remove_XSS($_GET['selectcat'])
 	      							.'&offset='.($this->offset+LIMIT)
@@ -98,9 +114,7 @@ class FlatViewTable extends SortableTable
 	      					.get_lang('Next').' '.$calcnext . ' '.get_lang('Evaluations')
 	      					.'<img src="../img/lp_rightarrow.gif" alt="'.get_lang('Next').'/" />'
 	      					.'</a>';
-      		}
-      		else
-      		{
+      		} else {
   				$header .= get_lang('Next').' '.get_lang('Evaluations').'<img src="../img/lp_rightarrow.gif" alt="'.get_lang('Next').'/" />';
 	          			
       		}
@@ -113,13 +127,11 @@ class FlatViewTable extends SortableTable
 		// retrieve sorting type
 		$users_sorting = ($this->column == 0 ? FlatViewDataGenerator :: FVDG_SORT_LASTNAME
 											 : FlatViewDataGenerator :: FVDG_SORT_FIRSTNAME);
-		if ($this->direction == 'DESC')
+		if ($this->direction == 'DESC') {
 			$users_sorting |= FlatViewDataGenerator :: FVDG_SORT_DESC;
-		else
+		} else {
 			$users_sorting |= FlatViewDataGenerator :: FVDG_SORT_ASC;
-
-
-
+		}
 		// step 1: generate columns: evaluations and links
 
 		$header_names = $this->datagen->get_header_names($this->offset, $selectlimit);
@@ -128,12 +140,12 @@ class FlatViewTable extends SortableTable
 		$this->set_header($column++, $header_names[0]);
 		$this->set_header($column++, $header_names[1]);
 
-		while ($column < count($header_names))
-		{
+		while ($column < count($header_names)) {
 			$this->set_header($column, $header_names[$column], false);
 			$column++;
 		}
-
+		
+		//$this->set_header($column++, get_lang('Total'));
 
 		// step 2: generate rows: students
 		
@@ -142,14 +154,14 @@ class FlatViewTable extends SortableTable
 										 $this->offset, $selectlimit);
 
 		$table_data = array();
-		foreach ($data_array as $user_row)
-		{
+		foreach ($data_array as $user_row) {
 			$table_row = array ();
 			$count = 0;
 			$table_row[]= $this->build_name_link($user_row[$count++], $user_row[$count++]);
 			$table_row[]= $user_row[$count++];
-			while ($count < count($user_row))
-				$table_row[] = $user_row[$count++];
+			while ($count < count($user_row)) {
+				$table_row[] = $user_row[$count++];	
+			}
 			$table_data[]= $table_row;
 		}
 		return $table_data;
@@ -160,11 +172,7 @@ class FlatViewTable extends SortableTable
 
 	// Other functions
 
-	private function build_name_link ($user_id, $lastname)
-	{
+	private function build_name_link ($user_id, $lastname) {
 		return '<a href="user_stats.php?userid='.$user_id.'&selectcat='.$this->selectcat->get_id().'">'.$lastname.'</a>';
 	}
-
-	
-}
-?>
+}

+ 60 - 87
main/gradebook/lib/fe/gradebooktable.class.php

@@ -21,38 +21,37 @@
 */
 
 
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
 
 /**
  * Table to display categories, evaluations and links
  * @author Stijn Konings
- * @author Bert Stepp (refactored, optimised)
+ * @author Bert Steppé (refactored, optimised)
  */
 class GradebookTable extends SortableTable
 {
 
 	private $currentcat;
 	private $datagen;
-
+	private $evals_links;
 
 	/**
 	 * Constructor
 	 */
-    function GradebookTable ($currentcat, $cats = array(), $evals = array(), $links = array(), $addparams = null)
-    {
+    function GradebookTable ($currentcat, $cats = array(), $evals = array(), $links = array(), $addparams = null) {
     	parent :: SortableTable ('gradebooklist', null, null, (api_is_allowed_to_create_course()?1:0));
-
+		$this->evals_links = array_merge($evals, $links);
 		$this->currentcat = $currentcat;
 
 		$this->datagen = new GradebookDataGenerator($cats, $evals, $links);
-		
-		if (isset($addparams))
+		if (isset($addparams)) {
 			$this->set_additional_parameters($addparams);
-	
+		}
 		$column= 0;
-		if (api_is_allowed_to_create_course())
+		if (api_is_allowed_to_create_course()) {
 			$this->set_header($column++, '', false);
+		}	
 		$this->set_header($column++, get_lang('Type'));
 		$this->set_header($column++, get_lang('Name'));
 		$this->set_header($column++, get_lang('Description')); 
@@ -60,21 +59,19 @@ class GradebookTable extends SortableTable
 		$this->set_header($column++, get_lang('Date'),true, 'width="100"');
 		
 		//admins get an edit column
-		if (api_is_allowed_to_create_course())
-		{
-			
-			$this->set_header($column++, get_lang('Modify'), false, 'width="80"');
+		if (api_is_allowed_to_create_course()) {
+			$this->set_header($column++, get_lang('Modify'), false, 'width="100"');
 			//actions on multiple selected documents
 			$this->set_form_actions(array (
-				'delete' => get_lang('DeleteSelected'),
+				'deleted' => get_lang('DeleteSelected'),
 				'setvisible' => get_lang('SetVisible'),
 				'setinvisible' => get_lang('SetInvisible')));
-		}
-		//students get a result column
-		else
-		{
-			$this->set_header($column++, get_lang('Results'), false);
-			$this->set_header($column++, get_lang('Certificates'), false);
+		} else {
+	            $evals_links = array_merge($evals, $links);
+ 	             if(count($evals_links)>0) {
+ 	             	$this->set_header($column++, get_lang('Results'), false);
+ 	             }
+			//$this->set_header($column++, get_lang('Certificates'), false);
 		}
     }
 
@@ -82,8 +79,7 @@ class GradebookTable extends SortableTable
 	/**
 	 * Function used by SortableTable to get total number of items in the table
 	 */
-	function get_total_number_of_items()
-	{
+	function get_total_number_of_items() {
 		return $this->datagen->get_total_items_count();
 	}
 
@@ -91,13 +87,11 @@ class GradebookTable extends SortableTable
 	/** 
 	 * Function used by SortableTable to generate the data to display
 	 */
-	function get_table_data($from = 1)
-	{
+	function get_table_data($from = 1) {
 
 		// determine sorting type
 		$col_adjust = (api_is_allowed_to_create_course() ? 1 : 0);
-		switch ($this->column)
-		{
+		switch ($this->column) {
 			// Type
 			case (0 + $col_adjust) :
 				$sorting = GradebookDataGenerator :: GDG_SORT_TYPE;
@@ -115,20 +109,15 @@ class GradebookTable extends SortableTable
 				$sorting = GradebookDataGenerator :: GDG_SORT_DATE;
 				break;
 		}
-		if ($this->direction == 'DESC')
+		if ($this->direction == 'DESC') {
 			$sorting |= GradebookDataGenerator :: GDG_SORT_DESC;
-		else
+		} else {
 			$sorting |= GradebookDataGenerator :: GDG_SORT_ASC;
-
-
-
+		}
 		$data_array = $this->datagen->get_data($sorting, $from, $this->per_page);
-
-
 		// generate the data to display
 		$sortable_data = array();
-		foreach ($data_array as $data)
-		{
+		foreach ($data_array as $data) {
 			$row = array ();
 
 			$item = $data[0];
@@ -137,42 +126,35 @@ class GradebookTable extends SortableTable
 			$invisibility_span_open = (api_is_allowed_to_create_course() && $item->is_visible() == '0') ? '<span class="invisible">' : '';
 			$invisibility_span_close = (api_is_allowed_to_create_course() && $item->is_visible() == '0') ? '</span>' : '';
 			
-			if (api_is_allowed_to_create_course())
+			
+			if (api_is_allowed_to_create_course()) {
 				$row[] = $this->build_id_column ($item);
-				
+			}
 			$row[] = $this->build_type_column ($item);
 			$row[] = $invisibility_span_open . $this->build_name_link ($item) . $invisibility_span_close;
 			$row[] = $invisibility_span_open . $data[2] . $invisibility_span_close;
 			$row[] = $invisibility_span_open . $data[3] . $invisibility_span_close;
-			$row[] = $invisibility_span_open . $data[4] . $invisibility_span_close;
+			$row[] = $invisibility_span_open . str_replace(' ','&nbsp;',$data[4]) . $invisibility_span_close;
 
 			//admins get an edit column
-			if (api_is_allowed_to_create_course())
-			{
+			if (api_is_allowed_to_create_course()) {
 				$row[] = $this->build_edit_column ($item);
-			}
+			} else {
 			//students get the results and certificates columns
-			else
-			{
-				$row[] = $data[5];
-				$row[] = $data[6];
+				if (count($this->evals_links)>0) {
+					$row[] = $data[5];
+				}
+				//$row[] = $data[6];
 			}
 			$sortable_data[] = $row;
 		}
 		
 		return $sortable_data;
 	}
-
-
-
-
-	
 // Other functions
 
-	private function build_id_column ($item)
-	{
-		switch ($item->get_item_type())
-		{
+	private function build_id_column ($item) {
+		switch ($item->get_item_type()) {
 			// category
 			case 'C' :
 				return 'CATE' . $item->get_id();
@@ -181,22 +163,20 @@ class GradebookTable extends SortableTable
 				return 'EVAL' . $item->get_id();
 			// link
 			case 'L' :
-				return 'LINK' . $item->get_id();
+				return 'LINK' . $item->get_id();				
 		}
 	}
 
-	private function build_type_column ($item)
-	{
+	private function build_type_column ($item) {
 		return build_type_icon_tag($item->get_icon_name());
 	}
 
-	private function build_name_link ($item)
-	{
-		switch ($item->get_item_type())
-		{
+	private function build_name_link ($item) {
+		
+		switch ($item->get_item_type()) {
 			// category
 			case 'C' :
-				return '&nbsp;<a href="gradebook.php?selectcat=' . $item->get_id() . '">'
+				return '&nbsp;<a href="'.$_SESSION['gradebook_dest'].'?selectcat=' . $item->get_id() . '">'
 				 		. $item->get_name()
 				 		. '</a>'
 				 		. ($item->is_course() ? ' &nbsp;[' . $item->get_course_code() . ']' : '');
@@ -204,44 +184,40 @@ class GradebookTable extends SortableTable
 			case 'E' :
 
 				// course/platform admin can go to the view_results page
-				if (api_is_allowed_to_create_course())
+				if (api_is_allowed_to_create_course()) {
 					return '&nbsp;'
 						. '<a href="gradebook_view_result.php?selecteval=' . $item->get_id() . '">'
 						. $item->get_name()
 						. '</a>';
-				// students can go to the statistics page (if custom display enabled)
-				elseif (ScoreDisplay :: instance()->is_custom())
+				} elseif (ScoreDisplay :: instance()->is_custom()) {
+					// students can go to the statistics page (if custom display enabled)
 					return '&nbsp;'
 						. '<a href="gradebook_statistics.php?selecteval=' . $item->get_id() . '">'
 						. $item->get_name()
 						. '</a>';
-				else
+				} else {
 					return $item->get_name();
-				
+				}
 			// link
 			case 'L' :
-				$url = $item->get_link();
-				if (isset($url))
+				$url = $item->get_link();				
+				if (isset($url)) {
 					$text = '&nbsp;<a href="' . $item->get_link() . '">'
 							. $item->get_name()
 							. '</a>';
-				else
+				} else {
 					$text = $item->get_name();
+				}
 				$text .= '&nbsp;[' . $item->get_type_name() . ']';
 				$cc = $this->currentcat->get_course_code();
-				if(empty($cc))
-				{
+				if(empty($cc)) {
 					$text .= '&nbsp;[<a href="'.api_get_path(REL_COURSE_PATH).$item->get_course_code().'/">'.$item->get_course_code().'</a>]';
 				}
-				return $text;
+				return $text;	
 		}
 	}
-
-
-	private function build_edit_column ($item)
-	{
-		switch ($item->get_item_type())
-		{
+	private function build_edit_column ($item) {
+		switch ($item->get_item_type()) {
 			// category
 			case 'C' :
 				return build_edit_icons_cat($item, $this->currentcat->get_id());
@@ -250,11 +226,8 @@ class GradebookTable extends SortableTable
 				return build_edit_icons_eval($item, $this->currentcat->get_id());
 			// link
 			case 'L' :
-				return build_edit_icons_link($item, $this->currentcat->get_id());
+				return build_edit_icons_link($item, $this->currentcat->get_id());				
+			
 		}
 	}
-
-
-
-}
-?>
+}

+ 60 - 52
main/gradebook/lib/fe/linkaddeditform.class.php

@@ -1,8 +1,31 @@
 <?php
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
-include_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
+require_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
 require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php');
 
 /**
@@ -21,79 +44,68 @@ class LinkAddEditForm extends FormValidator
 	 * To add link, define category_object and link_type
 	 * To edit link, define link_object
 	 */
-    function LinkAddEditForm($form_type, $category_object, $link_type, $link_object, $form_name, $action = null)
-    {
+    function LinkAddEditForm($form_type, $category_object, $link_type, $link_object, $form_name, $action = null) {
 		parent :: __construct($form_name, 'post', $action);
 
 		// set or create link object
-		if (isset ($link_object))
+		if (isset ($link_object)) {
 			$link = $link_object;
-		elseif (isset ($link_type) && isset ($category_object))
-		{
+		} elseif (isset ($link_type) && isset ($category_object)) {
 			$link = LinkFactory :: create ($link_type);
 			$cc = $category_object->get_course_code();
-			if(empty($cc) && !empty($_GET['course_code']))
-			{
+			if (empty($cc) && !empty($_GET['course_code'])) {
 				$link->set_course_code(Database::escape_string($_GET['course_code']));
-			}
-			else
-			{
+			} else {
 				$link->set_course_code($category_object->get_course_code());
 			}
-		}
-		else
+		} else {
 			die ('LinkAddEditForm error: define link_type/category_object or link_object');
-
+		}
 		$defaults = array();
 		$this->addElement('hidden', 'zero', 0);
 
 		// ELEMENT: name
-		if ($form_type == self :: TYPE_ADD || $link->is_allowed_to_change_name())
-		{
-			if ($link->needs_name_and_description())
-			{
+		if ($form_type == self :: TYPE_ADD || $link->is_allowed_to_change_name()) {
+			if ($link->needs_name_and_description()) {
 				$this->add_textfield('name',
 									  get_lang('Name'),
 									  true,
 									  array('size'=>'40',
 											'maxlength'=>'40'));
-			}
-			else
-			{
+			} else {
 				$select = $this->addElement('select',
 											'select_link',
 											get_lang('ChooseExercise'));
 				foreach ($link->get_all_links() as $newlink)
 					$select->addoption($newlink[1],$newlink[0]);
 			}
-		}
-		else
+		} else {
 			$this->addElement('static',
 								'label',
 								get_lang('Name'),
 								$link->get_name().' ['.$link->get_type_name().']');
-
-
+		}
+			
 		// ELEMENT: weight
 		$this->add_textfield('weight', get_lang('Weight'),true,array('size'=>'4','maxlength'=>'4'));
 		$this->addRule('weight',get_lang('OnlyNumbers'),'numeric');
 		$this->addRule(array ('weight', 'zero'), get_lang('NegativeValue'), 'compare', '>=');
-		if ($form_type == self :: TYPE_EDIT)
+		if ($form_type == self :: TYPE_EDIT) {
 			$defaults['weight'] = $link->get_weight();
-
+		}
 		// ELEMENT: max
-		if ($link->needs_max())
-		{
-			if ($form_type == self :: TYPE_EDIT && $link->has_results())
+		if ($link->needs_max()) {
+			if ($form_type == self :: TYPE_EDIT && $link->has_results()) {
 				$this->add_textfield('max', get_lang('Max'), false, array ('size' => '4','maxlength' => '4', 'disabled' => 'disabled'));
-			else
-			{
+			} else {
 				$this->add_textfield('max', get_lang('Max'), true, array ('size' => '4','maxlength' => '4'));
 				$this->addRule('max', get_lang('OnlyNumbers'), 'numeric');
 				$this->addRule(array ('max', 'zero'), get_lang('NegativeValue'), 'compare', '>=');
 			}
-			if ($form_type == self :: TYPE_EDIT)
+			if ($form_type == self :: TYPE_EDIT) {
 				$defaults['max'] = $link->get_max();
+			}
+				
 		}
 		
 		// ELEMENT: date
@@ -102,36 +114,32 @@ class LinkAddEditForm extends FormValidator
 		
 		
 		// ELEMENT: description
-		if ($link->needs_name_and_description())
-		{
+		if ($link->needs_name_and_description()) {
 			$this->addElement('textarea', 'description', get_lang('Description'), array ('rows' => '3','cols' => '34'));
-			if ($form_type == self :: TYPE_EDIT)
+			if ($form_type == self :: TYPE_EDIT) {
 				$defaults['description'] = $link->get_description();
+			}		
 		}
 
 		// ELEMENT: visible
 		$visible = ($form_type == self :: TYPE_EDIT && $link->is_visible()) ? '1' : '0';
 		$this->addElement('checkbox', 'visible',get_lang('Visible'),null,$visible);
-		if ($form_type == self :: TYPE_EDIT)
+		if ($form_type == self :: TYPE_EDIT) {
 			$defaults['visible'] = $link->is_visible();
-
+		}
 		// ELEMENT: add results
-		if ($form_type == self :: TYPE_ADD && $link->needs_results())
+		if ($form_type == self :: TYPE_ADD && $link->needs_results()) {
 			$this->addElement('checkbox', 'addresult', get_lang('AddResult'));
-
-
+		}
 		// submit button
-		if ($form_type == self :: TYPE_ADD)
+		if ($form_type == self :: TYPE_ADD) {
 			$this->addElement('submit', null, get_lang('Add'));
-		else
+		} else {
 			$this->addElement('submit', null, get_lang('Edit'));
-		
-		
+		}
+
 		// set default values
 		$this->setDefaults($defaults);
 
 	}
-    
-    
-}
-?>
+}

+ 51 - 39
main/gradebook/lib/fe/linkform.class.php

@@ -1,8 +1,31 @@
 <?php
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
-include_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
+require_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
 require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php');
 
 /**
@@ -29,36 +52,33 @@ class LinkForm extends FormValidator
 	 * @param method
 	 * @param action
 	 */
-	function LinkForm($form_type, $category_object,$link_object, $form_name, $method = 'post', $action = null, $extra = null)
-	{
+	function LinkForm($form_type, $category_object,$link_object, $form_name, $method = 'post', $action = null, $extra = null) {
 		parent :: __construct($form_name, $method, $action);
 
-		if (isset ($category_object))
+		if (isset ($category_object)) {
 			$this->category_object = $category_object;
-		if (isset ($link_object))
+		} if (isset ($link_object)) {
 			$this->link_object = $link_object;
-		if (isset ($extra))
+		}
+		if (isset ($extra)) {
 			$this->extra = $extra;
-
-		if ($form_type == self :: TYPE_CREATE)
+		}
+		if ($form_type == self :: TYPE_CREATE) {
 			$this->build_create();
-		elseif ($form_type == self :: TYPE_MOVE)
+		} elseif ($form_type == self :: TYPE_MOVE) {
 			$this->build_move();
-
+		}
 		//$this->setDefaults();
 	}
 
-	protected function build_move()
-	{
+	protected function build_move() {
 		$renderer =& $this->defaultRenderer();
 		$renderer->setElementTemplate('<span>{element}</span> ');
 		$this->addElement('static',null,null,'"'.$this->link_object->get_name().'" ');
 		$this->addElement('static',null,null,get_lang('MoveTo').' : ');
 		$select = $this->addElement('select','move_cat',null,null);
-		foreach ($this->link_object->get_target_categories() as $cat)
-		{
-			for ($i=0;$i<$cat[2];$i++)
-			{
+		foreach ($this->link_object->get_target_categories() as $cat) {
+			for ($i=0;$i<$cat[2];$i++) {
 				$line .= '&mdash;';
 			}
 			$select->addoption($line.' '.$cat[1],$cat[0]);
@@ -67,8 +87,7 @@ class LinkForm extends FormValidator
    		$this->addElement('submit', null, get_lang('Ok'));		
 	}
 
-	protected function build_create()
-	{
+	protected function build_create() {
 		
 		$select = $this->addElement('select',
 									'select_link',
@@ -81,32 +100,25 @@ class LinkForm extends FormValidator
 		$select->addoption('['.get_lang('ChooseLink').']', 0);
 
 		$cc = $this->category_object->get_course_code();
-		foreach ($linktypes as $linktype)
-		{
+		foreach ($linktypes as $linktype) {
 			$link = LinkFactory :: create ($linktype);
-			if(!empty($cc))
-			{
+			if(!empty($cc)) {
 				$link->set_course_code($cc);
-			}
-			elseif(!empty($_GET['course_code']))
-			{
+			} elseif(!empty($_GET['course_code'])) {
 				$link->set_course_code(Database::escape_string($_GET['course_code']));
 			}
 			// disable this element if the link works with a dropdownlist
 			// and if there are no links left
-			if (!$link->needs_name_and_description()
-				&& count($link->get_all_links()) == '0')
-				$select->addoption($link->get_type_name(), $linktype, 'disabled');
-			else
-				$select->addoption($link->get_type_name(), $linktype);
+			if (!$link->needs_name_and_description() 
+				&& count($link->get_all_links()) == '0') {
+				$select->addoption($link->get_type_name(), $linktype, 'disabled');	
+			} else {
+					$select->addoption($link->get_type_name(), $linktype);
+			}
 		}
 
-		if (isset($this->extra))
-		{
+		if (isset($this->extra)) {
 			$this->setDefaults(array('select_link' => $this->extra));
 		}
-
 	}
-
-}
-?>
+}

+ 54 - 43
main/gradebook/lib/fe/resulttable.class.php

@@ -1,7 +1,29 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
 
 /**
  * Table to display results for an evaluation
@@ -20,8 +42,7 @@ class ResultTable extends SortableTable
 	/**
 	 * Constructor
 	 */
-    function ResultTable ($evaluation, $results = array(), $iscourse, $addparams = null,$forprint = false)
-    {
+    function ResultTable ($evaluation, $results = array(), $iscourse, $addparams = null,$forprint = false) {
     	parent :: SortableTable ('resultlist', null, null, 1);
 
 		$this->datagen = new ResultsDataGenerator($evaluation, $results, true);
@@ -30,14 +51,12 @@ class ResultTable extends SortableTable
 		$this->iscourse = $iscourse;
 		$this->forprint = $forprint;
 		
-		if (isset ($addparams))
+		if (isset ($addparams))  {
 			$this->set_additional_parameters($addparams);
-
+		}
 		$scoredisplay = ScoreDisplay :: instance();
-
 		$column= 0;
-		if ($this->iscourse == '1')
-		{
+		if ($this->iscourse == '1') {
 			$this->set_header($column++, '', false);
 			$this->set_form_actions(array (
 					'delete' => get_lang('Delete')
@@ -46,19 +65,19 @@ class ResultTable extends SortableTable
 		$this->set_header($column++, get_lang('LastName'));
 		$this->set_header($column++, get_lang('FirstName'));
 		$this->set_header($column++, get_lang('Score'));
-		if ($scoredisplay->is_custom())
+		if ($scoredisplay->is_custom()) {
 			$this->set_header($column++, get_lang('Display'));
-		if (!$this->forprint)
+		}
+		if (!$this->forprint) {
 			$this->set_header($column++, get_lang('Modify'),false);
-		
+		}
     }
 
 
 	/**
 	 * Function used by SortableTable to get total number of items in the table
 	 */
-	function get_total_number_of_items()
-	{
+	function get_total_number_of_items () {
 		return $this->datagen->get_total_results_count();
 	}
 
@@ -66,15 +85,13 @@ class ResultTable extends SortableTable
 	/** 
 	 * Function used by SortableTable to generate the data to display
 	 */
-	function get_table_data($from = 1)
-	{
+	function get_table_data ($from = 1) {
 
 		$scoredisplay = ScoreDisplay :: instance();
 
 		// determine sorting type
 		$col_adjust = ($this->iscourse == '1' ? 1 : 0);
-		switch ($this->column)
-		{
+		switch ($this->column) {
 			// Type
 			case (0 + $col_adjust):
 				$sorting = ResultsDataGenerator :: RDG_SORT_LASTNAME;
@@ -89,63 +106,57 @@ class ResultTable extends SortableTable
 				$sorting = ResultsDataGenerator :: RDG_SORT_MASK;
 				break;
 		}
-		if ($this->direction == 'DESC')
+		if ($this->direction == 'DESC') {
 			$sorting |= ResultsDataGenerator :: RDG_SORT_DESC;
-		else
+		} else {
 			$sorting |= ResultsDataGenerator :: RDG_SORT_ASC;
-
-
+		}
+			
 		$data_array = $this->datagen->get_data($sorting, $from, $this->per_page);
 
 
 		// generate the data to display
 		$sortable_data = array();
-		foreach ($data_array as $item)
-		{
+		foreach ($data_array as $item) {
 			$row = array ();
-			if ($this->iscourse == '1')
-				 $row[] = $item['result_id'];	
+			if ($this->iscourse == '1') {
+				 $row[] = $item['result_id'];
+			}	
 			$row[] = $item['lastname'];
 			$row[] = $item['firstname'];
 			$row[] = $item['score'];
-			if ($scoredisplay->is_custom())
+			if ($scoredisplay->is_custom()) {
 				$row[] = $item['display'];
-			if (!$this->forprint)
+			}
+			if (!$this->forprint) {
 				$row[] = $this->build_edit_column ($item);
+			}
 			$sortable_data[] = $row;
 		}
 		
 		return $sortable_data;
 	}
 
-
-
-
-	
 // Other functions
 
-	private function build_edit_column ($item)
-	{
+	private function build_edit_column ($item) {
 		$edit_column = '<a href="' . api_get_self() . '?editres=' . $item['result_id'] . '&selecteval=' . $this->evaluation->get_id() . '"><img src="../img/edit.gif" border="0" title="' . get_lang('Modify') . '" alt="" /></a>';
-		if ($this->evaluation->get_course_code() == null)
+		if ($this->evaluation->get_course_code() == null) {
 			$edit_column.= '&nbsp;<a href="' . api_get_self() . '?resultdelete=' . $item['result_id'] . '&selecteval=' . $this->evaluation->get_id() . '" onclick="return confirmationuser();"><img src="../img/delete.gif" border="0" title="' . get_lang('Delete') . '" alt="" /></a>';
 		$edit_column.= '&nbsp;<a href="user_stats.php?userid=' . $item['id'] . '&selecteval=' . $this->evaluation->get_id() . '"><img src="../img/statistics.gif" width="17px" border="0" title="' . get_lang('Statistics') . '" alt="" /></a>';
 
+		}
 		// evaluation's origin is a link
-		if ($this->evaluation->get_category_id() < 0)
-		{
+		if ($this->evaluation->get_category_id() < 0) {
 			$link = LinkFactory :: get_evaluation_link ($this->evaluation->get_id());
 
 			$doc_url = $link->get_view_url($item['id']);
-			if ($doc_url != null)
+			if ($doc_url != null) {
 				$edit_column .= '&nbsp;<a href="'. $doc_url . '" target="_blank">'
 								.'<img src="'. api_get_path(WEB_CODE_PATH) . 'img/link.gif" border="0" title="' . get_lang('OpenDocument') . '" alt="" />'
 								.'</a>';
+			}
 		}
-
 		return $edit_column;
-		
 	}
-
-}
-?>
+}

+ 36 - 20
main/gradebook/lib/fe/scoredisplayform.class.php

@@ -1,7 +1,30 @@
 <?php
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
 require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php');
 /**
  * Form for the score display dialog
@@ -11,8 +34,7 @@ require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.ph
  */
 class ScoreDisplayForm extends FormValidator
 {
-	function ScoreDisplayForm($form_name, $action= null)
-	{
+	function ScoreDisplayForm($form_name, $action= null) {
 		parent :: __construct($form_name, 'post', $action);
 		$displayscore= ScoreDisplay :: instance();
 		$customdisplays= $displayscore->get_custom_score_display_settings();
@@ -29,10 +51,8 @@ class ScoreDisplayForm extends FormValidator
 		
 		//setting the default values
 		
-		if(is_array($customdisplays))
-		{
-			foreach ($customdisplays as $customdisplay)
-			{
+		if(is_array($customdisplays)) {
+			foreach ($customdisplays as $customdisplay) {
 				$this->setDefaults(array (
 					'endscore[' . $counter . ']' => $customdisplay['score'],
 					'displaytext[' . $counter . ']' => $customdisplay['display']
@@ -51,7 +71,7 @@ class ScoreDisplayForm extends FormValidator
 			<!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->{label}
 			</div>
 			<div class="formw">
-			<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	'.get_lang('Below').'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{element} % '.get_lang('WillColorRed').'
+			<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	'.get_lang('Below').'&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{element} % '.get_lang('WillColorRed').'
 			</div>
 			</div>';	
 
@@ -70,8 +90,7 @@ class ScoreDisplayForm extends FormValidator
 		$this->addElement('header', 'h2', '<b>' . get_lang('ScoringSystem') . '</b>');
 		$this->addElement('checkbox', 'enablescore', null, get_lang('EnableScoringSystem'), null);
 
-		if ($displayscore->is_custom())
-		{
+		if ($displayscore->is_custom()) {
 			$this->addElement('checkbox', 'includeupperlimit', null, get_lang('IncludeUpperLimit'), null);
 			$this->addElement('static', null, null, '<small>' . get_lang('ScoreInfo') . '</small>');
 			$scorenull[]= & $this->CreateElement('static', null, null, get_lang('Between'));
@@ -85,17 +104,16 @@ class ScoreDisplayForm extends FormValidator
 			));
 			$scorenull[]= & $this->CreateElement('static', null, null, ' %');
 			$this->addGroup($scorenull, '', '', ' ');
-			for ($counter= 1; $counter <= 20; $counter++)
-			{
+			for ($counter= 1; $counter <= 20; $counter++) {
 
 				$renderer =& $this->defaultRenderer();
 				$elementTemplateTwoLabel = 
 				'<div id=' . $counter . ' style="display: '.(($counter<=$nr_items)?'inline':'none').';" class="row">
 				<p><!-- BEGIN required --><span class="form_required">*</span> <!-- END required -->{label}
-				<div class="formw"><!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	<b>'.get_lang('And').'</b>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{element} % =';	
+				<div class="formw"><!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->	<b>'.get_lang('And').'</b>&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp{element} % =';	
 
 				$elementTemplateTwoLabel2 =
-				'<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->&nbsp;{element}
+				'<!-- BEGIN error --><span class="form_error">{error}</span><br /><!-- END error -->&nbsp{element}
 				<a href="javascript:minItem(' . ($counter) . ')"><img style="display: '.(($counter>=$nr_items && $counter!=1)?'inline':'none').';" id="min-' . $counter . '" src="../img/gradebook_remove.gif" alt="'.get_lang('Delete').'" title="'.get_lang('Delete').'"></img></a>			
 				<a href="javascript:plusItem(' . ($counter+1) . ')"><img style="display: '.(($counter>=$nr_items)?'inline':'none').';" id="plus-' . ($counter+1) . '" src="../img/gradebook_add.gif" alt="'.get_lang('Add').'" title="'.get_lang('Add').'"></img></a>
 				</div></p></div>';
@@ -122,9 +140,7 @@ class ScoreDisplayForm extends FormValidator
 		'enablescore' => $displayscore->is_custom(), 'includeupperlimit' => $displayscore->is_upperlimit_included()));
 		$this->addElement('submit', 'submit', get_lang('Ok'));
 	}
-	function validate()
-	{
+	function validate() {
 		return parent :: validate();
 	}
-}
-?>
+}

+ 38 - 26
main/gradebook/lib/fe/userform.class.php

@@ -1,8 +1,31 @@
 <?php
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
-include_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
+/*
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
+require_once (dirname(__FILE__).'/../gradebook_functions.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'groupmanager.lib.php');
 require_once (api_get_path(LIBRARY_PATH) . 'formvalidator/FormValidator.class.php');
 /**
  * Extends formvalidator with import and export forms
@@ -21,33 +44,26 @@ class UserForm extends FormValidator
 	 * @param method
 	 * @param action
 	 */
-	function UserForm($form_type, $user, $form_name, $method= 'post', $action= null)
-	{
+	function UserForm($form_type, $user, $form_name, $method= 'post', $action= null) {
 		parent :: __construct($form_name, $method, $action);
 		$this->form_type= $form_type;
-		if (isset ($user))
-		{
+		if (isset ($user)) {
 			$this->user_info= $user;
 		}
-		if (isset ($result_object))
-		{
+		if (isset ($result_object)) {
 			$this->result_object= $result_object;
 		}
-		if ($this->form_type == self :: TYPE_USER_INFO)
-		{
+		if ($this->form_type == self :: TYPE_USER_INFO) {
 			$this->build_user_info_form();
 		}
-		elseif ($this->form_type == self :: TYPE_SIMPLE_SEARCH)
-		{
+		elseif ($this->form_type == self :: TYPE_SIMPLE_SEARCH) {
 			$this->build_simple_search();
 		}
 		$this->setDefaults();
 	}
 	
-	protected function build_simple_search()
-	{	
-		if (isset($_GET['search']) && (!empty($_GET['search'])))
-		{
+	protected function build_simple_search() {	
+		if (isset($_GET['search']) && (!empty($_GET['search']))) {
 		   	$this->setDefaults(array(
    		    'keyword' => Security::remove_XSS($_GET['search'])
    		    ));
@@ -58,8 +74,7 @@ class UserForm extends FormValidator
 		$this->addElement('submit','submit',get_lang('Search'));
 	}
 	
-	protected function build_user_info_form()
-	{
+	protected function build_user_info_form() {
 		$this->addElement('static', 'fname', get_lang('FirstName'), $this->user_info['firstname']);
 		$this->addElement('static', 'lname', get_lang('LastName'), $this->user_info['lastname']);
 		$this->addElement('static', 'uname', get_lang('UserName'), $this->user_info['username']);
@@ -68,13 +83,10 @@ class UserForm extends FormValidator
 		$this->addElement('static', 'phone', get_lang('Phone'), $this->user_info['phone']);
 		$this->addElement('submit', null, get_lang('Back'));
 	}
-	function display()
-	{
+	function display() {
 		parent :: display();
 	}
-	function setDefaults($defaults= array ())
-	{
+	function setDefaults($defaults= array ()) {
 		parent :: setDefaults($defaults);
 	}
-}
-?>
+}

+ 40 - 35
main/gradebook/lib/fe/usertable.class.php

@@ -1,7 +1,29 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
-include_once (dirname(__FILE__).'/../../../inc/global.inc.php');
-include_once (dirname(__FILE__).'/../be.inc.php');
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once (dirname(__FILE__).'/../../../inc/global.inc.php');
+require_once (dirname(__FILE__).'/../be.inc.php');
 
 /**
  * Table to display flat view of a student's evaluations and links
@@ -18,17 +40,16 @@ class UserTable extends SortableTable
 	/**
 	 * Constructor
 	 */
-    function UserTable ($userid, $evals = array(), $links = array(), $addparams = null)
-    {
+    function UserTable ($userid, $evals = array(), $links = array(), $addparams = null) {
     	parent :: SortableTable ('userlist', null, null, 0);
 
 		$this->userid = $userid;
 
 		$this->datagen = new UserDataGenerator($userid, $evals, $links);
 
-		if (isset($addparams))
+		if (isset($addparams)) {
 			$this->set_additional_parameters($addparams);
-
+		}
 		$column = 0;
 		$this->set_header($column++, get_lang('Type'));
 		$this->set_header($column++, get_lang('Evaluation'));
@@ -38,17 +59,16 @@ class UserTable extends SortableTable
 		$this->set_header($column++, get_lang('Result'));
 		
 		$scoredisplay = ScoreDisplay :: instance();
-		if ($scoredisplay->is_custom())
+		if ($scoredisplay->is_custom()) {
 			$this->set_header($column++, get_lang('Display'));
-		
+		}
     }
 
 
 	/**
 	 * Function used by SortableTable to get total number of items in the table
 	 */
-	function get_total_number_of_items()
-	{
+	function get_total_number_of_items () {
 		return $this->datagen->get_total_items_count();
 	}
 
@@ -56,14 +76,12 @@ class UserTable extends SortableTable
 	/** 
 	 * Function used by SortableTable to generate the data to display
 	 */
-	function get_table_data($from = 1)
-	{
+	function get_table_data ($from = 1) {
 
 		$scoredisplay = ScoreDisplay :: instance();
 
 		// determine sorting type
-		switch ($this->column)
-		{
+		switch ($this->column) {
 			// Type
 			case 0:
 				$sorting = UserDataGenerator :: UDG_SORT_TYPE;
@@ -87,19 +105,15 @@ class UserTable extends SortableTable
 				$sorting = UserDataGenerator :: UDG_SORT_MASK;
 				break;
 		}
-		if ($this->direction == 'DESC')
+		if ($this->direction == 'DESC') {
 			$sorting |= UserDataGenerator :: UDG_SORT_DESC;
-		else
+		} else {
 			$sorting |= UserDataGenerator :: UDG_SORT_ASC;
-
-
+		}
 		$data_array = $this->datagen->get_data($sorting, $from, $this->per_page);
-
-
 		// generate the data to display
 		$sortable_data = array();
-		foreach ($data_array as $data)
-		{
+		foreach ($data_array as $data) {
 			$row = array ();
 			$row[] = $this->build_type_column ($data[0]);
 			$row[] = $this->build_name_link ($data[0]);
@@ -116,20 +130,14 @@ class UserTable extends SortableTable
 	}
 
 
-
-
-	
 // Other functions
 
-	private function build_type_column ($item)
-	{
+	private function build_type_column ($item) {
 		return build_type_icon_tag($item->get_icon_name());
 	}
 
-	private function build_name_link ($item)
-	{
-		switch ($item->get_item_type())
-		{
+	private function build_name_link ($item) {
+		switch ($item->get_item_type()) {
 			// evaluation
 			case 'E' :
 				return '&nbsp;'
@@ -145,7 +153,4 @@ class UserTable extends SortableTable
 		}
 	}
 
-
-
-}
-?>
+}

+ 82 - 66
main/gradebook/lib/flatview_data_generator.class.php

@@ -1,9 +1,31 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Class to select, sort and transform object data into array data,
  * used for the teacher's flat view
- * @author Bert Steppé
+ * @author Bert Stepp�
  */
 class FlatViewDataGenerator
 {
@@ -22,8 +44,7 @@ class FlatViewDataGenerator
 	/**
 	 * Constructor
 	 */
-    public function FlatViewDataGenerator ($users= array (), $evals= array (), $links= array ())
-    {
+    public function FlatViewDataGenerator ($users= array (), $evals= array (), $links= array ()) {
 		$this->users = (isset($users) ? $users : array());
 		$this->evals = (isset($evals) ? $evals : array());
 		$this->links = (isset($links) ? $links : array());
@@ -34,16 +55,14 @@ class FlatViewDataGenerator
 	/**
 	 * Get total number of users (rows)
 	 */
-	public function get_total_users_count()
-	{
+	public function get_total_users_count() {
 		return count($this->users);
 	}
 	
 	/**
 	 * Get total number of evaluations/links (columns) (the 2 users columns not included)
 	 */
-	public function get_total_items_count()
-	{
+	public function get_total_items_count() {
 		return count($this->evals_links);
 	}
 	
@@ -51,27 +70,23 @@ class FlatViewDataGenerator
 	/**
 	 * Get array containing column header names (incl user columns)
 	 */
-	public function get_header_names ($items_start = 0, $items_count = null)
-	{
+	public function get_header_names ($items_start = 0, $items_count = null) {
 		$headers = array();
 		$headers[] = get_lang('LastName');
 		$headers[] = get_lang('FirstName');
-
-		if (!isset($items_count))
-			$items_count = count($this->evals_links) - $items_start;
-
+		if (!isset($items_count)) {
+			$items_count = count($this->evals_links) - $items_start;			
+		}
 		for ($count=0;
 			 ($count < $items_count ) && ($items_start + $count < count($this->evals_links));
-			 $count++)
-		{
+			 $count++) {
 			$item = $this->evals_links [$count + $items_start];
 			$headers[] = $item->get_name();
 		}
-		
+		$headers[] = get_lang('GradebookQualificationTotal');
 		return $headers;
 	}
 
-
 	/**
 	 * Get actual array data
 	 * @return array 2-dimensional array - each array contains the elements:
@@ -83,61 +98,67 @@ class FlatViewDataGenerator
 	public function get_data ($users_sorting = 0,
 							  $users_start = 0, $users_count = null, 
 							  $items_start = 0, $items_count = null,
-							  $ignore_score_color = false)
-	{
-
+							  $ignore_score_color = false) {
 		// do some checks on users/items counts, redefine if invalid values
-		if (!isset($users_count))
-			$users_count = count ($this->users) - $users_start;
-		if ($users_count < 0)
-			$users_count = 0;
-		if (!isset($items_count))
-			$items_count = count ($this->evals) + count ($this->links) - $items_start;
-		if ($items_count < 0)
-			$items_count = 0;
-
+		if (!isset($users_count)) {
+			$users_count = count ($this->users) - $users_start;			
+		}
+		if ($users_count < 0) {
+			$users_count = 0;		
+		}
+		if (!isset($items_count)) {
+			$items_count = count ($this->evals) + count ($this->links) - $items_start;			
+		}
+		if ($items_count < 0) {
+			$items_count = 0;			
+		}
 		// copy users to a new array that we will sort
 		// TODO - needed ?
 		$usertable = array ();
-		foreach ($this->users as $user)
-			$usertable[] = $user;
-
+		foreach ($this->users as $user) {
+			$usertable[] = $user;			
+		}
 		// sort users array
-		if ($users_sorting & self :: FVDG_SORT_LASTNAME)
+		if ($users_sorting & self :: FVDG_SORT_LASTNAME) {
 			usort($usertable, array ('FlatViewDataGenerator','sort_by_last_name'));
-		elseif ($users_sorting & self :: FVDG_SORT_FIRSTNAME)
-			usort($usertable, array ('FlatViewDataGenerator','sort_by_first_name'));
-		if ($users_sorting & self :: FVDG_SORT_DESC)
-			$usertable = array_reverse($usertable);
-
+		} elseif ($users_sorting & self :: FVDG_SORT_FIRSTNAME) {
+			usort($usertable, array ('FlatViewDataGenerator','sort_by_first_name'));			
+		}
+		if ($users_sorting & self :: FVDG_SORT_DESC) {
+			$usertable = array_reverse($usertable);			
+		}
 		// select the requested users
 		$selected_users = array_slice($usertable, $users_start, $users_count);
-		
-
 		// generate actual data array
 
 		$scoredisplay = ScoreDisplay :: instance();
 		
 		$data= array ();
 		$displaytype = SCORE_DIV;
-		if ($ignore_score_color)
-			$displaytype |= SCORE_IGNORE_SPLIT;
-
-		foreach ($selected_users as $user)
-		{
+		if ($ignore_score_color) {
+			$displaytype |= SCORE_IGNORE_SPLIT;			
+		}
+		foreach ($selected_users as $user) {
 			$row = array ();
 			$row[] = $user[0];	// user id
 			$row[] = $user[1];	// last name
 			$row[] = $user[2];	// first name
-
+			
+			$item_value=0;
+			$item_total=0;
+			
 			for ($count=0;
 				 ($count < $items_count ) && ($items_start + $count < count($this->evals_links));
-				 $count++)
-			{
+				 $count++) {
 				$item = $this->evals_links [$count + $items_start];
 				$score = $item->calc_score($user[0]);
-				$row[] = $scoredisplay->display_score($score,$displaytype);
+				$item_value+=$score[0];
+				$item_total+=$score[1];				
+				$row[] = $scoredisplay->display_score($score,SCORE_DIV_PERCENT);								
 			}
+			$total_score=array($item_value,$item_total);
+			$row[] = $scoredisplay->display_score($total_score,SCORE_DIV_PERCENT);
+
 			unset($score);
 			$data[] = $row;
 		}
@@ -145,27 +166,22 @@ class FlatViewDataGenerator
 		return $data;
 
 	}
-
-
-
-
 	// Sort functions - used internally
 
-	function sort_by_last_name($item1, $item2)
-	{
-		if (strtolower($item1[1]) == strtolower($item2[1]))
-			return 0;
-		else
-			return (strtolower($item1[1]) < strtolower($item2[1]) ? -1 : 1);
+	function sort_by_last_name($item1, $item2) {
+		if (strtolower($item1[1]) == strtolower($item2[1])) {
+			return 0;			
+		} else {
+			return (strtolower($item1[1]) < strtolower($item2[1]) ? -1 : 1);			
+		}
 	}
 
 	function sort_by_first_name($item1, $item2)
 	{
-		if (strtolower($item1[2]) == strtolower($item2[2]))
-			return $this->sort_by_last_name($item1, $item2);
-		else
-			return (strtolower($item1[2]) < strtolower($item2[2]) ? -1 : 1);
+		if (strtolower($item1[2]) == strtolower($item2[2])) {
+			return $this->sort_by_last_name($item1, $item2);			
+		} else {
+			return (strtolower($item1[2]) < strtolower($item2[2]) ? -1 : 1);			
+		}
 	}
-
-}
-?>
+}

+ 109 - 104
main/gradebook/lib/gradebook_data_generator.class.php

@@ -1,5 +1,27 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Class to select, sort and transform object data into array data,
  * used for the general gradebook view
@@ -20,24 +42,22 @@ class GradebookDataGenerator
 
 
 	private $items;
+	private $evals_links;
 
-
-    function GradebookDataGenerator($cats = array(), $evals = array(), $links = array())
-    {
+    function GradebookDataGenerator($cats = array(), $evals = array(), $links = array()) {
 		$allcats = (isset($cats) ? $cats : array());
 		$allevals = (isset($evals) ? $evals : array());
 		$alllinks = (isset($links) ? $links : array());
-
 		// merge categories, evaluations and links
 		$this->items = array_merge($allcats, $allevals, $alllinks);
+		$this->evals_links = array_merge($allevals, $alllinks);
     }
 
 
 	/**
 	 * Get total number of items (rows)
 	 */
-	public function get_total_items_count()
-	{
+	public function get_total_items_count() {
 		return count($this->items);
 	}
 
@@ -54,53 +74,49 @@ class GradebookDataGenerator
 	 * 4: date
 	 * 5: student's score (if student logged in)
 	 */
-	public function get_data ($sorting = 0, $start = 0, $count = null, $ignore_score_color = false)
-	{
-		
+	public function get_data ($sorting = 0, $start = 0, $count = null, $ignore_score_color = false) {		
 		// do some checks on count, redefine if invalid value
-		if (!isset($count))
-			$count = count ($this->items) - $start;
-		if ($count < 0)
+		if (!isset($count)) {
+			$count = count ($this->items) - $start;			
+		}
+		if ($count < 0) {
 			$count = 0;
-
+		}
 		$allitems = $this->items;
-
 		// sort array
-		if ($sorting & self :: GDG_SORT_TYPE)
-			usort($allitems, array('GradebookDataGenerator', 'sort_by_type'));
-		elseif ($sorting & self :: GDG_SORT_NAME)
-			usort($allitems, array('GradebookDataGenerator', 'sort_by_name'));
-		elseif ($sorting & self :: GDG_SORT_DESCRIPTION)
-			usort($allitems, array('GradebookDataGenerator', 'sort_by_description'));
-		elseif ($sorting & self :: GDG_SORT_WEIGHT)
-			usort($allitems, array('GradebookDataGenerator', 'sort_by_weight'));
-		elseif ($sorting & self :: GDG_SORT_DATE)
-			usort($allitems, array('GradebookDataGenerator', 'sort_by_date'));
-
-		if ($sorting & self :: GDG_SORT_DESC)
-			$allitems = array_reverse($allitems);
-
-
+		if ($sorting & self :: GDG_SORT_TYPE) {
+			usort($allitems, array('GradebookDataGenerator', 'sort_by_type'));			
+		} elseif ($sorting & self :: GDG_SORT_NAME) {
+			usort($allitems, array('GradebookDataGenerator', 'sort_by_name'));			
+		} elseif ($sorting & self :: GDG_SORT_DESCRIPTION) {
+			usort($allitems, array('GradebookDataGenerator', 'sort_by_description'));			
+		} elseif ($sorting & self :: GDG_SORT_WEIGHT) {
+			usort($allitems, array('GradebookDataGenerator', 'sort_by_weight'));			
+		} elseif ($sorting & self :: GDG_SORT_DATE) {
+			usort($allitems, array('GradebookDataGenerator', 'sort_by_date'));			
+		}
+		if ($sorting & self :: GDG_SORT_DESC) {
+			$allitems = array_reverse($allitems);			
+		}
 		// get selected items
 		$visibleitems = array_slice($allitems, $start, $count);
-
-
 		// generate the data to display
 		$data = array();
-		foreach ($visibleitems as $item)
-		{
+		foreach ($visibleitems as $item) {
 			$row = array ();
 			$row[] = $item;
 			$row[] = $item->get_name();
 			$row[] = $item->get_description();
 			$row[] = $item->get_weight();
 			$row[] = $this->build_date_column ($item);
-			if (!api_is_allowed_to_create_course())
-				$row[] = $this->build_result_column ($item, $ignore_score_color);
-				$row[] = $this->get_certificate_link ($item);
-			$data[] = $row;
-		}
-		
+			
+			if(count($this->evals_links)>0)
+				if (!api_is_allowed_to_create_course())
+					$row[] = $this->build_result_column ($item, $ignore_score_color);
+					//$row[] = $this->get_certificate_link ($item);
+					$data[] = $row;
+				 }
+		    
 		return $data;
 
 	}
@@ -110,108 +126,97 @@ class GradebookDataGenerator
 	 * returns an empty string. This only works with categories.
 	 * @param	object Item 
 	 */
-	function get_certificate_link($item)
-	{
-		if(is_a($item, 'Category'))
-		{
-			if($item->is_certificate_available(api_get_user_id()))
-			{
-				$link = '<a href="gradebook.php?export_certificate=1&cat='.$item->get_id().'&user='.api_get_user_id().'">'.get_lang('Certificate').'</a>';
+	function get_certificate_link($item) {
+		if(is_a($item, 'Category')) {
+			if($item->is_certificate_available(api_get_user_id())) {
+				$link = '<a href="'.$_SESSION['gradebook_dest'].'?export_certificate=1&cat='.$item->get_id().'&user='.api_get_user_id().'">'.get_lang('Certificate').'</a>';
 				return $link;
 			}
 		}
 		return '';
 	}
-
-
-
-
 // Sort functions
 // Make sure to only use functions as defined in the GradebookItem interface !
 
-	function sort_by_name($item1, $item2)
-	{
-		if (strtolower($item1->get_name()) == strtolower($item2->get_name()))
-			return 0;
-		else
-			return (strtolower($item1->get_name()) < strtolower($item2->get_name()) ? -1 : 1);
+	function sort_by_name($item1, $item2) {
+		if (strtolower($item1->get_name()) == strtolower($item2->get_name())) {
+			return 0;			
+		} else {
+			return (strtolower($item1->get_name()) < strtolower($item2->get_name()) ? -1 : 1);			
+		}
 	}
 
-	function sort_by_type($item1, $item2)
-	{
-		if ($item1->get_item_type() == $item2->get_item_type())
-			return $this->sort_by_name($item1,$item2);
-		else
-			return ($item1->get_item_type() < $item2->get_item_type() ? -1 : 1);
+	function sort_by_type($item1, $item2) {
+		if ($item1->get_item_type() == $item2->get_item_type()) {
+			return $this->sort_by_name($item1,$item2);		
+		} else {
+			return ($item1->get_item_type() < $item2->get_item_type() ? -1 : 1);			
+		}
+
 	}
 	
-	function sort_by_description($item1, $item2)
-	{
-		if (strtolower($item1->get_description()) == strtolower($item2->get_description()))
-			return $this->sort_by_name($item1,$item2);
-		else
-			return (strtolower($item1->get_description()) < strtolower($item2->get_description()) ? -1 : 1);
+	function sort_by_description($item1, $item2) {
+		if (strtolower($item1->get_description()) == strtolower($item2->get_description())) {
+			return $this->sort_by_name($item1,$item2);			
+		} else {
+			return (strtolower($item1->get_description()) < strtolower($item2->get_description()) ? -1 : 1);			
+		}
+
 	}
 	
-	function sort_by_weight($item1, $item2)
-	{
-		if ($item1->get_weight() == $item2->get_weight())
-			return $this->sort_by_name($item1,$item2);
-		else
-			return ($item1->get_weight() < $item2->get_weight() ? -1 : 1);
+	function sort_by_weight($item1, $item2) {
+		if ($item1->get_weight() == $item2->get_weight()) {
+			return $this->sort_by_name($item1,$item2);		
+		} else {
+			return ($item1->get_weight() < $item2->get_weight() ? -1 : 1);			
+		}
 	}
 	
-	function sort_by_date($item1, $item2)
-	{
-		if ($item1->get_date() == $item2->get_date())
-			return $this->sort_by_name($item1,$item2);
-		else
-			return ($item1->get_date() < $item2->get_date() ? -1 : 1);
+	function sort_by_date($item1, $item2) {
+		if ($item1->get_date() == $item2->get_date()) {
+			return $this->sort_by_name($item1,$item2);			
+		} else {
+			return ($item1->get_date() < $item2->get_date() ? -1 : 1);			
+		}
 	}
 	
 
 // Other functions
 
-
 	private function build_result_column ($item, $ignore_score_color)
 	{
 		$scoredisplay = ScoreDisplay :: instance();
 		$score = $item->calc_score(api_get_user_id());
 
-		switch ($item->get_item_type())
-		{
+		switch ($item->get_item_type()) {
 			// category
 			case 'C' :
-				if ($score != null)
-				{
+				if ($score != null) {
 					$displaytype = SCORE_PERCENT;
-					if ($ignore_score_color)
-						$displaytype |= SCORE_IGNORE_SPLIT;
-					return get_lang('Total') . ' : '
-						 . $scoredisplay->display_score($score,$displaytype);
-				}
-				else
+					if ($ignore_score_color) {
+						$displaytype |= SCORE_IGNORE_SPLIT;			
+					}
+						return get_lang('Total') . ' : '. $scoredisplay->display_score($score,$displaytype);
+				} else {
 					return '';
-
+				}
 			// evaluation and link
 			case 'E' :
 			case 'L' :
 				$displaytype = SCORE_DIV_PERCENT;
-				if ($ignore_score_color)
-					$displaytype |= SCORE_IGNORE_SPLIT;
+				if ($ignore_score_color) {
+					$displaytype |= SCORE_IGNORE_SPLIT;					
+				}
 				return $scoredisplay->display_score($score,$displaytype);
 		}
 	}
 
-	private function build_date_column ($item)
-	{
+	private function build_date_column ($item) {
 		$date = $item->get_date();
-		if (!isset($date) || empty($date))
-			return '';
-		else
-			return date("j/n/Y g:i", $date);
+		if (!isset($date) || empty($date)) {
+			return '';			
+		} else {
+			return date("j/n/Y g:i", $date);			
+		}
 	}
-
-
-}
-?>
+}

+ 181 - 33
main/gradebook/lib/gradebook_functions.inc.php

@@ -25,14 +25,105 @@
 * @author Stijn Konings <konings.stijn@skynet.be>, Hogeschool Ghent
 * @version april 2007
 */
-include_once ('gradebook_functions_users.inc.php');
+require_once ('gradebook_functions_users.inc.php');
 
 
-function block_students()
-{
-	if (!api_is_allowed_to_create_course())
-	{
-		include (api_get_path(INCLUDE_PATH)."header.inc.php");
+/**
+ * Adds a resource to the unique gradebook of a given course
+ * @param   string  Course code
+ * @param   int     Resource type (use constants defined in linkfactory.class.php)
+ * @param   int     Resource ID in the corresponding tool
+ * @param   string  Resource name to show in the gradebook
+ * @param   int     Resource weight to set in the gradebook
+ * @param   int     Resource max
+ * @param   string  Resource description
+ * @param   string  Date
+ * @param   int     Visibility (0 hidden, 1 shown)
+ * @param   int     Session ID (optional or 0 if not defined)
+ * @return  boolean True on success, false on failure
+ */
+function add_resource_to_course_gradebook($course_code, $resource_type, $resource_id, $resource_name='', $weight=0, $max=0, $resource_description='', $date=null, $visible=0, $session_id = 0) {
+    /* See defines in lib/be/linkfactory.class.php
+    define('LINK_EXERCISE',1);
+    define('LINK_DROPBOX',2);
+    define('LINK_STUDENTPUBLICATION',3);
+    define('LINK_LEARNPATH',4);
+    define('LINK_FORUM_THREAD',5),
+    define('LINK_WORK',6);
+    */
+    $category = 0;
+    require_once (api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php');
+    $link= LinkFactory :: create($resource_type);
+    $link->set_user_id(api_get_user_id());
+    $link->set_course_code($course_code);
+    // TODO find the corresponding category (the first one for this course, ordered by ID)
+    $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+    $sql = "SELECT * FROM $t WHERE course_code = '".Database::escape_string($course_code)."' ";
+    if (!empty($session_id)) {
+    	$sql .= " AND session_id = ".(int)$session_id;
+    } else {
+    	$sql .= " AND (session_id IS NULL OR session_id = 0) ";
+    }
+    $sql .= " ORDER BY id";
+    $res = api_sql_query($sql,__FILE__,__LINE__);
+    if (Database::num_rows($res)<1){ 
+        //there is no unique category for this course+session combination,
+        // => create one
+        $cat= new Category();
+        if (!empty($session_id)) {
+            $s_name = api_get_session_name();
+            $cat->set_name($course_code.' - '.get_lang('Session').' '.$s_name);
+            $cat->set_session_id($session_id);
+        } else {
+            $cat->set_name($course_code);
+        }
+        $cat->set_course_code($course_code);
+        $cat->set_description(null);
+        $cat->set_user_id(api_get_user_id());
+        $cat->set_parent_id(0);
+        $cat->set_weight(100);
+        $cat->set_visible(0);
+        $can_edit = api_is_allowed_to_edit(true, true);
+        if ($can_edit) {
+            $cat->add();
+        }
+        $category = $cat->get_id();
+        unset ($cat);
+    } else {
+        $row = Database::fetch_array($res);
+        $category = $row['id'];
+    }
+    $link->set_category_id($category);
+    
+    if ($link->needs_name_and_description()) {
+    	$link->set_name($resource_name);
+    } else {
+    	$link->set_ref_id($resource_id);
+    }
+    $link->set_weight($weight);
+    
+    if ($link->needs_max()) {
+    	$link->set_max($max);
+    }
+    if (isset($date)) {
+        $link->set_date($date);
+    }
+    if ($link->needs_name_and_description()) {
+    	$link->set_description($resource_description);
+    }
+        
+    $link->set_visible(empty ($visible) ? 0 : 1);
+
+    if (!empty($session_id)) {
+    	$link->set_session_id($session_id);
+    }
+    $link->add();
+    return true;
+}
+
+function block_students() {
+	if (!api_is_allowed_to_create_course()) {
+		require_once (api_get_path(INCLUDE_PATH)."header.inc.php");
 		api_not_allowed();
 	}
 }
@@ -46,13 +137,11 @@ function block_students()
  * Returns the course name from a given code
  * @param string $code
  */
-function get_course_name_from_code($code)
-{
+function get_course_name_from_code($code) {
 	$tbl_main_categories= Database :: get_main_table(TABLE_MAIN_COURSE);
 	$sql= 'SELECT title,code FROM ' . $tbl_main_categories . 'WHERE code = "' . $code . '"';
 	$result= api_sql_query($sql,__FILE__,__LINE__);
-	if ($col= Database::fetch_array($result))
-	{
+	if ($col= Database::fetch_array($result)) {
 		return $col['title'];
 	}
 }
@@ -60,8 +149,7 @@ function get_course_name_from_code($code)
  * Builds an img tag for a gradebook item
  * @param string $type value returned by a gradebookitem's get_icon_name()
  */
-function build_type_icon_tag($kind)
-{
+function build_type_icon_tag($kind) {
 	return '<img src="' . get_icon_file_name ($kind) . '" border="0" hspace="5" align="middle" alt="" />';
 }
 
@@ -70,18 +158,18 @@ function build_type_icon_tag($kind)
  * Returns the icon filename for a gradebook item
  * @param string $type value returned by a gradebookitem's get_icon_name()
  */
-function get_icon_file_name ($type)
-{
-	if ($type == 'cat')
+function get_icon_file_name ($type) {
+	if ($type == 'cat') {
 		return api_get_path(WEB_CODE_PATH) . 'img/folder_document.gif';
-	elseif ($type == 'evalempty')
+	} elseif ($type == 'evalempty') {
 		return api_get_path(WEB_CODE_PATH) . 'img/empty.gif';
-	elseif ($type == 'evalnotempty')
+	} elseif ($type == 'evalnotempty') {
 		return api_get_path(WEB_CODE_PATH) . 'img/gradebook_eval_not_empty.gif';
-	elseif ($type == 'link')
+	} elseif ($type == 'link') {
 		return api_get_path(WEB_CODE_PATH) . 'img/link.gif';
-	else
+	} else {
 		return null;
+	}
 }
 
 
@@ -91,18 +179,15 @@ function get_icon_file_name ($type)
  * @param object $cat category object
  * @param int $selectcat id of selected category
  */
-function build_edit_icons_cat($cat, $selectcat)
-{
+function build_edit_icons_cat($cat, $selectcat) {
 	$visibility_icon= ($cat->is_visible() == 0) ? 'invisible' : 'visible';
 	$visibility_command= ($cat->is_visible() == 0) ? 'set_visible' : 'set_invisible';
 	$modify_icons= '<a href="gradebook_edit_cat.php?editcat=' . $cat->get_id() . '"><img src="../img/edit.gif" border="0" title="' . get_lang('Modify') . '" alt="" /></a>';
-	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . '" onclick="return confirmation();"><img src="../img/delete.gif" border="0" title="' . get_lang('DeleteAll') . '" alt="" /></a>';
+	//$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . '" onclick="return confirmation();"><img src="../img/delete.gif" border="0" title="' . get_lang('DeleteAll') . '" alt="" /></a>';
 	//no move ability for root categories
-	if ($cat->is_movable())
-	{
+	if ($cat->is_movable()) {
 		$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?movecat=' . $cat->get_id() . '&amp;selectcat=' . $selectcat . '"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
-	} else
-	{
+	} else {
 		$modify_icons .= '&nbsp;<img src="../img/deplacer_fichier_na.gif" border="0" title="' . get_lang('Move') . '" alt="" />';
 	}
 	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblecat=' . $cat->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . '"><img src="../img/' . $visibility_icon . '.gif" border="0" title="' . get_lang('Visible') . '" alt="" /></a>';
@@ -113,14 +198,16 @@ function build_edit_icons_cat($cat, $selectcat)
  * @param object $eval evaluation object
  * @param int $selectcat id of selected category
  */
-function build_edit_icons_eval($eval, $selectcat)
-{
+function build_edit_icons_eval($eval, $selectcat) {
 	$visibility_icon= ($eval->is_visible() == 0) ? 'invisible' : 'visible';
 	$visibility_command= ($eval->is_visible() == 0) ? 'set_visible' : 'set_invisible';
 	$modify_icons= '<a href="gradebook_edit_eval.php?editeval=' . $eval->get_id() . '"><img src="../img/edit.gif" border="0" title="' . get_lang('Modify') . '" alt="" /></a>';
 	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deleteeval=' . $eval->get_id() . '&selectcat=' . $selectcat . '" onclick="return confirmation();"><img src="../img/delete.gif" border="0" title="' . get_lang('Delete') . '" alt="" /></a>';
-	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?moveeval=' . $eval->get_id() . '&selectcat=' . $selectcat . '"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
+	//$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?moveeval=' . $eval->get_id() . '&selectcat=' . $selectcat . '"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
 	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visibleeval=' . $eval->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . '"><img src="../img/' . $visibility_icon . '.gif" border="0" title="' . get_lang('Visible') . '" alt="" /></a>';
+	if (api_is_course_admin() == true){
+		$modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog=' . $eval->get_id() . '&amp;selectcat=' . $selectcat . '"><img src="../img/file_txt_small.gif" border="0" title="' . get_lang('GradebookQualifyLog') . '" alt="" /></a>';
+	}
 	return $modify_icons;
 }
 /**
@@ -128,14 +215,75 @@ function build_edit_icons_eval($eval, $selectcat)
  * @param object $linkobject
  * @param int $selectcat id of selected category
  */
-function build_edit_icons_link($link, $selectcat)
-{
+function build_edit_icons_link($link, $selectcat) {
 	$visibility_icon= ($link->is_visible() == 0) ? 'invisible' : 'visible';
 	$visibility_command= ($link->is_visible() == 0) ? 'set_visible' : 'set_invisible';
 	$modify_icons= '<a href="gradebook_edit_link.php?editlink=' . $link->get_id() . '"><img src="../img/edit.gif" border="0" title="' . get_lang('Modify') . '" alt="" /></a>';
 	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?deletelink=' . $link->get_id() . '&selectcat=' . $selectcat . '" onclick="return confirmation();"><img src="../img/delete.gif" border="0" title="' . get_lang('Delete') . '" alt="" /></a>';
-	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?movelink=' . $link->get_id() . '&selectcat=' . $selectcat . '"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
+	//$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?movelink=' . $link->get_id() . '&selectcat=' . $selectcat . '"><img src="../img/deplacer_fichier.gif" border="0" title="' . get_lang('Move') . '" alt="" /></a>';
 	$modify_icons .= '&nbsp;<a href="' . api_get_self() . '?visiblelink=' . $link->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . '"><img src="../img/' . $visibility_icon . '.gif" border="0" title="' . get_lang('Visible') . '" alt="" /></a>';
+	$modify_icons .= '&nbsp;<a href="gradebook_showlog_link.php?visiblelink=' . $link->get_id() . '&amp;selectcat=' . $selectcat . '"><img src="../img/file_txt_small.gif" border="0" title="' . get_lang('GradebookQualifyLog') . '" alt="" /></a>';
+	//if (api_is_course_admin() == true){
+	//$modify_icons .= '&nbsp;<a href="gradebook_showlog_eval.php?visiblelog=' . $eval->get_id() . '&amp;' . $visibility_command . '=&amp;selectcat=' . $selectcat . '"><img src="../img/file_txt_small.gif" border="0" title="' . get_lang('GradebookQualifyLog') . '" alt="" /></a>';
+	//}
 	return $modify_icons;
 }
-?>
+
+/**
+ * Checks if a resource is in the unique gradebook of a given course
+ * @param    string  Course code
+ * @param    int     Resource type (use constants defined in linkfactory.class.php)
+ * @param    int     Resource ID in the corresponding tool
+ * @param    int     Session ID (optional -  0 if not defined)
+ * @return   int     false on error or link ID
+ */
+function is_resource_in_course_gradebook($course_code, $resource_type, $resource_id, $session_id = 0) {
+    /* See defines in lib/be/linkfactory.class.php
+    define('LINK_EXERCISE',1);
+    define('LINK_DROPBOX',2);
+    define('LINK_STUDENTPUBLICATION',3);
+    define('LINK_LEARNPATH',4);
+    define('LINK_FORUM_THREAD',5),
+    define('LINK_WORK',6);
+    */
+    require_once(api_get_path(SYS_CODE_PATH).'gradebook/lib/be/linkfactory.class.php');
+    require_once (api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php');
+	require_once(api_get_path(SYS_CODE_PATH).'gradebook/lib/be/linkfactory.class.php');
+    // TODO find the corresponding category (the first one for this course, ordered by ID)
+    $t = Database::get_main_table(TABLE_MAIN_GRADEBOOK_CATEGORY);
+    $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+    $sql = "SELECT * FROM $t WHERE course_code = '".Database::escape_string($course_code)."' ";
+    if (!empty($session_id)) {
+        $sql .= " AND session_id = ".(int)$session_id;
+    } else {
+        $sql .= " AND (session_id IS NULL OR session_id = 0) ";
+    }
+    $sql .= " ORDER BY id";
+    $res = api_sql_query($sql,__FILE__,__LINE__);
+    if (Database::num_rows($res)<1) { 
+    	return false; 
+    }
+    $row = Database::fetch_array($res);
+    $category = $row['id'];
+    $sql = "SELECT * FROM $l l WHERE l.category_id = $category AND type = ".(int) $resource_type." and ref_id = ".(int) $resource_id;
+    $res = api_sql_query($sql,__FILE__,__LINE__);
+    if (Database::num_rows($res)<1) { 
+    	return false; 
+    }
+    $row = Database::fetch_array($res);
+    return $row['id'];    
+}
+/**
+ * Remove a resource from the unique gradebook of a given course
+ * @param    int     Link/Resource ID
+ * @return   bool    false on error, true on success
+ */
+function remove_resource_from_course_gradebook($link_id) {
+    if ( empty($link_id) ) { return false; }
+    require_once (api_get_path(SYS_CODE_PATH).'gradebook/lib/be.inc.php');
+    // TODO find the corresponding category (the first one for this course, ordered by ID)
+    $l = Database::get_main_table(TABLE_MAIN_GRADEBOOK_LINK);
+    $sql = "DELETE FROM $l WHERE id = ".(int)$link_id;
+    $res = api_sql_query($sql,__FILE__,__LINE__);
+    return true;
+}

+ 51 - 53
main/gradebook/lib/gradebook_functions_users.inc.php

@@ -1,16 +1,36 @@
 <?php
-
 /*
- * Various user related functions
- */
+==============================================================================
+	Dokeos - elearning and course management software
+
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+/**
+ * Various user related functions
+ * @package dokeos.gradebook
+ */
 /**
  * returns users within a course given by param
  * @param $course_id
  */
-function get_users_in_course($course_id)
-{
+function get_users_in_course($course_id) {
 	$tbl_course_user = Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 	$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
 
@@ -21,17 +41,14 @@ function get_users_in_course($course_id)
 			." AND course_rel_user.course_code='".$course_id."'"
 			.' ORDER BY lastname ASC';
 	$result = api_sql_query($sql, __FILE__, __LINE__);
-	return get_user_array_from_mysql_result($result);
+	return get_user_array_from_sql_result($result);
 }
 
 
-function get_user_array_from_mysql_result($result)
-{
+function get_user_array_from_sql_result($result) {
 	$a_students = array();
-	while ($user = mysql_fetch_array($result))
-	{
-		if (!array_key_exists($user['user_id'],$a_students))
-		{
+	while ($user = Database::fetch_array($result)) {
+		if (!array_key_exists($user['user_id'],$a_students)) {
 			$a_current_student = array ();
 			$a_current_student[] = $user['user_id'];
 			$a_current_student[] = $user['lastname'];
@@ -39,30 +56,22 @@ function get_user_array_from_mysql_result($result)
 			$a_students['STUD'.$user['user_id']] = $a_current_student;
 		}
 	}
-	//var_dump($a_students);
 	return $a_students;
 }
 
-function get_all_users ($evals = array(), $links = array())
-{
+function get_all_users ($evals = array(), $links = array()) {
 	$coursecodes = array();
 	$users = array();
 	
-	foreach ($evals as $eval)
-	{
+	foreach ($evals as $eval) {
 		$coursecode = $eval->get_course_code();
 		// evaluation in course
-		if (isset($coursecode) && !empty($coursecode))
-		{
-			if (!array_key_exists($coursecode,$coursecodes))
-			{
+		if (isset($coursecode) && !empty($coursecode)) {
+			if (!array_key_exists($coursecode,$coursecodes)) {
 				$coursecodes[$coursecode] = '1';
 				$users = array_merge($users, get_users_in_course($coursecode));
 			}
-		}
-		// course independent evaluation
-		else
-		{
+		} else {// course independent evaluation
 			$tbl_user = Database :: get_main_table(TABLE_MAIN_USER);
 			$tbl_res = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_RESULT);
 			
@@ -71,71 +80,60 @@ function get_all_users ($evals = array(), $links = array())
 					.' WHERE res.evaluation_id = '.$eval->get_id()
 					.' AND res.user_id = user.user_id';
 			$result = api_sql_query($sql, __FILE__, __LINE__);
-			$users = array_merge($users,get_user_array_from_mysql_result($result));
+			$users = array_merge($users,get_user_array_from_sql_result($result));
 		}
 	}
 	
-	foreach ($links as $link)
-	{
+	foreach ($links as $link) {
 		// links are always in a course
 		$coursecode = $link->get_course_code();
-		if (!array_key_exists($coursecode,$coursecodes))
-		{
+		if (!array_key_exists($coursecode,$coursecodes)) {
 			$coursecodes[$coursecode] = '1';
 			$users = array_merge($users, get_users_in_course($coursecode));
 		}
 	}
-	
 	unset ($coursecodes);
-	
 	return $users;
-	
 }
 
-
 /**
  * Search students matching a given last name and/or first name
  * @author Bert Stepp�
  */
-function find_students($mask= '')
-{
+function find_students($mask= '') {
 	// students shouldn't be here // don't search if mask empty
-	if (!api_is_allowed_to_create_course() || empty ($mask))
-		return null;
-	
+	if (!api_is_allowed_to_create_course() || empty ($mask)) {
+		return null;		
+	}
 	$tbl_user= Database :: get_main_table(TABLE_MAIN_USER);
 	$tbl_cru= Database :: get_main_table(TABLE_MAIN_COURSE_USER);
 	$sql= 'SELECT DISTINCT user.user_id, user.lastname, user.firstname, user.email' . ' FROM ' . $tbl_user . ' user';
-	if (!api_is_platform_admin())
-		$sql .= ', ' . $tbl_cru . ' cru';
+	if (!api_is_platform_admin()) {
+		$sql .= ', ' . $tbl_cru . ' cru';	
+	}
+
 	$sql .= ' WHERE user.status = ' . STUDENT;
 	$sql .= ' AND (user.lastname LIKE '."'%" . $mask . "%'";
 	$sql .= ' OR user.firstname LIKE '."'%" . $mask . "%')";
 
-	if (!api_is_platform_admin())
-		$sql .= ' AND user.user_id = cru.user_id' . ' AND cru.course_code in' . ' (SELECT course_code' . ' FROM ' . $tbl_cru . ' WHERE user_id = ' . api_get_user_id() . ' AND status = ' . COURSEMANAGER . ')';
+	if (!api_is_platform_admin()) {
+		$sql .= ' AND user.user_id = cru.user_id' . ' AND cru.course_code in' . ' (SELECT course_code' . ' FROM ' . $tbl_cru . ' WHERE user_id = ' . api_get_user_id() . ' AND status = ' . COURSEMANAGER . ')';	
+	}
 	$sql .= ' ORDER BY lastname';
 	$result= api_sql_query($sql, __FILE__, __LINE__);
 	$db_users= api_store_result($result);
 	return $db_users;
 }
 
-
 /**
  * Get user information from a given id
  * @param int $userid The userid
  * @return array All user information as an associative array
  */
-function get_user_info_from_id($userid)
-{
+function get_user_info_from_id($userid) {
 	$user_table= Database :: get_main_table(TABLE_MAIN_USER);
 	$sql= 'SELECT * FROM ' . $user_table . ' WHERE user_id=' . $userid;
-	//var_dump( $sql);
 	$res= api_sql_query($sql, __FILE__, __LINE__);
-	$user= mysql_fetch_array($res, MYSQL_ASSOC);
+	$user= Database::fetch_array($res,ASSOC);
 	return $user;
-}
-
-
-
-?>
+}

+ 70 - 60
main/gradebook/lib/results_data_generator.class.php

@@ -1,9 +1,31 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 /**
  * Class to select, sort and transform object data into array data,
  * used for the teacher's evaluation results view
- * @author Bert Steppé
+ * @author Bert Steppé
  */
 class ResultsDataGenerator
 {
@@ -29,8 +51,7 @@ class ResultsDataGenerator
 	 */
     function ResultsDataGenerator ( $evaluation,
     								$results = array(),
-    								$include_edit = false)
-    {
+    								$include_edit = false) {
     	$this->evaluation = $evaluation;
 		$this->results = (isset($results) ? $results : array());
     }
@@ -39,8 +60,7 @@ class ResultsDataGenerator
 	/**
 	 * Get total number of results (rows)
 	 */
-	public function get_total_results_count()
-	{
+	public function get_total_results_count () {
 		return count($this->results);
 	}
 
@@ -55,21 +75,19 @@ class ResultsDataGenerator
 	 * 4 ['score']     : student's score
 	 * 5 ['display']   : custom score display (only if custom scoring enabled)
 	 */
-	public function get_data ($sorting = 0, $start = 0, $count = null, $ignore_score_color = false)
-	{
+	public function get_data ($sorting = 0, $start = 0, $count = null, $ignore_score_color = false) {
 
 		// do some checks on count, redefine if invalid value
-		if (!isset($count))
+		if (!isset($count)) {
 			$count = count ($this->results) - $start;
-		if ($count < 0)
+		}
+		if ($count < 0) {
 			$count = 0;
-
+		}
 		$scoredisplay = ScoreDisplay :: instance();
-
 		// generate actual data array
 		$table = array();
-		foreach($this->results as $result)
-		{
+		foreach($this->results as $result) {
 			$user = array();
 			$info = get_user_info_from_id($result->get_user_id());
 			$user['id'] = $result->get_user_id();
@@ -84,77 +102,69 @@ class ResultsDataGenerator
 
 
 		// sort array
-		if ($sorting & self :: RDG_SORT_LASTNAME)
+		if ($sorting & self :: RDG_SORT_LASTNAME) {
 			usort($table, array('ResultsDataGenerator', 'sort_by_last_name'));
-		elseif ($sorting & self :: RDG_SORT_FIRSTNAME)
-			usort($table, array('ResultsDataGenerator', 'sort_by_first_name'));
-		elseif ($sorting & self :: RDG_SORT_SCORE)
+		} elseif ($sorting & self :: RDG_SORT_FIRSTNAME) {
+			usort($table, array('ResultsDataGenerator', 'sort_by_first_name'));	
+		} elseif ($sorting & self :: RDG_SORT_SCORE) {
 			usort($table, array('ResultsDataGenerator', 'sort_by_score'));
-		elseif ($sorting & self :: RDG_SORT_MASK)
-			usort($table, array('ResultsDataGenerator', 'sort_by_mask'));
-		if ($sorting & self :: RDG_SORT_DESC)
-			$table = array_reverse($table);
-
-
+		} elseif ($sorting & self :: RDG_SORT_MASK) {
+			usort($table, array('ResultsDataGenerator', 'sort_by_mask'));			
+		}
+		if ($sorting & self :: RDG_SORT_DESC) {
+			$table = array_reverse($table);			
+		}
 		return array_slice($table, $start, $count);
 
 	}
 
-
-
-	private function get_score_display ($score, $realscore, $ignore_score_color)
-	{
-		if ($score != null)
-		{
+	private function get_score_display ($score, $realscore, $ignore_score_color) {
+		if ($score != null) {
 			$display_type = SCORE_DIV_PERCENT;
-			if ($ignore_score_color)
-				$display_type |= SCORE_IGNORE_SPLIT;
+			if ($ignore_score_color) {
+				$display_type |= SCORE_IGNORE_SPLIT;				
+			}
 			$scoredisplay = ScoreDisplay :: instance();
 			return $scoredisplay->display_score
 					(array($score,$this->evaluation->get_max()),
 					 $display_type,
 					 $realscore ? SCORE_ONLY_DEFAULT : SCORE_ONLY_CUSTOM);
-		}
-		else
-			return '';
+			}
+			else {
+				return '';			
+		  }
 	}
 
-
-
-
-
 	// Sort functions - used internally
-
-	function sort_by_last_name($item1, $item2)
-	{
-		if (strtolower($item1['lastname']) == strtolower($item2['lastname']))
+	function sort_by_last_name($item1, $item2) {
+		if (strtolower($item1['lastname']) == strtolower($item2['lastname'])) {
 			return 0;
-		else
-			return (strtolower($item1['lastname']) < strtolower($item2['lastname']) ? -1 : 1);
+		} else {
+			return (strtolower($item1['lastname']) < strtolower($item2['lastname']) ? -1 : 1);			
+		}
 	}
 
-	function sort_by_first_name($item1, $item2)
-	{
-		if (strtolower($item1['firstname']) == strtolower($item2['firstname']))
+	function sort_by_first_name($item1, $item2) {
+		if (strtolower($item1['firstname']) == strtolower($item2['firstname'])) {
 			return 0;
-		else
-			return (strtolower($item1['firstname']) < strtolower($item2['firstname']) ? -1 : 1);
+		}
+		else {
+			return (strtolower($item1['firstname']) < strtolower($item2['firstname']) ? -1 : 1);			
+		}
+
 	}
 	
-	function sort_by_score($item1, $item2)
-	{
-		if ($item1['score'] == $item2['score'])
-			return 0;
-		else
-			return ($item1['score'] < $item2['score'] ? -1 : 1);
+	function sort_by_score($item1, $item2) {
+		if ($item1['score'] == $item2['score']) {
+			return 0;			
+		}else {
+			return ($item1['score'] < $item2['score'] ? -1 : 1);			
+		}
 	}
 	
-	function sort_by_mask ($item1, $item2)
-	{
+	function sort_by_mask ($item1, $item2) {
 		$score1 = (isset($item1['score']) ? array($item1['score'],$this->evaluation->get_max()) : null);
 		$score2 = (isset($item2['score']) ? array($item2['score'],$this->evaluation->get_max()) : null);
 		return ScoreDisplay :: compare_scores_by_custom_display($score1, $score2);
 	}
-
-}
-?>
+}

+ 116 - 146
main/gradebook/lib/scoredisplay.class.php

@@ -1,14 +1,33 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
 // Score display types constants
 define('SCORE_DIV',1);
 define('SCORE_PERCENT',2);
 define('SCORE_DIV_PERCENT',3);
 define('SCORE_AVERAGE',4);
-
 define('SCORE_IGNORE_SPLIT', 8);
-
 define('SCORE_BOTH',1);
 define('SCORE_ONLY_DEFAULT',2);
 define('SCORE_ONLY_CUSTOM',3);
@@ -28,11 +47,11 @@ class ScoreDisplay
 	/**
 	 * Get the instance of this class
 	 */
-	public static function instance()
-	{
+	public static function instance() {
 		static $instance;
-		if (!isset ($instance))
-			$instance = new ScoreDisplay();
+		if (!isset ($instance)) {
+			$instance = new ScoreDisplay();	
+		}
 		return $instance;
 	}
 	
@@ -44,24 +63,22 @@ class ScoreDisplay
 	 */
 	public static function compare_scores_by_custom_display ($score1, $score2)
 	{
-		if (!isset($score1))
-			return (isset($score2) ? 1 : 0);
-		elseif (!isset($score2))
-			return -1;
-		else
-		{
+		if (!isset($score1)) {
+			return (isset($score2) ? 1 : 0);			
+		} elseif (!isset($score2)) {
+			return -1;			
+		} else {
 			$scoredisplay = ScoreDisplay :: instance();
 			$custom1 = $scoredisplay->display_custom($score1);
 			$custom2 = $scoredisplay->display_custom($score2);
-			if ($custom1 == $custom2)
-				return 0;
-			else
-				return (($score1[0]/$score1[1]) < ($score2[0]/$score2[1]) ? -1 : 1);
+			if ($custom1 == $custom2) {
+				return 0;				
+			} else {
+				return (($score1[0]/$score1[1]) < ($score2[0]/$score2[1]) ? -1 : 1);				
+			}
+
 		}
 	}
-
-
-
 // As object
 
 	private $coloring_enabled;
@@ -75,23 +92,18 @@ class ScoreDisplay
 	/**
 	 * Protected constructor - call instance() to instantiate
 	 */
-    protected function ScoreDisplay()
-    {
+    protected function ScoreDisplay() {
     	$this->coloring_enabled = $this->load_bool_setting('gradebook_score_display_coloring',0);
-    	if ($this->coloring_enabled)
-    		$this->color_split_value = $this->load_int_setting('gradebook_score_display_colorsplit',50);
-    	
+    	if ($this->coloring_enabled) {
+    		$this->color_split_value = $this->load_int_setting('gradebook_score_display_colorsplit',50);    		
+    	}
     	$this->custom_enabled = $this->load_bool_setting('gradebook_score_display_custom', 0);
-    	if ($this->custom_enabled)
-    	{
+    	if ($this->custom_enabled) {
     		$this->upperlimit_included = $this->load_bool_setting('gradebook_score_display_upperlimit', 0);
     		$this->custom_display = $this->get_custom_displays();
     		$this->custom_display_conv = $this->convert_displays($this->custom_display);
     	}
     }
-
-	
-
 	/**
 	 * Is coloring enabled ?
 	 */
@@ -99,7 +111,6 @@ class ScoreDisplay
 	{
 		return $this->coloring_enabled;
 	}
-	
 	/**
 	 * Is custom score display enabled ?
 	 */
@@ -107,7 +118,6 @@ class ScoreDisplay
 	{
 		return $this->custom_enabled;
 	}
-
 	/**
 	 * Is upperlimit included ?
 	 */
@@ -115,14 +125,11 @@ class ScoreDisplay
 	{
 		return $this->upperlimit_included;
 	}
-
-
 	/**
 	 * Update the 'coloring' setting
 	 * @param boolean $coloring coloring enabled or disabled
 	 */
-	public function set_coloring_enabled ($coloring)
-	{
+	public function set_coloring_enabled ($coloring) {
 		$this->coloring_enabled = $coloring;
 		$this->save_bool_setting ('gradebook_score_display_coloring', $coloring);
 	}
@@ -131,8 +138,7 @@ class ScoreDisplay
 	 * Update the 'colorsplit' setting
 	 * @param int $colorsplit color split value, in percent
 	 */
-	public function set_color_split_value ($colorsplit)
-	{
+	public function set_color_split_value ($colorsplit) {
 		$this->color_split_value = $colorsplit;
 		$this->save_int_setting ('gradebook_score_display_colorsplit', $colorsplit);
 	}
@@ -142,8 +148,7 @@ class ScoreDisplay
 	 * Update the 'custom' setting
 	 * @param boolean $custom custom enabled or disabled
 	 */
-	public function set_custom ($custom)
-	{
+	public function set_custom ($custom) {
 		$this->custom_enabled = $custom;
 		$this->save_bool_setting ('gradebook_score_display_custom', $custom);
 	}
@@ -152,8 +157,7 @@ class ScoreDisplay
 	 * Update the 'upperlimit' setting
 	 * @param boolean $upperlimit_included true if upper limit must be included, false otherwise
 	 */
-	public function set_upperlimit_included ($upperlimit_included)
-	{
+	public function set_upperlimit_included ($upperlimit_included) {
 		$this->upperlimit_incl = $upperlimit_included;
 		$this->save_bool_setting ('gradebook_score_display_upperlimit', $upperlimit_included);
 	}
@@ -163,8 +167,7 @@ class ScoreDisplay
 	 * See also update_custom_score_display_settings
 	 * @return array current settings (or null if feature not enabled)
 	 */
-	public function get_custom_score_display_settings()
-	{
+	public function get_custom_score_display_settings() {
 		return $this->custom_display;
 	}
 
@@ -172,8 +175,7 @@ class ScoreDisplay
 	 * If coloring is enabled, scores below this value will be displayed in red.
 	 * @return int color split value, in percent (or null if feature not enabled)
 	 */
-	public function get_color_split_value()
-	{
+	public function get_color_split_value() {
 		return $this->color_split_value;
 	}
 
@@ -181,8 +183,7 @@ class ScoreDisplay
 	 * Update custom score display settings
 	 * @param array $displays 2-dimensional array - every subarray must have keys (score, display)
 	 */
-	public function update_custom_score_display_settings ($displays)
-	{
+	public function update_custom_score_display_settings ($displays) {
 		$this->custom_display = $displays;
    		$this->custom_display_conv = $this->convert_displays($this->custom_display);
 		
@@ -194,19 +195,16 @@ class ScoreDisplay
 		// add new settings
 		$sql = 'INSERT INTO '.$tbl_display.' (id, score, display) VALUES ';
 		$count = 0;
-		foreach ($displays as $display)
-		{
-			if ($count > 0)
-				$sql .= ',';
+		foreach ($displays as $display) {
+			if ($count > 0) {
+				$sql .= ',';				
+			}
 			$sql .= "(NULL, '".$display['score']."', '".$display['display']."')";
 			$count++;
 		}
-		
 		api_sql_query($sql, __FILE__, __LINE__);
 	}
 
-	
-
 	/**
 	 * Display a score according to the current settings
 	 * @param array $score score data structure, as returned by the calc_score functions
@@ -215,47 +213,40 @@ class ScoreDisplay
 	 * @param int $what one of the following constants: SCORE_BOTH, SCORE_ONLY_DEFAULT, SCORE_ONLY_CUSTOM (default: SCORE_BOTH)
 	 * (only taken into account if custom score display is enabled and for course/platform admin)
 	 */
-	public function display_score($score,$type,$what = SCORE_BOTH)
-	{
+	public function display_score($score,$type,$what = SCORE_BOTH) {
 		$type2 = $type & 7;	// removes the 'SCORE_IGNORE_SPLIT' bit
 		$split_enabled = ($type2 == $type);
 		
-		if (!isset($score))
-			return '';
-
-		elseif ($this->custom_enabled && isset($this->custom_display_conv))
-		{
-			// students only see the custom display
-			if (!api_is_allowed_to_create_course())
-				$display = $this->display_custom($score);
-
-			// course/platform admins
-			elseif ($what == SCORE_ONLY_DEFAULT)
-				$display = $this->display_default ($score, $type2);
-			elseif ($what == SCORE_ONLY_CUSTOM)
-				$display = $this->display_custom ($score);
-			else
-				$display = $this->display_default ($score, $type2)
-							.' ('.$this->display_custom ($score).')';
-		}
+		if (!isset($score)) {
+			return '';			
+		} elseif ($this->custom_enabled && isset($this->custom_display_conv)) {
+				// students only see the custom display
+				if (!api_is_allowed_to_create_course()) {
+					$display = $this->display_custom($score);				
+				}
+				// course/platform admins
+				elseif ($what == SCORE_ONLY_DEFAULT) {
+					$display = $this->display_default ($score, $type2);				
+				}
+				elseif ($what == SCORE_ONLY_CUSTOM) {
+					$display = $this->display_custom ($score);				
+				} else {
+					$display = $this->display_default ($score, $type2)
+							.' ('.$this->display_custom ($score).')';				
+			}
 
+		} else {
 		// if no custom display set, use default display
-		else
-			$display = $this->display_default ($score, $type2);
-
+			$display = $this->display_default ($score, $type2);		
+		}
 		return (($split_enabled ? $this->get_color_display_start_tag($score) : '')
 				. $display
 				. ($split_enabled ? $this->get_color_display_end_tag($score) : ''));
 	}
-
-
-
 // Internal functions
 
-	private function display_default ($score, $type)
-	{
-		switch ($type)
-		{
+	private function display_default ($score, $type) {
+		switch ($type) {
 			case SCORE_DIV :			// X / Y
 				return $this->display_as_div($score);
 
@@ -271,56 +262,46 @@ class ScoreDisplay
 		}
 	}
 
-	private function display_as_percent ($score)
-	{
+	private function display_as_percent ($score) {
 		return round(($score[0] / $score[1]) * 100) . ' %';
 	}
 
-	private function display_as_div ($score)
-	{
+	private function display_as_div ($score) {
 		return $score[0] . ' / ' . $score[1];
 	}
 
-	private function display_custom ($score)
-	{
+	private function display_custom ($score) {
 		$scaledscore = $score[0] / $score[1];
-		if ($this->upperlimit_included)
-		{
-			foreach ($this->custom_display_conv as $displayitem)
-			{
-				if ($scaledscore <= $displayitem['score'])
+		if ($this->upperlimit_included) {
+			foreach ($this->custom_display_conv as $displayitem) {
+				if ($scaledscore <= $displayitem['score']) {
 					return $displayitem['display'];
+				}
 			}
-		}
-		else
-		{
-			foreach ($this->custom_display_conv as $displayitem)
-			{
-				if ($scaledscore < $displayitem['score'] || $displayitem['score'] == 1)
+		} else {
+			foreach ($this->custom_display_conv as $displayitem) {
+				if ($scaledscore < $displayitem['score'] || $displayitem['score'] == 1) {
 					return $displayitem['display'];
+				}
 			}
 		}
 	}
-
-
-	private function load_bool_setting ($property, $default = 0)
-	{
+	private function load_bool_setting ($property, $default = 0) {
 		$value = $this->load_int_setting($property, $default);
 		return ($value == 'true' ? true : false);
 	}
 
-	private function load_int_setting ($property, $default = 0)
-	{
+	private function load_int_setting ($property, $default = 0) {
     	$tbl_setting = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 
 		$sql = "SELECT selected_value FROM ".$tbl_setting
 				." WHERE category = 'Gradebook' AND variable = '".$property."'";
 		$result = api_sql_query($sql, __FILE__, __LINE__);
 
-		if ($data = mysql_fetch_row($result))
+		if ($data = Database::fetch_row($result)) {
 			return $data[0];
-		else
-		{
+		}
+		else {
 			// if not present, add default setting into table...
 			$sql = "INSERT INTO ".$tbl_setting
 					." (variable, selected_value, category)"
@@ -332,13 +313,11 @@ class ScoreDisplay
 	}
 
 	
-	private function save_bool_setting ($property, $value)
-	{
+	private function save_bool_setting ($property, $value) {
 		$this->save_int_setting ($property, ($value ? 'true' : 'false') );
 	}
 
-	private function save_int_setting ($property, $value)
-	{
+	private function save_int_setting ($property, $value) {
     	$tbl_setting = Database :: get_main_table(TABLE_MAIN_SETTINGS_CURRENT);
 		$sql = 'UPDATE '.$tbl_setting
 				." SET selected_value = '".$value."' "
@@ -351,8 +330,7 @@ class ScoreDisplay
 	 * Get current custom score display settings
 	 * @return array 2-dimensional array - every element contains 3 subelements (id, score, display)
 	 */
-	private function get_custom_displays()
-	{
+	private function get_custom_displays() {
     	$tbl_display = Database :: get_main_table(TABLE_MAIN_GRADEBOOK_SCORE_DISPLAY);
 		$sql = 'SELECT * FROM '.$tbl_display.' ORDER BY score';
 		//echo $sql;
@@ -364,20 +342,17 @@ class ScoreDisplay
 	/**
 	 * Convert display settings to internally used values
 	 */
-	private function convert_displays($custom_display)
-	{
-		if (isset($custom_display))
-		{
+	private function convert_displays($custom_display) {
+		if (isset($custom_display)) {
 			// get highest score entry, and copy each element to a new array
 			$converted = array();
 			$highest = 0;
-			foreach ($custom_display as $element)
-			{
-				if ($element['score'] > $highest)
+			foreach ($custom_display as $element) {
+				if ($element['score'] > $highest) {
 					$highest = $element['score'];
+				}
 				$converted[] = $element;
 			}
-
 			// sort the new array (ascending)
 			usort($converted, array('ScoreDisplay', 'sort_display'));
 
@@ -385,44 +360,39 @@ class ScoreDisplay
 			// each score is scaled between 0 and 1
 			// the highest score in this array will be equal to 1
 			$converted2 = array();
-			foreach ($converted as $element)
-			{
+			foreach ($converted as $element) {
 				$newelement = array();
 				$newelement['score'] = $element['score'] / $highest;
 				$newelement['display'] = $element['display'];
 				$converted2[] = $newelement;
 			}
-			
 			return $converted2;
-		}
-		else
+		} else {
 			return null;
+		}
 	}
 
-	private function sort_display ($item1, $item2)
-	{
-		if ($item1['score'] == $item2['score'])
+	private function sort_display ($item1, $item2) {
+		if ($item1['score'] == $item2['score']) {
 			return 0;
-		else
+		} else {
 			return ($item1['score'] < $item2['score'] ? -1 : 1);
+		}	
 	}
 
-
-	private function get_color_display_start_tag($score)
-	{
-		if ($this->coloring_enabled && ($score[0]/$score[1]) < ($this->color_split_value / 100))
+	private function get_color_display_start_tag($score) {
+		if ($this->coloring_enabled && ($score[0]/$score[1]) < ($this->color_split_value / 100)) {
 			return '<font color="red">';
-		else
-			return '';
+		} else {
+			return '';	
+		}
 	}
 
-	private function get_color_display_end_tag($score)
-	{
-		if ($this->coloring_enabled && ($score[0]/$score[1]) < ($this->color_split_value / 100))
+	private function get_color_display_end_tag($score) {
+		if ($this->coloring_enabled && ($score[0]/$score[1]) < ($this->color_split_value / 100)) {
 			return '</font>';
-		else
+		} else {
 			return '';
+		}
 	}
-
-}
-?>
+}

+ 95 - 126
main/gradebook/lib/user_data_generator.class.php

@@ -30,23 +30,23 @@ class UserDataGenerator
 	private $avgcache;
 
 
-    function UserDataGenerator($userid, $evals = array(), $links = array())
-    {
+    function UserDataGenerator($userid, $evals = array(), $links = array()) {
 		$this->userid = $userid;
 
 		$evals_filtered = array();
-		foreach ($evals as $eval)
-		{
+		foreach ($evals as $eval) {
 			$toadd = true;
 			$coursecode = $eval->get_course_code();
-			if (isset($coursecode))
-			{
+			if (isset($coursecode)) {
 				$result = Result :: load (null, $userid, $eval->get_id());
-				if (count($result) == 0)
+				if (count($result) == 0) {
 					$toadd = false;
+				}	
 			}
-			if ($toadd)
+			if ($toadd) {
 				$evals_filtered[] = $eval;
+			}
+				
 		}
 		
 		$this->items = array_merge ($evals_filtered, $links);
@@ -63,8 +63,7 @@ class UserDataGenerator
 	/**
 	 * Get total number of items (rows)
 	 */
-	public function get_total_items_count()
-	{
+	public function get_total_items_count() {
 		return count($this->items);
 	}
 
@@ -81,72 +80,67 @@ class UserDataGenerator
 	 * 5: student's score
 	 * 6: student's score as custom display (only if custom scoring enabled)
 	 */
-	public function get_data ($sorting = 0, $start = 0, $count = null, $ignore_score_color = false)
-	{
+	public function get_data ($sorting = 0, $start = 0, $count = null, $ignore_score_color = false) {
 		
 		// do some checks on count, redefine if invalid value
-		if (!isset($count))
+		if (!isset($count)) {
 			$count = count ($this->items) - $start;
-		if ($count < 0)
+		}
+		if ($count < 0) {
 			$count = 0;
-
+		}
 		$allitems = $this->items;
 
 		// sort users array
-		if ($sorting & self :: UDG_SORT_TYPE)
+		if ($sorting & self :: UDG_SORT_TYPE) {
 			usort($allitems, array('UserDataGenerator', 'sort_by_type'));
-		elseif ($sorting & self :: UDG_SORT_NAME)
+		}elseif ($sorting & self :: UDG_SORT_NAME) {
 			usort($allitems, array('UserDataGenerator', 'sort_by_name'));
-		elseif ($sorting & self :: UDG_SORT_COURSE)
+		} elseif ($sorting & self :: UDG_SORT_COURSE) {
 			usort($allitems, array('UserDataGenerator', 'sort_by_course'));
-		elseif ($sorting & self :: UDG_SORT_CATEGORY)
+		} elseif ($sorting & self :: UDG_SORT_CATEGORY) {
 			usort($allitems, array('UserDataGenerator', 'sort_by_category'));
-		elseif ($sorting & self :: UDG_SORT_AVERAGE)
-		{
+		} elseif ($sorting & self :: UDG_SORT_AVERAGE) {
 			// if user sorts on average scores, first calculate them and cache them
-			foreach ($allitems as $item)
+			foreach ($allitems as $item) {
 				$this->avgcache[$item->get_item_type() . $item->get_id()]
 								= $item->calc_score();
+			}
 			usort($allitems, array('UserDataGenerator', 'sort_by_average'));
-		}
-		elseif ($sorting & self :: UDG_SORT_SCORE)
-		{
+		} elseif ($sorting & self :: UDG_SORT_SCORE) {
 			// if user sorts on student's scores, first calculate them and cache them
-			foreach ($allitems as $item)
+			foreach ($allitems as $item) {
 				$this->scorecache[$item->get_item_type() . $item->get_id()]
 								= $item->calc_score($this->userid);
+			}		
 			usort($allitems, array('UserDataGenerator', 'sort_by_score'));
-		}
-		elseif ($sorting & self :: UDG_SORT_MASK)
-		{
+		} elseif ($sorting & self :: UDG_SORT_MASK) {
 			// if user sorts on student's masks, first calculate scores and cache them
-			foreach ($allitems as $item)
+			foreach ($allitems as $item) {
 				$this->scorecache[$item->get_item_type() . $item->get_id()]
 								= $item->calc_score($this->userid);
+			}
 			usort($allitems, array('UserDataGenerator', 'sort_by_mask'));
 		}
 
-		if ($sorting & self :: UDG_SORT_DESC)
+		if ($sorting & self :: UDG_SORT_DESC) {
 			$allitems = array_reverse($allitems);
-
+		}
 		// select the items we have to display
 		$visibleitems = array_slice($allitems, $start, $count);
 
-
 		// fill score cache if not done yet
-		if (!isset ($this->scorecache))
-		{
-			foreach ($visibleitems as $item)
+		if (!isset ($this->scorecache)) {
+			foreach ($visibleitems as $item) {
 				$this->scorecache[$item->get_item_type() . $item->get_id()]
 								= $item->calc_score($this->userid);
+			}
+				
 		}
-
-
 		// generate the data to display
 		$scoredisplay = ScoreDisplay :: instance();
 		$data = array();
-		foreach ($visibleitems as $item)
-		{
+		foreach ($visibleitems as $item) {
 			$row = array ();
 			$row[] = $item;
 			$row[] = $item->get_name();
@@ -163,114 +157,98 @@ class UserDataGenerator
 
 	}
 
-
-
-
-
-
-
 // Sort functions
 // Make sure to only use functions as defined in the GradebookItem interface !
 
-	function sort_by_type($item1, $item2)
-	{
-		if ($item1->get_item_type() == $item2->get_item_type())
+	function sort_by_type($item1, $item2) {
+		if ($item1->get_item_type() == $item2->get_item_type()) {
 			return $this->sort_by_name($item1,$item2);
-		else
+		} else {
 			return ($item1->get_item_type() < $item2->get_item_type() ? -1 : 1);
+		}
 	}
 
-	function sort_by_course($item1, $item2)
-	{
+	function sort_by_course($item1, $item2) {
 		$name1 = strtolower($this->get_course_name_from_code_cached($item1->get_course_code()));
 		$name2 = strtolower($this->get_course_name_from_code_cached($item2->get_course_code()));
-		if ($name1 == $name2)
+		if ($name1 == $name2) {
 			return 0;
-		else
+		} else {
 			return ($name1 < $name2 ? -1 : 1);
+		}
 	}
 
-	function sort_by_category($item1, $item2)
-	{
+	function sort_by_category($item1, $item2) {
 		$cat1 = $this->get_category_cached($item1->get_category_id());
 		$cat2 = $this->get_category_cached($item2->get_category_id());
 
 		$name1 = strtolower($this->get_category_name_to_display($cat1));
 		$name2 = strtolower($this->get_category_name_to_display($cat2));
-		if ($name1 == $name2)
+		if ($name1 == $name2) {
 			return 0;
-		else
+		} else {
 			return ($name1 < $name2 ? -1 : 1);
+		}
 	}
 
 
-	function sort_by_name($item1, $item2)
-	{
-		if (strtolower($item1->get_name()) == strtolower($item2->get_name()))
+	function sort_by_name($item1, $item2) {
+		if (strtolower($item1->get_name()) == strtolower($item2->get_name())) {
 			return 0;
-		else
+		} else {
 			return (strtolower($item1->get_name()) < strtolower($item2->get_name()) ? -1 : 1);
+		}		
 	}
 
 
-	function sort_by_average($item1, $item2)
-	{
+	function sort_by_average($item1, $item2) {
 		$score1 = $this->avgcache[$item1->get_item_type() . $item1->get_id()];
 		$score2 = $this->avgcache[$item2->get_item_type() . $item2->get_id()];
 		return $this->compare_scores($score1, $score2);
 	}	
 
-	function sort_by_score($item1, $item2)
-	{
+	function sort_by_score($item1, $item2) {
 		$score1 = $this->scorecache[$item1->get_item_type() . $item1->get_id()];
 		$score2 = $this->scorecache[$item2->get_item_type() . $item2->get_id()];
 		return $this->compare_scores($score1, $score2);
 	}	
 
-	function sort_by_mask($item1, $item2)
-	{
+	function sort_by_mask($item1, $item2) {
 		$score1 = $this->scorecache[$item1->get_item_type() . $item1->get_id()];
 		$score2 = $this->scorecache[$item2->get_item_type() . $item2->get_id()];
 		return ScoreDisplay :: compare_scores_by_custom_display($score1, $score2);
 	}	
 
-	function compare_scores ($score1, $score2)
-	{
-		if (!isset($score1))
+	function compare_scores ($score1, $score2) {
+		if (!isset($score1)) {
 			return (isset($score2) ? 1 : 0);
-		elseif (!isset($score2))
+		} elseif (!isset($score2)) {
 			return -1;
-		elseif (($score1[0]/$score1[1]) == ($score2[0]/$score2[1]))
+		} elseif (($score1[0]/$score1[1]) == ($score2[0]/$score2[1])) {
 			return 0;
-		else
+		} else {
 			return (($score1[0]/$score1[1]) < ($score2[0]/$score2[1]) ? -1 : 1);
+		}
+			
 	}		
 
-
-
-
-
 // Other functions
-
-
-	private function build_course_name ($item)
-	{
+	private function build_course_name ($item) {
 		return $this->get_course_name_from_code_cached($item->get_course_code());
 	}
 
-	private function build_category_name ($item)
-	{
+	private function build_category_name ($item) {
 		$cat = $this->get_category_cached($item->get_category_id());
 		return $this->get_category_name_to_display($cat);
 	}
 
 
-	private function build_average_column ($item, $ignore_score_color)
-	{
-		if (isset($this->avgcache))
+	private function build_average_column ($item, $ignore_score_color) {
+		if (isset($this->avgcache)) {
 			$avgscore = $this->avgcache[$item->get_item_type() . $item->get_id()];
-		else
+		} else {
 			$avgscore = $item->calc_score();
+		}
 		$scoredisplay = ScoreDisplay :: instance();
 		$displaytype = SCORE_AVERAGE;
 		if ($ignore_score_color)
@@ -278,73 +256,64 @@ class UserDataGenerator
 		return $scoredisplay->display_score($avgscore, $displaytype);
 	}
 
-
-	private function build_result_column ($item, $ignore_score_color)
-	{
+	private function build_result_column ($item, $ignore_score_color) {
 		$studscore = $this->scorecache[$item->get_item_type() . $item->get_id()];
 		$scoredisplay = ScoreDisplay :: instance();
 		$displaytype = SCORE_DIV_PERCENT;
-		if ($ignore_score_color)
+		if ($ignore_score_color) {
 			$displaytype |= SCORE_IGNORE_SPLIT;
+		}
 		return $scoredisplay->display_score($studscore, $displaytype, SCORE_ONLY_DEFAULT);
 	}
 
-	private function build_mask_column ($item, $ignore_score_color)
-	{
+	private function build_mask_column ($item, $ignore_score_color) {
 		$studscore = $this->scorecache[$item->get_item_type() . $item->get_id()];
 		$scoredisplay = ScoreDisplay :: instance();
 		$displaytype = SCORE_DIV_PERCENT;
-		if ($ignore_score_color)
+		if ($ignore_score_color) {
 			$displaytype |= SCORE_IGNORE_SPLIT;
+		}
 		return $scoredisplay->display_score($studscore, $displaytype, SCORE_ONLY_CUSTOM);
 	}
 
 
-	private function get_course_name_from_code_cached ($coursecode)
-	{
+	private function get_course_name_from_code_cached ($coursecode) {
 		if (isset ($this->coursecodecache)
-		 && isset ($this->coursecodecache[$coursecode]))
-			return $this->coursecodecache[$coursecode];
-		else
-		{
+		 && isset ($this->coursecodecache[$coursecode])) {
+		 	return $this->coursecodecache[$coursecode];
+		 } else {
 			$name = get_course_name_from_code($coursecode);
 			$this->coursecodecache[$coursecode] = $name;
 			return $name;
 		}
 	}
 
-	private function get_category_cached ($category_id)
-	{
+	private function get_category_cached ($category_id) {
 		if (isset ($this->categorycache)
-		 && isset ($this->categorycache[$category_id]))
-			return $this->categorycache[$category_id];
-		else
-		{
+		 && isset ($this->categorycache[$category_id])) {
+		 	return $this->categorycache[$category_id];
+		 }else {
 			$cat = Category::load($category_id);
-			if (isset($cat))
-			{
+			if (isset($cat)){
 				$this->categorycache[$category_id] = $cat[0];
 				return $cat[0];
-			}
-			else
+			}else
 				return null;
 		}
 	}
 
-	private function get_category_name_to_display ($cat)
-	{
-		if (isset($cat))
-		{
-			if ($cat->get_parent_id() == '0' || $cat->get_parent_id() == null)
-				return '';
-			else
-				return $cat->get_name();
-		}
-		else
-			return '';
+	private function get_category_name_to_display ($cat) {
 		
+		if (isset($cat)){
+			
+			if ($cat->get_parent_id() == '0' || $cat->get_parent_id() == null){
+					return '';
+				} else {
+					return $cat->get_name();
+				}
+				
+			} else {
+					return '';
+			}
 	}
-
-
-}
-?>
+}

+ 22 - 5
main/gradebook/open_document.php

@@ -1,11 +1,28 @@
 <?php
+/*
+==============================================================================
+	Dokeos - elearning and course management software
 
-include ('../inc/global.inc.php');
-include ('../inc/lib/document.lib.php');
-api_block_anonymous_users();
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
+	Copyright (c) 2006 Ghent University (UGent)
+	Copyright (c) various contributors
 
+	For a full list of contributors, see "credits.txt".
+	The full license can be read in "license.txt".
 
-DocumentManager :: file_send_for_download(api_get_path(SYS_COURSE_PATH).$_GET['file']);
+	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 address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
+	Mail: info@dokeos.com
+==============================================================================
+*/
+require_once ('../inc/global.inc.php');
+require_once ('../inc/lib/document.lib.php');
+api_block_anonymous_users();
+DocumentManager :: file_send_for_download(api_get_path(SYS_COURSE_PATH).$_GET['file']);

+ 18 - 22
main/gradebook/user_info.php

@@ -1,12 +1,10 @@
-<?php
-// test
-
-// $Id: gradebook_view_result.php 479 2007-04-12 11:50:58Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -20,33 +18,31 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file = 'gradebook';
-$cidReset = true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/userform.class.php');
-include_once (api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
-include_once (api_get_path(LIBRARY_PATH) . 'export.lib.inc.php');
-include_once (api_get_path(LIBRARY_PATH) . 'import.lib.php');
+//$cidReset = true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/userform.class.php');
+require_once (api_get_path(LIBRARY_PATH) . 'fileManage.lib.php');
+require_once (api_get_path(LIBRARY_PATH) . 'export.lib.inc.php');
+require_once (api_get_path(LIBRARY_PATH) . 'import.lib.php');
 api_block_anonymous_users();
 block_students();
 
 $user = get_user_info_from_id($_GET['userid']);
 $form = new UserForm(UserForm :: TYPE_USER_INFO, $user, 'user_info_form', null, api_get_self() . '?userid=' . $_GET['userid'] . '&selecteval=' . $_GET['selecteval']);
 if ($form->validate()) {
-
-	header('Location: user_stats.php?selecteval=' . $_GET['selecteval'].'&userid=' . $_GET['userid']);
+	header('Location: user_stats.php?selecteval=' . Security::remove_XSS($_GET['selecteval']).'&userid=' .Security::remove_XSS($_GET['userid']));
 	exit;
-
 }
 
 $interbreadcrumb[] = array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 Display :: display_header(get_lang('UserInfo'));
@@ -58,10 +54,10 @@ $img_attributes = 'src="'.$image_file.'?rand='.time().'" '
 	.'alt="'.$user_data['lastname'].' '.$user_data['firstname'].'" '
 	.'style="float:'.($text_dir == 'rtl' ? 'left' : 'right').'; padding:5px;" ';
 
-if ($image_size[0] > 300) //limit display width to 300px
+if ($image_size[0] > 300) {
+	//limit display width to 300px
 	$img_attributes .= 'width="300" ';
-
+}
 echo '<img '.$img_attributes.'/>';
 $form->display();
-Display :: display_footer();
-?>
+Display :: display_footer();

+ 35 - 39
main/gradebook/user_stats.php

@@ -1,10 +1,10 @@
-<?php
-// $Id: gradebook_view_result.php 479 2007-04-12 11:50:58Z stijn $
+<?php // $Id: $
 /*
 ==============================================================================
 	Dokeos - elearning and course management software
 
-	Copyright (c) 2006 Dokeos S.A.
+	Copyright (c) 2008 Dokeos Latinoamerica SAC
+	Copyright (c) 2006 Dokeos SPRL
 	Copyright (c) 2006 Ghent University (UGent)
 	Copyright (c) various contributors
 
@@ -18,43 +18,43 @@
 
 	See the GNU General Public License for more details.
 
-	Contact address: Dokeos, 44 rue des palais, B-1030 Brussels, Belgium
+	Contact address: Dokeos, rue du Corbeau, 108, B-1030 Brussels, Belgium
 	Mail: info@dokeos.com
 ==============================================================================
 */
 $language_file= 'gradebook';
-$cidReset= true;
-include_once ('../inc/global.inc.php');
-include_once ('lib/be.inc.php');
-include_once ('lib/gradebook_functions.inc.php');
-include_once ('lib/fe/userform.class.php');
-include_once ('lib/user_data_generator.class.php');
-include_once ('lib/fe/usertable.class.php');
-include_once ('lib/fe/displaygradebook.php');
-include_once ('lib/scoredisplay.class.php');
-include_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
+//$cidReset= true;
+require_once ('../inc/global.inc.php');
+require_once ('lib/be.inc.php');
+require_once ('lib/gradebook_functions.inc.php');
+require_once ('lib/fe/userform.class.php');
+require_once ('lib/user_data_generator.class.php');
+require_once ('lib/fe/usertable.class.php');
+require_once ('lib/fe/displaygradebook.php');
+require_once ('lib/scoredisplay.class.php');
+require_once (api_get_path(LIBRARY_PATH).'ezpdf/class.ezpdf.php');
 api_block_anonymous_users();
 block_students();
 $interbreadcrumb[]= array (
-	'url' => 'gradebook.php',
+	'url' => $_SESSION['gradebook_dest'],
 	'name' => get_lang('Gradebook'
 ));
 $category= Category :: load(0);
 $allevals= $category[0]->get_evaluations($_GET['userid'], true);
 $alllinks= $category[0]->get_links($_GET['userid'], true);
-if ($_GET['selectcat'] != null)
+if ($_GET['selectcat'] != null) {
 	$addparams= array (
 		'userid' => $_GET['userid'],
 		'selectcat' => $_GET['selectcat']
-	);
-else
+	);	
+} else {
 	$addparams= array (
 		'userid' => $_GET['userid'],
 		'selecteval' => $_GET['selecteval']
-	);
+	);	
+}
 $user_table= new UserTable($_GET['userid'], $allevals, $alllinks, $addparams);
-if (isset ($_GET['exportpdf']))
-{
+if (isset ($_GET['exportpdf'])) {
 	$pdf= new Cezpdf();
 	$pdf->selectFont(api_get_path(LIBRARY_PATH).'ezpdf/fonts/Courier.afm');
 	$pdf->ezSetMargins(30, 30, 50, 30);
@@ -64,8 +64,7 @@ if (isset ($_GET['exportpdf']))
 	$newarray= array ();
 	$displayscore= Scoredisplay :: instance();
 	$newitem= array ();
-	foreach ($data_array as $data)
-	{
+	foreach ($data_array as $data) {
 		$newarray[] = array_slice($data, 1);	
 	}
 	$pdf->ezSetY(810);
@@ -75,14 +74,15 @@ if (isset ($_GET['exportpdf']))
 	$pdf->line(50,40,550,40);	
 	
 	$pdf->ezSetY(750);
-	if ($displayscore->is_custom())
+	if ($displayscore->is_custom()) {
 		$header_names= array (
 			get_lang('Evaluation'
-		), get_lang('Course'), get_lang('Category'), get_lang('EvaluationAverage'),get_lang('Result'),get_lang('Display'));
-	else
+		), get_lang('Course'), get_lang('Category'), get_lang('EvaluationAverage'),get_lang('Result'),get_lang('Display'));		
+	} else {
 		$header_names= array (
 			get_lang('Evaluation'
-		), get_lang('Course'), get_lang('Category'), get_lang('EvaluationAverage'),get_lang('Result'));
+		), get_lang('Course'), get_lang('Category'), get_lang('EvaluationAverage'),get_lang('Result'));		
+	}
 	$pdf->ezTable($newarray, $header_names, '', array (
 		'showHeadings' => 1,
 		'shaded' => 1,
@@ -93,28 +93,24 @@ if (isset ($_GET['exportpdf']))
 	$pdf->ezStream();
 	exit;
 }
-if (isset ($_GET['selectcat']))
-{
+if (isset ($_GET['selectcat'])) {
 	$interbreadcrumb[]= array (
-		'url' => 'gradebook_flatview.php?selecteval=' . $_GET['selectcat'],
+		'url' => 'gradebook_flatview.php?selecteval=' . Security::remove_XSS($_GET['selectcat']),
 		'name' => get_lang('FlatView'
 	));
-	$backto= '<a href=gradebook_flatview.php?selectcat=' . $_GET['selectcat'] . '><img src=../img/lp_leftarrow.gif alt=' . get_lang('BackToOverview') . ' align=absmiddle/> ' . get_lang('BackToOverview') . '</a>&nbsp;&nbsp;';
+	$backto= '<a href=gradebook_flatview.php?selectcat=' .Security::remove_XSS($_GET['selectcat']) . '><img src=../img/lp_leftarrow.gif alt=' . get_lang('BackToOverview') . ' align=absmiddle/> ' . get_lang('BackToOverview') . '</a>&nbsp&nbsp';
 
 }
-if (isset ($_GET['selecteval']))
-{
+if (isset ($_GET['selecteval'])) {
 	$interbreadcrumb[]= array (
-		'url' => 'gradebook_view_result.php?selecteval=' . $_GET['selecteval'],
+		'url' => 'gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']),
 		'name' => get_lang('ViewResult'
 	));
-	$backto= '<a href=gradebook_view_result.php?selecteval=' . $_GET['selecteval'] . '><img src=../img/lp_leftarrow.gif alt=' . get_lang('BackToEvaluation') . ' align=absmiddle/> ' . get_lang('BackToEvaluation') . '</a>&nbsp;&nbsp;';
+	$backto= '<a href=gradebook_view_result.php?selecteval=' . Security::remove_XSS($_GET['selecteval']) . '><img src=../img/lp_leftarrow.gif alt=' . get_lang('BackToEvaluation') . ' align=absmiddle/> ' . get_lang('BackToEvaluation') . '</a>&nbsp&nbsp';
 }
-$backto .= '<a href="' . api_get_self() . '?exportpdf=&userid='.$_GET['userid'].'&selectcat=' . $category[0]->get_id() . '" target="_blank"><img src=../img/calendar_up.gif alt=' . get_lang('ExportPDF') . '/> ' . get_lang('ExportPDF') . '</a>';
+$backto .= '<a href="' . api_get_self() . '?exportpdf=&userid='.Security::remove_XSS($_GET['userid']).'&selectcat=' . $category[0]->get_id() . '" target="_blank"><img src=../img/calendar_up.gif alt=' . get_lang('ExportPDF') . '/> ' . get_lang('ExportPDF') . '</a>';
 
 Display :: display_header(get_lang('ResultsPerUser'));
 DisplayGradebook :: display_header_user($_GET['userid']);
 echo $backto;
-$user_table->display();
-Display :: display_footer();
-?>
+$user_table->display();

Some files were not shown because too many files changed in this diff